@axiom-lattice/core 6.1.1 → 6.3.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.
package/dist/index.d.mts CHANGED
@@ -8,15 +8,15 @@ import { BaseLanguageModelInput, LanguageModelLike } from '@langchain/core/langu
8
8
  import { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';
9
9
  import { ChatResult } from '@langchain/core/outputs';
10
10
  import * as _axiom_lattice_protocols from '@axiom-lattice/protocols';
11
- import { LLMConfig, SemanticMetricsServerConfig, MetricMeta, MetricQueryResult, DataSource, SemanticMetricsQueryRequest, SemanticMetricsQueryResponse, TableQueryRequest, TableQueryResponse, ExecuteSqlQueryRequest, ExecuteSqlQueryResponse, MetricsServerType, MetricsServerConfig, ToolConfig, ToolExecutor, AgentConfig, MiddlewareType, GraphBuildOptions, DeepAgentConfig, MessageChunk, MessageChunkType, QueueLatticeProtocol, QueueConfig, QueueClient, QueueResult, ScheduleLatticeProtocol, ScheduleConfig, ScheduleClient, ScheduleStorage, TaskHandler, ScheduleOnceOptions, ScheduleCronOptions, ScheduledTaskDefinition, ScheduledTaskStatus, ScheduleExecutionType, TrustedRunContext, QueuedExecutionMode, ThreadStore, AssistantStore, SkillStore, CollectionStore, WorkspaceStore, ProjectStore, DatabaseConfigStore, MetricsServerConfigStore, McpServerConfigStore, ModelProviderStore, UserStore, TenantStore, UserTenantLinkStore, WorkflowTrackingStore, EvalStore, ChannelInstallationStore, BindingRegistry, MenuRegistry, A2AApiKeyStore, OpenAuditStore, TaskStore, SharedResourceStore, ConnectionStore, TaskWorkItemStore, AgentWebAppStore, CapabilityBundleStore, ProjectRoomStore, ProjectMembershipStore, ProjectBotMembershipStore, ProjectRoomMessageStore, ProjectRoomReadStateStore, UserPushSubscriptionStore, VectorStoreProvider, Thread, CreateThreadRequest, Assistant, CreateAssistantRequest, AgentWebApp, CreateAgentWebAppInput, AgentWebAppStorePatch, AgentWebAppUpdateOptions, Project, CreateProjectRequest, UpdateProjectRequest, UpdateProjectCapabilityBundlesResult, CapabilityBundle, InternalCreateCapabilityBundleInput, InternalUpdateCapabilityBundleInput, CapabilityBundleDeleteResult, Skill, CreateSkillRequest, SkillStoreContext, DatabaseConfigEntry, CreateDatabaseConfigRequest, UpdateDatabaseConfigRequest, ModelProviderEntry, CreateModelProviderRequest, UpdateModelProviderRequest, ModelProviderStatus, ModelProviderModelEntry, ProviderModelInput, User, CreateUserRequest, UpdateUserRequest, Tenant, CreateTenantRequest, UpdateTenantRequest, UserTenantLink, CreateUserTenantLinkRequest, UpdateUserTenantLinkRequest, ChannelInstallation, ChannelInstallationType, CreateChannelInstallationInput, UpdateChannelInstallationRequest, Binding, CreateBindingInput, BindingMutablePatch, BindingListParams, A2AApiKeyRecord, CreateA2AApiKeyInput, UpdateA2AApiKeyInput, A2AApiKeyEntry, OpenAuditAppendInput, OpenAuditQuery, OpenAuditRecord, TaskMutationSnapshot, CreateTaskRequest, TaskItem, TaskListFilter, TaskDependentListQuery, UpdateTaskRequest, CreateWorkItemRequest, TaskWorkItem, CreateWorkItemIfAbsentRequest, TaskWorkItemListFilter, ProjectLifecycleEventQuery, Collection, CreateCollectionRequest, UpdateCollectionRequest, MenuItem, CreateMenuItemInput, UpdateMenuItemInput, ProjectRoom, ProjectMembership, ProjectBotMembership, ProjectRoomMessage, ProjectHumanRole, ProjectMembershipMutationResult, ProjectRoomReadState, UserPushSubscription, STTModelLatticeProtocol, STTConfig, STTClient, TranscriptionResult, LoggerLatticeProtocol, LoggerConfig, LoggerClient, LoggerContext, SkillConfig, SkillClient, PluginSkillDefinition, McpTool, McpUiResourcePayload, McpServerConfig, McpUiRef, ResourceResolver, ResourceAddress, ShareVisibility, OpenGrant, CreateShareRequest, ChannelAdapter, InterruptPolicy, ProjectTaskLifecycleAction, TaskBeliefState, PluginMeta, Plugin, PluginMetaOutput, SandboxPluginManifest, SandboxPluginToolDef, SandboxPluginDiagnostic, CapabilityPreview, CreateCapabilityBundleInput, UpdateCapabilityBundleInput, InternalStateField, InternalInput, InternalNode, InternalAgentNode, InternalMapNode, InternalDSL, ConnectionEntry } from '@axiom-lattice/protocols';
11
+ import { LLMConfig, SemanticMetricsServerConfig, MetricMeta, MetricQueryResult, DataSource, SemanticMetricsQueryRequest, SemanticMetricsQueryResponse, TableQueryRequest, TableQueryResponse, ExecuteSqlQueryRequest, ExecuteSqlQueryResponse, MetricsServerType, MetricsServerConfig, ToolConfig, ToolExecutor, AgentConfig, MiddlewareType, GraphBuildOptions, DeepAgentConfig, MessageChunk, MessageChunkType, QueueLatticeProtocol, QueueConfig, QueueClient, QueueResult, ScheduleLatticeProtocol, ScheduleConfig, ScheduleClient, ScheduleStorage, TaskHandler, ScheduleOnceOptions, ScheduleCronOptions, ScheduledTaskDefinition, ScheduledTaskStatus, ScheduleExecutionType, TrustedRunContext, QueuedExecutionMode, ThreadStore, AssistantStore, SkillStore, CollectionStore, WorkspaceStore, ProjectStore, DatabaseConfigStore, MetricsServerConfigStore, McpServerConfigStore, ModelProviderStore, UserStore, TenantStore, UserTenantLinkStore, WorkflowTrackingStore, EvalStore, ChannelInstallationStore, BindingRegistry, MenuRegistry, A2AApiKeyStore, OpenAuditStore, TaskStore, SharedResourceStore, ConnectionStore, TaskWorkItemStore, AgentWebAppStore, CapabilityBundleStore, ProjectRoomStore, ProjectMembershipStore, ProjectBotMembershipStore, ProjectRoomMessageStore, ProjectRoomReadStateStore, UserPushSubscriptionStore, LeaseStore, OutboxStore, VectorStoreProvider, Thread, CreateThreadRequest, Assistant, CreateAssistantRequest, AgentWebApp, CreateAgentWebAppInput, AgentWebAppStorePatch, AgentWebAppUpdateOptions, Project, CreateProjectRequest, UpdateProjectRequest, UpdateProjectCapabilityBundlesResult, CapabilityBundle, InternalCreateCapabilityBundleInput, InternalUpdateCapabilityBundleInput, CapabilityBundleDeleteResult, Skill, CreateSkillRequest, SkillStoreContext, DatabaseConfigEntry, CreateDatabaseConfigRequest, UpdateDatabaseConfigRequest, ModelProviderEntry, CreateModelProviderRequest, UpdateModelProviderRequest, ModelProviderStatus, ModelProviderModelEntry, ProviderModelInput, User, CreateUserRequest, UpdateUserRequest, Tenant, CreateTenantRequest, UpdateTenantRequest, UserTenantLink, CreateUserTenantLinkRequest, UpdateUserTenantLinkRequest, ChannelInstallation, ChannelInstallationType, CreateChannelInstallationInput, UpdateChannelInstallationRequest, Binding, CreateBindingInput, BindingMutablePatch, BindingListParams, A2AApiKeyRecord, CreateA2AApiKeyInput, UpdateA2AApiKeyInput, A2AApiKeyEntry, OpenAuditAppendInput, OpenAuditQuery, OpenAuditRecord, TaskMutationSnapshot, CreateTaskRequest, TaskItem, TaskListFilter, TaskDependentListQuery, UpdateTaskRequest, CreateWorkItemRequest, TaskWorkItem, CreateWorkItemIfAbsentRequest, TaskWorkItemListFilter, ProjectLifecycleEventQuery, Collection, CreateCollectionRequest, UpdateCollectionRequest, MenuItem, CreateMenuItemInput, UpdateMenuItemInput, ProjectRoom, ProjectMembership, ProjectBotMembership, ProjectRoomMessage, ProjectHumanRole, ProjectMembershipMutationResult, ProjectRoomReadState, UserPushSubscription, LeaseRecord, OutboxEvent, STTModelLatticeProtocol, STTConfig, STTClient, TranscriptionResult, LoggerLatticeProtocol, LoggerConfig, LoggerClient, LoggerContext, SkillConfig, SkillClient, PluginSkillDefinition, McpTool, McpUiResourcePayload, McpServerConfig, McpUiRef, ResourceResolver, ResourceAddress, ShareVisibility, OpenGrant, CreateShareRequest, ChannelAdapter, InterruptPolicy, ProjectTaskLifecycleAction, TaskBeliefState, PluginMeta, Plugin, PluginMetaOutput, SandboxPluginManifest, SandboxPluginToolDef, SandboxPluginDiagnostic, CapabilityPreview, CreateCapabilityBundleInput, UpdateCapabilityBundleInput, InternalStateField, InternalInput, InternalNode, InternalAgentNode, InternalMapNode, InternalDSL, ConnectionEntry } from '@axiom-lattice/protocols';
12
12
  export { _axiom_lattice_protocols as Protocols };
13
13
  export { AgentConfig, AgentType, GraphBuildOptions, MemoryType, ProjectRoomTrustedRunContext, QueuedExecutionMode, TrustedRunContext, parseQueuedExecutionMode, parseTrustedRunContext } from '@axiom-lattice/protocols';
14
14
  import * as langchain from 'langchain';
15
- import { ReactAgent, AgentMiddleware } from 'langchain';
15
+ import { StructuredTool, ReactAgent, AgentMiddleware } from 'langchain';
16
16
  import z, { z as z$1, ZodTypeAny } from 'zod';
17
17
  import { BaseStore, BaseCheckpointSaver } from '@langchain/langgraph-checkpoint';
18
18
  import * as _langchain_core_tools from '@langchain/core/tools';
19
- import { StructuredTool, DynamicStructuredTool } from '@langchain/core/tools';
19
+ import { StructuredTool as StructuredTool$1, DynamicStructuredTool } from '@langchain/core/tools';
20
20
  import * as _langchain_langgraph from '@langchain/langgraph';
21
21
  import { CompiledStateGraph, CommandParams, AnnotationRoot } from '@langchain/langgraph';
22
22
  import { ReplaySubject } from 'rxjs';
@@ -1721,11 +1721,21 @@ interface SandboxManagerProtocol {
1721
1721
  getVolumeBackendForPath(config: RunSandboxConfig, filePath: string): Promise<BackendProtocol | null>;
1722
1722
  }
1723
1723
 
1724
+ /**
1725
+ * Shell Execution Tool (shell_exec)
1726
+ *
1727
+ * Execute a shell command in the sandbox environment.
1728
+ */
1729
+
1730
+ declare const createShellExecTool: ({ vmIsolation, }: {
1731
+ vmIsolation: SandboxIsolationLevel;
1732
+ }) => StructuredTool;
1733
+
1724
1734
  type ToolDefinition = ToolConfig;
1725
1735
  interface ToolLattice {
1726
1736
  key: string;
1727
1737
  config: ToolConfig;
1728
- client: StructuredTool;
1738
+ client: StructuredTool$1;
1729
1739
  }
1730
1740
  /**
1731
1741
  * ToolLatticeManager - 单例工具Lattice管理器
@@ -1788,7 +1798,7 @@ declare class ToolLatticeManager extends BaseLatticeManager<ToolLattice> {
1788
1798
  * 获取工具客户端
1789
1799
  * @param key Lattice键名
1790
1800
  */
1791
- getToolClient(key: string): StructuredTool;
1801
+ getToolClient(key: string): StructuredTool$1;
1792
1802
  /**
1793
1803
  * 获取所有工具定义
1794
1804
  */
@@ -1798,7 +1808,7 @@ declare class ToolLatticeManager extends BaseLatticeManager<ToolLattice> {
1798
1808
  * @param key Lattice键名
1799
1809
  * @param tool 已有的StructuredTool实例
1800
1810
  */
1801
- registerExistingTool(key: string, tool: StructuredTool): void;
1811
+ registerExistingTool(key: string, tool: StructuredTool$1): void;
1802
1812
  /**
1803
1813
  * Register an existing StructuredTool into a specific tenant's tool bucket.
1804
1814
  *
@@ -1806,7 +1816,7 @@ declare class ToolLatticeManager extends BaseLatticeManager<ToolLattice> {
1806
1816
  * @param key - tool lattice key (no tenant prefix)
1807
1817
  * @param tool - the StructuredTool client
1808
1818
  */
1809
- registerExistingToolWithTenant(tenantId: string, key: string, tool: StructuredTool): void;
1819
+ registerExistingToolWithTenant(tenantId: string, key: string, tool: StructuredTool$1): void;
1810
1820
  /**
1811
1821
  * Get a tool lattice from a specific tenant bucket.
1812
1822
  *
@@ -1823,7 +1833,7 @@ declare class ToolLatticeManager extends BaseLatticeManager<ToolLattice> {
1823
1833
  * @param key - tool lattice key
1824
1834
  * @returns the StructuredTool client
1825
1835
  */
1826
- getToolClientWithTenant(tenantId: string, key: string): StructuredTool;
1836
+ getToolClientWithTenant(tenantId: string, key: string): StructuredTool$1;
1827
1837
  /**
1828
1838
  * 验证工具输入参数
1829
1839
  * @param key Lattice键名
@@ -1833,12 +1843,12 @@ declare class ToolLatticeManager extends BaseLatticeManager<ToolLattice> {
1833
1843
  }
1834
1844
  declare const toolLatticeManager: ToolLatticeManager;
1835
1845
  declare const registerToolLattice: (key: string, config: ToolConfig, executor: ToolExecutor) => void;
1836
- declare const registerExistingTool: (key: string, tool: StructuredTool) => void;
1837
- declare const registerExistingToolWithTenant: (tenantId: string, key: string, tool: StructuredTool) => void;
1846
+ declare const registerExistingTool: (key: string, tool: StructuredTool$1) => void;
1847
+ declare const registerExistingToolWithTenant: (tenantId: string, key: string, tool: StructuredTool$1) => void;
1838
1848
  declare const getToolLattice: (key: string) => ToolLattice | undefined;
1839
- declare const getToolClientWithTenant: (tenantId: string, key: string) => StructuredTool<_langchain_core_tools.ToolSchemaBase, any, any, any>;
1849
+ declare const getToolClientWithTenant: (tenantId: string, key: string) => StructuredTool$1<_langchain_core_tools.ToolSchemaBase, any, any, any>;
1840
1850
  declare const getToolDefinition: (key: string) => ToolConfig;
1841
- declare const getToolClient: (key: string) => StructuredTool<_langchain_core_tools.ToolSchemaBase, any, any, any>;
1851
+ declare const getToolClient: (key: string) => StructuredTool$1<_langchain_core_tools.ToolSchemaBase, any, any, any>;
1842
1852
  declare const getAllToolDefinitions: () => ToolConfig[];
1843
1853
  declare const validateToolInput: (key: string, input: any) => boolean;
1844
1854
 
@@ -2155,6 +2165,17 @@ declare const unregisterTeammateAgent: (key: string) => boolean;
2155
2165
  * @returns 返回CompiledGraph对象
2156
2166
  */
2157
2167
  declare const getAgentClient: (tenantId: string, key: string, options?: GraphBuildOptions) => Promise<AgentClient>;
2168
+ /**
2169
+ * 获取或初始化Agent客户端(异步,支持从store加载)
2170
+ *
2171
+ * 如果内存中不存在,会尝试从store异步加载
2172
+ *
2173
+ * @param tenantId 租户ID
2174
+ * @param key Agent Lattice键名
2175
+ * @param options 构建选项
2176
+ * @returns 返回CompiledGraph对象
2177
+ */
2178
+ declare const getAgentClientAsync: (tenantId: string, key: string, options?: GraphBuildOptions) => Promise<AgentClient>;
2158
2179
 
2159
2180
  /**
2160
2181
  * Built-in Agents
@@ -2701,6 +2722,22 @@ declare class MemoryScheduleStorage implements ScheduleStorage {
2701
2722
  * Update task
2702
2723
  */
2703
2724
  update(taskId: string, updates: Partial<ScheduledTaskDefinition>): Promise<void>;
2725
+ /**
2726
+ * Atomically claims one due fire by transitioning the task `pending -> running`.
2727
+ *
2728
+ * @param taskId Task to claim.
2729
+ * @returns True when this caller won the claim (task was `pending`); false if
2730
+ * another replica already claimed it or it is not pending.
2731
+ */
2732
+ claimScheduledRun(taskId: string): Promise<boolean>;
2733
+ /**
2734
+ * Requeues `running` tasks whose `updatedAt` is older than `olderThanMs` back
2735
+ * to `pending` (recovery after a crash that left a claim unsettled).
2736
+ *
2737
+ * @param olderThanMs Age threshold in milliseconds.
2738
+ * @returns The number of tasks requeued.
2739
+ */
2740
+ requeueStaleRunning(olderThanMs: number): Promise<number>;
2704
2741
  /**
2705
2742
  * Delete task
2706
2743
  */
@@ -2892,6 +2929,20 @@ interface ThreadInfo {
2892
2929
  projectId?: string | null;
2893
2930
  }
2894
2931
  type QueueScope = Pick<ThreadInfo, "tenantId" | "assistantId" | "workspaceId" | "projectId">;
2932
+ /**
2933
+ * Options for an atomic pending→processing claim.
2934
+ *
2935
+ * @remarks `owner` identifies the claimant replica (see `getReplicaId`); a
2936
+ * claim is only reclaimable once its lease expires.
2937
+ */
2938
+ interface ClaimMessagesOptions {
2939
+ /** Replica/owner id stamped on claimed rows. */
2940
+ owner: string;
2941
+ /** Lease time-to-live in milliseconds. */
2942
+ ttlMs: number;
2943
+ /** Maximum rows to claim; omitted means all currently-pending rows. */
2944
+ limit?: number;
2945
+ }
2895
2946
  /**
2896
2947
  * Interface for message queue storage
2897
2948
  * Implemented by pg-stores or other storage backends
@@ -2901,6 +2952,24 @@ interface IMessageQueueStore {
2901
2952
  addMessageIfCapacity(params: AddMessageParams, maxSize: number): Promise<boolean>;
2902
2953
  addMessageAtHead(params: AddMessageParams): Promise<PendingMessage>;
2903
2954
  getPendingMessages(threadId: string, scope?: QueueScope): Promise<PendingMessage[]>;
2955
+ /**
2956
+ * Atomically claims pending messages for `owner`, moving them to `processing`
2957
+ * with a lease. Concurrent callers receive disjoint sets.
2958
+ *
2959
+ * @param threadId Thread whose queue is claimed.
2960
+ * @param scope Optional exact scope filter.
2961
+ * @param options Owner id, lease TTL, and optional row limit.
2962
+ * @returns The messages this caller actually claimed (possibly empty).
2963
+ */
2964
+ claimPendingMessages(threadId: string, scope: QueueScope | undefined, options: ClaimMessagesOptions): Promise<PendingMessage[]>;
2965
+ /**
2966
+ * Returns `processing` messages whose lease expired to `pending`.
2967
+ *
2968
+ * @param threadId Thread to reclaim.
2969
+ * @param scope Optional exact scope filter.
2970
+ * @returns The number of rows reset to `pending`.
2971
+ */
2972
+ reclaimExpiredProcessing(threadId: string, scope?: QueueScope): Promise<number>;
2904
2973
  getProcessingMessages(threadId: string, scope?: QueueScope): Promise<PendingMessage[]>;
2905
2974
  getQueueSize(threadId: string, scope?: QueueScope): Promise<number>;
2906
2975
  getThreadsWithPendingMessages(): Promise<ThreadInfo[]>;
@@ -2995,6 +3064,8 @@ type StoreTypeMap = {
2995
3064
  projectRoomMessage: ProjectRoomMessageStore;
2996
3065
  projectRoomReadState: ProjectRoomReadStateStore;
2997
3066
  userPushSubscription: UserPushSubscriptionStore;
3067
+ lease: LeaseStore;
3068
+ outbox: OutboxStore;
2998
3069
  };
2999
3070
  /**
3000
3071
  * Store type keys
@@ -4008,9 +4079,11 @@ declare class InMemoryOpenAuditStore implements OpenAuditStore {
4008
4079
  */
4009
4080
 
4010
4081
  declare class InMemoryThreadMessageQueueStore implements IMessageQueueStore {
4082
+ private readonly now;
4011
4083
  private messages;
4012
4084
  private messageIdCounter;
4013
4085
  private capacityTail;
4086
+ constructor(now?: () => number);
4014
4087
  private generateId;
4015
4088
  private getMessagesForThread;
4016
4089
  private inScope;
@@ -4019,6 +4092,8 @@ declare class InMemoryThreadMessageQueueStore implements IMessageQueueStore {
4019
4092
  addMessageAtHead(params: AddMessageParams): Promise<PendingMessage>;
4020
4093
  getPendingMessages(threadId: string, scope?: QueueScope): Promise<PendingMessage[]>;
4021
4094
  getProcessingMessages(threadId: string, scope?: QueueScope): Promise<PendingMessage[]>;
4095
+ claimPendingMessages(threadId: string, scope: QueueScope | undefined, options: ClaimMessagesOptions): Promise<PendingMessage[]>;
4096
+ reclaimExpiredProcessing(threadId: string, scope?: QueueScope): Promise<number>;
4022
4097
  getQueueSize(threadId: string, scope?: QueueScope): Promise<number>;
4023
4098
  getThreadsWithPendingMessages(): Promise<ThreadInfo[]>;
4024
4099
  removeMessage(messageId: string, scope?: QueueScope): Promise<boolean>;
@@ -4628,6 +4703,79 @@ declare class InMemoryUserPushSubscriptionStore implements UserPushSubscriptionS
4628
4703
  delete(tenantId: string, userId: string, endpoint: string): Promise<boolean>;
4629
4704
  }
4630
4705
 
4706
+ /**
4707
+ * In-process {@link LeaseStore} used for single-process runs and tests.
4708
+ *
4709
+ * @remarks Real cross-replica exclusion requires the PostgreSQL implementation;
4710
+ * this store only serializes within one Node process.
4711
+ */
4712
+ declare class InMemoryLeaseStore implements LeaseStore {
4713
+ private readonly leases;
4714
+ private readonly now;
4715
+ /**
4716
+ * @param now Injectable clock in epoch milliseconds (tests use a fake clock).
4717
+ */
4718
+ constructor(now?: () => number);
4719
+ /** Atomically acquires a free/expired key (or the caller's own key). */
4720
+ tryAcquire(key: string, holder: string, ttlMs: number): Promise<boolean>;
4721
+ /** Extends a lease only while `holder` still owns it. */
4722
+ renew(key: string, holder: string, ttlMs: number): Promise<boolean>;
4723
+ /** Deletes a lease only when `holder` owns it. */
4724
+ release(key: string, holder: string): Promise<boolean>;
4725
+ /** Returns the live lease, pruning an expired one. */
4726
+ get(key: string): Promise<LeaseRecord | null>;
4727
+ }
4728
+
4729
+ /**
4730
+ * In-process {@link OutboxStore} used for single-process runs and tests.
4731
+ *
4732
+ * @remarks Real cross-replica fan-out requires the PostgreSQL implementation;
4733
+ * this store only preserves a monotonic log within one Node process. Ids are
4734
+ * assigned from an in-memory counter and serialized as decimal strings to match
4735
+ * the transport-neutral contract.
4736
+ */
4737
+ declare class InMemoryOutboxStore implements OutboxStore {
4738
+ private readonly events;
4739
+ private counter;
4740
+ private readonly now;
4741
+ /**
4742
+ * Creates an in-memory outbox store.
4743
+ *
4744
+ * @param now Optional clock override (defaults to the system clock); it stamps
4745
+ * `createdAt` and is used to evaluate age-based retention.
4746
+ */
4747
+ constructor(now?: () => Date);
4748
+ /**
4749
+ * Appends one event, assigning the next monotonic id.
4750
+ * @param input Topic, JSON-safe payload, and authoring replica id.
4751
+ * @returns A defensive copy of the stored event.
4752
+ */
4753
+ append(input: {
4754
+ topic: string;
4755
+ payload: unknown;
4756
+ originReplicaId: string;
4757
+ }): Promise<OutboxEvent>;
4758
+ /**
4759
+ * Lists events strictly newer than `cursor`, ascending, bounded by `limit`.
4760
+ * @param cursor Last-seen id, or `null` to read from the start.
4761
+ * @param limit Maximum number of events to return.
4762
+ * @returns Defensive copies of the matching events.
4763
+ */
4764
+ listAfter(cursor: string | null, limit: number): Promise<OutboxEvent[]>;
4765
+ /**
4766
+ * Returns the newest event id.
4767
+ * @returns The last id, or `null` when the log is empty.
4768
+ */
4769
+ latestId(): Promise<string | null>;
4770
+ /**
4771
+ * Deletes events older than `olderThanMs`, evaluated against this store's clock.
4772
+ *
4773
+ * @param olderThanMs Age threshold in milliseconds.
4774
+ * @returns The number of events removed.
4775
+ */
4776
+ pruneOlderThan(olderThanMs: number): Promise<number>;
4777
+ }
4778
+
4631
4779
  /**
4632
4780
  * Embeddings Lattice Interface
4633
4781
  * Defines the structure of an embeddings lattice entry
@@ -6569,6 +6717,13 @@ declare class DaytonaInstance implements SandboxInstance {
6569
6717
  readonly shell: SandboxShellService;
6570
6718
  }
6571
6719
 
6720
+ /**
6721
+ * Environment variables that must never reach sandbox-executed code.
6722
+ *
6723
+ * A denylist MVP for the local provider (which host-executes). A future
6724
+ * follow-up should flip this to a default-deny allowlist of benign vars.
6725
+ */
6726
+ declare const PLATFORM_SECRET_ENV_VARS: readonly string[];
6572
6727
  /**
6573
6728
  * Sandbox instance backed by the host filesystem.
6574
6729
  *
@@ -6775,6 +6930,81 @@ interface SharePayload {
6775
6930
  */
6776
6931
  declare function createSharePayload(tenantId: string, workspaceId: string, projectId: string, userId: string, request: CreateShareRequest): SharePayload;
6777
6932
 
6933
+ /**
6934
+ * Sandbox open-credential seam.
6935
+ *
6936
+ * A process-global provider (registered by the gateway composition root) resolves
6937
+ * a short-lived Open bearer for a running sandbox so sandbox code can call the
6938
+ * Open MCP endpoint. Core never mints tokens — it only transports a provider's
6939
+ * result into single-process env.
6940
+ */
6941
+ /** Identity of the sandbox whose code will consume the credential. */
6942
+ interface SandboxOpenCredentialContext {
6943
+ tenantId: string;
6944
+ workspaceId?: string;
6945
+ projectId?: string;
6946
+ /** Resolved sandbox name; determines the token's `self` binding. */
6947
+ sandboxName: string;
6948
+ /** Caller Assistant id (agent runs); absent for plugin-handler callers. */
6949
+ assistantId?: string;
6950
+ /** Caller thread id (agent runs). */
6951
+ threadId?: string;
6952
+ /** Current orchestration depth; nested mints pass depth+1. */
6953
+ depth?: number;
6954
+ }
6955
+ /** A resolved Open bearer plus the gateway base URL to call. */
6956
+ interface SandboxOpenCredential {
6957
+ gatewayUrl: string;
6958
+ token: string;
6959
+ }
6960
+ /** Resolves a credential for a sandbox, or `undefined` to inject nothing. */
6961
+ type SandboxOpenCredentialProvider = (context: SandboxOpenCredentialContext) => Promise<SandboxOpenCredential | undefined>;
6962
+ /** Env var name carrying the platform gateway URL into sandbox code. */
6963
+ declare const SANDBOX_OPEN_GATEWAY_URL_ENV = "API_GATEWAY_URL";
6964
+ /** Env var name carrying the short-lived Open bearer into sandbox code. */
6965
+ declare const SANDBOX_OPEN_TOKEN_ENV = "OPEN_API_TOKEN";
6966
+ /** Options for {@link registerSandboxOpenCredentialProvider}. */
6967
+ interface SandboxOpenCredentialProviderOptions {
6968
+ /** Invoked (best-effort) when the provider throws; use for structured warnings. */
6969
+ onError?: (error: unknown) => void;
6970
+ }
6971
+ /**
6972
+ * Register (or replace) the process-global sandbox open-credential provider.
6973
+ *
6974
+ * @param next - Provider implementation supplied by the composition root
6975
+ * @param options - Optional error hook for structured warnings
6976
+ * @returns An unregister function that clears the registration when it is still current
6977
+ *
6978
+ * @remarks
6979
+ * Singleton, last-write-wins. A stale unregister (from a superseded registration)
6980
+ * is a no-op, so hot-path re-registration cannot be disarmed by an old handle.
6981
+ *
6982
+ * @example
6983
+ * ```ts
6984
+ * const unregister = registerSandboxOpenCredentialProvider(
6985
+ * async (ctx) => ({ gatewayUrl: process.env.PUBLIC_GATEWAY_URL!, token: mint(ctx) }),
6986
+ * { onError: (err) => logger.warn({ err }, "sandbox credential failed") },
6987
+ * );
6988
+ * ```
6989
+ */
6990
+ declare function registerSandboxOpenCredentialProvider(next: SandboxOpenCredentialProvider, options?: SandboxOpenCredentialProviderOptions): () => void;
6991
+ /**
6992
+ * Resolve the credential for a sandbox.
6993
+ *
6994
+ * @param context - Sandbox identity and resolved sandbox name
6995
+ * @returns The credential, or `undefined` when no provider is registered or it throws
6996
+ */
6997
+ declare function getSandboxOpenCredential(context: SandboxOpenCredentialContext): Promise<SandboxOpenCredential | undefined>;
6998
+ /**
6999
+ * Build the shell `export … && export …` prefix for a credential.
7000
+ *
7001
+ * @param credential - Resolved gateway URL and bearer
7002
+ * @returns A single-quote-escaped `export` chain safe to prepend to a command
7003
+ */
7004
+ declare function buildSandboxOpenEnv(credential: SandboxOpenCredential): string;
7005
+ /** @internal */
7006
+ declare function clearSandboxOpenCredentialProviderForTests(): void;
7007
+
6778
7008
  /**
6779
7009
  * Channel connection lifecycle.
6780
7010
  *
@@ -7587,7 +7817,7 @@ interface TeammateSpec {
7587
7817
  /** Model override (defaults to team-level model) */
7588
7818
  model?: LanguageModelLike | string;
7589
7819
  /** Tools this teammate has access to (in addition to team tools) */
7590
- tools?: StructuredTool[];
7820
+ tools?: StructuredTool$1[];
7591
7821
  /** Custom system prompt for this teammate */
7592
7822
  systemPrompt?: string;
7593
7823
  /** Additional middleware for this teammate */
@@ -7606,7 +7836,7 @@ interface TeamConfig {
7606
7836
  /** Custom system prompt for the team lead */
7607
7837
  systemPrompt?: string;
7608
7838
  /** Tools available to the team lead */
7609
- tools?: StructuredTool[];
7839
+ tools?: StructuredTool$1[];
7610
7840
  /** Checkpointer for persisting agent state between runs */
7611
7841
  checkpointer?: BaseCheckpointSaver | boolean;
7612
7842
  /** Pluggable task list store (default: InMemoryTaskListStore) */
@@ -7806,7 +8036,7 @@ interface TeammateToolsOptions {
7806
8036
  * - Task lifecycle: claim_task, complete_task, fail_task
7807
8037
  * - Communication: send_message, read_messages
7808
8038
  */
7809
- declare function createTeammateTools(options: TeammateToolsOptions): StructuredTool[];
8039
+ declare function createTeammateTools(options: TeammateToolsOptions): StructuredTool$1[];
7810
8040
 
7811
8041
  /**
7812
8042
  * Agent Graph Builder 接口
@@ -8671,6 +8901,9 @@ type TaskLifecycleListener = (event: TaskLifecycleNotification) => void | Promis
8671
8901
  declare class TaskLifecycleNotifier {
8672
8902
  private readonly listeners;
8673
8903
  private readonly tails;
8904
+ private outbox;
8905
+ /** Installs (or clears) the durable outbox used to fan notifications to other replicas. */
8906
+ setOutbox(outbox: OutboxStore | undefined): void;
8674
8907
  /**
8675
8908
  * Registers an async lifecycle listener.
8676
8909
  *
@@ -8686,6 +8919,8 @@ declare class TaskLifecycleNotifier {
8686
8919
  * @throws Error when the event is malformed or one or more listeners reject.
8687
8920
  */
8688
8921
  publish(event: TaskLifecycleNotification): Promise<void>;
8922
+ /** Delivers one outbox payload to local listeners without re-appending (poller path). */
8923
+ deliverFromOutbox(event: unknown): Promise<void>;
8689
8924
  private deliver;
8690
8925
  }
8691
8926
  /** Process-global notifier used by every lifecycle service unless explicitly injected. */
@@ -8725,6 +8960,9 @@ declare class ProjectTaskAdmissionNotifier {
8725
8960
  private readonly listeners;
8726
8961
  private readonly tails;
8727
8962
  private readonly listenerTimeoutMs;
8963
+ private outbox;
8964
+ /** Installs (or clears) the durable outbox used to fan notifications to other replicas. */
8965
+ setOutbox(outbox: OutboxStore | undefined): void;
8728
8966
  /**
8729
8967
  * Creates a bounded Project task admission notifier.
8730
8968
  *
@@ -8745,12 +8983,68 @@ declare class ProjectTaskAdmissionNotifier {
8745
8983
  * @returns A promise settled after every snapshotted listener settles.
8746
8984
  */
8747
8985
  publish(event: ProjectTaskAdmissionNotification): Promise<void>;
8986
+ /** Delivers one outbox payload to local listeners without re-appending (poller path). */
8987
+ deliverFromOutbox(event: unknown): Promise<void>;
8748
8988
  private deliver;
8749
8989
  private deliverTo;
8750
8990
  }
8751
8991
  /** Process-global Project task admission notifier used by the managed dispatch path. */
8752
8992
  declare const projectTaskAdmissionNotifier: ProjectTaskAdmissionNotifier;
8753
8993
 
8994
+ /** Dependencies for {@link OutboxPoller}. */
8995
+ interface OutboxPollerDeps {
8996
+ /** Durable outbox log. */
8997
+ store: OutboxStore;
8998
+ /** This replica's id; rows it authored are skipped (already delivered locally). */
8999
+ owner: string;
9000
+ /** Handlers per topic that deliver a foreign payload to local listeners. */
9001
+ handlers: Record<string, (payload: unknown) => Promise<void>>;
9002
+ /** Poll interval in ms (default 1000). */
9003
+ intervalMs?: number;
9004
+ /** Max rows per query (default 100). */
9005
+ batchSize?: number;
9006
+ /** Per-handler delivery timeout in ms (default 5000); a hung listener cannot stall the poller. */
9007
+ handlerTimeoutMs?: number;
9008
+ /** Optional structured logger for recoverable delivery/poll failures. */
9009
+ log?: {
9010
+ warn(message: string, context: Record<string, unknown>): void;
9011
+ };
9012
+ }
9013
+ /**
9014
+ * Polls a durable outbox and delivers FOREIGN events to local handlers.
9015
+ *
9016
+ * @remarks
9017
+ * - The cursor starts at the current `latestId()` (no history replay); events
9018
+ * missed during downtime are covered by existing startup repair.
9019
+ * - Rows authored by this replica (`originReplicaId === owner`) are skipped
9020
+ * because `publish` already delivered them locally.
9021
+ * - A handler failure is logged and skipped (the cursor still advances), so one
9022
+ * bad event cannot stall the log.
9023
+ */
9024
+ declare class OutboxPoller {
9025
+ private readonly deps;
9026
+ private cursor;
9027
+ private timer;
9028
+ private polling;
9029
+ /**
9030
+ * Creates a poller bound to one durable outbox.
9031
+ *
9032
+ * @param deps Store, owner replica id, topic handlers, and optional tuning.
9033
+ */
9034
+ constructor(deps: OutboxPollerDeps);
9035
+ /** Captures the starting cursor and begins polling. */
9036
+ start(): Promise<void>;
9037
+ /** Stops polling. */
9038
+ stop(): void;
9039
+ /** Runs one drain pass (exported for tests). */
9040
+ pollOnce(): Promise<void>;
9041
+ /**
9042
+ * Runs one handler bounded by `handlerTimeoutMs` so a hung listener cannot
9043
+ * stall cross-replica delivery for this replica.
9044
+ */
9045
+ private deliverWithTimeout;
9046
+ }
9047
+
8754
9048
  /** Exact Tenant and Project scope for collaboration mutations. */
8755
9049
  interface ProjectMutationScope {
8756
9050
  tenantId: string;
@@ -8763,6 +9057,14 @@ interface ProjectMutationScope {
8763
9057
  * When an operation needs both a Project task machine mutex and this mutex, it
8764
9058
  * must acquire the machine mutex first. Project-only membership, roster, human,
8765
9059
  * and ordinary Task mutations acquire only this mutex.
9060
+ *
9061
+ * A coordination lease store may be installed process-wide
9062
+ * ({@link configureCoordinationLeaseStore}). When present, each critical section
9063
+ * additionally holds a bounded distributed lease (`project-mutation:<tenant>:<project>`)
9064
+ * so mutations on the same Tenant and Project serialize across replicas, not just
9065
+ * within this process. The local FIFO lock is always retained; the lease only adds
9066
+ * cross-replica exclusion. When no store is configured (single process, tests),
9067
+ * behavior is unchanged.
8766
9068
  */
8767
9069
  declare class ProjectMutationMutex {
8768
9070
  private readonly queues;
@@ -8793,6 +9095,23 @@ interface ResumeTaskResult {
8793
9095
  status: ThreadStatus;
8794
9096
  /** Whether processing rows are settled and pending queue work may continue. */
8795
9097
  settled: boolean;
9098
+ /**
9099
+ * True only when the thread-run lease was held by another replica, so this
9100
+ * call did nothing and left the thread entirely to its owner.
9101
+ *
9102
+ * This disambiguates the two situations that report `settled: false`:
9103
+ * - **Lease contention** — a peer owns the run; recovery must be deferred and
9104
+ * the caller must not settle, arm watchdogs, or classify the thread.
9105
+ * - **Genuine interruption / busy** — this replica observed the thread and
9106
+ * reports an authoritative status (`INTERRUPTED`/`BUSY`) that the caller
9107
+ * must still act on.
9108
+ *
9109
+ * Callers that defer recovery on contention MUST branch on this flag, not on
9110
+ * `settled`, and callers that continue processing on `INTERRUPTED` must ignore
9111
+ * it. It is never set on the `INTERRUPTED`, `BUSY`, `IDLE`, or `ERROR`
9112
+ * returns from {@link Agent.resumeTask}.
9113
+ */
9114
+ leaseContended?: boolean;
8796
9115
  }
8797
9116
  /**
8798
9117
  * Snapshot of a thread's current state including queue and status.
@@ -9053,6 +9372,14 @@ declare class Agent {
9053
9372
  private queueProcessorGeneration;
9054
9373
  private queueWakeRequested;
9055
9374
  private recoveryBlockedKey?;
9375
+ /**
9376
+ * Thread-run ownership lease held while this replica is actively processing
9377
+ * the thread. Acquired non-blockingly in {@link startQueueProcessor}; released
9378
+ * exactly once when the processor definitively stops.
9379
+ */
9380
+ private threadRunLease;
9381
+ private threadRunLeaseRetryAttempt;
9382
+ private threadRunLeaseRetryTimer;
9056
9383
  asyncTasks: AsyncTaskRecord[];
9057
9384
  /**
9058
9385
  * Constructs an Agent instance.
@@ -9154,6 +9481,19 @@ declare class Agent {
9154
9481
  private resumeGraphFromCheckpoint;
9155
9482
  private waitingForQueueEnd;
9156
9483
  private getQueueStore;
9484
+ /**
9485
+ * Resolves the shared lease store used to serialize thread runs across
9486
+ * Gateway replicas. Returns `undefined` when no lease store is registered so
9487
+ * single-process deployments keep running unconditionally.
9488
+ */
9489
+ private getLeaseStore;
9490
+ /**
9491
+ * Releases this replica's thread-run ownership lease, if held.
9492
+ *
9493
+ * @remarks Safe to call from any definitive-stop path; a second call is a
9494
+ * no-op. The handle's unique holder makes a stale release harmless.
9495
+ */
9496
+ private releaseThreadRunLease;
9157
9497
  private getDefaultQueueConfig;
9158
9498
  /**
9159
9499
  * Override the thread's queue processing mode.
@@ -9216,6 +9556,21 @@ declare class Agent {
9216
9556
  private finishQueueProcessor;
9217
9557
  private scheduleQueueProcessorRetry;
9218
9558
  private cancelQueueProcessorRetry;
9559
+ /**
9560
+ * Bounded re-attempt after losing the thread-run lease to a peer. Covers the
9561
+ * narrow window where the peer releases the lease without having observed a
9562
+ * just-enqueued message. Bounded so a genuinely long-held thread does not make
9563
+ * this replica poll forever — the owning replica's loop drains new messages.
9564
+ */
9565
+ private scheduleThreadRunLeaseRetry;
9566
+ /**
9567
+ * Clears any pending thread-run lease retry and resets its backoff budget.
9568
+ *
9569
+ * @remarks Called on lease acquisition and on every definitive processor
9570
+ * stop so the next enqueue starts from the base delay. Never called on
9571
+ * continue/re-arm paths, which must preserve the bounded budget.
9572
+ */
9573
+ private cancelThreadRunLeaseRetry;
9219
9574
  private runQueueProcessor;
9220
9575
  /**
9221
9576
  * Remove pending message
@@ -9276,6 +9631,8 @@ declare class Agent {
9276
9631
  * queue work must not start; `IDLE` and `ERROR` mean those rows were settled.
9277
9632
  */
9278
9633
  resumeTask(): Promise<ResumeTaskResult>;
9634
+ /** Recovery body of {@link resumeTask}, executed while thread ownership is settled. */
9635
+ private resumeTaskLocked;
9279
9636
  /**
9280
9637
  * Fully abort all activity on this thread.
9281
9638
  *
@@ -9487,12 +9844,39 @@ declare class AgentInstanceManager {
9487
9844
  private agents;
9488
9845
  static getInstance(): AgentInstanceManager;
9489
9846
  private constructor();
9847
+ /**
9848
+ * A thread's identity is `(tenant_id, assistant_id, thread_id)`.
9849
+ *
9850
+ * Workspace/project are execution scope chosen when the instance is created,
9851
+ * not part of identity: including them let the same thread exist as several
9852
+ * Agents when callers defaulted optional workspace/project headers
9853
+ * differently (e.g. `createRun` passing `undefined` while `abort` defaulted
9854
+ * to `"default"`), so control-plane calls could address a different instance
9855
+ * than the one running. `undefined`/`null` normalize to `""`; ids are assumed
9856
+ * not to contain `:` (UUID-shaped in practice).
9857
+ */
9490
9858
  private getKey;
9491
9859
  /**
9492
9860
  * Get or create Agent instance for a thread
9493
9861
  * Ensures only one instance per thread exists
9494
9862
  */
9495
9863
  getAgent(params: AgentThreadInterface): Agent;
9864
+ /**
9865
+ * Get the managed Agent for a thread WITHOUT creating or registering one.
9866
+ *
9867
+ * Read-only control-plane callers (state, memory, inbox) must not be the first
9868
+ * to establish a thread's execution scope: since identity is
9869
+ * `(tenant_id, assistant_id, thread_id)`, whichever caller reaches
9870
+ * {@link getAgent} first fixes the instance's workspace/project for its whole
9871
+ * lifetime, and a later trusted dispatch on that thread would then fail
9872
+ * trusted-scope validation. This returns the existing managed instance when
9873
+ * present, otherwise a transient unregistered Agent that is sufficient for
9874
+ * state reads and disappears with the request.
9875
+ *
9876
+ * @param params - Thread identity; scope is only used for the transient Agent.
9877
+ * @returns The managed instance if any, else an unregistered read-only Agent.
9878
+ */
9879
+ getAgentForRead(params: AgentThreadInterface): Agent;
9496
9880
  /**
9497
9881
  * Check if an agent instance exists for the thread
9498
9882
  */
@@ -9509,20 +9893,6 @@ declare class AgentInstanceManager {
9509
9893
  * Clear all agent instances (use with caution)
9510
9894
  */
9511
9895
  clearAll(): void;
9512
- /**
9513
- * Restore agent instances for threads with pending messages after server restart
9514
- * Queries the message queue store for threads with pending/processing messages
9515
- * and recreates agent instances to resume processing
9516
- */
9517
- restore(): Promise<{
9518
- restored: number;
9519
- errors: number;
9520
- }>;
9521
- /**
9522
- * Restore a single thread
9523
- * Delegates actual recovery logic to Agent.resumeTask()
9524
- */
9525
- private restoreThread;
9526
9896
  }
9527
9897
  declare const agentInstanceManager: AgentInstanceManager;
9528
9898
 
@@ -9654,6 +10024,8 @@ interface ResumeInterruptionInput {
9654
10024
  actor: string;
9655
10025
  /** Optional thread to retain in the interruption audit context. */
9656
10026
  threadId?: string;
10027
+ /** Optional run identity to retain; omitted for a first-attempt continuation. */
10028
+ runId?: string;
9657
10029
  }
9658
10030
  /** Input for atomically starting or retrying an agent task. */
9659
10031
  interface StartTaskInput {
@@ -9661,6 +10033,12 @@ interface StartTaskInput {
9661
10033
  taskId: string;
9662
10034
  actor: string;
9663
10035
  threadId?: string;
10036
+ /** Re-attempt identity persisted as `context.run_id`; omitted for a first start. */
10037
+ runId?: string;
10038
+ /** Caller thread that dispatched this run (ordinary dispatch only). */
10039
+ callerThreadId?: string;
10040
+ /** Caller assistant that dispatched this run (ordinary dispatch only). */
10041
+ callerAssistantId?: string;
9664
10042
  }
9665
10043
  /** Input for atomically failing an active agent task. */
9666
10044
  interface FailTaskInput {
@@ -9897,6 +10275,18 @@ declare class TaskLifecycleService {
9897
10275
  private writeResumeEvent;
9898
10276
  private transitionAgentTask;
9899
10277
  private statusEventKey;
10278
+ /**
10279
+ * Writes a lifecycle work-item event, retrying transient store failures.
10280
+ *
10281
+ * @param request Event request passed through to the work-item store.
10282
+ * @returns The persisted or pre-existing work item.
10283
+ * @remarks The write is idempotent by `eventKey`
10284
+ * (`createIfAbsentByEventKey`), so retrying after a transient failure (pool
10285
+ * exhaustion, shutdown, statement timeout, disk IO) is safe. The status CAS has
10286
+ * already committed by this point, and the event key embeds `updatedAt`, so a
10287
+ * lost event cannot be reconstructed later — hence the bounded retry.
10288
+ */
10289
+ private writeWorkItemWithRetry;
9900
10290
  private writeStatusEvent;
9901
10291
  /**
9902
10292
  * Publishes one committed transition for any scope-bearing task.
@@ -9969,6 +10359,15 @@ interface TaskExecutionServiceDeps {
9969
10359
  * task's `context.thread_id`.
9970
10360
  */
9971
10361
  createThreadId?: () => string;
10362
+ /**
10363
+ * Optional run-id generator; defaults to `randomUUID`.
10364
+ *
10365
+ * @remarks A `runId` is allocated for a re-attempt (a failed retry, or an
10366
+ * interruption whose thread already produced a result) and appended to the
10367
+ * execution-result key as `execution-result:<threadId>:<runId>`, so several
10368
+ * attempts can share one worker thread without colliding.
10369
+ */
10370
+ createRunId?: () => string;
9972
10371
  }
9973
10372
  /** Identifies a persistent task, target Agent, caller, and runtime scope. */
9974
10373
  interface StartTaskExecutionInput {
@@ -9987,7 +10386,11 @@ interface StartTaskExecutionInput {
9987
10386
  callerThreadId?: string;
9988
10387
  /** Trusted Project caller membership forwarded to a managed authority, when known. */
9989
10388
  callerMembershipId?: string;
9990
- /** Trusted Project caller Assistant forwarded to a managed authority, when known. */
10389
+ /**
10390
+ * Caller Assistant: the ordinary dispatch link persisted into the task's
10391
+ * `context.caller_assistant_id` (used by orphan recovery), and, for trusted
10392
+ * Project tasks, the caller Assistant forwarded to a managed authority.
10393
+ */
9991
10394
  callerAssistantId?: string;
9992
10395
  }
9993
10396
  /** Successful isolated execution observation recorded for later reconciliation. */
@@ -10046,7 +10449,12 @@ type TaskExecutionResult = TaskExecutionSuccess | TaskExecutionManaged | TaskExe
10046
10449
  * const result = await service.start({ tenantId, taskId, agentId, actor });
10047
10450
  * ```
10048
10451
  *
10049
- * @remarks A returned observation is execution evidence only. This service never completes or fails the TaskItem.
10452
+ * @remarks A returned observation is execution evidence only. This service never completes a task
10453
+ * (completion stays with the worker's `manage_task`), but it owns the run's engine duties: it marks
10454
+ * the task live for the duration of the run and converges abnormal invocation outcomes to `failed`
10455
+ * (or `interrupted` on a graph interrupt). A successful run leaves the task's lifecycle untouched:
10456
+ * the caller observes the returned `executionResultId` and reconciles it (ADR-077), so a
10457
+ * middleware-less worker's task stays `in_progress` for the caller to complete.
10050
10458
  */
10051
10459
  declare function createTaskExecutionService(deps: TaskExecutionServiceDeps): {
10052
10460
  start: (input: StartTaskExecutionInput) => Promise<TaskExecutionResult>;
@@ -10076,6 +10484,8 @@ interface ImmediateDispatchPlan {
10076
10484
  actor: string;
10077
10485
  /** Caller thread provenance; not the run link (the executor links its own run thread). */
10078
10486
  callerThreadId?: string;
10487
+ /** Caller assistant that dispatched this run (ordinary dispatch only). */
10488
+ callerAssistantId?: string;
10079
10489
  /** In-scope parent task, when the task has one; otherwise `null`. */
10080
10490
  parent: TaskItem | null;
10081
10491
  /** In-scope, completed dependencies whose results seed the worker message. */
@@ -10163,6 +10573,19 @@ interface BeginRunInput {
10163
10573
  * Optional so callers that dispatch before a thread exists can omit it.
10164
10574
  */
10165
10575
  threadId?: string;
10576
+ /**
10577
+ * Re-attempt identity linked into the task as `context.run_id`.
10578
+ *
10579
+ * @remarks Allocated only for a re-attempt (a failed retry, or an
10580
+ * interruption whose run already produced a result) so several attempts can
10581
+ * share one worker thread without colliding on the execution-result key.
10582
+ * Omitted for a first attempt and for a genuine HITL resume.
10583
+ */
10584
+ runId?: string;
10585
+ /** Caller thread that dispatched this run (ordinary dispatch only). */
10586
+ callerThreadId?: string;
10587
+ /** Caller assistant that dispatched this run (ordinary dispatch only). */
10588
+ callerAssistantId?: string;
10166
10589
  }
10167
10590
  /**
10168
10591
  * Result of a dispatch that mutated (or confirmed) the run's starting state.
@@ -10425,29 +10848,47 @@ interface ReconcileStaleTaskRunsInput {
10425
10848
  /** Actor recorded on the convergence transition. */
10426
10849
  actor: string;
10427
10850
  /** Lifecycle used to converge an orphaned task. */
10428
- lifecycle: Pick<TaskLifecycleService, "interruptTask">;
10851
+ lifecycle: Pick<TaskLifecycleService, "failTask">;
10429
10852
  /** Registry override (tests); defaults to {@link taskRunRegistry}. */
10430
10853
  registry?: TaskRunRegistry;
10854
+ /**
10855
+ * Optional cross-replica liveness probe. When provided and it resolves true,
10856
+ * the task is treated as live and NOT converged (a peer replica owns it). A
10857
+ * rejection is also treated as live, so a probe error never converges a task.
10858
+ */
10859
+ isTaskLive?: (task: TaskItem) => Promise<boolean>;
10431
10860
  }
10432
10861
  /** Result of {@link reconcileStaleTaskRuns}. */
10433
10862
  interface ReconcileStaleTaskRunsResult {
10434
- /** Task ids that were converged to `interrupted`. */
10863
+ /** Task ids that were converged to `failed`. */
10435
10864
  converged: string[];
10865
+ /**
10866
+ * Post-convergence snapshots (`status: "failed"`) for each converged task.
10867
+ *
10868
+ * @remarks Recovery reads the caller link and the terminal outcome from these.
10869
+ */
10870
+ convergedTasks: TaskItem[];
10436
10871
  }
10437
10872
  /**
10438
- * Converges `in_progress` tasks that no live run holds to `interrupted`.
10873
+ * Converges `in_progress` tasks that no live run holds to `failed(no_executor)`.
10439
10874
  *
10440
- * @param input Candidate tasks, actor, lifecycle, and optional registry.
10875
+ * @param input Candidate tasks, actor, lifecycle, optional registry, and optional
10876
+ * cross-replica liveness probe.
10441
10877
  * @returns The ids that were converged.
10442
10878
  * @remarks
10443
10879
  * The caller owns scope enumeration (a store cannot list across tenants). A task
10444
- * is converged only when it is `in_progress` and absent from the registry, so a
10445
- * task a live run genuinely holds is never touched.
10880
+ * is converged only when it is `in_progress`, absent from the process-local
10881
+ * registry, and (when `isTaskLive` is supplied) not reported live by the host's
10882
+ * cross-replica probe. The probe lets a host consult a durable lease so a peer
10883
+ * replica's live run is never mistaken for an orphan. An orphaned run is a
10884
+ * mechanical failure, not a human-in-the-loop interruption, so it converges to
10885
+ * `failed`, never `interrupted`.
10446
10886
  *
10447
10887
  * @example
10448
10888
  * ```ts
10449
10889
  * const { converged } = await reconcileStaleTaskRuns({
10450
10890
  * tasks: scopeTasks, actor: "system:reconcile", lifecycle,
10891
+ * isTaskLive: async (task) => (await leaseStore.get(`task-run:${task.id}`)) !== null,
10451
10892
  * });
10452
10893
  * ```
10453
10894
  */
@@ -10461,7 +10902,7 @@ interface ReconcileTenantTaskRunsInput {
10461
10902
  /** Store used to enumerate the tenant's `in_progress` tasks. */
10462
10903
  taskStore: Pick<TaskStore, "list">;
10463
10904
  /** Lifecycle used to converge an orphaned task. */
10464
- lifecycle: Pick<TaskLifecycleService, "interruptTask">;
10905
+ lifecycle: Pick<TaskLifecycleService, "failTask">;
10465
10906
  /** Registry override (tests); defaults to {@link taskRunRegistry}. */
10466
10907
  registry?: TaskRunRegistry;
10467
10908
  /**
@@ -10472,22 +10913,33 @@ interface ReconcileTenantTaskRunsInput {
10472
10913
  * generic reconciler never competes with a domain reconciler.
10473
10914
  */
10474
10915
  include?: (task: TaskItem) => boolean;
10916
+ /**
10917
+ * Optional cross-replica liveness probe forwarded to
10918
+ * {@link reconcileStaleTaskRuns}. When provided and it resolves true, the
10919
+ * task is treated as live and NOT converged (a peer replica owns it). A
10920
+ * rejection is also treated as live, so a probe error never converges a task.
10921
+ */
10922
+ isTaskLive?: (task: TaskItem) => Promise<boolean>;
10475
10923
  }
10476
10924
  /**
10477
- * Reconciles a tenant's orphaned `in_progress` tasks.
10925
+ * Reconciles a tenant's orphaned `in_progress` tasks, converged to `failed`.
10478
10926
  *
10479
- * @param input Tenant, actor, store, lifecycle, optional registry and predicate.
10927
+ * @param input Tenant, actor, store, lifecycle, optional registry, predicate, and
10928
+ * cross-replica liveness probe.
10480
10929
  * @returns The ids that were converged.
10481
10930
  * @remarks
10482
10931
  * Enumerates `{ tenantId, status: "in_progress" }` and delegates to
10483
10932
  * {@link reconcileStaleTaskRuns}. The caller owns the `include` predicate; a
10484
- * host must exclude task families that have their own reconciliation.
10933
+ * host must exclude task families that have their own reconciliation. The
10934
+ * optional `isTaskLive` probe is forwarded unchanged so the host can consult a
10935
+ * cross-replica lease.
10485
10936
  *
10486
10937
  * @example
10487
10938
  * ```ts
10488
10939
  * await reconcileTenantTaskRuns({
10489
10940
  * tenantId, actor: "system:reconcile", taskStore, lifecycle,
10490
10941
  * include: (task) => !isProjectLifecycleTask(task),
10942
+ * isTaskLive: async (task) => (await leaseStore.get(`task-run:${task.id}`)) !== null,
10491
10943
  * });
10492
10944
  * ```
10493
10945
  */
@@ -10505,26 +10957,36 @@ interface ReconcileAllTenantTaskRunsInput {
10505
10957
  /** Store used to enumerate each tenant's `in_progress` tasks. */
10506
10958
  taskStore: Pick<TaskStore, "list">;
10507
10959
  /** Lifecycle used to converge an orphaned task. */
10508
- lifecycle: Pick<TaskLifecycleService, "interruptTask">;
10960
+ lifecycle: Pick<TaskLifecycleService, "failTask">;
10509
10961
  /** Registry override (tests); defaults to {@link taskRunRegistry}. */
10510
10962
  registry?: TaskRunRegistry;
10511
10963
  /** Host predicate selecting which candidates this reconciler owns. */
10512
10964
  include?: (task: TaskItem) => boolean;
10965
+ /**
10966
+ * Optional cross-replica liveness probe forwarded per tenant to
10967
+ * {@link reconcileTenantTaskRuns}. When provided and it resolves true, the
10968
+ * task is treated as live and NOT converged (a peer replica owns it). A
10969
+ * rejection is also treated as live, so a probe error never converges a task.
10970
+ */
10971
+ isTaskLive?: (task: TaskItem) => Promise<boolean>;
10513
10972
  }
10514
10973
  /**
10515
- * Reconciles orphaned `in_progress` tasks across all tenants.
10974
+ * Reconciles orphaned `in_progress` tasks across all tenants, converged to `failed`.
10516
10975
  *
10517
- * @param input Actor, tenant store, task store, lifecycle, optional registry and predicate.
10976
+ * @param input Actor, tenant store, task store, lifecycle, optional registry,
10977
+ * predicate, and cross-replica liveness probe.
10518
10978
  * @returns The ids that were converged across every tenant.
10519
10979
  * @remarks Enumerates tenants via `listTenants()` and delegates per tenant to
10520
- * {@link reconcileTenantTaskRuns}. Intended for a host startup/interval job;
10521
- * callers own when it runs.
10980
+ * {@link reconcileTenantTaskRuns}. The optional `isTaskLive` probe is forwarded
10981
+ * to every tenant so the host can consult a cross-replica lease. Intended for a
10982
+ * host startup/interval job; callers own when it runs.
10522
10983
  *
10523
10984
  * @example
10524
10985
  * ```ts
10525
10986
  * await reconcileAllTenantTaskRuns({
10526
10987
  * actor: "system:reconcile", tenantStore, taskStore, lifecycle,
10527
10988
  * include: (task) => !isProjectLifecycleTask(task),
10989
+ * isTaskLive: async (task) => (await leaseStore.get(`task-run:${task.id}`)) !== null,
10528
10990
  * });
10529
10991
  * ```
10530
10992
  */
@@ -10632,6 +11094,286 @@ declare class ExecutionAuthorityRegistry {
10632
11094
  /** Process-global execution authority registry used by the immediate executor. */
10633
11095
  declare const executionAuthorityRegistry: ExecutionAuthorityRegistry;
10634
11096
 
11097
+ /**
11098
+ * Returns the stable identity of this Gateway process.
11099
+ *
11100
+ * Resolution order: `AXIOM_REPLICA_ID` (trimmed, when non-empty), else
11101
+ * `<hostname>:<pid>`. Cached for the process lifetime so leases, run ownership,
11102
+ * and logs attribute consistently.
11103
+ *
11104
+ * @returns The replica id used by distributed leases and run ownership.
11105
+ *
11106
+ * @example
11107
+ * ```ts
11108
+ * import { getReplicaId } from "@axiom-lattice/core";
11109
+ * const owner = getReplicaId();
11110
+ * ```
11111
+ *
11112
+ * @remarks Multi-replica deployments SHOULD set `AXIOM_REPLICA_ID` to a stable
11113
+ * unique value (e.g. the pod name) so a restarted replica is distinguishable
11114
+ * from a concurrently running one; otherwise a restart can appear to still own
11115
+ * a lease it held before its pid/hostname changed.
11116
+ */
11117
+ declare function getReplicaId(): string;
11118
+ /**
11119
+ * Test seam: clears the cached id so a changed env takes effect.
11120
+ *
11121
+ * @remarks Not part of the public runtime contract; call only from tests.
11122
+ */
11123
+ declare function resetReplicaIdForTests(): void;
11124
+
11125
+ /**
11126
+ * Installs the process-wide coordination lease store.
11127
+ *
11128
+ * @param store A shared (PostgreSQL) lease store, or `undefined` to clear it.
11129
+ * @remarks Called once at the composition root (gateway startup) after stores
11130
+ * are configured. When unset, coordination mutexes keep their process-local
11131
+ * behavior only (single-process / tests).
11132
+ */
11133
+ declare function configureCoordinationLeaseStore(store: LeaseStore | undefined): void;
11134
+ /** Returns the configured coordination lease store, if any. */
11135
+ declare function getCoordinationLeaseStore(): LeaseStore | undefined;
11136
+
11137
+ /** Raised when a lease could not be acquired within the bounded wait. */
11138
+ declare class LeaseAcquisitionTimeoutError extends Error {
11139
+ readonly key: string;
11140
+ readonly holder: string;
11141
+ readonly timeoutMs: number;
11142
+ /** Stable machine-readable code. */
11143
+ readonly code: "LEASE_ACQUISITION_TIMEOUT";
11144
+ /**
11145
+ * @param key Lease key that could not be acquired.
11146
+ * @param holder Unique holder that attempted acquisition.
11147
+ * @param timeoutMs How long the caller waited before giving up.
11148
+ */
11149
+ constructor(key: string, holder: string, timeoutMs: number);
11150
+ }
11151
+ /** Tuning for {@link withLease}. */
11152
+ interface WithLeaseOptions {
11153
+ /** Lease time-to-live; must exceed the longest expected critical section. */
11154
+ ttlMs?: number;
11155
+ /** Bounded wait for acquisition before throwing. */
11156
+ acquireTimeoutMs?: number;
11157
+ /** Delay between acquisition attempts. */
11158
+ retryDelayMs?: number;
11159
+ /** Heartbeat interval; defaults to `ttlMs / 3` (min 1s). */
11160
+ heartbeatMs?: number;
11161
+ }
11162
+ /**
11163
+ * Runs `fn` under a distributed lease, heartbeating for the duration.
11164
+ *
11165
+ * @param store Lease store (PostgreSQL in multi-replica deployments).
11166
+ * @param key Lease key, e.g. `project-mutation:<tenant>:<project>`.
11167
+ * @param ownerLabel Stable owner label (e.g. `getReplicaId()`); a unique suffix
11168
+ * is appended per invocation so concurrent sections on the same replica still
11169
+ * serialize.
11170
+ * @param fn Critical section to run while holding the lease.
11171
+ * @param options TTL, acquisition timeout, retry, and heartbeat tuning.
11172
+ * @returns Whatever `fn` returns.
11173
+ *
11174
+ * @remarks
11175
+ * - Acquires with a per-invocation unique holder (`<ownerLabel>#<uuid>`), so two
11176
+ * concurrent calls on the same key serialize regardless of backend — both
11177
+ * within one replica and across replicas.
11178
+ * - Retries with a fixed delay until `acquireTimeoutMs`, then throws
11179
+ * {@link LeaseAcquisitionTimeoutError}.
11180
+ * - A heartbeat renews the lease while `fn` runs; a lost lease is not force-killed
11181
+ * (the work should be CAS/idempotent), and the heartbeat stops on completion.
11182
+ * - The lease is released in `finally`, including when `fn` throws.
11183
+ *
11184
+ * @example
11185
+ * ```ts
11186
+ * await withLease(leaseStore, `task-run:${taskId}`, getReplicaId(), () => run());
11187
+ * ```
11188
+ */
11189
+ declare function withLease<T>(store: LeaseStore, key: string, ownerLabel: string, fn: () => Promise<T>, options?: WithLeaseOptions): Promise<T>;
11190
+
11191
+ /** Builds the canonical thread-run lease key. */
11192
+ declare function threadRunLeaseKey(tenantId: string, assistantId: string, threadId: string): string;
11193
+ /** A held thread-run lease; call `release()` when the processor stops. */
11194
+ interface ThreadRunLeaseHandle {
11195
+ /** True once the lease was lost to another holder (a heartbeat renew failed). */
11196
+ readonly lost: boolean;
11197
+ /** Releases the lease (no-op if already lost/taken over). */
11198
+ release(): Promise<void>;
11199
+ }
11200
+ /** Input for {@link tryAcquireThreadRun}. */
11201
+ interface TryAcquireThreadRunInput {
11202
+ /** Shared lease store (PostgreSQL in multi-replica deployments). */
11203
+ store: LeaseStore;
11204
+ tenantId: string;
11205
+ assistantId: string;
11206
+ threadId: string;
11207
+ /** Owner label, e.g. `getReplicaId()`. */
11208
+ owner: string;
11209
+ /** Lease TTL in milliseconds; must exceed one processing cycle's gaps. */
11210
+ ttlMs: number;
11211
+ /** Heartbeat interval; defaults to `ttlMs / 3` (min 1s). */
11212
+ heartbeatMs?: number;
11213
+ /** Invoked once (best-effort) when the lease is lost to another holder. */
11214
+ onLost?: () => void;
11215
+ }
11216
+ /**
11217
+ * Non-blocking acquire of a thread's run ownership lease.
11218
+ *
11219
+ * @param input Store, thread identity, owner, and TTL.
11220
+ * @returns A handle to release the lease, or `null` when another replica holds it.
11221
+ *
11222
+ * @remarks
11223
+ * - The holder is unique per call (`<owner>#<uuid>`), so lease release can never
11224
+ * remove another holder's lease (a stale release is a no-op).
11225
+ * - A heartbeat renews while held; the caller MUST call `release()` when the
11226
+ * processor stops so another replica can take over without waiting for expiry.
11227
+ * Once released, an in-flight renew that resolves `false` cannot flip `lost`
11228
+ * or fire `onLost` (a clean release is not a loss).
11229
+ * - When a heartbeat renew returns `false`, ownership has moved to another
11230
+ * holder: `handle.lost` flips true and `onLost` fires exactly once so the
11231
+ * caller can self-abort. This is a bounded mitigation only — a holder that is
11232
+ * CPU-blocked and resumes before the next detection can still write; it does
11233
+ * not fence such a zombie.
11234
+ *
11235
+ * @example
11236
+ * ```ts
11237
+ * const lease = await tryAcquireThreadRun({ store, tenantId, assistantId, threadId, owner: getReplicaId(), ttlMs: 60_000 });
11238
+ * if (!lease) return; // another replica owns this thread
11239
+ * try { await process(); } finally { await lease.release(); }
11240
+ * ```
11241
+ */
11242
+ declare function tryAcquireThreadRun(input: TryAcquireThreadRunInput): Promise<ThreadRunLeaseHandle | null>;
11243
+ /** Input for {@link getThreadRunOwner}. */
11244
+ interface GetThreadRunOwnerInput {
11245
+ tenantId: string;
11246
+ assistantId: string;
11247
+ threadId: string;
11248
+ /** Test seam; defaults to the registered `default`/`lease` store. */
11249
+ store?: LeaseStore;
11250
+ }
11251
+ /**
11252
+ * Reads the replica that currently owns a thread's run, or `null` when the
11253
+ * thread is free (idle, completed, or the lease expired).
11254
+ *
11255
+ * @remarks
11256
+ * - The holder is `<owner>#<uuid>`; the returned value is the replica part.
11257
+ * - Best-effort: a missing store or read failure returns `null` (callers must
11258
+ * treat `null` as "cannot prove another owner", never as an error).
11259
+ */
11260
+ declare function getThreadRunOwner(input: GetThreadRunOwnerInput): Promise<string | null>;
11261
+
11262
+ /** Builds the canonical task-run lease key. */
11263
+ declare function taskRunLeaseKey(taskId: string): string;
11264
+ /** A held task-run lease; call `release()` when the processor stops. */
11265
+ interface TaskRunLeaseHandle {
11266
+ /** True once the lease was lost to another holder (a heartbeat renew failed). */
11267
+ readonly lost: boolean;
11268
+ /** Releases the lease (no-op if already lost/taken over). */
11269
+ release(): Promise<void>;
11270
+ }
11271
+ /** Input for {@link tryAcquireTaskRun}. */
11272
+ interface TryAcquireTaskRunInput {
11273
+ /** Shared lease store (PostgreSQL in multi-replica deployments). */
11274
+ store: LeaseStore;
11275
+ taskId: string;
11276
+ /** Owner label, e.g. `getReplicaId()`. */
11277
+ owner: string;
11278
+ /** Lease TTL in milliseconds; must exceed one processing cycle's gaps. */
11279
+ ttlMs: number;
11280
+ /** Heartbeat interval; defaults to `ttlMs / 3` (min 1s). */
11281
+ heartbeatMs?: number;
11282
+ /** Invoked once (best-effort) when the lease is lost to another holder. */
11283
+ onLost?: () => void;
11284
+ }
11285
+ /**
11286
+ * Non-blocking acquire of a task's run ownership lease.
11287
+ *
11288
+ * @param input Store, task identity, owner, and TTL.
11289
+ * @returns A handle to release the lease, or `null` when another replica holds it.
11290
+ *
11291
+ * @remarks
11292
+ * - The holder is unique per call (`<owner>#<uuid>`), so lease release can never
11293
+ * remove another holder's lease (a stale release is a no-op).
11294
+ * - A heartbeat renews while held; the caller MUST call `release()` when the
11295
+ * processor stops so another replica can take over without waiting for expiry.
11296
+ * Once released, an in-flight renew that resolves `false` cannot flip `lost`
11297
+ * or fire `onLost` (a clean release is not a loss).
11298
+ * - When a heartbeat renew returns `false`, ownership has moved to another
11299
+ * holder: `handle.lost` flips true and `onLost` fires exactly once so the
11300
+ * caller can self-abort. This is a bounded mitigation only — a holder that is
11301
+ * CPU-blocked and resumes before the next detection can still write; it does
11302
+ * not fence such a zombie.
11303
+ *
11304
+ * @example
11305
+ * ```ts
11306
+ * const lease = await tryAcquireTaskRun({ store, taskId, owner: getReplicaId(), ttlMs: 60_000 });
11307
+ * if (!lease) return; // another replica owns this task
11308
+ * try { await process(); } finally { await lease.release(); }
11309
+ * ```
11310
+ */
11311
+ declare function tryAcquireTaskRun(input: TryAcquireTaskRunInput): Promise<TaskRunLeaseHandle | null>;
11312
+
11313
+ /** Options for {@link runAsLeader}. */
11314
+ interface RunAsLeaderOptions {
11315
+ /** Owner label; defaults to {@link getReplicaId}. */
11316
+ owner?: string;
11317
+ /** Lease TTL in milliseconds (default 60_000). */
11318
+ ttlMs?: number;
11319
+ /**
11320
+ * When true, the lease is NOT released after `fn` — it is held until it
11321
+ * expires, so a replica that boots later in the same window also skips.
11322
+ * When false (default) the lease is released immediately after `fn`.
11323
+ */
11324
+ hold?: boolean;
11325
+ }
11326
+ /** Outcome of {@link runAsLeader}. */
11327
+ interface RunAsLeaderResult<T> {
11328
+ /** Whether this caller won leadership and ran `fn`. */
11329
+ ran: boolean;
11330
+ /** The value returned by `fn`, when it ran. */
11331
+ result?: T;
11332
+ }
11333
+ /**
11334
+ * Runs `fn` on exactly one caller (non-blocking leader election).
11335
+ *
11336
+ * @param store Shared lease store (PostgreSQL in multi-replica deployments).
11337
+ * @param name Logical job name; leased as `leader:<name>`.
11338
+ * @param fn The one-shot critical work.
11339
+ * @param options Owner, TTL, and whether to hold the lease until expiry.
11340
+ * @returns `{ ran: true, result }` for the winner, `{ ran: false }` for the rest.
11341
+ *
11342
+ * @remarks
11343
+ * - Non-blocking: losers return immediately (they must not wait for the leader).
11344
+ * - The lease is heartbeated while `fn` runs, so an unbounded leader job cannot
11345
+ * let the lease lapse and admit a late second leader.
11346
+ * - The lease is released in `finally` unless `hold` is set.
11347
+ * - With the default in-memory lease store a single process always wins, so
11348
+ * single-process behavior is unchanged.
11349
+ *
11350
+ * @example
11351
+ * ```ts
11352
+ * const { ran } = await runAsLeader(leaseStore, "startup-recovery", () => recoverAll());
11353
+ * ```
11354
+ */
11355
+ declare function runAsLeader<T>(store: LeaseStore, name: string, fn: () => Promise<T>, options?: RunAsLeaderOptions): Promise<RunAsLeaderResult<T>>;
11356
+
11357
+ /** Outbox topic carrying cross-replica plugin-catalog invalidation. */
11358
+ declare const PLUGIN_CATALOG_CHANGED_TOPIC = "plugin-catalog-changed";
11359
+ /**
11360
+ * Installs the process-wide outbox used to broadcast plugin-catalog invalidation.
11361
+ *
11362
+ * @param next Shared outbox + this replica id, or `undefined` to clear.
11363
+ * @remarks Called once at the composition root (gateway startup).
11364
+ */
11365
+ declare function configurePluginCatalogSync(next: {
11366
+ outbox: OutboxStore;
11367
+ owner: string;
11368
+ } | undefined): void;
11369
+ /**
11370
+ * Best-effort broadcast that a tenant's plugin catalog changed.
11371
+ *
11372
+ * @param tenantId Tenant whose catalog was reloaded.
11373
+ * @remarks Never throws: a miss is corrected by the 30s catalog TTL.
11374
+ */
11375
+ declare function publishPluginCatalogChanged(tenantId: string): Promise<void>;
11376
+
10635
11377
  declare const AGENT_TASK_EVENT = "agent:execute";
10636
11378
 
10637
11379
  /**
@@ -10982,6 +11724,8 @@ interface SandboxRunConfig {
10982
11724
  workspaceId?: string;
10983
11725
  /** Project that scopes the run. */
10984
11726
  projectId?: string;
11727
+ /** Current orchestration depth; nested mints pass depth+1. */
11728
+ depth?: number;
10985
11729
  }
10986
11730
  /**
10987
11731
  * Resolves a `SandboxInstance` for the given run identity.
@@ -11442,6 +12186,90 @@ declare function resolveTenantPluginSkill(tenantId: string, owner: string, skill
11442
12186
  */
11443
12187
  declare function resolveEnabledPluginSkill(owner: string | undefined, skillName: string, enabledDefinition: PluginSkillDefinition | undefined, tenantId: string | undefined): Promise<ResolvedPluginSkill | undefined>;
11444
12188
 
12189
+ /**
12190
+ * Versioned provisioning of the Open MCP client bundle into a sandbox volume.
12191
+ *
12192
+ * Writes the built zero-dependency client + CLI as **raw bundle files** under
12193
+ * `/root/.agents/sdk/open-mcp-client` (plus a version manifest at
12194
+ * `/root/.agents/sdk/.open-client-manifest.json`). Sandbox code can load the
12195
+ * entry point by absolute path, e.g.
12196
+ * `require("/root/.agents/sdk/open-mcp-client/index.js")`.
12197
+ *
12198
+ * @remarks
12199
+ * This helper only writes files. `NODE_PATH`/`PATH` resolution is **not**
12200
+ * configured here: a consumer (a prebuilt image, or the caller after
12201
+ * provisioning) must expose the directory on `NODE_PATH` (for bare module
12202
+ * resolution) or `PATH` (for the `cli.js` shim, which keeps its
12203
+ * `#!/usr/bin/env node` shebang). The bundle is not laid out as a scoped
12204
+ * `node_modules/@axiom-lattice/...` tree, so do NOT advertise
12205
+ * `require("@axiom-lattice/open-mcp-client")` or a bare `NODE_PATH` pointing at
12206
+ * `/root/.agents/sdk/node_modules` unless that layout is created too.
12207
+ */
12208
+ /** Minimal sandbox file surface required for provisioning. */
12209
+ interface ProvisionFileSink {
12210
+ /**
12211
+ * Create a directory (recursively) inside the sandbox volume.
12212
+ *
12213
+ * @param path - Absolute sandbox path to create.
12214
+ * @returns A promise resolved after the directory exists.
12215
+ */
12216
+ createDirectory(path: string): Promise<void>;
12217
+ /**
12218
+ * Write a UTF-8 text file inside the sandbox volume.
12219
+ *
12220
+ * @param path - Absolute sandbox path to write.
12221
+ * @param content - File contents.
12222
+ * @returns A promise resolved after the file is written.
12223
+ */
12224
+ writeFile(path: string, content: string): Promise<void>;
12225
+ }
12226
+ /** Bundle contents to provision. */
12227
+ interface SandboxOpenClientBundle {
12228
+ /** Built CommonJS entry point, loaded by absolute path in the sandbox. */
12229
+ indexJs: string;
12230
+ /** Executable CLI source, invoked as `node cli.js`. */
12231
+ cliJs: string;
12232
+ /** Package version recorded in the sandbox manifest. */
12233
+ version: string;
12234
+ }
12235
+ /**
12236
+ * Write the Open MCP client bundle into the sandbox at `/root/.agents/sdk`.
12237
+ *
12238
+ * Idempotent: rewrites the same paths.
12239
+ *
12240
+ * @param sandbox - Sandbox whose volume receives the bundle.
12241
+ * @param bundle - Client JS/CLI source and version.
12242
+ * @returns A promise resolved after the files and manifest are written.
12243
+ *
12244
+ * @example
12245
+ * ```ts
12246
+ * await provisionSandboxOpenClient(sandbox, {
12247
+ * indexJs: 'module.exports = { createClient };',
12248
+ * cliJs: '#!/usr/bin/env node\n// ...',
12249
+ * version: "0.1.0",
12250
+ * });
12251
+ * // sandbox code loads it by absolute path:
12252
+ * // const client = require("/root/.agents/sdk/open-mcp-client/index.js");
12253
+ * ```
12254
+ *
12255
+ * @remarks
12256
+ * The version manifest is written last, so its presence means the JS files were
12257
+ * written first. This only writes raw bundle files; consumers load `index.js` by
12258
+ * absolute path and must add the directory to `PATH` themselves to run `cli.js`.
12259
+ * No scoped `node_modules` tree is created.
12260
+ */
12261
+ declare function provisionSandboxOpenClient(sandbox: {
12262
+ file: ProvisionFileSink;
12263
+ }, bundle: SandboxOpenClientBundle): Promise<void>;
12264
+ /**
12265
+ * Build a bundle from an installed package's built files.
12266
+ *
12267
+ * @param distDir - Directory containing `index.js` and `cli.js`.
12268
+ * @param version - Package version to record in the manifest.
12269
+ * @returns The bundle.
12270
+ */
12271
+ declare function buildBundleFromDist(distDir: string, version: string): SandboxOpenClientBundle;
12272
+
11445
12273
  /** Stable failure codes emitted when capability bundles cannot be composed. */
11446
12274
  type CapabilityBundleMergeErrorCode = "CAPABILITY_BUNDLE_DUPLICATE_ID" | "CAPABILITY_BUNDLE_EMPTY_ALLOWED_TOOLS" | "CAPABILITY_BUNDLE_INVALID_CONFIG" | "CAPABILITY_BUNDLE_NULL_VALUE" | "CAPABILITY_BUNDLE_UNSAFE_KEY";
11447
12275
  /** Describes invalid capability bundle input rejected by the pure merger. */
@@ -12587,4 +13415,4 @@ declare function parseDirectRoomType(projectId: string): "human" | "bot" | null;
12587
13415
  */
12588
13416
  declare function isDirectRoom(projectId: string): boolean;
12589
13417
 
12590
- export { AGENT_TASK_EVENT, type AddMessageParams, type AddMessageResult, Agent, type AgentClient, type AgentExecutor, AgentInstanceManager, type AgentLattice, AgentLatticeManager, type AgentLifecycleEventName, AgentManager, type AgentStreamExecutor, type AgentTaskCompletionInput, type AgentThreadInterface, type ApproveInterruptedTaskInput, type AssignTaskOwnerInput, BUILTIN_PLUGINS, BUILTIN_SKILLS, type BackendFactory, type BackendProtocol, type BeginRunFailure, type BeginRunInput, type BeginRunResult, type BeginRunSuccess, type BufferStats, CAPABILITY_TOOL_NAME_CONFLICT, type CacheEntry, type CalibrationProbe, CapabilityBundleMergeError, type CapabilityBundleMergeErrorCode, CapabilityBundleMerger, CapabilityBundleValidationError, type CapabilityBundleValidationErrorCode, type CapabilityGuardDenialCode, type CapabilityResourceSelector, type CapabilityToolMetadata, CapabilityToolNameConflictError, CapabilityToolRegistry, type CaseRunResult, type Chunk, ChunkBuffer, ChunkBufferLatticeManager, CollectionLatticeManager, type ColumnInfo, type CompileSandboxPluginArgs, CompositeBackend, type ConflictItem, type ConnectAllChannelsOptions, ConnectionRegistry, ConsoleLoggerClient, type CreateSandboxProviderConfig, type CronFields, CustomMetricsClient, type CustomMiddlewareFactory, CustomMiddlewareRegistry, DEFAULT_CALIBRATION_PROBES, DEFAULT_CONNECT_TIMEOUT_MS, DEFAULT_DELAY_MS, DEFAULT_MAX_ATTEMPTS, type DatabaseConfig, type DatabaseType, DaytonaInstance, DaytonaProvider, type DaytonaProviderConfig, DefaultScheduleClient, DelegatedScopeNotQueueableError, type DeleteResult, DependencyResolver, type DispatchPreparation, DuplicateProjectRoomMessageIdempotencyKeyError, E2BInstance, E2BProvider, type E2BProviderConfig, EMPTY_CONTENT_WARNING, type EditResult, type EmbeddingsInfo, type EmbeddingsLatticeInterface, EmbeddingsLatticeManager, type EnsureMicrosandboxInput, type EvalRunService, type ExecutionAuthority, ExecutionAuthorityRegistry, type ExportBundle, type ExportContext, type ExportJob, type ExportableEntity, type ExportableEntityDefinition, ExportableEntityRegistry, type ExportableFile, type ExportableTypeInfo, type FileData, type FileInfo, FileSystemSkillStore, type FileSystemSkillStoreOptions, FilesystemBackend, type FsEntry, type GrepMatch, HEALTH_CHECK_INTERVAL_MS, HEALTH_CHECK_TIMEOUT_MS, type IMessageQueueStore, type IMetricsServerClient, type ISqlDatabase, IdRemapper, type ImmediateDispatchPlan, type ImportApplyResolution, type ImportApplyResult, type ImportEntityResult, type ImportEntityStatus, type ImportPreviewResult, InMemoryA2AApiKeyStore, InMemoryAgentWebAppStore, InMemoryAssistantStore, InMemoryBindingStore, InMemoryCapabilityBundleStore, InMemoryChannelInstallationStore, InMemoryChunkBuffer, InMemoryCollectionStore, InMemoryDatabaseConfigStore, InMemoryMailboxStore, InMemoryMenuStore, InMemoryModelProviderStore, InMemoryOpenAuditStore, InMemoryProjectBotMembershipStore, InMemoryProjectMembershipStore, InMemoryProjectRoomCoordinator, InMemoryProjectRoomMessageStore, InMemoryProjectRoomReadStateStore, InMemoryProjectRoomStore, InMemoryTaskListStore, InMemoryTaskStore, InMemoryTaskWorkItemStore, InMemoryTenantStore, InMemoryThreadMessageQueueStore, InMemoryThreadStore, InMemoryUserPushSubscriptionStore, InMemoryUserStore, InMemoryUserTenantLinkStore, type InsertionItem, type JudgeVerdict, LINE_NUMBER_WIDTH, type LangGraphStateChecker, type LatticeAgentStepConfig, LatticeEval, type LatticeEvalBatchReport, type LatticeEvalCase, type LatticeEvalCaseType, type LatticeEvalCaseWithTemplate, type LatticeEvalConfig, type LatticeEvalLogEvent, type LatticeEvalLogLevel, LatticeEvalProject, type LatticeEvalProjectType, type LatticeEvalResult, type LatticeEvalRubric, LatticeEvalSuite, type LatticeEvalSuiteType, type LatticeEvalTemplate, type LifecycleResult, type LifecycleWarning, LocalSandboxInstance, LocalSandboxProvider, type LocalSandboxProviderConfig, type LoggerLattice, LoggerLatticeManager, type LoopBreakerConfig, MAX_BACKOFF_MS, MAX_LINE_LENGTH, MAX_PACK_ENTRIES, MAX_PACK_FILE_BYTES, MAX_PACK_TOTAL_BYTES, type MailboxMessage, type MailboxStore, ManagedTaskStartError, type ManagedTaskStartOptions, type ManifestValidationResult, type McpClientFactory, type McpClientLike, type McpClientSession, type McpConnectionOptions, McpLatticeManager, type McpRegisterOptions, type McpServerId, type McpServerRuntime, type McpServerState, MemoryBackend, MemoryLatticeManager, MemoryQueueClient, MemoryScheduleStorage, type MergedPluginSkills, type MessageCompletedEvent, type MessageContent, type MessageContentPart, type MessageContentValue, type MessageFailedEvent, type MessageInterruptedEvent, type MessageLike, type MessageStartedEvent, MessageType, MetricsServerManager, MicrosandboxRemoteInstance, MicrosandboxRemoteProvider, type MicrosandboxRemoteProviderClient, type MicrosandboxRemoteProviderConfig, MicrosandboxServiceClient, type MicrosandboxServiceClientConfig, type MicrosandboxShellExecInput, type ModelConfig, type ModelLatticeInterface, ModelLatticeManager, MysqlDatabase, type OutputType, PACK_DIRECTORY_TIMEOUT_SECONDS, type PackSourceInfo, type PendingMessage, PersonalAssistantConfig, PinoLoggerClient, type PluginConnectionScope, PluginRegistry, type PostProcessTaskMutationResponseInput, PostgresDatabase, type PreviewError, ProjectBotMembershipIdConflictError, ProjectMutationMutex, type ProjectMutationScope, ProjectRoomMessageIdConflictError, type ProjectTaskAdmissionListener, type ProjectTaskAdmissionNotification, ProjectTaskAdmissionNotifier, type ProjectTaskAdmissionNotifierOptions, type ProjectTaskAssignmentScope, ProjectTaskOwnerPolicy, type ProjectTaskOwnerPolicyCode, ProjectTaskOwnerPolicyError, type ProjectTaskReassignmentAuthorization, type ProjectTaskReassignmentAuthorizationInput, type ProjectTaskReassignmentAuthorizer, type ProjectTaskReassignmentThreadValidationInput, type ProjectTaskReassignmentThreadValidator, type ProjectTaskRosterScope, PrometheusClient, type QueryResult, type QueueLattice, QueueLatticeManager, type QueueMessage, QueueMode, type QueuePendingEvent, type QueueScope, ROOM_COORDINATOR_KEY, type ReassignProjectTaskInput, type ReconcileAllTenantTaskRunsInput, type ReconcileStaleTaskRunsInput, type ReconcileStaleTaskRunsResult, type ReconcileTaskDescriptionInput, type ReconcileTenantTaskRunsInput, type RejectInterruptedTaskInput, RemoteSandboxInstance, RemoteSandboxProvider, type RemoteSandboxProviderConfig, type RepeatedToolCallBreakerOptions, RepeatedToolCallError, type ReplyReadyEvent, type Resolution, type ResolutionAction, type ResolveAgentFn, type ResolvedConfig, type ResolvedPluginConnection, type ResolvedPluginSkill, type ResumeTaskResult, type RoomAgentMessageCallbackFailure, type RoomAgentMessageCommitted, type RoomAgentMessageInput, RoomAgentMessageService, type RoomAgentReplyInput, type RunSandboxConfig, type RuntimeModelConfig, type RuntimeSkillSelection, SAFE_PATH_COMPONENT, type STTModelInfo, STTModelLattice, type STTModelLatticeInterface, STTModelLatticeManager, type SandboxFileInfo, type SandboxFileService, SandboxFilesystem, type SandboxGrepMatch, type SandboxInstance, type SandboxIsolationLevel, SandboxLatticeManager, type SandboxManagerProtocol, SandboxPluginExecutor, type SandboxPluginExecutorDeps, type SandboxPluginInvokeArgs, type SandboxPluginResult, type SandboxProvider, type SandboxProviderFactory, type SandboxProviderType, type SandboxResolver, type SandboxRunConfig, type SandboxShellService, SandboxSkillStore, type SandboxSkillStoreOptions, type SandboxVolumeDefinition, type ScheduleLattice, ScheduleLatticeManager, type SchedulerMiddlewareOptions, SemanticMetricsClient, type SettleRunInput, type SettleRunOutcome, type SharePayload, SimpleMemoryVectorStore, type SkillLattice, SkillLatticeManager, type SkillMeta, type SkillResource, SqlDatabaseManager, type StartLifecycleResult, type StartTaskExecutionInput, type StateAndStore, StateBackend, StoreBackend, type StoreLattice, StoreLatticeManager, type StoreType, type StoreTypeMap, type SubmitTaskReviewInput, TASK_RESPONSE_FINAL_WARNING_LIMIT, TASK_RESPONSE_PRIOR_WARNING_LIMIT, TASK_RESPONSE_SCALAR_MAX_BYTES, TOOL_RESULT_TOKEN_LIMIT, TRUNCATION_GUIDANCE, type TableInfo, type TableSchema, type TaskAgentInvocation, type TaskEvent, type TaskExecutionFailure, type TaskExecutionManaged, type TaskExecutionResult, type TaskExecutionServiceDeps, type TaskExecutionSuccess, type TaskLifecycleListener, type TaskLifecycleNotification, TaskLifecycleNotifier, TaskLifecycleService, type TaskLifecycleServiceDeps, type TaskListStore, type TaskResponseParseResult, type TaskRunBridge, type TaskRunBridgeDeps, TaskRunBridgeStoresRequiredError, TaskRunRegistry, type TaskSpec, TaskStatus, type TaskUpdatable, TeamAgentGraphBuilder, type TeamConfig, type TeamMiddlewareOptions, type TeamTask, type TeammateSpec, type TeammateToolsOptions, TenantPluginCatalog, type TenantPluginCatalogDeps, type TenantPlugins, type ThreadBuffer, type ThreadBufferConfig, type ThreadBusyEvent, type ThreadEndCode, ThreadEndError, type ThreadIdleEvent, type ThreadInfo, type ThreadQueueConfig, type ThreadState, ThreadStatus, type ThreadStatusChangedEvent, TokenCache, type ToolDefinition, type ToolLattice, ToolLatticeManager, type TransferOwnerInput, type TransferOwnerResult, type TrustedAgentMessageDispatcher, type TrustedMessageOptions, type UnknownToolHandlerConfig, UnsafeUpstreamUrlError, type UnsafeUrlReason, type ValidateManifestArgs, type VectorStoreLatticeInterface, VectorStoreLatticeManager, type VectorStoreProviderLattice, VectorStoreProviderManager, VolumeFilesystem, type VolumeFsClient, type WorkflowValidationError, type WriteResult, abortWorkflowRun, agentInstanceManager, agentLatticeManager, appendReconciliationWarning, appendUiFence, assertSafeUpstreamUrl, buildGrepResultsDict, buildInput, buildNamedVolumeName, buildRemotePackDirectoryCommand, buildSandboxMetadataEnv, buildSkillFile, buildStateAnnotation, buildTableName, buildTaskMutationFallback, buildTaskNormalizationFallback, checkEmptyContent, clearEncryptionKeyCache, clearEvalRunService, collectionLatticeManager, compileInternal, compileSandboxPlugin, compileWorkflow, computeSandboxName, configureStores, connectAllChannels, convertToConnection, createAgentNode, createAgentTeam, createCapabilityGuardMiddleware, createExecuteSqlQueryTool, createFileData, createInfoSqlTool, createListMetricsDataSourcesTool, createListMetricsServersTool, createListTablesSqlTool, createMapNode, createModelSelectorMiddleware, createNodeHandler, createProjectRoomMiddleware, createProjectTaskOwnerPolicy, createProjectTaskReassignmentAuthorizer, createQueryCheckerSqlTool, createQueryMetricDefinitionTool, createQueryMetricsListTool, createQuerySemanticMetricDataTool, createQuerySqlTool, createQueryTableDefinitionTool, createQueryTablesListTool, createRepeatedToolCallBreakerMiddleware, createResourceAddress, createSandboxProvider, createSandboxResolver, createSchedulerMiddleware, createSharePayload, createTaskExecutionService, createTaskLifecycleService, createTaskMiddleware, createTaskRunBridge, createTeamMiddleware, createTeammateTools, createTrustedAgentMessageDispatcher, createUnknownToolHandlerMiddleware, createWidgetMiddleware, decrypt, describeCronExpression, documentLearningPlugin, documentParserPlugin, embeddingsLatticeManager, encrypt, ensureBuiltinAgentsForTenant, ensurePluginSkillInSandbox, evaluateLatticeCaseWithLogs, eventBus, eventBus as eventBusDefault, executionAuthorityRegistry, extractAppsRef, extractFetcherError, extractLegacyRefs, extractOutput, fileDataToString, formatContentWithLineNumbers, formatGrepMatches, formatGrepResults, formatReadResponse, generateDirectBotProjectId, generateDirectHumanProjectId, generateToken, getAgentClient, getAgentConfig, getAllAgentConfigs, getAllBuiltInSkillMetas, getAllToolDefinitions, getBindingRegistry, getBuiltInSkillContent, getBuiltInSkillMeta, getBuiltInSkillNames, getCheckpointSaver, getChunkBuffer, getCollectionEntryCount, getEmbeddingsClient, getEmbeddingsLattice, getEncryptionKey, getEvalRunService, getLoggerLattice, getMenuRegistry, getModelLattice, getNextCronTime, getOrCreateCollectionVectorStore, getPluginSkillManifestVersion, getQueueLattice, getRuntimeCapabilityConfig, getRuntimeSkillSelection, getSTTClient, getSTTClientWithTenant, getSTTModelLattice, getSandBoxManager, getSandboxPluginCatalog, getScheduleLattice, getStoreLattice, getToolClient, getToolClientWithTenant, getToolDefinition, getToolLattice, getVectorStoreClient, getVectorStoreLattice, getVectorStoreProvider, getWorkflowSignal, globSearchFiles, grepMatchesFromFiles, grepSearchFiles, hasChunkBuffer, hasDelegatedWorkerToken, hasRuntimeCapabilityPolicy, invokeWithRetry, isBuiltInSkill, isDirectRoom, isMcpConnectionError, isPluginSkillAuthorizedInSandbox, isPluginSkillManagedInSandbox, isUsingDefaultKey, isValidCronExpression, isValidSandboxName, isValidSkillName, jsonSchemaToZod, listCollectionEntries, listSandboxProviderTypes, loggerLatticeManager, mcpManager, mergeCapabilityBundles, mergePluginSkills, mergePluginSources, metricsServerManager, modelLatticeManager, nextBackoffDelay, normalizeSandboxName, ownTaskResponseField, parallelLimit, parseCronExpression, parseDirectRoomType, parseJudgeVerdict, parsePackSize, parseSkillFrontmatter, parseTaskResponse, parseYaml, performStringReplacement, postProcessTaskMutationResponse, prepareTaskDispatch, projectMutationMutex, projectRoomPlugin, projectTaskAdmissionNotifier, queueLatticeManager, readLoopBreakerConfig, reconcileAllTenantTaskRuns, reconcileStaleTaskRuns, reconcileTenantTaskRuns, registerAgentLattice, registerAgentLatticeWithTenant, registerAgentLattices, registerCheckpointSaver, registerChunkBuffer, registerEmbeddingsLattice, registerExistingTool, registerExistingToolWithTenant, registerLoggerLattice, registerModelLattice, registerModelLatticeForTenant, registerQueueLattice, registerSTTModelLattice, registerSandboxProviderType, registerScheduleLattice, registerStoreLattice, registerTeammateAgent, registerToolLattice, registerVectorStoreLattice, registerVectorStoreProvider, registerWorkflowRun, removeCollectionVectorStore, renderTemplate, resolveEnabledPluginSkill, resolveJudgeModelKey, resolvePath, resolvePluginConnections, resolveSandboxPluginConnections, resolveTenantPluginSkill, roomCoordinatorConfig, runRemotePackDirectory, safeTaskResponseId, sandboxLatticeManager, sanitizeToolCallId, scheduleLatticeManager, serializePluginMeta, serializeTaskMutationSuccess, serializeTaskNormalizationFallback, serializeTaskReadResponse, setBindingRegistry, setEvalRunService, setMenuRegistry, setSandboxPluginCatalog, skillLatticeManager, sqlDatabaseManager, storeLatticeManager, sttModelLatticeManager, taskLifecycleNotifier, taskRunRegistry, toJsonSchema, toSafeStateExpr, toolLatticeManager, truncateIfTooLong, unregisterTeammateAgent, unregisterWorkflowRun, updateFileData, validateAgentInput, validateCapabilityBundleInput, validateDSL, validateEncryptionKey, validatePackSourcePath, validatePath, validateRelativePath, validateSandboxPluginManifest, validateSkillName, validateToolInput, vectorStoreLatticeManager, vectorStoreProviderManager, withTimeout, wrapMcpToolWithUi };
13418
+ export { AGENT_TASK_EVENT, type AddMessageParams, type AddMessageResult, Agent, type AgentClient, type AgentExecutor, AgentInstanceManager, type AgentLattice, AgentLatticeManager, type AgentLifecycleEventName, AgentManager, type AgentStreamExecutor, type AgentTaskCompletionInput, type AgentThreadInterface, type ApproveInterruptedTaskInput, type AssignTaskOwnerInput, BUILTIN_PLUGINS, BUILTIN_SKILLS, type BackendFactory, type BackendProtocol, type BeginRunFailure, type BeginRunInput, type BeginRunResult, type BeginRunSuccess, type BufferStats, CAPABILITY_TOOL_NAME_CONFLICT, type CacheEntry, type CalibrationProbe, CapabilityBundleMergeError, type CapabilityBundleMergeErrorCode, CapabilityBundleMerger, CapabilityBundleValidationError, type CapabilityBundleValidationErrorCode, type CapabilityGuardDenialCode, type CapabilityResourceSelector, type CapabilityToolMetadata, CapabilityToolNameConflictError, CapabilityToolRegistry, type CaseRunResult, type Chunk, ChunkBuffer, ChunkBufferLatticeManager, type ClaimMessagesOptions, CollectionLatticeManager, type ColumnInfo, type CompileSandboxPluginArgs, CompositeBackend, type ConflictItem, type ConnectAllChannelsOptions, ConnectionRegistry, ConsoleLoggerClient, type CreateSandboxProviderConfig, type CronFields, CustomMetricsClient, type CustomMiddlewareFactory, CustomMiddlewareRegistry, DEFAULT_CALIBRATION_PROBES, DEFAULT_CONNECT_TIMEOUT_MS, DEFAULT_DELAY_MS, DEFAULT_MAX_ATTEMPTS, type DatabaseConfig, type DatabaseType, DaytonaInstance, DaytonaProvider, type DaytonaProviderConfig, DefaultScheduleClient, DelegatedScopeNotQueueableError, type DeleteResult, DependencyResolver, type DispatchPreparation, DuplicateProjectRoomMessageIdempotencyKeyError, E2BInstance, E2BProvider, type E2BProviderConfig, EMPTY_CONTENT_WARNING, type EditResult, type EmbeddingsInfo, type EmbeddingsLatticeInterface, EmbeddingsLatticeManager, type EnsureMicrosandboxInput, type EvalRunService, type ExecutionAuthority, ExecutionAuthorityRegistry, type ExportBundle, type ExportContext, type ExportJob, type ExportableEntity, type ExportableEntityDefinition, ExportableEntityRegistry, type ExportableFile, type ExportableTypeInfo, type FileData, type FileInfo, FileSystemSkillStore, type FileSystemSkillStoreOptions, FilesystemBackend, type FsEntry, type GetThreadRunOwnerInput, type GrepMatch, HEALTH_CHECK_INTERVAL_MS, HEALTH_CHECK_TIMEOUT_MS, type IMessageQueueStore, type IMetricsServerClient, type ISqlDatabase, IdRemapper, type ImmediateDispatchPlan, type ImportApplyResolution, type ImportApplyResult, type ImportEntityResult, type ImportEntityStatus, type ImportPreviewResult, InMemoryA2AApiKeyStore, InMemoryAgentWebAppStore, InMemoryAssistantStore, InMemoryBindingStore, InMemoryCapabilityBundleStore, InMemoryChannelInstallationStore, InMemoryChunkBuffer, InMemoryCollectionStore, InMemoryDatabaseConfigStore, InMemoryLeaseStore, InMemoryMailboxStore, InMemoryMenuStore, InMemoryModelProviderStore, InMemoryOpenAuditStore, InMemoryOutboxStore, InMemoryProjectBotMembershipStore, InMemoryProjectMembershipStore, InMemoryProjectRoomCoordinator, InMemoryProjectRoomMessageStore, InMemoryProjectRoomReadStateStore, InMemoryProjectRoomStore, InMemoryTaskListStore, InMemoryTaskStore, InMemoryTaskWorkItemStore, InMemoryTenantStore, InMemoryThreadMessageQueueStore, InMemoryThreadStore, InMemoryUserPushSubscriptionStore, InMemoryUserStore, InMemoryUserTenantLinkStore, type InsertionItem, type JudgeVerdict, LINE_NUMBER_WIDTH, type LangGraphStateChecker, type LatticeAgentStepConfig, LatticeEval, type LatticeEvalBatchReport, type LatticeEvalCase, type LatticeEvalCaseType, type LatticeEvalCaseWithTemplate, type LatticeEvalConfig, type LatticeEvalLogEvent, type LatticeEvalLogLevel, LatticeEvalProject, type LatticeEvalProjectType, type LatticeEvalResult, type LatticeEvalRubric, LatticeEvalSuite, type LatticeEvalSuiteType, type LatticeEvalTemplate, LeaseAcquisitionTimeoutError, type LifecycleResult, type LifecycleWarning, LocalSandboxInstance, LocalSandboxProvider, type LocalSandboxProviderConfig, type LoggerLattice, LoggerLatticeManager, type LoopBreakerConfig, MAX_BACKOFF_MS, MAX_LINE_LENGTH, MAX_PACK_ENTRIES, MAX_PACK_FILE_BYTES, MAX_PACK_TOTAL_BYTES, type MailboxMessage, type MailboxStore, ManagedTaskStartError, type ManagedTaskStartOptions, type ManifestValidationResult, type McpClientFactory, type McpClientLike, type McpClientSession, type McpConnectionOptions, McpLatticeManager, type McpRegisterOptions, type McpServerId, type McpServerRuntime, type McpServerState, MemoryBackend, MemoryLatticeManager, MemoryQueueClient, MemoryScheduleStorage, type MergedPluginSkills, type MessageCompletedEvent, type MessageContent, type MessageContentPart, type MessageContentValue, type MessageFailedEvent, type MessageInterruptedEvent, type MessageLike, type MessageStartedEvent, MessageType, MetricsServerManager, MicrosandboxRemoteInstance, MicrosandboxRemoteProvider, type MicrosandboxRemoteProviderClient, type MicrosandboxRemoteProviderConfig, MicrosandboxServiceClient, type MicrosandboxServiceClientConfig, type MicrosandboxShellExecInput, type ModelConfig, type ModelLatticeInterface, ModelLatticeManager, MysqlDatabase, OutboxPoller, type OutboxPollerDeps, type OutputType, PACK_DIRECTORY_TIMEOUT_SECONDS, PLATFORM_SECRET_ENV_VARS, PLUGIN_CATALOG_CHANGED_TOPIC, type PackSourceInfo, type PendingMessage, PersonalAssistantConfig, PinoLoggerClient, type PluginConnectionScope, PluginRegistry, type PostProcessTaskMutationResponseInput, PostgresDatabase, type PreviewError, ProjectBotMembershipIdConflictError, ProjectMutationMutex, type ProjectMutationScope, ProjectRoomMessageIdConflictError, type ProjectTaskAdmissionListener, type ProjectTaskAdmissionNotification, ProjectTaskAdmissionNotifier, type ProjectTaskAdmissionNotifierOptions, type ProjectTaskAssignmentScope, ProjectTaskOwnerPolicy, type ProjectTaskOwnerPolicyCode, ProjectTaskOwnerPolicyError, type ProjectTaskReassignmentAuthorization, type ProjectTaskReassignmentAuthorizationInput, type ProjectTaskReassignmentAuthorizer, type ProjectTaskReassignmentThreadValidationInput, type ProjectTaskReassignmentThreadValidator, type ProjectTaskRosterScope, PrometheusClient, type ProvisionFileSink, type QueryResult, type QueueLattice, QueueLatticeManager, type QueueMessage, QueueMode, type QueuePendingEvent, type QueueScope, ROOM_COORDINATOR_KEY, type ReassignProjectTaskInput, type ReconcileAllTenantTaskRunsInput, type ReconcileStaleTaskRunsInput, type ReconcileStaleTaskRunsResult, type ReconcileTaskDescriptionInput, type ReconcileTenantTaskRunsInput, type RejectInterruptedTaskInput, RemoteSandboxInstance, RemoteSandboxProvider, type RemoteSandboxProviderConfig, type RepeatedToolCallBreakerOptions, RepeatedToolCallError, type ReplyReadyEvent, type Resolution, type ResolutionAction, type ResolveAgentFn, type ResolvedConfig, type ResolvedPluginConnection, type ResolvedPluginSkill, type ResumeTaskResult, type RoomAgentMessageCallbackFailure, type RoomAgentMessageCommitted, type RoomAgentMessageInput, RoomAgentMessageService, type RoomAgentReplyInput, type RunAsLeaderOptions, type RunAsLeaderResult, type RunSandboxConfig, type RuntimeModelConfig, type RuntimeSkillSelection, SAFE_PATH_COMPONENT, SANDBOX_OPEN_GATEWAY_URL_ENV, SANDBOX_OPEN_TOKEN_ENV, type STTModelInfo, STTModelLattice, type STTModelLatticeInterface, STTModelLatticeManager, type SandboxFileInfo, type SandboxFileService, SandboxFilesystem, type SandboxGrepMatch, type SandboxInstance, type SandboxIsolationLevel, SandboxLatticeManager, type SandboxManagerProtocol, type SandboxOpenClientBundle, type SandboxOpenCredential, type SandboxOpenCredentialContext, type SandboxOpenCredentialProvider, type SandboxOpenCredentialProviderOptions, SandboxPluginExecutor, type SandboxPluginExecutorDeps, type SandboxPluginInvokeArgs, type SandboxPluginResult, type SandboxProvider, type SandboxProviderFactory, type SandboxProviderType, type SandboxResolver, type SandboxRunConfig, type SandboxShellService, SandboxSkillStore, type SandboxSkillStoreOptions, type SandboxVolumeDefinition, type ScheduleLattice, ScheduleLatticeManager, type SchedulerMiddlewareOptions, SemanticMetricsClient, type SettleRunInput, type SettleRunOutcome, type SharePayload, SimpleMemoryVectorStore, type SkillLattice, SkillLatticeManager, type SkillMeta, type SkillResource, SqlDatabaseManager, type StartLifecycleResult, type StartTaskExecutionInput, type StateAndStore, StateBackend, StoreBackend, type StoreLattice, StoreLatticeManager, type StoreType, type StoreTypeMap, type SubmitTaskReviewInput, TASK_RESPONSE_FINAL_WARNING_LIMIT, TASK_RESPONSE_PRIOR_WARNING_LIMIT, TASK_RESPONSE_SCALAR_MAX_BYTES, TOOL_RESULT_TOKEN_LIMIT, TRUNCATION_GUIDANCE, type TableInfo, type TableSchema, type TaskAgentInvocation, type TaskEvent, type TaskExecutionFailure, type TaskExecutionManaged, type TaskExecutionResult, type TaskExecutionServiceDeps, type TaskExecutionSuccess, type TaskLifecycleListener, type TaskLifecycleNotification, TaskLifecycleNotifier, TaskLifecycleService, type TaskLifecycleServiceDeps, type TaskListStore, type TaskResponseParseResult, type TaskRunBridge, type TaskRunBridgeDeps, TaskRunBridgeStoresRequiredError, type TaskRunLeaseHandle, TaskRunRegistry, type TaskSpec, TaskStatus, type TaskUpdatable, TeamAgentGraphBuilder, type TeamConfig, type TeamMiddlewareOptions, type TeamTask, type TeammateSpec, type TeammateToolsOptions, TenantPluginCatalog, type TenantPluginCatalogDeps, type TenantPlugins, type ThreadBuffer, type ThreadBufferConfig, type ThreadBusyEvent, type ThreadEndCode, ThreadEndError, type ThreadIdleEvent, type ThreadInfo, type ThreadQueueConfig, type ThreadRunLeaseHandle, type ThreadState, ThreadStatus, type ThreadStatusChangedEvent, TokenCache, type ToolDefinition, type ToolLattice, ToolLatticeManager, type TransferOwnerInput, type TransferOwnerResult, type TrustedAgentMessageDispatcher, type TrustedMessageOptions, type TryAcquireTaskRunInput, type TryAcquireThreadRunInput, type UnknownToolHandlerConfig, UnsafeUpstreamUrlError, type UnsafeUrlReason, type ValidateManifestArgs, type VectorStoreLatticeInterface, VectorStoreLatticeManager, type VectorStoreProviderLattice, VectorStoreProviderManager, VolumeFilesystem, type VolumeFsClient, type WithLeaseOptions, type WorkflowValidationError, type WriteResult, abortWorkflowRun, agentInstanceManager, agentLatticeManager, appendReconciliationWarning, appendUiFence, assertSafeUpstreamUrl, buildBundleFromDist, buildGrepResultsDict, buildInput, buildNamedVolumeName, buildRemotePackDirectoryCommand, buildSandboxMetadataEnv, buildSandboxOpenEnv, buildSkillFile, buildStateAnnotation, buildTableName, buildTaskMutationFallback, buildTaskNormalizationFallback, checkEmptyContent, clearEncryptionKeyCache, clearEvalRunService, clearSandboxOpenCredentialProviderForTests, collectionLatticeManager, compileInternal, compileSandboxPlugin, compileWorkflow, computeSandboxName, configureCoordinationLeaseStore, configurePluginCatalogSync, configureStores, connectAllChannels, convertToConnection, createAgentNode, createAgentTeam, createCapabilityGuardMiddleware, createExecuteSqlQueryTool, createFileData, createInfoSqlTool, createListMetricsDataSourcesTool, createListMetricsServersTool, createListTablesSqlTool, createMapNode, createModelSelectorMiddleware, createNodeHandler, createProjectRoomMiddleware, createProjectTaskOwnerPolicy, createProjectTaskReassignmentAuthorizer, createQueryCheckerSqlTool, createQueryMetricDefinitionTool, createQueryMetricsListTool, createQuerySemanticMetricDataTool, createQuerySqlTool, createQueryTableDefinitionTool, createQueryTablesListTool, createRepeatedToolCallBreakerMiddleware, createResourceAddress, createSandboxProvider, createSandboxResolver, createSchedulerMiddleware, createSharePayload, createShellExecTool, createTaskExecutionService, createTaskLifecycleService, createTaskMiddleware, createTaskRunBridge, createTeamMiddleware, createTeammateTools, createTrustedAgentMessageDispatcher, createUnknownToolHandlerMiddleware, createWidgetMiddleware, decrypt, describeCronExpression, documentLearningPlugin, documentParserPlugin, embeddingsLatticeManager, encrypt, ensureBuiltinAgentsForTenant, ensurePluginSkillInSandbox, evaluateLatticeCaseWithLogs, eventBus, eventBus as eventBusDefault, executionAuthorityRegistry, extractAppsRef, extractFetcherError, extractLegacyRefs, extractOutput, fileDataToString, formatContentWithLineNumbers, formatGrepMatches, formatGrepResults, formatReadResponse, generateDirectBotProjectId, generateDirectHumanProjectId, generateToken, getAgentClient, getAgentClientAsync, getAgentConfig, getAllAgentConfigs, getAllBuiltInSkillMetas, getAllToolDefinitions, getBindingRegistry, getBuiltInSkillContent, getBuiltInSkillMeta, getBuiltInSkillNames, getCheckpointSaver, getChunkBuffer, getCollectionEntryCount, getCoordinationLeaseStore, getEmbeddingsClient, getEmbeddingsLattice, getEncryptionKey, getEvalRunService, getLoggerLattice, getMenuRegistry, getModelLattice, getNextCronTime, getOrCreateCollectionVectorStore, getPluginSkillManifestVersion, getQueueLattice, getReplicaId, getRuntimeCapabilityConfig, getRuntimeSkillSelection, getSTTClient, getSTTClientWithTenant, getSTTModelLattice, getSandBoxManager, getSandboxOpenCredential, getSandboxPluginCatalog, getScheduleLattice, getStoreLattice, getThreadRunOwner, getToolClient, getToolClientWithTenant, getToolDefinition, getToolLattice, getVectorStoreClient, getVectorStoreLattice, getVectorStoreProvider, getWorkflowSignal, globSearchFiles, grepMatchesFromFiles, grepSearchFiles, hasChunkBuffer, hasDelegatedWorkerToken, hasRuntimeCapabilityPolicy, invokeWithRetry, isBuiltInSkill, isDirectRoom, isMcpConnectionError, isPluginSkillAuthorizedInSandbox, isPluginSkillManagedInSandbox, isUsingDefaultKey, isValidCronExpression, isValidSandboxName, isValidSkillName, jsonSchemaToZod, listCollectionEntries, listSandboxProviderTypes, loggerLatticeManager, mcpManager, mergeCapabilityBundles, mergePluginSkills, mergePluginSources, metricsServerManager, modelLatticeManager, nextBackoffDelay, normalizeSandboxName, ownTaskResponseField, parallelLimit, parseCronExpression, parseDirectRoomType, parseJudgeVerdict, parsePackSize, parseSkillFrontmatter, parseTaskResponse, parseYaml, performStringReplacement, postProcessTaskMutationResponse, prepareTaskDispatch, projectMutationMutex, projectRoomPlugin, projectTaskAdmissionNotifier, provisionSandboxOpenClient, publishPluginCatalogChanged, queueLatticeManager, readLoopBreakerConfig, reconcileAllTenantTaskRuns, reconcileStaleTaskRuns, reconcileTenantTaskRuns, registerAgentLattice, registerAgentLatticeWithTenant, registerAgentLattices, registerCheckpointSaver, registerChunkBuffer, registerEmbeddingsLattice, registerExistingTool, registerExistingToolWithTenant, registerLoggerLattice, registerModelLattice, registerModelLatticeForTenant, registerQueueLattice, registerSTTModelLattice, registerSandboxOpenCredentialProvider, registerSandboxProviderType, registerScheduleLattice, registerStoreLattice, registerTeammateAgent, registerToolLattice, registerVectorStoreLattice, registerVectorStoreProvider, registerWorkflowRun, removeCollectionVectorStore, renderTemplate, resetReplicaIdForTests, resolveEnabledPluginSkill, resolveJudgeModelKey, resolvePath, resolvePluginConnections, resolveSandboxPluginConnections, resolveTenantPluginSkill, roomCoordinatorConfig, runAsLeader, runRemotePackDirectory, safeTaskResponseId, sandboxLatticeManager, sanitizeToolCallId, scheduleLatticeManager, serializePluginMeta, serializeTaskMutationSuccess, serializeTaskNormalizationFallback, serializeTaskReadResponse, setBindingRegistry, setEvalRunService, setMenuRegistry, setSandboxPluginCatalog, skillLatticeManager, sqlDatabaseManager, storeLatticeManager, sttModelLatticeManager, taskLifecycleNotifier, taskRunLeaseKey, taskRunRegistry, threadRunLeaseKey, toJsonSchema, toSafeStateExpr, toolLatticeManager, truncateIfTooLong, tryAcquireTaskRun, tryAcquireThreadRun, unregisterTeammateAgent, unregisterWorkflowRun, updateFileData, validateAgentInput, validateCapabilityBundleInput, validateDSL, validateEncryptionKey, validatePackSourcePath, validatePath, validateRelativePath, validateSandboxPluginManifest, validateSkillName, validateToolInput, vectorStoreLatticeManager, vectorStoreProviderManager, withLease, withTimeout, wrapMcpToolWithUi };