@axiom-lattice/pg-stores 3.3.13 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/.turbo/turbo-build.log +10 -10
  2. package/CHANGELOG.md +208 -0
  3. package/dist/index.d.mts +357 -3
  4. package/dist/index.d.ts +357 -3
  5. package/dist/index.js +2337 -77
  6. package/dist/index.js.map +1 -1
  7. package/dist/index.mjs +2342 -76
  8. package/dist/index.mjs.map +1 -1
  9. package/package.json +3 -3
  10. package/src/__tests__/AgentRunRetention.migrations.test.ts +41 -0
  11. package/src/__tests__/PostgreSQLAgentRunLedger.test.ts +305 -0
  12. package/src/__tests__/PostgreSQLAgentRunRetention.test.ts +126 -0
  13. package/src/__tests__/PostgreSQLAgentRunTaskQueue.test.ts +1375 -0
  14. package/src/__tests__/PostgreSQLChannelReplyJobStore.test.ts +335 -0
  15. package/src/__tests__/PostgreSQLCheckpointStorage.deleteAfter.test.ts +473 -0
  16. package/src/__tests__/PostgreSQLCheckpointStorage.test.ts +538 -0
  17. package/src/__tests__/PostgreSQLStore.test.ts +173 -0
  18. package/src/__tests__/PostgreSQLThreadStore.test.ts +80 -0
  19. package/src/__tests__/ThreadMessageQueueStore.integration.test.ts +21 -0
  20. package/src/__tests__/ThreadMessageQueueStore.test.ts +8 -3
  21. package/src/__tests__/createPgStoreConfig.test.ts +38 -0
  22. package/src/__tests__/eval-task-id.test.ts +14 -3
  23. package/src/createPgStoreConfig.ts +35 -2
  24. package/src/index.ts +7 -0
  25. package/src/migrations/agent_run_base_checkpoint_captured_migration.ts +34 -0
  26. package/src/migrations/agent_run_capability_revision_migration.ts +24 -0
  27. package/src/migrations/agent_run_ledger_migration.ts +51 -0
  28. package/src/migrations/agent_run_project_task_migration.ts +34 -0
  29. package/src/migrations/agent_run_project_task_running_index_migration.ts +33 -0
  30. package/src/migrations/agent_run_retention_migration.ts +25 -0
  31. package/src/migrations/agent_run_rollback_failure_migration.ts +28 -0
  32. package/src/migrations/agent_run_running_index_source_migration.ts +31 -0
  33. package/src/migrations/agent_run_task_queue_migration.ts +65 -0
  34. package/src/migrations/channel_reply_job_migration.ts +55 -0
  35. package/src/migrations/eval_migrations.ts +19 -0
  36. package/src/migrations/store_migrations.ts +50 -0
  37. package/src/migrations/task_migration.ts +17 -0
  38. package/src/migrations/thread_migrations.ts +25 -0
  39. package/src/stores/PostgreSQLAgentRunLedger.ts +1221 -0
  40. package/src/stores/PostgreSQLChannelReplyJobStore.ts +373 -0
  41. package/src/stores/PostgreSQLCheckpointStorage.ts +548 -0
  42. package/src/stores/PostgreSQLEvalStore.ts +17 -4
  43. package/src/stores/PostgreSQLStore.ts +167 -0
  44. package/src/stores/PostgreSQLTaskStore.ts +4 -0
  45. package/src/stores/PostgreSQLThreadStore.ts +49 -10
  46. package/src/stores/ThreadMessageQueueStore.ts +10 -5
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { Pool, PoolConfig, PoolClient } from 'pg';
2
2
  export { Pool, PoolConfig } from 'pg';
3
- import { ThreadStore, Thread, CreateThreadRequest, AssistantStore, Assistant, CreateAssistantRequest, DatabaseConfigStore, DatabaseConfigEntry, CreateDatabaseConfigRequest, UpdateDatabaseConfigRequest, ConnectionStore, ConnectionEntry, MetricsServerConfigStore, MetricsServerConfigEntry, CreateMetricsServerConfigRequest, UpdateMetricsServerConfigRequest, McpServerConfigStore, McpServerConfigEntry, CreateMcpServerConfigRequest, UpdateMcpServerConfigRequest, WorkspaceStore, Workspace, CreateWorkspaceRequest, UpdateWorkspaceRequest, ProjectStore, ProjectFilter, Project, CreateProjectRequest, UpdateProjectRequest, UpdateProjectCapabilityBundlesResult, UserStore, User, CreateUserRequest, UpdateUserRequest, TenantStore, Tenant, CreateTenantRequest, UpdateTenantRequest, UserTenantLinkStore, UserTenantLink, CreateUserTenantLinkRequest, UpdateUserTenantLinkRequest, WorkflowTrackingStore, CreateWorkflowRunRequest, WorkflowRun, UpdateWorkflowRunRequest, QueryWorkflowRunsOptions, QueryWorkflowRunsResult, CreateRunStepRequest, RunStep, UpdateRunStepRequest, StepType, EvalStore, EvalProject, CreateEvalProjectRequest, EvalSuite, CreateEvalSuiteRequest, EvalCase, CreateEvalCaseRequest, EvalRun, CreateEvalRunRequest, EvalRunResult, EvalProjectReport, BindingRegistry, Binding, CreateBindingInput, BindingMutablePatch, BindingListParams, ChannelInstallationStore, ChannelInstallation, ChannelInstallationType, CreateChannelInstallationInput, UpdateChannelInstallationRequest, A2AApiKeyStore, A2AApiKeyRecord, CreateA2AApiKeyInput, UpdateA2AApiKeyInput, A2AApiKeyEntry, OpenAuditStore, OpenAuditQuery, OpenAuditRecord, OpenAuditAppendInput, AgentWebAppStore, AgentWebApp, CreateAgentWebAppInput, AgentWebAppStorePatch, AgentWebAppUpdateOptions, ScheduleStorage, ScheduledTaskDefinition, ScheduledTaskStatus, ScheduleExecutionType, TaskStore, CreateTaskRequest, TaskItem, TaskListFilter, TaskDependentListQuery, UpdateTaskRequest, TaskMutationSnapshot, TaskWorkItemStore, CreateWorkItemRequest, TaskWorkItem, CreateWorkItemIfAbsentRequest, TaskWorkItemListFilter, ProjectLifecycleEventQuery, MenuRegistry, MenuItem, CreateMenuItemInput, UpdateMenuItemInput, SharedResourceStore, ShareRecord, CollectionStore, Collection, CreateCollectionRequest, UpdateCollectionRequest, VectorStoreProvider, VectorStoreCreateParams, CapabilityBundleStore, CapabilityBundle, InternalCreateCapabilityBundleInput, InternalUpdateCapabilityBundleInput, CapabilityBundleDeleteResult, ProjectRoomStore, ProjectRoom, ProjectMembershipStore, ProjectMembership, ProjectHumanRole, ProjectMembershipMutationResult, ProjectBotMembershipStore, ProjectBotMembership, ProjectRoomMessageStore, ProjectRoomMessage, ProjectRoomReadStateStore, ProjectRoomReadState, UserPushSubscriptionStore, UserPushSubscription, ModelProviderStore, ModelProviderEntry, CreateModelProviderRequest, UpdateModelProviderRequest, ModelProviderStatus, ModelProviderModelEntry, ProviderModelInput, LeaseStore, LeaseRecord, OutboxStore, OutboxEvent, PluginDeploymentStore, PluginDeployment, SkillStore, Skill, CreateSkillRequest } from '@axiom-lattice/protocols';
3
+ import { ThreadStore, Thread, CreateThreadRequest, AssistantStore, Assistant, CreateAssistantRequest, DatabaseConfigStore, DatabaseConfigEntry, CreateDatabaseConfigRequest, UpdateDatabaseConfigRequest, ConnectionStore, ConnectionEntry, MetricsServerConfigStore, MetricsServerConfigEntry, CreateMetricsServerConfigRequest, UpdateMetricsServerConfigRequest, McpServerConfigStore, McpServerConfigEntry, CreateMcpServerConfigRequest, UpdateMcpServerConfigRequest, WorkspaceStore, Workspace, CreateWorkspaceRequest, UpdateWorkspaceRequest, ProjectStore, ProjectFilter, Project, CreateProjectRequest, UpdateProjectRequest, UpdateProjectCapabilityBundlesResult, UserStore, User, CreateUserRequest, UpdateUserRequest, TenantStore, Tenant, CreateTenantRequest, UpdateTenantRequest, UserTenantLinkStore, UserTenantLink, CreateUserTenantLinkRequest, UpdateUserTenantLinkRequest, WorkflowTrackingStore, CreateWorkflowRunRequest, WorkflowRun, UpdateWorkflowRunRequest, QueryWorkflowRunsOptions, QueryWorkflowRunsResult, CreateRunStepRequest, RunStep, UpdateRunStepRequest, StepType, EvalStore, EvalProject, CreateEvalProjectRequest, EvalSuite, CreateEvalSuiteRequest, EvalCase, CreateEvalCaseRequest, EvalRun, CreateEvalRunRequest, EvalRunResult, EvalProjectReport, BindingRegistry, Binding, CreateBindingInput, BindingMutablePatch, BindingListParams, ChannelInstallationStore, ChannelInstallation, ChannelInstallationType, CreateChannelInstallationInput, UpdateChannelInstallationRequest, A2AApiKeyStore, A2AApiKeyRecord, CreateA2AApiKeyInput, UpdateA2AApiKeyInput, A2AApiKeyEntry, OpenAuditStore, OpenAuditQuery, OpenAuditRecord, OpenAuditAppendInput, AgentWebAppStore, AgentWebApp, CreateAgentWebAppInput, AgentWebAppStorePatch, AgentWebAppUpdateOptions, ScheduleStorage, ScheduledTaskDefinition, ScheduledTaskStatus, ScheduleExecutionType, TaskStore, CreateTaskRequest, TaskItem, TaskListFilter, TaskDependentListQuery, UpdateTaskRequest, TaskMutationSnapshot, TaskWorkItemStore, CreateWorkItemRequest, TaskWorkItem, CreateWorkItemIfAbsentRequest, TaskWorkItemListFilter, ProjectLifecycleEventQuery, MenuRegistry, MenuItem, CreateMenuItemInput, UpdateMenuItemInput, SharedResourceStore, ShareRecord, CollectionStore, Collection, CreateCollectionRequest, UpdateCollectionRequest, VectorStoreProvider, VectorStoreCreateParams, CapabilityBundleStore, CapabilityBundle, InternalCreateCapabilityBundleInput, InternalUpdateCapabilityBundleInput, CapabilityBundleDeleteResult, ProjectRoomStore, ProjectRoom, ProjectMembershipStore, ProjectMembership, ProjectHumanRole, ProjectMembershipMutationResult, ProjectBotMembershipStore, ProjectBotMembership, ProjectRoomMessageStore, ProjectRoomMessage, ProjectRoomReadStateStore, ProjectRoomReadState, UserPushSubscriptionStore, UserPushSubscription, ModelProviderStore, ModelProviderEntry, CreateModelProviderRequest, UpdateModelProviderRequest, ModelProviderStatus, ModelProviderModelEntry, ProviderModelInput, LeaseStore, LeaseRecord, OutboxStore, OutboxEvent, PluginDeploymentStore, PluginDeployment, ChannelReplyJobStore, CreateChannelReplyJobInput, ChannelReplyJob, CheckpointStorage, CheckpointMaintenance, ThreadCheckpointStorage, StoreProtocol, StorePutInput, StoreItem, StoreSearchInput, SkillStore, Skill, CreateSkillRequest } from '@axiom-lattice/protocols';
4
4
  export { AgentWebApp, AgentWebAppAppearance, AgentWebAppFeatures, AgentWebAppScope, AgentWebAppStatus, AgentWebAppStore, Assistant, AssistantStore, Binding, BindingRegistry, CapabilityBundle, CapabilityBundleStore, ChannelInstallation, ChannelInstallationStore, ConnectionEntry, ConnectionStore, CreateAgentWebAppInput, CreateAssistantRequest, CreateBindingInput, CreateCapabilityBundleInput, CreateChannelInstallationInput, CreateChannelInstallationRequest, CreateDatabaseConfigRequest, CreateEvalCaseRequest, CreateEvalProjectRequest, CreateEvalRunRequest, CreateEvalSuiteRequest, CreateMcpServerConfigRequest, CreateMenuItemInput, CreateMetricsServerConfigRequest, CreateProjectRequest, CreateRunStepRequest, CreateShareRequest, CreateSkillRequest, CreateTenantRequest, CreateThreadRequest, CreateUserRequest, CreateUserTenantLinkRequest, CreateWorkflowRunRequest, CreateWorkspaceRequest, DatabaseConfig, DatabaseConfigEntry, DatabaseConfigStore, DatabaseType, EvalCase, EvalProject, EvalProjectReport, EvalRun, EvalRunResult, EvalStore, EvalSuite, LarkChannelInstallationConfig, McpServerConfigEntry, McpServerConfigStore, MenuItem, MenuRegistry, MetricsServerConfig, MetricsServerConfigEntry, MetricsServerConfigStore, Project, ProjectStore, ResourceAddress, RunStep, ScheduleExecutionType, ScheduleStorage, ScheduledTaskDefinition, ScheduledTaskStatus, ShareRecord, ShareResult, ShareVisibility, SharedResourceStore, Skill, SkillStore, StorageType, Tenant, TenantStatus, TenantStore, Thread, ThreadStore, UpdateAgentWebAppInput, UpdateCapabilityBundleInput, UpdateChannelInstallationRequest, UpdateDatabaseConfigRequest, UpdateMcpServerConfigRequest, UpdateMetricsServerConfigRequest, UpdateProjectRequest, UpdateRunStepRequest, UpdateTenantRequest, UpdateUserRequest, UpdateUserTenantLinkRequest, UpdateWorkflowRunRequest, UpdateWorkspaceRequest, User, UserStore, UserTenantLink, UserTenantLinkStore, UserTenantRole, WorkflowRun, WorkflowTrackingStore, Workspace, WorkspaceStore } from '@axiom-lattice/protocols';
5
- import { IMessageQueueStore, AddMessageParams, PendingMessage, QueueScope, ClaimMessagesOptions, ThreadInfo } from '@axiom-lattice/core';
5
+ import { IMessageQueueStore, AddMessageParams, PendingMessage, QueueScope, ClaimMessagesOptions, ThreadInfo, IAgentRunLedger, BeginAgentRunInput, AgentRunRecord, CreatePendingAgentRunInput, ListPendingRunsOptions, ClaimAgentRunInput, DeleteAgentRunExpected, AgentRunStatus, RollbackFailureResult, AgentRunRollbackResult, AgentRunExpiredOutcome, SettleExpiredRunOptions, AgentRunCounts, AgentRunSource, ReapedAgentRun } from '@axiom-lattice/core';
6
6
  export { AddMessageParams, PendingMessage, ThreadInfo } from '@axiom-lattice/core';
7
7
  import { PostgresSaver } from '@langchain/langgraph-checkpoint-postgres';
8
8
  import { DocumentInterface } from '@langchain/core/documents';
@@ -78,6 +78,10 @@ declare class PostgreSQLThreadStore implements ThreadStore {
78
78
  * Check if thread exists
79
79
  */
80
80
  hasThread(tenantId: string, threadId: string): Promise<boolean>;
81
+ /**
82
+ * List expired threads across all tenants, oldest expiry first.
83
+ */
84
+ listExpiredThreads(now: Date, limit: number): Promise<Thread[]>;
81
85
  /**
82
86
  * Ensure store is initialized
83
87
  */
@@ -875,6 +879,8 @@ declare class PostgreSQLEvalStore implements EvalStore {
875
879
  error?: string;
876
880
  completedAt?: Date;
877
881
  }): Promise<EvalRun | null>;
882
+ /** Request cooperative cancellation for a running evaluation. */
883
+ requestCancel(tenantId: string, id: string): Promise<boolean>;
878
884
  /** Delete a run and its results */
879
885
  deleteRun(tenantId: string, id: string): Promise<boolean>;
880
886
  /** Get all results belonging to a run */
@@ -943,6 +949,9 @@ declare class ThreadMessageQueueStore implements IMessageQueueStore {
943
949
  getQueueSize(threadId: string, scope?: QueueScope): Promise<number>;
944
950
  /**
945
951
  * Get all threads with pending or processing messages
952
+ *
953
+ * @returns One entry per full scope, with `hasPending` distinguishing
954
+ * processing-only threads (no pending row) from threads with work to drain.
946
955
  */
947
956
  getThreadsWithPendingMessages(): Promise<ThreadInfo[]>;
948
957
  /**
@@ -1937,6 +1946,309 @@ declare class PostgreSQLPluginDeploymentStore implements PluginDeploymentStore {
1937
1946
  delete(tenantId: string, pluginType: string): Promise<boolean>;
1938
1947
  }
1939
1948
 
1949
+ /**
1950
+ * PostgreSQL Agent Run Ledger
1951
+ *
1952
+ * Durable run lifecycle and task queue. `source='run_api'` rows are claimed by
1953
+ * the run-task worker; `source='legacy'` rows preserve the existing
1954
+ * observational ledger/message-queue behavior.
1955
+ */
1956
+
1957
+ /** Options accepted by {@link PostgreSQLAgentRunLedger}. */
1958
+ interface PostgreSQLAgentRunLedgerOptions {
1959
+ /** Externally managed pool. When supplied, migrations are not run here. */
1960
+ pool?: Pool;
1961
+ /** Connection string or pool config used to create a pool. */
1962
+ poolConfig?: string | PoolConfig;
1963
+ /** Set to `false` to skip running this store's migration automatically. */
1964
+ autoMigrate?: boolean;
1965
+ }
1966
+ /**
1967
+ * PostgreSQL implementation of {@link IAgentRunLedger}.
1968
+ *
1969
+ * @remarks
1970
+ * - Run rows are the durable queue for `run_api` and `project_task` work.
1971
+ * Claim is an atomic CAS guarded by the same-thread running rule.
1972
+ * - Legacy `beginRun` keeps the historical reconcile-then-insert behavior and
1973
+ * writes `source='legacy'`.
1974
+ * - `reapExpired` reports expired run-queue rows without mutating them;
1975
+ * `reapLegacyExpired` preserves the supervisor's legacy settle behavior.
1976
+ */
1977
+ declare class PostgreSQLAgentRunLedger implements IAgentRunLedger {
1978
+ private pool;
1979
+ private ownsPool;
1980
+ private initialized;
1981
+ private initPromise;
1982
+ private migrationManager;
1983
+ /**
1984
+ * @param options An externally managed pool, or a pool config/connection URL.
1985
+ */
1986
+ constructor(options: PostgreSQLAgentRunLedgerOptions);
1987
+ /** Runs pending migrations once. */
1988
+ initialize(): Promise<void>;
1989
+ /** Ends the pool when this store owns it. */
1990
+ dispose(): Promise<void>;
1991
+ /**
1992
+ * Creates a running legacy run, reconciling any existing running row first.
1993
+ *
1994
+ * @remarks The caller holds the `thread-run` lease, so a surviving `running`
1995
+ * row is stale (its owner can no longer hold the lease) even when its ledger
1996
+ * lease has not expired yet.
1997
+ */
1998
+ beginRun(input: BeginAgentRunInput): Promise<AgentRunRecord>;
1999
+ /** Creates an unowned pending run-queue row. */
2000
+ createPendingRun(input: CreatePendingAgentRunInput): Promise<AgentRunRecord>;
2001
+ /** Lists claimable run-queue rows, oldest available first. */
2002
+ listPendingRuns(options?: ListPendingRunsOptions): Promise<AgentRunRecord[]>;
2003
+ /** Atomically claims a pending run-queue row. */
2004
+ claimRun(input: ClaimAgentRunInput): Promise<AgentRunRecord | undefined>;
2005
+ /**
2006
+ * Claims under a per-tenant running cap.
2007
+ *
2008
+ * @remarks Serializes claims for one tenant with a transaction-scoped
2009
+ * advisory lock, counts running rows, then runs the same claim statement.
2010
+ * The lock is shared with admission creates so cap checks cannot race.
2011
+ */
2012
+ private claimRunWithTenantCap;
2013
+ /** Captures the checkpoint a running run-queue row started from. */
2014
+ setBaseCheckpoint(tenantId: string, runId: string, owner: string, baseCheckpointId: string | null): Promise<boolean>;
2015
+ /** Records the resolved capability runtime revision for a running run. */
2016
+ setCapabilityRevision(tenantId: string, runId: string, owner: string, revision: string | null): Promise<boolean>;
2017
+ /** Deletes a run row immediately, optionally guarded by status/owner. */
2018
+ deleteRun(tenantId: string, runId: string, expected?: DeleteAgentRunExpected): Promise<boolean>;
2019
+ /** Deletes terminal rows finished before `cutoffMs`, oldest first. */
2020
+ deleteTerminalBefore(cutoffMs: number, limit: number): Promise<number>;
2021
+ /** Extends a running run's lease when `owner` still holds it. */
2022
+ heartbeatRun(runId: string, owner: string, leaseMs: number): Promise<boolean>;
2023
+ /** Settles a running run when `owner` still holds it. */
2024
+ settleRun(runId: string, owner: string, status: Exclude<AgentRunStatus, "pending" | "running">, error?: string): Promise<boolean>;
2025
+ /** Settles a running run only when no rollback is pending. */
2026
+ settleRunUnlessRollbackRequested(runId: string, owner: string, status: Exclude<AgentRunStatus, "pending" | "running">, error?: string): Promise<boolean>;
2027
+ /** Terminates an uncaptured rollback run with a repair signal. */
2028
+ settleRollbackFailure(tenantId: string, runId: string, error: string): Promise<boolean>;
2029
+ /** Records one bounded rollback failure and optionally converges. */
2030
+ recordRollbackFailure(tenantId: string, runId: string, error: string, maxAttempts: number): Promise<RollbackFailureResult | undefined>;
2031
+ /** Reads a run within a tenant. */
2032
+ getRun(tenantId: string, runId: string): Promise<AgentRunRecord | undefined>;
2033
+ /** Finds the active (pending/running) run for a ProjectTask. */
2034
+ getActiveRunForTask(tenantId: string, taskId: string): Promise<AgentRunRecord | undefined>;
2035
+ /** Lists a thread's runs, newest first (including pending rows). */
2036
+ listRuns(tenantId: string, threadId: string, options?: {
2037
+ limit?: number;
2038
+ offset?: number;
2039
+ }): Promise<AgentRunRecord[]>;
2040
+ /** Finds the thread's running run, if any. */
2041
+ findRunning(tenantId: string, threadId: string): Promise<AgentRunRecord | undefined>;
2042
+ /** Requests cancellation, settling pending/expired rows interrupted. */
2043
+ requestCancel(tenantId: string, runId: string): Promise<"cancelled" | "requested" | "not_found" | "terminal">;
2044
+ /** Deletes a pending run or flags a running run for rollback. */
2045
+ requestRollback(tenantId: string, runId: string): Promise<AgentRunRollbackResult>;
2046
+ /** Atomically reclaims an expired running row without requeueing it. */
2047
+ recoverExpiredRun(runId: string, owner: string, leaseMs: number): Promise<AgentRunRecord | undefined>;
2048
+ /** Atomically requeues or interrupts an expired run-queue row. */
2049
+ settleExpiredRun(runId: string, outcome: AgentRunExpiredOutcome, options?: SettleExpiredRunOptions): Promise<boolean>;
2050
+ /** Counts runs grouped by lifecycle status. */
2051
+ counts(): Promise<AgentRunCounts>;
2052
+ /** Reports expired run-queue rows for the requested sources. */
2053
+ reapExpired(sources?: readonly AgentRunSource[]): Promise<ReapedAgentRun[]>;
2054
+ /** Lists rollback work that still needs a checkpoint rewind. */
2055
+ listRollbackRuns(): Promise<ReapedAgentRun[]>;
2056
+ /** Settles expired legacy rows, preserving the historical supervisor behavior. */
2057
+ reapLegacyExpired(): Promise<ReapedAgentRun[]>;
2058
+ }
2059
+
2060
+ /** Options accepted by {@link PostgreSQLChannelReplyJobStore}. */
2061
+ interface PostgreSQLChannelReplyJobStoreOptions {
2062
+ /** Externally managed pool. When supplied, migrations are not run here. */
2063
+ pool?: Pool;
2064
+ /** Connection string or pool config used to create a pool. */
2065
+ poolConfig?: string | PoolConfig;
2066
+ /** Set to `false` to skip running this store's migration automatically. */
2067
+ autoMigrate?: boolean;
2068
+ }
2069
+ /**
2070
+ * PostgreSQL {@link ChannelReplyJobStore}.
2071
+ *
2072
+ * @remarks Claims are a single conditional `UPDATE` (CAS) guarded by status,
2073
+ * `available_at`, and lease expiry, so competing replicas cannot both win.
2074
+ * Lease/created/updated/delivered timestamps use the database clock; only the
2075
+ * caller-supplied `availableAt` epoch is stored as-is.
2076
+ */
2077
+ declare class PostgreSQLChannelReplyJobStore implements ChannelReplyJobStore {
2078
+ private pool;
2079
+ private ownsPool;
2080
+ private initialized;
2081
+ private initPromise;
2082
+ private migrationManager;
2083
+ /** @param options An externally managed pool, or a pool config/connection URL. */
2084
+ constructor(options: PostgreSQLChannelReplyJobStoreOptions);
2085
+ /** Runs pending migrations once. */
2086
+ initialize(): Promise<void>;
2087
+ /** Ends the pool when this store owns it. */
2088
+ dispose(): Promise<void>;
2089
+ /** Creates a pending job with database-clock created/updated timestamps. */
2090
+ create(input: CreateChannelReplyJobInput): Promise<ChannelReplyJob>;
2091
+ /** Reads one job within a tenant scope. */
2092
+ get(tenantId: string, runId: string): Promise<ChannelReplyJob | null>;
2093
+ /** Lists claimable pending jobs that are due at `now`, oldest first. */
2094
+ listPending(now: number, limit?: number): Promise<ChannelReplyJob[]>;
2095
+ /**
2096
+ * Atomically leases a claimable job.
2097
+ *
2098
+ * @param now Accepted for interface symmetry; PostgreSQL uses the database clock.
2099
+ */
2100
+ claim(tenantId: string, runId: string, owner: string, leaseMs: number, now?: number): Promise<ChannelReplyJob | null>;
2101
+ /**
2102
+ * Marks a job delivered when `owner` still holds the lease.
2103
+ *
2104
+ * @param now Accepted for interface symmetry; PostgreSQL uses the database clock.
2105
+ */
2106
+ markDelivered(tenantId: string, runId: string, owner: string, outputMessageId?: string | null, now?: number): Promise<ChannelReplyJob | null>;
2107
+ /**
2108
+ * Returns a job to pending with an incremented attempt count.
2109
+ *
2110
+ * @param now Accepted for interface symmetry; PostgreSQL uses the database clock.
2111
+ */
2112
+ reschedule(tenantId: string, runId: string, owner: string, error: string, availableAt: number, now?: number): Promise<ChannelReplyJob | null>;
2113
+ /**
2114
+ * Marks a job terminally failed when `owner` still holds the lease.
2115
+ *
2116
+ * @param now Accepted for interface symmetry; PostgreSQL uses the database clock.
2117
+ */
2118
+ markFailed(tenantId: string, runId: string, owner: string, error: string, now?: number): Promise<ChannelReplyJob | null>;
2119
+ /** Deletes one job. Returns whether a row was removed. */
2120
+ delete(tenantId: string, runId: string): Promise<boolean>;
2121
+ /** Deletes terminal jobs whose last update is older than `before`. */
2122
+ deleteTerminalBefore(before: number, limit?: number): Promise<number>;
2123
+ }
2124
+
2125
+ /**
2126
+ * Raised when a checkpoint copy targets a thread that already owns rows.
2127
+ */
2128
+ declare class CheckpointTargetNotEmptyError extends Error {
2129
+ /** Machine-readable conflict code. */
2130
+ readonly code: "CHECKPOINT_TARGET_NOT_EMPTY";
2131
+ /**
2132
+ * @param threadId - Non-empty target thread id.
2133
+ */
2134
+ constructor(threadId: string);
2135
+ }
2136
+ /**
2137
+ * Raised when a checkpoint rewind targets a base checkpoint that does not exist.
2138
+ */
2139
+ declare class CheckpointBaseNotFoundError extends Error {
2140
+ /** Machine-readable failure code. */
2141
+ readonly code: "CHECKPOINT_BASE_NOT_FOUND";
2142
+ /** Thread owning the missing base checkpoint. */
2143
+ readonly threadId: string;
2144
+ /** Base checkpoint id that was not found. */
2145
+ readonly baseCheckpointId: string;
2146
+ /**
2147
+ * @param threadId - Thread owning the missing base checkpoint.
2148
+ * @param baseCheckpointId - Base checkpoint id that was not found.
2149
+ */
2150
+ constructor(threadId: string, baseCheckpointId: string);
2151
+ }
2152
+ /**
2153
+ * Checkpoint accounting and maintenance over LangGraph's built-in
2154
+ * `PostgresSaver` tables.
2155
+ *
2156
+ * `get` is a read-only aggregate. `copyThread`, `deleteThread`, `deleteAfter`,
2157
+ * and `pruneThread` are the explicit maintenance operations; each runs in one
2158
+ * transaction and touches only the `checkpoints`, `checkpoint_blobs`, and
2159
+ * `checkpoint_writes` tables created by `PostgresSaver.setup()`. No migration
2160
+ * is added.
2161
+ */
2162
+ declare class PostgreSQLCheckpointStorage implements CheckpointStorage, CheckpointMaintenance {
2163
+ private readonly pool;
2164
+ /**
2165
+ * @param pool - PostgreSQL pool shared with the rest of the store config.
2166
+ */
2167
+ constructor(pool: Pool);
2168
+ /**
2169
+ * Measure the checkpoint storage used by one thread.
2170
+ *
2171
+ * @param threadId - Thread id whose checkpoint rows should be measured.
2172
+ * @returns Counts and byte sizes grouped by checkpoint storage category.
2173
+ */
2174
+ get(threadId: string): Promise<ThreadCheckpointStorage>;
2175
+ /**
2176
+ * Copy every checkpoint row from a source thread to an empty target thread.
2177
+ *
2178
+ * @param sourceThreadId - Thread whose rows are copied.
2179
+ * @param targetThreadId - Empty thread that receives the rows.
2180
+ * @returns Resolves when the copy commits; an empty source is a no-op.
2181
+ * @throws {CheckpointTargetNotEmptyError} When the target already owns rows.
2182
+ */
2183
+ copyThread(sourceThreadId: string, targetThreadId: string): Promise<void>;
2184
+ /**
2185
+ * Retain only the latest N checkpoints per checkpoint namespace.
2186
+ *
2187
+ * @param threadId - Thread whose checkpoint history is pruned.
2188
+ * @param options - Retention options.
2189
+ * @param options.keepLatest - Number of latest checkpoints to retain per namespace.
2190
+ * @returns Counts of deleted checkpoint, blob, and write rows.
2191
+ */
2192
+ pruneThread(threadId: string, options: {
2193
+ keepLatest: number;
2194
+ }): Promise<{
2195
+ checkpoints: number;
2196
+ blobs: number;
2197
+ writes: number;
2198
+ }>;
2199
+ /**
2200
+ * Delete the checkpoints that descend from a base checkpoint.
2201
+ *
2202
+ * Descendants are discovered by following both same-namespace
2203
+ * `parent_checkpoint_id` edges and cross-namespace `metadata.parents` edges
2204
+ * (LangGraph's `{ "<parent checkpoint_ns>": "<parent checkpoint id>" }` map on
2205
+ * subgraph checkpoints), recursively across every namespace. Out-of-order or
2206
+ * clock-skewed ids do not affect the result. Writes keyed to the base
2207
+ * checkpoint belong to the rolled-back run's first superstep and are deleted
2208
+ * too. Blobs referenced only by deleted checkpoints are removed.
2209
+ *
2210
+ * @param threadId - Thread whose later checkpoint history is deleted.
2211
+ * @param baseCheckpointId - Checkpoint to retain as the new tip, or `null` to
2212
+ * delete every checkpoint for the thread.
2213
+ * @returns Resolves when the deletion commits; no descendants is a no-op.
2214
+ * @throws {RangeError} When `baseCheckpointId` is an empty string.
2215
+ * @throws {CheckpointBaseNotFoundError} When the base checkpoint does not
2216
+ * exist on the thread.
2217
+ */
2218
+ deleteAfter(threadId: string, baseCheckpointId: string | null): Promise<void>;
2219
+ /**
2220
+ * Delete every checkpoint row for a thread.
2221
+ *
2222
+ * @param threadId - Thread whose checkpoint rows are deleted.
2223
+ * @returns Resolves when the deletion commits.
2224
+ */
2225
+ deleteThread(threadId: string): Promise<void>;
2226
+ }
2227
+
2228
+ /**
2229
+ * PostgreSQL tenant-scoped namespaced key-value store.
2230
+ *
2231
+ * @remarks
2232
+ * - `namespace` is a `TEXT[]`; prefix search compares `namespace[1:n]`.
2233
+ * - `filter` uses JSONB containment (`value @> $filter`).
2234
+ * - `query` is a case-insensitive substring over `value::text`.
2235
+ * - Expired items are excluded from reads/searches and hard-deleted by
2236
+ * {@link deleteExpired}.
2237
+ */
2238
+ declare class PostgreSQLStore implements StoreProtocol {
2239
+ private readonly pool;
2240
+ /**
2241
+ * @param pool - Pool shared with the rest of the store config.
2242
+ */
2243
+ constructor(pool: Pool);
2244
+ put(tenantId: string, input: StorePutInput): Promise<StoreItem>;
2245
+ get(tenantId: string, namespace: string[], key: string): Promise<StoreItem | null>;
2246
+ delete(tenantId: string, namespace: string[], key: string): Promise<boolean>;
2247
+ search(tenantId: string, input: StoreSearchInput): Promise<StoreItem[]>;
2248
+ listNamespaces(tenantId: string, prefix?: string[], limit?: number): Promise<string[][]>;
2249
+ deleteExpired(now: Date, limit: number): Promise<number>;
2250
+ }
2251
+
1940
2252
  declare function createPgStoreConfig(connectionString: string): Promise<{
1941
2253
  workspace: PostgreSQLWorkspaceStore;
1942
2254
  project: PostgreSQLProjectStore;
@@ -1974,8 +2286,12 @@ declare function createPgStoreConfig(connectionString: string): Promise<{
1974
2286
  lease: PostgreSQLLeaseStore;
1975
2287
  outbox: PostgreSQLOutboxStore;
1976
2288
  pluginDeployment: PostgreSQLPluginDeploymentStore;
2289
+ agentRun: PostgreSQLAgentRunLedger;
2290
+ channelReplyJob: PostgreSQLChannelReplyJobStore;
1977
2291
  vectorStoreProvider: PGVectorStoreProvider;
1978
2292
  checkpoint: PostgresSaver;
2293
+ checkpointStorage: PostgreSQLCheckpointStorage;
2294
+ store: PostgreSQLStore;
1979
2295
  }>;
1980
2296
 
1981
2297
  /**
@@ -2136,6 +2452,12 @@ declare class MigrationManager {
2136
2452
  * Initial migration: Create threads table
2137
2453
  */
2138
2454
  declare const createThreadsTable: Migration;
2455
+ /**
2456
+ * Migration: Add per-thread expiry (`expires_at`) for the TTL sweeper.
2457
+ *
2458
+ * A partial index keeps expiry scans cheap while leaving non-TTL threads out.
2459
+ */
2460
+ declare const addThreadExpiresAt: Migration;
2139
2461
 
2140
2462
  /**
2141
2463
  * Thread table tenant isolation migration
@@ -2446,6 +2768,8 @@ declare const addInterruptPolicyToEvalCases: Migration;
2446
2768
  declare const enforceUniqueEvalProjectName: Migration;
2447
2769
  /** Add task_id to eval runs (training round association, 1 task : N runs) */
2448
2770
  declare const addTaskIdToEvalRuns: Migration;
2771
+ /** Cooperative cancellation flag for running eval runs. */
2772
+ declare const addCancelRequestedToEvalRuns: Migration;
2449
2773
  /** All eval migrations in version order */
2450
2774
  declare const evalMigrations: Migration[];
2451
2775
 
@@ -2481,4 +2805,34 @@ declare const createPluginDeployments: Migration;
2481
2805
  */
2482
2806
  declare const dropPluginDeploymentAuthToken: Migration;
2483
2807
 
2484
- export { ChannelBindingStore, type ChannelBindingStoreOptions, type ChannelIdentityMapping, ChannelIdentityMappingStore, type ChannelIdentityMappingStoreOptions, type CreateChannelIdentityMappingInput, DuplicateProjectMembershipError, DuplicateProjectRoomMessageIdempotencyKeyError, MenuStore, type MenuStoreOptions, type Migration, MigrationManager, PGVectorStoreProvider, PostgreSQLA2AApiKeyStore, type PostgreSQLA2AApiKeyStoreOptions, PostgreSQLAgentWebAppStore, type PostgreSQLAgentWebAppStoreOptions, PostgreSQLAssistantStore, type PostgreSQLAssistantStoreOptions, PostgreSQLCapabilityBundleStore, type PostgreSQLCapabilityBundleStoreOptions, PostgreSQLChannelInstallationStore, type PostgreSQLChannelInstallationStoreOptions, PostgreSQLCollectionStore, type PostgreSQLCollectionStoreOptions, PostgreSQLConnectionStore, PostgreSQLDatabaseConfigStore, type PostgreSQLDatabaseConfigStoreOptions, PostgreSQLEvalStore, type PostgreSQLEvalStoreOptions, PostgreSQLMcpServerConfigStore, type PostgreSQLMcpServerConfigStoreOptions, PostgreSQLMetricsServerConfigStore, type PostgreSQLMetricsServerConfigStoreOptions, PostgreSQLModelProviderStore, type PostgreSQLModelProviderStoreOptions, PostgreSQLOpenAuditStore, type PostgreSQLOpenAuditStoreOptions, PostgreSQLPluginDeploymentStore, PostgreSQLProjectBotMembershipStore, PostgreSQLProjectMembershipStore, PostgreSQLProjectRoomMessageStore, PostgreSQLProjectRoomReadStateStore, PostgreSQLProjectRoomStore, PostgreSQLProjectStore, type PostgreSQLProjectStoreOptions, PostgreSQLScheduleStorage, type PostgreSQLScheduleStorageOptions, PostgreSQLSkillStore, type PostgreSQLSkillStoreOptions, PostgreSQLTaskWorkItemStore, type PostgreSQLTaskWorkItemStoreOptions, PostgreSQLTenantStore, type PostgreSQLTenantStoreOptions, type PostgreSQLThreadMessageQueueStoreOptions, PostgreSQLThreadStore, type PostgreSQLThreadStoreOptions, PostgreSQLUserStore, type PostgreSQLUserStoreOptions, PostgreSQLUserTenantLinkStore, type PostgreSQLUserTenantLinkStoreOptions, PostgreSQLWorkflowTrackingStore, type PostgreSQLWorkflowTrackingStoreOptions, PostgreSQLWorkspaceStore, type PostgreSQLWorkspaceStoreOptions, PostgresSharedResourceStore, type PostgresSharedResourceStoreOptions, ProjectBotMembershipIdConflictError, ProjectMembershipIdConflictError, ProjectRoomMessageIdConflictError, ThreadMessageQueueStore, addAssistantTenantId, addEnvToEvalRuns, addFileContentType, addHoldoutToEvalRuns, addInterruptColumnsToEval, addInterruptPolicyToEvalCases, addMcpAppContentType, addProjectConfigColumn, addScheduleTenantId, addSkillTenantId, addStepThreadId, addTaskIdToEvalRuns, addThreadTenantId, addWorkflowRunsTenantStatusUpdatedIndex, alterChannelInstallationsTable, changeAssistantPrimaryKey, changeSkillPrimaryKey, changeThreadPrimaryKey, createA2AApiKeysTable, createAgentWebAppsTable, createAssistantsTable, createCapabilityBundlesTable, createChannelBindingsTable, createChannelIdentityMappingTables, createChannelInstallationsTable, createCollectionsTable, createDatabaseConfigsTable, createEvalCasesTable, createEvalProjectsTable, createEvalRunResultsTable, createEvalRunsTable, createEvalSuitesTable, createMcpServerConfigsTable, createMenuItemsTable, createMetricsConfigsTable, createPGVectorStoreProvider, createPgStoreConfig, createPluginDeployments, createProjectRoomReadStates, createProjectRoomTables, createProjectsTable, createScheduledTasksTable, createSharedResourcesTable, createSkillsTable, createTenantsTable, createThreadMessageQueueTable, createThreadsTable, createUsersTable, createWorkflowTrackingTables, createWorkspacesTable, dropPluginDeploymentAuthToken, enforceUniqueEvalProjectName, evalMigrations, mapRowToRunStep, mapRowToWorkflowRun, safeParse };
2808
+ /**
2809
+ * Creates the durable agent run ledger.
2810
+ *
2811
+ * @remarks
2812
+ * The partial unique index enforces the ledger invariant: at most one
2813
+ * `running` row per `(tenant_id, thread_id)`.
2814
+ */
2815
+ declare const createAgentRunLedgerTable: Migration;
2816
+
2817
+ /**
2818
+ * Durable channel reply jobs used by the cross-replica reply dispatcher.
2819
+ *
2820
+ * @remarks Lease-based claims make the row the single source of truth for
2821
+ * "which replica is delivering this run's channel reply". Timestamps are epoch
2822
+ * milliseconds from the database clock.
2823
+ */
2824
+ declare const createChannelReplyJobsTable: Migration;
2825
+
2826
+ /**
2827
+ * Namespaced KV store migrations.
2828
+ */
2829
+
2830
+ /**
2831
+ * Migration: create the tenant-scoped namespaced KV store table.
2832
+ *
2833
+ * GIN indexes support namespace prefix and JSONB containment filters; the
2834
+ * partial expiry index supports the TTL sweeper.
2835
+ */
2836
+ declare const createStoreItemsTable: Migration;
2837
+
2838
+ export { ChannelBindingStore, type ChannelBindingStoreOptions, type ChannelIdentityMapping, ChannelIdentityMappingStore, type ChannelIdentityMappingStoreOptions, CheckpointBaseNotFoundError, CheckpointTargetNotEmptyError, type CreateChannelIdentityMappingInput, DuplicateProjectMembershipError, DuplicateProjectRoomMessageIdempotencyKeyError, MenuStore, type MenuStoreOptions, type Migration, MigrationManager, PGVectorStoreProvider, PostgreSQLA2AApiKeyStore, type PostgreSQLA2AApiKeyStoreOptions, PostgreSQLAgentRunLedger, type PostgreSQLAgentRunLedgerOptions, PostgreSQLAgentWebAppStore, type PostgreSQLAgentWebAppStoreOptions, PostgreSQLAssistantStore, type PostgreSQLAssistantStoreOptions, PostgreSQLCapabilityBundleStore, type PostgreSQLCapabilityBundleStoreOptions, PostgreSQLChannelInstallationStore, type PostgreSQLChannelInstallationStoreOptions, PostgreSQLChannelReplyJobStore, type PostgreSQLChannelReplyJobStoreOptions, PostgreSQLCheckpointStorage, PostgreSQLCollectionStore, type PostgreSQLCollectionStoreOptions, PostgreSQLConnectionStore, PostgreSQLDatabaseConfigStore, type PostgreSQLDatabaseConfigStoreOptions, PostgreSQLEvalStore, type PostgreSQLEvalStoreOptions, PostgreSQLMcpServerConfigStore, type PostgreSQLMcpServerConfigStoreOptions, PostgreSQLMetricsServerConfigStore, type PostgreSQLMetricsServerConfigStoreOptions, PostgreSQLModelProviderStore, type PostgreSQLModelProviderStoreOptions, PostgreSQLOpenAuditStore, type PostgreSQLOpenAuditStoreOptions, PostgreSQLPluginDeploymentStore, PostgreSQLProjectBotMembershipStore, PostgreSQLProjectMembershipStore, PostgreSQLProjectRoomMessageStore, PostgreSQLProjectRoomReadStateStore, PostgreSQLProjectRoomStore, PostgreSQLProjectStore, type PostgreSQLProjectStoreOptions, PostgreSQLScheduleStorage, type PostgreSQLScheduleStorageOptions, PostgreSQLSkillStore, type PostgreSQLSkillStoreOptions, PostgreSQLStore, PostgreSQLTaskWorkItemStore, type PostgreSQLTaskWorkItemStoreOptions, PostgreSQLTenantStore, type PostgreSQLTenantStoreOptions, type PostgreSQLThreadMessageQueueStoreOptions, PostgreSQLThreadStore, type PostgreSQLThreadStoreOptions, PostgreSQLUserStore, type PostgreSQLUserStoreOptions, PostgreSQLUserTenantLinkStore, type PostgreSQLUserTenantLinkStoreOptions, PostgreSQLWorkflowTrackingStore, type PostgreSQLWorkflowTrackingStoreOptions, PostgreSQLWorkspaceStore, type PostgreSQLWorkspaceStoreOptions, PostgresSharedResourceStore, type PostgresSharedResourceStoreOptions, ProjectBotMembershipIdConflictError, ProjectMembershipIdConflictError, ProjectRoomMessageIdConflictError, ThreadMessageQueueStore, addAssistantTenantId, addCancelRequestedToEvalRuns, addEnvToEvalRuns, addFileContentType, addHoldoutToEvalRuns, addInterruptColumnsToEval, addInterruptPolicyToEvalCases, addMcpAppContentType, addProjectConfigColumn, addScheduleTenantId, addSkillTenantId, addStepThreadId, addTaskIdToEvalRuns, addThreadExpiresAt, addThreadTenantId, addWorkflowRunsTenantStatusUpdatedIndex, alterChannelInstallationsTable, changeAssistantPrimaryKey, changeSkillPrimaryKey, changeThreadPrimaryKey, createA2AApiKeysTable, createAgentRunLedgerTable, createAgentWebAppsTable, createAssistantsTable, createCapabilityBundlesTable, createChannelBindingsTable, createChannelIdentityMappingTables, createChannelInstallationsTable, createChannelReplyJobsTable, createCollectionsTable, createDatabaseConfigsTable, createEvalCasesTable, createEvalProjectsTable, createEvalRunResultsTable, createEvalRunsTable, createEvalSuitesTable, createMcpServerConfigsTable, createMenuItemsTable, createMetricsConfigsTable, createPGVectorStoreProvider, createPgStoreConfig, createPluginDeployments, createProjectRoomReadStates, createProjectRoomTables, createProjectsTable, createScheduledTasksTable, createSharedResourcesTable, createSkillsTable, createStoreItemsTable, createTenantsTable, createThreadMessageQueueTable, createThreadsTable, createUsersTable, createWorkflowTrackingTables, createWorkspacesTable, dropPluginDeploymentAuthToken, enforceUniqueEvalProjectName, evalMigrations, mapRowToRunStep, mapRowToWorkflowRun, safeParse };