@axiom-lattice/core 4.2.17 → 4.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,7 +8,7 @@ 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, 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, 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, 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, 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, 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, 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';
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';
@@ -23,7 +23,7 @@ import { ReplaySubject } from 'rxjs';
23
23
  import { Embeddings } from '@langchain/core/embeddings';
24
24
  import { VectorStore } from '@langchain/core/vectorstores';
25
25
  import { DocumentInterface } from '@langchain/core/documents';
26
- import { Connection, MultiServerMCPClient } from '@langchain/mcp-adapters';
26
+ import { Connection } from '@langchain/mcp-adapters';
27
27
  import { SandboxClient } from '@agent-infra/sandbox';
28
28
  import { Sandbox } from 'e2b';
29
29
  import { Sandbox as Sandbox$1 } from '@daytonaio/sdk';
@@ -1739,6 +1739,31 @@ declare class ToolLatticeManager extends BaseLatticeManager<ToolLattice> {
1739
1739
  * @param tool 已有的StructuredTool实例
1740
1740
  */
1741
1741
  registerExistingTool(key: string, tool: StructuredTool): void;
1742
+ /**
1743
+ * Register an existing StructuredTool into a specific tenant's tool bucket.
1744
+ *
1745
+ * @param tenantId - tenant that owns the tool
1746
+ * @param key - tool lattice key (no tenant prefix)
1747
+ * @param tool - the StructuredTool client
1748
+ */
1749
+ registerExistingToolWithTenant(tenantId: string, key: string, tool: StructuredTool): void;
1750
+ /**
1751
+ * Get a tool lattice from a specific tenant bucket.
1752
+ *
1753
+ * @param tenantId - tenant bucket
1754
+ * @param key - tool lattice key
1755
+ * @returns the tool lattice or undefined
1756
+ */
1757
+ getToolLatticeWithTenant(tenantId: string, key: string): ToolLattice | undefined;
1758
+ /**
1759
+ * Get a tool client for a tenant, falling back to the "default" bucket for
1760
+ * built-in tools. Throws if the tool exists in neither bucket.
1761
+ *
1762
+ * @param tenantId - requesting tenant
1763
+ * @param key - tool lattice key
1764
+ * @returns the StructuredTool client
1765
+ */
1766
+ getToolClientWithTenant(tenantId: string, key: string): StructuredTool;
1742
1767
  /**
1743
1768
  * 验证工具输入参数
1744
1769
  * @param key Lattice键名
@@ -1749,7 +1774,9 @@ declare class ToolLatticeManager extends BaseLatticeManager<ToolLattice> {
1749
1774
  declare const toolLatticeManager: ToolLatticeManager;
1750
1775
  declare const registerToolLattice: (key: string, config: ToolConfig, executor: ToolExecutor) => void;
1751
1776
  declare const registerExistingTool: (key: string, tool: StructuredTool) => void;
1777
+ declare const registerExistingToolWithTenant: (tenantId: string, key: string, tool: StructuredTool) => void;
1752
1778
  declare const getToolLattice: (key: string) => ToolLattice | undefined;
1779
+ declare const getToolClientWithTenant: (tenantId: string, key: string) => StructuredTool<_langchain_core_tools.ToolSchemaBase, any, any, any>;
1753
1780
  declare const getToolDefinition: (key: string) => ToolConfig;
1754
1781
  declare const getToolClient: (key: string) => StructuredTool<_langchain_core_tools.ToolSchemaBase, any, any, any>;
1755
1782
  declare const getAllToolDefinitions: () => ToolConfig[];
@@ -2086,6 +2113,39 @@ declare function ensureBuiltinAgentsForTenant(tenantId: string): void;
2086
2113
  declare const ROOM_COORDINATOR_KEY = "room-coordinator";
2087
2114
  declare const roomCoordinatorConfig: DeepAgentConfig;
2088
2115
 
2116
+ /**
2117
+ * Detects whether an agent exposes task management through its middleware
2118
+ * configuration.
2119
+ *
2120
+ * An agent has managed task capability when it has an enabled `task` middleware
2121
+ * whose `allowedTools` list either is unset, is empty, or explicitly includes
2122
+ * `manage_task` — i.e. the `manage_task` tool is reachable. A non-empty
2123
+ * `allowedTools` that excludes `manage_task` removes the capability.
2124
+ *
2125
+ * This mirrors the host-side `assistantHasGovernedTask` rule and is used by the
2126
+ * `task` dispatch capability gate to refuse a target agent that cannot manage
2127
+ * tasks.
2128
+ *
2129
+ * @param config - Agent configuration to inspect. `middleware` may be omitted;
2130
+ * every entry's `type`, `enabled`, and `allowedTools` are optional and treated
2131
+ * conservatively (an entry missing `enabled: true` does not grant capability).
2132
+ * @returns `true` when an enabled `task` middleware makes `manage_task`
2133
+ * reachable, otherwise `false` (including when `config` is undefined).
2134
+ *
2135
+ * @example
2136
+ * ```ts
2137
+ * agentHasManagedTaskCapability({ middleware: [{ type: "task", enabled: true }] }); // true
2138
+ * agentHasManagedTaskCapability({ middleware: [{ type: "task", enabled: false }] }); // false
2139
+ * ```
2140
+ */
2141
+ declare function agentHasManagedTaskCapability(config: {
2142
+ middleware?: Array<{
2143
+ type?: string;
2144
+ enabled?: boolean;
2145
+ allowedTools?: string[];
2146
+ }>;
2147
+ } | undefined): boolean;
2148
+
2089
2149
  /**
2090
2150
  * MemoryLatticeManager
2091
2151
  *
@@ -3927,6 +3987,42 @@ declare class InMemoryTaskStore implements TaskStore {
3927
3987
  clear(tenantId?: string): void;
3928
3988
  }
3929
3989
 
3990
+ /**
3991
+ * In-memory implementation of TaskWorkItemStore.
3992
+ * Stores work items per tenant in a Map<tenantId, Map<taskId, TaskWorkItem[]>>.
3993
+ */
3994
+ declare class InMemoryTaskWorkItemStore implements TaskWorkItemStore {
3995
+ private readonly tasks?;
3996
+ private store;
3997
+ private events;
3998
+ /** Creates a store optionally coordinated with an in-memory task store. */
3999
+ constructor(tasks?: InMemoryTaskStore | undefined);
4000
+ /**
4001
+ * Create a new work item
4002
+ */
4003
+ create(params: CreateWorkItemRequest): Promise<TaskWorkItem>;
4004
+ /** Atomically append only while the shared task snapshot matches. */
4005
+ createIfTaskSnapshot(params: CreateWorkItemRequest, snapshot: TaskMutationSnapshot): Promise<TaskWorkItem | null>;
4006
+ private append;
4007
+ /** Find an event by its tenant- and task-scoped key. */
4008
+ findByEventKey(tenantId: string, taskId: string, eventKey: string): Promise<TaskWorkItem | null>;
4009
+ /** Atomically return an existing event or create it once. */
4010
+ createIfAbsentByEventKey(params: CreateWorkItemIfAbsentRequest): Promise<TaskWorkItem>;
4011
+ /**
4012
+ * List work items matching filter criteria
4013
+ */
4014
+ list(filter: TaskWorkItemListFilter): Promise<TaskWorkItem[]>;
4015
+ /** List a bounded newest-first view of unreconciled execution results. */
4016
+ listPendingExecutionResults(params: {
4017
+ tenantId: string;
4018
+ taskId: string;
4019
+ limit: number;
4020
+ }): Promise<TaskWorkItem[]>;
4021
+ /** Lists canonical project lifecycle events with an exclusive cursor. */
4022
+ listProjectLifecycleEvents(query: ProjectLifecycleEventQuery): Promise<TaskWorkItem[]>;
4023
+ private eventMapKey;
4024
+ }
4025
+
3930
4026
  /**
3931
4027
  * InMemoryCollectionStore
3932
4028
  *
@@ -5273,92 +5369,448 @@ declare class SimpleMemoryVectorStore extends VectorStore {
5273
5369
  }
5274
5370
 
5275
5371
  /**
5276
- * McpLatticeManager
5277
- *
5278
- * MCP Lattice Manager - Manages MCP client connections.
5279
- * Each MCP server gets its own independent MultiServerMCPClient instance,
5280
- * so adding/removing servers never affects other servers' connections or tools.
5281
- * Follows the singleton pattern for global access.
5372
+ * MCP runtime types for tenant-scoped connection management.
5282
5373
  */
5283
5374
 
5284
- interface McpServerInfo {
5285
- name: string;
5286
- connection: Connection;
5375
+ /** Exact tenant + server identity used as the runtime map key. */
5376
+ interface McpServerId {
5377
+ tenantId: string;
5378
+ serverKey: string;
5287
5379
  }
5288
- interface McpLatticeInterface {
5289
- client: MultiServerMCPClient;
5290
- servers: Map<string, McpServerInfo>;
5380
+ /** Per-server connection policy. */
5381
+ interface McpConnectionOptions {
5382
+ /** Single connect/handshake timeout in ms. */
5383
+ timeoutMs?: number;
5384
+ /** Max reconnect attempts before giving up. */
5385
+ maxAttempts?: number;
5386
+ /** Base delay for exponential backoff in ms. */
5387
+ delayMs?: number;
5388
+ }
5389
+ /** Options accepted by `McpLatticeManager.registerServer`. */
5390
+ interface McpRegisterOptions extends McpConnectionOptions {
5391
+ /** Tool-name allowlist to persist on the runtime for reconnect re-registration. `undefined` = all, `[]` = none. */
5392
+ selectedTools?: string[];
5393
+ }
5394
+ /** Runtime lifecycle state of one MCP server. */
5395
+ type McpServerState = "idle" | "connecting" | "connected" | "reconnecting" | "failed";
5396
+ /** Minimal MCP client session surface used for health checks, tool listing and UI resource access. */
5397
+ interface McpClientSession {
5398
+ listTools(): Promise<{
5399
+ tools: Array<{
5400
+ name: string;
5401
+ description?: string;
5402
+ inputSchema?: unknown;
5403
+ _meta?: Record<string, unknown>;
5404
+ }>;
5405
+ }>;
5406
+ readResource?(params: {
5407
+ uri: string;
5408
+ }): Promise<{
5409
+ contents: Array<{
5410
+ uri: string;
5411
+ mimeType?: string;
5412
+ text?: string;
5413
+ blob?: string;
5414
+ _meta?: Record<string, unknown>;
5415
+ }>;
5416
+ }>;
5417
+ callTool?(params: {
5418
+ name: string;
5419
+ arguments?: Record<string, unknown>;
5420
+ }): Promise<unknown>;
5421
+ }
5422
+ /** Structural surface of MultiServerMCPClient used by the manager (injectable for tests). */
5423
+ interface McpClientLike {
5424
+ initializeConnections(): Promise<unknown>;
5425
+ getClient(serverName: string): Promise<McpClientSession | undefined>;
5426
+ getTools(serverName: string): Promise<DynamicStructuredTool[]>;
5427
+ close(): Promise<void>;
5428
+ }
5429
+ /** Factory seam so tests can inject a fake MCP client. */
5430
+ type McpClientFactory = (config: {
5431
+ mcpServers: Record<string, Connection>;
5432
+ }) => McpClientLike;
5433
+ /** Internal per-(tenant, server) runtime record. */
5434
+ interface McpServerRuntime {
5435
+ id: McpServerId;
5436
+ connection: Connection;
5437
+ options: Required<McpConnectionOptions>;
5438
+ state: McpServerState;
5439
+ client?: McpClientLike;
5440
+ toolKeys: string[];
5441
+ selectedTools?: string[];
5442
+ attempt: number;
5443
+ timer?: ReturnType<typeof setTimeout>;
5444
+ /** In-flight connect promise, used to single-flight concurrent connects. */
5445
+ connectPromise?: Promise<void>;
5291
5446
  }
5292
- declare class McpLatticeManager extends BaseLatticeManager<McpLatticeInterface> {
5447
+
5448
+ /**
5449
+ * McpLatticeManager
5450
+ *
5451
+ * Tenant-scoped MCP connection manager with transparent self-healing.
5452
+ * Each (tenantId, serverKey) pair owns an independent client, tool set and
5453
+ * reconnect state, so a failure in one never affects the others.
5454
+ */
5455
+
5456
+ /**
5457
+ * Manages tenant-scoped MCP connections with isolated failures and background
5458
+ * self-healing.
5459
+ *
5460
+ * @example
5461
+ * ```ts
5462
+ * mcpManager.registerServer("tenant-1", "github", connection);
5463
+ * await mcpManager.connectAll();
5464
+ * await mcpManager.registerToolsToToolLattice("tenant-1", "github", ["list_issues"]);
5465
+ * ```
5466
+ *
5467
+ * @remarks
5468
+ * - One MCP client per `(tenantId, serverKey)`; a failure in one server is
5469
+ * isolated from the others.
5470
+ * - Connect attempts are bounded by `timeoutMs`; failed servers retry with
5471
+ * exponential backoff up to `maxAttempts`.
5472
+ * - A periodic watchdog health-checks connected sessions and reconnects them.
5473
+ * - Concurrent connects for the same server are single-flighted; removing or
5474
+ * re-registering a server aborts any in-flight connect so it cannot
5475
+ * resurrect the runtime or republish its tools.
5476
+ */
5477
+ declare class McpLatticeManager extends BaseLatticeManager<McpClientLike> {
5293
5478
  private static _instance;
5294
- /** One MultiServerMCPClient per server, keyed by server name */
5295
- private clients;
5296
- /** Server connection configs, keyed by server name */
5297
- private servers;
5298
- /** Track registered tool keys per server for cleanup */
5299
- private registeredToolKeys;
5479
+ private runtimes;
5480
+ private clientFactory;
5481
+ private watchdog?;
5482
+ private healthCheckInFlight;
5300
5483
  static getInstance(): McpLatticeManager;
5301
5484
  protected getLatticeType(): string;
5302
- registerServers(servers: McpServerInfo[]): void;
5303
- addServer(name: string, connection: Connection): void;
5485
+ /** Test seam: override the MCP client factory. */
5486
+ configure(options?: {
5487
+ clientFactory?: McpClientFactory;
5488
+ }): void;
5489
+ private compositeKey;
5490
+ private getRuntime;
5304
5491
  /**
5305
- * Remove a server. Closes its client and unregisters its tools.
5492
+ * Whether a runtime is still the live entry for its `(tenantId, serverKey)`.
5493
+ * In-flight continuations use this to avoid publishing onto an orphaned
5494
+ * runtime that was removed or overwritten.
5306
5495
  */
5307
- removeServer(name: string): Promise<boolean>;
5496
+ private isActive;
5308
5497
  /**
5309
- * Connect all registered servers that are not yet connected.
5310
- * Each server gets its own MultiServerMCPClient instance.
5311
- * Existing connections are not affected.
5498
+ * Build the tool lattice key for an MCP tool.
5499
+ *
5500
+ * @param serverKey - MCP server business key
5501
+ * @param toolName - MCP tool name
5502
+ * @returns the tenant-agnostic tool key `mcp:{server}:{tool}`
5312
5503
  */
5313
- connect(): Promise<void>;
5504
+ static buildToolKey(serverKey: string, toolName: string): string;
5314
5505
  /**
5315
- * Reconnect a single server: close old client, create new one, re-register tools.
5506
+ * Register (or replace) an MCP server connection for a tenant.
5507
+ *
5508
+ * @param tenantId Tenant that owns the connection.
5509
+ * @param serverKey Stable server identifier within the tenant.
5510
+ * @param connection Adapter connection config.
5511
+ * @param options Optional connect timeout / retry policy overrides.
5512
+ * @remarks Re-registering an existing `(tenantId, serverKey)` clears its
5513
+ * pending reconnect timer, unregisters its tools, closes the old client
5514
+ * (fire-and-forget) and aborts any in-flight connect.
5316
5515
  */
5317
- reconnectServer(name: string): Promise<void>;
5318
- disconnect(): Promise<void>;
5319
- isConnected(): boolean;
5320
- isServerConnected(name: string): boolean;
5516
+ registerServer(tenantId: string, serverKey: string, connection: Connection, options?: McpRegisterOptions): void;
5321
5517
  /**
5322
- * Get tools from a specific server using raw MCP protocol.
5323
- * Returns native JSON schema tools — suitable for API responses.
5518
+ * Whether a server is currently registered for a tenant.
5519
+ *
5520
+ * @param tenantId Tenant that owns the connection.
5521
+ * @param serverKey Server identifier within the tenant.
5522
+ * @returns `true` if a runtime entry exists.
5324
5523
  */
5325
- getServerTools(serverName: string): Promise<McpTool[]>;
5524
+ hasServer(tenantId: string, serverKey: string): boolean;
5326
5525
  /**
5327
- * Get all tools from all servers as McpTool[] (API format).
5526
+ * Whether a server's client is connected.
5527
+ *
5528
+ * @param tenantId Tenant that owns the connection.
5529
+ * @param serverKey Server identifier within the tenant.
5530
+ * @returns `true` only when the runtime state is `connected`.
5328
5531
  */
5329
- getAllTools(): Promise<McpTool[]>;
5532
+ isServerConnected(tenantId: string, serverKey: string): boolean;
5533
+ private ensureWatchdog;
5534
+ private connectRuntime;
5330
5535
  /**
5331
- * Get raw LangChain DynamicStructuredTool objects for ToolLattice registration.
5332
- * Optionally filtered by server name.
5536
+ * Connect a single registered server, throwing on failure.
5537
+ *
5538
+ * @param tenantId Tenant that owns the connection.
5539
+ * @param serverKey Server identifier within the tenant.
5540
+ * @throws If the server is not registered or the connect attempt fails.
5541
+ * @remarks On failure the server is scheduled for background reconnect.
5333
5542
  */
5334
- getRawTools(serverName?: string): Promise<DynamicStructuredTool[]>;
5335
- getServerNames(): string[];
5336
- hasServer(name: string): boolean;
5543
+ connectServer(tenantId: string, serverKey: string): Promise<void>;
5337
5544
  /**
5338
- * Build the tool lattice key for an MCP tool.
5545
+ * Connect every registered server, isolating per-server failures.
5546
+ *
5547
+ * @remarks Failures are caught and scheduled for background reconnect, so
5548
+ * this method never rejects because one server is unreachable.
5549
+ */
5550
+ connectAll(): Promise<void>;
5551
+ /**
5552
+ * Reuse a healthy connection, otherwise (re)connect the server.
5553
+ *
5554
+ * @param tenantId Tenant that owns the connection.
5555
+ * @param serverKey Server identifier within the tenant.
5556
+ * @throws If the server is not registered or the connect attempt fails.
5557
+ * @remarks Concurrent calls are single-flighted onto one connect attempt.
5558
+ * On failure the server is scheduled for background reconnect.
5339
5559
  */
5340
- static buildToolKey(serverName: string, toolName: string): string;
5560
+ ensureConnected(tenantId: string, serverKey: string): Promise<void>;
5561
+ private scheduleReconnect;
5562
+ private reconnectRuntime;
5341
5563
  /**
5342
- * Unregister all tools for a specific server from ToolLattice.
5564
+ * Force a reconnect of a registered server, re-registering its tools.
5565
+ *
5566
+ * @param tenantId Tenant that owns the connection.
5567
+ * @param serverKey Server identifier within the tenant.
5568
+ * @throws If the server is not registered or the reconnect attempt fails.
5343
5569
  */
5344
- unregisterServerTools(serverName: string): void;
5570
+ reconnectServer(tenantId: string, serverKey: string): Promise<void>;
5571
+ private checkHealth;
5345
5572
  /**
5346
- * Register MCP tools from a specific server to Tool Lattice.
5347
- * Tools are registered with key pattern: mcp:{serverName}:{toolName}
5348
- * Only registers tools whose names are in selectedTools (if provided).
5573
+ * Remove a registered server, closing its client and unregistering its tools.
5574
+ *
5575
+ * @param tenantId Tenant that owns the connection.
5576
+ * @param serverKey Server identifier within the tenant.
5577
+ * @returns `true` if a server was removed.
5578
+ * @remarks The runtime is removed from the map before the client is closed
5579
+ * so any in-flight connect aborts instead of resurrecting it.
5349
5580
  */
5350
- registerToolsToToolLattice(serverName: string, selectedTools?: string[]): Promise<void>;
5581
+ removeServer(tenantId: string, serverKey: string): Promise<boolean>;
5351
5582
  /**
5352
- * Test a single MCP server connection using a standalone client.
5353
- * Does not affect the global mcpManager state.
5583
+ * List a connected server's tools in API format.
5584
+ *
5585
+ * @param tenantId Tenant that owns the connection.
5586
+ * @param serverKey Server identifier within the tenant.
5587
+ * @returns Native JSON-schema tool descriptors.
5588
+ * @throws If the server is not connected.
5589
+ */
5590
+ getServerTools(tenantId: string, serverKey: string): Promise<McpTool[]>;
5591
+ /**
5592
+ * Get a connected server's raw LangChain tools.
5593
+ *
5594
+ * @param tenantId Tenant that owns the connection.
5595
+ * @param serverKey Server identifier within the tenant.
5596
+ * @returns Raw `DynamicStructuredTool` instances.
5597
+ * @throws If the server is not connected.
5598
+ */
5599
+ getRawTools(tenantId: string, serverKey: string): Promise<DynamicStructuredTool[]>;
5600
+ /**
5601
+ * List a connected server's tools including raw `_meta` (for UI association).
5602
+ *
5603
+ * @param tenantId Tenant that owns the connection.
5604
+ * @param serverKey Server identifier within the tenant.
5605
+ * @returns Tool descriptors with optional `_meta`.
5606
+ * @throws If the server is not connected.
5607
+ */
5608
+ getAvailableTools(tenantId: string, serverKey: string): Promise<Array<{
5609
+ name: string;
5610
+ description: string;
5611
+ inputSchema: unknown;
5612
+ meta?: Record<string, unknown>;
5613
+ }>>;
5614
+ /**
5615
+ * Read a `ui://` resource and surface its content-item `_meta.ui` CSP/permissions.
5616
+ *
5617
+ * @param tenantId Tenant that owns the connection.
5618
+ * @param serverKey Server identifier within the tenant.
5619
+ * @param uri The `ui://` resource URI.
5620
+ * @returns Normalized UI resource payload.
5621
+ * @throws If the server is not connected or has no resources support.
5622
+ */
5623
+ readUiResource(tenantId: string, serverKey: string, uri: string): Promise<McpUiResourcePayload>;
5624
+ /**
5625
+ * Proxy a `tools/call` to a connected server (used by the gateway UI RPC route).
5626
+ *
5627
+ * @param tenantId Tenant that owns the connection.
5628
+ * @param serverKey Server identifier within the tenant.
5629
+ * @param name Tool name.
5630
+ * @param args Tool arguments.
5631
+ * @returns Raw CallToolResult.
5632
+ * @throws If the server is not connected.
5633
+ */
5634
+ callServerTool(tenantId: string, serverKey: string, name: string, args: Record<string, unknown>): Promise<unknown>;
5635
+ /**
5636
+ * Read a non-UI resource from a connected server.
5637
+ *
5638
+ * @param tenantId Tenant that owns the connection.
5639
+ * @param serverKey Server identifier within the tenant.
5640
+ * @param uri Resource URI.
5641
+ * @returns Raw ReadResourceResult.
5642
+ * @throws If the server is not connected or has no resources support.
5643
+ */
5644
+ readServerResource(tenantId: string, serverKey: string, uri: string): Promise<unknown>;
5645
+ /**
5646
+ * Unregister a server's tools from the tool lattice.
5647
+ *
5648
+ * @param tenantId Tenant that owns the connection.
5649
+ * @param serverKey Server identifier within the tenant.
5650
+ */
5651
+ unregisterServerTools(tenantId: string, serverKey: string): void;
5652
+ /**
5653
+ * Register a connected server's tools into the tool lattice.
5654
+ *
5655
+ * @param tenantId Tenant that owns the connection.
5656
+ * @param serverKey Server identifier within the tenant.
5657
+ * @param selectedTools Tool names to expose. `undefined` registers all tools;
5658
+ * an empty array registers none. Once provided, the selection is remembered
5659
+ * and reused on reconnect.
5660
+ * @throws If the server is not registered or not connected.
5661
+ * @remarks No-op if the runtime was removed/replaced while fetching tools.
5354
5662
  */
5355
- static testConnection(serverName: string, connection: Connection): Promise<{
5663
+ registerToolsToToolLattice(tenantId: string, serverKey: string, selectedTools?: string[]): Promise<void>;
5664
+ /**
5665
+ * Test a single MCP server using a standalone client.
5666
+ * Never touches manager state and always closes the client.
5667
+ */
5668
+ static testConnection(serverName: string, connection: Connection, factory?: McpClientFactory): Promise<{
5356
5669
  tools: McpTool[];
5357
5670
  latency: number;
5358
5671
  }>;
5672
+ /**
5673
+ * Stop the watchdog and close/clear every runtime.
5674
+ *
5675
+ * @remarks Intended for shutdown and test teardown: it also aborts any
5676
+ * in-flight connect because every runtime is cleared from the map.
5677
+ */
5678
+ dispose(): Promise<void>;
5359
5679
  }
5360
5680
  declare const mcpManager: McpLatticeManager;
5361
5681
 
5682
+ /**
5683
+ * Pure reconnect/backoff policy helpers for the MCP manager.
5684
+ */
5685
+ /** Default timeout (ms) for a single MCP connect/handshake attempt. */
5686
+ declare const DEFAULT_CONNECT_TIMEOUT_MS = 15000;
5687
+ /** Default number of reconnect attempts before a server is marked failed. */
5688
+ declare const DEFAULT_MAX_ATTEMPTS = 3;
5689
+ /** Default base delay (ms) for exponential reconnect backoff. */
5690
+ declare const DEFAULT_DELAY_MS = 1000;
5691
+ /** Upper bound (ms) for a single reconnect backoff delay. */
5692
+ declare const MAX_BACKOFF_MS = 30000;
5693
+ /** Interval (ms) between MCP session health checks. */
5694
+ declare const HEALTH_CHECK_INTERVAL_MS = 30000;
5695
+ /** Timeout (ms) for a single MCP session health check. */
5696
+ declare const HEALTH_CHECK_TIMEOUT_MS = 5000;
5697
+ /**
5698
+ * Exponential backoff delay: `base * 2^(attempt-1)`, capped at `max`.
5699
+ * `attempt <= 0` returns `base`.
5700
+ *
5701
+ * @param attempt Zero-based reconnect attempt index.
5702
+ * @param base Base delay in ms.
5703
+ * @param max Maximum delay in ms.
5704
+ * @returns Delay in ms for the given attempt.
5705
+ */
5706
+ declare function nextBackoffDelay(attempt: number, base?: number, max?: number): number;
5707
+ /**
5708
+ * Race an operation against a timeout. On timeout it rejects first, then runs
5709
+ * `onTimeout` (best-effort cleanup, e.g. close a leaking client) without
5710
+ * blocking the rejection and swallowing any cleanup error.
5711
+ *
5712
+ * @param operation The operation to race.
5713
+ * @param ms Timeout in ms.
5714
+ * @param onTimeout Fire-and-forget cleanup invoked once the timeout wins.
5715
+ * @returns The operation's result if it settles before the timeout.
5716
+ * @throws Error with `timed out` when `ms` elapses first, otherwise the
5717
+ * operation's own rejection.
5718
+ */
5719
+ declare function withTimeout<T>(operation: Promise<T>, ms: number, onTimeout: () => Promise<void>): Promise<T>;
5720
+
5721
+ /**
5722
+ * Convert a persisted McpServerConfig into a @langchain/mcp-adapters Connection,
5723
+ * enabling transport-level auto-recovery (stdio restart / http+sse reconnect).
5724
+ */
5725
+
5726
+ /**
5727
+ * Map an MCP server config to an adapter connection.
5728
+ *
5729
+ * @param config - persisted MCP server configuration
5730
+ * @returns adapter Connection with auto-recovery enabled
5731
+ */
5732
+ declare function convertToConnection(config: McpServerConfig): Connection;
5733
+
5734
+ /**
5735
+ * Extract an MCP Apps UI ref from a tool's raw `_meta`.
5736
+ *
5737
+ * Supports both the current nested `_meta.ui.resourceUri` shape and the
5738
+ * deprecated flat `_meta["ui/resourceUri"]` key. Only `ui://` URIs qualify.
5739
+ *
5740
+ * @param meta Tool `_meta` object (may be undefined).
5741
+ * @param serverKey Owning MCP server key.
5742
+ * @returns Normalized {@link McpUiRef} or `null` when no UI resource is declared.
5743
+ */
5744
+ declare function extractAppsRef(meta: unknown, serverKey: string): McpUiRef | null;
5745
+ /**
5746
+ * Extract legacy MCP-UI refs from a tool result's content blocks.
5747
+ *
5748
+ * Finds `resource` content blocks whose `resource.uri` is a `ui://` URI and
5749
+ * normalizes them into {@link McpUiRef} entries.
5750
+ *
5751
+ * @param content Tool result content (array of blocks, or any other shape).
5752
+ * @param serverKey Owning MCP server key.
5753
+ * @returns Matching refs; empty when none are found.
5754
+ */
5755
+ declare function extractLegacyRefs(content: unknown, serverKey: string): McpUiRef[];
5756
+ /**
5757
+ * Append the `mcp_app` content fence to a tool result, preserving its shape.
5758
+ *
5759
+ * `@langchain/mcp-adapters` commonly returns an array of content blocks
5760
+ * (text/image/audio/file). Joining only `.text` would silently drop every
5761
+ * non-text block, so instead of normalizing to a string this function appends
5762
+ * the fence as an extra text block:
5763
+ *
5764
+ * - `string` → `"<content>\n\n<fence>"` (still a string).
5765
+ * - `array` → `[...content, { type: "text", text: fence }]` (new array).
5766
+ * - single **pure text block** (`type === "text"` or `type` undefined, with no
5767
+ * `data`/`resource`) → `"<text>\n\n<fence>"` (a string, so the fence is
5768
+ * directly discoverable by string consumers).
5769
+ * - single non-text block object (e.g. an image with a text caption) →
5770
+ * `[content, { type: "text", text: fence }]` so `data`/`resource` and every
5771
+ * other field survive instead of being dropped or stringified.
5772
+ * - anything else → stringified content with the fence appended (fallback).
5773
+ *
5774
+ * @param content Existing content (string, content block, block array, or other value).
5775
+ * @param ref UI ref to encode into the fence.
5776
+ * @returns The fence appended in a shape that preserves every original block.
5777
+ */
5778
+ declare function appendUiFence(content: unknown, ref: McpUiRef): string | unknown[];
5779
+ /**
5780
+ * Wrap an MCP tool so its result carries an `mcp_app` fence for the given ref.
5781
+ *
5782
+ * The wrapped tool keeps the raw tool's `responseFormat` so `.invoke()` receives
5783
+ * a shape it expects: for `"content_and_artifact"` the wrapper always returns a
5784
+ * two-tuple (`[fencedContent, artifact]`), preserving the original artifact when
5785
+ * present; for any other format it returns the fenced content directly.
5786
+ *
5787
+ * The original content shape is preserved — a string or a single pure text
5788
+ * block stays a string, a block array gains an extra text block for the fence,
5789
+ * and a single non-text block (including one with a text caption) is wrapped in
5790
+ * an array (see {@link appendUiFence}) so non-text blocks are never dropped.
5791
+ *
5792
+ * The fence carries only the UI ref identity (server key, resource URI,
5793
+ * display mode, title). MCP rich results (`structuredContent`, `_meta`,
5794
+ * non-text blocks) stay on the raw tool result / `artifact`, which the client
5795
+ * merger normalizes into `ToolCall.ui` — the fence must not duplicate them.
5796
+ *
5797
+ * @param raw The original LangChain tool.
5798
+ * @param ref UI ref known at registration time.
5799
+ * @returns A new {@link DynamicStructuredTool} preserving the raw tool's name,
5800
+ * description, schema, `responseFormat`, `defaultConfig`, `metadata`, and
5801
+ * `returnDirect`.
5802
+ *
5803
+ * @example
5804
+ * ```ts
5805
+ * const ref = { kind: "mcp", serverKey: "weather", resourceUri: "ui://weather/app", displayMode: "inline" };
5806
+ * const fenced = wrapMcpToolWithUi(rawMcpTool, ref);
5807
+ * // fenced.invoke({ city: "Paris" }) resolves to content ending in a ```mcp_app fence
5808
+ * ```
5809
+ *
5810
+ * @remarks Only use this when a ref exists; otherwise register `raw` unchanged.
5811
+ */
5812
+ declare function wrapMcpToolWithUi(raw: DynamicStructuredTool, ref: McpUiRef): DynamicStructuredTool;
5813
+
5362
5814
  interface FsEntry {
5363
5815
  path: string;
5364
5816
  kind: string;
@@ -8108,11 +8560,14 @@ interface ProjectTaskAdmissionNotifierOptions {
8108
8560
  listenerTimeoutMs?: number;
8109
8561
  }
8110
8562
  /**
8111
- * Publishes process-local hints that newly persisted Agent Project tasks need reconciliation.
8563
+ * Publishes process-local hints that a TaskItem was explicitly dispatched to the Project queue
8564
+ * runtime.
8112
8565
  *
8113
- * @remarks Delivery is FIFO per Tenant/Task and awaits every listener settlement. Callers that
8114
- * persist tasks must invoke `publish` fire-and-forget and contain rejection because this hint is
8115
- * not durable lifecycle authority.
8566
+ * @remarks The only publisher is the `task` tool's managed-authority path (`onManagedStart`).
8567
+ * Creation and status writes never publish: a created task is a record until `task` runs it.
8568
+ * Delivery is FIFO per Tenant/Task and awaits every listener settlement. Callers that dispatch
8569
+ * must invoke `publish` fire-and-forget and contain rejection because this hint is not durable
8570
+ * lifecycle authority.
8116
8571
  */
8117
8572
  declare class ProjectTaskAdmissionNotifier {
8118
8573
  private readonly listeners;
@@ -8141,7 +8596,7 @@ declare class ProjectTaskAdmissionNotifier {
8141
8596
  private deliver;
8142
8597
  private deliverTo;
8143
8598
  }
8144
- /** Process-global Project task admission notifier used by governed creation paths. */
8599
+ /** Process-global Project task admission notifier used by the managed dispatch path. */
8145
8600
  declare const projectTaskAdmissionNotifier: ProjectTaskAdmissionNotifier;
8146
8601
 
8147
8602
  /** Exact Tenant and Project scope for collaboration mutations. */
@@ -8930,6 +9385,15 @@ interface BeliefImpactInput {
8930
9385
  key: string;
8931
9386
  after: number;
8932
9387
  basis: string;
9388
+ /**
9389
+ * Declares that `key` is intentionally a NEW belief the reporting task
9390
+ * discovered, rather than a reference to an existing owner-table key.
9391
+ *
9392
+ * When absent, the key MUST already exist in the belief owner's table;
9393
+ * a missing key without this flag is rejected (`INVALID_BELIEF_KEY`) so a
9394
+ * typo or hallucinated key can never silently pollute the shared model.
9395
+ */
9396
+ isNew?: boolean;
8933
9397
  }
8934
9398
 
8935
9399
  /** A recoverable work-item failure that occurred after a task transition committed. */
@@ -8953,6 +9417,7 @@ type LifecycleResult = {
8953
9417
  code: string;
8954
9418
  error: string;
8955
9419
  hint?: string;
9420
+ retryable?: boolean;
8956
9421
  evidenceId?: string;
8957
9422
  eventKey?: string;
8958
9423
  warnings?: LifecycleWarning[];
@@ -8975,6 +9440,7 @@ type StartLifecycleResult = {
8975
9440
  code: string;
8976
9441
  error: string;
8977
9442
  hint?: string;
9443
+ retryable?: boolean;
8978
9444
  eventKey?: string;
8979
9445
  warnings?: LifecycleWarning[];
8980
9446
  };
@@ -8994,6 +9460,11 @@ interface AgentTaskCompletionInput {
8994
9460
  actor: string;
8995
9461
  threadId?: string;
8996
9462
  sourceId?: string;
9463
+ /**
9464
+ * Completes despite a persisted `requireReview` because no HITL channel can
9465
+ * ever review it. The caller records the waiver (audit) separately.
9466
+ */
9467
+ waiveReview?: boolean;
8997
9468
  }
8998
9469
  /** Input for submitting agent completion evidence to HITL review. */
8999
9470
  interface SubmitTaskReviewInput extends AgentTaskCompletionInput {
@@ -9101,18 +9572,7 @@ interface BeliefOwnerSnapshot {
9101
9572
  workspaceId?: string;
9102
9573
  projectId?: string;
9103
9574
  };
9104
- parentUpdatedAt?: string;
9105
9575
  }
9106
- /**
9107
- * Returns whether a task belongs to the trusted, nondefault Project lifecycle.
9108
- *
9109
- * @param task Task snapshot whose durable scope and trusted origin are inspected.
9110
- * @returns True only for nondefault Project Room or Project Task origins.
9111
- */
9112
- declare function isProjectLifecycleTask(task: TaskItem): task is TaskItem & {
9113
- workspaceId: string;
9114
- projectId: string;
9115
- };
9116
9576
  /**
9117
9577
  * Parses a descriptor-safe canonical external-dependency interruption.
9118
9578
  *
@@ -9162,6 +9622,17 @@ declare class TaskLifecycleService {
9162
9622
  * @remarks Review interruptions must be approved or rejected through their evidence-bound methods.
9163
9623
  */
9164
9624
  resumeInterruption(input: ResumeInterruptionInput): Promise<LifecycleResult>;
9625
+ /**
9626
+ * Reopens a review interruption without an approval.
9627
+ *
9628
+ * @param input Task, actor, and optional thread.
9629
+ * @returns Structured resume result with an audited `review_waived` transition.
9630
+ * @remarks Explicit escape for the "review channel does not exist" case: unlike
9631
+ * `resumeInterruption`, this intentionally allows a `review_required`
9632
+ * interruption so the requester can complete with a waiver. A real HITL
9633
+ * channel keeps using `approveInterrupted`/`rejectInterrupted`.
9634
+ */
9635
+ withdrawReview(input: ResumeInterruptionInput): Promise<LifecycleResult>;
9165
9636
  /** Atomically fails an active agent task and records an idempotent status event. */
9166
9637
  failTask(input: FailTaskInput): Promise<LifecycleResult>;
9167
9638
  /** Atomically starts a pending agent task and records an idempotent status event. */
@@ -9247,11 +9718,32 @@ declare class TaskLifecycleService {
9247
9718
  private transitionAgentTask;
9248
9719
  private statusEventKey;
9249
9720
  private writeStatusEvent;
9721
+ /**
9722
+ * Publishes one committed transition for any scope-bearing task.
9723
+ *
9724
+ * @remarks `action` keeps the `ProjectTaskLifecycleAction` type for wire
9725
+ * compatibility even though publication is now generic (ADR-118 Plan A).
9726
+ * Presence-based gating means tasks with a real workspace/project publish even
9727
+ * when they are not project-sourced, including the literal `"default"` scope.
9728
+ * The gateway subscriber filters by its own project predicate; this bounded
9729
+ * window lasts until the host filter lands (ADR-118 Plan A, Task 3).
9730
+ */
9250
9731
  private notifyWinningTransition;
9251
9732
  private validateExternalDependencies;
9252
9733
  private externalDependencyReadiness;
9253
9734
  private finishExternalDependencyInterruption;
9254
9735
  private clearAuditMarker;
9736
+ /**
9737
+ * Restores a context marker removed by {@link clearAuditMarker}.
9738
+ *
9739
+ * @param task Task whose marker was cleared.
9740
+ * @param key Context key to restore.
9741
+ * @param value Marker payload to write back.
9742
+ * @returns The updated task, or the input task when the CAS loses or throws.
9743
+ * @remarks Used when publishing the completion notification fails after the
9744
+ * marker was cleared, so the transition keeps a repair marker for a later pass.
9745
+ */
9746
+ private restoreContextKey;
9255
9747
  private writeReviewActivity;
9256
9748
  private createEvent;
9257
9749
  private success;
@@ -9265,6 +9757,15 @@ declare class TaskLifecycleService {
9265
9757
  */
9266
9758
  declare function createTaskLifecycleService(deps?: TaskLifecycleServiceDeps): TaskLifecycleService;
9267
9759
 
9760
+ /**
9761
+ * Shared persistent-task execution types.
9762
+ *
9763
+ * @remarks ADR-118 follow-up: the dispatch planner and the run-only executor both
9764
+ * depend on these contracts. Keeping them in a neutral module lets the planner
9765
+ * consume them without importing the executor, which in turn imports the planner
9766
+ * value (avoiding a type-level cycle between the two).
9767
+ */
9768
+
9268
9769
  /** Describes one isolated Agent invocation for persistent task execution. */
9269
9770
  interface TaskAgentInvocation {
9270
9771
  tenantId: string;
@@ -9284,6 +9785,14 @@ interface TaskExecutionServiceDeps {
9284
9785
  workItemStore: TaskWorkItemStore;
9285
9786
  invokeAgent: (input: TaskAgentInvocation) => Promise<unknown>;
9286
9787
  resolveAgent: (tenantId: string, agentId: string) => Promise<boolean>;
9788
+ /**
9789
+ * Optional capability probe for the dispatch target.
9790
+ *
9791
+ * @remarks When provided, `start` refuses a target that cannot manage tasks
9792
+ * before routing to any authority. Omitted by callers that do not know how to
9793
+ * inspect Agent configuration.
9794
+ */
9795
+ resolveTaskCapability?: (tenantId: string, agentId: string) => Promise<boolean>;
9287
9796
  createThreadId?: () => string;
9288
9797
  }
9289
9798
  /** Identifies a persistent task, target Agent, caller, and runtime scope. */
@@ -9295,6 +9804,10 @@ interface StartTaskExecutionInput {
9295
9804
  agentId: string;
9296
9805
  actor: string;
9297
9806
  callerThreadId?: string;
9807
+ /** Trusted Project caller membership forwarded to a managed authority, when known. */
9808
+ callerMembershipId?: string;
9809
+ /** Trusted Project caller Assistant forwarded to a managed authority, when known. */
9810
+ callerAssistantId?: string;
9298
9811
  }
9299
9812
  /** Successful isolated execution observation recorded for later reconciliation. */
9300
9813
  interface TaskExecutionSuccess {
@@ -9306,6 +9819,20 @@ interface TaskExecutionSuccess {
9306
9819
  executionResultId: string;
9307
9820
  warnings?: LifecycleWarning[];
9308
9821
  }
9822
+ /**
9823
+ * Result of routing execution to a registered authority.
9824
+ *
9825
+ * @remarks The authority (e.g. the durable Project queue) runs the task
9826
+ * asynchronously; the caller observes the task itself rather than an inline
9827
+ * observation.
9828
+ */
9829
+ interface TaskExecutionManaged {
9830
+ success: true;
9831
+ managed: true;
9832
+ taskId: string;
9833
+ agentId: string;
9834
+ authorityId: string;
9835
+ }
9309
9836
  /** Typed validation, lifecycle, or Agent invocation failure. */
9310
9837
  interface TaskExecutionFailure {
9311
9838
  success: false;
@@ -9317,15 +9844,20 @@ interface TaskExecutionFailure {
9317
9844
  executionResultId?: string;
9318
9845
  blockedBy?: string[];
9319
9846
  invocationError?: string;
9847
+ /** Actionable remediation for the failure, when one is known. */
9848
+ hint?: string;
9849
+ /** Whether the caller may safely retry the same dispatch. */
9850
+ retryable?: boolean;
9320
9851
  warnings?: LifecycleWarning[];
9321
9852
  }
9322
- /** Result returned by a persistent task execution attempt. */
9323
- type TaskExecutionResult = TaskExecutionSuccess | TaskExecutionFailure;
9853
+ /** Result returned by a persistent task execution attempt or authority route. */
9854
+ type TaskExecutionResult = TaskExecutionSuccess | TaskExecutionManaged | TaskExecutionFailure;
9855
+
9324
9856
  /**
9325
9857
  * Creates a synchronous persistent-task execution service from injected stores and Agent adapters.
9326
9858
  *
9327
9859
  * @param deps Task stores, target resolution, isolated invocation, and optional thread ID generation.
9328
- * @returns A service whose `start` method validates, starts, dispatches, and records an observation.
9860
+ * @returns A service whose `start` method plans, runs, and records a persistent task dispatch.
9329
9861
  *
9330
9862
  * @example
9331
9863
  * ```ts
@@ -9339,11 +9871,434 @@ declare function createTaskExecutionService(deps: TaskExecutionServiceDeps): {
9339
9871
  start: (input: StartTaskExecutionInput) => Promise<TaskExecutionResult>;
9340
9872
  };
9341
9873
 
9874
+ /**
9875
+ * Dispatch planner for immediate persistent task execution (ADR-118 §边界修正 1).
9876
+ *
9877
+ * @remarks This module owns the L1/L3 half of dispatch: record read, scope
9878
+ * verification, record preconditions, target capability, registered authority
9879
+ * routing, target existence, and dependency/parent resolution. It performs no
9880
+ * direct task-store write (but may trigger a registered authority's managed-start
9881
+ * side effect) and never invokes an Agent. {@link prepareTaskDispatch} returns either
9882
+ * a routed managed result, a typed failure, or an {@link ImmediateDispatchPlan}
9883
+ * consumed by the run-only executor.
9884
+ */
9885
+
9886
+ /** Everything the run half needs to invoke the target and record the result. */
9887
+ interface ImmediateDispatchPlan {
9888
+ /** Tenant owning the task and the run. */
9889
+ tenantId: string;
9890
+ /** Persisted task snapshot that passed every precondition. */
9891
+ task: TaskItem;
9892
+ /** Resolved target Agent to execute the task. */
9893
+ agentId: string;
9894
+ /** Actor recorded on lifecycle and work-item writes. */
9895
+ actor: string;
9896
+ /** Owning thread identifier forwarded to the run's dispatch, when known. */
9897
+ callerThreadId?: string;
9898
+ /** In-scope parent task, when the task has one; otherwise `null`. */
9899
+ parent: TaskItem | null;
9900
+ /** In-scope, completed dependencies whose results seed the worker message. */
9901
+ completedDependencies: TaskItem[];
9902
+ }
9903
+ /**
9904
+ * Outcome of planning a dispatch, before any run-side mutation or invocation.
9905
+ *
9906
+ * @remarks A discriminated union: `managed` means a registered authority owns
9907
+ * execution, `failure` carries a typed precondition/policy rejection, and
9908
+ * `ready` carries the {@link ImmediateDispatchPlan} for immediate execution.
9909
+ */
9910
+ type DispatchPreparation = {
9911
+ kind: "managed";
9912
+ result: TaskExecutionManaged;
9913
+ } | {
9914
+ kind: "failure";
9915
+ failure: TaskExecutionFailure;
9916
+ } | {
9917
+ kind: "ready";
9918
+ plan: ImmediateDispatchPlan;
9919
+ };
9920
+ /**
9921
+ * Plans a persistent task dispatch without mutating state or invoking an Agent.
9922
+ *
9923
+ * @param deps Task store, target existence probe, and optional capability probe.
9924
+ * @param input Tenant, target Agent, actor, caller, and runtime scope.
9925
+ * @returns A managed route, a typed failure, or a ready immediate dispatch plan.
9926
+ *
9927
+ * @remarks Steps run in a fixed order so the first applicable outcome wins:
9928
+ * read/scope → status preconditions → capability → authority routing →
9929
+ * target existence → dependency validation → parent load. Only the immediate
9930
+ * path reaches the target-existence and dependency/parent steps; a managed
9931
+ * authority returns before them. This function performs no direct task-store
9932
+ * write (a managed authority's managed-start side effect may still run).
9933
+ *
9934
+ * @example
9935
+ * ```ts
9936
+ * const prepared = await prepareTaskDispatch(deps, { tenantId, taskId, agentId, actor });
9937
+ * if (prepared.kind === "ready") await run(prepared.plan);
9938
+ * ```
9939
+ */
9940
+ declare function prepareTaskDispatch(deps: Pick<TaskExecutionServiceDeps, "taskStore" | "resolveAgent" | "resolveTaskCapability">, input: StartTaskExecutionInput): Promise<DispatchPreparation>;
9941
+
9942
+ /**
9943
+ * TaskRunBridge — the single owner of "execution writes to the task record".
9944
+ *
9945
+ * @remarks ADR-118: the execution layer (L2) must not write task state inline. This bridge
9946
+ * owns dispatch (`pending → in_progress`, `beginRun`, shared by the immediate executor and
9947
+ * the managed project dispatch) and abnormal outcome convergence (`settleRun`, used by the
9948
+ * managed observer). Normal completion stays with the worker's own `manage_task` writes
9949
+ * (single-writer convention; not a lease).
9950
+ */
9951
+
9952
+ /**
9953
+ * Raised when an ownership transfer is requested without an injected task store.
9954
+ *
9955
+ * @remarks The immediate executor always supplies the store; the managed Project
9956
+ * dispatch builds the bridge with only `lifecycle` and never calls
9957
+ * {@link TaskRunBridge.transferOwner}.
9958
+ */
9959
+ declare class TaskRunBridgeStoresRequiredError extends Error {
9960
+ /** Stable machine-readable failure code. */
9961
+ readonly code: "TASK_RUN_BRIDGE_STORES_REQUIRED";
9962
+ constructor();
9963
+ }
9964
+ /**
9965
+ * Describes one dispatch attempt for a persisted task run.
9966
+ *
9967
+ * @remarks `threadId` is optional so callers that dispatch before a thread
9968
+ * exists can omit it; the lifecycle and work-item writes record it when present.
9969
+ */
9970
+ interface BeginRunInput {
9971
+ /** Tenant identifier owning the task. */
9972
+ tenantId: string;
9973
+ /** Persisted task snapshot captured before dispatch. */
9974
+ task: TaskItem;
9975
+ /** Actor recorded on the lifecycle transition and status work item. */
9976
+ actor: string;
9977
+ /** Optional owning thread identifier recorded on the run. */
9978
+ threadId?: string;
9979
+ }
9980
+ /**
9981
+ * Result of a dispatch that mutated (or confirmed) the run's starting state.
9982
+ *
9983
+ * @remarks `mutated` and `transitioned` are propagated verbatim from the
9984
+ * lifecycle winner; a `false` value is a successful no-op, not a failure.
9985
+ */
9986
+ interface BeginRunSuccess {
9987
+ success: true;
9988
+ /** Latest task snapshot after dispatch. */
9989
+ task: TaskItem;
9990
+ /** Recoverable work-item warnings emitted while starting the run. */
9991
+ warnings: LifecycleWarning[];
9992
+ /** Whether any persisted task field changed. */
9993
+ mutated: boolean;
9994
+ /** Whether this dispatch won the pending-to-in-progress transition. */
9995
+ transitioned: boolean;
9996
+ }
9997
+ /** Typed dispatch failure returned unchanged from the lifecycle or task store. */
9998
+ interface BeginRunFailure {
9999
+ success: false;
10000
+ /** Stable machine-readable failure code. */
10001
+ code: string;
10002
+ /** Human-readable failure message. */
10003
+ error: string;
10004
+ /** Optional remediation hint from the lifecycle. */
10005
+ hint?: string;
10006
+ /** Whether the caller may safely retry the dispatch. */
10007
+ retryable?: boolean;
10008
+ /** Recoverable work-item warnings emitted before the failure. */
10009
+ warnings?: LifecycleWarning[];
10010
+ }
10011
+ /** Discriminated result of {@link TaskRunBridge.beginRun}. */
10012
+ type BeginRunResult = BeginRunSuccess | BeginRunFailure;
10013
+ /**
10014
+ * Terminal-ish outcome a finished run converged to.
10015
+ *
10016
+ * @remarks `failed` with `lifecycleHandled: true` means the lifecycle already
10017
+ * converged the task and the bridge must not write again (pure no-op).
10018
+ */
10019
+ type SettleRunOutcome =
10020
+ /**
10021
+ * The agent run ended without the task's own lifecycle transition.
10022
+ *
10023
+ * @remarks This is intentionally NOT a success path: it maps to
10024
+ * `failTask("Agent execution ended without a task lifecycle transition")`
10025
+ * so a run that stopped without converging the task is recorded as a
10026
+ * failure rather than silently left active.
10027
+ */
10028
+ {
10029
+ kind: "completed";
10030
+ }
10031
+ /** Cancels the run; `summary` overrides the default cancellation summary. */
10032
+ | {
10033
+ kind: "cancelled";
10034
+ summary?: string;
10035
+ }
10036
+ /** Interrupts the run; `summary` overrides the default interruption summary. */
10037
+ | {
10038
+ kind: "interrupted";
10039
+ summary?: string;
10040
+ } | {
10041
+ kind: "failed";
10042
+ lifecycleHandled: boolean;
10043
+ error: string;
10044
+ };
10045
+ /**
10046
+ * Describes one ordinary task ownership transfer performed before dispatch.
10047
+ *
10048
+ * @remarks Transfers are last-write-wins (ADR-116): content writes do not use
10049
+ * CAS. The task must already be captured in scope before calling.
10050
+ */
10051
+ interface TransferOwnerInput {
10052
+ /** Tenant identifier owning the task. */
10053
+ tenantId: string;
10054
+ /** Persisted task snapshot captured before dispatch. */
10055
+ task: TaskItem;
10056
+ /** Agent that will own and execute the dispatched task. */
10057
+ agentId: string;
10058
+ }
10059
+ /**
10060
+ * Result of {@link TaskRunBridge.transferOwner}.
10061
+ *
10062
+ * @remarks On success, `task` is the transferred snapshot when the write
10063
+ * succeeded, or the original snapshot when the task was already owned by the
10064
+ * target or the store update returned `null`. A store write rejection is
10065
+ * returned as a typed failure so callers keep their no-throw contract.
10066
+ */
10067
+ type TransferOwnerResult = {
10068
+ success: true;
10069
+ /** Latest task snapshot after the attempted transfer. */
10070
+ task: TaskItem;
10071
+ } | {
10072
+ success: false;
10073
+ /** Stable machine-readable failure code. */
10074
+ code: string;
10075
+ /** Human-readable failure message. */
10076
+ error: string;
10077
+ };
10078
+ /** Describes one outcome convergence write for a finished run. */
10079
+ interface SettleRunInput {
10080
+ /** Tenant identifier owning the task. */
10081
+ tenantId: string;
10082
+ /** Persisted task snapshot captured before convergence. */
10083
+ task: TaskItem;
10084
+ /** Actor recorded on the lifecycle transition. */
10085
+ actor: string;
10086
+ /**
10087
+ * Optional owning thread identifier recorded on the lifecycle transition.
10088
+ *
10089
+ * @remarks Callers that converge a task without an exact thread (for example
10090
+ * the A2A adapter observing an external state) may omit it.
10091
+ */
10092
+ threadId?: string;
10093
+ /** Run outcome to converge onto the task record. */
10094
+ outcome: SettleRunOutcome;
10095
+ }
10096
+ /** Persistence and lifecycle dependencies used by {@link createTaskRunBridge}. */
10097
+ interface TaskRunBridgeDeps {
10098
+ /** Task lifecycle operations the bridge is allowed to invoke. */
10099
+ lifecycle: Pick<TaskLifecycleService, "startTask" | "failTask" | "cancelTask" | "interruptTask">;
10100
+ /**
10101
+ * Optional task store used by ownership transfer (any owner type) and the
10102
+ * non-agent (user-owned) dispatch branch. Callers that never transfer or
10103
+ * dispatch user-owned tasks (such as the Project task observer) may omit it.
10104
+ */
10105
+ taskStore?: Pick<TaskStore, "updateIfStatusAndUpdatedAt" | "update">;
10106
+ /**
10107
+ * Optional work-item store used only by the non-agent (user-owned) dispatch
10108
+ * branch. Agent-only callers may omit it.
10109
+ */
10110
+ workItemStore?: Pick<TaskWorkItemStore, "create">;
10111
+ }
10112
+ /**
10113
+ * The single owner of "execution writes to the task record".
10114
+ *
10115
+ * @remarks
10116
+ * - `beginRun` owns the `pending -> in_progress` dispatch write.
10117
+ * - `settleRun` owns outcome convergence for a finished run.
10118
+ * - Callers are responsible for running lifecycle result checks (e.g. logging,
10119
+ * notification) on the value returned by `settleRun`.
10120
+ */
10121
+ interface TaskRunBridge {
10122
+ /**
10123
+ * Transfers ordinary (non-governed) task ownership to the dispatch target.
10124
+ *
10125
+ * @param input Tenant, captured task snapshot, and target Agent identifier.
10126
+ * @returns A success carrying the transferred snapshot when the write
10127
+ * succeeds (or the original snapshot when the task is already owned by the
10128
+ * target agent, or the store update returns `null`), or a typed
10129
+ * `TASK_STORE_WRITE_FAILED` failure when the store write rejects.
10130
+ *
10131
+ * @remarks
10132
+ * - Ownership is compared on **both** fields: a `user` task whose `ownerId`
10133
+ * equals `agentId` still transfers to `ownerType: "agent"`.
10134
+ * - Writes last-write-wins (ADR-116); when `update` returns `null` the
10135
+ * dispatch proceeds with the original snapshot and {@link beginRun} decides.
10136
+ * - A store write rejection is returned as a failure, never thrown, so
10137
+ * callers keep their no-throw contract.
10138
+ * - Throws {@link TaskRunBridgeStoresRequiredError} when no task store was
10139
+ * injected.
10140
+ */
10141
+ transferOwner(input: TransferOwnerInput): Promise<TransferOwnerResult>;
10142
+ /**
10143
+ * Dispatches a run, moving a pending task to `in_progress`.
10144
+ *
10145
+ * @param input Tenant, captured task snapshot, actor, and optional thread ID.
10146
+ * @returns A success carrying the winning snapshot and transition metadata, or
10147
+ * an unchanged lifecycle/store failure.
10148
+ */
10149
+ beginRun(input: BeginRunInput): Promise<BeginRunResult>;
10150
+ /**
10151
+ * Converges a finished run's outcome onto the task record.
10152
+ *
10153
+ * @param input Tenant, captured task snapshot, actor, optional thread ID, and outcome.
10154
+ * @returns The lifecycle result for the convergence transition, or a
10155
+ * successful no-op when the run already handled its own lifecycle.
10156
+ *
10157
+ * @remarks The bridge returns only the lifecycle result. The caller still
10158
+ * owns the run `cause` it used for `outcome-${cause}` labels/telemetry; the
10159
+ * bridge does not echo or reinterpret it. This method performs the lifecycle
10160
+ * write **unconditionally**: it does no re-read/terminal/ownership precondition
10161
+ * check, so callers must keep their own guards (e.g. the observer's
10162
+ * aborted/re-read/owner+thread/terminal guard block) before calling it.
10163
+ */
10164
+ settleRun(input: SettleRunInput): Promise<LifecycleResult>;
10165
+ }
10166
+ /**
10167
+ * Creates the task/run bridge that centralizes execution writes to the task record.
10168
+ *
10169
+ * The bridge owns three writes: ownership transfer (`transferOwner`), dispatch
10170
+ * (`beginRun`), and outcome convergence (`settleRun`). All are
10171
+ * behavior-preserving extracts of the immediate executor and the Project task
10172
+ * observer so those callers stop writing the task record directly.
10173
+ *
10174
+ * @param deps Lifecycle operations plus the optional task/work-item stores used
10175
+ * by ownership transfer and the non-agent dispatch branch.
10176
+ * @returns A {@link TaskRunBridge} with `transferOwner`, `beginRun`, and
10177
+ * `settleRun`.
10178
+ *
10179
+ * @example
10180
+ * ```ts
10181
+ * const bridge = createTaskRunBridge({
10182
+ * lifecycle: createTaskLifecycleService({ taskStore, workItemStore }),
10183
+ * taskStore,
10184
+ * workItemStore,
10185
+ * });
10186
+ *
10187
+ * const transfer = await bridge.transferOwner({ tenantId, task, agentId });
10188
+ * if (!transfer.success) return transfer;
10189
+ * const started = await bridge.beginRun({ tenantId, task: transfer.task, actor, threadId });
10190
+ * ```
10191
+ *
10192
+ * @remarks
10193
+ * `transferOwner` and the non-agent (user-owned) dispatch branch require
10194
+ * `taskStore` (and `workItemStore` for the latter); callers that only dispatch
10195
+ * agent tasks (such as the Project task observer) may omit them. `settleRun`
10196
+ * only requires `lifecycle`.
10197
+ */
10198
+ declare function createTaskRunBridge(deps: TaskRunBridgeDeps): TaskRunBridge;
10199
+
9342
10200
  /** Internal authority for immediate delegated worker execution. */
9343
10201
  declare const DELEGATED_WORKER_SCOPE_TOKEN: unique symbol;
9344
10202
  /** Reports whether a run configuration contains the private delegated token key. */
9345
10203
  declare function hasDelegatedWorkerToken(runConfig: Record<string, unknown> & Partial<Record<typeof DELEGATED_WORKER_SCOPE_TOKEN, unknown>>): boolean;
9346
10204
 
10205
+ /**
10206
+ * Requested dispatch target and trusted caller identity forwarded to a managed authority.
10207
+ *
10208
+ * @remarks Core forwards the requested `agentId` and the trusted Project caller
10209
+ * it parsed from the run context. The authority owns every roster, ownership
10210
+ * transfer, and authorization decision; Core never interprets them.
10211
+ */
10212
+ interface ManagedTaskStartOptions {
10213
+ /** Requested dispatch target Agent, when the caller named one. */
10214
+ agentId?: string;
10215
+ /** Trusted Project caller membership identifier, when the run context carried one. */
10216
+ callerMembershipId?: string;
10217
+ /** Trusted Project caller Assistant identifier, when the run context carried one. */
10218
+ callerAssistantId?: string;
10219
+ }
10220
+ /**
10221
+ * Typed failure a managed authority throws to surface a stable dispatch outcome.
10222
+ *
10223
+ * @remarks Only this error type is surfaced verbatim by the immediate primitive
10224
+ * (code, message, `hint`, `retryable`). Any other thrown error is reported as
10225
+ * `TASK_EXECUTION_ENQUEUE_FAILED` so unrelated driver or store codes never leak
10226
+ * into the dispatch result.
10227
+ *
10228
+ * @example
10229
+ * ```ts
10230
+ * throw new ManagedTaskStartError("PROJECT_TASK_OWNER_INACTIVE", "Owner is not active", {
10231
+ * hint: "Dispatch to an active bot in this Project's roster.",
10232
+ * });
10233
+ * ```
10234
+ */
10235
+ declare class ManagedTaskStartError extends Error {
10236
+ /** Stable machine-readable failure code surfaced to the dispatch caller. */
10237
+ readonly code: string;
10238
+ /** Actionable remediation shown alongside the failure, when known. */
10239
+ readonly hint?: string;
10240
+ /** Whether the caller may safely retry the same dispatch, when known. */
10241
+ readonly retryable?: boolean;
10242
+ /**
10243
+ * Creates a managed dispatch failure.
10244
+ *
10245
+ * @param code Stable machine-readable failure code.
10246
+ * @param message Human-readable failure description.
10247
+ * @param options Optional remediation hint and retryability flag.
10248
+ */
10249
+ constructor(code: string, message: string, options?: {
10250
+ hint?: string;
10251
+ retryable?: boolean;
10252
+ });
10253
+ }
10254
+ /**
10255
+ * A registered owner of task execution.
10256
+ *
10257
+ * A matching authority means "this task is executed by the authority, not by
10258
+ * the immediate primitive". The registration is a composition concern: the
10259
+ * business scenario (Project Room/Task, Learning, ...) supplies the predicate
10260
+ * and messaging; the execution primitive only queries the registry.
10261
+ */
10262
+ interface ExecutionAuthority {
10263
+ /** Stable identifier of the authority (e.g. `project-lifecycle`). */
10264
+ id: string;
10265
+ /** Predicate deciding whether this authority owns the given task. */
10266
+ matches(task: TaskItem): boolean;
10267
+ /** Failure code returned by the immediate primitive when it is bypassed. */
10268
+ code?: string;
10269
+ /** Human-readable message returned alongside the code. */
10270
+ message?: string;
10271
+ /**
10272
+ * Optional hook invoked by the immediate primitive when this authority owns
10273
+ * the task. When present, `start` routes the request to the authority and
10274
+ * returns a managed (asynchronous) result instead of refusing.
10275
+ *
10276
+ * @param task Persisted task snapshot captured before routing.
10277
+ * @param options Requested target and trusted caller identity, when known.
10278
+ */
10279
+ onManagedStart?(task: TaskItem, options?: ManagedTaskStartOptions): Promise<void> | void;
10280
+ }
10281
+ /**
10282
+ * Process-global registry mapping tasks to the authority that owns their execution.
10283
+ *
10284
+ * @remarks
10285
+ * - Registration is idempotent by `id` (re-registering replaces the entry).
10286
+ * - `resolve` is order-insensitive: the first matching authority wins.
10287
+ * - A throwing predicate is treated as a non-match so a broken scenario can
10288
+ * never brick the immediate execution primitive.
10289
+ */
10290
+ declare class ExecutionAuthorityRegistry {
10291
+ private readonly authorities;
10292
+ /** Registers (or replaces) an authority. @returns An unregister function. */
10293
+ register(authority: ExecutionAuthority): () => void;
10294
+ /** Resolves the authority that owns the task's execution, if any. */
10295
+ resolve(task: TaskItem): ExecutionAuthority | undefined;
10296
+ /** Removes every registration. Intended for isolated tests. */
10297
+ clear(): void;
10298
+ }
10299
+ /** Process-global execution authority registry used by the immediate executor. */
10300
+ declare const executionAuthorityRegistry: ExecutionAuthorityRegistry;
10301
+
9347
10302
  declare const AGENT_TASK_EVENT = "agent:execute";
9348
10303
 
9349
10304
  /**
@@ -9803,12 +10758,15 @@ declare function compileSandboxPlugin(args: CompileSandboxPluginArgs): Plugin;
9803
10758
  * @property hash - Content hash of the validated manifests and their relative file paths; empty when the sandbox was unavailable.
9804
10759
  * @property plugins - Compiled plugins ready to register for the tenant.
9805
10760
  * @property diagnostics - Structured load/validation diagnostics for the snapshot.
10761
+ * @property manifests - Normalized manifests keyed by plugin type; the validated
10762
+ * source of truth for handler paths and tool caps (not the raw `plugin.json`).
9806
10763
  */
9807
10764
  interface TenantPlugins {
9808
10765
  tenantId: string;
9809
10766
  hash: string;
9810
10767
  plugins: Plugin[];
9811
10768
  diagnostics: SandboxPluginDiagnostic[];
10769
+ manifests: Record<string, SandboxPluginManifest>;
9812
10770
  }
9813
10771
  /**
9814
10772
  * Dependencies for {@link TenantPluginCatalog}.
@@ -9876,6 +10834,20 @@ declare class TenantPluginCatalog {
9876
10834
  * @returns The cached snapshot, or `undefined` when the tenant has not loaded
9877
10835
  */
9878
10836
  getCached(tenantId: string): TenantPlugins | undefined;
10837
+ /**
10838
+ * Return the validated manifest for a tenant plugin type.
10839
+ *
10840
+ * The returned manifest is the normalized output of
10841
+ * {@link validateSandboxPluginManifest}, **not** the raw `plugin.json` bytes.
10842
+ * Callers that execute tools must read handler paths and resource caps from
10843
+ * here so a cache/TOCTOU skew or a hand-edited file cannot bypass validation.
10844
+ *
10845
+ * @param tenantId - Tenant that owns the plugin
10846
+ * @param type - Plugin type (directory name)
10847
+ * @returns The normalized manifest, or `undefined` when the plugin is absent
10848
+ * or failed validation
10849
+ */
10850
+ getValidatedManifest(tenantId: string, type: string): Promise<SandboxPluginManifest | undefined>;
9879
10851
  /**
9880
10852
  * Drop the cached snapshot for a tenant.
9881
10853
  *
@@ -10191,13 +11163,16 @@ declare const documentParserPlugin: Plugin;
10191
11163
  * Semantic Metrics Middleware & Plugin (connection-backed, /api/v1).
10192
11164
  *
10193
11165
  * Exposes datasource exploration, meta publishing, and runtime query tools.
10194
- * Credentials are resolved via the framework-injected `_resolvedConnections`.
11166
+ * Credentials are resolved by the plugin's own tools at invocation time from
11167
+ * the tenant-scoped Connection Store (see `resolveMetricsClientFromSelector`).
10195
11168
  */
10196
11169
 
10197
11170
  /**
10198
11171
  * Create the Semantic Metrics middleware exposing three action-dispatch tools.
10199
11172
  *
10200
- * @param config - Plugin config; reads `config._resolvedConnections` (framework-injected).
11173
+ * @param config - Plugin config; reads `connections`/`connectAll` (resolved per
11174
+ * invocation from the tenant-scoped Connection Store). Resource scope is owned
11175
+ * by the connection's own `selectedEntities`.
10201
11176
  * @returns Middleware with the datasource/meta/runtime tool set.
10202
11177
  */
10203
11178
  declare function createSemanticMetricsMiddleware(config: Record<string, unknown>): AgentMiddleware;
@@ -10337,6 +11312,76 @@ interface UnknownToolHandlerConfig {
10337
11312
  */
10338
11313
  declare function createUnknownToolHandlerMiddleware(config?: UnknownToolHandlerConfig): AgentMiddleware;
10339
11314
 
11315
+ /**
11316
+ * Repeated Tool Call Breaker Middleware
11317
+ *
11318
+ * Model-agnostic loop guard. Counts consecutive identical tool-call signatures
11319
+ * in graph state (`afterModel`), blocks the call with a corrective reminder at
11320
+ * the warn threshold (`wrapToolCall`), and throws a `RepeatedToolCallError` to
11321
+ * hard-stop the run at the stop threshold.
11322
+ *
11323
+ * This protects runs from models that re-issue the exact same call (same tool,
11324
+ * same arguments) without incorporating the previous result — e.g. a deepseek
11325
+ * agent issuing the identical `read_eval get_run_results` call dozens of times.
11326
+ *
11327
+ * @example
11328
+ * ```ts
11329
+ * middlewares.push(createRepeatedToolCallBreakerMiddleware({ warnThreshold: 3, stopThreshold: 5 }));
11330
+ * ```
11331
+ *
11332
+ * @remarks
11333
+ * Thresholds are supplied at construction time; callers typically read them from
11334
+ * env via `readLoopBreakerConfig`. A threshold of `0` disables the guard.
11335
+ */
11336
+
11337
+ /** Raised when a run keeps issuing the identical tool call past the stop threshold. */
11338
+ declare class RepeatedToolCallError extends Error {
11339
+ readonly toolName: string | undefined;
11340
+ readonly count: number;
11341
+ readonly stopThreshold: number;
11342
+ readonly argsPreview: string;
11343
+ constructor(toolName: string | undefined, count: number, stopThreshold: number, argsPreview: string);
11344
+ }
11345
+ /** Thresholds for the loop guards. A value of `0` disables that guard. */
11346
+ interface LoopBreakerConfig {
11347
+ /** Call count at which repeated identical calls are blocked with a reminder. */
11348
+ repeatWarn: number;
11349
+ /** Call count at which a `RepeatedToolCallError` is thrown. */
11350
+ repeatStop: number;
11351
+ /** Per-run tool-call budget for the global limit middleware. */
11352
+ runLimit: number;
11353
+ /** Per-run cap for the `skill` tool, to stop skill-load enumeration (0 disables). */
11354
+ skillRunLimit: number;
11355
+ }
11356
+ /** Read loop-breaker thresholds from env. 0 disables a guard. Invalid values fall back to defaults. */
11357
+ declare function readLoopBreakerConfig(env?: NodeJS.ProcessEnv): LoopBreakerConfig;
11358
+ /** Construction options for {@link createRepeatedToolCallBreakerMiddleware}. */
11359
+ interface RepeatedToolCallBreakerOptions {
11360
+ /**
11361
+ * Call count at which the repeated call is blocked with a reminder (default 3).
11362
+ * A positive value is floored to `2` so the first call of every signature always
11363
+ * executes (`warnThreshold: 1` cannot brick all tool use). A value `<= 0` disables
11364
+ * the blocking tier while counting and the stop throw stay active.
11365
+ */
11366
+ warnThreshold?: number;
11367
+ /**
11368
+ * Call count at which a `RepeatedToolCallError` is thrown (default 5).
11369
+ * Construction coerces this to at least 1; a value `<= 0` disables the whole guard at install time.
11370
+ */
11371
+ stopThreshold?: number;
11372
+ }
11373
+ /**
11374
+ * Warn-and-block, then hard-stop, when the model keeps issuing the identical tool call.
11375
+ *
11376
+ * @param options - Threshold configuration; see {@link RepeatedToolCallBreakerOptions}.
11377
+ * A positive `warnThreshold` has an effective minimum of `2`, so the first call of
11378
+ * every signature always executes; `warnThreshold <= 0` disables the block tier
11379
+ * (counting and the hard stop still apply); `stopThreshold <= 0` is treated as
11380
+ * disabled at install time (callers gate on it).
11381
+ * @returns A LangChain `AgentMiddleware` that can be pushed onto the middleware chain.
11382
+ */
11383
+ declare function createRepeatedToolCallBreakerMiddleware(options?: RepeatedToolCallBreakerOptions): AgentMiddleware;
11384
+
10340
11385
  /** Describes how a tool argument selects a capability-scoped resource. */
10341
11386
  interface CapabilityResourceSelector {
10342
11387
  /** Tool argument containing the selected resource key. */
@@ -10794,6 +11839,39 @@ declare class ConnectionRegistry {
10794
11839
  private static ensureStore;
10795
11840
  }
10796
11841
 
11842
+ /** A plugin connection resolved to its stored key and config. */
11843
+ interface ResolvedPluginConnection {
11844
+ /** Connection key (unique within `(tenantId, type)`). */
11845
+ key: string;
11846
+ /** Stored connection config (credentials, resource selection, …). */
11847
+ config: Record<string, unknown>;
11848
+ }
11849
+ /** Run-scoped identity needed to resolve a plugin's connections. */
11850
+ interface PluginConnectionScope {
11851
+ /** Authoritative tenant; resolution is skipped when absent. */
11852
+ tenantId?: string;
11853
+ }
11854
+ /**
11855
+ * Resolve the connections selected by a plugin's `connections` / `connectAll`
11856
+ * config against the tenant-scoped Connection Store.
11857
+ *
11858
+ * @param type - Plugin type (`Plugin.meta.type` = `ConnectionEntry.type`).
11859
+ * @param config - Plugin middleware config carrying `connections` and/or `connectAll`.
11860
+ * @param scope - Run-scoped identity; only `tenantId` is used.
11861
+ * @returns The matching `{ key, config }` entries in registry order; empty when
11862
+ * no tenant, no selection, or nothing matches (foreign tenant/type filtered out).
11863
+ * @remarks
11864
+ * - `connectAll: true` lists every connection of the type for the tenant.
11865
+ * - Explicit `connections` are looked up individually; missing keys are dropped.
11866
+ * - Callers are trusted in-process plugin code; the resolver does not verify that
11867
+ * `type` is the caller's own plugin type. Plugins must pass their own
11868
+ * `meta.type` — treating this as a tenant-wide credential read is out of contract.
11869
+ */
11870
+ declare function resolvePluginConnections(type: string, config: {
11871
+ connections?: unknown;
11872
+ connectAll?: unknown;
11873
+ }, scope: PluginConnectionScope): Promise<ResolvedPluginConnection[]>;
11874
+
10797
11875
  /**
10798
11876
  * Export/Import shared type definitions.
10799
11877
  *
@@ -11157,4 +12235,4 @@ declare function parseDirectRoomType(projectId: string): "human" | "bot" | null;
11157
12235
  */
11158
12236
  declare function isDirectRoom(projectId: string): boolean;
11159
12237
 
11160
- 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, BUILTIN_PLUGINS, BUILTIN_SKILLS, type BackendFactory, type BackendProtocol, 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, type DatabaseConfig, type DatabaseType, DaytonaInstance, DaytonaProvider, type DaytonaProviderConfig, DefaultScheduleClient, DelegatedScopeNotQueueableError, type DeleteResult, DependencyResolver, DuplicateProjectRoomMessageIdempotencyKeyError, E2BInstance, E2BProvider, type E2BProviderConfig, EMPTY_CONTENT_WARNING, type EditResult, type EmbeddingsInfo, type EmbeddingsLatticeInterface, EmbeddingsLatticeManager, type EnsureMicrosandboxInput, type EvalRunService, type ExportBundle, type ExportContext, type ExportJob, type ExportableEntity, type ExportableEntityDefinition, ExportableEntityRegistry, type ExportableFile, type ExportableTypeInfo, type ExternalDependencyInterruption, type FileData, type FileInfo, FileSystemSkillStore, type FileSystemSkillStoreOptions, FilesystemBackend, type FsEntry, type GrepMatch, type IMessageQueueStore, type IMetricsServerClient, type ISqlDatabase, IdRemapper, type ImportApplyResolution, type ImportApplyResult, type ImportEntityResult, type ImportEntityStatus, type ImportPreviewResult, InMemoryA2AApiKeyStore, InMemoryAgentWebAppStore, InMemoryAssistantStore, InMemoryBindingStore, InMemoryCapabilityBundleStore, InMemoryChannelInstallationStore, InMemoryChunkBuffer, InMemoryCollectionStore, InMemoryDatabaseConfigStore, InMemoryMailboxStore, InMemoryMenuStore, InMemoryOpenAuditStore, InMemoryProjectBotMembershipStore, InMemoryProjectMembershipStore, InMemoryProjectRoomCoordinator, InMemoryProjectRoomMessageStore, InMemoryProjectRoomReadStateStore, InMemoryProjectRoomStore, InMemoryTaskListStore, InMemoryTaskStore, 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, MAX_LINE_LENGTH, MAX_PACK_ENTRIES, MAX_PACK_FILE_BYTES, MAX_PACK_TOTAL_BYTES, type MailboxMessage, type MailboxStore, type ManifestValidationResult, type McpLatticeInterface, McpLatticeManager, type McpServerInfo, 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, 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 ReconcileTaskDescriptionInput, type RejectInterruptedTaskInput, RemoteSandboxInstance, RemoteSandboxProvider, type RemoteSandboxProviderConfig, type ReplyReadyEvent, type Resolution, type ResolutionAction, type ResolveAgentFn, type ResolvedConfig, 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 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 TaskExecutionResult, type TaskExecutionServiceDeps, type TaskExecutionSuccess, type TaskLifecycleListener, type TaskLifecycleNotification, TaskLifecycleNotifier, TaskLifecycleService, type TaskLifecycleServiceDeps, type TaskListStore, type TaskResponseParseResult, 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 TrustedAgentMessageDispatcher, type TrustedMessageOptions, type UnknownToolHandlerConfig, type ValidateManifestArgs, type VectorStoreLatticeInterface, VectorStoreLatticeManager, type VectorStoreProviderLattice, VectorStoreProviderManager, VolumeFilesystem, type VolumeFsClient, type WorkflowValidationError, type WriteResult, abortWorkflowRun, agentInstanceManager, agentLatticeManager, appendReconciliationWarning, buildGrepResultsDict, buildInput, buildNamedVolumeName, buildRemotePackDirectoryCommand, buildSandboxMetadataEnv, buildSkillFile, buildStateAnnotation, buildTableName, buildTaskMutationFallback, buildTaskNormalizationFallback, checkEmptyContent, clearEncryptionKeyCache, clearEvalRunService, collectionLatticeManager, compileInternal, compileSandboxPlugin, compileWorkflow, computeSandboxName, configureStores, connectAllChannels, createAgentNode, createAgentTeam, createCapabilityGuardMiddleware, createExecuteSqlQueryTool, createFileData, createInfoSqlTool, createListMetricsDataSourcesTool, createListMetricsServersTool, createListTablesSqlTool, createMapNode, createModelSelectorMiddleware, createNodeHandler, createProjectRoomMiddleware, createProjectTaskOwnerPolicy, createProjectTaskReassignmentAuthorizer, createQueryCheckerSqlTool, createQueryMetricDefinitionTool, createQueryMetricsListTool, createQuerySemanticMetricDataTool, createQuerySqlTool, createQueryTableDefinitionTool, createQueryTablesListTool, createResourceAddress, createSandboxProvider, createSandboxResolver, createSchedulerMiddleware, createSemanticMetricsMiddleware, createSharePayload, createTaskExecutionService, createTaskLifecycleService, createTaskMiddleware, createTeamMiddleware, createTeammateTools, createTrustedAgentMessageDispatcher, createUnknownToolHandlerMiddleware, createWidgetMiddleware, decrypt, describeCronExpression, documentLearningPlugin, documentParserPlugin, embeddingsLatticeManager, encrypt, ensureBuiltinAgentsForTenant, ensurePluginSkillInSandbox, evaluateLatticeCaseWithLogs, eventBus, eventBus as eventBusDefault, extractFetcherError, 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, getToolDefinition, getToolLattice, getVectorStoreClient, getVectorStoreLattice, getVectorStoreProvider, getWorkflowSignal, globSearchFiles, grepMatchesFromFiles, grepSearchFiles, hasChunkBuffer, hasDelegatedWorkerToken, hasRuntimeCapabilityPolicy, invokeWithRetry, isBuiltInSkill, isDirectRoom, isPluginSkillAuthorizedInSandbox, isPluginSkillManagedInSandbox, isProjectLifecycleTask, isUsingDefaultKey, isValidCronExpression, isValidSandboxName, isValidSkillName, jsonSchemaToZod, listCollectionEntries, listSandboxProviderTypes, loggerLatticeManager, mcpManager, mergeCapabilityBundles, mergePluginSkills, mergePluginSources, metricsServerManager, modelLatticeManager, normalizeSandboxName, ownTaskResponseField, parallelLimit, parseCronExpression, parseDirectRoomType, parseExternalDependency, parseJudgeVerdict, parsePackSize, parseSkillFrontmatter, parseTaskResponse, parseYaml, performStringReplacement, postProcessTaskMutationResponse, projectMutationMutex, projectRoomPlugin, projectTaskAdmissionNotifier, queueLatticeManager, registerAgentLattice, registerAgentLatticeWithTenant, registerAgentLattices, registerCheckpointSaver, registerChunkBuffer, registerEmbeddingsLattice, registerExistingTool, registerLoggerLattice, registerModelLattice, registerQueueLattice, registerSTTModelLattice, registerSandboxProviderType, registerScheduleLattice, registerStoreLattice, registerTeammateAgent, registerToolLattice, registerVectorStoreLattice, registerVectorStoreProvider, registerWorkflowRun, removeCollectionVectorStore, renderTemplate, resolveEnabledPluginSkill, resolveJudgeModelKey, resolvePath, resolveSandboxPluginConnections, resolveTenantPluginSkill, roomCoordinatorConfig, runRemotePackDirectory, safeTaskResponseId, sandboxLatticeManager, sanitizeToolCallId, scheduleLatticeManager, semanticMetricsPlugin, serializePluginMeta, serializeTaskMutationSuccess, serializeTaskNormalizationFallback, serializeTaskReadResponse, setBindingRegistry, setEvalRunService, setMenuRegistry, setSandboxPluginCatalog, skillLatticeManager, sqlDatabaseManager, storeLatticeManager, sttModelLatticeManager, taskLifecycleNotifier, toJsonSchema, toSafeStateExpr, toolLatticeManager, truncateIfTooLong, unregisterTeammateAgent, unregisterWorkflowRun, updateFileData, validateAgentInput, validateCapabilityBundleInput, validateDSL, validateEncryptionKey, validatePackSourcePath, validatePath, validateRelativePath, validateSandboxPluginManifest, validateSkillName, validateToolInput, vectorStoreLatticeManager, vectorStoreProviderManager };
12238
+ 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, 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 ExternalDependencyInterruption, 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, 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 ReconcileTaskDescriptionInput, 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, 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, type ValidateManifestArgs, type VectorStoreLatticeInterface, VectorStoreLatticeManager, type VectorStoreProviderLattice, VectorStoreProviderManager, VolumeFilesystem, type VolumeFsClient, type WorkflowValidationError, type WriteResult, abortWorkflowRun, agentHasManagedTaskCapability, agentInstanceManager, agentLatticeManager, appendReconciliationWarning, appendUiFence, 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, createSemanticMetricsMiddleware, 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, isPluginSkillAuthorizedInSandbox, isPluginSkillManagedInSandbox, isUsingDefaultKey, isValidCronExpression, isValidSandboxName, isValidSkillName, jsonSchemaToZod, listCollectionEntries, listSandboxProviderTypes, loggerLatticeManager, mcpManager, mergeCapabilityBundles, mergePluginSkills, mergePluginSources, metricsServerManager, modelLatticeManager, nextBackoffDelay, normalizeSandboxName, ownTaskResponseField, parallelLimit, parseCronExpression, parseDirectRoomType, parseExternalDependency, parseJudgeVerdict, parsePackSize, parseSkillFrontmatter, parseTaskResponse, parseYaml, performStringReplacement, postProcessTaskMutationResponse, prepareTaskDispatch, projectMutationMutex, projectRoomPlugin, projectTaskAdmissionNotifier, queueLatticeManager, readLoopBreakerConfig, registerAgentLattice, registerAgentLatticeWithTenant, registerAgentLattices, registerCheckpointSaver, registerChunkBuffer, registerEmbeddingsLattice, registerExistingTool, registerExistingToolWithTenant, registerLoggerLattice, registerModelLattice, registerQueueLattice, registerSTTModelLattice, registerSandboxProviderType, registerScheduleLattice, registerStoreLattice, registerTeammateAgent, registerToolLattice, registerVectorStoreLattice, registerVectorStoreProvider, registerWorkflowRun, removeCollectionVectorStore, renderTemplate, resolveEnabledPluginSkill, resolveJudgeModelKey, resolvePath, resolvePluginConnections, resolveSandboxPluginConnections, resolveTenantPluginSkill, roomCoordinatorConfig, runRemotePackDirectory, safeTaskResponseId, sandboxLatticeManager, sanitizeToolCallId, scheduleLatticeManager, semanticMetricsPlugin, serializePluginMeta, serializeTaskMutationSuccess, serializeTaskNormalizationFallback, serializeTaskReadResponse, setBindingRegistry, setEvalRunService, setMenuRegistry, setSandboxPluginCatalog, skillLatticeManager, sqlDatabaseManager, storeLatticeManager, sttModelLatticeManager, taskLifecycleNotifier, toJsonSchema, toSafeStateExpr, toolLatticeManager, truncateIfTooLong, unregisterTeammateAgent, unregisterWorkflowRun, updateFileData, validateAgentInput, validateCapabilityBundleInput, validateDSL, validateEncryptionKey, validatePackSourcePath, validatePath, validateRelativePath, validateSandboxPluginManifest, validateSkillName, validateToolInput, vectorStoreLatticeManager, vectorStoreProviderManager, withTimeout, wrapMcpToolWithUi };