@axiom-lattice/protocols 4.1.2 → 4.1.3

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.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/AgentLatticeProtocol.ts","../src/MemoryLatticeProtocol.ts","../src/UILatticeProtocol.ts","../src/QueueLatticeProtocol.ts","../src/ScheduleLatticeProtocol.ts","../src/LoggerLatticeProtocol.ts","../src/MessageProtocol.ts","../src/McpLatticeProtocol.ts","../src/WorkspaceStoreProtocol.ts","../src/BindingProtocol.ts","../src/TaskWorkItemProtocol.ts","../src/TaskBeliefProtocol.ts","../src/AgentWebAppRuntimeProtocol.ts","../src/ExactDataSnapshot.ts","../src/ProjectRoomRealtimeProtocol.ts","../src/TrustedRunContextProtocol.ts"],"sourcesContent":["/**\n * Protocols\n *\n * 导出所有Lattice协议接口,为整个系统提供统一的接口规范\n */\n\nexport * from \"./BaseLatticeProtocol\";\nexport * from \"./ToolLatticeProtocol\";\nexport * from \"./ModelLatticeProtocol\";\nexport * from \"./AgentLatticeProtocol\";\nexport * from \"./MemoryLatticeProtocol\";\nexport * from \"./UILatticeProtocol\";\nexport * from \"./QueueLatticeProtocol\";\nexport * from \"./ScheduleLatticeProtocol\";\nexport * from \"./EmbeddingsLatticeProtocol\";\nexport * from \"./STTModelLatticeProtocol\";\nexport * from \"./VectorStoreLatticeProtocol\";\nexport * from \"./LoggerLatticeProtocol\";\nexport * from \"./MessageProtocol\";\nexport * from \"./ThreadStoreProtocol\";\nexport * from \"./AssistantStoreProtocol\";\nexport * from \"./SkillLatticeProtocol\";\nexport * from \"./SkillStoreProtocol\";\nexport * from \"./McpLatticeProtocol\";\nexport * from \"./WorkspaceStoreProtocol\";\nexport * from \"./TenantStoreProtocol\";\nexport * from \"./DatabaseConfigStoreProtocol\";\nexport * from \"./ConnectionStoreProtocol\";\nexport * from \"./ChannelInstallationStoreProtocol\";\nexport * from \"./MetricsServerConfigStoreProtocol\";\nexport * from \"./McpServerConfigStoreProtocol\";\nexport * from \"./UserStoreProtocol\";\nexport * from \"./UserTenantLinkProtocol\";\nexport * from \"./WorkflowTrackingStoreProtocol\";\nexport * from \"./BindingProtocol\";\nexport * from \"./CollectionStoreProtocol\";\nexport * from \"./VectorStoreProviderProtocol\";\nexport * from \"./MenuProtocol\";\nexport * from \"./EvalStoreProtocol\";\nexport * from \"./TaskStoreProtocol\";\nexport * from \"./TaskWorkItemProtocol\";\nexport * from \"./TaskBeliefProtocol\";\n\nexport * from \"./LocalA2ATemplateConfig\";\nexport * from \"./ChannelAdapterProtocol\";\nexport * from \"./A2AProtocol\";\nexport * from \"./A2AApiKeyStoreProtocol\";\nexport * from \"./ConversationStoreProtocol\";\nexport * from \"./AgentWebAppStoreProtocol\";\nexport * from \"./AgentWebAppRuntimeProtocol\";\nexport * from \"./CapabilityBundleStoreProtocol\";\nexport * from \"./CapabilityRuntimeProtocol\";\nexport * from \"./ProjectRoomProtocol\";\nexport * from \"./ProjectRoomStoreProtocol\";\nexport * from \"./ProjectMembershipStoreProtocol\";\nexport * from \"./ProjectBotMembershipStoreProtocol\";\nexport * from \"./ProjectRoomMessageStoreProtocol\";\nexport * from \"./ExactDataSnapshot\";\nexport * from \"./ProjectRoomRealtimeProtocol\";\n\n// Workflow DSL (concise, public API)\nexport * from \"./WorkflowDSL\";\n\n// Internal DSL (expanded IR, internal use)\nexport * from \"./InternalDSL\";\n\nexport * from \"./SandboxResourceProtocol\";\n\n// Plugin system\nexport type {\n Plugin,\n PluginMeta,\n PluginMetaOutput,\n PluginConnection,\n PluginConnectionFieldSchema,\n PluginConnectionTestResult,\n PluginDiscoveredResource,\n PluginContext,\n PluginToolMeta,\n PluginSkillResource,\n PluginSkillDefinition,\n PluginStandardConnectionConfig,\n PluginMiddlewareFactory,\n} from \"./PluginProtocol\";\n\n// 导出通用类型\nexport * from \"./types\";\nexport * from \"./TrustedRunContextProtocol\";\n","/**\n * AgentLatticeProtocol\n *\n * 智能体Lattice的协议,定义了智能体的行为和组合方式\n */\n\nimport { CompiledStateGraph } from \"@langchain/langgraph\";\nimport { ZodObject } from \"zod\";\nimport { BaseLatticeProtocol } from \"./BaseLatticeProtocol\";\n\n/**\n * 智能体类型枚举\n */\nexport enum AgentType {\n REACT = \"react\",\n DEEP_AGENT = \"deep_agent\",\n TEAM = \"team\",\n PROCESSING = \"processing\",\n /** Remote A2A agent — delegates to an external A2A-compatible server */\n A2A_REMOTE = \"a2a_remote\",\n /** Workflow agent — compiled from YAML DSL into a LangGraph StateGraph */\n WORKFLOW = \"workflow\",\n}\n\n/**\n * Runtime configuration that will be injected into LangGraphRunnableConfig.configurable\n * Tools can access these values via config.configurable.runConfig\n */\nexport interface AgentRunConfig {\n /** Database key for SQL tools (registered via sqlDatabaseManager) */\n databaseKey?: string;\n /** Any additional runtime configuration */\n [key: string]: any;\n}\n\n/**\n * Base agent configuration shared by all agent types\n */\ninterface BaseAgentConfig {\n key: string; // Unique key\n name: string; // Name\n description: string; // Description\n prompt: string; // Prompt\n /**\n * Key of the parent agent to inherit configuration from.\n * When set, unspecified fields are inherited from the parent agent's config.\n * Child's explicitly set fields override the parent's.\n */\n extendsAgent?: string;\n schema?: ZodObject<any, any, any, any, any>; // Input validation schema\n modelKey?: string; // Model key to use\n /**\n * Runtime configuration to inject into tool execution context\n * Will be available in tools via config.configurable.runConfig\n */\n runConfig?: AgentRunConfig;\n skillCategories?: string[];\n middleware?: AgentMiddlewareConfig[];\n /**\n * Structured output response format for the agent.\n * Supports Zod schema (z.object({...})), JSON Schema object ({ type: \"object\", properties: {...} }),\n * providerStrategy(), toolStrategy(), and other formats accepted by the underlying model.\n *\n * @example\n * ```ts\n * // Zod schema\n * responseFormat: z.object({ name: z.string(), age: z.number() })\n *\n * // JSON Schema\n * responseFormat: { type: \"object\", properties: { name: { type: \"string\" } }, required: [\"name\"] }\n * ```\n */\n responseFormat?: any;\n /**\n * Arbitrary metadata as string-to-string map (optional).\n * Mirrors the skill metadata convention. Useful for:\n * - trust tier (e.g. verified: \"human-reviewed\" | \"machine-confirmed\")\n * - version tracking (e.g. version: \"1.2\")\n * - provenance (e.g. source material, learning run id)\n */\n metadata?: Record<string, string>;\n}\n\nexport type AvailableModule = \"filesystem\" | \"code_eval\" | \"browser\";\n\nexport interface SandboxMiddlewareConfig {\n vmIsolation: \"agent\" | \"project\" | \"global\";\n modules: AvailableModule[];\n}\n\nexport interface CodeEvalMiddlewareConfig {\n vmIsolation: \"agent\" | \"project\" | \"global\";\n timeout: number;\n memoryLimit: number;\n}\n\nexport interface BrowserMiddlewareConfig {\n vmIsolation: \"agent\" | \"project\" | \"global\";\n headless: boolean;\n}\n\nexport interface SqlMiddlewareConfig {\n databaseKeys?: string[];\n}\n\nexport interface MetricsMiddlewareConfig {\n /** List of configured metrics server keys */\n serverKeys: string[];\n /** Optional descriptions for each server */\n serverDescriptions?: Record<string, string>;\n}\n\nexport interface SchedulerMiddlewareConfig {\n defaultMaxRetries?: number;\n}\n\nexport interface CollectionMiddlewareConfig {\n /** List of configured collection keys */\n collectionKeys: string[];\n /**\n * When true, all collections for the tenant are available.\n * When false or undefined, only collections in collectionKeys are used.\n */\n connectAll?: boolean;\n}\n\nexport type MiddlewareType = \"filesystem\" | \"code_eval\" | \"browser\" | \"sql\" | \"skill\" | \"http\" | \"custom\" | \"metrics\" | \"ask_user_to_clarify\" | \"widget\" | \"claw\" | \"date\" | \"scheduler\" | \"topology\" | \"task\" | \"collection\" | string;\n\nexport interface AgentMiddlewareConfig {\n id: string;\n type: MiddlewareType;\n name: string;\n description: string;\n enabled: boolean;\n /** 可选:限制该中间件暴露的工具列表。不配置则默认暴露所有工具 */\n allowedTools?: string[];\n config: SandboxMiddlewareConfig | CodeEvalMiddlewareConfig | BrowserMiddlewareConfig | SqlMiddlewareConfig | MetricsMiddlewareConfig | ClawMiddlewareConfig | CollectionMiddlewareConfig | SchedulerMiddlewareConfig | Record<string, any>;\n}\n\n/**\n * Bootstrap file configuration\n * Defines default content for project bootstrap files\n */\nexport interface BootstrapFilesConfig {\n /** Default content for AGENTS.md - operating instructions */\n agents?: string;\n /** Default content for SOUL.md - personality and tone */\n soul?: string;\n /** Default content for IDENTITY.md - agent identity */\n identity?: string;\n /** Default content for USER.md - user preferences */\n user?: string;\n /** Default content for TOOLS.md - tool documentation */\n tools?: string;\n /** Default content for BOOTSTRAP.md - first-run tasks */\n bootstrap?: string;\n}\n\n/**\n * Claw Middleware 配置\n * 用于配置 bootstrap 文件管理行为\n */\nexport interface ClawMiddlewareConfig {\n /** 是否启用 bootstrap 文件注入(默认:true) */\n injectBootstrapFiles?: boolean;\n /** 自定义 bootstrap 文件内容 */\n bootstrapFiles?: BootstrapFilesConfig;\n}\n\n\n/**\n * REACT agent configuration\n */\nexport interface ReactAgentConfig extends BaseAgentConfig {\n type: AgentType.REACT;\n tools?: string[]; // Tool list\n}\n\n/**\n * DEEP_AGENT configuration - only this type supports subAgents\n */\nexport interface DeepAgentConfig extends BaseAgentConfig {\n type: AgentType.DEEP_AGENT;\n tools?: string[]; // Tool list\n subAgents?: string[]; // Sub-agent list (unique to DEEP_AGENT)\n internalSubAgents?: AgentConfig[]; // Internal sub-agent list (unique to DEEP_AGENT)\n}\n\n/**\n * PROCESSING agent configuration — workflow orchestration with topology enforcement.\n * Replaces todoListMiddleware with topologyMiddleware.\n */\nexport interface ProcessingAgentConfig extends BaseAgentConfig {\n type: AgentType.PROCESSING;\n tools?: string[];\n subAgents?: string[];\n internalSubAgents?: AgentConfig[];\n}\n\n/**\n * Team teammate configuration -- describes an available teammate.\n */\nexport interface TeamTeammateConfig {\n /** Unique name for this teammate (used as agent ID) */\n name: string;\n /** Role category (e.g. \"research\", \"writing\", \"review\") */\n role: string;\n /** Human-readable description of what this teammate does */\n description: string;\n /** Tool keys this teammate has access to */\n tools?: string[];\n /** Custom system prompt for this teammate */\n prompt?: string;\n /** Model key override for this teammate */\n modelKey?: string;\n}\n\n/**\n * TEAM agent configuration -- a team lead that dynamically creates teammates.\n * Teammates are created on-the-fly from create_team tool input (name, role, description).\n */\nexport interface TeamAgentConfig extends BaseAgentConfig {\n type: AgentType.TEAM;\n /** Tool keys available to the team lead */\n tools?: string[];\n /** Maximum number of teammates running concurrently */\n maxConcurrency?: number;\n /**\n * Schedule lattice key for polling task list / mailbox.\n * When set, teammates use ScheduleLattice for periodic polling instead of event-driven wait.\n */\n scheduleLatticeKey?: string;\n /** Poll interval in ms when using schedule lattice (default: 5000) */\n pollIntervalMs?: number;\n}\n\n/**\n * Type guard to check if config is TeamAgentConfig\n */\nexport function isTeamAgentConfig(\n config: AgentConfig\n): config is TeamAgentConfig {\n return config.type === AgentType.TEAM;\n}\n\n// ─── A2A_REMOTE Agent ──────────────────────────────────────────────────────\n\nexport interface LocalRuntimeConfig {\n label?: string;\n agentCardUrl: string;\n healthUrl?: string;\n command: {\n executable: string;\n args: string[];\n cwd?: string;\n env?: Record<string, string>;\n };\n}\n\n/**\n * A2A_REMOTE agent configuration — wraps a remote A2A-compatible agent endpoint.\n *\n * This agent type wraps a remote A2A endpoint so orchestrators can treat\n * external agents the same as local LangGraph agents.\n */\nexport interface A2ARemoteAgentConfig extends BaseAgentConfig {\n type: AgentType.A2A_REMOTE;\n /**\n * URL of the remote agent's agent card (e.g. http://host:3000/.well-known/agent-card.json).\n * The builder fetches this card to discover the JSON-RPC endpoint.\n */\n agentCardUrl: string;\n /**\n * Optional API key sent as a Bearer token.\n */\n apiKey?: string;\n /**\n * HTTP timeout in milliseconds (default: 300_000 = 5 min).\n */\n timeout?: number;\n projectId?: string;\n /**\n * Optional tool keys (not used by the builder, but included for type compatibility).\n */\n tools?: string[];\n /**\n * Optional local runtime snapshot for Local Managed A2A assistants.\n * When present, the gateway manages a local process for this assistant.\n * Copied from a template or custom form at creation time.\n */\n localRuntime?: LocalRuntimeConfig;\n}\n\nexport type LocalA2AProviderId = string;\n\nexport type LocalA2AProviderStatus =\n | \"missing\"\n | \"disabled\"\n | \"starting\"\n | \"running\"\n | \"stopped\"\n | \"failed\";\n\nexport interface LocalA2AProviderState {\n runtimeId: string;\n label: string;\n status: LocalA2AProviderStatus;\n enabled: boolean;\n assistantId?: string;\n agentCardUrl?: string;\n healthUrl?: string;\n pid?: number;\n message?: string;\n lastStartedAt?: string;\n lastStoppedAt?: string;\n}\n\n/**\n * WORKFLOW agent configuration — compiled from YAML workflow DSL into a LangGraph StateGraph.\n *\n * The workflow field contains the full DSL definition (nodes, edges, state).\n * The WorkflowAgentGraphBuilder compiles this into a multi-node LangGraph\n * where each node invokes a registered sub-agent by ref.\n */\nexport interface WorkflowAgentConfig extends BaseAgentConfig {\n type: AgentType.WORKFLOW;\n /** The YAML workflow DSL definition string (needs+if format) */\n workflowYaml: string;\n /** Optional tool keys */\n tools?: string[];\n}\n\n/**\n * Type guard to check if config is A2ARemoteAgentConfig\n */\nexport function isA2ARemoteAgentConfig(\n config: AgentConfig\n): config is A2ARemoteAgentConfig {\n return config.type === AgentType.A2A_REMOTE;\n}\n\n/**\n * Type guard to check if config is WorkflowAgentConfig\n */\nexport function isWorkflowAgentConfig(\n config: AgentConfig\n): config is WorkflowAgentConfig {\n return config.type === AgentType.WORKFLOW;\n}\n\n/**\n * Agent configuration union type\n * Different agent types have different configuration options\n */\nexport type AgentConfig =\n | ReactAgentConfig\n | DeepAgentConfig\n | TeamAgentConfig\n | ProcessingAgentConfig\n | A2ARemoteAgentConfig\n | WorkflowAgentConfig\n\n/**\n * Agent configuration with tools property\n */\nexport type AgentConfigWithTools =\n | ReactAgentConfig\n | DeepAgentConfig\n | TeamAgentConfig\n | ProcessingAgentConfig\n | A2ARemoteAgentConfig\n | WorkflowAgentConfig\n\n/**\n * Type guard to check if config has tools property\n */\nexport function hasTools(config: AgentConfig): config is AgentConfigWithTools {\n return true;\n}\n\n/**\n * Type guard to check if config is DeepAgentConfig (has subAgents)\n */\nexport function isDeepAgentConfig(\n config: AgentConfig\n): config is DeepAgentConfig {\n return config.type === AgentType.DEEP_AGENT;\n}\n\n/**\n * Type guard to check if config is ProcessingAgentConfig (has subAgents + topology)\n */\nexport function isProcessingAgentConfig(\n config: AgentConfig\n): config is ProcessingAgentConfig {\n return config.type === AgentType.PROCESSING;\n}\n\n/**\n * Get tools from config safely\n */\nexport function getToolsFromConfig(config: AgentConfig): string[] {\n if (hasTools(config)) {\n return config.tools || [];\n }\n return [];\n}\n\n/**\n * Get subAgents from config safely (DeepAgentConfig and ProcessingAgentConfig have subAgents)\n */\nexport function getSubAgentsFromConfig(config: AgentConfig): string[] {\n if (isDeepAgentConfig(config) || isProcessingAgentConfig(config)) {\n return config.subAgents || [];\n }\n return [];\n}\n\n/**\n * 智能体客户端类型\n */\nexport type AgentClient = CompiledStateGraph<any, any, any, any, any>;\n\n/**\n * Graph构建选项\n */\nexport interface GraphBuildOptions {\n overrideTools?: string[];\n overrideModel?: string;\n metadata?: Record<string, any>;\n}\n\n/**\n * 智能体Lattice协议接口\n */\nexport interface AgentLatticeProtocol\n extends BaseLatticeProtocol<AgentConfig, AgentClient> {\n // 智能体执行函数\n invoke: (input: any, options?: any) => Promise<any>;\n\n // 构建智能体图\n buildGraph: (options?: GraphBuildOptions) => Promise<AgentClient>;\n}\n","/**\n * MemoryLatticeProtocol\n *\n * 记忆Lattice的协议,用于管理智能体的上下文和记忆\n */\n\nimport { BaseLatticeProtocol } from \"./BaseLatticeProtocol\";\n\n/**\n * 记忆类型枚举\n */\nexport enum MemoryType {\n SHORT_TERM = \"short_term\",\n LONG_TERM = \"long_term\",\n EPISODIC = \"episodic\",\n SEMANTIC = \"semantic\",\n WORKING = \"working\",\n}\n\n/**\n * 记忆配置接口\n */\nexport interface MemoryConfig {\n name: string; // 名称\n description: string; // 描述\n type: MemoryType; // 记忆类型\n ttl?: number; // 生存时间\n capacity?: number; // 容量限制\n}\n\n/**\n * 记忆客户端接口\n */\nexport interface MemoryClient {\n add: (key: string, value: any) => Promise<void>;\n get: (key: string) => Promise<any>;\n update: (key: string, value: any) => Promise<void>;\n delete: (key: string) => Promise<void>;\n search: (query: string, options?: any) => Promise<any[]>;\n clear: () => Promise<void>;\n}\n\n/**\n * 记忆Lattice协议接口\n */\nexport interface MemoryLatticeProtocol\n extends BaseLatticeProtocol<MemoryConfig, MemoryClient> {\n // 记忆操作方法\n add: (key: string, value: any) => Promise<void>;\n get: (key: string) => Promise<any>;\n update: (key: string, value: any) => Promise<void>;\n delete: (key: string) => Promise<void>;\n search: (query: string, options?: any) => Promise<any[]>;\n clear: () => Promise<void>;\n}\n","/**\n * UILatticeProtocol\n *\n * UI Lattice的协议,用于定义用户界面组件\n */\n\nimport { BaseLatticeProtocol } from \"./BaseLatticeProtocol\";\n\n/**\n * UI组件类型枚举\n */\nexport enum UIComponentType {\n CONTAINER = \"container\",\n INPUT = \"input\",\n BUTTON = \"button\",\n LIST = \"list\",\n TABLE = \"table\",\n CHART = \"chart\",\n FORM = \"form\",\n CARD = \"card\",\n MODAL = \"modal\",\n CUSTOM = \"custom\",\n}\n\n/**\n * UI配置接口\n */\nexport interface UIConfig {\n name: string; // 组件名称\n description: string; // 组件描述\n type: UIComponentType; // 组件类型\n props?: Record<string, any>; // 组件属性\n children?: string[]; // 子组件列表\n}\n\n/**\n * UI组件接口\n * 使用泛型以适应不同的UI框架(React, Vue等)\n */\nexport interface UIComponent<T = any> {\n render: (props?: any) => T;\n addEventListener: (event: string, handler: (...args: unknown[]) => void) => void;\n removeEventListener: (event: string, handler: (...args: unknown[]) => void) => void;\n}\n\n/**\n * UI Lattice协议接口\n */\nexport interface UILatticeProtocol<T = any>\n extends BaseLatticeProtocol<UIConfig, UIComponent<T>> {\n // UI渲染方法\n render: (props?: any) => T;\n\n // 事件处理\n addEventListener: (event: string, handler: (...args: unknown[]) => void) => void;\n removeEventListener: (event: string, handler: (...args: unknown[]) => void) => void;\n}\n","/**\n * QueueLatticeProtocol\n *\n * Queue Lattice protocol for task queue management\n */\n\nimport { BaseLatticeProtocol } from \"./BaseLatticeProtocol\";\n\n/**\n * Queue service type enumeration\n */\nexport enum QueueType {\n MEMORY = \"memory\",\n REDIS = \"redis\",\n}\n\n/**\n * Queue configuration interface\n */\nexport interface QueueConfig {\n name: string; // Queue name\n description: string; // Queue description\n type: QueueType; // Queue service type\n queueName?: string; // Specific queue name (e.g., \"tasks\")\n options?: Record<string, any>; // Additional options (e.g., Redis connection options)\n}\n\n/**\n * Queue operation result interface\n */\nexport interface QueueResult<T = any> {\n data: T | null;\n error: any | null;\n}\n\n/**\n * Queue client interface\n */\nexport interface QueueClient {\n push: (item: any) => Promise<QueueResult<number>>;\n pop: () => Promise<QueueResult<any>>;\n createQueue?: () => Promise<{ success: boolean; queue_name?: string; error?: any }>;\n}\n\n/**\n * Queue Lattice protocol interface\n */\nexport interface QueueLatticeProtocol\n extends BaseLatticeProtocol<QueueConfig, QueueClient> {\n // Queue operations\n push: (item: any) => Promise<QueueResult<number>>;\n pop: () => Promise<QueueResult<any>>;\n createQueue?: () => Promise<{ success: boolean; queue_name?: string; error?: any }>;\n}\n\n\n\n","/**\n * ScheduleLatticeProtocol\n *\n * Schedule Lattice protocol for delayed and recurring task execution management\n * Supports persistence and recovery after service restart\n * Supports both one-time delayed tasks and cron-style recurring tasks\n */\n\nimport { BaseLatticeProtocol } from \"./BaseLatticeProtocol\";\n\n/**\n * Schedule service type enumeration\n */\nexport enum ScheduleType {\n MEMORY = \"memory\",\n POSTGRES = \"postgres\",\n REDIS = \"redis\",\n}\n\n/**\n * Schedule execution type - one-time or recurring\n */\nexport enum ScheduleExecutionType {\n ONCE = \"once\", // Execute once at specified time\n CRON = \"cron\", // Recurring based on cron expression\n}\n\n/**\n * Task status enumeration\n */\nexport enum ScheduledTaskStatus {\n PENDING = \"pending\", // Waiting to be executed\n RUNNING = \"running\", // Currently executing\n COMPLETED = \"completed\", // Successfully completed (for ONCE type)\n FAILED = \"failed\", // Execution failed\n CANCELLED = \"cancelled\", // Manually cancelled\n PAUSED = \"paused\", // Paused (for CRON type)\n}\n\n/**\n * Schedule configuration interface\n */\nexport interface ScheduleConfig {\n name: string;\n description: string;\n type: ScheduleType;\n storage?: ScheduleStorage; // Optional storage for persistence\n options?: Record<string, any>;\n}\n\n/**\n * Scheduled task definition - fully serializable\n * Supports both one-time and cron-style recurring tasks\n */\nexport interface ScheduledTaskDefinition {\n taskId: string;\n taskType: string; // Maps to a registered handler\n payload: Record<string, any>; // JSON-serializable data passed to handler\n\n // Context fields for querying\n tenantId: string; // Tenant isolation\n assistantId?: string; // Which assistant created/owns this task\n threadId?: string; // Which thread this task belongs to\n\n // Execution configuration\n executionType: ScheduleExecutionType;\n\n // For ONCE type - execute at specific time or after delay\n executeAt?: number; // Timestamp when to execute\n delayMs?: number; // Original delay in milliseconds (for reference)\n\n // For CRON type - recurring schedule\n cronExpression?: string; // Cron format: \"0 9 * * *\" (min hour day month weekday)\n timezone?: string; // Timezone: \"Asia/Shanghai\", defaults to system timezone\n nextRunAt?: number; // Next calculated execution time\n lastRunAt?: number; // Last execution time\n\n // Execution tracking\n status: ScheduledTaskStatus;\n runCount: number; // How many times executed\n maxRuns?: number; // Max executions (null/undefined = infinite for cron, 1 for once)\n\n // Error handling\n retryCount: number; // Current retry count\n maxRetries: number; // Maximum retry attempts\n lastError?: string; // Last error message if failed\n\n // Timestamps\n createdAt: number;\n updatedAt: number;\n expiresAt?: number; // When to stop (for cron, optional)\n\n metadata?: Record<string, any>; // Additional metadata\n}\n\n/**\n * Task handler function type\n */\nexport type TaskHandler = (\n payload: Record<string, any>,\n taskInfo: ScheduledTaskDefinition\n) => void | Promise<void>;\n\n/**\n * Options for scheduling a one-time task\n */\nexport interface ScheduleOnceOptions {\n executeAt?: number; // Absolute timestamp to execute\n delayMs?: number; // OR relative delay from now\n maxRetries?: number; // Max retry attempts (default: 0)\n tenantId?: string; // Tenant isolation\n assistantId?: string; // Which assistant created/owns this task\n threadId?: string; // Which thread this task belongs to\n metadata?: Record<string, any>;\n}\n\n/**\n * Options for scheduling a cron task\n */\nexport interface ScheduleCronOptions {\n cronExpression: string; // Cron expression: \"0 9 * * *\"\n timezone?: string; // Timezone: \"Asia/Shanghai\"\n maxRuns?: number; // Max executions (undefined = infinite)\n expiresAt?: number; // Stop after this timestamp\n maxRetries?: number; // Max retry attempts per run (default: 0)\n tenantId?: string; // Tenant isolation\n assistantId?: string; // Which assistant created/owns this task\n threadId?: string; // Which thread this task belongs to\n metadata?: Record<string, any>;\n}\n\n/**\n * Schedule storage interface for persistence\n */\nexport interface ScheduleStorage {\n /**\n * Save a new task\n */\n save(task: ScheduledTaskDefinition): Promise<void>;\n\n /**\n * Get task by ID\n */\n get(taskId: string): Promise<ScheduledTaskDefinition | null>;\n\n /**\n * Update task\n */\n update(\n taskId: string,\n updates: Partial<ScheduledTaskDefinition>\n ): Promise<void>;\n\n /**\n * Delete task\n */\n delete(taskId: string): Promise<void>;\n\n /**\n * Get all pending/active tasks (for recovery)\n * Returns tasks with status: PENDING or PAUSED\n */\n getActiveTasks(): Promise<ScheduledTaskDefinition[]>;\n\n /**\n * Get tasks by type\n */\n getTasksByType(taskType: string): Promise<ScheduledTaskDefinition[]>;\n\n /**\n * Get tasks by status\n */\n getTasksByStatus(\n status: ScheduledTaskStatus\n ): Promise<ScheduledTaskDefinition[]>;\n\n /**\n * Get tasks by execution type\n */\n getTasksByExecutionType(\n executionType: ScheduleExecutionType\n ): Promise<ScheduledTaskDefinition[]>;\n\n /**\n * Get tasks by assistant ID\n */\n getTasksByAssistantId(\n assistantId: string\n ): Promise<ScheduledTaskDefinition[]>;\n\n /**\n * Get tasks by thread ID\n */\n getTasksByThreadId(threadId: string): Promise<ScheduledTaskDefinition[]>;\n\n /**\n * Get all tasks (with optional filters)\n */\n getAllTasks(filters?: {\n tenantId?: string;\n status?: ScheduledTaskStatus;\n executionType?: ScheduleExecutionType;\n taskType?: string;\n assistantId?: string;\n threadId?: string;\n limit?: number;\n offset?: number;\n }): Promise<ScheduledTaskDefinition[]>;\n\n /**\n * Count tasks (with optional filters)\n */\n countTasks(filters?: {\n tenantId?: string;\n status?: ScheduledTaskStatus;\n executionType?: ScheduleExecutionType;\n taskType?: string;\n assistantId?: string;\n threadId?: string;\n }): Promise<number>;\n\n /**\n * Delete completed/cancelled tasks older than specified time\n * Useful for cleanup\n */\n deleteOldTasks(olderThanMs: number): Promise<number>;\n}\n\n/**\n * Schedule client interface\n */\nexport interface ScheduleClient {\n // ===== Handler Registration =====\n\n /**\n * Register a handler for a task type\n * Must be called before scheduling tasks of this type\n */\n registerHandler(taskType: string, handler: TaskHandler): void;\n\n /**\n * Unregister a handler\n */\n unregisterHandler(taskType: string): boolean;\n\n /**\n * Check if a handler is registered\n */\n hasHandler(taskType: string): boolean;\n\n /**\n * Get all registered handler types\n */\n getHandlerTypes(): string[];\n\n // ===== One-time Task Scheduling =====\n\n /**\n * Schedule a one-time task\n * @param taskId - Unique identifier for the task\n * @param taskType - Type of task (must have a registered handler)\n * @param payload - Data to pass to the handler (must be JSON-serializable)\n * @param options - Execution options (executeAt or delayMs required)\n */\n scheduleOnce(\n taskId: string,\n taskType: string,\n payload: Record<string, any>,\n options: ScheduleOnceOptions\n ): Promise<boolean>;\n\n // ===== Cron Task Scheduling =====\n\n /**\n * Schedule a recurring cron task\n * @param taskId - Unique identifier for the task\n * @param taskType - Type of task (must have a registered handler)\n * @param payload - Data to pass to the handler (must be JSON-serializable)\n * @param options - Cron options (cronExpression required)\n */\n scheduleCron(\n taskId: string,\n taskType: string,\n payload: Record<string, any>,\n options: ScheduleCronOptions\n ): Promise<boolean>;\n\n // ===== Task Management =====\n\n /**\n * Cancel a scheduled task\n */\n cancel(taskId: string): Promise<boolean>;\n\n /**\n * Pause a cron task (only for CRON type)\n */\n pause(taskId: string): Promise<boolean>;\n\n /**\n * Resume a paused cron task (only for CRON type)\n */\n resume(taskId: string): Promise<boolean>;\n\n /**\n * Check if a task exists\n */\n has(taskId: string): Promise<boolean>;\n\n /**\n * Get task information\n */\n getTask(taskId: string): Promise<ScheduledTaskDefinition | null>;\n\n /**\n * Get remaining time until next execution\n * Returns -1 if task not found or already executed\n */\n getRemainingTime(taskId: string): Promise<number>;\n\n /**\n * Get count of active tasks (pending + paused)\n */\n getActiveTaskCount(): Promise<number>;\n\n /**\n * Get all active task IDs\n */\n getActiveTaskIds(): Promise<string[]>;\n\n /**\n * Cancel all active tasks\n */\n cancelAll(): Promise<void>;\n\n // ===== Recovery =====\n\n /**\n * Restore active tasks from storage (call on service startup)\n * Re-schedules all pending tasks with their remaining time\n * Re-schedules all cron tasks for their next run\n * @returns Number of tasks restored\n */\n restore(): Promise<number>;\n\n // ===== Storage =====\n\n /**\n * Set the storage backend\n */\n setStorage(storage: ScheduleStorage): void;\n\n /**\n * Get current storage backend\n */\n getStorage(): ScheduleStorage | null;\n}\n\n/**\n * Schedule Lattice protocol interface\n */\nexport interface ScheduleLatticeProtocol\n extends BaseLatticeProtocol<ScheduleConfig, ScheduleClient> {\n // Handler registration\n registerHandler: (taskType: string, handler: TaskHandler) => void;\n unregisterHandler: (taskType: string) => boolean;\n hasHandler: (taskType: string) => boolean;\n getHandlerTypes: () => string[];\n\n // One-time task scheduling\n scheduleOnce: (\n taskId: string,\n taskType: string,\n payload: Record<string, any>,\n options: ScheduleOnceOptions\n ) => Promise<boolean>;\n\n // Cron task scheduling\n scheduleCron: (\n taskId: string,\n taskType: string,\n payload: Record<string, any>,\n options: ScheduleCronOptions\n ) => Promise<boolean>;\n\n // Task management\n cancel: (taskId: string) => Promise<boolean>;\n pause: (taskId: string) => Promise<boolean>;\n resume: (taskId: string) => Promise<boolean>;\n has: (taskId: string) => Promise<boolean>;\n getTask: (taskId: string) => Promise<ScheduledTaskDefinition | null>;\n getRemainingTime: (taskId: string) => Promise<number>;\n getActiveTaskCount: () => Promise<number>;\n getActiveTaskIds: () => Promise<string[]>;\n cancelAll: () => Promise<void>;\n\n // Recovery\n restore: () => Promise<number>;\n}\n","/**\n * LoggerLatticeProtocol\n *\n * Logger Lattice protocol for logging management\n */\n\nimport { BaseLatticeProtocol } from \"./BaseLatticeProtocol\";\n\n/**\n * Logger service type enumeration\n */\nexport enum LoggerType {\n PINO = \"pino\",\n CONSOLE = \"console\",\n CUSTOM = \"custom\",\n}\n\n/**\n * Logger context interface\n */\nexport interface LoggerContext {\n \"x-user-id\"?: string;\n \"x-tenant-id\"?: string;\n \"x-request-id\"?: string;\n \"x-task-id\"?: string;\n \"x-thread-id\"?: string;\n [key: string]: any;\n}\n\n/**\n * Pino logger file transport options\n */\nexport interface PinoFileOptions {\n file?: string; // Log file path (e.g., \"./logs/app.log\" or \"./logs/app\")\n frequency?: \"daily\" | \"hourly\" | \"minutely\" | string; // Log rotation frequency\n mkdir?: boolean; // Create directory if not exists\n size?: string; // Max file size (e.g., \"10M\", \"100K\")\n maxFiles?: number; // Maximum number of log files to keep\n}\n\n/**\n * Logger configuration interface\n */\nexport interface LoggerConfig {\n name: string; // Logger name\n description?: string; // Logger description\n type: LoggerType; // Logger service type\n serviceName?: string; // Service name (e.g., \"lattice-gateway\")\n loggerName?: string; // Logger instance name (e.g., \"fastify-server\")\n context?: LoggerContext; // Initial context\n // File logging options (for PINO type)\n file?: string | PinoFileOptions; // Log file path or detailed file options\n // Additional options (e.g., pino config, custom logger settings)\n options?: Record<string, any>;\n}\n\n/**\n * Logger client interface\n */\nexport interface LoggerClient {\n info: (msg: string, obj?: object) => void;\n error: (msg: string, obj?: object | Error) => void;\n warn: (msg: string, obj?: object) => void;\n debug: (msg: string, obj?: object) => void;\n updateContext?: (context: Partial<LoggerContext>) => void;\n child?: (options: Partial<LoggerConfig>) => LoggerClient;\n}\n\n/**\n * Logger Lattice protocol interface\n */\nexport interface LoggerLatticeProtocol\n extends BaseLatticeProtocol<LoggerConfig, LoggerClient> {\n // Logger operations\n info: (msg: string, obj?: object) => void;\n error: (msg: string, obj?: object | Error) => void;\n warn: (msg: string, obj?: object) => void;\n debug: (msg: string, obj?: object) => void;\n updateContext?: (context: Partial<LoggerContext>) => void;\n child?: (options: Partial<LoggerConfig>) => LoggerClient;\n}\n","/**\n * MessageProtocol\n *\n */\n\n\n\n/**\n * Base message interface\n */\nexport interface BaseMessage {\n id: string; // Unique identifier for the message\n role: string; // Role of the sender (user, assistant, system, tool, developer)\n content?: string; // Optional text content of the message\n name?: string; // Optional name of the sender\n}\n\n/**\n * User message interface\n */\nexport interface UserMessage extends BaseMessage {\n role: \"human\";\n content: string; // Text input from the user\n files?: Array<{ name: string; id: string }>; // Optional files attached to the message\n}\n\n/**\n * Tool call interface\n */\nexport interface ToolCall {\n id: string; // Unique identifier for this tool call\n name: string; // Name of the tool/function to call\n args: Record<string, any>; // Arguments as an object\n type: \"tool_call\"; // Type of tool call\n response?: string; // Optional response from the tool execution\n}\n\n/**\n * Assistant message interface\n */\nexport interface AssistantMessage extends BaseMessage {\n role: \"ai\";\n content?: string; // Text response from the assistant (optional if using tool calls)\n tool_calls?: ToolCall[]; // Optional tool calls made by the assistant\n}\n\nexport interface InterruptMessage extends BaseMessage {\n type: \"interrupt\";\n value: any;\n}\n\n/**\n * System message interface\n */\nexport interface SystemMessage extends BaseMessage {\n role: \"system\";\n content: string; // Instructions or context for the assistant\n}\n\n/**\n * Tool message interface\n */\nexport interface ToolMessage extends BaseMessage {\n role: \"tool\";\n content: string; // Result from the tool execution\n tool_call_id: string; // ID of the tool call this message responds to\n}\n\n/**\n * Developer message interface\n */\nexport interface DeveloperMessage extends BaseMessage {\n role: \"developer\";\n content: string; // Content for development or debugging\n}\n\n/**\n * Message chunk type constants\n */\nexport const MessageChunkTypes = {\n HUMAN: 'human',\n AI: 'ai',\n TOOL: 'tool',\n INTERRUPT: 'interrupt',\n MESSAGE_COMPLETED: 'message_completed',\n MESSAGE_FAILED: 'message_failed',\n THREAD_IDLE: 'thread_idle',\n} as const;\n\nexport type MessageChunkType = typeof MessageChunkTypes[keyof typeof MessageChunkTypes];\n\nexport interface MessageChunk {\n type: MessageChunkType;\n data: {\n id: string;\n content?: string;\n tool_call_chunks?: Array<{\n name?: string;\n args?: string;\n id?: string;\n index: number;\n }>;\n tool_calls?: Array<{\n name: string;\n args: Record<string, any>;\n id: string;\n type: string;\n response?: string;\n }>;\n additional_kwargs?: {\n tool_calls?: Array<{\n function?: { name?: string; arguments?: any };\n id?: string;\n }>;\n };\n tool_call_id?: string;\n };\n}\n\n/**\n * Message type union\n */\nexport type Message =\n | UserMessage\n | AssistantMessage\n | SystemMessage\n | ToolMessage\n | DeveloperMessage;\n","/**\n * McpLatticeProtocol\n *\n * Model Context Protocol (MCP) lattice protocol for integrating MCP servers\n * with the Lattice framework. Provides standardized interfaces for MCP\n * client connections, tool discovery, and remote execution.\n */\n\nimport { BaseLatticeProtocol, LatticeMessage } from \"./BaseLatticeProtocol\";\n\n/**\n * MCP transport type\n */\nexport type McpTransportType = \"stdio\" | \"streamable_http\" | \"sse\";\n\n/**\n * MCP server configuration\n */\nexport interface McpServerConfig {\n /** Server name */\n name: string;\n /** Server version */\n version: string;\n /** Transport type */\n transport: McpTransportType;\n /** Command for stdio transport (e.g., \"npx\", \"python\") */\n command?: string;\n /** Arguments for stdio transport */\n args?: string[];\n /** URL for HTTP/SSE transport */\n url?: string;\n /** Environment variables */\n env?: Record<string, string>;\n /** Connection timeout in milliseconds */\n timeout?: number;\n /** Retry attempts on connection failure */\n retryAttempts?: number;\n}\n\n/**\n * MCP tool definition\n */\nexport interface McpTool {\n /** Tool name */\n name: string;\n /** Tool description */\n description: string;\n /** Input schema */\n inputSchema: {\n type: \"object\";\n properties: Record<string, any>;\n required?: string[];\n };\n /** Tool metadata */\n metadata?: Record<string, any>;\n}\n\n/**\n * MCP tool call result\n */\nexport interface McpToolResult {\n /** Whether the call was successful */\n success: boolean;\n /** Result content */\n content: Array<{\n type: \"text\" | \"image\" | \"audio\" | \"resource\";\n data: any;\n mimeType?: string;\n }>;\n /** Error message if failed */\n error?: string;\n /** Execution metadata */\n metadata?: {\n duration: number;\n tokens?: number;\n model?: string;\n };\n}\n\n/**\n * MCP client interface\n */\nexport interface McpClient {\n /** Client name */\n name: string;\n /** Client version */\n version: string;\n /** Server configuration */\n serverConfig: McpServerConfig;\n \n /**\n * Connect to MCP server\n */\n connect(): Promise<void>;\n \n /**\n * Disconnect from MCP server\n */\n disconnect(): Promise<void>;\n \n /**\n * Check if connected\n */\n isConnected(): boolean;\n \n /**\n * List available tools\n */\n listTools(): Promise<McpTool[]>;\n \n /**\n * Call a tool\n */\n callTool(name: string, arguments_: Record<string, any>): Promise<McpToolResult>;\n \n /**\n * Subscribe to server notifications\n */\n subscribe(topic: string, handler: (data: any) => void): void;\n \n /**\n * Unsubscribe from server notifications\n */\n unsubscribe(topic: string): void;\n \n /**\n * Get client statistics\n */\n getStats(): McpStats;\n \n /**\n * Get connection status\n */\n getStatus(): McpConnectionStatus;\n}\n\n/**\n * MCP client options\n */\nexport interface McpClientOptions {\n /** Client name */\n name: string;\n /** Client version */\n version: string;\n /** Server configuration */\n serverConfig: McpServerConfig;\n /** Auto-connect on initialization */\n autoConnect?: boolean;\n /** Error handler */\n onError?: (error: Error) => void;\n /** Connection status handler */\n onStatusChange?: (status: McpConnectionStatus) => void;\n}\n\n/**\n * MCP Lattice protocol interface\n */\nexport interface McpLatticeProtocol\n extends BaseLatticeProtocol<McpServerConfig, McpClient> {\n /**\n * Server configuration\n */\n config: McpServerConfig;\n \n /**\n * MCP client instance\n */\n client: McpClient;\n \n /**\n * Connect to MCP server\n */\n connect(): Promise<void>;\n \n /**\n * Disconnect from MCP server\n */\n disconnect(): Promise<void>;\n \n /**\n * Get available tools\n */\n getTools(): Promise<McpTool[]>;\n \n /**\n * Execute a tool\n */\n executeTool(\n name: string,\n arguments_: Record<string, any>\n ): Promise<McpToolResult>;\n \n /**\n * Execute with automatic retries\n */\n executeToolWithRetry(\n name: string,\n arguments_: Record<string, any>,\n maxRetries?: number\n ): Promise<McpToolResult>;\n \n /**\n * Get protocol version\n */\n getProtocolVersion(): string;\n \n /**\n * Health check\n */\n healthCheck(): Promise<boolean>;\n}\n\n/**\n * MCP message types\n */\nexport enum McpMessageType {\n CONNECT = \"mcp:connect\",\n DISCONNECT = \"mcp:disconnect\",\n LIST_TOOLS = \"mcp:list_tools\",\n CALL_TOOL = \"mcp:call_tool\",\n TOOL_RESULT = \"mcp:tool_result\",\n NOTIFICATION = \"mcp:notification\",\n ERROR = \"mcp:error\",\n HEALTH_CHECK = \"mcp:health_check\",\n}\n\n/**\n * MCP Lattice message\n */\nexport interface McpLatticeMessage extends LatticeMessage {\n type: McpMessageType;\n payload: {\n toolName?: string;\n arguments?: Record<string, any>;\n result?: McpToolResult;\n tools?: McpTool[];\n error?: string;\n };\n}\n\n/**\n * MCP connection status\n */\nexport type McpConnectionStatus =\n | \"disconnected\"\n | \"connecting\"\n | \"connected\"\n | \"reconnecting\"\n | \"error\";\n\n/**\n * MCP statistics\n */\nexport interface McpStats {\n totalCalls: number;\n successfulCalls: number;\n failedCalls: number;\n averageLatency: number;\n lastCallTimestamp: number;\n}\n","/**\n * WorkspaceStoreProtocol\n *\n * Workspace and Project store protocol definitions\n * for the Axiom Lattice framework\n */\n\nexport type StorageType = \"sandbox\" | \"filesystem\";\n\n/**\n * Workspace type definition\n */\nexport interface Workspace {\n id: string;\n tenantId: string;\n name: string;\n description?: string;\n storageType: StorageType;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/**\n * Create workspace request type\n */\nexport interface CreateWorkspaceRequest {\n name: string;\n description?: string;\n storageType: StorageType;\n}\n\n/**\n * Update workspace request type\n */\nexport interface UpdateWorkspaceRequest {\n name?: string;\n description?: string;\n storageType?: StorageType;\n}\n\n/**\n * WorkspaceStore interface\n * Provides CRUD operations for workspace data\n */\nexport interface WorkspaceStore {\n getAllWorkspaces(tenantId: string): Promise<Workspace[]>;\n getWorkspaceById(tenantId: string, id: string): Promise<Workspace | null>;\n createWorkspace(tenantId: string, id: string, data: CreateWorkspaceRequest): Promise<Workspace>;\n updateWorkspace(tenantId: string, id: string, updates: UpdateWorkspaceRequest): Promise<Workspace | null>;\n deleteWorkspace(tenantId: string, id: string): Promise<boolean>;\n}\n\n/**\n * Project kind classification\n *\n * Defaults to \"business\" for legacy rows and omitted input.\n */\nexport type ProjectKind = \"business\" | \"training\" | \"personal\";\n\n/**\n * Project type definition\n */\nexport interface Project {\n id: string;\n tenantId: string;\n workspaceId: string;\n name: string;\n description?: string;\n /** Application-specific configuration stored as JSON */\n config?: Record<string, unknown>;\n /** Project classification; defaults to \"business\" when omitted */\n kind?: ProjectKind;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/**\n * Create project request type\n */\nexport interface CreateProjectRequest {\n name: string;\n description?: string;\n /** Application-specific configuration stored as JSON (optional) */\n config?: Record<string, unknown>;\n /** Project classification; defaults to \"business\" when omitted */\n kind?: ProjectKind;\n}\n\n/**\n * Update project request type\n *\n * @remarks\n * - The `config` field uses **replace** semantics: if provided, it completely\n * overwrites the existing config. To preserve the current config, omit this field.\n */\nexport interface UpdateProjectRequest {\n name?: string;\n description?: string;\n /** Application-specific configuration stored as JSON (replaces existing if provided) */\n config?: Record<string, unknown>;\n /** Project classification */\n kind?: ProjectKind;\n}\n\n/** Error raised when generic project writes attempt to change capability Bundle references. */\nexport class InvalidProjectCapabilityBundleConfigError extends Error {\n /** Stable machine-readable error code. */\n readonly code = \"INVALID_BUNDLE_CONFIG\" as const;\n\n /** Creates the reserved-config error returned by generic Project writes. */\n constructor() {\n super(\"Use the project capability-bundles endpoint to update capability bundle IDs\");\n this.name = \"InvalidProjectCapabilityBundleConfigError\";\n }\n}\n\n/** Rejects capability Bundle references supplied through generic Project config writes. */\nexport function assertGenericProjectConfig(config: Record<string, unknown> | undefined): void {\n if (config !== undefined && Object.prototype.hasOwnProperty.call(config, \"capabilityBundleIds\")) {\n throw new InvalidProjectCapabilityBundleConfigError();\n }\n}\n\n/**\n * Filter options for listing projects within a workspace\n */\nexport interface ProjectFilter {\n kind?: ProjectKind;\n}\n\n/** Atomic result of replacing a Project's capability Bundle IDs. */\nexport type UpdateProjectCapabilityBundlesResult =\n | { status: \"updated\"; project: Project }\n | { status: \"project_not_found\" }\n | { status: \"bundle_not_found\" }\n | { status: \"bundle_conflict\" };\n\n/** Revision preconditions for the bundles reviewed before project assignment. */\nexport type ExpectedCapabilityBundleRevisions = Record<string, string>;\n\n/**\n * ProjectStore interface\n * Provides CRUD operations for project data\n */\nexport interface ProjectStore {\n getProjectsByWorkspace(tenantId: string, workspaceId: string, filter?: ProjectFilter): Promise<Project[]>;\n getProjectById(tenantId: string, id: string): Promise<Project | null>;\n createProject(tenantId: string, workspaceId: string, id: string, data: CreateProjectRequest): Promise<Project>;\n updateProject(tenantId: string, id: string, updates: UpdateProjectRequest): Promise<Project | null>;\n /** Omitted expectedRevisions is reserved for internal maintenance callers. */\n updateCapabilityBundleIds(tenantId: string, projectId: string, bundleIds: string[], expectedRevisions?: ExpectedCapabilityBundleRevisions): Promise<UpdateProjectCapabilityBundlesResult>;\n deleteProject(tenantId: string, id: string): Promise<boolean>;\n /** Returns whether a tenant project references the given capability bundle. */\n isCapabilityBundleReferenced(tenantId: string, bundleId: string): Promise<boolean>;\n}\n","/**\n * BindingProtocol\n *\n */\n\nexport interface Binding {\n id: string;\n channel: string;\n channelInstallationId: string;\n tenantId: string;\n senderId: string;\n agentId: string;\n threadId?: string;\n workspaceId?: string;\n projectId?: string;\n threadMode: \"fixed\" | \"per_conversation\";\n senderDisplayName?: string;\n senderMetadata?: Record<string, unknown>;\n enabled: boolean;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport interface CreateBindingInput {\n channel: string;\n channelInstallationId: string;\n tenantId: string;\n senderId: string;\n agentId: string;\n threadId?: string;\n threadMode?: \"fixed\" | \"per_conversation\";\n senderDisplayName?: string;\n senderMetadata?: Record<string, unknown>;\n workspaceId?: string;\n projectId?: string;\n /** Whether the binding is eligible for inbound resolution immediately after creation. */\n enabled?: boolean;\n}\n\n/** Filters binding records before pagination is applied. */\nexport interface BindingListParams {\n tenantId: string;\n channel?: string;\n agentId?: string;\n channelInstallationId?: string;\n /** Installation ID prefixes excluded before pagination, for internal namespaces. */\n excludeInstallationIdPrefixes?: string[];\n excludeChannels?: string[];\n limit?: number;\n offset?: number;\n}\n\n/**\n * Fields that may change after a binding is created.\n *\n * Binding identity (`id`, tenant, channel, installation, sender, and timestamps) is intentionally\n * absent so every persistence backend can enforce tenant-scoped mutation without identity drift.\n */\nexport interface BindingMutablePatch {\n /** Agent that receives messages for this subject. */\n agentId?: string;\n /** Fixed thread used when `threadMode` is `fixed`. */\n threadId?: string;\n /** Optional workspace execution scope. */\n workspaceId?: string;\n /** Optional project execution scope. */\n projectId?: string;\n /** Whether messages share one thread or create one per conversation. */\n threadMode?: \"fixed\" | \"per_conversation\";\n /** Human-readable sender label. */\n senderDisplayName?: string;\n /** Mutable sender metadata supplied by trusted internal callers. */\n senderMetadata?: Record<string, unknown>;\n /** Whether inbound resolution may use this binding. */\n enabled?: boolean;\n}\n\n/** Raised when a channel installation already has a binding for the same tenant and sender. */\nexport class DuplicateChannelBindingSubjectError extends Error {\n constructor() {\n super(\"A binding already exists for this channel subject\");\n this.name = \"DuplicateChannelBindingSubjectError\";\n }\n}\n\n/** A duplicate subject found while upgrading a local channel-binding database. */\nexport interface ChannelBindingMigrationConflict {\n tenantId: string;\n channel: string;\n channelInstallationId: string;\n senderId: string;\n count: number;\n}\n\n/**\n * Raised when a local binding uniqueness migration requires operator reconciliation.\n *\n * The conflict list contains only subject identifiers and row counts; binding metadata and other\n * potentially sensitive payloads are never included.\n */\nexport class ChannelBindingMigrationConflictError extends Error {\n readonly conflicts: ChannelBindingMigrationConflict[];\n\n constructor(conflicts: ChannelBindingMigrationConflict[]) {\n super(`Channel binding migration found ${conflicts.length} duplicate subject(s)`);\n this.name = \"ChannelBindingMigrationConflictError\";\n this.conflicts = conflicts;\n }\n}\n\nexport interface BindingRegistry {\n findById(tenantId: string, id: string): Promise<Binding | null>;\n\n findBySubject(params: {\n tenantId: string;\n channel: string;\n channelInstallationId: string;\n senderId: string;\n }): Promise<Binding | null>;\n\n resolve(params: {\n channel: string;\n senderId: string;\n channelInstallationId: string;\n tenantId: string;\n }): Promise<Binding | null>;\n\n create(binding: CreateBindingInput): Promise<Binding>;\n update(tenantId: string, id: string, patch: BindingMutablePatch): Promise<Binding>;\n delete(tenantId: string, id: string): Promise<void>;\n\n list(params: BindingListParams): Promise<Binding[]>;\n\n import(tenantId: string, bindings: CreateBindingInput[]): Promise<Binding[]>;\n export(params: { tenantId: string }): Promise<Binding[]>;\n}\n","import type { TaskMutationSnapshot } from \"./TaskStoreProtocol\";\n\n/**\n * TaskWorkItemProtocol\n *\n * Work item protocol for event-sourced task change tracking.\n * Every status change or action on a TaskItem produces one TaskWorkItem.\n */\n\nexport interface TaskWorkItem {\n id: string;\n taskId: string;\n tenantId: string;\n workspaceId?: string;\n projectId?: string;\n action: string;\n actor: string;\n threadId?: string;\n summary?: string;\n detail?: Record<string, unknown>;\n attempt?: number;\n /** Deterministic task-scoped identity used for idempotent event replay. */\n eventKey?: string;\n createdAt: Date;\n}\n\nexport interface CreateWorkItemRequest {\n taskId: string;\n tenantId: string;\n workspaceId?: string;\n projectId?: string;\n action: string;\n actor: string;\n threadId?: string;\n summary?: string;\n detail?: Record<string, unknown>;\n attempt?: number;\n}\n\n/**\n * Work-item creation request requiring a deterministic event identity.\n *\n * Event keys are unique within a tenant and task, not globally.\n */\nexport interface CreateWorkItemIfAbsentRequest extends CreateWorkItemRequest {\n /** Deterministic task-scoped identity used for idempotent event replay. */\n eventKey: string;\n}\n\nexport interface TaskWorkItemListFilter {\n tenantId: string;\n taskId: string;\n workspaceId?: string;\n projectId?: string;\n action?: string;\n order?: 'asc' | 'desc';\n limit?: number;\n offset?: number;\n}\n\n/** Canonical prefix for public task execution-result event identities. */\nexport const EXECUTION_RESULT_EVENT_KEY_PREFIX = \"execution-result:\";\n\n/**\n * Portable regular-expression source for canonical execution-result event keys.\n *\n * The entire key is the literal `execution-result:` prefix followed by a nonempty\n * suffix containing only ASCII letters, digits, period, underscore, colon, or hyphen.\n * Colon is intentionally allowed so callers can compose structured suffixes.\n */\nexport const EXECUTION_RESULT_EVENT_KEY_PATTERN_SOURCE =\n \"^execution-result:[A-Za-z0-9._:-]+$\";\n\n/** Compiled runtime expression for canonical execution-result event keys. */\nexport const EXECUTION_RESULT_EVENT_KEY_PATTERN =\n new RegExp(EXECUTION_RESULT_EVENT_KEY_PATTERN_SOURCE);\n\n/** Maximum pending execution-result rows accepted by one store query. */\nexport const MAX_PENDING_EXECUTION_RESULTS_LIMIT = 1_000;\n\n/**\n * Determines whether a runtime value is a canonical execution-result event key.\n *\n * @param value Runtime value to validate.\n * @returns True only for the portable canonical ASCII grammar.\n */\nexport function isExecutionResultEventKey(value: unknown): value is string {\n return typeof value === \"string\" && EXECUTION_RESULT_EVENT_KEY_PATTERN.test(value);\n}\n\n/** Canonical lifecycle actions projected into Project Rooms. */\nexport const PROJECT_TASK_LIFECYCLE_ACTIONS = [\n \"in_progress\", \"interrupted\", \"failed\", \"completed\", \"cancelled\", \"reassigned\",\n] as const;\n\n/** Lifecycle action eligible for Project Room projection. */\nexport type ProjectTaskLifecycleAction = typeof PROJECT_TASK_LIFECYCLE_ACTIONS[number];\n\n/** Exclusive cursor for deterministic project lifecycle pagination. */\nexport interface ProjectLifecycleEventCursor {\n /** Creation timestamp of the last returned event. */\n createdAt: Date;\n /** Identifier of the last returned event. */\n id: string;\n}\n\n/** Exact project scope and bounded page for canonical lifecycle events. */\nexport interface ProjectLifecycleEventQuery {\n /** Tenant identifier. */\n tenantId: string;\n /** Workspace identifier. */\n workspaceId: string;\n /** Project identifier. */\n projectId: string;\n /** Nonempty lifecycle actions to include. */\n actions: ProjectTaskLifecycleAction[];\n /** Optional exclusive descending cursor. */\n before?: ProjectLifecycleEventCursor;\n /** Maximum rows to return, from 1 through 100. */\n limit: number;\n}\n\nexport interface TaskWorkItemStore {\n create(params: CreateWorkItemRequest): Promise<TaskWorkItem>;\n /** Atomically creates a work item only while the owning task snapshot matches. */\n createIfTaskSnapshot?(\n params: CreateWorkItemRequest,\n snapshot: TaskMutationSnapshot,\n ): Promise<TaskWorkItem | null>;\n list(filter: TaskWorkItemListFilter): Promise<TaskWorkItem[]>;\n\n /**\n * List the newest bounded set of execution results awaiting reconciliation.\n *\n * Only `execution_result` items with a canonical ASCII\n * `execution-result:[A-Za-z0-9._:-]+` event key are returned. An item is excluded when\n * a task-scoped `execution_reconciled` item has a\n * `detail.executionResultId` equal to that event key. Results are ordered by\n * `createdAt` descending and then `id` descending for deterministic ties.\n *\n * @param params Tenant/task scope and required maximum number of rows.\n * @returns At most `limit` pending execution-result work items, newest first.\n * @throws RangeError with code `INVALID_LIMIT` unless limit is a safe integer from zero through\n * {@link MAX_PENDING_EXECUTION_RESULTS_LIMIT}.\n * @remarks Optional optimization. Stores that omit it remain compatible; callers may use a\n * bounded, non-authoritative fallback through the pre-existing list and event-key methods.\n */\n listPendingExecutionResults?(params: {\n tenantId: string;\n taskId: string;\n limit: number;\n }): Promise<TaskWorkItem[]>;\n\n /**\n * Lists canonical lifecycle events in an exact project scope.\n *\n * @param query Exact scope, actions, exclusive cursor, and page bound.\n * @returns Events ordered by creation time and ID descending.\n */\n listProjectLifecycleEvents?(query: ProjectLifecycleEventQuery): Promise<TaskWorkItem[]>;\n\n /**\n * Find an event by deterministic identity without list pagination.\n *\n * @param tenantId Tenant identifier.\n * @param taskId Task identifier that scopes the event key.\n * @param eventKey Deterministic event identity.\n * @returns The matching item, or `null` when absent.\n */\n findByEventKey(tenantId: string, taskId: string, eventKey: string): Promise<TaskWorkItem | null>;\n\n /**\n * Atomically create an event unless its task-scoped key already exists.\n * Existing events are returned unchanged, preserving immutable replay.\n *\n * @param params Work-item fields including the required event key.\n * @returns The existing or newly created work item.\n */\n createIfAbsentByEventKey(params: CreateWorkItemIfAbsentRequest): Promise<TaskWorkItem>;\n}\n\n/** Work-item capabilities required by trusted Project Task consumers. */\nexport interface ProjectTaskWorkItemStore extends TaskWorkItemStore {\n createIfTaskSnapshot(\n params: CreateWorkItemRequest,\n snapshot: TaskMutationSnapshot,\n ): Promise<TaskWorkItem | null>;\n listProjectLifecycleEvents(\n query: ProjectLifecycleEventQuery,\n ): Promise<TaskWorkItem[]>;\n}\n\n/** Stable capability failure raised before any trusted Project Task mutation. */\nexport class ProjectTaskStoreUnsupportedError extends Error {\n readonly code = \"PROJECT_TASK_STORE_UNSUPPORTED\" as const;\n\n constructor(readonly missingMethods: readonly string[]) {\n super(`Project Task WorkItem store is missing: ${missingMethods.join(\", \")}`);\n this.name = \"ProjectTaskStoreUnsupportedError\";\n }\n}\n\n/** Refines a Main-compatible WorkItem store for trusted Project Task consumers. */\nexport function requireProjectTaskWorkItemStore(\n store: TaskWorkItemStore,\n): ProjectTaskWorkItemStore {\n const missingMethods = [\"createIfTaskSnapshot\", \"listProjectLifecycleEvents\"]\n .filter((name) => {\n try {\n return typeof Reflect.get(store as object, name) !== \"function\";\n } catch {\n return true;\n }\n });\n if (missingMethods.length > 0) {\n throw new ProjectTaskStoreUnsupportedError(missingMethods);\n }\n return store as ProjectTaskWorkItemStore;\n}\n","/**\n * A single canonical belief recorded in a task description.\n *\n * `probability` is retained as the persisted field name, but task guidance uses\n * it as an evidence-support percentage rather than a calibrated probability.\n */\nexport interface TaskBeliefEntry {\n key: string;\n probability: number;\n target: number;\n basis: string;\n}\n\n/** The canonical belief snapshot embedded in task Markdown. */\nexport interface TaskBeliefState {\n entries: TaskBeliefEntry[];\n}\n\n/** Stable diagnostic identifiers returned by the Belief State parser. */\nexport type TaskBeliefDiagnosticCode =\n | \"MISSING_BELIEF_STATE\"\n | \"DUPLICATE_BELIEF_STATE\"\n | \"INVALID_BELIEF_HEADERS\"\n | \"MALFORMED_BELIEF_ROW\"\n | \"INVALID_BELIEF_KEY\"\n | \"INVALID_BELIEF_PERCENT\"\n | \"DUPLICATE_BELIEF_KEY\";\n\n/** A structured failure produced while parsing a task Belief State. */\nexport interface TaskBeliefParseFailure {\n success: false;\n code: TaskBeliefDiagnosticCode;\n message: string;\n line?: number;\n key?: string;\n column?: \"probability\" | \"target\";\n}\n\n/** A successfully parsed task Belief State. */\nexport interface TaskBeliefParseSuccess {\n success: true;\n state: TaskBeliefState;\n}\n\n/** The discriminated result of parsing a task Belief State. */\nexport type TaskBeliefParseResult = TaskBeliefParseSuccess | TaskBeliefParseFailure;\n\ninterface MarkdownLine {\n text: string;\n start: number;\n end: number;\n fenced: boolean;\n lineNumber: number;\n}\n\ninterface SectionRange {\n headingLine: number;\n start: number;\n end: number;\n}\n\nconst BELIEF_HEADING = \"## Belief State\";\nconst ACCEPTANCE_HEADING = \"## Acceptance Criteria\";\nconst EXPECTED_HEADERS = [\"Belief Key\", \"Probability\", \"Target\", \"Basis\"];\nconst KEY_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\nconst PERCENT_PATTERN = /^(?:100|[0-9]{1,2})%$/;\n\nfunction markdownLines(markdown: string): MarkdownLine[] {\n const lines: MarkdownLine[] = [];\n let start = 0;\n let fence: { marker: \"`\" | \"~\"; length: number } | undefined;\n\n while (start <= markdown.length) {\n const newline = markdown.indexOf(\"\\n\", start);\n const end = newline === -1 ? markdown.length : newline + 1;\n const textEnd = newline === -1 ? markdown.length : newline;\n const rawText = markdown.slice(start, textEnd);\n const text = rawText.endsWith(\"\\r\") ? rawText.slice(0, -1) : rawText;\n const fenceMatch = text.match(/^ {0,3}(`{3,}|~{3,})/);\n const fenced = fence !== undefined;\n\n if (!fence && fenceMatch) {\n const marker = fenceMatch[1][0] as \"`\" | \"~\";\n fence = { marker, length: fenceMatch[1].length };\n } else if (fence) {\n const closePattern = new RegExp(`^ {0,3}\\\\${fence.marker}{${fence.length},}[ \\\\t]*$`);\n if (closePattern.test(text)) fence = undefined;\n }\n\n lines.push({\n text,\n start,\n end,\n fenced: fenced || fenceMatch !== null,\n lineNumber: lines.length + 1,\n });\n if (newline === -1) break;\n start = end;\n }\n\n return lines;\n}\n\nfunction sectionRanges(markdown: string, heading: string): SectionRange[] {\n const lines = markdownLines(markdown);\n const ranges: SectionRange[] = [];\n\n for (let index = 0; index < lines.length; index += 1) {\n const line = lines[index];\n if (line.fenced || line.text.trimEnd().replace(/^ {0,3}/, \"\") !== heading) continue;\n\n let end = markdown.length;\n for (let next = index + 1; next < lines.length; next += 1) {\n if (!lines[next].fenced && /^ {0,3}#{1,2}(?:[ \\t]+|$)/.test(lines[next].text)) {\n end = lines[next].start;\n break;\n }\n }\n ranges.push({ headingLine: index, start: line.start, end });\n }\n\n return ranges;\n}\n\nfunction splitTableRow(line: string): string[] | undefined {\n const trimmed = line.trim();\n const finalPipe = trimmed.length - 1;\n if (!trimmed.startsWith(\"|\") || !trimmed.endsWith(\"|\") || isEscapedPipe(trimmed, finalPipe)) {\n return undefined;\n }\n\n const cells: string[] = [];\n let cell = \"\";\n for (let index = 1; index < trimmed.length - 1; index += 1) {\n const character = trimmed[index];\n if (character === \"|\" && isEscapedPipe(trimmed, index)) {\n cell += character;\n } else if (character === \"|\") {\n cells.push(unescapeTableCell(cell.trim()));\n cell = \"\";\n } else {\n cell += character;\n }\n }\n cells.push(unescapeTableCell(cell.trim()));\n return cells;\n}\n\nfunction unescapeTableCell(cell: string): string {\n let unescaped = \"\";\n for (let index = 0; index < cell.length; index += 1) {\n if (cell[index] === \"\\\\\" && (cell[index + 1] === \"\\\\\" || cell[index + 1] === \"|\")) {\n index += 1;\n }\n unescaped += cell[index];\n }\n return unescaped;\n}\n\nfunction isEscapedPipe(line: string, pipeIndex: number): boolean {\n let backslashes = 0;\n for (let index = pipeIndex - 1; index >= 0 && line[index] === \"\\\\\"; index -= 1) {\n backslashes += 1;\n }\n return backslashes % 2 === 1;\n}\n\nfunction failure(\n code: TaskBeliefDiagnosticCode,\n message: string,\n details: Pick<TaskBeliefParseFailure, \"line\" | \"key\" | \"column\"> = {},\n): TaskBeliefParseFailure {\n return { success: false, code, message, ...details };\n}\n\nfunction normalizedText(value: string): string {\n return value.trim().replace(/\\s+/g, \" \");\n}\n\nfunction validateTaskBeliefState(state: TaskBeliefState): void {\n const keys = new Set<string>();\n for (const entry of state.entries) {\n if (!KEY_PATTERN.test(entry.key)) {\n throw new Error(\"Belief keys must be kebab-case without backticks or newlines.\");\n }\n if (keys.has(entry.key)) {\n throw new Error(`Belief key '${entry.key}' appears more than once.`);\n }\n for (const field of [\"probability\", \"target\"] as const) {\n const value = entry[field];\n if (!Number.isInteger(value) || value < 0 || value > 100) {\n throw new Error(`Belief ${field} must be an integer from 0 to 100.`);\n }\n }\n if (entry.basis.trim().length === 0 || /[\\r\\n]/.test(entry.basis)) {\n throw new Error(\"Belief basis must be a nonempty single line.\");\n }\n keys.add(entry.key);\n }\n}\n\nfunction formatTaskBeliefState(state: TaskBeliefState): string {\n validateTaskBeliefState(state);\n const rows = state.entries.map(({ key, probability, target, basis }) => {\n const escapedBasis = normalizedText(basis).replace(/\\\\/g, \"\\\\\\\\\").replace(/\\|/g, \"\\\\|\");\n return `| \\`${key}\\` | ${probability}% | ${target}% | ${escapedBasis} |`;\n });\n return [\n BELIEF_HEADING,\n \"\",\n \"| Belief Key | Probability | Target | Basis |\",\n \"|---|---:|---:|---|\",\n ...rows,\n ].join(\"\\n\");\n}\n\n/** Parses the unique non-code-fenced canonical Belief State section in Markdown. */\nexport function parseTaskBeliefState(markdown: string): TaskBeliefParseResult {\n const sections = sectionRanges(markdown, BELIEF_HEADING);\n if (sections.length === 0) {\n return failure(\"MISSING_BELIEF_STATE\", \"Markdown does not contain a Belief State section.\");\n }\n if (sections.length > 1) {\n return failure(\"DUPLICATE_BELIEF_STATE\", \"Markdown contains more than one Belief State section.\");\n }\n\n const lines = markdownLines(markdown);\n const section = sections[0];\n const content = lines\n .slice(section.headingLine + 1)\n .filter((line) => line.start < section.end && line.text.trim() !== \"\");\n const header = content[0] && splitTableRow(content[0].text);\n const separator = content[1] && splitTableRow(content[1].text);\n if (\n !header ||\n header.length !== EXPECTED_HEADERS.length ||\n header.some((cell, index) => cell !== EXPECTED_HEADERS[index]) ||\n !separator ||\n separator.length !== EXPECTED_HEADERS.length ||\n separator.some((cell) => !/^:?-{3,}:?$/.test(cell))\n ) {\n return failure(\"INVALID_BELIEF_HEADERS\", \"Belief State must use the canonical four-column headers.\");\n }\n\n const entries: TaskBeliefEntry[] = [];\n const keys = new Set<string>();\n for (const line of content.slice(2)) {\n const cells = splitTableRow(line.text);\n if (!cells || cells.length !== 4 || cells[3].length === 0) {\n return failure(\"MALFORMED_BELIEF_ROW\", \"Belief State contains a malformed row.\", {\n line: line.lineNumber,\n });\n }\n\n const keyMatch = cells[0].match(/^`([^`]+)`$/);\n if (!keyMatch || !KEY_PATTERN.test(keyMatch[1])) {\n return failure(\"INVALID_BELIEF_KEY\", \"Belief keys must be backtick-wrapped kebab-case.\", {\n line: line.lineNumber,\n });\n }\n const key = keyMatch[1];\n if (keys.has(key)) {\n return failure(\"DUPLICATE_BELIEF_KEY\", `Belief key '${key}' appears more than once.`, {\n line: line.lineNumber,\n key,\n });\n }\n\n for (const [index, column] of [[1, \"probability\"], [2, \"target\"]] as const) {\n if (!PERCENT_PATTERN.test(cells[index])) {\n return failure(\"INVALID_BELIEF_PERCENT\", `Belief ${column} must be an integer from 0% to 100%.`, {\n line: line.lineNumber,\n column,\n });\n }\n }\n\n keys.add(key);\n entries.push({\n key,\n probability: Number.parseInt(cells[1], 10),\n target: Number.parseInt(cells[2], 10),\n basis: cells[3],\n });\n }\n\n return { success: true, state: { entries } };\n}\n\n/** Compares two Belief States while ignoring entry order and insignificant whitespace. */\nexport function taskBeliefStatesEqual(left: TaskBeliefState, right: TaskBeliefState): boolean {\n if (left.entries.length !== right.entries.length) return false;\n\n const byKey = new Map(right.entries.map((entry) => [entry.key, entry]));\n return left.entries.every((entry) => {\n const other = byKey.get(entry.key);\n return other !== undefined &&\n entry.probability === other.probability &&\n entry.target === other.target &&\n normalizedText(entry.basis) === normalizedText(other.basis);\n });\n}\n\n/**\n * Replaces a unique Belief State section, or inserts one after Acceptance Criteria content.\n *\n * @throws {Error} If the state is noncanonical or the Markdown contains duplicate sections.\n */\nexport function replaceTaskBeliefState(markdown: string, state: TaskBeliefState): string {\n const replacement = formatTaskBeliefState(state);\n const sections = sectionRanges(markdown, BELIEF_HEADING);\n if (sections.length > 1) {\n throw new Error(\"Cannot replace duplicate Belief State sections.\");\n }\n if (sections.length === 1) {\n const section = sections[0];\n const originalSection = markdown.slice(section.start, section.end);\n const trailingWhitespace = originalSection.match(/\\s*$/)?.[0] ?? \"\";\n return markdown.slice(0, section.start) + replacement + trailingWhitespace + markdown.slice(section.end);\n }\n\n const acceptance = sectionRanges(markdown, ACCEPTANCE_HEADING)[0];\n const insertion = acceptance?.end ?? markdown.length;\n const before = markdown.slice(0, insertion);\n const after = markdown.slice(insertion);\n const leadingBreaks = before.length === 0 ? \"\" : before.endsWith(\"\\n\\n\") ? \"\" : before.endsWith(\"\\n\") ? \"\\n\" : \"\\n\\n\";\n const trailingBreaks = after.length === 0 ? \"\" : after.startsWith(\"\\n\") ? \"\\n\" : \"\\n\\n\";\n return before + leadingBreaks + replacement + trailingBreaks + after;\n}\n","import type {\n AgentWebAppAppearance,\n AgentWebAppFeatures,\n} from \"./AgentWebAppStoreProtocol\";\n\n/** Server-owned metadata that isolates an external user's Web App thread. */\nexport interface AgentWebAppThreadMetadata {\n source: \"web_app\";\n webAppId: string;\n userId: string;\n projectId: string;\n label?: string;\n}\n\n/** Public, redacted projection of a thread owned by an Agent Web App identity. */\nexport interface AgentWebAppRuntimeThread {\n id: string;\n projectId: string;\n label?: string;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/** Reviewed public message projection. Structured internal content is not exposed. */\nexport interface AgentWebAppRuntimeMessage {\n id: string;\n role: \"human\" | \"ai\";\n content?: string | AgentWebAppGenUIBlock[];\n}\n\nexport interface AgentWebAppCalloutWidget {\n kind: \"callout\";\n text: string;\n title?: string;\n tone?: \"info\" | \"success\" | \"warning\";\n}\n\nexport interface AgentWebAppTableWidget {\n kind: \"table\";\n columns: string[];\n rows: string[][];\n caption?: string;\n}\n\n/** V1 declarative GenUI block. It deliberately has no HTML, URL, or executable fields. */\nexport interface AgentWebAppGenUIBlock {\n type: \"widget\";\n widget: AgentWebAppCalloutWidget | AgentWebAppTableWidget;\n}\n\n/** Public initialization data available to an external Agent Web App. */\nexport interface AgentWebAppBootstrap {\n webApp: {\n id: string;\n name: string;\n description?: string;\n assistant: {\n id: string;\n name: string;\n description?: string;\n };\n defaultProjectId: string;\n defaultModelKey?: string;\n features: AgentWebAppFeatures;\n appearance: AgentWebAppAppearance;\n identityAssurance: \"unverified\";\n };\n projects: Array<{\n id: string;\n name: string;\n }>;\n models: Array<{\n key: string;\n label: string;\n }>;\n /** Latest owned thread, created implicitly only when thread management is disabled. */\n thread?: AgentWebAppRuntimeThread;\n}\n\n/** Human-in-the-loop interruption exposed through the Web App runtime. */\nexport interface AgentWebAppInterrupt {\n id: string;\n type: string;\n prompt: string;\n data?: Record<string, unknown>;\n}\n\n/**\n * Stable machine-readable error codes returned by the Web App runtime.\n *\n * `INVALID_REQUEST` covers redacted request-validation failures and\n * `INTERNAL_ERROR` covers redacted unexpected server failures.\n */\nexport type AgentWebAppErrorCode =\n | \"WEB_APP_NOT_FOUND\"\n | \"WEB_APP_DISABLED\"\n | \"USER_ID_REQUIRED\"\n | \"INVALID_USER_ID\"\n | \"PROJECT_NOT_ALLOWED\"\n | \"PROJECT_SELECTOR_DISABLED\"\n | \"MODEL_NOT_ALLOWED\"\n | \"FEATURE_DISABLED\"\n | \"THREAD_NOT_FOUND\"\n | \"STREAM_CONFLICT\"\n | \"STREAM_FAILED\"\n | \"INVALID_REQUEST\"\n | \"INTERNAL_ERROR\";\n\n/** Public error payload returned by the Web App runtime. */\nexport interface AgentWebAppError {\n code: AgentWebAppErrorCode;\n message: string;\n retryable: boolean;\n}\n\n/** Stable stream events projected from internal agent execution output. */\nexport type AgentWebAppStreamEvent =\n | { type: \"message.delta\"; text: string }\n | { type: \"message.completed\"; messageId: string }\n | { type: \"tool.started\"; id: string; name: string }\n | { type: \"tool.completed\"; id: string }\n | { type: \"interrupt.created\"; interrupt: AgentWebAppInterrupt }\n | { type: \"genui.render\"; block: AgentWebAppGenUIBlock }\n | { type: \"error\"; error: AgentWebAppError }\n | { type: \"stream.completed\" };\n\nconst MAX_WIDGET_TEXT = 2_000;\nconst MAX_TABLE_COLUMNS = 12;\nconst MAX_TABLE_ROWS = 100;\n\n/** Validate and copy one strict public GenUI block at a trust boundary. */\nexport function parseAgentWebAppGenUIBlock(value: unknown): AgentWebAppGenUIBlock | undefined {\n if (!isExactRecord(value, [\"type\", \"widget\"]) || value.type !== \"widget\" || !isRecord(value.widget)) return undefined;\n const widget = value.widget;\n if (widget.kind === \"callout\") {\n if (!hasOnlyKeys(widget, [\"kind\", \"text\"], [\"title\", \"tone\"]) || !boundedText(widget.text)) return undefined;\n if (widget.title !== undefined && !boundedText(widget.title)) return undefined;\n if (widget.tone !== undefined && widget.tone !== \"info\" && widget.tone !== \"success\" && widget.tone !== \"warning\") return undefined;\n return { type: \"widget\", widget: { kind: \"callout\", text: widget.text, ...(typeof widget.title === \"string\" ? { title: widget.title } : {}), ...(widget.tone ? { tone: widget.tone } : {}) } };\n }\n if (widget.kind === \"table\") {\n if (!hasOnlyKeys(widget, [\"kind\", \"columns\", \"rows\"], [\"caption\"]) || !Array.isArray(widget.columns) || !Array.isArray(widget.rows)) return undefined;\n const columns = widget.columns;\n const rows = widget.rows;\n if (columns.length === 0 || columns.length > MAX_TABLE_COLUMNS || !columns.every(boundedText)) return undefined;\n if (rows.length > MAX_TABLE_ROWS || !rows.every((row) => Array.isArray(row) && row.length === columns.length && row.every(boundedText))) return undefined;\n if (widget.caption !== undefined && !boundedText(widget.caption)) return undefined;\n return { type: \"widget\", widget: { kind: \"table\", columns: [...columns], rows: rows.map((row) => [...row]), ...(typeof widget.caption === \"string\" ? { caption: widget.caption } : {}) } };\n }\n return undefined;\n}\n\nfunction boundedText(value: unknown): value is string {\n return typeof value === \"string\" && value.length <= MAX_WIDGET_TEXT;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isExactRecord(value: unknown, keys: string[]): value is Record<string, unknown> {\n return isRecord(value) && Object.keys(value).length === keys.length && keys.every((key) => key in value);\n}\n\nfunction hasOnlyKeys(value: Record<string, unknown>, required: string[], optional: string[]): boolean {\n const keys = Object.keys(value);\n return required.every((key) => key in value) && keys.every((key) => required.includes(key) || optional.includes(key));\n}\n","/** A safely extracted value from an own enumerable data-property descriptor. */\nexport interface DescriptorDataValue {\n ok: true;\n value: unknown;\n}\n\nfunction ownDescriptorField(descriptor: object, key: string): unknown {\n const field = Object.getOwnPropertyDescriptor(descriptor, key);\n return field && Object.prototype.hasOwnProperty.call(field, \"value\")\n ? field.value\n : undefined;\n}\n\n/**\n * Reads an own enumerable data-property descriptor without consulting its prototype.\n *\n * @param descriptor Property descriptor to inspect.\n * @returns The descriptor value when it is an own enumerable data descriptor, otherwise `undefined`.\n */\nexport function descriptorDataValue(descriptor: unknown): DescriptorDataValue | undefined {\n if (typeof descriptor !== \"object\" || descriptor === null) return undefined;\n try {\n const keys = Reflect.ownKeys(descriptor);\n if (!keys.includes(\"value\") || !keys.includes(\"enumerable\")\n || keys.includes(\"get\") || keys.includes(\"set\")) return undefined;\n const valueField = Object.getOwnPropertyDescriptor(descriptor, \"value\");\n if (!valueField || !Object.prototype.hasOwnProperty.call(valueField, \"value\")\n || ownDescriptorField(descriptor, \"enumerable\") !== true) return undefined;\n return { ok: true, value: valueField.value };\n } catch {\n return undefined;\n }\n}\n\n/**\n * Copies an object-like value into a local plain record using only exact own enumerable data descriptors.\n *\n * Prototypes are deliberately ignored so records from other JavaScript realms remain valid and inherited\n * behavior can never participate in validation.\n *\n * @param value Untrusted value to snapshot.\n * @param required Own string keys that must be present.\n * @param optional Own string keys that may be present.\n * @returns A canonical local record, or `undefined` for malformed descriptors, keys, arrays, or proxies.\n */\nexport function snapshotExactRecord(\n value: unknown,\n required: readonly string[],\n optional: readonly string[] = [],\n): Record<string, unknown> | undefined {\n try {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return undefined;\n const keys = Reflect.ownKeys(value);\n const allowed = new Set([...required, ...optional]);\n if (required.some((key) => !keys.includes(key))\n || keys.some((key) => typeof key !== \"string\" || !allowed.has(key))) return undefined;\n const descriptors = Object.getOwnPropertyDescriptors(value);\n const descriptorKeys = Reflect.ownKeys(descriptors);\n if (descriptorKeys.length !== keys.length || keys.some((key) => !descriptorKeys.includes(key))) return undefined;\n const result: Record<string, unknown> = {};\n for (const key of keys) {\n if (typeof key !== \"string\") return undefined;\n const descriptor = descriptors[key];\n const data = descriptorDataValue(descriptor);\n if (!data) return undefined;\n Object.defineProperty(result, key, {\n value: data.value,\n enumerable: true,\n configurable: true,\n writable: true,\n });\n }\n return result;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Copies a dense cross-realm array using only own element data descriptors and the intrinsic length descriptor.\n *\n * @param value Untrusted value to snapshot.\n * @returns A canonical local dense array, or `undefined` for holes, extras, accessors, or malformed proxies.\n */\nexport function snapshotExactArray(value: unknown): unknown[] | undefined {\n try {\n if (!Array.isArray(value)) return undefined;\n const keys = Reflect.ownKeys(value);\n const descriptors = Object.getOwnPropertyDescriptors(value);\n const descriptorKeys = Reflect.ownKeys(descriptors);\n if (descriptorKeys.length !== keys.length || keys.some((key) => !descriptorKeys.includes(key))) return undefined;\n const lengthDescriptorField = Object.getOwnPropertyDescriptor(descriptors, \"length\");\n const lengthDescriptor = lengthDescriptorField\n && Object.prototype.hasOwnProperty.call(lengthDescriptorField, \"value\")\n ? lengthDescriptorField.value\n : undefined;\n if (typeof lengthDescriptor !== \"object\" || lengthDescriptor === null\n || Reflect.ownKeys(lengthDescriptor).some((key) => key === \"get\" || key === \"set\")\n || !Object.prototype.hasOwnProperty.call(lengthDescriptor, \"value\")) return undefined;\n const length = ownDescriptorField(lengthDescriptor, \"value\");\n if (ownDescriptorField(lengthDescriptor, \"enumerable\") !== false\n || ownDescriptorField(lengthDescriptor, \"configurable\") !== false\n || ownDescriptorField(lengthDescriptor, \"writable\") !== true\n || !Number.isSafeInteger(length) || typeof length !== \"number\" || length < 0\n || keys.length !== length + 1) return undefined;\n const result: unknown[] = [];\n for (let index = 0; index < length; index += 1) {\n const key = String(index);\n const descriptor = descriptors[key];\n const data = descriptorDataValue(descriptor);\n if (!keys.includes(key) || !data) return undefined;\n result.push(data.value);\n }\n if (keys.some((key) => typeof key !== \"string\" || (key !== \"length\" && !/^(0|[1-9]\\d*)$/.test(key)))) return undefined;\n return result;\n } catch {\n return undefined;\n }\n}\n","import type {\n ProjectBotMembershipStatus,\n ProjectBotRole,\n ProjectHumanRole,\n ProjectMembershipStatus,\n ProjectRoomMention,\n ProjectRoomMessageSource,\n} from \"./ProjectRoomProtocol\";\nimport type { TaskItem } from \"./TaskStoreProtocol\";\nimport { snapshotExactArray, snapshotExactRecord } from \"./ExactDataSnapshot\";\n\n/** A message shape safe to expose to Project Room clients. */\nexport interface ProjectRoomPublicMessage {\n id: string;\n roomId: string;\n author:\n | { type: \"human\"; userId: string }\n | { type: \"bot\"; membershipId: string }\n | { type: \"system\" };\n content: { type: \"text\"; text: string };\n mentions: ProjectRoomMention[];\n replyToMessageId?: string;\n source: ProjectRoomMessageSource;\n createdAt: string;\n}\n\n/** A human membership shape safe to expose to Project Room clients. */\nexport interface ProjectRoomPublicMembership {\n id: string;\n userId: string;\n role: ProjectHumanRole;\n status: ProjectMembershipStatus;\n joinedAt: string;\n updatedAt: string;\n}\n\n/** A bot membership shape safe to expose to Project Room clients. */\nexport interface ProjectRoomPublicBotMembership {\n id: string;\n role: ProjectBotRole;\n title: string;\n responsibility?: string;\n mentionName: string;\n status: ProjectBotMembershipStatus;\n joinedAt: string;\n updatedAt: string;\n}\n\n/** A fully identified business event carried by the realtime stream. */\nexport interface ProjectRoomEventOf<TType extends string, TData> {\n id: string;\n type: TType;\n occurredAt: string;\n data: TData;\n}\n\n/** A newly committed message event. */\nexport type ProjectRoomMessageCreatedEvent = ProjectRoomEventOf<\n \"message.created\",\n { message: ProjectRoomPublicMessage }\n>;\n\n/** A changed bot roster event. */\nexport type ProjectRoomRosterChangedEvent = ProjectRoomEventOf<\n \"roster.changed\",\n { change: \"added\" | \"updated\" | \"paused\" | \"resumed\" | \"removed\"; membership: ProjectRoomPublicBotMembership }\n>;\n\n/** A changed human membership event. */\nexport type ProjectRoomMembershipChangedEvent = ProjectRoomEventOf<\n \"membership.changed\",\n { change: \"added\" | \"role_changed\" | \"removed\"; membership: ProjectRoomPublicMembership }\n>;\n\n/** A changed Project Task fact event. */\nexport type ProjectRoomTaskChangedEvent = ProjectRoomEventOf<\n \"task.changed\",\n {\n taskId: string;\n status: TaskItem[\"status\"];\n ownerMembershipId: string;\n updatedAt: string;\n }\n>;\n\n/** All identified business events retained by the realtime broker. */\nexport type ProjectRoomBusinessEvent =\n | ProjectRoomMessageCreatedEvent\n | ProjectRoomRosterChangedEvent\n | ProjectRoomMembershipChangedEvent\n | ProjectRoomTaskChangedEvent;\n\n/** A business event before the broker assigns its process-local ID. */\nexport type ProjectRoomBusinessEventDraft =\n | Omit<ProjectRoomMessageCreatedEvent, \"id\">\n | Omit<ProjectRoomRosterChangedEvent, \"id\">\n | Omit<ProjectRoomMembershipChangedEvent, \"id\">\n | Omit<ProjectRoomTaskChangedEvent, \"id\">;\n\n/** A connection control event; control events are never replayed. */\nexport type ProjectRoomControlEvent =\n | { type: \"ready\"; data: { epoch: string; headEventId: string | null } }\n | { type: \"resync\"; data: { reason: \"SERVER_RESTART\" | \"CURSOR_EXPIRED\" | \"SLOW_CONSUMER\" } }\n | { type: \"access.revoked\"; data: { reason: \"PROJECT_ACCESS_REVOKED\" | \"TOKEN_EXPIRED\" } };\n\n/** The authenticated identity used by Project Room realtime access checks. */\nexport interface ProjectRoomRealtimeActor {\n tenantId: string;\n userId: string;\n projectId: string;\n tokenExpiresAt: number;\n}\n\n/** Writable HTTP socket surface required by the bounded SSE transport. */\nexport interface ProjectRoomSseWritable {\n write(chunk: string): boolean;\n end(): void;\n destroy(): void;\n on(event: \"close\" | \"error\" | \"drain\", listener: () => void): this;\n off(event: \"close\" | \"error\" | \"drain\", listener: () => void): this;\n}\n\n/** The scope used to isolate events between tenant rooms. */\nexport interface ProjectRoomEventScope {\n tenantId: string;\n roomId: string;\n projectId: string;\n}\n\n/** An internal broker event carrying scope that is removed before public serialization. */\nexport type ProjectRoomScopedBusinessEvent = ProjectRoomBusinessEvent & {\n scope: ProjectRoomEventScope;\n};\n\n/** A broker subscription containing replay and its room head. */\nexport interface ProjectRoomEventSubscription {\n replay: ProjectRoomBusinessEvent[];\n headEventId: string | null;\n unsubscribe(): void;\n}\n\n/** The narrow broker contract consumed by realtime publishers and services. */\nexport interface ProjectRoomEventBrokerProtocol {\n readonly epoch: string;\n publish(scope: ProjectRoomEventScope, draft: ProjectRoomBusinessEventDraft): ProjectRoomScopedBusinessEvent;\n subscribe(\n scope: ProjectRoomEventScope,\n afterEventId: string | undefined,\n listener: (event: ProjectRoomBusinessEvent) => void,\n ): ProjectRoomEventSubscription;\n close(): void;\n}\n\n/** A typed cursor failure requiring client REST resynchronization. */\nexport class ProjectRoomCursorError extends Error {\n readonly name = \"ProjectRoomCursorError\";\n\n constructor(readonly code: \"SERVER_RESTART\" | \"CURSOR_EXPIRED\") {\n super(`Project Room realtime cursor requires resynchronization: ${code}`);\n }\n}\n\n/** A typed failure raised when the process-local event sequence is exhausted. */\nexport class ProjectRoomBrokerCapacityError extends Error {\n readonly name = \"ProjectRoomBrokerCapacityError\";\n readonly code = \"PROJECT_ROOM_EVENT_SEQUENCE_EXHAUSTED\" as const;\n\n constructor() {\n super(\"Project Room realtime event sequence is exhausted\");\n }\n}\n\nconst PROJECT_ROOM_EVENT_ID_PATTERN = /^([0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}):([1-9][0-9]*)$/i;\n\n/** The parsed components of a canonical Project Room event ID. */\nexport interface ProjectRoomEventId {\n epoch: string;\n sequence: number;\n}\n\n/** Parses a canonical event ID, returning undefined for malformed or unsafe IDs. */\nexport function parseProjectRoomEventId(value: unknown): ProjectRoomEventId | undefined {\n if (typeof value !== \"string\") return undefined;\n const match = PROJECT_ROOM_EVENT_ID_PATTERN.exec(value);\n if (!match) return undefined;\n const sequence = Number(match[2]);\n if (!Number.isSafeInteger(sequence)) return undefined;\n if (match[1] !== match[1].toLowerCase()) return undefined;\n return { epoch: match[1], sequence };\n}\n\n/** Checks an event ID without relying on realm-specific object identity. */\nexport function isProjectRoomEventId(value: unknown): value is string {\n return parseProjectRoomEventId(value) !== undefined;\n}\n\nfunction isoDate(value: unknown): string | undefined {\n if (typeof value !== \"object\" || value === null) return undefined;\n try {\n const time = Date.prototype.getTime.call(value);\n return Number.isFinite(time) ? new Date(time).toISOString() : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction stringField(record: Record<string, unknown>, key: string): string | undefined {\n return typeof record[key] === \"string\" ? record[key] : undefined;\n}\n\nfunction isOneOf<T extends string>(value: unknown, values: readonly T[]): value is T {\n return typeof value === \"string\" && values.includes(value as T);\n}\n\nconst messageSources = [\"user\", \"agent\", \"task\", \"routine\", \"system\"] as const;\nconst humanRoles = [\"owner\", \"admin\", \"member\", \"viewer\"] as const;\nconst membershipStatuses = [\"active\", \"removed\"] as const;\nconst botRoles = [\"coordinator\", \"specialist\"] as const;\nconst botStatuses = [\"active\", \"paused\", \"removed\"] as const;\n\nfunction mapPublicMessageRecord(record: Record<string, unknown>): ProjectRoomPublicMessage | undefined {\n const id = stringField(record, \"id\");\n const roomId = stringField(record, \"roomId\");\n const source = stringField(record, \"source\");\n const createdAt = isoDate(record.createdAt);\n const content = snapshotExactRecord(record.content, [\"type\", \"text\"]);\n const mentions = snapshotPublicMentions(record.mentions);\n const author = snapshotExactRecord(record.author, [\"type\"], [\"userId\", \"membershipId\", \"assistantId\"]);\n if (!id || !roomId || !isOneOf(source, messageSources) || !createdAt || !content || content.type !== \"text\"\n || typeof content.text !== \"string\" || !mentions || !author || typeof author.type !== \"string\") return undefined;\n const publicAuthor = author.type === \"human\" && typeof author.userId === \"string\"\n ? { type: \"human\" as const, userId: author.userId }\n : author.type === \"bot\" && typeof author.membershipId === \"string\"\n ? { type: \"bot\" as const, membershipId: author.membershipId }\n : author.type === \"system\" ? { type: \"system\" as const } : undefined;\n if (!publicAuthor) return undefined;\n const result: ProjectRoomPublicMessage = { id, roomId, author: publicAuthor, content: { type: \"text\", text: content.text }, mentions: mentions as ProjectRoomMention[], source: source as ProjectRoomMessageSource, createdAt };\n if (record.replyToMessageId !== undefined) {\n if (typeof record.replyToMessageId !== \"string\") return undefined;\n result.replyToMessageId = record.replyToMessageId;\n }\n return result;\n}\n\nfunction snapshotPublicMentions(value: unknown): ProjectRoomMention[] | undefined {\n const rows = snapshotExactArray(value);\n if (!rows) return undefined;\n const result: ProjectRoomMention[] = [];\n for (const row of rows) {\n const team = snapshotExactRecord(row, [\"type\"]);\n if (team?.type === \"team\") { result.push({ type: \"team\" }); continue; }\n const bot = snapshotExactRecord(row, [\"type\", \"membershipId\"]);\n if (bot?.type === \"bot\" && typeof bot.membershipId === \"string\") {\n result.push({ type: \"bot\", membershipId: bot.membershipId });\n continue;\n }\n return undefined;\n }\n return result;\n}\n\nfunction mapPublicMembershipRecord(record: Record<string, unknown>): ProjectRoomPublicMembership | undefined {\n const joinedAt = isoDate(record.joinedAt); const updatedAt = isoDate(record.updatedAt);\n if (typeof record.id !== \"string\" || typeof record.userId !== \"string\" || !isOneOf(record.role, humanRoles) || !isOneOf(record.status, membershipStatuses) || !joinedAt || !updatedAt) return undefined;\n return { id: record.id, userId: record.userId, role: record.role, status: record.status, joinedAt, updatedAt };\n}\n\nfunction mapPublicBotMembershipRecord(record: Record<string, unknown>): ProjectRoomPublicBotMembership | undefined {\n const joinedAt = isoDate(record.joinedAt); const updatedAt = isoDate(record.updatedAt);\n if (typeof record.id !== \"string\" || !isOneOf(record.role, botRoles) || typeof record.title !== \"string\" || typeof record.mentionName !== \"string\" || !isOneOf(record.status, botStatuses) || !joinedAt || !updatedAt || record.responsibility !== undefined && typeof record.responsibility !== \"string\") return undefined;\n return { id: record.id, role: record.role, title: record.title, ...(record.responsibility === undefined ? {} : { responsibility: record.responsibility }), mentionName: record.mentionName, status: record.status, joinedAt, updatedAt };\n}\n\n/** Maps a canonical internal message to the strict public message DTO. */\nexport function toProjectRoomPublicMessage(value: unknown): ProjectRoomPublicMessage | undefined {\n const record = snapshotExactRecord(value, [\n \"id\", \"tenantId\", \"workspaceId\", \"projectId\", \"roomId\", \"author\", \"content\", \"mentions\", \"source\", \"createdAt\",\n ], [\"replyToMessageId\", \"sourceId\", \"idempotencyKey\"]);\n if (!record) return undefined;\n return mapPublicMessageRecord(record);\n}\n\n/** A descriptor-safe message projection together with its canonical realtime scope. */\nexport function snapshotProjectRoomMessageRealtime(value: unknown): {\n scope: { tenantId: string; roomId: string; projectId: string };\n publicMessage: ProjectRoomPublicMessage;\n} | undefined {\n const record = snapshotExactRecord(value, [\"id\", \"tenantId\", \"workspaceId\", \"projectId\", \"roomId\", \"author\", \"content\", \"mentions\", \"source\", \"createdAt\"], [\"replyToMessageId\", \"sourceId\", \"idempotencyKey\"]);\n if (!record) return undefined;\n const publicMessage = mapPublicMessageRecord(record);\n if (!publicMessage || typeof record.tenantId !== \"string\" || typeof record.projectId !== \"string\") return undefined;\n return { scope: { tenantId: record.tenantId, roomId: publicMessage.roomId, projectId: record.projectId }, publicMessage };\n}\n\n/** Maps a canonical internal human membership to the strict public DTO. */\nexport function toProjectRoomPublicMembership(value: unknown): ProjectRoomPublicMembership | undefined {\n const record = snapshotExactRecord(value,\n [\"id\", \"tenantId\", \"projectId\", \"userId\", \"role\", \"status\", \"joinedAt\", \"updatedAt\"]);\n if (!record || typeof record.id !== \"string\" || typeof record.userId !== \"string\"\n || !isOneOf(record.role, humanRoles) || !isOneOf(record.status, membershipStatuses)) return undefined;\n const joinedAt = isoDate(record.joinedAt);\n const updatedAt = isoDate(record.updatedAt);\n if (!joinedAt || !updatedAt) return undefined;\n return { id: record.id, userId: record.userId, role: record.role,\n status: record.status, joinedAt, updatedAt };\n}\n\n/** A descriptor-safe human membership projection with canonical tenant/project scope. */\nexport function snapshotProjectRoomMembershipRealtime(value: unknown): {\n scope: { tenantId: string; projectId: string };\n publicMembership: ProjectRoomPublicMembership;\n} | undefined {\n const record = snapshotExactRecord(value, [\"id\", \"tenantId\", \"projectId\", \"userId\", \"role\", \"status\", \"joinedAt\", \"updatedAt\"]);\n if (!record) return undefined;\n const publicMembership = mapPublicMembershipRecord(record);\n if (!publicMembership || typeof record.tenantId !== \"string\" || typeof record.projectId !== \"string\") return undefined;\n return { scope: { tenantId: record.tenantId, projectId: record.projectId }, publicMembership };\n}\n\n/** Maps a canonical internal bot membership to the strict public DTO. */\nexport function toProjectRoomPublicBotMembership(value: unknown): ProjectRoomPublicBotMembership | undefined {\n const record = snapshotExactRecord(value,\n [\"id\", \"tenantId\", \"workspaceId\", \"projectId\", \"roomId\", \"assistantId\", \"role\", \"title\", \"mentionName\", \"status\", \"roomThreadId\", \"joinedAt\", \"updatedAt\"],\n [\"responsibility\"]);\n if (!record || typeof record.id !== \"string\" || !isOneOf(record.role, botRoles) || typeof record.title !== \"string\"\n || typeof record.mentionName !== \"string\" || !isOneOf(record.status, botStatuses)) return undefined;\n if (record.responsibility !== undefined && typeof record.responsibility !== \"string\") return undefined;\n const joinedAt = isoDate(record.joinedAt);\n const updatedAt = isoDate(record.updatedAt);\n if (!joinedAt || !updatedAt) return undefined;\n const result: ProjectRoomPublicBotMembership = {\n id: record.id, role: record.role, title: record.title,\n mentionName: record.mentionName, status: record.status, joinedAt, updatedAt,\n };\n if (record.responsibility !== undefined) result.responsibility = record.responsibility;\n return result;\n}\n\n/** A descriptor-safe bot membership projection with canonical realtime scope. */\nexport function snapshotProjectRoomBotMembershipRealtime(value: unknown): {\n scope: { tenantId: string; roomId: string; projectId: string };\n publicMembership: ProjectRoomPublicBotMembership;\n} | undefined {\n const record = snapshotExactRecord(value, [\"id\", \"tenantId\", \"workspaceId\", \"projectId\", \"roomId\", \"assistantId\", \"role\", \"title\", \"mentionName\", \"status\", \"roomThreadId\", \"joinedAt\", \"updatedAt\"], [\"responsibility\"]);\n if (!record) return undefined;\n const publicMembership = mapPublicBotMembershipRecord(record);\n if (!publicMembership || typeof record.tenantId !== \"string\" || typeof record.roomId !== \"string\" || typeof record.projectId !== \"string\") return undefined;\n return { scope: { tenantId: record.tenantId, roomId: record.roomId, projectId: record.projectId }, publicMembership };\n}\n","import { snapshotExactRecord } from \"./ExactDataSnapshot\";\n\n/** Queue execution behavior available to privileged host dispatchers. */\nexport type QueuedExecutionMode = \"followup\";\n\n/** Trusted Project Room identity persisted with a privileged queue message. */\nexport interface ProjectRoomTrustedRunContext {\n tenantId: string;\n workspaceId: string;\n projectId: string;\n roomId: string;\n sourceRoomMessageId: string;\n membershipId: string;\n assistantId: string;\n inputMessageId: string;\n role: \"coordinator\" | \"specialist\";\n title: string;\n responsibility?: string;\n}\n\n/** Trusted Project Task identity persisted with a privileged queue message. */\nexport interface ProjectTaskTrustedRunContext {\n tenantId: string;\n workspaceId: string;\n projectId: string;\n roomId: string;\n membershipId: string;\n assistantId: string;\n taskId: string;\n threadId: string;\n inputMessageId: string;\n}\n\n/** Host-authenticated metadata that cannot be supplied through public Agent APIs. */\nexport interface TrustedRunContext {\n projectRoom?: ProjectRoomTrustedRunContext;\n projectTask?: ProjectTaskTrustedRunContext;\n}\n\n/**\n * Strictly validates and clones host-authenticated queue context read from durable storage.\n *\n * @param value - Untrusted decoded database value.\n * @returns A validated defensive clone of the trusted run context.\n * @throws Error when the stored value does not exactly match the trusted context contract.\n */\nexport function parseTrustedRunContext(value: unknown): TrustedRunContext {\n const contextValues = snapshotExactRecord(value, [], [\"projectRoom\", \"projectTask\"]);\n if (!contextValues || Object.keys(contextValues).length !== 1) {\n throw new Error(\"Invalid trusted agent run context\");\n }\n if (Object.prototype.hasOwnProperty.call(contextValues, \"projectTask\")) {\n const requiredKeys = [\n \"tenantId\", \"workspaceId\", \"projectId\", \"roomId\", \"membershipId\",\n \"assistantId\", \"taskId\", \"threadId\", \"inputMessageId\",\n ] as const;\n const projectTaskValues = snapshotExactRecord(contextValues.projectTask, requiredKeys);\n if (!projectTaskValues\n || requiredKeys.some((key) => typeof projectTaskValues[key] !== \"string\" || projectTaskValues[key].length === 0)) {\n throw new Error(\"Invalid trusted agent run context\");\n }\n return {\n projectTask: {\n tenantId: projectTaskValues.tenantId as string,\n workspaceId: projectTaskValues.workspaceId as string,\n projectId: projectTaskValues.projectId as string,\n roomId: projectTaskValues.roomId as string,\n membershipId: projectTaskValues.membershipId as string,\n assistantId: projectTaskValues.assistantId as string,\n taskId: projectTaskValues.taskId as string,\n threadId: projectTaskValues.threadId as string,\n inputMessageId: projectTaskValues.inputMessageId as string,\n },\n };\n }\n const projectRoomValue = contextValues?.projectRoom;\n const requiredKeys = [\n \"tenantId\", \"workspaceId\", \"projectId\", \"roomId\", \"sourceRoomMessageId\", \"membershipId\",\n \"assistantId\", \"inputMessageId\", \"role\", \"title\",\n ] as const;\n const projectRoomValues = snapshotExactRecord(projectRoomValue, requiredKeys, [\"responsibility\"]);\n const hasResponsibility = projectRoomValues !== undefined\n && Object.prototype.hasOwnProperty.call(projectRoomValues, \"responsibility\");\n if (!projectRoomValues\n || requiredKeys.some((key) => typeof projectRoomValues[key] !== \"string\" || projectRoomValues[key].length === 0)\n || (hasResponsibility && projectRoomValues.responsibility !== undefined\n && (typeof projectRoomValues.responsibility !== \"string\" || projectRoomValues.responsibility.length === 0))\n || (projectRoomValues.role !== \"coordinator\" && projectRoomValues.role !== \"specialist\")) {\n throw new Error(\"Invalid trusted agent run context\");\n }\n const parsedProjectRoom: ProjectRoomTrustedRunContext = {\n tenantId: projectRoomValues.tenantId as string,\n workspaceId: projectRoomValues.workspaceId as string,\n projectId: projectRoomValues.projectId as string,\n roomId: projectRoomValues.roomId as string,\n sourceRoomMessageId: projectRoomValues.sourceRoomMessageId as string,\n membershipId: projectRoomValues.membershipId as string,\n assistantId: projectRoomValues.assistantId as string,\n inputMessageId: projectRoomValues.inputMessageId as string,\n role: projectRoomValues.role,\n title: projectRoomValues.title as string,\n };\n if (hasResponsibility && typeof projectRoomValues.responsibility === \"string\") {\n parsedProjectRoom.responsibility = projectRoomValues.responsibility;\n }\n return { projectRoom: parsedProjectRoom };\n}\n\n/**\n * Strictly validates a queued execution mode read from durable storage.\n *\n * @param value - Untrusted database value.\n * @returns The validated execution mode.\n * @throws Error when the stored value is not supported.\n */\nexport function parseQueuedExecutionMode(value: unknown): QueuedExecutionMode {\n if (value !== \"followup\") throw new Error(\"Invalid queued execution mode\");\n return value;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACaO,IAAK,YAAL,kBAAKA,eAAL;AACL,EAAAA,WAAA,WAAQ;AACR,EAAAA,WAAA,gBAAa;AACb,EAAAA,WAAA,UAAO;AACP,EAAAA,WAAA,gBAAa;AAEb,EAAAA,WAAA,gBAAa;AAEb,EAAAA,WAAA,cAAW;AARD,SAAAA;AAAA,GAAA;AAkOL,SAAS,kBACd,QAC2B;AAC3B,SAAO,OAAO,SAAS;AACzB;AA4FO,SAAS,uBACd,QACgC;AAChC,SAAO,OAAO,SAAS;AACzB;AAKO,SAAS,sBACd,QAC+B;AAC/B,SAAO,OAAO,SAAS;AACzB;AA4BO,SAAS,SAAS,QAAqD;AAC5E,SAAO;AACT;AAKO,SAAS,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ScheduleType","ScheduleExecutionType","ScheduledTaskStatus","LoggerType","McpMessageType","requiredKeys"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/AgentLatticeProtocol.ts","../src/MemoryLatticeProtocol.ts","../src/UILatticeProtocol.ts","../src/QueueLatticeProtocol.ts","../src/ScheduleLatticeProtocol.ts","../src/LoggerLatticeProtocol.ts","../src/MessageProtocol.ts","../src/McpLatticeProtocol.ts","../src/WorkspaceStoreProtocol.ts","../src/BindingProtocol.ts","../src/TaskWorkItemProtocol.ts","../src/TaskBeliefProtocol.ts","../src/AgentWebAppRuntimeProtocol.ts","../src/ExactDataSnapshot.ts","../src/ProjectRoomRealtimeProtocol.ts","../src/TrustedRunContextProtocol.ts"],"sourcesContent":["/**\n * Protocols\n *\n * 导出所有Lattice协议接口,为整个系统提供统一的接口规范\n */\n\nexport * from \"./BaseLatticeProtocol\";\nexport * from \"./ToolLatticeProtocol\";\nexport * from \"./ModelLatticeProtocol\";\nexport * from \"./AgentLatticeProtocol\";\nexport * from \"./MemoryLatticeProtocol\";\nexport * from \"./UILatticeProtocol\";\nexport * from \"./QueueLatticeProtocol\";\nexport * from \"./ScheduleLatticeProtocol\";\nexport * from \"./EmbeddingsLatticeProtocol\";\nexport * from \"./STTModelLatticeProtocol\";\nexport * from \"./VectorStoreLatticeProtocol\";\nexport * from \"./LoggerLatticeProtocol\";\nexport * from \"./MessageProtocol\";\nexport * from \"./ThreadStoreProtocol\";\nexport * from \"./AssistantStoreProtocol\";\nexport * from \"./SkillLatticeProtocol\";\nexport * from \"./SkillStoreProtocol\";\nexport * from \"./McpLatticeProtocol\";\nexport * from \"./WorkspaceStoreProtocol\";\nexport * from \"./TenantStoreProtocol\";\nexport * from \"./DatabaseConfigStoreProtocol\";\nexport * from \"./ConnectionStoreProtocol\";\nexport * from \"./ChannelInstallationStoreProtocol\";\nexport * from \"./MetricsServerConfigStoreProtocol\";\nexport * from \"./McpServerConfigStoreProtocol\";\nexport * from \"./UserStoreProtocol\";\nexport * from \"./UserTenantLinkProtocol\";\nexport * from \"./WorkflowTrackingStoreProtocol\";\nexport * from \"./BindingProtocol\";\nexport * from \"./CollectionStoreProtocol\";\nexport * from \"./VectorStoreProviderProtocol\";\nexport * from \"./MenuProtocol\";\nexport * from \"./EvalStoreProtocol\";\nexport * from \"./TaskStoreProtocol\";\nexport * from \"./TaskWorkItemProtocol\";\nexport * from \"./TaskBeliefProtocol\";\n\nexport * from \"./LocalA2ATemplateConfig\";\nexport * from \"./ChannelAdapterProtocol\";\nexport * from \"./A2AProtocol\";\nexport * from \"./A2AApiKeyStoreProtocol\";\nexport * from \"./ConversationStoreProtocol\";\nexport * from \"./AgentWebAppStoreProtocol\";\nexport * from \"./AgentWebAppRuntimeProtocol\";\nexport * from \"./CapabilityBundleStoreProtocol\";\nexport * from \"./CapabilityRuntimeProtocol\";\nexport * from \"./ProjectRoomProtocol\";\nexport * from \"./ProjectRoomStoreProtocol\";\nexport * from \"./ProjectMembershipStoreProtocol\";\nexport * from \"./ProjectBotMembershipStoreProtocol\";\nexport * from \"./ProjectRoomMessageStoreProtocol\";\nexport * from \"./ExactDataSnapshot\";\nexport * from \"./ProjectRoomRealtimeProtocol\";\n\n// Workflow DSL (concise, public API)\nexport * from \"./WorkflowDSL\";\n\n// Internal DSL (expanded IR, internal use)\nexport * from \"./InternalDSL\";\n\nexport * from \"./SandboxResourceProtocol\";\n\n// Plugin system\nexport type {\n Plugin,\n PluginMeta,\n PluginMetaOutput,\n PluginConnection,\n PluginConnectionFieldSchema,\n PluginConnectionTestResult,\n PluginDiscoveredResource,\n PluginContext,\n PluginToolMeta,\n PluginSkillResource,\n PluginSkillDefinition,\n PluginStandardConnectionConfig,\n PluginMiddlewareFactory,\n} from \"./PluginProtocol\";\n\n// 导出通用类型\nexport * from \"./types\";\nexport * from \"./TrustedRunContextProtocol\";\n","/**\n * AgentLatticeProtocol\n *\n * 智能体Lattice的协议,定义了智能体的行为和组合方式\n */\n\nimport { CompiledStateGraph } from \"@langchain/langgraph\";\nimport { ZodObject } from \"zod\";\nimport { BaseLatticeProtocol } from \"./BaseLatticeProtocol\";\n\n/**\n * 智能体类型枚举\n */\nexport enum AgentType {\n REACT = \"react\",\n DEEP_AGENT = \"deep_agent\",\n TEAM = \"team\",\n PROCESSING = \"processing\",\n /** Remote A2A agent — delegates to an external A2A-compatible server */\n A2A_REMOTE = \"a2a_remote\",\n /** Workflow agent — compiled from YAML DSL into a LangGraph StateGraph */\n WORKFLOW = \"workflow\",\n}\n\n/**\n * Runtime configuration that will be injected into LangGraphRunnableConfig.configurable\n * Tools can access these values via config.configurable.runConfig\n */\nexport interface AgentRunConfig {\n /** Database key for SQL tools (registered via sqlDatabaseManager) */\n databaseKey?: string;\n /** Any additional runtime configuration */\n [key: string]: any;\n}\n\n/**\n * Base agent configuration shared by all agent types\n */\ninterface BaseAgentConfig {\n key: string; // Unique key\n name: string; // Name\n description: string; // Description\n prompt: string; // Prompt\n /**\n * Key of the parent agent to inherit configuration from.\n * When set, unspecified fields are inherited from the parent agent's config.\n * Child's explicitly set fields override the parent's.\n */\n extendsAgent?: string;\n schema?: ZodObject<any, any, any, any, any>; // Input validation schema\n modelKey?: string; // Model key to use\n /**\n * Runtime configuration to inject into tool execution context\n * Will be available in tools via config.configurable.runConfig\n */\n runConfig?: AgentRunConfig;\n skillCategories?: string[];\n middleware?: AgentMiddlewareConfig[];\n /**\n * Structured output response format for the agent.\n * Supports Zod schema (z.object({...})), JSON Schema object ({ type: \"object\", properties: {...} }),\n * providerStrategy(), toolStrategy(), and other formats accepted by the underlying model.\n *\n * @example\n * ```ts\n * // Zod schema\n * responseFormat: z.object({ name: z.string(), age: z.number() })\n *\n * // JSON Schema\n * responseFormat: { type: \"object\", properties: { name: { type: \"string\" } }, required: [\"name\"] }\n * ```\n */\n responseFormat?: any;\n /**\n * Arbitrary metadata as string-to-string map (optional).\n * Mirrors the skill metadata convention. Useful for:\n * - trust tier (e.g. verified: \"human-reviewed\" | \"machine-confirmed\")\n * - version tracking (e.g. version: \"1.2\")\n * - provenance (e.g. source material, learning run id)\n */\n metadata?: Record<string, string>;\n}\n\nexport type AvailableModule = \"filesystem\" | \"code_eval\" | \"browser\";\n\nexport interface SandboxMiddlewareConfig {\n vmIsolation: \"agent\" | \"project\" | \"global\";\n modules: AvailableModule[];\n}\n\nexport interface CodeEvalMiddlewareConfig {\n vmIsolation: \"agent\" | \"project\" | \"global\";\n timeout: number;\n memoryLimit: number;\n}\n\nexport interface BrowserMiddlewareConfig {\n vmIsolation: \"agent\" | \"project\" | \"global\";\n headless: boolean;\n}\n\nexport interface SqlMiddlewareConfig {\n databaseKeys?: string[];\n}\n\nexport interface MetricsMiddlewareConfig {\n /** List of configured metrics server keys */\n serverKeys: string[];\n /** Optional descriptions for each server */\n serverDescriptions?: Record<string, string>;\n}\n\nexport interface SchedulerMiddlewareConfig {\n defaultMaxRetries?: number;\n}\n\nexport interface CollectionMiddlewareConfig {\n /** List of configured collection keys */\n collectionKeys: string[];\n /**\n * When true, all collections for the tenant are available.\n * When false or undefined, only collections in collectionKeys are used.\n */\n connectAll?: boolean;\n}\n\nexport type MiddlewareType = \"filesystem\" | \"code_eval\" | \"browser\" | \"sql\" | \"skill\" | \"http\" | \"custom\" | \"metrics\" | \"ask_user_to_clarify\" | \"widget\" | \"claw\" | \"date\" | \"scheduler\" | \"topology\" | \"task\" | \"collection\" | string;\n\nexport interface AgentMiddlewareConfig {\n id: string;\n type: MiddlewareType;\n name: string;\n description: string;\n enabled: boolean;\n /** 可选:限制该中间件暴露的工具列表。不配置则默认暴露所有工具 */\n allowedTools?: string[];\n config: SandboxMiddlewareConfig | CodeEvalMiddlewareConfig | BrowserMiddlewareConfig | SqlMiddlewareConfig | MetricsMiddlewareConfig | ClawMiddlewareConfig | CollectionMiddlewareConfig | SchedulerMiddlewareConfig | Record<string, any>;\n}\n\n/**\n * Bootstrap file configuration\n * Defines default content for project bootstrap files\n */\nexport interface BootstrapFilesConfig {\n /** Default content for AGENTS.md - operating instructions */\n agents?: string;\n /** Default content for SOUL.md - personality and tone */\n soul?: string;\n /** Default content for IDENTITY.md - agent identity */\n identity?: string;\n /** Default content for USER.md - user preferences */\n user?: string;\n /** Default content for TOOLS.md - tool documentation */\n tools?: string;\n /** Default content for BOOTSTRAP.md - first-run tasks */\n bootstrap?: string;\n}\n\n/**\n * Claw Middleware 配置\n * 用于配置 bootstrap 文件管理行为\n */\nexport interface ClawMiddlewareConfig {\n /** 是否启用 bootstrap 文件注入(默认:true) */\n injectBootstrapFiles?: boolean;\n /** 自定义 bootstrap 文件内容 */\n bootstrapFiles?: BootstrapFilesConfig;\n}\n\n\n/**\n * REACT agent configuration\n */\nexport interface ReactAgentConfig extends BaseAgentConfig {\n type: AgentType.REACT;\n tools?: string[]; // Tool list\n}\n\n/**\n * DEEP_AGENT configuration - only this type supports subAgents\n */\nexport interface DeepAgentConfig extends BaseAgentConfig {\n type: AgentType.DEEP_AGENT;\n tools?: string[]; // Tool list\n subAgents?: string[]; // Sub-agent list (unique to DEEP_AGENT)\n internalSubAgents?: AgentConfig[]; // Internal sub-agent list (unique to DEEP_AGENT)\n}\n\n/**\n * PROCESSING agent configuration — workflow orchestration with topology enforcement.\n * Replaces todoListMiddleware with topologyMiddleware.\n */\nexport interface ProcessingAgentConfig extends BaseAgentConfig {\n type: AgentType.PROCESSING;\n tools?: string[];\n subAgents?: string[];\n internalSubAgents?: AgentConfig[];\n}\n\n/**\n * Team teammate configuration -- describes an available teammate.\n */\nexport interface TeamTeammateConfig {\n /** Unique name for this teammate (used as agent ID) */\n name: string;\n /** Role category (e.g. \"research\", \"writing\", \"review\") */\n role: string;\n /** Human-readable description of what this teammate does */\n description: string;\n /** Tool keys this teammate has access to */\n tools?: string[];\n /** Custom system prompt for this teammate */\n prompt?: string;\n /** Model key override for this teammate */\n modelKey?: string;\n}\n\n/**\n * TEAM agent configuration -- a team lead that dynamically creates teammates.\n * Teammates are created on-the-fly from create_team tool input (name, role, description).\n */\nexport interface TeamAgentConfig extends BaseAgentConfig {\n type: AgentType.TEAM;\n /** Tool keys available to the team lead */\n tools?: string[];\n /** Maximum number of teammates running concurrently */\n maxConcurrency?: number;\n /**\n * Schedule lattice key for polling task list / mailbox.\n * When set, teammates use ScheduleLattice for periodic polling instead of event-driven wait.\n */\n scheduleLatticeKey?: string;\n /** Poll interval in ms when using schedule lattice (default: 5000) */\n pollIntervalMs?: number;\n}\n\n/**\n * Type guard to check if config is TeamAgentConfig\n */\nexport function isTeamAgentConfig(\n config: AgentConfig\n): config is TeamAgentConfig {\n return config.type === AgentType.TEAM;\n}\n\n// ─── A2A_REMOTE Agent ──────────────────────────────────────────────────────\n\nexport interface LocalRuntimeConfig {\n label?: string;\n agentCardUrl: string;\n healthUrl?: string;\n command: {\n executable: string;\n args: string[];\n cwd?: string;\n env?: Record<string, string>;\n };\n}\n\n/**\n * A2A_REMOTE agent configuration — wraps a remote A2A-compatible agent endpoint.\n *\n * This agent type wraps a remote A2A endpoint so orchestrators can treat\n * external agents the same as local LangGraph agents.\n */\nexport interface A2ARemoteAgentConfig extends BaseAgentConfig {\n type: AgentType.A2A_REMOTE;\n /**\n * URL of the remote agent's agent card (e.g. http://host:3000/.well-known/agent-card.json).\n * The builder fetches this card to discover the JSON-RPC endpoint.\n */\n agentCardUrl: string;\n /**\n * Optional API key sent as a Bearer token.\n */\n apiKey?: string;\n /**\n * HTTP timeout in milliseconds (default: 300_000 = 5 min).\n */\n timeout?: number;\n projectId?: string;\n /**\n * Optional tool keys (not used by the builder, but included for type compatibility).\n */\n tools?: string[];\n /**\n * Optional local runtime snapshot for Local Managed A2A assistants.\n * When present, the gateway manages a local process for this assistant.\n * Copied from a template or custom form at creation time.\n */\n localRuntime?: LocalRuntimeConfig;\n}\n\nexport type LocalA2AProviderId = string;\n\nexport type LocalA2AProviderStatus =\n | \"missing\"\n | \"disabled\"\n | \"starting\"\n | \"running\"\n | \"stopped\"\n | \"failed\";\n\nexport interface LocalA2AProviderState {\n runtimeId: string;\n label: string;\n status: LocalA2AProviderStatus;\n enabled: boolean;\n assistantId?: string;\n agentCardUrl?: string;\n healthUrl?: string;\n pid?: number;\n message?: string;\n lastStartedAt?: string;\n lastStoppedAt?: string;\n}\n\n/**\n * WORKFLOW agent configuration — compiled from YAML workflow DSL into a LangGraph StateGraph.\n *\n * The workflow field contains the full DSL definition (nodes, edges, state).\n * The WorkflowAgentGraphBuilder compiles this into a multi-node LangGraph\n * where each node invokes a registered sub-agent by ref.\n */\nexport interface WorkflowAgentConfig extends BaseAgentConfig {\n type: AgentType.WORKFLOW;\n /** The YAML workflow DSL definition string (needs+if format) */\n workflowYaml: string;\n /** Optional tool keys */\n tools?: string[];\n}\n\n/**\n * Type guard to check if config is A2ARemoteAgentConfig\n */\nexport function isA2ARemoteAgentConfig(\n config: AgentConfig\n): config is A2ARemoteAgentConfig {\n return config.type === AgentType.A2A_REMOTE;\n}\n\n/**\n * Type guard to check if config is WorkflowAgentConfig\n */\nexport function isWorkflowAgentConfig(\n config: AgentConfig\n): config is WorkflowAgentConfig {\n return config.type === AgentType.WORKFLOW;\n}\n\n/**\n * Agent configuration union type\n * Different agent types have different configuration options\n */\nexport type AgentConfig =\n | ReactAgentConfig\n | DeepAgentConfig\n | TeamAgentConfig\n | ProcessingAgentConfig\n | A2ARemoteAgentConfig\n | WorkflowAgentConfig\n\n/**\n * Agent configuration with tools property\n */\nexport type AgentConfigWithTools =\n | ReactAgentConfig\n | DeepAgentConfig\n | TeamAgentConfig\n | ProcessingAgentConfig\n | A2ARemoteAgentConfig\n | WorkflowAgentConfig\n\n/**\n * Type guard to check if config has tools property\n */\nexport function hasTools(config: AgentConfig): config is AgentConfigWithTools {\n return true;\n}\n\n/**\n * Type guard to check if config is DeepAgentConfig (has subAgents)\n */\nexport function isDeepAgentConfig(\n config: AgentConfig\n): config is DeepAgentConfig {\n return config.type === AgentType.DEEP_AGENT;\n}\n\n/**\n * Type guard to check if config is ProcessingAgentConfig (has subAgents + topology)\n */\nexport function isProcessingAgentConfig(\n config: AgentConfig\n): config is ProcessingAgentConfig {\n return config.type === AgentType.PROCESSING;\n}\n\n/**\n * Get tools from config safely\n */\nexport function getToolsFromConfig(config: AgentConfig): string[] {\n if (hasTools(config)) {\n return config.tools || [];\n }\n return [];\n}\n\n/**\n * Get subAgents from config safely (DeepAgentConfig and ProcessingAgentConfig have subAgents)\n */\nexport function getSubAgentsFromConfig(config: AgentConfig): string[] {\n if (isDeepAgentConfig(config) || isProcessingAgentConfig(config)) {\n return config.subAgents || [];\n }\n return [];\n}\n\n/**\n * 智能体客户端类型\n */\nexport type AgentClient = CompiledStateGraph<any, any, any, any, any>;\n\n/**\n * Graph构建选项\n */\nexport interface GraphBuildOptions {\n overrideTools?: string[];\n overrideModel?: string;\n metadata?: Record<string, any>;\n}\n\n/**\n * 智能体Lattice协议接口\n */\nexport interface AgentLatticeProtocol\n extends BaseLatticeProtocol<AgentConfig, AgentClient> {\n // 智能体执行函数\n invoke: (input: any, options?: any) => Promise<any>;\n\n // 构建智能体图\n buildGraph: (options?: GraphBuildOptions) => Promise<AgentClient>;\n}\n","/**\n * MemoryLatticeProtocol\n *\n * 记忆Lattice的协议,用于管理智能体的上下文和记忆\n */\n\nimport { BaseLatticeProtocol } from \"./BaseLatticeProtocol\";\n\n/**\n * 记忆类型枚举\n */\nexport enum MemoryType {\n SHORT_TERM = \"short_term\",\n LONG_TERM = \"long_term\",\n EPISODIC = \"episodic\",\n SEMANTIC = \"semantic\",\n WORKING = \"working\",\n}\n\n/**\n * 记忆配置接口\n */\nexport interface MemoryConfig {\n name: string; // 名称\n description: string; // 描述\n type: MemoryType; // 记忆类型\n ttl?: number; // 生存时间\n capacity?: number; // 容量限制\n}\n\n/**\n * 记忆客户端接口\n */\nexport interface MemoryClient {\n add: (key: string, value: any) => Promise<void>;\n get: (key: string) => Promise<any>;\n update: (key: string, value: any) => Promise<void>;\n delete: (key: string) => Promise<void>;\n search: (query: string, options?: any) => Promise<any[]>;\n clear: () => Promise<void>;\n}\n\n/**\n * 记忆Lattice协议接口\n */\nexport interface MemoryLatticeProtocol\n extends BaseLatticeProtocol<MemoryConfig, MemoryClient> {\n // 记忆操作方法\n add: (key: string, value: any) => Promise<void>;\n get: (key: string) => Promise<any>;\n update: (key: string, value: any) => Promise<void>;\n delete: (key: string) => Promise<void>;\n search: (query: string, options?: any) => Promise<any[]>;\n clear: () => Promise<void>;\n}\n","/**\n * UILatticeProtocol\n *\n * UI Lattice的协议,用于定义用户界面组件\n */\n\nimport { BaseLatticeProtocol } from \"./BaseLatticeProtocol\";\n\n/**\n * UI组件类型枚举\n */\nexport enum UIComponentType {\n CONTAINER = \"container\",\n INPUT = \"input\",\n BUTTON = \"button\",\n LIST = \"list\",\n TABLE = \"table\",\n CHART = \"chart\",\n FORM = \"form\",\n CARD = \"card\",\n MODAL = \"modal\",\n CUSTOM = \"custom\",\n}\n\n/**\n * UI配置接口\n */\nexport interface UIConfig {\n name: string; // 组件名称\n description: string; // 组件描述\n type: UIComponentType; // 组件类型\n props?: Record<string, any>; // 组件属性\n children?: string[]; // 子组件列表\n}\n\n/**\n * UI组件接口\n * 使用泛型以适应不同的UI框架(React, Vue等)\n */\nexport interface UIComponent<T = any> {\n render: (props?: any) => T;\n addEventListener: (event: string, handler: (...args: unknown[]) => void) => void;\n removeEventListener: (event: string, handler: (...args: unknown[]) => void) => void;\n}\n\n/**\n * UI Lattice协议接口\n */\nexport interface UILatticeProtocol<T = any>\n extends BaseLatticeProtocol<UIConfig, UIComponent<T>> {\n // UI渲染方法\n render: (props?: any) => T;\n\n // 事件处理\n addEventListener: (event: string, handler: (...args: unknown[]) => void) => void;\n removeEventListener: (event: string, handler: (...args: unknown[]) => void) => void;\n}\n","/**\n * QueueLatticeProtocol\n *\n * Queue Lattice protocol for task queue management\n */\n\nimport { BaseLatticeProtocol } from \"./BaseLatticeProtocol\";\n\n/**\n * Queue service type enumeration\n */\nexport enum QueueType {\n MEMORY = \"memory\",\n REDIS = \"redis\",\n}\n\n/**\n * Queue configuration interface\n */\nexport interface QueueConfig {\n name: string; // Queue name\n description: string; // Queue description\n type: QueueType; // Queue service type\n queueName?: string; // Specific queue name (e.g., \"tasks\")\n options?: Record<string, any>; // Additional options (e.g., Redis connection options)\n}\n\n/**\n * Queue operation result interface\n */\nexport interface QueueResult<T = any> {\n data: T | null;\n error: any | null;\n}\n\n/**\n * Queue client interface\n */\nexport interface QueueClient {\n push: (item: any) => Promise<QueueResult<number>>;\n pop: () => Promise<QueueResult<any>>;\n createQueue?: () => Promise<{ success: boolean; queue_name?: string; error?: any }>;\n}\n\n/**\n * Queue Lattice protocol interface\n */\nexport interface QueueLatticeProtocol\n extends BaseLatticeProtocol<QueueConfig, QueueClient> {\n // Queue operations\n push: (item: any) => Promise<QueueResult<number>>;\n pop: () => Promise<QueueResult<any>>;\n createQueue?: () => Promise<{ success: boolean; queue_name?: string; error?: any }>;\n}\n\n\n\n","/**\n * ScheduleLatticeProtocol\n *\n * Schedule Lattice protocol for delayed and recurring task execution management\n * Supports persistence and recovery after service restart\n * Supports both one-time delayed tasks and cron-style recurring tasks\n */\n\nimport { BaseLatticeProtocol } from \"./BaseLatticeProtocol\";\n\n/**\n * Schedule service type enumeration\n */\nexport enum ScheduleType {\n MEMORY = \"memory\",\n POSTGRES = \"postgres\",\n REDIS = \"redis\",\n}\n\n/**\n * Schedule execution type - one-time or recurring\n */\nexport enum ScheduleExecutionType {\n ONCE = \"once\", // Execute once at specified time\n CRON = \"cron\", // Recurring based on cron expression\n}\n\n/**\n * Task status enumeration\n */\nexport enum ScheduledTaskStatus {\n PENDING = \"pending\", // Waiting to be executed\n RUNNING = \"running\", // Currently executing\n COMPLETED = \"completed\", // Successfully completed (for ONCE type)\n FAILED = \"failed\", // Execution failed\n CANCELLED = \"cancelled\", // Manually cancelled\n PAUSED = \"paused\", // Paused (for CRON type)\n}\n\n/**\n * Schedule configuration interface\n */\nexport interface ScheduleConfig {\n name: string;\n description: string;\n type: ScheduleType;\n storage?: ScheduleStorage; // Optional storage for persistence\n options?: Record<string, any>;\n}\n\n/**\n * Scheduled task definition - fully serializable\n * Supports both one-time and cron-style recurring tasks\n */\nexport interface ScheduledTaskDefinition {\n taskId: string;\n taskType: string; // Maps to a registered handler\n payload: Record<string, any>; // JSON-serializable data passed to handler\n\n // Context fields for querying\n tenantId: string; // Tenant isolation\n assistantId?: string; // Which assistant created/owns this task\n threadId?: string; // Which thread this task belongs to\n\n // Execution configuration\n executionType: ScheduleExecutionType;\n\n // For ONCE type - execute at specific time or after delay\n executeAt?: number; // Timestamp when to execute\n delayMs?: number; // Original delay in milliseconds (for reference)\n\n // For CRON type - recurring schedule\n cronExpression?: string; // Cron format: \"0 9 * * *\" (min hour day month weekday)\n timezone?: string; // Timezone: \"Asia/Shanghai\", defaults to system timezone\n nextRunAt?: number; // Next calculated execution time\n lastRunAt?: number; // Last execution time\n\n // Execution tracking\n status: ScheduledTaskStatus;\n runCount: number; // How many times executed\n maxRuns?: number; // Max executions (null/undefined = infinite for cron, 1 for once)\n\n // Error handling\n retryCount: number; // Current retry count\n maxRetries: number; // Maximum retry attempts\n lastError?: string; // Last error message if failed\n\n // Timestamps\n createdAt: number;\n updatedAt: number;\n expiresAt?: number; // When to stop (for cron, optional)\n\n metadata?: Record<string, any>; // Additional metadata\n}\n\n/**\n * Task handler function type\n */\nexport type TaskHandler = (\n payload: Record<string, any>,\n taskInfo: ScheduledTaskDefinition\n) => void | Promise<void>;\n\n/**\n * Options for scheduling a one-time task\n */\nexport interface ScheduleOnceOptions {\n executeAt?: number; // Absolute timestamp to execute\n delayMs?: number; // OR relative delay from now\n maxRetries?: number; // Max retry attempts (default: 0)\n tenantId?: string; // Tenant isolation\n assistantId?: string; // Which assistant created/owns this task\n threadId?: string; // Which thread this task belongs to\n metadata?: Record<string, any>;\n}\n\n/**\n * Options for scheduling a cron task\n */\nexport interface ScheduleCronOptions {\n cronExpression: string; // Cron expression: \"0 9 * * *\"\n timezone?: string; // Timezone: \"Asia/Shanghai\"\n maxRuns?: number; // Max executions (undefined = infinite)\n expiresAt?: number; // Stop after this timestamp\n maxRetries?: number; // Max retry attempts per run (default: 0)\n tenantId?: string; // Tenant isolation\n assistantId?: string; // Which assistant created/owns this task\n threadId?: string; // Which thread this task belongs to\n metadata?: Record<string, any>;\n}\n\n/**\n * Schedule storage interface for persistence\n */\nexport interface ScheduleStorage {\n /**\n * Save a new task\n */\n save(task: ScheduledTaskDefinition): Promise<void>;\n\n /**\n * Get task by ID\n */\n get(taskId: string): Promise<ScheduledTaskDefinition | null>;\n\n /**\n * Update task\n */\n update(\n taskId: string,\n updates: Partial<ScheduledTaskDefinition>\n ): Promise<void>;\n\n /**\n * Delete task\n */\n delete(taskId: string): Promise<void>;\n\n /**\n * Get all pending/active tasks (for recovery)\n * Returns tasks with status: PENDING or PAUSED\n */\n getActiveTasks(): Promise<ScheduledTaskDefinition[]>;\n\n /**\n * Get tasks by type\n */\n getTasksByType(taskType: string): Promise<ScheduledTaskDefinition[]>;\n\n /**\n * Get tasks by status\n */\n getTasksByStatus(\n status: ScheduledTaskStatus\n ): Promise<ScheduledTaskDefinition[]>;\n\n /**\n * Get tasks by execution type\n */\n getTasksByExecutionType(\n executionType: ScheduleExecutionType\n ): Promise<ScheduledTaskDefinition[]>;\n\n /**\n * Get tasks by assistant ID\n */\n getTasksByAssistantId(\n assistantId: string\n ): Promise<ScheduledTaskDefinition[]>;\n\n /**\n * Get tasks by thread ID\n */\n getTasksByThreadId(threadId: string): Promise<ScheduledTaskDefinition[]>;\n\n /**\n * Get all tasks (with optional filters)\n */\n getAllTasks(filters?: {\n tenantId?: string;\n status?: ScheduledTaskStatus;\n executionType?: ScheduleExecutionType;\n taskType?: string;\n assistantId?: string;\n threadId?: string;\n limit?: number;\n offset?: number;\n }): Promise<ScheduledTaskDefinition[]>;\n\n /**\n * Count tasks (with optional filters)\n */\n countTasks(filters?: {\n tenantId?: string;\n status?: ScheduledTaskStatus;\n executionType?: ScheduleExecutionType;\n taskType?: string;\n assistantId?: string;\n threadId?: string;\n }): Promise<number>;\n\n /**\n * Delete completed/cancelled tasks older than specified time\n * Useful for cleanup\n */\n deleteOldTasks(olderThanMs: number): Promise<number>;\n}\n\n/**\n * Schedule client interface\n */\nexport interface ScheduleClient {\n // ===== Handler Registration =====\n\n /**\n * Register a handler for a task type\n * Must be called before scheduling tasks of this type\n */\n registerHandler(taskType: string, handler: TaskHandler): void;\n\n /**\n * Unregister a handler\n */\n unregisterHandler(taskType: string): boolean;\n\n /**\n * Check if a handler is registered\n */\n hasHandler(taskType: string): boolean;\n\n /**\n * Get all registered handler types\n */\n getHandlerTypes(): string[];\n\n // ===== One-time Task Scheduling =====\n\n /**\n * Schedule a one-time task\n * @param taskId - Unique identifier for the task\n * @param taskType - Type of task (must have a registered handler)\n * @param payload - Data to pass to the handler (must be JSON-serializable)\n * @param options - Execution options (executeAt or delayMs required)\n */\n scheduleOnce(\n taskId: string,\n taskType: string,\n payload: Record<string, any>,\n options: ScheduleOnceOptions\n ): Promise<boolean>;\n\n // ===== Cron Task Scheduling =====\n\n /**\n * Schedule a recurring cron task\n * @param taskId - Unique identifier for the task\n * @param taskType - Type of task (must have a registered handler)\n * @param payload - Data to pass to the handler (must be JSON-serializable)\n * @param options - Cron options (cronExpression required)\n */\n scheduleCron(\n taskId: string,\n taskType: string,\n payload: Record<string, any>,\n options: ScheduleCronOptions\n ): Promise<boolean>;\n\n // ===== Task Management =====\n\n /**\n * Cancel a scheduled task\n */\n cancel(taskId: string): Promise<boolean>;\n\n /**\n * Pause a cron task (only for CRON type)\n */\n pause(taskId: string): Promise<boolean>;\n\n /**\n * Resume a paused cron task (only for CRON type)\n */\n resume(taskId: string): Promise<boolean>;\n\n /**\n * Check if a task exists\n */\n has(taskId: string): Promise<boolean>;\n\n /**\n * Get task information\n */\n getTask(taskId: string): Promise<ScheduledTaskDefinition | null>;\n\n /**\n * Get remaining time until next execution\n * Returns -1 if task not found or already executed\n */\n getRemainingTime(taskId: string): Promise<number>;\n\n /**\n * Get count of active tasks (pending + paused)\n */\n getActiveTaskCount(): Promise<number>;\n\n /**\n * Get all active task IDs\n */\n getActiveTaskIds(): Promise<string[]>;\n\n /**\n * Cancel all active tasks\n */\n cancelAll(): Promise<void>;\n\n // ===== Recovery =====\n\n /**\n * Restore active tasks from storage (call on service startup)\n * Re-schedules all pending tasks with their remaining time\n * Re-schedules all cron tasks for their next run\n * @returns Number of tasks restored\n */\n restore(): Promise<number>;\n\n // ===== Storage =====\n\n /**\n * Set the storage backend\n */\n setStorage(storage: ScheduleStorage): void;\n\n /**\n * Get current storage backend\n */\n getStorage(): ScheduleStorage | null;\n}\n\n/**\n * Schedule Lattice protocol interface\n */\nexport interface ScheduleLatticeProtocol\n extends BaseLatticeProtocol<ScheduleConfig, ScheduleClient> {\n // Handler registration\n registerHandler: (taskType: string, handler: TaskHandler) => void;\n unregisterHandler: (taskType: string) => boolean;\n hasHandler: (taskType: string) => boolean;\n getHandlerTypes: () => string[];\n\n // One-time task scheduling\n scheduleOnce: (\n taskId: string,\n taskType: string,\n payload: Record<string, any>,\n options: ScheduleOnceOptions\n ) => Promise<boolean>;\n\n // Cron task scheduling\n scheduleCron: (\n taskId: string,\n taskType: string,\n payload: Record<string, any>,\n options: ScheduleCronOptions\n ) => Promise<boolean>;\n\n // Task management\n cancel: (taskId: string) => Promise<boolean>;\n pause: (taskId: string) => Promise<boolean>;\n resume: (taskId: string) => Promise<boolean>;\n has: (taskId: string) => Promise<boolean>;\n getTask: (taskId: string) => Promise<ScheduledTaskDefinition | null>;\n getRemainingTime: (taskId: string) => Promise<number>;\n getActiveTaskCount: () => Promise<number>;\n getActiveTaskIds: () => Promise<string[]>;\n cancelAll: () => Promise<void>;\n\n // Recovery\n restore: () => Promise<number>;\n}\n","/**\n * LoggerLatticeProtocol\n *\n * Logger Lattice protocol for logging management\n */\n\nimport { BaseLatticeProtocol } from \"./BaseLatticeProtocol\";\n\n/**\n * Logger service type enumeration\n */\nexport enum LoggerType {\n PINO = \"pino\",\n CONSOLE = \"console\",\n CUSTOM = \"custom\",\n}\n\n/**\n * Logger context interface\n */\nexport interface LoggerContext {\n \"x-user-id\"?: string;\n \"x-tenant-id\"?: string;\n \"x-request-id\"?: string;\n \"x-task-id\"?: string;\n \"x-thread-id\"?: string;\n [key: string]: any;\n}\n\n/**\n * Pino logger file transport options\n */\nexport interface PinoFileOptions {\n file?: string; // Log file path (e.g., \"./logs/app.log\" or \"./logs/app\")\n frequency?: \"daily\" | \"hourly\" | \"minutely\" | string; // Log rotation frequency\n mkdir?: boolean; // Create directory if not exists\n size?: string; // Max file size (e.g., \"10M\", \"100K\")\n maxFiles?: number; // Maximum number of log files to keep\n}\n\n/**\n * Logger configuration interface\n */\nexport interface LoggerConfig {\n name: string; // Logger name\n description?: string; // Logger description\n type: LoggerType; // Logger service type\n serviceName?: string; // Service name (e.g., \"lattice-gateway\")\n loggerName?: string; // Logger instance name (e.g., \"fastify-server\")\n context?: LoggerContext; // Initial context\n // File logging options (for PINO type)\n file?: string | PinoFileOptions; // Log file path or detailed file options\n // Additional options (e.g., pino config, custom logger settings)\n options?: Record<string, any>;\n}\n\n/**\n * Logger client interface\n */\nexport interface LoggerClient {\n info: (msg: string, obj?: object) => void;\n error: (msg: string, obj?: object | Error) => void;\n warn: (msg: string, obj?: object) => void;\n debug: (msg: string, obj?: object) => void;\n updateContext?: (context: Partial<LoggerContext>) => void;\n child?: (options: Partial<LoggerConfig>) => LoggerClient;\n}\n\n/**\n * Logger Lattice protocol interface\n */\nexport interface LoggerLatticeProtocol\n extends BaseLatticeProtocol<LoggerConfig, LoggerClient> {\n // Logger operations\n info: (msg: string, obj?: object) => void;\n error: (msg: string, obj?: object | Error) => void;\n warn: (msg: string, obj?: object) => void;\n debug: (msg: string, obj?: object) => void;\n updateContext?: (context: Partial<LoggerContext>) => void;\n child?: (options: Partial<LoggerConfig>) => LoggerClient;\n}\n","/**\n * MessageProtocol\n *\n */\n\n\n\n/**\n * Base message interface\n */\nexport interface BaseMessage {\n id: string; // Unique identifier for the message\n role: string; // Role of the sender (user, assistant, system, tool, developer)\n content?: string; // Optional text content of the message\n name?: string; // Optional name of the sender\n}\n\n/**\n * User message interface\n */\nexport interface UserMessage extends BaseMessage {\n role: \"human\";\n content: string; // Text input from the user\n files?: Array<{ name: string; id: string }>; // Optional files attached to the message\n}\n\n/**\n * Tool call interface\n */\nexport interface ToolCall {\n id: string; // Unique identifier for this tool call\n name: string; // Name of the tool/function to call\n args: Record<string, any>; // Arguments as an object\n type: \"tool_call\"; // Type of tool call\n response?: string; // Optional response from the tool execution\n}\n\n/**\n * Assistant message interface\n */\nexport interface AssistantMessage extends BaseMessage {\n role: \"ai\";\n content?: string; // Text response from the assistant (optional if using tool calls)\n tool_calls?: ToolCall[]; // Optional tool calls made by the assistant\n}\n\nexport interface InterruptMessage extends BaseMessage {\n type: \"interrupt\";\n value: any;\n}\n\n/**\n * System message interface\n */\nexport interface SystemMessage extends BaseMessage {\n role: \"system\";\n content: string; // Instructions or context for the assistant\n}\n\n/**\n * Tool message interface\n */\nexport interface ToolMessage extends BaseMessage {\n role: \"tool\";\n content: string; // Result from the tool execution\n tool_call_id: string; // ID of the tool call this message responds to\n}\n\n/**\n * Developer message interface\n */\nexport interface DeveloperMessage extends BaseMessage {\n role: \"developer\";\n content: string; // Content for development or debugging\n}\n\n/**\n * Message chunk type constants\n */\nexport const MessageChunkTypes = {\n HUMAN: 'human',\n AI: 'ai',\n TOOL: 'tool',\n INTERRUPT: 'interrupt',\n MESSAGE_COMPLETED: 'message_completed',\n MESSAGE_FAILED: 'message_failed',\n THREAD_IDLE: 'thread_idle',\n} as const;\n\nexport type MessageChunkType = typeof MessageChunkTypes[keyof typeof MessageChunkTypes];\n\nexport interface MessageChunk {\n type: MessageChunkType;\n data: {\n id: string;\n content?: string;\n tool_call_chunks?: Array<{\n name?: string;\n args?: string;\n id?: string;\n index: number;\n }>;\n tool_calls?: Array<{\n name: string;\n args: Record<string, any>;\n id: string;\n type: string;\n response?: string;\n }>;\n additional_kwargs?: {\n tool_calls?: Array<{\n function?: { name?: string; arguments?: any };\n id?: string;\n }>;\n };\n tool_call_id?: string;\n };\n}\n\n/**\n * Message type union\n */\nexport type Message =\n | UserMessage\n | AssistantMessage\n | SystemMessage\n | ToolMessage\n | DeveloperMessage;\n","/**\n * McpLatticeProtocol\n *\n * Model Context Protocol (MCP) lattice protocol for integrating MCP servers\n * with the Lattice framework. Provides standardized interfaces for MCP\n * client connections, tool discovery, and remote execution.\n */\n\nimport { BaseLatticeProtocol, LatticeMessage } from \"./BaseLatticeProtocol\";\n\n/**\n * MCP transport type\n */\nexport type McpTransportType = \"stdio\" | \"streamable_http\" | \"sse\";\n\n/**\n * MCP server configuration\n */\nexport interface McpServerConfig {\n /** Server name */\n name: string;\n /** Server version */\n version: string;\n /** Transport type */\n transport: McpTransportType;\n /** Command for stdio transport (e.g., \"npx\", \"python\") */\n command?: string;\n /** Arguments for stdio transport */\n args?: string[];\n /** URL for HTTP/SSE transport */\n url?: string;\n /** Environment variables */\n env?: Record<string, string>;\n /** Connection timeout in milliseconds */\n timeout?: number;\n /** Retry attempts on connection failure */\n retryAttempts?: number;\n}\n\n/**\n * MCP tool definition\n */\nexport interface McpTool {\n /** Tool name */\n name: string;\n /** Tool description */\n description: string;\n /** Input schema */\n inputSchema: {\n type: \"object\";\n properties: Record<string, any>;\n required?: string[];\n };\n /** Tool metadata */\n metadata?: Record<string, any>;\n}\n\n/**\n * MCP tool call result\n */\nexport interface McpToolResult {\n /** Whether the call was successful */\n success: boolean;\n /** Result content */\n content: Array<{\n type: \"text\" | \"image\" | \"audio\" | \"resource\";\n data: any;\n mimeType?: string;\n }>;\n /** Error message if failed */\n error?: string;\n /** Execution metadata */\n metadata?: {\n duration: number;\n tokens?: number;\n model?: string;\n };\n}\n\n/**\n * MCP client interface\n */\nexport interface McpClient {\n /** Client name */\n name: string;\n /** Client version */\n version: string;\n /** Server configuration */\n serverConfig: McpServerConfig;\n \n /**\n * Connect to MCP server\n */\n connect(): Promise<void>;\n \n /**\n * Disconnect from MCP server\n */\n disconnect(): Promise<void>;\n \n /**\n * Check if connected\n */\n isConnected(): boolean;\n \n /**\n * List available tools\n */\n listTools(): Promise<McpTool[]>;\n \n /**\n * Call a tool\n */\n callTool(name: string, arguments_: Record<string, any>): Promise<McpToolResult>;\n \n /**\n * Subscribe to server notifications\n */\n subscribe(topic: string, handler: (data: any) => void): void;\n \n /**\n * Unsubscribe from server notifications\n */\n unsubscribe(topic: string): void;\n \n /**\n * Get client statistics\n */\n getStats(): McpStats;\n \n /**\n * Get connection status\n */\n getStatus(): McpConnectionStatus;\n}\n\n/**\n * MCP client options\n */\nexport interface McpClientOptions {\n /** Client name */\n name: string;\n /** Client version */\n version: string;\n /** Server configuration */\n serverConfig: McpServerConfig;\n /** Auto-connect on initialization */\n autoConnect?: boolean;\n /** Error handler */\n onError?: (error: Error) => void;\n /** Connection status handler */\n onStatusChange?: (status: McpConnectionStatus) => void;\n}\n\n/**\n * MCP Lattice protocol interface\n */\nexport interface McpLatticeProtocol\n extends BaseLatticeProtocol<McpServerConfig, McpClient> {\n /**\n * Server configuration\n */\n config: McpServerConfig;\n \n /**\n * MCP client instance\n */\n client: McpClient;\n \n /**\n * Connect to MCP server\n */\n connect(): Promise<void>;\n \n /**\n * Disconnect from MCP server\n */\n disconnect(): Promise<void>;\n \n /**\n * Get available tools\n */\n getTools(): Promise<McpTool[]>;\n \n /**\n * Execute a tool\n */\n executeTool(\n name: string,\n arguments_: Record<string, any>\n ): Promise<McpToolResult>;\n \n /**\n * Execute with automatic retries\n */\n executeToolWithRetry(\n name: string,\n arguments_: Record<string, any>,\n maxRetries?: number\n ): Promise<McpToolResult>;\n \n /**\n * Get protocol version\n */\n getProtocolVersion(): string;\n \n /**\n * Health check\n */\n healthCheck(): Promise<boolean>;\n}\n\n/**\n * MCP message types\n */\nexport enum McpMessageType {\n CONNECT = \"mcp:connect\",\n DISCONNECT = \"mcp:disconnect\",\n LIST_TOOLS = \"mcp:list_tools\",\n CALL_TOOL = \"mcp:call_tool\",\n TOOL_RESULT = \"mcp:tool_result\",\n NOTIFICATION = \"mcp:notification\",\n ERROR = \"mcp:error\",\n HEALTH_CHECK = \"mcp:health_check\",\n}\n\n/**\n * MCP Lattice message\n */\nexport interface McpLatticeMessage extends LatticeMessage {\n type: McpMessageType;\n payload: {\n toolName?: string;\n arguments?: Record<string, any>;\n result?: McpToolResult;\n tools?: McpTool[];\n error?: string;\n };\n}\n\n/**\n * MCP connection status\n */\nexport type McpConnectionStatus =\n | \"disconnected\"\n | \"connecting\"\n | \"connected\"\n | \"reconnecting\"\n | \"error\";\n\n/**\n * MCP statistics\n */\nexport interface McpStats {\n totalCalls: number;\n successfulCalls: number;\n failedCalls: number;\n averageLatency: number;\n lastCallTimestamp: number;\n}\n","/**\n * WorkspaceStoreProtocol\n *\n * Workspace and Project store protocol definitions\n * for the Axiom Lattice framework\n */\n\nexport type StorageType = \"sandbox\" | \"filesystem\";\n\n/**\n * Workspace type definition\n */\nexport interface Workspace {\n id: string;\n tenantId: string;\n name: string;\n description?: string;\n storageType: StorageType;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/**\n * Create workspace request type\n */\nexport interface CreateWorkspaceRequest {\n name: string;\n description?: string;\n storageType: StorageType;\n}\n\n/**\n * Update workspace request type\n */\nexport interface UpdateWorkspaceRequest {\n name?: string;\n description?: string;\n storageType?: StorageType;\n}\n\n/**\n * WorkspaceStore interface\n * Provides CRUD operations for workspace data\n */\nexport interface WorkspaceStore {\n getAllWorkspaces(tenantId: string): Promise<Workspace[]>;\n getWorkspaceById(tenantId: string, id: string): Promise<Workspace | null>;\n createWorkspace(tenantId: string, id: string, data: CreateWorkspaceRequest): Promise<Workspace>;\n updateWorkspace(tenantId: string, id: string, updates: UpdateWorkspaceRequest): Promise<Workspace | null>;\n deleteWorkspace(tenantId: string, id: string): Promise<boolean>;\n}\n\n/**\n * Project kind classification\n *\n * Defaults to \"business\" for legacy rows and omitted input.\n * \"public\" is reserved for the automatically ensured workspace public room;\n * user-facing project create/update APIs reject it.\n */\nexport type ProjectKind = \"business\" | \"training\" | \"personal\" | \"public\";\n\n/**\n * Project type definition\n */\nexport interface Project {\n id: string;\n tenantId: string;\n workspaceId: string;\n name: string;\n description?: string;\n /** Application-specific configuration stored as JSON */\n config?: Record<string, unknown>;\n /** Project classification; defaults to \"business\" when omitted */\n kind?: ProjectKind;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/**\n * Create project request type\n */\nexport interface CreateProjectRequest {\n name: string;\n description?: string;\n /** Application-specific configuration stored as JSON (optional) */\n config?: Record<string, unknown>;\n /** Project classification; defaults to \"business\" when omitted */\n kind?: ProjectKind;\n}\n\n/**\n * Update project request type\n *\n * @remarks\n * - The `config` field uses **replace** semantics: if provided, it completely\n * overwrites the existing config. To preserve the current config, omit this field.\n */\nexport interface UpdateProjectRequest {\n name?: string;\n description?: string;\n /** Application-specific configuration stored as JSON (replaces existing if provided) */\n config?: Record<string, unknown>;\n /** Project classification */\n kind?: ProjectKind;\n}\n\n/** Error raised when generic project writes attempt to change capability Bundle references. */\nexport class InvalidProjectCapabilityBundleConfigError extends Error {\n /** Stable machine-readable error code. */\n readonly code = \"INVALID_BUNDLE_CONFIG\" as const;\n\n /** Creates the reserved-config error returned by generic Project writes. */\n constructor() {\n super(\"Use the project capability-bundles endpoint to update capability bundle IDs\");\n this.name = \"InvalidProjectCapabilityBundleConfigError\";\n }\n}\n\n/** Rejects capability Bundle references supplied through generic Project config writes. */\nexport function assertGenericProjectConfig(config: Record<string, unknown> | undefined): void {\n if (config !== undefined && Object.prototype.hasOwnProperty.call(config, \"capabilityBundleIds\")) {\n throw new InvalidProjectCapabilityBundleConfigError();\n }\n}\n\n/**\n * Filter options for listing projects within a workspace\n */\nexport interface ProjectFilter {\n kind?: ProjectKind;\n}\n\n/** Atomic result of replacing a Project's capability Bundle IDs. */\nexport type UpdateProjectCapabilityBundlesResult =\n | { status: \"updated\"; project: Project }\n | { status: \"project_not_found\" }\n | { status: \"bundle_not_found\" }\n | { status: \"bundle_conflict\" };\n\n/** Revision preconditions for the bundles reviewed before project assignment. */\nexport type ExpectedCapabilityBundleRevisions = Record<string, string>;\n\n/**\n * ProjectStore interface\n * Provides CRUD operations for project data\n */\nexport interface ProjectStore {\n getProjectsByWorkspace(tenantId: string, workspaceId: string, filter?: ProjectFilter): Promise<Project[]>;\n getProjectById(tenantId: string, id: string): Promise<Project | null>;\n createProject(tenantId: string, workspaceId: string, id: string, data: CreateProjectRequest): Promise<Project>;\n updateProject(tenantId: string, id: string, updates: UpdateProjectRequest): Promise<Project | null>;\n /** Omitted expectedRevisions is reserved for internal maintenance callers. */\n updateCapabilityBundleIds(tenantId: string, projectId: string, bundleIds: string[], expectedRevisions?: ExpectedCapabilityBundleRevisions): Promise<UpdateProjectCapabilityBundlesResult>;\n deleteProject(tenantId: string, id: string): Promise<boolean>;\n /** Returns whether a tenant project references the given capability bundle. */\n isCapabilityBundleReferenced(tenantId: string, bundleId: string): Promise<boolean>;\n}\n","/**\n * BindingProtocol\n *\n */\n\nexport interface Binding {\n id: string;\n channel: string;\n channelInstallationId: string;\n tenantId: string;\n senderId: string;\n agentId: string;\n threadId?: string;\n workspaceId?: string;\n projectId?: string;\n threadMode: \"fixed\" | \"per_conversation\";\n senderDisplayName?: string;\n senderMetadata?: Record<string, unknown>;\n enabled: boolean;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport interface CreateBindingInput {\n channel: string;\n channelInstallationId: string;\n tenantId: string;\n senderId: string;\n agentId: string;\n threadId?: string;\n threadMode?: \"fixed\" | \"per_conversation\";\n senderDisplayName?: string;\n senderMetadata?: Record<string, unknown>;\n workspaceId?: string;\n projectId?: string;\n /** Whether the binding is eligible for inbound resolution immediately after creation. */\n enabled?: boolean;\n}\n\n/** Filters binding records before pagination is applied. */\nexport interface BindingListParams {\n tenantId: string;\n channel?: string;\n agentId?: string;\n channelInstallationId?: string;\n /** Installation ID prefixes excluded before pagination, for internal namespaces. */\n excludeInstallationIdPrefixes?: string[];\n excludeChannels?: string[];\n limit?: number;\n offset?: number;\n}\n\n/**\n * Fields that may change after a binding is created.\n *\n * Binding identity (`id`, tenant, channel, installation, sender, and timestamps) is intentionally\n * absent so every persistence backend can enforce tenant-scoped mutation without identity drift.\n */\nexport interface BindingMutablePatch {\n /** Agent that receives messages for this subject. */\n agentId?: string;\n /** Fixed thread used when `threadMode` is `fixed`. */\n threadId?: string;\n /** Optional workspace execution scope. */\n workspaceId?: string;\n /** Optional project execution scope. */\n projectId?: string;\n /** Whether messages share one thread or create one per conversation. */\n threadMode?: \"fixed\" | \"per_conversation\";\n /** Human-readable sender label. */\n senderDisplayName?: string;\n /** Mutable sender metadata supplied by trusted internal callers. */\n senderMetadata?: Record<string, unknown>;\n /** Whether inbound resolution may use this binding. */\n enabled?: boolean;\n}\n\n/** Raised when a channel installation already has a binding for the same tenant and sender. */\nexport class DuplicateChannelBindingSubjectError extends Error {\n constructor() {\n super(\"A binding already exists for this channel subject\");\n this.name = \"DuplicateChannelBindingSubjectError\";\n }\n}\n\n/** A duplicate subject found while upgrading a local channel-binding database. */\nexport interface ChannelBindingMigrationConflict {\n tenantId: string;\n channel: string;\n channelInstallationId: string;\n senderId: string;\n count: number;\n}\n\n/**\n * Raised when a local binding uniqueness migration requires operator reconciliation.\n *\n * The conflict list contains only subject identifiers and row counts; binding metadata and other\n * potentially sensitive payloads are never included.\n */\nexport class ChannelBindingMigrationConflictError extends Error {\n readonly conflicts: ChannelBindingMigrationConflict[];\n\n constructor(conflicts: ChannelBindingMigrationConflict[]) {\n super(`Channel binding migration found ${conflicts.length} duplicate subject(s)`);\n this.name = \"ChannelBindingMigrationConflictError\";\n this.conflicts = conflicts;\n }\n}\n\nexport interface BindingRegistry {\n findById(tenantId: string, id: string): Promise<Binding | null>;\n\n findBySubject(params: {\n tenantId: string;\n channel: string;\n channelInstallationId: string;\n senderId: string;\n }): Promise<Binding | null>;\n\n resolve(params: {\n channel: string;\n senderId: string;\n channelInstallationId: string;\n tenantId: string;\n }): Promise<Binding | null>;\n\n create(binding: CreateBindingInput): Promise<Binding>;\n update(tenantId: string, id: string, patch: BindingMutablePatch): Promise<Binding>;\n delete(tenantId: string, id: string): Promise<void>;\n\n list(params: BindingListParams): Promise<Binding[]>;\n\n import(tenantId: string, bindings: CreateBindingInput[]): Promise<Binding[]>;\n export(params: { tenantId: string }): Promise<Binding[]>;\n}\n","import type { TaskMutationSnapshot } from \"./TaskStoreProtocol\";\n\n/**\n * TaskWorkItemProtocol\n *\n * Work item protocol for event-sourced task change tracking.\n * Every status change or action on a TaskItem produces one TaskWorkItem.\n */\n\nexport interface TaskWorkItem {\n id: string;\n taskId: string;\n tenantId: string;\n workspaceId?: string;\n projectId?: string;\n action: string;\n actor: string;\n threadId?: string;\n summary?: string;\n detail?: Record<string, unknown>;\n attempt?: number;\n /** Deterministic task-scoped identity used for idempotent event replay. */\n eventKey?: string;\n createdAt: Date;\n}\n\nexport interface CreateWorkItemRequest {\n taskId: string;\n tenantId: string;\n workspaceId?: string;\n projectId?: string;\n action: string;\n actor: string;\n threadId?: string;\n summary?: string;\n detail?: Record<string, unknown>;\n attempt?: number;\n}\n\n/**\n * Work-item creation request requiring a deterministic event identity.\n *\n * Event keys are unique within a tenant and task, not globally.\n */\nexport interface CreateWorkItemIfAbsentRequest extends CreateWorkItemRequest {\n /** Deterministic task-scoped identity used for idempotent event replay. */\n eventKey: string;\n}\n\nexport interface TaskWorkItemListFilter {\n tenantId: string;\n taskId: string;\n workspaceId?: string;\n projectId?: string;\n action?: string;\n order?: 'asc' | 'desc';\n limit?: number;\n offset?: number;\n}\n\n/** Canonical prefix for public task execution-result event identities. */\nexport const EXECUTION_RESULT_EVENT_KEY_PREFIX = \"execution-result:\";\n\n/**\n * Portable regular-expression source for canonical execution-result event keys.\n *\n * The entire key is the literal `execution-result:` prefix followed by a nonempty\n * suffix containing only ASCII letters, digits, period, underscore, colon, or hyphen.\n * Colon is intentionally allowed so callers can compose structured suffixes.\n */\nexport const EXECUTION_RESULT_EVENT_KEY_PATTERN_SOURCE =\n \"^execution-result:[A-Za-z0-9._:-]+$\";\n\n/** Compiled runtime expression for canonical execution-result event keys. */\nexport const EXECUTION_RESULT_EVENT_KEY_PATTERN =\n new RegExp(EXECUTION_RESULT_EVENT_KEY_PATTERN_SOURCE);\n\n/** Maximum pending execution-result rows accepted by one store query. */\nexport const MAX_PENDING_EXECUTION_RESULTS_LIMIT = 1_000;\n\n/**\n * Determines whether a runtime value is a canonical execution-result event key.\n *\n * @param value Runtime value to validate.\n * @returns True only for the portable canonical ASCII grammar.\n */\nexport function isExecutionResultEventKey(value: unknown): value is string {\n return typeof value === \"string\" && EXECUTION_RESULT_EVENT_KEY_PATTERN.test(value);\n}\n\n/** Canonical lifecycle actions projected into Project Rooms. */\nexport const PROJECT_TASK_LIFECYCLE_ACTIONS = [\n \"in_progress\", \"interrupted\", \"failed\", \"completed\", \"cancelled\", \"reassigned\",\n] as const;\n\n/** Lifecycle action eligible for Project Room projection. */\nexport type ProjectTaskLifecycleAction = typeof PROJECT_TASK_LIFECYCLE_ACTIONS[number];\n\n/** Exclusive cursor for deterministic project lifecycle pagination. */\nexport interface ProjectLifecycleEventCursor {\n /** Creation timestamp of the last returned event. */\n createdAt: Date;\n /** Identifier of the last returned event. */\n id: string;\n}\n\n/** Exact project scope and bounded page for canonical lifecycle events. */\nexport interface ProjectLifecycleEventQuery {\n /** Tenant identifier. */\n tenantId: string;\n /** Workspace identifier. */\n workspaceId: string;\n /** Project identifier. */\n projectId: string;\n /** Nonempty lifecycle actions to include. */\n actions: ProjectTaskLifecycleAction[];\n /** Optional exclusive descending cursor. */\n before?: ProjectLifecycleEventCursor;\n /** Maximum rows to return, from 1 through 100. */\n limit: number;\n}\n\nexport interface TaskWorkItemStore {\n create(params: CreateWorkItemRequest): Promise<TaskWorkItem>;\n /** Atomically creates a work item only while the owning task snapshot matches. */\n createIfTaskSnapshot?(\n params: CreateWorkItemRequest,\n snapshot: TaskMutationSnapshot,\n ): Promise<TaskWorkItem | null>;\n list(filter: TaskWorkItemListFilter): Promise<TaskWorkItem[]>;\n\n /**\n * List the newest bounded set of execution results awaiting reconciliation.\n *\n * Only `execution_result` items with a canonical ASCII\n * `execution-result:[A-Za-z0-9._:-]+` event key are returned. An item is excluded when\n * a task-scoped `execution_reconciled` item has a\n * `detail.executionResultId` equal to that event key. Results are ordered by\n * `createdAt` descending and then `id` descending for deterministic ties.\n *\n * @param params Tenant/task scope and required maximum number of rows.\n * @returns At most `limit` pending execution-result work items, newest first.\n * @throws RangeError with code `INVALID_LIMIT` unless limit is a safe integer from zero through\n * {@link MAX_PENDING_EXECUTION_RESULTS_LIMIT}.\n * @remarks Optional optimization. Stores that omit it remain compatible; callers may use a\n * bounded, non-authoritative fallback through the pre-existing list and event-key methods.\n */\n listPendingExecutionResults?(params: {\n tenantId: string;\n taskId: string;\n limit: number;\n }): Promise<TaskWorkItem[]>;\n\n /**\n * Lists canonical lifecycle events in an exact project scope.\n *\n * @param query Exact scope, actions, exclusive cursor, and page bound.\n * @returns Events ordered by creation time and ID descending.\n */\n listProjectLifecycleEvents?(query: ProjectLifecycleEventQuery): Promise<TaskWorkItem[]>;\n\n /**\n * Find an event by deterministic identity without list pagination.\n *\n * @param tenantId Tenant identifier.\n * @param taskId Task identifier that scopes the event key.\n * @param eventKey Deterministic event identity.\n * @returns The matching item, or `null` when absent.\n */\n findByEventKey(tenantId: string, taskId: string, eventKey: string): Promise<TaskWorkItem | null>;\n\n /**\n * Atomically create an event unless its task-scoped key already exists.\n * Existing events are returned unchanged, preserving immutable replay.\n *\n * @param params Work-item fields including the required event key.\n * @returns The existing or newly created work item.\n */\n createIfAbsentByEventKey(params: CreateWorkItemIfAbsentRequest): Promise<TaskWorkItem>;\n}\n\n/** Work-item capabilities required by trusted Project Task consumers. */\nexport interface ProjectTaskWorkItemStore extends TaskWorkItemStore {\n createIfTaskSnapshot(\n params: CreateWorkItemRequest,\n snapshot: TaskMutationSnapshot,\n ): Promise<TaskWorkItem | null>;\n listProjectLifecycleEvents(\n query: ProjectLifecycleEventQuery,\n ): Promise<TaskWorkItem[]>;\n}\n\n/** Stable capability failure raised before any trusted Project Task mutation. */\nexport class ProjectTaskStoreUnsupportedError extends Error {\n readonly code = \"PROJECT_TASK_STORE_UNSUPPORTED\" as const;\n\n constructor(readonly missingMethods: readonly string[]) {\n super(`Project Task WorkItem store is missing: ${missingMethods.join(\", \")}`);\n this.name = \"ProjectTaskStoreUnsupportedError\";\n }\n}\n\n/** Refines a Main-compatible WorkItem store for trusted Project Task consumers. */\nexport function requireProjectTaskWorkItemStore(\n store: TaskWorkItemStore,\n): ProjectTaskWorkItemStore {\n const missingMethods = [\"createIfTaskSnapshot\", \"listProjectLifecycleEvents\"]\n .filter((name) => {\n try {\n return typeof Reflect.get(store as object, name) !== \"function\";\n } catch {\n return true;\n }\n });\n if (missingMethods.length > 0) {\n throw new ProjectTaskStoreUnsupportedError(missingMethods);\n }\n return store as ProjectTaskWorkItemStore;\n}\n","/**\n * A single canonical belief recorded in a task description.\n *\n * `probability` is retained as the persisted field name, but task guidance uses\n * it as an evidence-support percentage rather than a calibrated probability.\n */\nexport interface TaskBeliefEntry {\n key: string;\n probability: number;\n target: number;\n basis: string;\n}\n\n/** The canonical belief snapshot embedded in task Markdown. */\nexport interface TaskBeliefState {\n entries: TaskBeliefEntry[];\n}\n\n/** Stable diagnostic identifiers returned by the Belief State parser. */\nexport type TaskBeliefDiagnosticCode =\n | \"MISSING_BELIEF_STATE\"\n | \"DUPLICATE_BELIEF_STATE\"\n | \"INVALID_BELIEF_HEADERS\"\n | \"MALFORMED_BELIEF_ROW\"\n | \"INVALID_BELIEF_KEY\"\n | \"INVALID_BELIEF_PERCENT\"\n | \"DUPLICATE_BELIEF_KEY\";\n\n/** A structured failure produced while parsing a task Belief State. */\nexport interface TaskBeliefParseFailure {\n success: false;\n code: TaskBeliefDiagnosticCode;\n message: string;\n line?: number;\n key?: string;\n column?: \"probability\" | \"target\";\n}\n\n/** A successfully parsed task Belief State. */\nexport interface TaskBeliefParseSuccess {\n success: true;\n state: TaskBeliefState;\n}\n\n/** The discriminated result of parsing a task Belief State. */\nexport type TaskBeliefParseResult = TaskBeliefParseSuccess | TaskBeliefParseFailure;\n\ninterface MarkdownLine {\n text: string;\n start: number;\n end: number;\n fenced: boolean;\n lineNumber: number;\n}\n\ninterface SectionRange {\n headingLine: number;\n start: number;\n end: number;\n}\n\nconst BELIEF_HEADING = \"## Belief State\";\nconst ACCEPTANCE_HEADING = \"## Acceptance Criteria\";\nconst EXPECTED_HEADERS = [\"Belief Key\", \"Probability\", \"Target\", \"Basis\"];\nconst KEY_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\nconst PERCENT_PATTERN = /^(?:100|[0-9]{1,2})%$/;\n\nfunction markdownLines(markdown: string): MarkdownLine[] {\n const lines: MarkdownLine[] = [];\n let start = 0;\n let fence: { marker: \"`\" | \"~\"; length: number } | undefined;\n\n while (start <= markdown.length) {\n const newline = markdown.indexOf(\"\\n\", start);\n const end = newline === -1 ? markdown.length : newline + 1;\n const textEnd = newline === -1 ? markdown.length : newline;\n const rawText = markdown.slice(start, textEnd);\n const text = rawText.endsWith(\"\\r\") ? rawText.slice(0, -1) : rawText;\n const fenceMatch = text.match(/^ {0,3}(`{3,}|~{3,})/);\n const fenced = fence !== undefined;\n\n if (!fence && fenceMatch) {\n const marker = fenceMatch[1][0] as \"`\" | \"~\";\n fence = { marker, length: fenceMatch[1].length };\n } else if (fence) {\n const closePattern = new RegExp(`^ {0,3}\\\\${fence.marker}{${fence.length},}[ \\\\t]*$`);\n if (closePattern.test(text)) fence = undefined;\n }\n\n lines.push({\n text,\n start,\n end,\n fenced: fenced || fenceMatch !== null,\n lineNumber: lines.length + 1,\n });\n if (newline === -1) break;\n start = end;\n }\n\n return lines;\n}\n\nfunction sectionRanges(markdown: string, heading: string): SectionRange[] {\n const lines = markdownLines(markdown);\n const ranges: SectionRange[] = [];\n\n for (let index = 0; index < lines.length; index += 1) {\n const line = lines[index];\n if (line.fenced || line.text.trimEnd().replace(/^ {0,3}/, \"\") !== heading) continue;\n\n let end = markdown.length;\n for (let next = index + 1; next < lines.length; next += 1) {\n if (!lines[next].fenced && /^ {0,3}#{1,2}(?:[ \\t]+|$)/.test(lines[next].text)) {\n end = lines[next].start;\n break;\n }\n }\n ranges.push({ headingLine: index, start: line.start, end });\n }\n\n return ranges;\n}\n\nfunction splitTableRow(line: string): string[] | undefined {\n const trimmed = line.trim();\n const finalPipe = trimmed.length - 1;\n if (!trimmed.startsWith(\"|\") || !trimmed.endsWith(\"|\") || isEscapedPipe(trimmed, finalPipe)) {\n return undefined;\n }\n\n const cells: string[] = [];\n let cell = \"\";\n for (let index = 1; index < trimmed.length - 1; index += 1) {\n const character = trimmed[index];\n if (character === \"|\" && isEscapedPipe(trimmed, index)) {\n cell += character;\n } else if (character === \"|\") {\n cells.push(unescapeTableCell(cell.trim()));\n cell = \"\";\n } else {\n cell += character;\n }\n }\n cells.push(unescapeTableCell(cell.trim()));\n return cells;\n}\n\nfunction unescapeTableCell(cell: string): string {\n let unescaped = \"\";\n for (let index = 0; index < cell.length; index += 1) {\n if (cell[index] === \"\\\\\" && (cell[index + 1] === \"\\\\\" || cell[index + 1] === \"|\")) {\n index += 1;\n }\n unescaped += cell[index];\n }\n return unescaped;\n}\n\nfunction isEscapedPipe(line: string, pipeIndex: number): boolean {\n let backslashes = 0;\n for (let index = pipeIndex - 1; index >= 0 && line[index] === \"\\\\\"; index -= 1) {\n backslashes += 1;\n }\n return backslashes % 2 === 1;\n}\n\nfunction failure(\n code: TaskBeliefDiagnosticCode,\n message: string,\n details: Pick<TaskBeliefParseFailure, \"line\" | \"key\" | \"column\"> = {},\n): TaskBeliefParseFailure {\n return { success: false, code, message, ...details };\n}\n\nfunction normalizedText(value: string): string {\n return value.trim().replace(/\\s+/g, \" \");\n}\n\nfunction validateTaskBeliefState(state: TaskBeliefState): void {\n const keys = new Set<string>();\n for (const entry of state.entries) {\n if (!KEY_PATTERN.test(entry.key)) {\n throw new Error(\"Belief keys must be kebab-case without backticks or newlines.\");\n }\n if (keys.has(entry.key)) {\n throw new Error(`Belief key '${entry.key}' appears more than once.`);\n }\n for (const field of [\"probability\", \"target\"] as const) {\n const value = entry[field];\n if (!Number.isInteger(value) || value < 0 || value > 100) {\n throw new Error(`Belief ${field} must be an integer from 0 to 100.`);\n }\n }\n if (entry.basis.trim().length === 0 || /[\\r\\n]/.test(entry.basis)) {\n throw new Error(\"Belief basis must be a nonempty single line.\");\n }\n keys.add(entry.key);\n }\n}\n\nfunction formatTaskBeliefState(state: TaskBeliefState): string {\n validateTaskBeliefState(state);\n const rows = state.entries.map(({ key, probability, target, basis }) => {\n const escapedBasis = normalizedText(basis).replace(/\\\\/g, \"\\\\\\\\\").replace(/\\|/g, \"\\\\|\");\n return `| \\`${key}\\` | ${probability}% | ${target}% | ${escapedBasis} |`;\n });\n return [\n BELIEF_HEADING,\n \"\",\n \"| Belief Key | Probability | Target | Basis |\",\n \"|---|---:|---:|---|\",\n ...rows,\n ].join(\"\\n\");\n}\n\n/** Parses the unique non-code-fenced canonical Belief State section in Markdown. */\nexport function parseTaskBeliefState(markdown: string): TaskBeliefParseResult {\n const sections = sectionRanges(markdown, BELIEF_HEADING);\n if (sections.length === 0) {\n return failure(\"MISSING_BELIEF_STATE\", \"Markdown does not contain a Belief State section.\");\n }\n if (sections.length > 1) {\n return failure(\"DUPLICATE_BELIEF_STATE\", \"Markdown contains more than one Belief State section.\");\n }\n\n const lines = markdownLines(markdown);\n const section = sections[0];\n const content = lines\n .slice(section.headingLine + 1)\n .filter((line) => line.start < section.end && line.text.trim() !== \"\");\n const header = content[0] && splitTableRow(content[0].text);\n const separator = content[1] && splitTableRow(content[1].text);\n if (\n !header ||\n header.length !== EXPECTED_HEADERS.length ||\n header.some((cell, index) => cell !== EXPECTED_HEADERS[index]) ||\n !separator ||\n separator.length !== EXPECTED_HEADERS.length ||\n separator.some((cell) => !/^:?-{3,}:?$/.test(cell))\n ) {\n return failure(\"INVALID_BELIEF_HEADERS\", \"Belief State must use the canonical four-column headers.\");\n }\n\n const entries: TaskBeliefEntry[] = [];\n const keys = new Set<string>();\n for (const line of content.slice(2)) {\n const cells = splitTableRow(line.text);\n if (!cells || cells.length !== 4 || cells[3].length === 0) {\n return failure(\"MALFORMED_BELIEF_ROW\", \"Belief State contains a malformed row.\", {\n line: line.lineNumber,\n });\n }\n\n const keyMatch = cells[0].match(/^`([^`]+)`$/);\n if (!keyMatch || !KEY_PATTERN.test(keyMatch[1])) {\n return failure(\"INVALID_BELIEF_KEY\", \"Belief keys must be backtick-wrapped kebab-case.\", {\n line: line.lineNumber,\n });\n }\n const key = keyMatch[1];\n if (keys.has(key)) {\n return failure(\"DUPLICATE_BELIEF_KEY\", `Belief key '${key}' appears more than once.`, {\n line: line.lineNumber,\n key,\n });\n }\n\n for (const [index, column] of [[1, \"probability\"], [2, \"target\"]] as const) {\n if (!PERCENT_PATTERN.test(cells[index])) {\n return failure(\"INVALID_BELIEF_PERCENT\", `Belief ${column} must be an integer from 0% to 100%.`, {\n line: line.lineNumber,\n column,\n });\n }\n }\n\n keys.add(key);\n entries.push({\n key,\n probability: Number.parseInt(cells[1], 10),\n target: Number.parseInt(cells[2], 10),\n basis: cells[3],\n });\n }\n\n return { success: true, state: { entries } };\n}\n\n/** Compares two Belief States while ignoring entry order and insignificant whitespace. */\nexport function taskBeliefStatesEqual(left: TaskBeliefState, right: TaskBeliefState): boolean {\n if (left.entries.length !== right.entries.length) return false;\n\n const byKey = new Map(right.entries.map((entry) => [entry.key, entry]));\n return left.entries.every((entry) => {\n const other = byKey.get(entry.key);\n return other !== undefined &&\n entry.probability === other.probability &&\n entry.target === other.target &&\n normalizedText(entry.basis) === normalizedText(other.basis);\n });\n}\n\n/**\n * Replaces a unique Belief State section, or inserts one after Acceptance Criteria content.\n *\n * @throws {Error} If the state is noncanonical or the Markdown contains duplicate sections.\n */\nexport function replaceTaskBeliefState(markdown: string, state: TaskBeliefState): string {\n const replacement = formatTaskBeliefState(state);\n const sections = sectionRanges(markdown, BELIEF_HEADING);\n if (sections.length > 1) {\n throw new Error(\"Cannot replace duplicate Belief State sections.\");\n }\n if (sections.length === 1) {\n const section = sections[0];\n const originalSection = markdown.slice(section.start, section.end);\n const trailingWhitespace = originalSection.match(/\\s*$/)?.[0] ?? \"\";\n return markdown.slice(0, section.start) + replacement + trailingWhitespace + markdown.slice(section.end);\n }\n\n const acceptance = sectionRanges(markdown, ACCEPTANCE_HEADING)[0];\n const insertion = acceptance?.end ?? markdown.length;\n const before = markdown.slice(0, insertion);\n const after = markdown.slice(insertion);\n const leadingBreaks = before.length === 0 ? \"\" : before.endsWith(\"\\n\\n\") ? \"\" : before.endsWith(\"\\n\") ? \"\\n\" : \"\\n\\n\";\n const trailingBreaks = after.length === 0 ? \"\" : after.startsWith(\"\\n\") ? \"\\n\" : \"\\n\\n\";\n return before + leadingBreaks + replacement + trailingBreaks + after;\n}\n","import type {\n AgentWebAppAppearance,\n AgentWebAppFeatures,\n} from \"./AgentWebAppStoreProtocol\";\n\n/** Server-owned metadata that isolates an external user's Web App thread. */\nexport interface AgentWebAppThreadMetadata {\n source: \"web_app\";\n webAppId: string;\n userId: string;\n projectId: string;\n label?: string;\n}\n\n/** Public, redacted projection of a thread owned by an Agent Web App identity. */\nexport interface AgentWebAppRuntimeThread {\n id: string;\n projectId: string;\n label?: string;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/** Reviewed public message projection. Structured internal content is not exposed. */\nexport interface AgentWebAppRuntimeMessage {\n id: string;\n role: \"human\" | \"ai\";\n content?: string | AgentWebAppGenUIBlock[];\n}\n\nexport interface AgentWebAppCalloutWidget {\n kind: \"callout\";\n text: string;\n title?: string;\n tone?: \"info\" | \"success\" | \"warning\";\n}\n\nexport interface AgentWebAppTableWidget {\n kind: \"table\";\n columns: string[];\n rows: string[][];\n caption?: string;\n}\n\n/** V1 declarative GenUI block. It deliberately has no HTML, URL, or executable fields. */\nexport interface AgentWebAppGenUIBlock {\n type: \"widget\";\n widget: AgentWebAppCalloutWidget | AgentWebAppTableWidget;\n}\n\n/** Public initialization data available to an external Agent Web App. */\nexport interface AgentWebAppBootstrap {\n webApp: {\n id: string;\n name: string;\n description?: string;\n assistant: {\n id: string;\n name: string;\n description?: string;\n };\n defaultProjectId: string;\n defaultModelKey?: string;\n features: AgentWebAppFeatures;\n appearance: AgentWebAppAppearance;\n identityAssurance: \"unverified\";\n };\n projects: Array<{\n id: string;\n name: string;\n }>;\n models: Array<{\n key: string;\n label: string;\n }>;\n /** Latest owned thread, created implicitly only when thread management is disabled. */\n thread?: AgentWebAppRuntimeThread;\n}\n\n/** Human-in-the-loop interruption exposed through the Web App runtime. */\nexport interface AgentWebAppInterrupt {\n id: string;\n type: string;\n prompt: string;\n data?: Record<string, unknown>;\n}\n\n/**\n * Stable machine-readable error codes returned by the Web App runtime.\n *\n * `INVALID_REQUEST` covers redacted request-validation failures and\n * `INTERNAL_ERROR` covers redacted unexpected server failures.\n */\nexport type AgentWebAppErrorCode =\n | \"WEB_APP_NOT_FOUND\"\n | \"WEB_APP_DISABLED\"\n | \"USER_ID_REQUIRED\"\n | \"INVALID_USER_ID\"\n | \"PROJECT_NOT_ALLOWED\"\n | \"PROJECT_SELECTOR_DISABLED\"\n | \"MODEL_NOT_ALLOWED\"\n | \"FEATURE_DISABLED\"\n | \"THREAD_NOT_FOUND\"\n | \"STREAM_CONFLICT\"\n | \"STREAM_FAILED\"\n | \"INVALID_REQUEST\"\n | \"INTERNAL_ERROR\";\n\n/** Public error payload returned by the Web App runtime. */\nexport interface AgentWebAppError {\n code: AgentWebAppErrorCode;\n message: string;\n retryable: boolean;\n}\n\n/** Stable stream events projected from internal agent execution output. */\nexport type AgentWebAppStreamEvent =\n | { type: \"message.delta\"; text: string }\n | { type: \"message.completed\"; messageId: string }\n | { type: \"tool.started\"; id: string; name: string }\n | { type: \"tool.completed\"; id: string }\n | { type: \"interrupt.created\"; interrupt: AgentWebAppInterrupt }\n | { type: \"genui.render\"; block: AgentWebAppGenUIBlock }\n | { type: \"error\"; error: AgentWebAppError }\n | { type: \"stream.completed\" };\n\nconst MAX_WIDGET_TEXT = 2_000;\nconst MAX_TABLE_COLUMNS = 12;\nconst MAX_TABLE_ROWS = 100;\n\n/** Validate and copy one strict public GenUI block at a trust boundary. */\nexport function parseAgentWebAppGenUIBlock(value: unknown): AgentWebAppGenUIBlock | undefined {\n if (!isExactRecord(value, [\"type\", \"widget\"]) || value.type !== \"widget\" || !isRecord(value.widget)) return undefined;\n const widget = value.widget;\n if (widget.kind === \"callout\") {\n if (!hasOnlyKeys(widget, [\"kind\", \"text\"], [\"title\", \"tone\"]) || !boundedText(widget.text)) return undefined;\n if (widget.title !== undefined && !boundedText(widget.title)) return undefined;\n if (widget.tone !== undefined && widget.tone !== \"info\" && widget.tone !== \"success\" && widget.tone !== \"warning\") return undefined;\n return { type: \"widget\", widget: { kind: \"callout\", text: widget.text, ...(typeof widget.title === \"string\" ? { title: widget.title } : {}), ...(widget.tone ? { tone: widget.tone } : {}) } };\n }\n if (widget.kind === \"table\") {\n if (!hasOnlyKeys(widget, [\"kind\", \"columns\", \"rows\"], [\"caption\"]) || !Array.isArray(widget.columns) || !Array.isArray(widget.rows)) return undefined;\n const columns = widget.columns;\n const rows = widget.rows;\n if (columns.length === 0 || columns.length > MAX_TABLE_COLUMNS || !columns.every(boundedText)) return undefined;\n if (rows.length > MAX_TABLE_ROWS || !rows.every((row) => Array.isArray(row) && row.length === columns.length && row.every(boundedText))) return undefined;\n if (widget.caption !== undefined && !boundedText(widget.caption)) return undefined;\n return { type: \"widget\", widget: { kind: \"table\", columns: [...columns], rows: rows.map((row) => [...row]), ...(typeof widget.caption === \"string\" ? { caption: widget.caption } : {}) } };\n }\n return undefined;\n}\n\nfunction boundedText(value: unknown): value is string {\n return typeof value === \"string\" && value.length <= MAX_WIDGET_TEXT;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isExactRecord(value: unknown, keys: string[]): value is Record<string, unknown> {\n return isRecord(value) && Object.keys(value).length === keys.length && keys.every((key) => key in value);\n}\n\nfunction hasOnlyKeys(value: Record<string, unknown>, required: string[], optional: string[]): boolean {\n const keys = Object.keys(value);\n return required.every((key) => key in value) && keys.every((key) => required.includes(key) || optional.includes(key));\n}\n","/** A safely extracted value from an own enumerable data-property descriptor. */\nexport interface DescriptorDataValue {\n ok: true;\n value: unknown;\n}\n\nfunction ownDescriptorField(descriptor: object, key: string): unknown {\n const field = Object.getOwnPropertyDescriptor(descriptor, key);\n return field && Object.prototype.hasOwnProperty.call(field, \"value\")\n ? field.value\n : undefined;\n}\n\n/**\n * Reads an own enumerable data-property descriptor without consulting its prototype.\n *\n * @param descriptor Property descriptor to inspect.\n * @returns The descriptor value when it is an own enumerable data descriptor, otherwise `undefined`.\n */\nexport function descriptorDataValue(descriptor: unknown): DescriptorDataValue | undefined {\n if (typeof descriptor !== \"object\" || descriptor === null) return undefined;\n try {\n const keys = Reflect.ownKeys(descriptor);\n if (!keys.includes(\"value\") || !keys.includes(\"enumerable\")\n || keys.includes(\"get\") || keys.includes(\"set\")) return undefined;\n const valueField = Object.getOwnPropertyDescriptor(descriptor, \"value\");\n if (!valueField || !Object.prototype.hasOwnProperty.call(valueField, \"value\")\n || ownDescriptorField(descriptor, \"enumerable\") !== true) return undefined;\n return { ok: true, value: valueField.value };\n } catch {\n return undefined;\n }\n}\n\n/**\n * Copies an object-like value into a local plain record using only exact own enumerable data descriptors.\n *\n * Prototypes are deliberately ignored so records from other JavaScript realms remain valid and inherited\n * behavior can never participate in validation.\n *\n * @param value Untrusted value to snapshot.\n * @param required Own string keys that must be present.\n * @param optional Own string keys that may be present.\n * @returns A canonical local record, or `undefined` for malformed descriptors, keys, arrays, or proxies.\n */\nexport function snapshotExactRecord(\n value: unknown,\n required: readonly string[],\n optional: readonly string[] = [],\n): Record<string, unknown> | undefined {\n try {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return undefined;\n const keys = Reflect.ownKeys(value);\n const allowed = new Set([...required, ...optional]);\n if (required.some((key) => !keys.includes(key))\n || keys.some((key) => typeof key !== \"string\" || !allowed.has(key))) return undefined;\n const descriptors = Object.getOwnPropertyDescriptors(value);\n const descriptorKeys = Reflect.ownKeys(descriptors);\n if (descriptorKeys.length !== keys.length || keys.some((key) => !descriptorKeys.includes(key))) return undefined;\n const result: Record<string, unknown> = {};\n for (const key of keys) {\n if (typeof key !== \"string\") return undefined;\n const descriptor = descriptors[key];\n const data = descriptorDataValue(descriptor);\n if (!data) return undefined;\n Object.defineProperty(result, key, {\n value: data.value,\n enumerable: true,\n configurable: true,\n writable: true,\n });\n }\n return result;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Copies a dense cross-realm array using only own element data descriptors and the intrinsic length descriptor.\n *\n * @param value Untrusted value to snapshot.\n * @returns A canonical local dense array, or `undefined` for holes, extras, accessors, or malformed proxies.\n */\nexport function snapshotExactArray(value: unknown): unknown[] | undefined {\n try {\n if (!Array.isArray(value)) return undefined;\n const keys = Reflect.ownKeys(value);\n const descriptors = Object.getOwnPropertyDescriptors(value);\n const descriptorKeys = Reflect.ownKeys(descriptors);\n if (descriptorKeys.length !== keys.length || keys.some((key) => !descriptorKeys.includes(key))) return undefined;\n const lengthDescriptorField = Object.getOwnPropertyDescriptor(descriptors, \"length\");\n const lengthDescriptor = lengthDescriptorField\n && Object.prototype.hasOwnProperty.call(lengthDescriptorField, \"value\")\n ? lengthDescriptorField.value\n : undefined;\n if (typeof lengthDescriptor !== \"object\" || lengthDescriptor === null\n || Reflect.ownKeys(lengthDescriptor).some((key) => key === \"get\" || key === \"set\")\n || !Object.prototype.hasOwnProperty.call(lengthDescriptor, \"value\")) return undefined;\n const length = ownDescriptorField(lengthDescriptor, \"value\");\n if (ownDescriptorField(lengthDescriptor, \"enumerable\") !== false\n || ownDescriptorField(lengthDescriptor, \"configurable\") !== false\n || ownDescriptorField(lengthDescriptor, \"writable\") !== true\n || !Number.isSafeInteger(length) || typeof length !== \"number\" || length < 0\n || keys.length !== length + 1) return undefined;\n const result: unknown[] = [];\n for (let index = 0; index < length; index += 1) {\n const key = String(index);\n const descriptor = descriptors[key];\n const data = descriptorDataValue(descriptor);\n if (!keys.includes(key) || !data) return undefined;\n result.push(data.value);\n }\n if (keys.some((key) => typeof key !== \"string\" || (key !== \"length\" && !/^(0|[1-9]\\d*)$/.test(key)))) return undefined;\n return result;\n } catch {\n return undefined;\n }\n}\n","import type {\n ProjectBotMembershipStatus,\n ProjectBotRole,\n ProjectHumanRole,\n ProjectMembershipStatus,\n ProjectRoomMention,\n ProjectRoomMessageSource,\n} from \"./ProjectRoomProtocol\";\nimport type { TaskItem } from \"./TaskStoreProtocol\";\nimport { snapshotExactArray, snapshotExactRecord } from \"./ExactDataSnapshot\";\n\n/** A message shape safe to expose to Project Room clients. */\nexport interface ProjectRoomPublicMessage {\n id: string;\n roomId: string;\n author:\n | { type: \"human\"; userId: string }\n | { type: \"bot\"; membershipId: string }\n | { type: \"system\" };\n content: { type: \"text\"; text: string };\n mentions: ProjectRoomMention[];\n replyToMessageId?: string;\n source: ProjectRoomMessageSource;\n createdAt: string;\n}\n\n/** A human membership shape safe to expose to Project Room clients. */\nexport interface ProjectRoomPublicMembership {\n id: string;\n userId: string;\n role: ProjectHumanRole;\n status: ProjectMembershipStatus;\n joinedAt: string;\n updatedAt: string;\n}\n\n/** A bot membership shape safe to expose to Project Room clients. */\nexport interface ProjectRoomPublicBotMembership {\n id: string;\n role: ProjectBotRole;\n title: string;\n responsibility?: string;\n mentionName: string;\n status: ProjectBotMembershipStatus;\n joinedAt: string;\n updatedAt: string;\n}\n\n/** A fully identified business event carried by the realtime stream. */\nexport interface ProjectRoomEventOf<TType extends string, TData> {\n id: string;\n type: TType;\n occurredAt: string;\n data: TData;\n}\n\n/** A newly committed message event. */\nexport type ProjectRoomMessageCreatedEvent = ProjectRoomEventOf<\n \"message.created\",\n { message: ProjectRoomPublicMessage }\n>;\n\n/** A changed bot roster event. */\nexport type ProjectRoomRosterChangedEvent = ProjectRoomEventOf<\n \"roster.changed\",\n { change: \"added\" | \"updated\" | \"paused\" | \"resumed\" | \"removed\"; membership: ProjectRoomPublicBotMembership }\n>;\n\n/** A changed human membership event. */\nexport type ProjectRoomMembershipChangedEvent = ProjectRoomEventOf<\n \"membership.changed\",\n { change: \"added\" | \"role_changed\" | \"removed\"; membership: ProjectRoomPublicMembership }\n>;\n\n/** A changed Project Task fact event. */\nexport type ProjectRoomTaskChangedEvent = ProjectRoomEventOf<\n \"task.changed\",\n {\n taskId: string;\n status: TaskItem[\"status\"];\n ownerMembershipId: string;\n updatedAt: string;\n }\n>;\n\n/** All identified business events retained by the realtime broker. */\nexport type ProjectRoomBusinessEvent =\n | ProjectRoomMessageCreatedEvent\n | ProjectRoomRosterChangedEvent\n | ProjectRoomMembershipChangedEvent\n | ProjectRoomTaskChangedEvent;\n\n/** A business event before the broker assigns its process-local ID. */\nexport type ProjectRoomBusinessEventDraft =\n | Omit<ProjectRoomMessageCreatedEvent, \"id\">\n | Omit<ProjectRoomRosterChangedEvent, \"id\">\n | Omit<ProjectRoomMembershipChangedEvent, \"id\">\n | Omit<ProjectRoomTaskChangedEvent, \"id\">;\n\n/** A connection control event; control events are never replayed. */\nexport type ProjectRoomControlEvent =\n | { type: \"ready\"; data: { epoch: string; headEventId: string | null } }\n | { type: \"resync\"; data: { reason: \"SERVER_RESTART\" | \"CURSOR_EXPIRED\" | \"SLOW_CONSUMER\" } }\n | { type: \"access.revoked\"; data: { reason: \"PROJECT_ACCESS_REVOKED\" | \"TOKEN_EXPIRED\" } };\n\n/** The authenticated identity used by Project Room realtime access checks. */\nexport interface ProjectRoomRealtimeActor {\n tenantId: string;\n userId: string;\n projectId: string;\n tokenExpiresAt: number;\n}\n\n/** Writable HTTP socket surface required by the bounded SSE transport. */\nexport interface ProjectRoomSseWritable {\n write(chunk: string): boolean;\n end(): void;\n destroy(): void;\n on(event: \"close\" | \"error\" | \"drain\", listener: () => void): this;\n off(event: \"close\" | \"error\" | \"drain\", listener: () => void): this;\n}\n\n/** The scope used to isolate events between tenant rooms. */\nexport interface ProjectRoomEventScope {\n tenantId: string;\n roomId: string;\n projectId: string;\n}\n\n/** An internal broker event carrying scope that is removed before public serialization. */\nexport type ProjectRoomScopedBusinessEvent = ProjectRoomBusinessEvent & {\n scope: ProjectRoomEventScope;\n};\n\n/** A broker subscription containing replay and its room head. */\nexport interface ProjectRoomEventSubscription {\n replay: ProjectRoomBusinessEvent[];\n headEventId: string | null;\n unsubscribe(): void;\n}\n\n/** The narrow broker contract consumed by realtime publishers and services. */\nexport interface ProjectRoomEventBrokerProtocol {\n readonly epoch: string;\n publish(scope: ProjectRoomEventScope, draft: ProjectRoomBusinessEventDraft): ProjectRoomScopedBusinessEvent;\n subscribe(\n scope: ProjectRoomEventScope,\n afterEventId: string | undefined,\n listener: (event: ProjectRoomBusinessEvent) => void,\n ): ProjectRoomEventSubscription;\n close(): void;\n}\n\n/** A typed cursor failure requiring client REST resynchronization. */\nexport class ProjectRoomCursorError extends Error {\n readonly name = \"ProjectRoomCursorError\";\n\n constructor(readonly code: \"SERVER_RESTART\" | \"CURSOR_EXPIRED\") {\n super(`Project Room realtime cursor requires resynchronization: ${code}`);\n }\n}\n\n/** A typed failure raised when the process-local event sequence is exhausted. */\nexport class ProjectRoomBrokerCapacityError extends Error {\n readonly name = \"ProjectRoomBrokerCapacityError\";\n readonly code = \"PROJECT_ROOM_EVENT_SEQUENCE_EXHAUSTED\" as const;\n\n constructor() {\n super(\"Project Room realtime event sequence is exhausted\");\n }\n}\n\nconst PROJECT_ROOM_EVENT_ID_PATTERN = /^([0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}):([1-9][0-9]*)$/i;\n\n/** The parsed components of a canonical Project Room event ID. */\nexport interface ProjectRoomEventId {\n epoch: string;\n sequence: number;\n}\n\n/** Parses a canonical event ID, returning undefined for malformed or unsafe IDs. */\nexport function parseProjectRoomEventId(value: unknown): ProjectRoomEventId | undefined {\n if (typeof value !== \"string\") return undefined;\n const match = PROJECT_ROOM_EVENT_ID_PATTERN.exec(value);\n if (!match) return undefined;\n const sequence = Number(match[2]);\n if (!Number.isSafeInteger(sequence)) return undefined;\n if (match[1] !== match[1].toLowerCase()) return undefined;\n return { epoch: match[1], sequence };\n}\n\n/** Checks an event ID without relying on realm-specific object identity. */\nexport function isProjectRoomEventId(value: unknown): value is string {\n return parseProjectRoomEventId(value) !== undefined;\n}\n\nfunction isoDate(value: unknown): string | undefined {\n if (typeof value !== \"object\" || value === null) return undefined;\n try {\n const time = Date.prototype.getTime.call(value);\n return Number.isFinite(time) ? new Date(time).toISOString() : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction stringField(record: Record<string, unknown>, key: string): string | undefined {\n return typeof record[key] === \"string\" ? record[key] : undefined;\n}\n\nfunction isOneOf<T extends string>(value: unknown, values: readonly T[]): value is T {\n return typeof value === \"string\" && values.includes(value as T);\n}\n\nconst messageSources = [\"user\", \"agent\", \"task\", \"routine\", \"system\"] as const;\nconst humanRoles = [\"owner\", \"admin\", \"member\", \"viewer\"] as const;\nconst membershipStatuses = [\"active\", \"removed\"] as const;\nconst botRoles = [\"coordinator\", \"specialist\"] as const;\nconst botStatuses = [\"active\", \"paused\", \"removed\"] as const;\n\nfunction mapPublicMessageRecord(record: Record<string, unknown>): ProjectRoomPublicMessage | undefined {\n const id = stringField(record, \"id\");\n const roomId = stringField(record, \"roomId\");\n const source = stringField(record, \"source\");\n const createdAt = isoDate(record.createdAt);\n const content = snapshotExactRecord(record.content, [\"type\", \"text\"]);\n const mentions = snapshotPublicMentions(record.mentions);\n const author = snapshotExactRecord(record.author, [\"type\"], [\"userId\", \"membershipId\", \"assistantId\"]);\n if (!id || !roomId || !isOneOf(source, messageSources) || !createdAt || !content || content.type !== \"text\"\n || typeof content.text !== \"string\" || !mentions || !author || typeof author.type !== \"string\") return undefined;\n const publicAuthor = author.type === \"human\" && typeof author.userId === \"string\"\n ? { type: \"human\" as const, userId: author.userId }\n : author.type === \"bot\" && typeof author.membershipId === \"string\"\n ? { type: \"bot\" as const, membershipId: author.membershipId }\n : author.type === \"system\" ? { type: \"system\" as const } : undefined;\n if (!publicAuthor) return undefined;\n const result: ProjectRoomPublicMessage = { id, roomId, author: publicAuthor, content: { type: \"text\", text: content.text }, mentions: mentions as ProjectRoomMention[], source: source as ProjectRoomMessageSource, createdAt };\n if (record.replyToMessageId !== undefined) {\n if (typeof record.replyToMessageId !== \"string\") return undefined;\n result.replyToMessageId = record.replyToMessageId;\n }\n return result;\n}\n\nfunction snapshotPublicMentions(value: unknown): ProjectRoomMention[] | undefined {\n const rows = snapshotExactArray(value);\n if (!rows) return undefined;\n const result: ProjectRoomMention[] = [];\n for (const row of rows) {\n const team = snapshotExactRecord(row, [\"type\"]);\n if (team?.type === \"team\") { result.push({ type: \"team\" }); continue; }\n const bot = snapshotExactRecord(row, [\"type\", \"membershipId\"]);\n if (bot?.type === \"bot\" && typeof bot.membershipId === \"string\") {\n result.push({ type: \"bot\", membershipId: bot.membershipId });\n continue;\n }\n return undefined;\n }\n return result;\n}\n\nfunction mapPublicMembershipRecord(record: Record<string, unknown>): ProjectRoomPublicMembership | undefined {\n const joinedAt = isoDate(record.joinedAt); const updatedAt = isoDate(record.updatedAt);\n if (typeof record.id !== \"string\" || typeof record.userId !== \"string\" || !isOneOf(record.role, humanRoles) || !isOneOf(record.status, membershipStatuses) || !joinedAt || !updatedAt) return undefined;\n return { id: record.id, userId: record.userId, role: record.role, status: record.status, joinedAt, updatedAt };\n}\n\nfunction mapPublicBotMembershipRecord(record: Record<string, unknown>): ProjectRoomPublicBotMembership | undefined {\n const joinedAt = isoDate(record.joinedAt); const updatedAt = isoDate(record.updatedAt);\n if (typeof record.id !== \"string\" || !isOneOf(record.role, botRoles) || typeof record.title !== \"string\" || typeof record.mentionName !== \"string\" || !isOneOf(record.status, botStatuses) || !joinedAt || !updatedAt || record.responsibility !== undefined && typeof record.responsibility !== \"string\") return undefined;\n return { id: record.id, role: record.role, title: record.title, ...(record.responsibility === undefined ? {} : { responsibility: record.responsibility }), mentionName: record.mentionName, status: record.status, joinedAt, updatedAt };\n}\n\n/** Maps a canonical internal message to the strict public message DTO. */\nexport function toProjectRoomPublicMessage(value: unknown): ProjectRoomPublicMessage | undefined {\n const record = snapshotExactRecord(value, [\n \"id\", \"tenantId\", \"workspaceId\", \"projectId\", \"roomId\", \"author\", \"content\", \"mentions\", \"source\", \"createdAt\",\n ], [\"replyToMessageId\", \"sourceId\", \"idempotencyKey\"]);\n if (!record) return undefined;\n return mapPublicMessageRecord(record);\n}\n\n/** A descriptor-safe message projection together with its canonical realtime scope. */\nexport function snapshotProjectRoomMessageRealtime(value: unknown): {\n scope: { tenantId: string; roomId: string; projectId: string };\n publicMessage: ProjectRoomPublicMessage;\n} | undefined {\n const record = snapshotExactRecord(value, [\"id\", \"tenantId\", \"workspaceId\", \"projectId\", \"roomId\", \"author\", \"content\", \"mentions\", \"source\", \"createdAt\"], [\"replyToMessageId\", \"sourceId\", \"idempotencyKey\"]);\n if (!record) return undefined;\n const publicMessage = mapPublicMessageRecord(record);\n if (!publicMessage || typeof record.tenantId !== \"string\" || typeof record.projectId !== \"string\") return undefined;\n return { scope: { tenantId: record.tenantId, roomId: publicMessage.roomId, projectId: record.projectId }, publicMessage };\n}\n\n/** Maps a canonical internal human membership to the strict public DTO. */\nexport function toProjectRoomPublicMembership(value: unknown): ProjectRoomPublicMembership | undefined {\n const record = snapshotExactRecord(value,\n [\"id\", \"tenantId\", \"projectId\", \"userId\", \"role\", \"status\", \"joinedAt\", \"updatedAt\"]);\n if (!record || typeof record.id !== \"string\" || typeof record.userId !== \"string\"\n || !isOneOf(record.role, humanRoles) || !isOneOf(record.status, membershipStatuses)) return undefined;\n const joinedAt = isoDate(record.joinedAt);\n const updatedAt = isoDate(record.updatedAt);\n if (!joinedAt || !updatedAt) return undefined;\n return { id: record.id, userId: record.userId, role: record.role,\n status: record.status, joinedAt, updatedAt };\n}\n\n/** A descriptor-safe human membership projection with canonical tenant/project scope. */\nexport function snapshotProjectRoomMembershipRealtime(value: unknown): {\n scope: { tenantId: string; projectId: string };\n publicMembership: ProjectRoomPublicMembership;\n} | undefined {\n const record = snapshotExactRecord(value, [\"id\", \"tenantId\", \"projectId\", \"userId\", \"role\", \"status\", \"joinedAt\", \"updatedAt\"]);\n if (!record) return undefined;\n const publicMembership = mapPublicMembershipRecord(record);\n if (!publicMembership || typeof record.tenantId !== \"string\" || typeof record.projectId !== \"string\") return undefined;\n return { scope: { tenantId: record.tenantId, projectId: record.projectId }, publicMembership };\n}\n\n/** Maps a canonical internal bot membership to the strict public DTO. */\nexport function toProjectRoomPublicBotMembership(value: unknown): ProjectRoomPublicBotMembership | undefined {\n const record = snapshotExactRecord(value,\n [\"id\", \"tenantId\", \"workspaceId\", \"projectId\", \"roomId\", \"assistantId\", \"role\", \"title\", \"mentionName\", \"status\", \"roomThreadId\", \"joinedAt\", \"updatedAt\"],\n [\"responsibility\"]);\n if (!record || typeof record.id !== \"string\" || !isOneOf(record.role, botRoles) || typeof record.title !== \"string\"\n || typeof record.mentionName !== \"string\" || !isOneOf(record.status, botStatuses)) return undefined;\n if (record.responsibility !== undefined && typeof record.responsibility !== \"string\") return undefined;\n const joinedAt = isoDate(record.joinedAt);\n const updatedAt = isoDate(record.updatedAt);\n if (!joinedAt || !updatedAt) return undefined;\n const result: ProjectRoomPublicBotMembership = {\n id: record.id, role: record.role, title: record.title,\n mentionName: record.mentionName, status: record.status, joinedAt, updatedAt,\n };\n if (record.responsibility !== undefined) result.responsibility = record.responsibility;\n return result;\n}\n\n/** A descriptor-safe bot membership projection with canonical realtime scope. */\nexport function snapshotProjectRoomBotMembershipRealtime(value: unknown): {\n scope: { tenantId: string; roomId: string; projectId: string };\n publicMembership: ProjectRoomPublicBotMembership;\n} | undefined {\n const record = snapshotExactRecord(value, [\"id\", \"tenantId\", \"workspaceId\", \"projectId\", \"roomId\", \"assistantId\", \"role\", \"title\", \"mentionName\", \"status\", \"roomThreadId\", \"joinedAt\", \"updatedAt\"], [\"responsibility\"]);\n if (!record) return undefined;\n const publicMembership = mapPublicBotMembershipRecord(record);\n if (!publicMembership || typeof record.tenantId !== \"string\" || typeof record.roomId !== \"string\" || typeof record.projectId !== \"string\") return undefined;\n return { scope: { tenantId: record.tenantId, roomId: record.roomId, projectId: record.projectId }, publicMembership };\n}\n","import { snapshotExactRecord } from \"./ExactDataSnapshot\";\n\n/** Queue execution behavior available to privileged host dispatchers. */\nexport type QueuedExecutionMode = \"followup\";\n\n/** Trusted Project Room identity persisted with a privileged queue message. */\nexport interface ProjectRoomTrustedRunContext {\n tenantId: string;\n workspaceId: string;\n projectId: string;\n roomId: string;\n sourceRoomMessageId: string;\n membershipId: string;\n assistantId: string;\n inputMessageId: string;\n role: \"coordinator\" | \"specialist\";\n title: string;\n responsibility?: string;\n}\n\n/** Trusted Project Task identity persisted with a privileged queue message. */\nexport interface ProjectTaskTrustedRunContext {\n tenantId: string;\n workspaceId: string;\n projectId: string;\n roomId: string;\n membershipId: string;\n assistantId: string;\n taskId: string;\n threadId: string;\n inputMessageId: string;\n}\n\n/** Host-authenticated metadata that cannot be supplied through public Agent APIs. */\nexport interface TrustedRunContext {\n projectRoom?: ProjectRoomTrustedRunContext;\n projectTask?: ProjectTaskTrustedRunContext;\n}\n\n/**\n * Strictly validates and clones host-authenticated queue context read from durable storage.\n *\n * @param value - Untrusted decoded database value.\n * @returns A validated defensive clone of the trusted run context.\n * @throws Error when the stored value does not exactly match the trusted context contract.\n */\nexport function parseTrustedRunContext(value: unknown): TrustedRunContext {\n const contextValues = snapshotExactRecord(value, [], [\"projectRoom\", \"projectTask\"]);\n if (!contextValues || Object.keys(contextValues).length !== 1) {\n throw new Error(\"Invalid trusted agent run context\");\n }\n if (Object.prototype.hasOwnProperty.call(contextValues, \"projectTask\")) {\n const requiredKeys = [\n \"tenantId\", \"workspaceId\", \"projectId\", \"roomId\", \"membershipId\",\n \"assistantId\", \"taskId\", \"threadId\", \"inputMessageId\",\n ] as const;\n const projectTaskValues = snapshotExactRecord(contextValues.projectTask, requiredKeys);\n if (!projectTaskValues\n || requiredKeys.some((key) => typeof projectTaskValues[key] !== \"string\" || projectTaskValues[key].length === 0)) {\n throw new Error(\"Invalid trusted agent run context\");\n }\n return {\n projectTask: {\n tenantId: projectTaskValues.tenantId as string,\n workspaceId: projectTaskValues.workspaceId as string,\n projectId: projectTaskValues.projectId as string,\n roomId: projectTaskValues.roomId as string,\n membershipId: projectTaskValues.membershipId as string,\n assistantId: projectTaskValues.assistantId as string,\n taskId: projectTaskValues.taskId as string,\n threadId: projectTaskValues.threadId as string,\n inputMessageId: projectTaskValues.inputMessageId as string,\n },\n };\n }\n const projectRoomValue = contextValues?.projectRoom;\n const requiredKeys = [\n \"tenantId\", \"workspaceId\", \"projectId\", \"roomId\", \"sourceRoomMessageId\", \"membershipId\",\n \"assistantId\", \"inputMessageId\", \"role\", \"title\",\n ] as const;\n const projectRoomValues = snapshotExactRecord(projectRoomValue, requiredKeys, [\"responsibility\"]);\n const hasResponsibility = projectRoomValues !== undefined\n && Object.prototype.hasOwnProperty.call(projectRoomValues, \"responsibility\");\n if (!projectRoomValues\n || requiredKeys.some((key) => typeof projectRoomValues[key] !== \"string\" || projectRoomValues[key].length === 0)\n || (hasResponsibility && projectRoomValues.responsibility !== undefined\n && (typeof projectRoomValues.responsibility !== \"string\" || projectRoomValues.responsibility.length === 0))\n || (projectRoomValues.role !== \"coordinator\" && projectRoomValues.role !== \"specialist\")) {\n throw new Error(\"Invalid trusted agent run context\");\n }\n const parsedProjectRoom: ProjectRoomTrustedRunContext = {\n tenantId: projectRoomValues.tenantId as string,\n workspaceId: projectRoomValues.workspaceId as string,\n projectId: projectRoomValues.projectId as string,\n roomId: projectRoomValues.roomId as string,\n sourceRoomMessageId: projectRoomValues.sourceRoomMessageId as string,\n membershipId: projectRoomValues.membershipId as string,\n assistantId: projectRoomValues.assistantId as string,\n inputMessageId: projectRoomValues.inputMessageId as string,\n role: projectRoomValues.role,\n title: projectRoomValues.title as string,\n };\n if (hasResponsibility && typeof projectRoomValues.responsibility === \"string\") {\n parsedProjectRoom.responsibility = projectRoomValues.responsibility;\n }\n return { projectRoom: parsedProjectRoom };\n}\n\n/**\n * Strictly validates a queued execution mode read from durable storage.\n *\n * @param value - Untrusted database value.\n * @returns The validated execution mode.\n * @throws Error when the stored value is not supported.\n */\nexport function parseQueuedExecutionMode(value: unknown): QueuedExecutionMode {\n if (value !== \"followup\") throw new Error(\"Invalid queued execution mode\");\n return value;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACaO,IAAK,YAAL,kBAAKA,eAAL;AACL,EAAAA,WAAA,WAAQ;AACR,EAAAA,WAAA,gBAAa;AACb,EAAAA,WAAA,UAAO;AACP,EAAAA,WAAA,gBAAa;AAEb,EAAAA,WAAA,gBAAa;AAEb,EAAAA,WAAA,cAAW;AARD,SAAAA;AAAA,GAAA;AAkOL,SAAS,kBACd,QAC2B;AAC3B,SAAO,OAAO,SAAS;AACzB;AA4FO,SAAS,uBACd,QACgC;AAChC,SAAO,OAAO,SAAS;AACzB;AAKO,SAAS,sBACd,QAC+B;AAC/B,SAAO,OAAO,SAAS;AACzB;AA4BO,SAAS,SAAS,QAAqD;AAC5E,SAAO;AACT;AAKO,SAAS,kBACd,QAC2B;AAC3B,SAA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heduledTaskStatus","LoggerType","McpMessageType","requiredKeys"]}