@happyvertical/smrt-workflows 0.62.3 → 0.62.4

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.
@@ -123,3 +123,20 @@ driver wiring on every job (after a restart nothing lives in a closure); its
123
123
  job (the run is then failed on the next read), so create every
124
124
  definition's host in each process that registers the handler, or give
125
125
  definitions their own queues. Upgrade every runner before enqueueing.
126
+
127
+ ## Host effects during a check
128
+
129
+ `WorkflowCheckContext.assertActive()` checks the abort signal, job claim and
130
+ running status through the driver's serialized accounting transaction. Call it
131
+ before each host effect in a long check. It throws `AiRunClaimLostError` for a
132
+ taken-over worker and `AiRunStoppedError` after a stop/cancel or active-duration budget stop. The assertion is
133
+ a boundary check, not a transaction spanning another database: effects must
134
+ still be safe to repeat and isolated by their host's durable identity.
135
+
136
+ Checks may return `diagnostics: {code,path,message}[]`. The host's `validate`
137
+ callback may return these objects alongside existing string errors. Structured
138
+ issues are recorded on failed schema checks and host checks, linked to the
139
+ judged call/handoff. At most 20 issues are kept (code 80, path 300, message
140
+ 1000 characters, 8 KiB total); repair input receives the same bounded details. An optional
141
+ `repair` hint (4000 characters) is checkpoint/model-only, excluded from events. Hosts must
142
+ supply safe validation text, never credentials or source data/fragments.
package/dist/driver.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { type AiRunBudget, type AiRunCheckpoint, type AiRunClaimFence, type TrackedAiClient } from '@happyvertical/smrt-core';
2
2
  import type { DatabaseInterface } from '@happyvertical/sql';
3
- import { type RunProgress, type WorkflowCheckpointState, type WorkflowDefinition, type WorkflowRunState } from './types.js';
3
+ import { type RunProgress, type WorkflowCheckpointState, type WorkflowDefinition, type WorkflowRunState, type WorkflowValidationIssue } from './types.js';
4
4
  /** A step's output could not be read as the step's JSON (a repairable attempt). */
5
5
  export declare class WorkflowOutputError extends Error {
6
6
  constructor(message: string);
@@ -15,7 +15,7 @@ export interface WorkflowRunDriverOptions {
15
15
  ai: TrackedAiClient;
16
16
  definition: WorkflowDefinition;
17
17
  /** The host's full JSON Schema validator (Ajv or equal); errors, or none. */
18
- validate(schema: Record<string, unknown>, output: unknown): readonly string[];
18
+ validate(schema: Record<string, unknown>, output: unknown): readonly (string | WorkflowValidationIssue)[];
19
19
  /** Resolve input passed by reference (`inputRef`). */
20
20
  readInput?(ref: string, scope: {
21
21
  ownerId: string;
@@ -1 +1 @@
1
- {"version":3,"file":"driver.d.ts","sourceRoot":"","sources":["../src/driver.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,WAAW,EAChB,KAAK,eAAe,EACpB,KAAK,eAAe,EAepB,KAAK,eAAe,EAGrB,MAAM,0BAA0B,CAAC;AAMlC,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAS5D,OAAO,EACL,KAAK,WAAW,EAGhB,KAAK,uBAAuB,EAC5B,KAAK,kBAAkB,EACvB,KAAK,gBAAgB,EAItB,MAAM,YAAY,CAAC;AAEpB,mFAAmF;AACnF,qBAAa,mBAAoB,SAAQ,KAAK;gBAChC,OAAO,EAAE,MAAM;CAI5B;AAED,8CAA8C;AAC9C,MAAM,WAAW,wBAAwB;IACvC;;;;OAIG;IACH,EAAE,EAAE,eAAe,CAAC;IACpB,UAAU,EAAE,kBAAkB,CAAC;IAC/B,6EAA6E;IAC7E,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,EAAE,OAAO,GAAG,SAAS,MAAM,EAAE,CAAC;IAC9E,sDAAsD;IACtD,SAAS,CAAC,CACR,GAAG,EAAE,MAAM,EACX,KAAK,EAAE;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAA;KAAE,GAClD,OAAO,CAAC,OAAO,CAAC,CAAC;IACpB,0EAA0E;IAC1E,UAAU,CAAC,CAAC,QAAQ,EAAE,WAAW,GAAG,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;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AAC;IAI9D;;;;;OAKG;eAEM,MAAM,WACJ,MAAM,eACH,kBAAkB,GAC7B,OAAO,CAAC,gBAAgB,CAAC;IAge5B,2DAA2D;gBACzC,MAAM,WAAW,MAAM,GAAG,OAAO,CAAC,gBAAgB,CAAC;IAUrE,4EAA4E;kBACxD,MAAM,WAAW,MAAM,GAAG,OAAO,CAAC,gBAAgB,CAAC;IAQvE;;;;;;;;OAQG;kBAEM,MAAM,WACJ,MAAM,kBACA;QACb,MAAM,CAAC,EAAE,WAAW,CAAC;QACrB,KAAK,CAAC,EAAE,eAAe,CAAC;QACxB,KAAK,CAAC,EAAE,CAAC,EAAE,EAAE,iBAAiB,EAAE,MAAM,EAAE,WAAW,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;KACvE,GACA,OAAO,CAAC,gBAAgB,CAAC;IAgD5B;;;;;;;OAOG;kBAEM,MAAM,WACJ,MAAM,YACL;QAAE,QAAQ,EAAE,OAAO,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,GAC7C,OAAO,CAAC,gBAAgB,CAAC;IAwC5B;;;;;;;OAOG;iBAEM,MAAM,WACJ,MAAM,iBACD;QAAE,EAAE,CAAC,EAAE,MAAM,CAAC;QAAC,MAAM,CAAC,EAAE,WAAW,CAAA;KAAE,GAClD,OAAO,CAAC,gBAAgB,CAAC;EA6D/B;AAED,6BAA6B;AAC7B,MAAM,MAAM,iBAAiB,GAAG,UAAU,CAAC,OAAO,uBAAuB,CAAC,CAAC"}
package/dist/index.d.ts CHANGED
@@ -7,5 +7,5 @@ export { createRunCheckpointStore, isWorkflowCheckpointState, type LoadedWorkflo
7
7
  export { workflowClaimFence, workflowStopFence } from './claim-fence.js';
8
8
  export { createWorkflowRunDriver, initialWorkflowState, readWorkflowRunLease, type StartWorkflowRun, WorkflowOutputError, type WorkflowRunDriver, type WorkflowRunDriverOptions, type WorkflowRunLease, type WorkflowRunOptions, } from './driver.js';
9
9
  export { createWorkflowRunJobs, registerWorkflowRunHandler, type StartWorkflowRunJob, WORKFLOW_RUN_HANDLER, WorkflowRunJobError, type WorkflowRunJobPayload, type WorkflowRunJobs, type WorkflowRunJobsOptions, WorkflowRunKeyConflictError, type WorkflowRunOwner, } from './jobs.js';
10
- export { type RunProgress, WORKFLOW_RUN_TYPE, WORKFLOW_STATE_VERSION, type WorkflowCheckContext, type WorkflowCheckpointState, type WorkflowDefinition, type WorkflowRunState, type WorkflowStep, type WorkflowStepCheck, type WorkflowStepContext, type WorkflowStepExecute, } from './types.js';
10
+ export { type RunProgress, WORKFLOW_RUN_TYPE, WORKFLOW_STATE_VERSION, type WorkflowCheckContext, type WorkflowCheckpointState, type WorkflowDefinition, type WorkflowRunState, type WorkflowStep, type WorkflowStepCheck, type WorkflowStepContext, type WorkflowStepExecute, type WorkflowValidationIssue, } from './types.js';
11
11
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EACL,wBAAwB,EACxB,yBAAyB,EACzB,KAAK,iBAAiB,EACtB,KAAK,kBAAkB,EACvB,KAAK,yBAAyB,EAC9B,gBAAgB,EAChB,KAAK,sBAAsB,EAC3B,wBAAwB,GACzB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACzE,OAAO,EACL,uBAAuB,EACvB,oBAAoB,EACpB,oBAAoB,EACpB,KAAK,gBAAgB,EACrB,mBAAmB,EACnB,KAAK,iBAAiB,EACtB,KAAK,wBAAwB,EAC7B,KAAK,gBAAgB,EACrB,KAAK,kBAAkB,GACxB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,qBAAqB,EACrB,0BAA0B,EAC1B,KAAK,mBAAmB,EACxB,oBAAoB,EACpB,mBAAmB,EACnB,KAAK,qBAAqB,EAC1B,KAAK,eAAe,EACpB,KAAK,sBAAsB,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K,mBAAmB,EACxB,KAAK,mBAAmB,EACxB,KAAK,uBAAuB,GAC7B,MAAM,YAAY,CAAC"}
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { WORKFLOW_RUN_TYPE, WORKFLOW_STATE_VERSION } from "./types.js";
2
- import { AiCallLimitError, AiRunCheckpointConflictError, AiRunClaimLostError, AiRunResumeRefusedError, AiRunStoppedError, aiRunEngine, appendAiRunEvent, cancelAiRun, createTrackedAiClient, finishAiRun, getAiRun, getRunTrajectory, lockAiRunChain, readAiRunCheckpoint, reconcileAiRunOnClaim, resumeAiRun, saveAiRunCheckpoint, startAiRunStep, stopAiRun, waitAiRunApproval, withAiRunTransaction } from "@happyvertical/smrt-core";
2
+ import { AiCallLimitError, AiRunCheckpointConflictError, AiRunClaimLostError, AiRunResumeRefusedError, AiRunStoppedError, aiRunActiveTime, aiRunEngine, appendAiRunEvent, cancelAiRun, createTrackedAiClient, finishAiRun, getAiRun, getRunTrajectory, lockAiRunChain, readAiRunCheckpoint, reconcileAiRunOnClaim, resumeAiRun, saveAiRunCheckpoint, startAiRunStep, stopAiRun, transitionAiRun, waitAiRunApproval, withAiRunTransaction } from "@happyvertical/smrt-core";
3
3
  import { JobClaimLostError, JobHandle, SmrtJobCollection, SmrtJobEventCollection, assertFailedJobDispatch, assertJobClaim, assertJobClaimForRelease, getJobClaim, isRunnerExecutionContext, jobHandlerTarget, listJobHandlers, registerJobHandler, unregisterJobHandler } from "@happyvertical/smrt-jobs";
4
4
  import { promptMessageOptions, resolvePrompt, trackedPromptCall } from "@happyvertical/smrt-prompts";
5
5
  import { createHash } from "node:crypto";
@@ -84,6 +84,15 @@ function workflowStopFence(claim) {
84
84
  }
85
85
  //#endregion
86
86
  //#region src/driver.ts
87
+ var boundedIssues = (issues) => {
88
+ const bounded = issues.slice(0, 20).map((issue) => ({
89
+ code: issue.code.slice(0, 80),
90
+ path: issue.path.slice(0, 300),
91
+ message: issue.message.slice(0, 1e3)
92
+ }));
93
+ while (new TextEncoder().encode(JSON.stringify(bounded)).byteLength > 8192) bounded.pop();
94
+ return bounded;
95
+ };
87
96
  var WorkflowOutputError = class extends Error {
88
97
  constructor(message) {
89
98
  super(message);
@@ -441,10 +450,32 @@ function createWorkflowRunDriver(options) {
441
450
  if (error instanceof WorkflowOutputError || error instanceof AiCallLimitError) errors = [error.message];
442
451
  else throw error;
443
452
  }
444
- if (!errors.length) errors = [...options.validate(step.schema, output)];
453
+ if (!errors.length) {
454
+ const issues = options.validate(step.schema, output);
455
+ const diagnostics = boundedIssues(issues.filter((issue) => typeof issue !== "string"));
456
+ errors = issues.slice(0, 20).map((issue) => typeof issue === "string" ? issue : JSON.stringify({
457
+ ...boundedIssues([issue])[0],
458
+ ...issue.repair ? { repair: issue.repair.slice(0, 4e3) } : {}
459
+ }));
460
+ if (diagnostics.length) await appendAiRunEvent(db, runId, {
461
+ type: "check",
462
+ status: "failed",
463
+ stepIndex: state.stepIndex,
464
+ name: step.name,
465
+ parentEventId: await judgedEvent(runId, before, state.stepIndex),
466
+ payload: { diagnostics }
467
+ }, fenced);
468
+ }
445
469
  if (errors.length) {
446
470
  const retries = loaded.run.budget.repairRetries ?? 0;
447
471
  if (state.repairs >= retries) {
472
+ await persist({
473
+ ...state,
474
+ invalid: {
475
+ output: output ?? null,
476
+ errors
477
+ }
478
+ });
448
479
  await fail("repairs_exhausted");
449
480
  break;
450
481
  }
@@ -493,6 +524,41 @@ function createWorkflowRunDriver(options) {
493
524
  }
494
525
  const result = step.check ? await step.check(pending.output, {
495
526
  ...base,
527
+ assertActive: async () => {
528
+ controller.signal.throwIfAborted();
529
+ const checked = await queue(() => withAiRunTransaction(db, async (tx) => {
530
+ if (fence) try {
531
+ if (await fence(tx.db, runId) === false) throw new AiRunClaimLostError(runId);
532
+ } catch (error) {
533
+ if (error instanceof Error && error.name === "JobClaimLostError") throw new AiRunClaimLostError(runId, error);
534
+ throw error;
535
+ }
536
+ const current2 = await getAiRun(tx.db, runId);
537
+ if (current2?.status === "running" && current2.budget.maxDurationMs !== void 0) {
538
+ const used = aiRunActiveTime(current2, tx.now);
539
+ if (used >= current2.budget.maxDurationMs) return transitionAiRun(tx.db, runId, {
540
+ from: "running",
541
+ to: "stopped",
542
+ stopReason: "max_duration",
543
+ stoppedByRunId: runId,
544
+ stopDetail: {
545
+ limit: "maxDurationMs",
546
+ runId,
547
+ limitValue: current2.budget.maxDurationMs,
548
+ used,
549
+ room: current2.budget.maxDurationMs - used
550
+ }
551
+ }, fenced);
552
+ }
553
+ return current2;
554
+ }, { now }));
555
+ if (!checked || checked.status !== "running") throw new AiRunStoppedError({
556
+ runId,
557
+ status: checked?.status ?? "stopped",
558
+ stopReason: checked?.stopReason ?? "interrupted",
559
+ stoppedByRunId: checked?.stoppedByRunId ?? null
560
+ });
561
+ },
496
562
  approval,
497
563
  approvals: state.approvals ?? 0
498
564
  }) : {};
@@ -513,8 +579,9 @@ function createWorkflowRunDriver(options) {
513
579
  parentEventId: pending.judgedEventId,
514
580
  stepIndex: state.stepIndex,
515
581
  name: step.name,
516
- ...result.note || result.failure ? { payload: {
582
+ ...result.note || result.failure || result.diagnostics?.length ? { payload: {
517
583
  ...result.note ? { note: result.note } : {},
584
+ ...result.diagnostics?.length ? { diagnostics: boundedIssues(result.diagnostics) } : {},
518
585
  ...result.failure ? { failure: result.failure } : {}
519
586
  } } : {}
520
587
  }, fenced);
package/dist/index.js.map CHANGED
@@ -1 +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,MAA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C1C,MAAM,aAAa,EAAE;KACrB,OAAO;IACT;;IAEA,MAAM,OAAO,IAAY;KACvB,MAAM,WAAW,EAAE;KACnB,MAAM,QAAQ,MAAM,MAAM,OAAO,IAAI,OAAO;KAC5C,MAAM,aAAa,EAAE;KACrB,OAAO;IACT;IACA;;;;;IAKA,MAAM,OACJ,IACA,UACA;KACA,MAAM,QAAQ,YAAY,KAAK;KAC/B,MAAM,aAAa,EAAE;KACrB,MAAM,WAAW,EAAE;KACnB,MAAM,UAAU,MAAM,MAAM,OAAO,IAAI,SAAS,QAAQ;KACxD,IAAI,SAAS,UAAU,OAAO,sBAAsB,EAAE;KACtD,OAAO;IACT;;IAEA;;IAEA,MAAM,MACJ,IACA,eAAsD,CAAC,GACvD;KACA,MAAM,QAAQ,MAAM,WAAW,EAAE;KACjC,MAAM,UAAU,MAAM,UAAU,OAAO,MAAM,KAAc,CAAA,CAAE,MAC3D,IACA,SACA,YACF;KACA,MAAM,QAAQ,OAAO,QAAQ,IAAI,QAAQ,MAAM;KAC/C,OAAO;IACT;GACF;EACF;CACF;AACF"}
1
+ {"version":3,"file":"index.js","names":["current"],"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 aiRunActiveTime,\n appendAiRunEvent,\n cancelAiRun,\n finishAiRun,\n getAiRun,\n getRunTrajectory,\n reconcileAiRunOnClaim,\n resumeAiRun,\n startAiRunStep,\n stopAiRun,\n type TrackedAiClient,\n transitionAiRun,\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 type WorkflowValidationIssue,\n} from './types.js';\n\n/** Persist only known diagnostic fields, with a fixed upper bound. */\nconst boundedIssues = (issues: readonly WorkflowValidationIssue[]) => {\n const bounded = issues.slice(0, 20).map((issue) => ({\n code: issue.code.slice(0, 80),\n path: issue.path.slice(0, 300),\n message: issue.message.slice(0, 1000),\n }));\n // Leave room for the note and event envelope under core's 16 KiB payload cap.\n while (new TextEncoder().encode(JSON.stringify(bounded)).byteLength > 8192)\n bounded.pop();\n return bounded;\n};\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(\n schema: Record<string, unknown>,\n output: unknown,\n ): readonly (string | WorkflowValidationIssue)[];\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 const issues = options.validate(step.schema, output);\n const diagnostics = boundedIssues(\n issues.filter(\n (issue): issue is WorkflowValidationIssue =>\n typeof issue !== 'string',\n ),\n );\n errors = issues.slice(0, 20).map((issue) =>\n typeof issue === 'string'\n ? issue\n : JSON.stringify({\n ...boundedIssues([issue])[0],\n ...(issue.repair\n ? { repair: issue.repair.slice(0, 4000) }\n : {}),\n }),\n );\n if (diagnostics.length)\n await appendAiRunEvent(\n db,\n runId,\n {\n type: 'check',\n status: 'failed',\n stepIndex: state.stepIndex,\n name: step.name,\n parentEventId: await judgedEvent(\n runId,\n before,\n state.stepIndex,\n ),\n payload: { diagnostics },\n },\n fenced,\n );\n }\n if (errors.length) {\n const retries = loaded.run.budget.repairRetries ?? 0;\n if (state.repairs >= retries) {\n await persist({\n ...state,\n invalid: { output: output ?? null, errors },\n });\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 assertActive: async () => {\n controller.signal.throwIfAborted();\n const checked = await queue(() =>\n withAiRunTransaction(\n db,\n async (tx) => {\n if (fence) {\n try {\n if ((await fence(tx.db, runId)) === false)\n throw new AiRunClaimLostError(runId);\n } catch (error) {\n if (\n error instanceof Error &&\n error.name === 'JobClaimLostError'\n )\n throw new AiRunClaimLostError(runId, error);\n throw error;\n }\n }\n const current = await getAiRun(tx.db, runId);\n if (\n current?.status === 'running' &&\n current.budget.maxDurationMs !== undefined\n ) {\n const used = aiRunActiveTime(current, tx.now);\n if (used >= current.budget.maxDurationMs)\n return transitionAiRun(\n tx.db,\n runId,\n {\n from: 'running',\n to: 'stopped',\n stopReason: 'max_duration',\n stoppedByRunId: runId,\n stopDetail: {\n limit: 'maxDurationMs',\n runId,\n limitValue: current.budget.maxDurationMs,\n used,\n room: current.budget.maxDurationMs - used,\n },\n },\n fenced,\n );\n }\n return current;\n },\n { now },\n ),\n );\n // Throw after the accounting transaction commits a duration stop.\n if (!checked || checked.status !== 'running')\n throw new AiRunStoppedError({\n runId,\n status: checked?.status ?? 'stopped',\n stopReason: checked?.stopReason ?? 'interrupted',\n stoppedByRunId: checked?.stoppedByRunId ?? null,\n });\n },\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 || result.diagnostics?.length\n ? {\n payload: {\n ...(result.note ? { note: result.note } : {}),\n ...(result.diagnostics?.length\n ? { diagnostics: boundedIssues(result.diagnostics) }\n : {}),\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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AAsB,EAAE;KACtD,OAAO;IACT;;IAEA;;IAEA,MAAM,MACJ,IACA,eAAsD,CAAC,GACvD;KACA,MAAM,QAAQ,MAAM,WAAW,EAAE;KACjC,MAAM,UAAU,MAAM,UAAU,OAAO,MAAM,KAAc,CAAA,CAAE,MAC3D,IACA,SACA,YACF;KACA,MAAM,QAAQ,OAAO,QAAQ,IAAI,QAAQ,MAAM;KAC/C,OAAO;IACT;GACF;EACF;CACF;AACF"}
@@ -2,7 +2,7 @@
2
2
  "version": "1.0.0",
3
3
  "timestamp": 0,
4
4
  "packageName": "@happyvertical/smrt-workflows",
5
- "packageVersion": "0.62.3",
5
+ "packageVersion": "0.62.4",
6
6
  "objects": {},
7
7
  "moduleType": "smrt",
8
8
  "smrtDependencies": [
@@ -3,14 +3,14 @@
3
3
  "sensitiveFieldsExcluded": true,
4
4
  "generatedAt": "1970-01-01T00:00:00.000Z",
5
5
  "packageName": "@happyvertical/smrt-workflows",
6
- "packageVersion": "0.62.3",
6
+ "packageVersion": "0.62.4",
7
7
  "sourceManifestPath": "dist/manifest.json",
8
8
  "agentDocPath": "AGENTS.md",
9
9
  "sourceHashes": {
10
- "manifest": "0d31a69082b45662f1ee498b35a37110094e6b0b0cf319ba3620a80481ace9a2",
11
- "packageJson": "fce461c251209108c14763227eae67f6fb4cbbef279e3a631700540756ae3274",
10
+ "manifest": "d1167fdc95f46d394e3e66c7f17d36826a1d186bb9b80e0292bd32265939d134",
11
+ "packageJson": "314d17e3f2c3784b3d6d396da745a7684ba880ca464774fd393a6154f76ef687",
12
12
  "agents": "30f9771d259f2dc436e406e70d0623c419f0ee8cf6933dfd8b55e78fd21b75ac",
13
- "moduleDoc:agents/workflow-runs.md": "ece3bcda576615d96be1c17141ee06bf4f1fc85efb6452e899e9a38864ad80cb"
13
+ "moduleDoc:agents/workflow-runs.md": "aa611afb2a7e2a5b81a943a4a6c776a76466b23002b97ecff1c126c74f1630f1"
14
14
  },
15
15
  "exports": [
16
16
  "."
@@ -82,7 +82,7 @@
82
82
  {
83
83
  "path": "agents/workflow-runs.md",
84
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"
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\n## Host effects during a check\n\n`WorkflowCheckContext.assertActive()` checks the abort signal, job claim and\nrunning status through the driver's serialized accounting transaction. Call it\nbefore each host effect in a long check. It throws `AiRunClaimLostError` for a\ntaken-over worker and `AiRunStoppedError` after a stop/cancel or active-duration budget stop. The assertion is\na boundary check, not a transaction spanning another database: effects must\nstill be safe to repeat and isolated by their host's durable identity.\n\nChecks may return `diagnostics: {code,path,message}[]`. The host's `validate`\ncallback may return these objects alongside existing string errors. Structured\nissues are recorded on failed schema checks and host checks, linked to the\njudged call/handoff. At most 20 issues are kept (code 80, path 300, message\n1000 characters, 8 KiB total); repair input receives the same bounded details. An optional\n`repair` hint (4000 characters) is checkpoint/model-only, excluded from events. Hosts must\nsupply safe validation text, never credentials or source data/fragments.\n"
86
86
  }
87
87
  ]
88
88
  }
@@ -5,10 +5,10 @@ description: "Durable workflow runs for SMRT: ordered host steps over registered
5
5
  status: "stable"
6
6
  generated:
7
7
  by: "smrt/scripts/generate-knowledge-okf.ts"
8
- at: "2026-11-17T21:17:44Z"
8
+ at: "2026-11-17T23:03:03Z"
9
9
  audience: "internal"
10
10
  evidence_level: "manifest-described"
11
- source_revision: "sha256:7dc8d0052fb5eb06d3c2b01c96463fa7d33646f154a38bd5f658fe997bb08273"
11
+ source_revision: "sha256:1172798e065dd62baea5878015164cc1945ee07830fd2051d86d20352424142d"
12
12
  sources:
13
13
  - id: "manifest"
14
14
  resource: "https://github.com/happyvertical/smrt/blob/main/packages/workflows/package.json"
package/dist/types.d.ts CHANGED
@@ -60,8 +60,18 @@ export interface RunProgress {
60
60
  stopReason: AiRunStopReason | null;
61
61
  phase: WorkflowCheckpointState['phase'];
62
62
  }
63
+ /** Safe host-authored validation details; never include source data or credentials. */
64
+ export interface WorkflowValidationIssue {
65
+ code: string;
66
+ path: string;
67
+ message: string;
68
+ /** Optional model repair hint, kept in the checkpoint, excluded from events (4000 chars). */
69
+ repair?: string;
70
+ }
63
71
  /** What a host check decides about a step's accepted output. */
64
72
  export interface WorkflowStepCheck {
73
+ /** Bounded structured diagnostics recorded on the check event. */
74
+ diagnostics?: readonly WorkflowValidationIssue[];
65
75
  /** Facts for the next step: replaces the run input. */
66
76
  input?: unknown;
67
77
  /**
@@ -114,6 +124,8 @@ export interface WorkflowStepContext {
114
124
  }
115
125
  /** What a step's check sees. */
116
126
  export interface WorkflowCheckContext extends WorkflowStepContext {
127
+ /** Assert the current claim and running status before a repeat-safe host effect. */
128
+ assertActive(): Promise<void>;
117
129
  /**
118
130
  * `approved` when the check runs again after a person approved the step's
119
131
  * latest hold; null otherwise. Asking for approval again requests a new
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,WAAW,EACX,YAAY,EACZ,WAAW,EACX,eAAe,EACf,eAAe,EAChB,MAAM,0BAA0B,CAAC;AAElC,yEAAyE;AACzE,eAAO,MAAM,iBAAiB,aAAa,CAAC;AAE5C,8DAA8D;AAC9D,eAAO,MAAM,sBAAsB,IAAI,CAAC;AAExC;;;;;;GAMG;AACH,MAAM,WAAW,uBAAuB;IACtC,CAAC,EAAE,OAAO,sBAAsB,CAAC;IACjC,kDAAkD;IAClD,SAAS,EAAE,MAAM,CAAC;IAClB,iGAAiG;IACjG,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC;IACxB,gEAAgE;IAChE,OAAO,EAAE,MAAM,CAAC;IAChB,gEAAgE;IAChE,OAAO,EAAE,MAAM,CAAC;IAChB,uDAAuD;IACvD,KAAK,EAAE,OAAO,CAAC;IACf,4EAA4E;IAC5E,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,8DAA8D;IAC9D,OAAO,EAAE,OAAO,EAAE,CAAC;IACnB,8DAA8D;IAC9D,OAAO,EAAE;QAAE,MAAM,EAAE,OAAO,CAAC;QAAC,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D,KAAK,EAAE,uBAAuB,CAAC,OAAO,CAAC,CAAC;IACxC,KAAK,EAAE,OAAO,CAAC;IACf,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,OAAO,EAAE,OAAO,EAAE,CAAC;IACnB,yEAAyE;IACzE,OAAO,EAAE,OAAO,CAAC;IACjB,wEAAwE;IACxE,MAAM,EAAE;QACN,MAAM,EAAE,MAAM,CAAC;QACf,KAAK,EAAE,MAAM,CAAC;QACd,QAAQ,EAAE,MAAM,CAAC;QACjB,SAAS,EAAE,MAAM,CAAC;QAClB,eAAe,EAAE,MAAM,CAAC;QACxB,cAAc,EAAE,MAAM,CAAC;QACvB,aAAa,EAAE,MAAM,CAAC;KACvB,CAAC;CACH"}
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","names":[],"sources":["../src/types.ts"],"sourcesContent":["import type {\n AiRunBudget,\n AiRunContext,\n AiRunStatus,\n AiRunStopDetail,\n AiRunStopReason,\n} from '@happyvertical/smrt-core';\n\n/** The run type every workflow run carries (docs/content/ai-runs.md). */\nexport const WORKFLOW_RUN_TYPE = 'workflow';\n\n/** Version of {@link WorkflowCheckpointState}'s own shape. */\nexport const WORKFLOW_STATE_VERSION = 1;\n\n/**\n * What a workflow run keeps in its checkpoint (the run type owns this\n * state; core wraps it in a versioned envelope): the step it is on, the\n * repair count, and the accepted outputs of the completed steps. Totals,\n * tokens and attempts are never here: the usage rows and events are the\n * record.\n */\nexport interface WorkflowCheckpointState {\n v: typeof WORKFLOW_STATE_VERSION;\n /** Zero-based index of the step the run is on. */\n stepIndex: number;\n /** `call`: the step's model call is next; `check`: its accepted output awaits the host check. */\n phase: 'call' | 'check';\n /** Repairs used on the current step (attempt = repairs + 1). */\n repairs: number;\n /** Times the host check asked to run the current step again. */\n repeats: number;\n /** The run input, when small enough to keep inline. */\n input: unknown;\n /** A pointer at input the host stores (large input passes by reference). */\n inputRef: string | null;\n /** Accepted outputs of the completed steps, by step index. */\n outputs: unknown[];\n /** The current step's accepted output, awaiting its check. */\n pending: { output: unknown; judgedEventId: string | null } | null;\n /** The current step's last invalid output, for the repair attempt. */\n invalid: { output: unknown; errors: string[] } | null;\n /** The approval (hold) requested for the pending output and not yet decided. */\n approval: { requestEventId: string } | null;\n /**\n * Holds of the current step a person approved so far. A step may hold\n * more than once (one hold per gated action); it passes only when its\n * check passes with no hold outstanding. Absent in older checkpoints: 0.\n */\n approvals?: number;\n}\n\n/** Host-facing progress; names are the host's plain text. */\nexport interface RunProgress {\n runId: string;\n /** One-based step position and the step's name. */\n step: { index: number; count: number; name: string };\n status: AiRunStatus;\n stopReason: AiRunStopReason | null;\n phase: WorkflowCheckpointState['phase'];\n}\n\n/** What a host check decides about a step's accepted output. */\nexport interface WorkflowStepCheck {\n /** Facts for the next step: replaces the run input. */\n input?: unknown;\n /**\n * The host finished the work at this step (it applied the accepted\n * output); the run ends `done` here without running later steps.\n */\n complete?: boolean;\n /**\n * A definitive rejection: the run ends `failed` with `check_failed`. A\n * safe, host-authored explanation; never model output or error text.\n */\n failure?: string;\n /** Run this step again (a new step instance), up to `maxRepeats`. */\n repeat?: boolean;\n /**\n * Pause for a person's decision (durable runs only). Every time a check\n * returns it, a new hold is requested (an `approval` event): a check that\n * holds again after an approval waits again, and the step passes only once\n * its check returns without it.\n */\n waitingApproval?: boolean;\n /**\n * What the hold points at in the host (`payload_ref` of the `approval`\n * request, e.g. `approval:<id>`), for mapping a host decision to the run.\n */\n holdRef?: string;\n /** A short host note recorded on the check or approval event. */\n note?: string;\n}\n\n/** What a step's call or check sees. */\nexport interface WorkflowStepContext {\n runId: string;\n step: { index: number; count: number; name: string };\n /** The run input (resolved from `inputRef` when passed by reference). */\n input: unknown;\n /** Accepted outputs of the completed steps. */\n outputs: readonly unknown[];\n /** 1 for the first try, 2 for the first repair, ... */\n attempt: number;\n /** The previous attempt's invalid output and its errors. */\n repair: { output: unknown; errors: readonly string[] } | null;\n signal: AbortSignal;\n}\n\n/** What a step's check sees. */\nexport interface WorkflowCheckContext extends WorkflowStepContext {\n /**\n * `approved` when the check runs again after a person approved the step's\n * latest hold; null otherwise. Asking for approval again requests a new\n * hold: it is never taken as passed.\n */\n approval: 'approved' | null;\n /** Holds of this step a person approved so far. */\n approvals: number;\n}\n\n/**\n * A step's own execution, replacing the default prompt call (a CLI engine,\n * say). It must send every model call it makes with `runContext`, so each\n * call is reserved, recorded and settled in this run, and return the step's\n * output (an object, or JSON text).\n */\nexport type WorkflowStepExecute = (\n request: WorkflowStepContext & { runContext: AiRunContext },\n) => Promise<unknown>;\n\n/**\n * One host-defined stage of a workflow. Model output cannot change it. By\n * default its call resolves the registered prompt `promptKey` through\n * `resolvePrompt` and sends it on the tracked client; the output must pass\n * `schema` (the host's full validator) and then the host `check`.\n */\nexport interface WorkflowStep {\n name: string;\n /** The registered prompt this step's call uses. */\n promptKey: string;\n schema: Record<string, unknown>;\n /**\n * The prompt's variables. Default: `input`, `outputs`, `schema`,\n * `repairOutput` and `repairErrors` as JSON or plain text.\n */\n variables?: (\n context: WorkflowStepContext,\n ) => Record<string, unknown> | Promise<Record<string, unknown>>;\n /** Deterministic and safe to repeat: recovery may replay it. */\n check?: (\n output: unknown,\n context: WorkflowCheckContext,\n ) => WorkflowStepCheck | Promise<WorkflowStepCheck>;\n /** How many times the check may ask to repeat this step (default 0). */\n maxRepeats?: number;\n /** The output allowance a call of this step is reserved with. */\n expectedOutputTokens?: number;\n execute?: WorkflowStepExecute;\n}\n\n/**\n * A versioned list of steps (one workflow definition). A run resumes only\n * under the version that saved its checkpoint, unless this version declares\n * it accepts older checkpoints and validates or migrates them.\n */\nexport interface WorkflowDefinition {\n key: string;\n version: string;\n steps: readonly WorkflowStep[];\n olderCheckpoints?: {\n /** Whether a checkpoint saved by `version` is accepted. */\n accepts(version: string | null): boolean;\n /**\n * Validate an accepted older checkpoint's state and return it in this\n * version's shape; throw to refuse it (the run then stops with\n * `definition_changed`).\n */\n migrate(\n state: WorkflowCheckpointState,\n version: string | null,\n ): WorkflowCheckpointState;\n };\n}\n\n/** A workflow run as the host sees it. */\nexport interface WorkflowRunState {\n id: string;\n ownerId: string | null;\n tenantId: string | null;\n definitionKey: string | null;\n definitionVersion: string | null;\n status: AiRunStatus;\n stopReason: AiRunStopReason | null;\n stoppedByRunId: string | null;\n stopDetail: AiRunStopDetail | null;\n retryOfRunId: string | null;\n budget: AiRunBudget;\n /** The checkpoint revision this snapshot was read at. */\n revision: number;\n step: { index: number; count: number; name: string };\n phase: WorkflowCheckpointState['phase'];\n input: unknown;\n inputRef: string | null;\n outputs: unknown[];\n /** The current step's accepted output awaiting its check or approval. */\n pending: unknown;\n /** Spend so far, from the run row (own and inclusive of child runs). */\n totals: {\n tokens: number;\n calls: number;\n costUsed: number;\n stepsUsed: number;\n inclusiveTokens: number;\n inclusiveCalls: number;\n inclusiveCost: number;\n };\n}\n"],"mappings":";AASO,IAAM,oBAAoB;AAG1B,IAAM,yBAAyB"}
1
+ {"version":3,"file":"types.js","names":[],"sources":["../src/types.ts"],"sourcesContent":["import type {\n AiRunBudget,\n AiRunContext,\n AiRunStatus,\n AiRunStopDetail,\n AiRunStopReason,\n} from '@happyvertical/smrt-core';\n\n/** The run type every workflow run carries (docs/content/ai-runs.md). */\nexport const WORKFLOW_RUN_TYPE = 'workflow';\n\n/** Version of {@link WorkflowCheckpointState}'s own shape. */\nexport const WORKFLOW_STATE_VERSION = 1;\n\n/**\n * What a workflow run keeps in its checkpoint (the run type owns this\n * state; core wraps it in a versioned envelope): the step it is on, the\n * repair count, and the accepted outputs of the completed steps. Totals,\n * tokens and attempts are never here: the usage rows and events are the\n * record.\n */\nexport interface WorkflowCheckpointState {\n v: typeof WORKFLOW_STATE_VERSION;\n /** Zero-based index of the step the run is on. */\n stepIndex: number;\n /** `call`: the step's model call is next; `check`: its accepted output awaits the host check. */\n phase: 'call' | 'check';\n /** Repairs used on the current step (attempt = repairs + 1). */\n repairs: number;\n /** Times the host check asked to run the current step again. */\n repeats: number;\n /** The run input, when small enough to keep inline. */\n input: unknown;\n /** A pointer at input the host stores (large input passes by reference). */\n inputRef: string | null;\n /** Accepted outputs of the completed steps, by step index. */\n outputs: unknown[];\n /** The current step's accepted output, awaiting its check. */\n pending: { output: unknown; judgedEventId: string | null } | null;\n /** The current step's last invalid output, for the repair attempt. */\n invalid: { output: unknown; errors: string[] } | null;\n /** The approval (hold) requested for the pending output and not yet decided. */\n approval: { requestEventId: string } | null;\n /**\n * Holds of the current step a person approved so far. A step may hold\n * more than once (one hold per gated action); it passes only when its\n * check passes with no hold outstanding. Absent in older checkpoints: 0.\n */\n approvals?: number;\n}\n\n/** Host-facing progress; names are the host's plain text. */\nexport interface RunProgress {\n runId: string;\n /** One-based step position and the step's name. */\n step: { index: number; count: number; name: string };\n status: AiRunStatus;\n stopReason: AiRunStopReason | null;\n phase: WorkflowCheckpointState['phase'];\n}\n\n/** Safe host-authored validation details; never include source data or credentials. */\nexport interface WorkflowValidationIssue {\n code: string;\n path: string;\n message: string;\n /** Optional model repair hint, kept in the checkpoint, excluded from events (4000 chars). */\n repair?: string;\n}\n\n/** What a host check decides about a step's accepted output. */\nexport interface WorkflowStepCheck {\n /** Bounded structured diagnostics recorded on the check event. */\n diagnostics?: readonly WorkflowValidationIssue[];\n /** Facts for the next step: replaces the run input. */\n input?: unknown;\n /**\n * The host finished the work at this step (it applied the accepted\n * output); the run ends `done` here without running later steps.\n */\n complete?: boolean;\n /**\n * A definitive rejection: the run ends `failed` with `check_failed`. A\n * safe, host-authored explanation; never model output or error text.\n */\n failure?: string;\n /** Run this step again (a new step instance), up to `maxRepeats`. */\n repeat?: boolean;\n /**\n * Pause for a person's decision (durable runs only). Every time a check\n * returns it, a new hold is requested (an `approval` event): a check that\n * holds again after an approval waits again, and the step passes only once\n * its check returns without it.\n */\n waitingApproval?: boolean;\n /**\n * What the hold points at in the host (`payload_ref` of the `approval`\n * request, e.g. `approval:<id>`), for mapping a host decision to the run.\n */\n holdRef?: string;\n /** A short host note recorded on the check or approval event. */\n note?: string;\n}\n\n/** What a step's call or check sees. */\nexport interface WorkflowStepContext {\n runId: string;\n step: { index: number; count: number; name: string };\n /** The run input (resolved from `inputRef` when passed by reference). */\n input: unknown;\n /** Accepted outputs of the completed steps. */\n outputs: readonly unknown[];\n /** 1 for the first try, 2 for the first repair, ... */\n attempt: number;\n /** The previous attempt's invalid output and its errors. */\n repair: { output: unknown; errors: readonly string[] } | null;\n signal: AbortSignal;\n}\n\n/** What a step's check sees. */\nexport interface WorkflowCheckContext extends WorkflowStepContext {\n /** Assert the current claim and running status before a repeat-safe host effect. */\n assertActive(): Promise<void>;\n /**\n * `approved` when the check runs again after a person approved the step's\n * latest hold; null otherwise. Asking for approval again requests a new\n * hold: it is never taken as passed.\n */\n approval: 'approved' | null;\n /** Holds of this step a person approved so far. */\n approvals: number;\n}\n\n/**\n * A step's own execution, replacing the default prompt call (a CLI engine,\n * say). It must send every model call it makes with `runContext`, so each\n * call is reserved, recorded and settled in this run, and return the step's\n * output (an object, or JSON text).\n */\nexport type WorkflowStepExecute = (\n request: WorkflowStepContext & { runContext: AiRunContext },\n) => Promise<unknown>;\n\n/**\n * One host-defined stage of a workflow. Model output cannot change it. By\n * default its call resolves the registered prompt `promptKey` through\n * `resolvePrompt` and sends it on the tracked client; the output must pass\n * `schema` (the host's full validator) and then the host `check`.\n */\nexport interface WorkflowStep {\n name: string;\n /** The registered prompt this step's call uses. */\n promptKey: string;\n schema: Record<string, unknown>;\n /**\n * The prompt's variables. Default: `input`, `outputs`, `schema`,\n * `repairOutput` and `repairErrors` as JSON or plain text.\n */\n variables?: (\n context: WorkflowStepContext,\n ) => Record<string, unknown> | Promise<Record<string, unknown>>;\n /** Deterministic and safe to repeat: recovery may replay it. */\n check?: (\n output: unknown,\n context: WorkflowCheckContext,\n ) => WorkflowStepCheck | Promise<WorkflowStepCheck>;\n /** How many times the check may ask to repeat this step (default 0). */\n maxRepeats?: number;\n /** The output allowance a call of this step is reserved with. */\n expectedOutputTokens?: number;\n execute?: WorkflowStepExecute;\n}\n\n/**\n * A versioned list of steps (one workflow definition). A run resumes only\n * under the version that saved its checkpoint, unless this version declares\n * it accepts older checkpoints and validates or migrates them.\n */\nexport interface WorkflowDefinition {\n key: string;\n version: string;\n steps: readonly WorkflowStep[];\n olderCheckpoints?: {\n /** Whether a checkpoint saved by `version` is accepted. */\n accepts(version: string | null): boolean;\n /**\n * Validate an accepted older checkpoint's state and return it in this\n * version's shape; throw to refuse it (the run then stops with\n * `definition_changed`).\n */\n migrate(\n state: WorkflowCheckpointState,\n version: string | null,\n ): WorkflowCheckpointState;\n };\n}\n\n/** A workflow run as the host sees it. */\nexport interface WorkflowRunState {\n id: string;\n ownerId: string | null;\n tenantId: string | null;\n definitionKey: string | null;\n definitionVersion: string | null;\n status: AiRunStatus;\n stopReason: AiRunStopReason | null;\n stoppedByRunId: string | null;\n stopDetail: AiRunStopDetail | null;\n retryOfRunId: string | null;\n budget: AiRunBudget;\n /** The checkpoint revision this snapshot was read at. */\n revision: number;\n step: { index: number; count: number; name: string };\n phase: WorkflowCheckpointState['phase'];\n input: unknown;\n inputRef: string | null;\n outputs: unknown[];\n /** The current step's accepted output awaiting its check or approval. */\n pending: unknown;\n /** Spend so far, from the run row (own and inclusive of child runs). */\n totals: {\n tokens: number;\n calls: number;\n costUsed: number;\n stepsUsed: number;\n inclusiveTokens: number;\n inclusiveCalls: number;\n inclusiveCost: number;\n };\n}\n"],"mappings":";AASO,IAAM,oBAAoB;AAG1B,IAAM,yBAAyB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@happyvertical/smrt-workflows",
3
- "version": "0.62.3",
3
+ "version": "0.62.4",
4
4
  "description": "Durable workflow runs for SMRT: ordered host steps over registered prompts, tracked calls, checkpoints, repair, approval and budgets",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -18,13 +18,13 @@
18
18
  }
19
19
  },
20
20
  "dependencies": {
21
- "@happyvertical/smrt-core": "0.62.3",
22
- "@happyvertical/smrt-jobs": "0.62.3",
23
- "@happyvertical/smrt-prompts": "0.62.3",
21
+ "@happyvertical/smrt-core": "0.62.4",
22
+ "@happyvertical/smrt-jobs": "0.62.4",
23
+ "@happyvertical/smrt-prompts": "0.62.4",
24
24
  "@happyvertical/sql": "^0.113.0"
25
25
  },
26
26
  "devDependencies": {
27
- "@happyvertical/smrt-vitest": "0.62.3",
27
+ "@happyvertical/smrt-vitest": "0.62.4",
28
28
  "@types/node": "24.13.6",
29
29
  "ajv": "8.20.0",
30
30
  "typescript": "6.0.3",