@mastra/core
Version:
242 lines • 10.9 kB
TypeScript
import type { StepResult, WorkflowRunState, WorkflowRunStatus } from '../../../workflows/index.js';
import type { ClaimRunOwnershipInput, ClaimRunOwnershipResult, RenewRunOwnershipInput, RenewRunOwnershipResult, RunFence, RunOwnershipRecord } from '../../run-fencing.js';
import type { WorkflowRun, WorkflowRuns, StorageListWorkflowRunsInput, UpdateWorkflowStateOptions } from '../../types.js';
import type { InMemoryDB } from '../inmemory-db.js';
import { WorkflowsStorage } from './base.js';
import type { StateRef, StateVersion, StoredWorkflowRun, StoredWorkflowRunHeader, WorkflowRunAppendHeader, WorkflowRunHeader } from './journal.js';
import type { StatePatchOp } from './state-patch.js';
/**
* Deep-clone in-memory workflow state.
*
* We previously used `JSON.parse(JSON.stringify(x))` here, but the agent loop
* and workflow engine legitimately place values in step results that don't
* survive JSON round-tripping:
* - `Date` instances (e.g. `response.timestamp`) — JSON turns them into ISO
* strings, downstream consumers that do `.getTime()` then break.
* - Explicitly-`undefined` properties (e.g. `headers`, `providerMetadata`,
* `usage.{cacheRead, cacheWrite, reasoning}`) — JSON drops keys with
* `undefined` values, breaking snapshot assertions that include them.
* - `Error` instances (e.g. tool execution failures, AssertionErrors from
* inside `tool.execute`) — JSON strips `message`/`name`/`stack` (non-
* enumerable). `structuredClone` isn't enough either — it preserves the
* Error type but drops subclass-specific enumerable props (`actual`,
* `expected`, `operator`).
*
* The custom walk below preserves all of that. It also handles builtins with
* internal slots explicitly — `Map`, `Set`, `RegExp`, `URL`, `ArrayBuffer`,
* typed arrays, and `DataView` — because cloning them via `Object.create(proto)`
* would produce a value that passes `instanceof` but whose methods throw (the
* internal slots were never initialized). Null-prototype dictionaries keep
* their null prototype.
*/
/** @internal Exported for testing only. */
export declare function cloneRunData<T>(value: T): T;
export declare class WorkflowsInMemory extends WorkflowsStorage {
private db;
constructor({ db }: {
db: InMemoryDB;
});
supportsConcurrentUpdates(): boolean;
supportsRunJournal(): boolean;
supportsGuardedSnapshotWrites(): boolean;
dangerouslyClearAll(): Promise<void>;
private getWorkflowKey;
/**
* A storage v2 run's state, latest or as of `at`, with its `state-base` resolved recursively.
* `{}` when the run isn't stored. Not cloned.
*/
private stateOf;
/**
* Whether a run's state version is still stored: its draft entry, or for a stored version a
* full state or state base at or below it (a checkpoint drops the old ones unless `stateShared`).
* A version past the run's `lastSeq` isn't written yet, so a run can only build on state that
* existed before it, and state bases can't form a loop.
*/
private hasStateVersion;
/**
* Before a run is deleted, store the full state in place of every `state-base` entry built on it,
* so the runs built on it keep reading the same state.
*/
private detachStateChildren;
/** A storage v2 run as a v1 row, with its state rebuilt from the entries. Not cloned. */
private materializedRow;
/** v1 rows, then v2 rows, optionally narrowed before v2 state is rebuilt. */
private allRows;
supportsRunFencing(): boolean;
private ownershipRecord;
private assertFence;
claimRunOwnership({ runId, ownerId, leaseMs, force, expectedGeneration, }: ClaimRunOwnershipInput): Promise<ClaimRunOwnershipResult>;
renewRunOwnership({ leaseMs, ...fence }: RenewRunOwnershipInput): Promise<RenewRunOwnershipResult>;
releaseRunOwnership(fence: RunFence): Promise<boolean>;
getRunOwnership({ runId }: {
runId: string;
}): Promise<RunOwnershipRecord | null>;
/** Reads every record in one pass, so the batch sees a single moment of the store. */
getRunOwnerships({ runIds }: {
runIds: string[];
}): Promise<Map<string, RunOwnershipRecord>>;
/**
* Merges one step's result into a v1 run's snapshot and returns the run's step results.
* Moves the run's `updatedAt`.
*/
updateWorkflowResults({ workflowName, runId, stepId, result, requestContext, state, fence, }: {
workflowName: string;
runId: string;
stepId: string;
result: StepResult<any, any, any, any>;
requestContext: Record<string, any>;
state?: Record<string, any>;
fence?: RunFence;
}): Promise<Record<string, StepResult<any, any, any, any>>>;
/**
* Patches a run's state, v1 or storage v2. With `opts.expectedStatus`, only when the stored
* status matches. Returns the updated snapshot, or undefined when nothing was written. A write
* moves the run's `updatedAt`.
*/
updateWorkflowState({ workflowName, runId, opts, fence, storageVersion, }: {
workflowName: string;
runId: string;
opts: UpdateWorkflowStateOptions;
fence?: RunFence;
storageVersion?: 1 | 2;
}): Promise<WorkflowRunState | undefined>;
loadWorkflowRunHeader({ workflowName, runId, }: {
workflowName: string;
runId: string;
}): Promise<StoredWorkflowRunHeader | null>;
loadWorkflowRun({ workflowName, runId, successfulSteps, }: {
workflowName: string;
runId: string;
successfulSteps: 'full' | 'summary';
}): Promise<StoredWorkflowRun | null>;
loadWorkflowRunSteps({ workflowName, runId, stepIds, upToSeq, expectedLastSeq, expectedRunToken, }: {
workflowName: string;
runId: string;
stepIds: string[];
upToSeq?: number;
expectedLastSeq?: number;
expectedRunToken?: string;
}): Promise<Record<string, StepResult<any, any, any, any>> | null>;
/**
* Patches a storage v2 run's header. With `opts.expectedStatus`, only when the stored status
* matches. Returns the updated header, or undefined when the run isn't stored or the status
* didn't match. A write moves the run's `updatedAt`.
*/
updateWorkflowRunHeader({ workflowName, runId, opts, fence, }: {
workflowName: string;
runId: string;
opts: UpdateWorkflowStateOptions;
fence?: RunFence;
}): Promise<StoredWorkflowRunHeader | undefined>;
writeWorkflowRunCheckpoint(args: {
workflowName: string;
runId: string;
resourceId?: string;
header: WorkflowRunHeader;
steps: Record<string, StepResult<any, any, any, any>>;
state?: Record<string, any>;
stateBase?: StateRef;
statePatch?: StatePatchOp[];
fence?: RunFence;
expectedStatus?: WorkflowRunStatus | WorkflowRunStatus[];
}): Promise<{
lastSeq: number;
runToken?: string;
} | null>;
appendWorkflowRunEntries(args: {
workflowName: string;
runId: string;
steps: Record<string, StepResult<any, any, any, any>>;
stepPatches?: Record<string, StatePatchOp[]>;
state?: Record<string, any>;
statePatch?: StatePatchOp[];
startStateSeq?: number;
fence?: RunFence;
expectedStatus?: WorkflowRunStatus | WorkflowRunStatus[];
} & WorkflowRunAppendHeader): Promise<{
lastSeq: number;
runToken?: string;
} | null>;
mergeWorkflowRunStepResult({ workflowName, runId, stepId, result, requestContext, statePatch, fence, }: {
workflowName: string;
runId: string;
stepId: string;
result: StepResult<any, any, any, any>;
requestContext?: Record<string, any>;
statePatch?: StatePatchOp[];
fence?: RunFence;
}): Promise<{
lastSeq: number;
result: StepResult<any, any, any, any>;
} | null>;
loadWorkflowRunState({ workflowName, runId, seq, keys, }: {
workflowName: string;
runId: string;
seq?: number;
keys?: string[];
}): Promise<Record<string, any> | null>;
protected writeStateCheckpoint({ workflowName, runId, stateSeq, state, }: {
workflowName: string;
runId: string;
stateSeq: number;
state: Record<string, any>;
}): Promise<void>;
appendWorkflowRunStateDraft(args: {
workflowName: string;
runId: string;
} & ({
on: StateVersion;
ops: StatePatchOp[];
} | {
state: Record<string, any>;
})): Promise<{
seq: number;
}>;
/**
* Writes the header (or with none, merges `requestContext` into the stored one) and one entry per
* step and step patch, then the state, state base or state patch. A checkpoint first drops the old
* step entries and starts the state over (`{}` when it carries none). It drops the old state
* entries too, unless another run's state builds on this run's (`stateShared`), which can name an
* earlier version. Returns the stored record. Writes nothing, returning null, without a header
* when the run isn't stored, or when the stored run's status doesn't match `expectedStatus`.
* Throws when the state base isn't stored.
*/
private writeRunEntries;
persistWorkflowSnapshot({ workflowName, runId, resourceId, snapshot, createdAt, updatedAt, fence, expectedStatus, }: {
workflowName: string;
runId: string;
resourceId?: string;
snapshot: WorkflowRunState;
createdAt?: Date;
updatedAt?: Date;
fence?: RunFence;
expectedStatus?: WorkflowRunStatus | WorkflowRunStatus[];
}): Promise<boolean>;
loadWorkflowRunStatus({ workflowName, runId, }: {
workflowName: string;
runId: string;
}): Promise<WorkflowRunStatus | null>;
private snapshotStatus;
loadWorkflowSnapshot({ workflowName, runId, storageVersion, }: {
workflowName: string;
runId: string;
storageVersion?: 1 | 2;
}): Promise<WorkflowRunState | null>;
/**
* Lists v1 and v2 runs, newest first. With `summary`, each returned snapshot keeps only its
* status, timestamp and parent run, and the stored snapshot is not cloned.
*/
listWorkflowRuns({ workflowName, fromDate, toDate, perPage, page, resourceId, threadId, status, summary, }?: StorageListWorkflowRunsInput): Promise<WorkflowRuns>;
getWorkflowRunById({ runId, workflowName, storageVersion, }: {
runId: string;
workflowName?: string;
storageVersion?: 1 | 2;
}): Promise<WorkflowRun | null>;
deleteWorkflowRunById({ runId, workflowName, storageVersion, fence, }: {
runId: string;
workflowName: string;
storageVersion?: 1 | 2;
fence?: RunFence;
}): Promise<void>;
}
//# sourceMappingURL=inmemory.d.ts.map