@factory/droid-sdk 0.1.1 → 0.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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/schemas/enums.ts","../src/schemas/constants.ts","../src/schemas/shared.ts","../src/schemas/messages.ts","../src/schemas/mcp.ts","../src/schemas/mission.ts","../src/schemas/client.ts","../src/schemas/server.ts","../src/errors.ts","../src/transport.ts","../src/protocol.ts","../src/client.ts","../src/stream.ts","../src/query.ts","../src/session.ts"],"sourcesContent":["// @factory-ai/droid-sdk - TypeScript SDK for the Factory Droid CLI\n// This is the public API barrel file.\n\n// --- Schemas (enums, constants, Zod schemas, types) ---\nexport * from \"./schemas/index.js\";\n\n// --- Errors ---\nexport * from \"./errors.js\";\n\n// --- Transport types ---\nexport * from \"./types.js\";\nexport { ProcessTransport } from \"./transport.js\";\n\n// --- Protocol engine ---\nexport { ProtocolEngine } from \"./protocol.js\";\nexport type {\n AskUserHandler,\n NotificationCallback,\n NotificationFilter,\n PermissionHandler,\n} from \"./protocol.js\";\n\n// --- Client ---\nexport { DroidClient } from \"./client.js\";\nexport type {\n ClientAskUserHandler,\n ClientPermissionHandler,\n DroidClientOptions,\n} from \"./client.js\";\n\n// --- Stream message types and converter ---\nexport {\n convertNotificationToStreamMessage,\n StreamStateTracker,\n} from \"./stream.js\";\nexport type {\n AssistantTextDelta,\n ThinkingTextDelta,\n ToolUse,\n ToolResult,\n ToolProgress,\n WorkingStateChanged,\n TokenUsageUpdate,\n CreateMessage,\n PermissionResolved,\n SettingsUpdated,\n SessionTitleUpdated,\n McpStatusChanged,\n MissionStateChanged,\n MissionFeaturesChanged,\n MissionProgressEntry,\n MissionHeartbeat,\n MissionWorkerStarted,\n MissionWorkerCompleted,\n McpAuthRequired,\n McpAuthCompleted,\n ErrorEvent,\n TurnComplete,\n DroidMessage,\n} from \"./stream.js\";\n\n// --- High-level API: query ---\nexport { query } from \"./query.js\";\nexport type { QueryOptions, DroidQuery } from \"./query.js\";\n\n// --- High-level API: session ---\nexport { createSession, resumeSession, DroidSession } from \"./session.js\";\nexport type {\n CreateSessionOptions,\n ResumeSessionOptions,\n MessageOptions,\n DroidResult,\n} from \"./session.js\";\n","/**\n * All protocol enums for the Factory Droid SDK.\n *\n * Ported from:\n * - packages/common/src/droid/enums.ts\n * - packages/common/src/shared/enums.ts\n * - packages/common/src/llm/enums.ts\n * - packages/common/src/settings/enums.ts\n */\n\n/** Droid server methods (client → server communication). */\nexport enum DroidServerMethod {\n INITIALIZE_SESSION = \"droid.initialize_session\",\n LOAD_SESSION = \"droid.load_session\",\n ADD_USER_MESSAGE = \"droid.add_user_message\",\n INTERRUPT_SESSION = \"droid.interrupt_session\",\n KILL_WORKER_SESSION = \"droid.kill_worker_session\",\n UPDATE_SESSION_SETTINGS = \"droid.update_session_settings\",\n TOGGLE_MCP_SERVER = \"droid.toggle_mcp_server\",\n AUTHENTICATE_MCP_SERVER = \"droid.authenticate_mcp_server\",\n CANCEL_MCP_AUTH = \"droid.cancel_mcp_auth\",\n CLEAR_MCP_AUTH = \"droid.clear_mcp_auth\",\n ADD_MCP_SERVER = \"droid.add_mcp_server\",\n REMOVE_MCP_SERVER = \"droid.remove_mcp_server\",\n LIST_MCP_REGISTRY = \"droid.list_mcp_registry\",\n LIST_MCP_TOOLS = \"droid.list_mcp_tools\",\n LIST_MCP_SERVERS = \"droid.list_mcp_servers\",\n TOGGLE_MCP_TOOL = \"droid.toggle_mcp_tool\",\n SUBMIT_MCP_AUTH_CODE = \"droid.submit_mcp_auth_code\",\n LIST_SKILLS = \"droid.list_skills\",\n SUBMIT_BUG_REPORT = \"droid.submit_bug_report\",\n}\n\n/** Droid client methods (server → client communication). */\nexport enum DroidClientMethod {\n SESSION_NOTIFICATION = \"droid.session_notification\",\n REQUEST_PERMISSION = \"droid.request_permission\",\n ASK_USER = \"droid.ask_user\",\n}\n\n/** Session notification types. */\nexport enum SessionNotificationType {\n TOOL_RESULT = \"tool_result\",\n TOOL_PROGRESS_UPDATE = \"tool_progress_update\",\n CREATE_MESSAGE = \"create_message\",\n ERROR = \"error\",\n DROID_WORKING_STATE_CHANGED = \"droid_working_state_changed\",\n PERMISSION_RESOLVED = \"permission_resolved\",\n SETTINGS_UPDATED = \"settings_updated\",\n SESSION_TITLE_UPDATED = \"session_title_updated\",\n MCP_STATUS_CHANGED = \"mcp_status_changed\",\n ASSISTANT_TEXT_DELTA = \"assistant_text_delta\",\n THINKING_TEXT_DELTA = \"thinking_text_delta\",\n SESSION_TOKEN_USAGE_CHANGED = \"session_token_usage_changed\",\n MISSION_STATE_CHANGED = \"mission_state_changed\",\n MISSION_FEATURES_CHANGED = \"mission_features_changed\",\n MISSION_PROGRESS_ENTRY = \"mission_progress_entry\",\n MISSION_HEARTBEAT = \"mission_heartbeat\",\n MISSION_WORKER_STARTED = \"mission_worker_started\",\n MISSION_WORKER_COMPLETED = \"mission_worker_completed\",\n MCP_AUTH_REQUIRED = \"mcp_auth_required\",\n MCP_AUTH_COMPLETED = \"mcp_auth_completed\",\n}\n\n/** Tool confirmation outcome options (possible user responses to permission requests). */\nexport enum ToolConfirmationOutcome {\n ProceedOnce = \"proceed_once\",\n ProceedAlways = \"proceed_always\",\n ProceedAutoRun = \"proceed_auto_run\",\n ProceedAutoRunLow = \"proceed_auto_run_low\",\n ProceedAutoRunMedium = \"proceed_auto_run_medium\",\n ProceedAutoRunHigh = \"proceed_auto_run_high\",\n ProceedEdit = \"proceed_edit\",\n Cancel = \"cancel\",\n}\n\n/** Tool confirmation type (which tool is requesting permission). */\nexport enum ToolConfirmationType {\n Edit = \"edit\",\n Execute = \"exec\",\n Create = \"create\",\n AskUser = \"ask_user\",\n ExitSpecMode = \"exit_spec_mode\",\n ProposeMission = \"propose_mission\",\n StartMissionRun = \"start_mission_run\",\n ApplyPatch = \"apply_patch\",\n McpTool = \"mcp_tool\",\n}\n\n/** Droid working state (represents what the agent is currently doing). */\nexport enum DroidWorkingState {\n Idle = \"idle\",\n StreamingAssistantMessage = \"streaming_assistant_message\",\n WaitingForToolConfirmation = \"waiting_for_tool_confirmation\",\n ExecutingTool = \"executing_tool\",\n CompactingConversation = \"compacting_conversation\",\n}\n\n/** Error types for error notifications. */\nexport enum DroidErrorType {\n CONNECTION_ERROR = \"ConnectionError\",\n PROTOCOL_ERROR = \"ProtocolError\",\n SESSION_ERROR = \"SessionError\",\n TIMEOUT_ERROR = \"TimeoutError\",\n DROID_CLIENT_ERROR = \"DroidClientError\",\n PROCESS_EXIT_ERROR = \"ProcessExitError\",\n ERROR = \"Error\",\n}\n\n/** MCP server connection status. */\nexport enum McpServerStatus {\n Connecting = \"connecting\",\n Connected = \"connected\",\n Disconnected = \"disconnected\",\n Failed = \"failed\",\n Disabled = \"disabled\",\n}\n\n/** MCP server transport type. */\nexport enum McpServerType {\n Stdio = \"stdio\",\n Http = \"http\",\n Sse = \"sse\",\n}\n\n/** Overall MCP initialization status. */\nexport enum McpStatus {\n NotInitialized = \"not-initialized\",\n Initializing = \"initializing\",\n Ready = \"ready\",\n NoServers = \"no-servers\",\n Failed = \"failed\",\n}\n\n/** MCP authentication outcome. */\nexport enum McpAuthOutcome {\n Success = \"success\",\n Cancelled = \"cancelled\",\n Failed = \"failed\",\n}\n\n/** Session type for mission decomposition (orchestrator manages workers). */\nexport enum DecompSessionType {\n Orchestrator = \"orchestrator\",\n Worker = \"worker\",\n}\n\n/** Mission state enum (used by orchestrator mission runner). */\nexport enum MissionState {\n AwaitingInput = \"awaiting_input\",\n Initializing = \"initializing\",\n Running = \"running\",\n Paused = \"paused\",\n OrchestratorTurn = \"orchestrator_turn\",\n Completed = \"completed\",\n}\n\n/** Feature status enum (mirrors orchestrator feature lifecycle). */\nexport enum FeatureStatus {\n Pending = \"pending\",\n InProgress = \"in_progress\",\n Completed = \"completed\",\n Cancelled = \"cancelled\",\n}\n\n/** Success state for feature completion. */\nexport enum FeatureSuccessState {\n Success = \"success\",\n Partial = \"partial\",\n Failure = \"failure\",\n}\n\n/** Issue severity for discovered issues. */\nexport enum IssueSeverity {\n Blocking = \"blocking\",\n NonBlocking = \"non_blocking\",\n Suggestion = \"suggestion\",\n}\n\n/** Dismissal item type. */\nexport enum DismissalType {\n DiscoveredIssue = \"discovered_issue\",\n CriticalContext = \"critical_context\",\n IncompleteWork = \"incomplete_work\",\n}\n\n/** Progress log entry type. */\nexport enum ProgressLogEntryType {\n MissionAccepted = \"mission_accepted\",\n MissionPaused = \"mission_paused\",\n MissionResumed = \"mission_resumed\",\n MissionRunStarted = \"mission_run_started\",\n WorkerStarted = \"worker_started\",\n WorkerSelectedFeature = \"worker_selected_feature\",\n WorkerCompleted = \"worker_completed\",\n WorkerFailed = \"worker_failed\",\n WorkerPaused = \"worker_paused\",\n HandoffItemsDismissed = \"handoff_items_dismissed\",\n MilestoneValidationTriggered = \"milestone_validation_triggered\",\n}\n\n/**\n * The interaction mode determines how Droid operates.\n * - Auto: Droid can execute actions based on autonomy level\n * - Spec: Droid is in planning/research mode only (read-only operations)\n * - AGI: Droid orchestrates missions with read-only tools and orchestrator controls\n */\nexport enum DroidInteractionMode {\n Auto = \"auto\",\n Spec = \"spec\",\n AGI = \"agi\",\n}\n\n/**\n * Autonomy level determines what actions Droid can perform without user confirmation.\n * - Off: User controls all actions (confirmation required for everything)\n * - Low: Allow file edits and read-only commands\n * - Medium: Allow reversible commands\n * - High: Allow all commands without prompts\n */\nexport enum AutonomyLevel {\n Off = \"off\",\n Low = \"low\",\n Medium = \"medium\",\n High = \"high\",\n}\n\n/**\n * Combined autonomy mode for backward compatibility.\n * @deprecated Use DroidInteractionMode + AutonomyLevel instead.\n */\nexport enum AutonomyMode {\n Normal = \"normal\",\n Spec = \"spec\",\n AutoLow = \"auto-low\",\n AutoMedium = \"auto-medium\",\n AutoHigh = \"auto-high\",\n}\n\n/** Reasoning effort levels for LLMs. */\nexport enum ReasoningEffort {\n None = \"none\",\n Dynamic = \"dynamic\",\n Off = \"off\",\n Minimal = \"minimal\",\n Low = \"low\",\n Medium = \"medium\",\n High = \"high\",\n ExtraHigh = \"xhigh\",\n Max = \"max\",\n}\n\n/** Model provider identifiers. */\nexport enum ModelProvider {\n ANTHROPIC = \"anthropic\",\n OPENAI = \"openai\",\n GENERIC_CHAT_COMPLETION_API = \"generic-chat-completion-api\",\n FACTORY = \"factory\",\n GOOGLE = \"google\",\n XAI = \"xai\",\n VOYAGE = \"voyage\",\n}\n\n/** Standard JSON-RPC 2.0 error codes. */\nexport enum JsonRpcErrorCode {\n PARSE_ERROR = -32700,\n INVALID_REQUEST = -32600,\n METHOD_NOT_FOUND = -32601,\n INVALID_PARAMS = -32602,\n INTERNAL_ERROR = -32603,\n AUTHENTICATION_ERROR = -32001,\n ENTITY_NOT_FOUND = -32004,\n SESSION_DISCONNECTED = -32005,\n}\n\n/** JSON-RPC message type discriminator. */\nexport enum JsonRpcMessageType {\n Request = \"request\",\n Response = \"response\",\n Notification = \"notification\",\n}\n\n/**\n * Settings hierarchy level enum.\n * Precedence order (highest to lowest): Org → Runtime → Folder → Project → User\n */\nexport enum SettingsLevel {\n Org = \"org\",\n Runtime = \"runtime\",\n User = \"user\",\n Project = \"project\",\n Folder = \"folder\",\n Dynamic = \"dynamic\",\n BuiltIn = \"builtin\",\n}\n\n/** Skill file location type. */\nexport enum SkillLocation {\n Project = \"project\",\n Personal = \"personal\",\n Builtin = \"builtin\",\n}\n","/**\n * Protocol version constants for the Factory Droid SDK.\n */\n\n/** JSON-RPC protocol version. */\nexport const JSONRPC_VERSION = \"2.0\" as const;\n\n/**\n * Legacy Factory API version for backward compatibility.\n * @deprecated Use FACTORY_PROTOCOL_VERSION for runtime compatibility instead.\n */\nexport const LEGACY_FACTORY_API_VERSION = \"1.0.0\" as const;\n\n/** Current Factory protocol version. */\nexport const FACTORY_PROTOCOL_VERSION = \"1.2.0\" as const;\n\n/** HTTP header identifying the Factory client type. */\nexport const FACTORY_CLIENT_HEADER = \"X-Factory-Client\" as const;\n\n/** HTTP header identifying the Factory client version. */\nexport const FACTORY_CLIENT_VERSION = \"X-Client-Version\" as const;\n\n/** Default request timeout in milliseconds (30s). */\nexport const DEFAULT_REQUEST_TIMEOUT = 30_000;\n\n/** Session initialization timeout in milliseconds (60s). */\nexport const SESSION_INIT_TIMEOUT = 60_000;\n\n/** MCP authentication timeout in milliseconds (300s). */\nexport const MCP_AUTH_TIMEOUT = 300_000;\n","/**\n * JSON-RPC 2.0 base schemas for the Factory Droid protocol.\n *\n * Ported from: packages/common/src/shared/schemas.ts\n */\n\nimport { z } from \"zod\";\n\nimport { JSONRPC_VERSION, LEGACY_FACTORY_API_VERSION } from \"./constants.js\";\nimport { JsonRpcErrorCode } from \"./enums.js\";\n\n// ---------------------------------------------------------------------------\n// Trace context metadata\n// ---------------------------------------------------------------------------\n\n/** Trace context metadata for distributed tracing propagation. */\nexport const TraceContextMetaSchema = z.object({\n traceparent: z.string().optional(),\n tracestate: z.string().optional(),\n});\n\nexport type TraceContextMeta = z.infer<typeof TraceContextMetaSchema>;\n\n// ---------------------------------------------------------------------------\n// JSON-RPC envelope\n// ---------------------------------------------------------------------------\n\n/** JSON-RPC 2.0 envelope with Factory protocol extensions. */\nexport const JsonRpcEnvelopeSchema = z.object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n factoryApiVersion: z.literal(LEGACY_FACTORY_API_VERSION),\n factoryProtocolVersion: z.string().optional(),\n _meta: TraceContextMetaSchema.optional(),\n});\n\nexport type JsonRpcEnvelope = z.infer<typeof JsonRpcEnvelopeSchema>;\n\n// ---------------------------------------------------------------------------\n// JSON-RPC error\n// ---------------------------------------------------------------------------\n\n/** JSON-RPC 2.0 error object. */\nexport const JsonRpcErrorSchema = z.object({\n code: z.nativeEnum(JsonRpcErrorCode),\n message: z.string(),\n data: z.unknown().optional(),\n});\n\nexport type JsonRpcError = z.infer<typeof JsonRpcErrorSchema>;\n\n// ---------------------------------------------------------------------------\n// Base message schemas (without envelope)\n// ---------------------------------------------------------------------------\n\n/** Base JSON-RPC request. */\nexport const BaseRequestSchema = z.object({\n type: z.literal(\"request\"),\n id: z.string(),\n method: z.string(),\n params: z.unknown().optional(),\n});\n\nexport type BaseRequest = z.infer<typeof BaseRequestSchema>;\n\n/** Base JSON-RPC success response. */\nexport const BaseResponseSuccessSchema = z.object({\n type: z.literal(\"response\"),\n id: z.string(),\n result: z.unknown(),\n});\n\nexport type BaseResponseSuccess = z.infer<typeof BaseResponseSuccessSchema>;\n\n/** Base JSON-RPC failure response. */\nexport const BaseResponseFailureSchema = z.object({\n type: z.literal(\"response\"),\n id: z.string().nullable(),\n error: JsonRpcErrorSchema,\n});\n\nexport type BaseResponseFailure = z.infer<typeof BaseResponseFailureSchema>;\n\n/** Base JSON-RPC notification. */\nexport const BaseNotificationSchema = z.object({\n type: z.literal(\"notification\"),\n method: z.string(),\n params: z.unknown().optional(),\n});\n\nexport type BaseNotification = z.infer<typeof BaseNotificationSchema>;\n\n// ---------------------------------------------------------------------------\n// Combined models (Envelope + Base)\n// ---------------------------------------------------------------------------\n\n/** Full JSON-RPC request with envelope fields. */\nexport const JsonRpcRequestSchema = JsonRpcEnvelopeSchema.extend(\n BaseRequestSchema.shape,\n);\n\nexport type JsonRpcRequest = z.infer<typeof JsonRpcRequestSchema>;\n\n/** Full JSON-RPC success response with envelope fields. */\nexport const JsonRpcResponseSuccessSchema = JsonRpcEnvelopeSchema.extend(\n BaseResponseSuccessSchema.shape,\n);\n\nexport type JsonRpcResponseSuccess = z.infer<\n typeof JsonRpcResponseSuccessSchema\n>;\n\n/** Full JSON-RPC failure response with envelope fields. */\nexport const JsonRpcResponseFailureSchema = JsonRpcEnvelopeSchema.extend(\n BaseResponseFailureSchema.shape,\n);\n\nexport type JsonRpcResponseFailure = z.infer<\n typeof JsonRpcResponseFailureSchema\n>;\n\n/** Full JSON-RPC notification with envelope fields. */\nexport const JsonRpcNotificationSchema = JsonRpcEnvelopeSchema.extend(\n BaseNotificationSchema.shape,\n);\n\nexport type JsonRpcNotification = z.infer<typeof JsonRpcNotificationSchema>;\n\n/** JSON-RPC response (success or failure). */\nexport const JsonRpcResponseSchema = z.union([\n JsonRpcResponseFailureSchema,\n JsonRpcResponseSuccessSchema,\n]);\n\nexport type JsonRpcResponse = z.infer<typeof JsonRpcResponseSchema>;\n\n/** Discriminated union for initial message type routing. */\nexport const JsonRpcMessageSchema = z.discriminatedUnion(\"type\", [\n JsonRpcRequestSchema,\n JsonRpcEnvelopeSchema.extend({\n type: z.literal(\"response\"),\n id: z.string().nullable(),\n result: z.unknown().optional(),\n error: JsonRpcErrorSchema.optional(),\n }),\n JsonRpcNotificationSchema,\n]);\n\nexport type JsonRpcMessage = z.infer<typeof JsonRpcMessageSchema>;\n","/**\n * Message content block schemas for the Factory Droid protocol.\n *\n * Ported from: packages/common/src/sessionV2/messages/schemas.ts\n */\n\nimport { z } from \"zod\";\n\n// ---------------------------------------------------------------------------\n// Content block schemas\n// ---------------------------------------------------------------------------\n\n/** Text content block. */\nexport const TextBlockSchema = z\n .object({\n type: z.literal(\"text\"),\n text: z.string(),\n id: z.string().optional(),\n })\n .passthrough();\n\nexport type TextBlock = z.infer<typeof TextBlockSchema>;\n\n/** Base64-encoded image source. */\nexport const Base64ImageSourceSchema = z\n .object({\n type: z.literal(\"base64\"),\n data: z.string(),\n mediaType: z.enum([\"image/jpeg\", \"image/png\", \"image/gif\", \"image/webp\"]),\n })\n .passthrough();\n\nexport type Base64ImageSource = z.infer<typeof Base64ImageSourceSchema>;\n\n/** Image content block. */\nexport const ImageBlockSchema = z\n .object({\n type: z.literal(\"image\"),\n source: Base64ImageSourceSchema,\n id: z.string().optional(),\n })\n .passthrough();\n\nexport type ImageBlock = z.infer<typeof ImageBlockSchema>;\n\n/** Thinking content block. */\nexport const ThinkingBlockSchema = z\n .object({\n type: z.literal(\"thinking\"),\n signature: z.string(),\n thinking: z.string(),\n id: z.string().optional(),\n signatureProvider: z.string().optional(),\n })\n .passthrough();\n\nexport type ThinkingBlock = z.infer<typeof ThinkingBlockSchema>;\n\n/** Redacted thinking content block. */\nexport const RedactedThinkingBlockSchema = z\n .object({\n type: z.literal(\"redacted_thinking\"),\n data: z.string(),\n id: z.string().optional(),\n })\n .passthrough();\n\nexport type RedactedThinkingBlock = z.infer<typeof RedactedThinkingBlockSchema>;\n\n/** Tool use content block. */\nexport const ToolUseBlockSchema = z\n .object({\n type: z.literal(\"tool_use\"),\n id: z.string(),\n input: z.record(z.unknown()),\n name: z.string(),\n thoughtSignature: z.string().optional(),\n })\n .passthrough();\n\nexport type ToolUseBlock = z.infer<typeof ToolUseBlockSchema>;\n\n/** Tool result content block. */\nexport const ToolResultBlockSchema = z\n .object({\n type: z.literal(\"tool_result\"),\n toolUseId: z.string(),\n content: z.union([z.string(), z.array(z.unknown())]).optional(),\n isError: z.boolean().optional(),\n id: z.string().optional(),\n })\n .passthrough();\n\nexport type ToolResultBlock = z.infer<typeof ToolResultBlockSchema>;\n\n/** Document content block. */\nexport const DocumentBlockSchema = z\n .object({\n type: z.literal(\"document\"),\n source: z.record(z.unknown()),\n id: z.string().optional(),\n })\n .passthrough();\n\nexport type DocumentBlock = z.infer<typeof DocumentBlockSchema>;\n\n/** Discriminated union over all content block types. */\nexport const ContentBlockSchema = z.discriminatedUnion(\"type\", [\n TextBlockSchema,\n ImageBlockSchema,\n ThinkingBlockSchema,\n RedactedThinkingBlockSchema,\n ToolUseBlockSchema,\n ToolResultBlockSchema,\n DocumentBlockSchema,\n]);\n\nexport type ContentBlock = z.infer<typeof ContentBlockSchema>;\n\n// ---------------------------------------------------------------------------\n// FactoryDroidMessage\n// ---------------------------------------------------------------------------\n\n/** Factory Droid message schema (used in CreateMessageNotification and session data). */\nexport const FactoryDroidMessageSchema = z\n .object({\n id: z.string(),\n role: z.enum([\"user\", \"assistant\", \"tool\", \"system\"]),\n content: z.array(ContentBlockSchema),\n createdAt: z.number(),\n updatedAt: z.number(),\n parentId: z.string().optional(),\n visibility: z.enum([\"both\", \"llm_only\", \"user_only\"]).optional(),\n isError: z.boolean().optional(),\n })\n .passthrough();\n\nexport type FactoryDroidMessage = z.infer<typeof FactoryDroidMessageSchema>;\n\n/** Document source for user messages (PDF or plain text). */\nexport const DocumentSourceSchema = z\n .object({\n type: z.string(),\n mediaType: z.string(),\n data: z.string(),\n name: z.string().optional(),\n mime: z.string().optional(),\n })\n .strict();\n\nexport type DocumentSource = z.infer<typeof DocumentSourceSchema>;\n","/**\n * MCP entity schemas for the Factory Droid protocol.\n *\n * Ported from: packages/common/src/droid/schemas/mcp.ts\n */\n\nimport { z } from \"zod\";\n\nimport { McpServerStatus, McpServerType, SettingsLevel, ToolConfirmationOutcome } from \"./enums.js\";\n\n// ---------------------------------------------------------------------------\n// MCP server config field schemas\n// ---------------------------------------------------------------------------\n\n/** Stdio MCP server configuration fields. */\nexport const McpStdioServerConfigFieldsSchema = z.object({\n command: z.string().optional(),\n args: z.array(z.string()).optional(),\n});\n\nexport type McpStdioServerConfigFields = z.infer<\n typeof McpStdioServerConfigFieldsSchema\n>;\n\n/** HTTP MCP server configuration fields. */\nexport const McpHttpServerConfigFieldsSchema = z.object({\n url: z.string().optional(),\n});\n\nexport type McpHttpServerConfigFields = z.infer<\n typeof McpHttpServerConfigFieldsSchema\n>;\n\n/** SSE MCP server configuration fields. */\nexport const McpSseServerConfigFieldsSchema = z.object({\n url: z.string(),\n headers: z.record(z.string()).optional(),\n});\n\nexport type McpSseServerConfigFields = z.infer<\n typeof McpSseServerConfigFieldsSchema\n>;\n\n// ---------------------------------------------------------------------------\n// MCP server status and summary\n// ---------------------------------------------------------------------------\n\n/** MCP server status information. */\nexport const McpServerStatusInfoSchema = z\n .object({\n name: z.string(),\n status: z.nativeEnum(McpServerStatus),\n source: z.nativeEnum(SettingsLevel),\n isManaged: z.boolean(),\n error: z.string().optional(),\n toolCount: z.number().optional(),\n serverType: z.nativeEnum(McpServerType).optional(),\n hasAuthTokens: z.boolean().optional(),\n })\n .passthrough();\n\nexport type McpServerStatusInfo = z.infer<typeof McpServerStatusInfoSchema>;\n\n/** MCP status summary. */\nexport const McpStatusSummarySchema = z\n .object({\n total: z.number(),\n connected: z.number(),\n connecting: z.number(),\n failed: z.number(),\n disabled: z.number().optional(),\n })\n .passthrough();\n\nexport type McpStatusSummary = z.infer<typeof McpStatusSummarySchema>;\n\n// ---------------------------------------------------------------------------\n// MCP registry server\n// ---------------------------------------------------------------------------\n\n/** MCP registry server entity. */\nexport const McpRegistryServerSchema = z\n .object({\n name: z.string(),\n description: z.string(),\n type: z.nativeEnum(McpServerType),\n // Stdio config fields\n command: z.string().optional(),\n args: z.array(z.string()).optional(),\n // HTTP config fields\n url: z.string().optional(),\n // Additional metadata\n note: z.string().optional(),\n logoUrl: z.string().optional(),\n })\n .passthrough();\n\nexport type McpRegistryServer = z.infer<typeof McpRegistryServerSchema>;\n\n// ---------------------------------------------------------------------------\n// MCP tool info\n// ---------------------------------------------------------------------------\n\n/** JSON Schema subset for MCP tool input parameters. */\nexport const McpToolInputSchemaSchema = z\n .object({\n type: z.string().optional(),\n properties: z.record(z.unknown()).optional(),\n required: z.array(z.string()).optional(),\n })\n .passthrough();\n\nexport type McpToolInputSchema = z.infer<typeof McpToolInputSchemaSchema>;\n\n/** MCP tool information entity. */\nexport const McpToolInfoSchema = z\n .object({\n serverName: z.string(),\n name: z.string(),\n description: z.string().optional(),\n isEnabled: z.boolean(),\n isReadOnly: z.boolean().optional(),\n inputSchema: McpToolInputSchemaSchema.optional(),\n })\n .passthrough();\n\nexport type McpToolInfo = z.infer<typeof McpToolInfoSchema>;\n\n// ---------------------------------------------------------------------------\n// Tool confirmation list item\n// ---------------------------------------------------------------------------\n\n/** Selectable list item for tool confirmation prompts. */\nexport const ToolConfirmationListItemSchema = z\n .object({\n label: z.string(),\n value: z.nativeEnum(ToolConfirmationOutcome),\n })\n .passthrough();\n\nexport type ToolConfirmationListItem = z.infer<\n typeof ToolConfirmationListItemSchema\n>;\n","/**\n * Mission decomposition schemas for the Factory Droid protocol.\n *\n * Ported from: packages/common/src/droid/schemas/mission-decomposition.ts\n */\n\nimport { z } from \"zod\";\n\nimport {\n DismissalType,\n FeatureStatus,\n FeatureSuccessState,\n IssueSeverity,\n ProgressLogEntryType,\n} from \"./enums.js\";\n\n// ---------------------------------------------------------------------------\n// Feature schema\n// ---------------------------------------------------------------------------\n\n/** Mission feature schema. */\nexport const MissionFeatureSchema = z\n .object({\n id: z.string(),\n description: z.string(),\n status: z.nativeEnum(FeatureStatus),\n skillName: z.string(),\n preconditions: z.array(z.string()),\n expectedBehavior: z.array(z.string()),\n verificationSteps: z.array(z.string()),\n fulfills: z.array(z.string()).optional(),\n milestone: z.string().optional(),\n workerSessionIds: z.array(z.string()).optional(),\n currentWorkerSessionId: z.string().nullable().optional(),\n completedWorkerSessionId: z.string().nullable().optional(),\n })\n .passthrough();\n\nexport type MissionFeature = z.infer<typeof MissionFeatureSchema>;\n\n// ---------------------------------------------------------------------------\n// Handoff-related schemas\n// ---------------------------------------------------------------------------\n\nexport const FeatureSuccessStateSchema = z.nativeEnum(FeatureSuccessState);\n\n/** Discovered issue during feature implementation. */\nexport const DiscoveredIssueSchema = z\n .object({\n severity: z.nativeEnum(IssueSeverity),\n description: z.string(),\n suggestedFix: z.string().optional(),\n })\n .passthrough();\n\nexport type DiscoveredIssue = z.infer<typeof DiscoveredIssueSchema>;\n\n/** A command run during verification. */\nexport const VerificationCommandSchema = z\n .object({\n command: z.string(),\n exitCode: z.number(),\n observation: z.string(),\n })\n .passthrough();\n\nexport type VerificationCommand = z.infer<typeof VerificationCommandSchema>;\n\n/** An interactive check performed during verification. */\nexport const InteractiveCheckSchema = z\n .object({\n action: z.string(),\n observed: z.string(),\n })\n .passthrough();\n\nexport type InteractiveCheck = z.infer<typeof InteractiveCheckSchema>;\n\n/** Verification performed during feature implementation. */\nexport const VerificationSchema = z\n .object({\n commandsRun: z.array(VerificationCommandSchema),\n interactiveChecks: z.array(InteractiveCheckSchema).optional(),\n })\n .passthrough();\n\nexport type Verification = z.infer<typeof VerificationSchema>;\n\n/** A single test case. */\nexport const TestCaseSchema = z\n .object({\n name: z.string(),\n verifies: z.string(),\n })\n .passthrough();\n\nexport type TestCase = z.infer<typeof TestCaseSchema>;\n\n/** A test file with its test cases. */\nexport const TestFileSchema = z\n .object({\n file: z.string(),\n cases: z.array(TestCaseSchema),\n })\n .passthrough();\n\nexport type TestFile = z.infer<typeof TestFileSchema>;\n\n/** Test information for a feature implementation. */\nexport const TestsSchema = z\n .object({\n added: z.array(TestFileSchema),\n updated: z.array(z.string()).optional(),\n coverage: z.string(),\n })\n .passthrough();\n\nexport type Tests = z.infer<typeof TestsSchema>;\n\n/** A deviation from the skill procedure. */\nexport const SkillDeviationSchema = z\n .object({\n step: z.string(),\n whatIDidInstead: z.string(),\n why: z.string(),\n })\n .passthrough();\n\nexport type SkillDeviation = z.infer<typeof SkillDeviationSchema>;\n\n/** Feedback on the skill procedure. */\nexport const SkillFeedbackSchema = z\n .object({\n followedProcedure: z.boolean(),\n deviations: z.array(SkillDeviationSchema),\n suggestedChanges: z.array(z.string()).optional(),\n })\n .passthrough();\n\nexport type SkillFeedback = z.infer<typeof SkillFeedbackSchema>;\n\n/** Worker handoff information. */\nexport const HandoffSchema = z\n .object({\n salientSummary: z.string().optional(),\n whatWasImplemented: z.string(),\n whatWasLeftUndone: z.string(),\n verification: VerificationSchema,\n tests: TestsSchema,\n discoveredIssues: z.array(DiscoveredIssueSchema),\n skillFeedback: SkillFeedbackSchema.optional(),\n })\n .passthrough();\n\nexport type Handoff = z.infer<typeof HandoffSchema>;\n\n/** A record of a dismissed handoff item. */\nexport const DismissalRecordSchema = z\n .object({\n type: z.nativeEnum(DismissalType),\n sourceFeatureId: z.string(),\n summary: z.string(),\n justification: z.string(),\n })\n .passthrough();\n\nexport type DismissalRecord = z.infer<typeof DismissalRecordSchema>;\n\n// ---------------------------------------------------------------------------\n// Progress log entry schemas\n// ---------------------------------------------------------------------------\n\nconst BaseProgressLogEntrySchema = z.object({\n timestamp: z.string(),\n});\n\nexport const MissionAcceptedEntrySchema = BaseProgressLogEntrySchema.extend({\n type: z.literal(ProgressLogEntryType.MissionAccepted),\n title: z.string(),\n}).passthrough();\n\nexport type MissionAcceptedEntry = z.infer<typeof MissionAcceptedEntrySchema>;\n\nexport const MissionPausedEntrySchema = BaseProgressLogEntrySchema.extend({\n type: z.literal(ProgressLogEntryType.MissionPaused),\n}).passthrough();\n\nexport type MissionPausedEntry = z.infer<typeof MissionPausedEntrySchema>;\n\nexport const MissionResumedEntrySchema = BaseProgressLogEntrySchema.extend({\n type: z.literal(ProgressLogEntryType.MissionResumed),\n}).passthrough();\n\nexport type MissionResumedEntry = z.infer<typeof MissionResumedEntrySchema>;\n\nexport const MissionRunStartedEntrySchema = BaseProgressLogEntrySchema.extend({\n type: z.literal(ProgressLogEntryType.MissionRunStarted),\n message: z.string().optional(),\n}).passthrough();\n\nexport type MissionRunStartedEntry = z.infer<\n typeof MissionRunStartedEntrySchema\n>;\n\nexport const WorkerStartedEntrySchema = BaseProgressLogEntrySchema.extend({\n type: z.literal(ProgressLogEntryType.WorkerStarted),\n workerSessionId: z.string(),\n spawnId: z.string(),\n featureId: z.string().optional(),\n}).passthrough();\n\nexport type WorkerStartedEntry = z.infer<typeof WorkerStartedEntrySchema>;\n\nexport const WorkerSelectedFeatureEntrySchema =\n BaseProgressLogEntrySchema.extend({\n type: z.literal(ProgressLogEntryType.WorkerSelectedFeature),\n workerSessionId: z.string(),\n featureId: z.string(),\n }).passthrough();\n\nexport type WorkerSelectedFeatureEntry = z.infer<\n typeof WorkerSelectedFeatureEntrySchema\n>;\n\nexport const WorkerCompletedEntrySchema = BaseProgressLogEntrySchema.extend({\n type: z.literal(ProgressLogEntryType.WorkerCompleted),\n workerSessionId: z.string(),\n featureId: z.string(),\n successState: FeatureSuccessStateSchema,\n returnToOrchestrator: z.boolean(),\n commitId: z.string().optional(),\n exitCode: z.number(),\n validatorsPassed: z.boolean().optional(),\n handoff: HandoffSchema.optional(),\n}).passthrough();\n\nexport type WorkerCompletedEntry = z.infer<typeof WorkerCompletedEntrySchema>;\n\nexport const WorkerFailedEntrySchema = BaseProgressLogEntrySchema.extend({\n type: z.literal(ProgressLogEntryType.WorkerFailed),\n workerSessionId: z.string().optional(),\n spawnId: z.string(),\n exitCode: z.number().optional(),\n reason: z.string(),\n}).passthrough();\n\nexport type WorkerFailedEntry = z.infer<typeof WorkerFailedEntrySchema>;\n\nexport const WorkerPausedEntrySchema = BaseProgressLogEntrySchema.extend({\n type: z.literal(ProgressLogEntryType.WorkerPaused),\n workerSessionId: z.string(),\n featureId: z.string().optional(),\n}).passthrough();\n\nexport type WorkerPausedEntry = z.infer<typeof WorkerPausedEntrySchema>;\n\nexport const HandoffItemsDismissedEntrySchema =\n BaseProgressLogEntrySchema.extend({\n type: z.literal(ProgressLogEntryType.HandoffItemsDismissed),\n dismissals: z.array(DismissalRecordSchema).optional(),\n }).passthrough();\n\nexport type HandoffItemsDismissedEntry = z.infer<\n typeof HandoffItemsDismissedEntrySchema\n>;\n\nexport const MilestoneValidationTriggeredEntrySchema =\n BaseProgressLogEntrySchema.extend({\n type: z.literal(ProgressLogEntryType.MilestoneValidationTriggered),\n milestone: z.string(),\n featureId: z.string(),\n }).passthrough();\n\nexport type MilestoneValidationTriggeredEntry = z.infer<\n typeof MilestoneValidationTriggeredEntrySchema\n>;\n\n/** Discriminated union over all 11 progress log entry types. */\nexport const ProgressLogEntrySchema = z.discriminatedUnion(\"type\", [\n MissionAcceptedEntrySchema,\n MissionPausedEntrySchema,\n MissionResumedEntrySchema,\n MissionRunStartedEntrySchema,\n WorkerStartedEntrySchema,\n WorkerSelectedFeatureEntrySchema,\n WorkerCompletedEntrySchema,\n WorkerFailedEntrySchema,\n WorkerPausedEntrySchema,\n HandoffItemsDismissedEntrySchema,\n MilestoneValidationTriggeredEntrySchema,\n]);\n\nexport type ProgressLogEntry = z.infer<typeof ProgressLogEntrySchema>;\n","/**\n * Client→server request/response schemas for the Factory Droid protocol.\n *\n * All 19 client→server RPC method request/response pairs.\n *\n * Ported from: packages/common/src/droid/schemas/client.ts\n */\n\nimport { z } from \"zod\";\n\nimport {\n AutonomyLevel,\n AutonomyMode,\n DecompSessionType,\n DroidInteractionMode,\n DroidServerMethod,\n McpServerType,\n MissionState,\n ModelProvider,\n ReasoningEffort,\n SettingsLevel,\n SkillLocation,\n} from \"./enums.js\";\nimport {\n McpRegistryServerSchema,\n McpServerStatusInfoSchema,\n McpStatusSummarySchema,\n McpToolInfoSchema,\n} from \"./mcp.js\";\nimport { Base64ImageSourceSchema, DocumentSourceSchema } from \"./messages.js\";\nimport { MissionFeatureSchema, ProgressLogEntrySchema } from \"./mission.js\";\nimport {\n type JsonRpcResponseFailure,\n JsonRpcRequestSchema,\n JsonRpcResponseFailureSchema,\n JsonRpcResponseSuccessSchema,\n} from \"./shared.js\";\n\n// ---------------------------------------------------------------------------\n// Supporting types\n// ---------------------------------------------------------------------------\n\n/** Session tag metadata. */\nexport const SessionTagSchema = z\n .object({\n name: z.string(),\n metadata: z.record(z.string()).optional(),\n })\n .strict();\n\nexport type SessionTag = z.infer<typeof SessionTagSchema>;\n\n/** Session source information. */\nexport const SessionSourceSchema = z\n .object({\n platform: z.string(),\n })\n .passthrough();\n\nexport type SessionSource = z.infer<typeof SessionSourceSchema>;\n\n/** Stdio MCP server configuration for initialization. */\nexport const StdioMcpConfigSchema = z\n .object({\n name: z.string(),\n command: z.string(),\n args: z.array(z.string()).default([]),\n env: z.record(z.string()).optional().default({}),\n })\n .strict();\n\nexport type StdioMcpConfig = z.infer<typeof StdioMcpConfigSchema>;\n\n/** HTTP header for MCP server configuration. */\nexport const HttpHeaderSchema = z\n .object({\n name: z.string(),\n value: z.string(),\n })\n .strict();\n\nexport type HttpHeader = z.infer<typeof HttpHeaderSchema>;\n\n/** HTTP MCP server configuration for initialization. */\nexport const HttpMcpConfigSchema = z\n .object({\n type: z.literal(\"http\"),\n name: z.string(),\n url: z.string().url(),\n headers: HttpHeaderSchema.array().default([]),\n })\n .strict();\n\nexport type HttpMcpConfig = z.infer<typeof HttpMcpConfigSchema>;\n\n/** SSE MCP server configuration for initialization. */\nexport const SseMcpConfigSchema = z\n .object({\n type: z.literal(\"sse\"),\n name: z.string(),\n url: z.string().url(),\n headers: HttpHeaderSchema.array().default([]),\n })\n .strict();\n\nexport type SseMcpConfig = z.infer<typeof SseMcpConfigSchema>;\n\n/** Union of MCP server configs. */\nexport const McpServerConfigSchema = z.union([\n StdioMcpConfigSchema,\n HttpMcpConfigSchema,\n SseMcpConfigSchema,\n]);\n\nexport type McpServerConfig = z.infer<typeof McpServerConfigSchema>;\n\n/** Session settings returned in init/load results. */\nexport const SessionSettingsSchema = z\n .object({\n modelId: z.string(),\n reasoningEffort: z.nativeEnum(ReasoningEffort),\n autonomyMode: z.nativeEnum(AutonomyMode).optional(),\n interactionMode: z.nativeEnum(DroidInteractionMode).optional().catch(undefined),\n autonomyLevel: z.nativeEnum(AutonomyLevel).optional().catch(undefined),\n specModeModelId: z.string().optional(),\n specModeReasoningEffort: z.nativeEnum(ReasoningEffort).optional(),\n })\n .passthrough();\n\nexport type SessionSettings = z.infer<typeof SessionSettingsSchema>;\n\n/** Git repository information. */\nexport const GitRepoInfoSchema = z\n .object({\n owner: z.string().optional(),\n repoName: z.string(),\n })\n .passthrough();\n\nexport type GitRepoInfo = z.infer<typeof GitRepoInfoSchema>;\n\n/** Available model configuration returned in session init/load responses. */\nexport const AvailableModelConfigSchema = z\n .object({\n id: z.string(),\n modelId: z.string().optional(),\n displayName: z.string(),\n shortDisplayName: z.string(),\n modelProvider: z.nativeEnum(ModelProvider),\n supportedReasoningEfforts: z.array(z.nativeEnum(ReasoningEffort)),\n defaultReasoningEffort: z.nativeEnum(ReasoningEffort),\n isCustom: z.boolean().default(false),\n noImageSupport: z.boolean().optional(),\n supportsPDFs: z.boolean().optional(),\n tier: z.string().optional(),\n tokenMultiplier: z.number().optional(),\n promoLabel: z.string().optional(),\n featureFlag: z.record(z.unknown()).optional(),\n usesUSBasedInference: z.boolean().optional(),\n })\n .passthrough();\n\nexport type AvailableModelConfig = z.infer<typeof AvailableModelConfigSchema>;\n\n/** Token usage information for a session. */\nexport const TokenUsageSchema = z\n .object({\n inputTokens: z.number(),\n outputTokens: z.number(),\n cacheCreationTokens: z.number(),\n cacheReadTokens: z.number(),\n thinkingTokens: z.number(),\n })\n .passthrough();\n\nexport type TokenUsage = z.infer<typeof TokenUsageSchema>;\n\n/** Worker state information for mission snapshots. */\nexport const WorkerStateInfoSchema = z\n .object({\n startedAt: z.string(),\n completedAt: z.string().optional(),\n exitCode: z.number().optional(),\n })\n .passthrough();\n\nexport type WorkerStateInfo = z.infer<typeof WorkerStateInfoSchema>;\n\n/** Skill resource file in a skill folder. */\nexport const SkillResourceSchema = z\n .object({\n name: z.string(),\n path: z.string(),\n type: z.enum([\"reference\", \"asset\"]),\n })\n .passthrough();\n\nexport type SkillResource = z.infer<typeof SkillResourceSchema>;\n\n/** Skill information returned by list_skills. */\nexport const SkillInfoSchema = z\n .object({\n name: z.string(),\n description: z.string().optional(),\n location: z.nativeEnum(SkillLocation),\n filePath: z.string(),\n enabled: z.boolean().optional(),\n userInvocable: z.boolean().optional(),\n version: z.string().optional(),\n content: z.string().optional(),\n resources: z.array(SkillResourceSchema).optional(),\n })\n .passthrough();\n\nexport type SkillInfo = z.infer<typeof SkillInfoSchema>;\n\n// ---------------------------------------------------------------------------\n// Request params schemas\n// ---------------------------------------------------------------------------\n\n/** Parameters for droid.initialize_session request. */\nexport const InitializeSessionRequestParamsSchema = z\n .object({\n machineId: z.string(),\n cwd: z.string(),\n workspaceId: z.string().optional(),\n sessionId: z.string().optional(),\n mcpServers: z.array(McpServerConfigSchema).optional(),\n autonomyMode: z.nativeEnum(AutonomyMode).optional(),\n interactionMode: z.nativeEnum(DroidInteractionMode).optional().catch(undefined),\n autonomyLevel: z.nativeEnum(AutonomyLevel).optional().catch(undefined),\n modelId: z.string().optional(),\n reasoningEffort: z.nativeEnum(ReasoningEffort).optional(),\n specModeModelId: z.string().optional(),\n specModeReasoningEffort: z.nativeEnum(ReasoningEffort).optional(),\n decompSessionType: z.nativeEnum(DecompSessionType).optional(),\n decompMissionId: z.string().optional(),\n skipPermissionsUnsafe: z.boolean().optional(),\n enabledToolIds: z.array(z.string()).optional(),\n sessionLocation: z.string().optional(),\n sessionSource: SessionSourceSchema.optional(),\n tags: z.array(SessionTagSchema).optional(),\n mcpOAuthCallbackUri: z.string().optional(),\n })\n .strict();\n\nexport type InitializeSessionRequestParams = z.infer<\n typeof InitializeSessionRequestParamsSchema\n>;\n\n/** Parameters for droid.load_session request. */\nexport const LoadSessionRequestParamsSchema = z\n .object({\n sessionId: z.string(),\n mcpServers: z.array(McpServerConfigSchema).optional(),\n mcpOAuthCallbackUri: z.string().optional(),\n })\n .strict();\n\nexport type LoadSessionRequestParams = z.infer<\n typeof LoadSessionRequestParamsSchema\n>;\n\n/** Parameters for droid.add_user_message request. */\nexport const AddUserMessageRequestParamsSchema = z\n .object({\n messageId: z.string().optional(),\n text: z.string(),\n images: z.array(Base64ImageSourceSchema).optional(),\n files: z.array(DocumentSourceSchema).optional(),\n })\n .strict();\n\nexport type AddUserMessageRequestParams = z.infer<\n typeof AddUserMessageRequestParamsSchema\n>;\n\n/** Parameters for droid.interrupt_session request (empty). */\nexport const InterruptSessionRequestParamsSchema = z.object({}).strict();\n\nexport type InterruptSessionRequestParams = z.infer<\n typeof InterruptSessionRequestParamsSchema\n>;\n\n/** Parameters for droid.kill_worker_session request. */\nexport const KillWorkerSessionRequestParamsSchema = z\n .object({\n workerSessionId: z.string(),\n })\n .strict();\n\nexport type KillWorkerSessionRequestParams = z.infer<\n typeof KillWorkerSessionRequestParamsSchema\n>;\n\n/** Parameters for droid.update_session_settings request. */\nexport const UpdateSessionSettingsRequestParamsSchema = z\n .object({\n modelId: z.string().optional(),\n reasoningEffort: z.nativeEnum(ReasoningEffort).optional(),\n autonomyMode: z.nativeEnum(AutonomyMode).optional(),\n interactionMode: z.nativeEnum(DroidInteractionMode).optional().catch(undefined),\n autonomyLevel: z.nativeEnum(AutonomyLevel).optional().catch(undefined),\n specModeModelId: z.string().nullable().optional(),\n specModeReasoningEffort: z.nativeEnum(ReasoningEffort).nullable().optional(),\n })\n .strict();\n\nexport type UpdateSessionSettingsRequestParams = z.infer<\n typeof UpdateSessionSettingsRequestParamsSchema\n>;\n\n/** Parameters for droid.toggle_mcp_server request. */\nexport const ToggleMcpServerRequestParamsSchema = z\n .object({\n serverName: z.string(),\n enabled: z.boolean(),\n settingsLevel: z.literal(SettingsLevel.User),\n })\n .strict();\n\nexport type ToggleMcpServerRequestParams = z.infer<\n typeof ToggleMcpServerRequestParamsSchema\n>;\n\n/** Parameters for droid.authenticate_mcp_server request. */\nexport const AuthenticateMcpServerRequestParamsSchema = z\n .object({\n serverName: z.string(),\n })\n .strict();\n\nexport type AuthenticateMcpServerRequestParams = z.infer<\n typeof AuthenticateMcpServerRequestParamsSchema\n>;\n\n/** Parameters for droid.cancel_mcp_auth request. */\nexport const CancelMcpAuthRequestParamsSchema = z\n .object({\n serverName: z.string(),\n })\n .strict();\n\nexport type CancelMcpAuthRequestParams = z.infer<\n typeof CancelMcpAuthRequestParamsSchema\n>;\n\n/** Parameters for droid.clear_mcp_auth request. */\nexport const ClearMcpAuthRequestParamsSchema = z\n .object({\n serverName: z.string(),\n })\n .strict();\n\nexport type ClearMcpAuthRequestParams = z.infer<\n typeof ClearMcpAuthRequestParamsSchema\n>;\n\n/** Parameters for droid.submit_mcp_auth_code request. */\nexport const SubmitMcpAuthCodeRequestParamsSchema = z\n .object({\n serverName: z.string(),\n code: z.string(),\n state: z.string(),\n })\n .strict();\n\nexport type SubmitMcpAuthCodeRequestParams = z.infer<\n typeof SubmitMcpAuthCodeRequestParamsSchema\n>;\n\n/** Parameters for droid.add_mcp_server request. */\nexport const AddMcpServerRequestParamsSchema = z\n .object({\n name: z.string(),\n type: z.nativeEnum(McpServerType),\n url: z.string().optional(),\n headers: z.record(z.string()).optional(),\n command: z.string().optional(),\n args: z.array(z.string()).optional(),\n env: z.record(z.string()).optional(),\n })\n .strict();\n\nexport type AddMcpServerRequestParams = z.infer<\n typeof AddMcpServerRequestParamsSchema\n>;\n\n/** Parameters for droid.remove_mcp_server request. */\nexport const RemoveMcpServerRequestParamsSchema = z\n .object({\n serverName: z.string(),\n settingsLevel: z.literal(SettingsLevel.User),\n })\n .strict();\n\nexport type RemoveMcpServerRequestParams = z.infer<\n typeof RemoveMcpServerRequestParamsSchema\n>;\n\n/** Parameters for droid.list_mcp_registry request (empty). */\nexport const ListMcpRegistryRequestParamsSchema = z.object({}).strict();\n\nexport type ListMcpRegistryRequestParams = z.infer<\n typeof ListMcpRegistryRequestParamsSchema\n>;\n\n/** Parameters for droid.list_mcp_tools request (empty). */\nexport const ListMcpToolsRequestParamsSchema = z.object({}).strict();\n\nexport type ListMcpToolsRequestParams = z.infer<\n typeof ListMcpToolsRequestParamsSchema\n>;\n\n/** Parameters for droid.list_mcp_servers request (empty). */\nexport const ListMcpServersRequestParamsSchema = z.object({}).strict();\n\nexport type ListMcpServersRequestParams = z.infer<\n typeof ListMcpServersRequestParamsSchema\n>;\n\n/** Parameters for droid.toggle_mcp_tool request. */\nexport const ToggleMcpToolRequestParamsSchema = z\n .object({\n serverName: z.string(),\n toolName: z.string(),\n enabled: z.boolean(),\n })\n .strict();\n\nexport type ToggleMcpToolRequestParams = z.infer<\n typeof ToggleMcpToolRequestParamsSchema\n>;\n\n/** Parameters for droid.list_skills request (empty). */\nexport const ListSkillsRequestParamsSchema = z.object({}).strict();\n\nexport type ListSkillsRequestParams = z.infer<\n typeof ListSkillsRequestParamsSchema\n>;\n\n/** Parameters for droid.submit_bug_report request. */\nexport const SubmitBugReportRequestParamsSchema = z\n .object({\n userComment: z.string(),\n clientLogs: z.string().optional(),\n })\n .strict();\n\nexport type SubmitBugReportRequestParams = z.infer<\n typeof SubmitBugReportRequestParamsSchema\n>;\n\n// ---------------------------------------------------------------------------\n// Full request schemas (JsonRpcRequest + method literal + typed params)\n// ---------------------------------------------------------------------------\n\nexport const InitializeSessionRequestSchema = JsonRpcRequestSchema.extend({\n method: z.literal(DroidServerMethod.INITIALIZE_SESSION),\n params: InitializeSessionRequestParamsSchema,\n});\n\nexport type InitializeSessionRequest = z.infer<typeof InitializeSessionRequestSchema>;\n\nexport const LoadSessionRequestSchema = JsonRpcRequestSchema.extend({\n method: z.literal(DroidServerMethod.LOAD_SESSION),\n params: LoadSessionRequestParamsSchema,\n});\n\nexport type LoadSessionRequest = z.infer<typeof LoadSessionRequestSchema>;\n\nexport const AddUserMessageRequestSchema = JsonRpcRequestSchema.extend({\n method: z.literal(DroidServerMethod.ADD_USER_MESSAGE),\n params: AddUserMessageRequestParamsSchema,\n});\n\nexport type AddUserMessageRequest = z.infer<typeof AddUserMessageRequestSchema>;\n\nexport const InterruptSessionRequestSchema = JsonRpcRequestSchema.extend({\n method: z.literal(DroidServerMethod.INTERRUPT_SESSION),\n params: InterruptSessionRequestParamsSchema,\n});\n\nexport type InterruptSessionRequest = z.infer<typeof InterruptSessionRequestSchema>;\n\nexport const KillWorkerSessionRequestSchema = JsonRpcRequestSchema.extend({\n method: z.literal(DroidServerMethod.KILL_WORKER_SESSION),\n params: KillWorkerSessionRequestParamsSchema,\n});\n\nexport type KillWorkerSessionRequest = z.infer<typeof KillWorkerSessionRequestSchema>;\n\nexport const UpdateSessionSettingsRequestSchema = JsonRpcRequestSchema.extend({\n method: z.literal(DroidServerMethod.UPDATE_SESSION_SETTINGS),\n params: UpdateSessionSettingsRequestParamsSchema,\n});\n\nexport type UpdateSessionSettingsRequest = z.infer<typeof UpdateSessionSettingsRequestSchema>;\n\nexport const ToggleMcpServerRequestSchema = JsonRpcRequestSchema.extend({\n method: z.literal(DroidServerMethod.TOGGLE_MCP_SERVER),\n params: ToggleMcpServerRequestParamsSchema,\n});\n\nexport type ToggleMcpServerRequest = z.infer<typeof ToggleMcpServerRequestSchema>;\n\nexport const AuthenticateMcpServerRequestSchema = JsonRpcRequestSchema.extend({\n method: z.literal(DroidServerMethod.AUTHENTICATE_MCP_SERVER),\n params: AuthenticateMcpServerRequestParamsSchema,\n});\n\nexport type AuthenticateMcpServerRequest = z.infer<typeof AuthenticateMcpServerRequestSchema>;\n\nexport const CancelMcpAuthRequestSchema = JsonRpcRequestSchema.extend({\n method: z.literal(DroidServerMethod.CANCEL_MCP_AUTH),\n params: CancelMcpAuthRequestParamsSchema,\n});\n\nexport type CancelMcpAuthRequest = z.infer<typeof CancelMcpAuthRequestSchema>;\n\nexport const ClearMcpAuthRequestSchema = JsonRpcRequestSchema.extend({\n method: z.literal(DroidServerMethod.CLEAR_MCP_AUTH),\n params: ClearMcpAuthRequestParamsSchema,\n});\n\nexport type ClearMcpAuthRequest = z.infer<typeof ClearMcpAuthRequestSchema>;\n\nexport const SubmitMcpAuthCodeRequestSchema = JsonRpcRequestSchema.extend({\n method: z.literal(DroidServerMethod.SUBMIT_MCP_AUTH_CODE),\n params: SubmitMcpAuthCodeRequestParamsSchema,\n});\n\nexport type SubmitMcpAuthCodeRequest = z.infer<typeof SubmitMcpAuthCodeRequestSchema>;\n\nexport const AddMcpServerRequestSchema = JsonRpcRequestSchema.extend({\n method: z.literal(DroidServerMethod.ADD_MCP_SERVER),\n params: AddMcpServerRequestParamsSchema,\n});\n\nexport type AddMcpServerRequest = z.infer<typeof AddMcpServerRequestSchema>;\n\nexport const RemoveMcpServerRequestSchema = JsonRpcRequestSchema.extend({\n method: z.literal(DroidServerMethod.REMOVE_MCP_SERVER),\n params: RemoveMcpServerRequestParamsSchema,\n});\n\nexport type RemoveMcpServerRequest = z.infer<typeof RemoveMcpServerRequestSchema>;\n\nexport const ListMcpRegistryRequestSchema = JsonRpcRequestSchema.extend({\n method: z.literal(DroidServerMethod.LIST_MCP_REGISTRY),\n params: ListMcpRegistryRequestParamsSchema,\n});\n\nexport type ListMcpRegistryRequest = z.infer<typeof ListMcpRegistryRequestSchema>;\n\nexport const ListMcpToolsRequestSchema = JsonRpcRequestSchema.extend({\n method: z.literal(DroidServerMethod.LIST_MCP_TOOLS),\n params: ListMcpToolsRequestParamsSchema,\n});\n\nexport type ListMcpToolsRequest = z.infer<typeof ListMcpToolsRequestSchema>;\n\nexport const ListMcpServersRequestSchema = JsonRpcRequestSchema.extend({\n method: z.literal(DroidServerMethod.LIST_MCP_SERVERS),\n params: ListMcpServersRequestParamsSchema,\n});\n\nexport type ListMcpServersRequest = z.infer<typeof ListMcpServersRequestSchema>;\n\nexport const ToggleMcpToolRequestSchema = JsonRpcRequestSchema.extend({\n method: z.literal(DroidServerMethod.TOGGLE_MCP_TOOL),\n params: ToggleMcpToolRequestParamsSchema,\n});\n\nexport type ToggleMcpToolRequest = z.infer<typeof ToggleMcpToolRequestSchema>;\n\nexport const ListSkillsRequestSchema = JsonRpcRequestSchema.extend({\n method: z.literal(DroidServerMethod.LIST_SKILLS),\n params: ListSkillsRequestParamsSchema,\n});\n\nexport type ListSkillsRequest = z.infer<typeof ListSkillsRequestSchema>;\n\nexport const SubmitBugReportRequestSchema = JsonRpcRequestSchema.extend({\n method: z.literal(DroidServerMethod.SUBMIT_BUG_REPORT),\n params: SubmitBugReportRequestParamsSchema,\n});\n\nexport type SubmitBugReportRequest = z.infer<typeof SubmitBugReportRequestSchema>;\n\n/** Discriminated union over all 19 client→server request types. */\nexport const ClientRequestSchema = z.discriminatedUnion(\"method\", [\n InitializeSessionRequestSchema,\n LoadSessionRequestSchema,\n AddUserMessageRequestSchema,\n InterruptSessionRequestSchema,\n KillWorkerSessionRequestSchema,\n UpdateSessionSettingsRequestSchema,\n ToggleMcpServerRequestSchema,\n AuthenticateMcpServerRequestSchema,\n CancelMcpAuthRequestSchema,\n ClearMcpAuthRequestSchema,\n SubmitMcpAuthCodeRequestSchema,\n AddMcpServerRequestSchema,\n RemoveMcpServerRequestSchema,\n ListMcpRegistryRequestSchema,\n ListMcpToolsRequestSchema,\n ListMcpServersRequestSchema,\n ToggleMcpToolRequestSchema,\n ListSkillsRequestSchema,\n SubmitBugReportRequestSchema,\n]);\n\nexport type ClientRequest = z.infer<typeof ClientRequestSchema>;\n\n// ---------------------------------------------------------------------------\n// Result schemas (all use passthrough for forward-compatibility)\n// ---------------------------------------------------------------------------\n\n/** Mission state snapshot (for orchestrator sessions). */\nexport const MissionSnapshotSchema = z\n .object({\n state: z.nativeEnum(MissionState),\n features: z.array(MissionFeatureSchema),\n progressLog: z.array(ProgressLogEntrySchema),\n workerSessionIds: z.array(z.string()),\n workerStates: z.record(WorkerStateInfoSchema).optional(),\n tokenUsage: TokenUsageSchema.optional(),\n tokenUsageBySessionId: z.record(TokenUsageSchema).optional(),\n })\n .passthrough();\n\nexport type MissionSnapshot = z.infer<typeof MissionSnapshotSchema>;\n\n/** Result for droid.initialize_session response. */\nexport const InitializeSessionResultSchema = z\n .object({\n sessionId: z.string(),\n session: z.record(z.unknown()),\n mcpServers: z.array(McpServerConfigSchema).optional(),\n settings: SessionSettingsSchema,\n gitRepo: GitRepoInfoSchema.optional(),\n availableModels: z.array(AvailableModelConfigSchema).optional(),\n })\n .passthrough();\n\nexport type InitializeSessionResult = z.infer<\n typeof InitializeSessionResultSchema\n>;\n\n/** Result for droid.load_session response. */\nexport const LoadSessionResultSchema = z\n .object({\n session: z.record(z.unknown()),\n mcpServers: z.array(McpServerConfigSchema).optional(),\n pendingPermissions: z.array(z.record(z.unknown())).optional(),\n pendingAskUserRequests: z.array(z.record(z.unknown())).optional(),\n settings: SessionSettingsSchema,\n isAgentLoopInProgress: z.boolean().optional(),\n queuedMessages: z.array(z.record(z.unknown())).optional(),\n gitRepo: GitRepoInfoSchema.optional(),\n cwd: z.string().optional(),\n callingSessionId: z.string().optional(),\n callingToolUseId: z.string().optional(),\n availableModels: z.array(AvailableModelConfigSchema).optional(),\n tokenUsage: TokenUsageSchema.optional(),\n mission: MissionSnapshotSchema.optional(),\n decompSessionType: z.nativeEnum(DecompSessionType).optional(),\n })\n .passthrough();\n\nexport type LoadSessionResult = z.infer<typeof LoadSessionResultSchema>;\n\n/** Result for droid.add_user_message response (empty). */\nexport const AddUserMessageResultSchema = z.object({}).passthrough();\n\nexport type AddUserMessageResult = z.infer<typeof AddUserMessageResultSchema>;\n\n/** Result for droid.interrupt_session response (empty). */\nexport const InterruptSessionResultSchema = z.object({}).passthrough();\n\nexport type InterruptSessionResult = z.infer<\n typeof InterruptSessionResultSchema\n>;\n\n/** Result for droid.kill_worker_session response (empty). */\nexport const KillWorkerSessionResultSchema = z.object({}).passthrough();\n\nexport type KillWorkerSessionResult = z.infer<\n typeof KillWorkerSessionResultSchema\n>;\n\n/** Result for droid.update_session_settings response (empty). */\nexport const UpdateSessionSettingsResultSchema = z.object({}).passthrough();\n\nexport type UpdateSessionSettingsResult = z.infer<\n typeof UpdateSessionSettingsResultSchema\n>;\n\n/** Result for droid.toggle_mcp_server response. */\nexport const ToggleMcpServerResultSchema = z\n .object({ success: z.boolean() })\n .passthrough();\n\nexport type ToggleMcpServerResult = z.infer<typeof ToggleMcpServerResultSchema>;\n\n/** Result for droid.authenticate_mcp_server response. */\nexport const AuthenticateMcpServerResultSchema = z\n .object({ success: z.boolean() })\n .passthrough();\n\nexport type AuthenticateMcpServerResult = z.infer<\n typeof AuthenticateMcpServerResultSchema\n>;\n\n/** Result for droid.cancel_mcp_auth response. */\nexport const CancelMcpAuthResultSchema = z\n .object({ success: z.boolean() })\n .passthrough();\n\nexport type CancelMcpAuthResult = z.infer<typeof CancelMcpAuthResultSchema>;\n\n/** Result for droid.clear_mcp_auth response. */\nexport const ClearMcpAuthResultSchema = z\n .object({ success: z.boolean() })\n .passthrough();\n\nexport type ClearMcpAuthResult = z.infer<typeof ClearMcpAuthResultSchema>;\n\n/** Result for droid.submit_mcp_auth_code response. */\nexport const SubmitMcpAuthCodeResultSchema = z\n .object({ success: z.boolean() })\n .passthrough();\n\nexport type SubmitMcpAuthCodeResult = z.infer<\n typeof SubmitMcpAuthCodeResultSchema\n>;\n\n/** Result for droid.add_mcp_server response. */\nexport const AddMcpServerResultSchema = z\n .object({ success: z.boolean() })\n .passthrough();\n\nexport type AddMcpServerResult = z.infer<typeof AddMcpServerResultSchema>;\n\n/** Result for droid.remove_mcp_server response. */\nexport const RemoveMcpServerResultSchema = z\n .object({ success: z.boolean() })\n .passthrough();\n\nexport type RemoveMcpServerResult = z.infer<typeof RemoveMcpServerResultSchema>;\n\n/** Result for droid.list_mcp_registry response. */\nexport const ListMcpRegistryResultSchema = z\n .object({ servers: z.array(McpRegistryServerSchema) })\n .passthrough();\n\nexport type ListMcpRegistryResult = z.infer<typeof ListMcpRegistryResultSchema>;\n\n/** Result for droid.list_mcp_tools response. */\nexport const ListMcpToolsResultSchema = z\n .object({ tools: z.array(McpToolInfoSchema) })\n .passthrough();\n\nexport type ListMcpToolsResult = z.infer<typeof ListMcpToolsResultSchema>;\n\n/** Result for droid.list_mcp_servers response. */\nexport const ListMcpServersResultSchema = z\n .object({\n servers: z.array(McpServerStatusInfoSchema),\n summary: McpStatusSummarySchema,\n })\n .passthrough();\n\nexport type ListMcpServersResult = z.infer<typeof ListMcpServersResultSchema>;\n\n/** Result for droid.toggle_mcp_tool response. */\nexport const ToggleMcpToolResultSchema = z\n .object({ success: z.boolean() })\n .passthrough();\n\nexport type ToggleMcpToolResult = z.infer<typeof ToggleMcpToolResultSchema>;\n\n/** Result for droid.list_skills response. */\nexport const ListSkillsResultSchema = z\n .object({ skills: z.array(SkillInfoSchema) })\n .passthrough();\n\nexport type ListSkillsResult = z.infer<typeof ListSkillsResultSchema>;\n\n/** Result for droid.submit_bug_report response. */\nexport const SubmitBugReportResultSchema = z\n .object({ bugReportId: z.string() })\n .passthrough();\n\nexport type SubmitBugReportResult = z.infer<typeof SubmitBugReportResultSchema>;\n\n// ---------------------------------------------------------------------------\n// Response schemas (union of success | failure)\n// ---------------------------------------------------------------------------\n\nexport const InitializeSessionResponseSchema = z.union([\n JsonRpcResponseSuccessSchema.extend({\n result: InitializeSessionResultSchema,\n }),\n JsonRpcResponseFailureSchema,\n]);\n\nexport type InitializeSessionResponse = z.infer<typeof InitializeSessionResponseSchema>;\n\n/** Concrete type for LoadSessionResponse (avoids TS7056 deep inference). */\nexport type LoadSessionResponse =\n | (Omit<z.infer<typeof JsonRpcResponseSuccessSchema>, \"result\"> & { result: LoadSessionResult })\n | JsonRpcResponseFailure;\n\nconst _LoadSessionResponseSchema = z.union([\n JsonRpcResponseSuccessSchema.extend({ result: LoadSessionResultSchema }),\n JsonRpcResponseFailureSchema,\n]);\n\nexport const LoadSessionResponseSchema: z.ZodType<\n LoadSessionResponse,\n z.ZodTypeDef,\n unknown\n> = _LoadSessionResponseSchema as z.ZodType<LoadSessionResponse, z.ZodTypeDef, unknown>;\n\nexport const AddUserMessageResponseSchema = z.union([\n JsonRpcResponseSuccessSchema.extend({ result: AddUserMessageResultSchema }),\n JsonRpcResponseFailureSchema,\n]);\n\nexport type AddUserMessageResponse = z.infer<typeof AddUserMessageResponseSchema>;\n\nexport const InterruptSessionResponseSchema = z.union([\n JsonRpcResponseSuccessSchema.extend({\n result: InterruptSessionResultSchema,\n }),\n JsonRpcResponseFailureSchema,\n]);\n\nexport type InterruptSessionResponse = z.infer<typeof InterruptSessionResponseSchema>;\n\nexport const KillWorkerSessionResponseSchema = z.union([\n JsonRpcResponseSuccessSchema.extend({\n result: KillWorkerSessionResultSchema,\n }),\n JsonRpcResponseFailureSchema,\n]);\n\nexport type KillWorkerSessionResponse = z.infer<typeof KillWorkerSessionResponseSchema>;\n\nexport const UpdateSessionSettingsResponseSchema = z.union([\n JsonRpcResponseSuccessSchema.extend({\n result: UpdateSessionSettingsResultSchema,\n }),\n JsonRpcResponseFailureSchema,\n]);\n\nexport type UpdateSessionSettingsResponse = z.infer<typeof UpdateSessionSettingsResponseSchema>;\n\nexport const ToggleMcpServerResponseSchema = z.union([\n JsonRpcResponseSuccessSchema.extend({\n result: ToggleMcpServerResultSchema,\n }),\n JsonRpcResponseFailureSchema,\n]);\n\nexport type ToggleMcpServerResponse = z.infer<typeof ToggleMcpServerResponseSchema>;\n\nexport const AuthenticateMcpServerResponseSchema = z.union([\n JsonRpcResponseSuccessSchema.extend({\n result: AuthenticateMcpServerResultSchema,\n }),\n JsonRpcResponseFailureSchema,\n]);\n\nexport type AuthenticateMcpServerResponse = z.infer<typeof AuthenticateMcpServerResponseSchema>;\n\nexport const CancelMcpAuthResponseSchema = z.union([\n JsonRpcResponseSuccessSchema.extend({ result: CancelMcpAuthResultSchema }),\n JsonRpcResponseFailureSchema,\n]);\n\nexport type CancelMcpAuthResponse = z.infer<typeof CancelMcpAuthResponseSchema>;\n\nexport const ClearMcpAuthResponseSchema = z.union([\n JsonRpcResponseSuccessSchema.extend({ result: ClearMcpAuthResultSchema }),\n JsonRpcResponseFailureSchema,\n]);\n\nexport type ClearMcpAuthResponse = z.infer<typeof ClearMcpAuthResponseSchema>;\n\nexport const SubmitMcpAuthCodeResponseSchema = z.union([\n JsonRpcResponseSuccessSchema.extend({\n result: SubmitMcpAuthCodeResultSchema,\n }),\n JsonRpcResponseFailureSchema,\n]);\n\nexport type SubmitMcpAuthCodeResponse = z.infer<typeof SubmitMcpAuthCodeResponseSchema>;\n\nexport const AddMcpServerResponseSchema = z.union([\n JsonRpcResponseSuccessSchema.extend({ result: AddMcpServerResultSchema }),\n JsonRpcResponseFailureSchema,\n]);\n\nexport type AddMcpServerResponse = z.infer<typeof AddMcpServerResponseSchema>;\n\nexport const RemoveMcpServerResponseSchema = z.union([\n JsonRpcResponseSuccessSchema.extend({ result: RemoveMcpServerResultSchema }),\n JsonRpcResponseFailureSchema,\n]);\n\nexport type RemoveMcpServerResponse = z.infer<typeof RemoveMcpServerResponseSchema>;\n\nexport const ListMcpRegistryResponseSchema = z.union([\n JsonRpcResponseSuccessSchema.extend({\n result: ListMcpRegistryResultSchema,\n }),\n JsonRpcResponseFailureSchema,\n]);\n\nexport type ListMcpRegistryResponse = z.infer<typeof ListMcpRegistryResponseSchema>;\n\nexport const ListMcpToolsResponseSchema = z.union([\n JsonRpcResponseSuccessSchema.extend({ result: ListMcpToolsResultSchema }),\n JsonRpcResponseFailureSchema,\n]);\n\nexport type ListMcpToolsResponse = z.infer<typeof ListMcpToolsResponseSchema>;\n\nexport const ListMcpServersResponseSchema = z.union([\n JsonRpcResponseSuccessSchema.extend({ result: ListMcpServersResultSchema }),\n JsonRpcResponseFailureSchema,\n]);\n\nexport type ListMcpServersResponse = z.infer<typeof ListMcpServersResponseSchema>;\n\nexport const ToggleMcpToolResponseSchema = z.union([\n JsonRpcResponseSuccessSchema.extend({ result: ToggleMcpToolResultSchema }),\n JsonRpcResponseFailureSchema,\n]);\n\nexport type ToggleMcpToolResponse = z.infer<typeof ToggleMcpToolResponseSchema>;\n\nexport const ListSkillsResponseSchema = z.union([\n JsonRpcResponseSuccessSchema.extend({ result: ListSkillsResultSchema }),\n JsonRpcResponseFailureSchema,\n]);\n\nexport type ListSkillsResponse = z.infer<typeof ListSkillsResponseSchema>;\n\nexport const SubmitBugReportResponseSchema = z.union([\n JsonRpcResponseSuccessSchema.extend({ result: SubmitBugReportResultSchema }),\n JsonRpcResponseFailureSchema,\n]);\n\nexport type SubmitBugReportResponse = z.infer<typeof SubmitBugReportResponseSchema>;\n","/**\n * Server→client schemas: notification payloads, permission requests, and ask-user requests.\n *\n * Ported from: packages/common/src/droid/schemas/cli.ts\n */\n\nimport { z } from \"zod\";\n\nimport { TokenUsageSchema } from \"./client.js\";\nimport {\n AutonomyLevel,\n AutonomyMode,\n DroidClientMethod,\n DroidErrorType,\n DroidInteractionMode,\n DroidWorkingState,\n McpAuthOutcome,\n MissionState,\n ReasoningEffort,\n SessionNotificationType,\n ToolConfirmationOutcome,\n ToolConfirmationType,\n} from \"./enums.js\";\nimport { FactoryDroidMessageSchema } from \"./messages.js\";\nimport {\n McpServerStatusInfoSchema,\n McpStatusSummarySchema,\n ToolConfirmationListItemSchema,\n} from \"./mcp.js\";\nimport { MissionFeatureSchema, ProgressLogEntrySchema } from \"./mission.js\";\nimport {\n JsonRpcNotificationSchema,\n JsonRpcRequestSchema,\n JsonRpcResponseFailureSchema,\n JsonRpcResponseSuccessSchema,\n} from \"./shared.js\";\n\n// ---------------------------------------------------------------------------\n// Supporting types for notification payloads\n// ---------------------------------------------------------------------------\n\n/** Tool use block (from ToolUseSchema in sessionV2/messages). */\nexport const ToolUseSchema = z\n .object({\n type: z.literal(\"tool_use\"),\n id: z.string(),\n input: z.record(z.unknown()),\n name: z.string(),\n thoughtSignature: z.string().optional(),\n })\n .passthrough();\n\nexport type ToolUse = z.infer<typeof ToolUseSchema>;\n\n/** Error detail object within an ErrorNotification. */\nexport const ErrorDetailSchema = z\n .object({\n name: z.string(),\n message: z.string(),\n })\n .passthrough();\n\nexport type ErrorDetail = z.infer<typeof ErrorDetailSchema>;\n\n/** Streaming update from subagent tool calls. */\nexport const ToolProgressUpdateSchema = z\n .object({\n type: z.enum([\"tool_call\", \"tool_result\", \"error\", \"status\", \"message\"]),\n toolName: z.string().optional(),\n status: z.string().optional(),\n details: z.string().optional(),\n text: z.string().optional(),\n error: z.string().optional(),\n timestamp: z.number().optional(),\n parameters: z.record(z.unknown()).optional(),\n valueSnippet: z.string().optional(),\n subagentSessionId: z.string().optional(),\n })\n .passthrough();\n\nexport type ToolProgressUpdate = z.infer<typeof ToolProgressUpdateSchema>;\n\n/** Settings payload within SettingsUpdatedNotification. */\nexport const SettingsUpdatedPayloadSchema = z\n .object({\n autonomyMode: z.nativeEnum(AutonomyMode).optional(),\n interactionMode: z.nativeEnum(DroidInteractionMode).optional().catch(undefined),\n autonomyLevel: z.nativeEnum(AutonomyLevel).optional().catch(undefined),\n modelId: z.string().optional(),\n reasoningEffort: z.nativeEnum(ReasoningEffort).optional(),\n specModeModelId: z.string().optional(),\n specModeReasoningEffort: z.nativeEnum(ReasoningEffort).optional(),\n })\n .passthrough();\n\nexport type SettingsUpdatedPayload = z.infer<\n typeof SettingsUpdatedPayloadSchema\n>;\n\n// ---------------------------------------------------------------------------\n// 20 notification payload types\n// ---------------------------------------------------------------------------\n\n/** Tool result notification. */\nexport const ToolResultNotificationSchema = z\n .object({\n type: z.literal(SessionNotificationType.TOOL_RESULT),\n messageId: z.string(),\n toolUseId: z.string(),\n content: z.unknown().optional(),\n isError: z.boolean().optional(),\n id: z.string().optional(),\n })\n .passthrough();\n\nexport type ToolResultNotification = z.infer<\n typeof ToolResultNotificationSchema\n>;\n\n/** Tool progress update notification. */\nexport const ToolProgressUpdateNotificationSchema = z\n .object({\n type: z.literal(SessionNotificationType.TOOL_PROGRESS_UPDATE),\n toolUseId: z.string(),\n toolName: z.string(),\n update: ToolProgressUpdateSchema,\n })\n .passthrough();\n\nexport type ToolProgressUpdateNotification = z.infer<\n typeof ToolProgressUpdateNotificationSchema\n>;\n\n/** Create message notification. */\nexport const CreateMessageNotificationSchema = z\n .object({\n type: z.literal(SessionNotificationType.CREATE_MESSAGE),\n message: FactoryDroidMessageSchema,\n parentId: z.string().optional(),\n requestId: z.string().optional(),\n })\n .passthrough();\n\nexport type CreateMessageNotification = z.infer<\n typeof CreateMessageNotificationSchema\n>;\n\n/** Error notification. */\nexport const ErrorNotificationSchema = z\n .object({\n type: z.literal(SessionNotificationType.ERROR),\n message: z.string(),\n errorType: z.nativeEnum(DroidErrorType),\n timestamp: z.string(),\n error: ErrorDetailSchema.optional(),\n })\n .passthrough();\n\nexport type ErrorNotification = z.infer<typeof ErrorNotificationSchema>;\n\n/** Droid working state changed notification. */\nexport const DroidWorkingStateChangedNotificationSchema = z\n .object({\n type: z.literal(SessionNotificationType.DROID_WORKING_STATE_CHANGED),\n newState: z.nativeEnum(DroidWorkingState),\n })\n .passthrough();\n\nexport type DroidWorkingStateChangedNotification = z.infer<\n typeof DroidWorkingStateChangedNotificationSchema\n>;\n\n/** Permission resolved notification. */\nexport const PermissionResolvedNotificationSchema = z\n .object({\n type: z.literal(SessionNotificationType.PERMISSION_RESOLVED),\n requestId: z.string(),\n toolUseIds: z.array(z.string()),\n selectedOption: z.nativeEnum(ToolConfirmationOutcome),\n })\n .passthrough();\n\nexport type PermissionResolvedNotification = z.infer<\n typeof PermissionResolvedNotificationSchema\n>;\n\n/** Settings updated notification. */\nexport const SettingsUpdatedNotificationSchema = z\n .object({\n type: z.literal(SessionNotificationType.SETTINGS_UPDATED),\n settings: SettingsUpdatedPayloadSchema,\n })\n .passthrough();\n\nexport type SettingsUpdatedNotification = z.infer<\n typeof SettingsUpdatedNotificationSchema\n>;\n\n/** Session title updated notification. */\nexport const SessionTitleUpdatedNotificationSchema = z\n .object({\n type: z.literal(SessionNotificationType.SESSION_TITLE_UPDATED),\n title: z.string(),\n })\n .passthrough();\n\nexport type SessionTitleUpdatedNotification = z.infer<\n typeof SessionTitleUpdatedNotificationSchema\n>;\n\n/** MCP status changed notification. */\nexport const McpStatusChangedNotificationSchema = z\n .object({\n type: z.literal(SessionNotificationType.MCP_STATUS_CHANGED),\n servers: z.array(McpServerStatusInfoSchema),\n summary: McpStatusSummarySchema,\n })\n .passthrough();\n\nexport type McpStatusChangedNotification = z.infer<\n typeof McpStatusChangedNotificationSchema\n>;\n\n/** Assistant text delta notification (streaming token). */\nexport const AssistantTextDeltaNotificationSchema = z\n .object({\n type: z.literal(SessionNotificationType.ASSISTANT_TEXT_DELTA),\n messageId: z.string(),\n blockIndex: z.number(),\n textDelta: z.string(),\n })\n .passthrough();\n\nexport type AssistantTextDeltaNotification = z.infer<\n typeof AssistantTextDeltaNotificationSchema\n>;\n\n/** Thinking text delta notification (streaming thinking token). */\nexport const ThinkingTextDeltaNotificationSchema = z\n .object({\n type: z.literal(SessionNotificationType.THINKING_TEXT_DELTA),\n messageId: z.string(),\n blockIndex: z.number(),\n textDelta: z.string(),\n })\n .passthrough();\n\nexport type ThinkingTextDeltaNotification = z.infer<\n typeof ThinkingTextDeltaNotificationSchema\n>;\n\n/** Session token usage changed notification. */\nexport const SessionTokenUsageChangedNotificationSchema = z\n .object({\n type: z.literal(SessionNotificationType.SESSION_TOKEN_USAGE_CHANGED),\n sessionId: z.string(),\n tokenUsage: TokenUsageSchema,\n })\n .passthrough();\n\nexport type SessionTokenUsageChangedNotification = z.infer<\n typeof SessionTokenUsageChangedNotificationSchema\n>;\n\n/** Mission state changed notification. */\nexport const MissionStateChangedNotificationSchema = z\n .object({\n type: z.literal(SessionNotificationType.MISSION_STATE_CHANGED),\n state: z.nativeEnum(MissionState),\n })\n .passthrough();\n\nexport type MissionStateChangedNotification = z.infer<\n typeof MissionStateChangedNotificationSchema\n>;\n\n/** Mission features changed notification. */\nexport const MissionFeaturesChangedNotificationSchema = z\n .object({\n type: z.literal(SessionNotificationType.MISSION_FEATURES_CHANGED),\n features: z.array(MissionFeatureSchema),\n })\n .passthrough();\n\nexport type MissionFeaturesChangedNotification = z.infer<\n typeof MissionFeaturesChangedNotificationSchema\n>;\n\n/** Mission progress entry notification. */\nexport const MissionProgressEntryNotificationSchema = z\n .object({\n type: z.literal(SessionNotificationType.MISSION_PROGRESS_ENTRY),\n progressLog: z.array(ProgressLogEntrySchema),\n })\n .passthrough();\n\nexport type MissionProgressEntryNotification = z.infer<\n typeof MissionProgressEntryNotificationSchema\n>;\n\n/** Mission heartbeat notification. */\nexport const MissionHeartbeatNotificationSchema = z\n .object({\n type: z.literal(SessionNotificationType.MISSION_HEARTBEAT),\n timestamp: z.string(),\n })\n .passthrough();\n\nexport type MissionHeartbeatNotification = z.infer<\n typeof MissionHeartbeatNotificationSchema\n>;\n\n/** Mission worker started notification. */\nexport const MissionWorkerStartedNotificationSchema = z\n .object({\n type: z.literal(SessionNotificationType.MISSION_WORKER_STARTED),\n workerSessionId: z.string(),\n })\n .passthrough();\n\nexport type MissionWorkerStartedNotification = z.infer<\n typeof MissionWorkerStartedNotificationSchema\n>;\n\n/** Mission worker completed notification. */\nexport const MissionWorkerCompletedNotificationSchema = z\n .object({\n type: z.literal(SessionNotificationType.MISSION_WORKER_COMPLETED),\n workerSessionId: z.string(),\n exitCode: z.number(),\n })\n .passthrough();\n\nexport type MissionWorkerCompletedNotification = z.infer<\n typeof MissionWorkerCompletedNotificationSchema\n>;\n\n/** MCP authentication required notification. */\nexport const McpAuthRequiredNotificationSchema = z\n .object({\n type: z.literal(SessionNotificationType.MCP_AUTH_REQUIRED),\n serverName: z.string(),\n authUrl: z.string(),\n message: z.string(),\n state: z.string(),\n })\n .passthrough();\n\nexport type McpAuthRequiredNotification = z.infer<\n typeof McpAuthRequiredNotificationSchema\n>;\n\n/** MCP authentication completed notification. */\nexport const McpAuthCompletedNotificationSchema = z\n .object({\n type: z.literal(SessionNotificationType.MCP_AUTH_COMPLETED),\n serverName: z.string(),\n outcome: z.nativeEnum(McpAuthOutcome),\n message: z.string(),\n })\n .passthrough();\n\nexport type McpAuthCompletedNotification = z.infer<\n typeof McpAuthCompletedNotificationSchema\n>;\n\n// ---------------------------------------------------------------------------\n// SessionNotification discriminated union\n// ---------------------------------------------------------------------------\n\n/** List of all session notification schemas (for discriminatedUnion). */\nexport const SessionNotificationSchemaList = [\n ToolResultNotificationSchema,\n ToolProgressUpdateNotificationSchema,\n CreateMessageNotificationSchema,\n ErrorNotificationSchema,\n DroidWorkingStateChangedNotificationSchema,\n PermissionResolvedNotificationSchema,\n SettingsUpdatedNotificationSchema,\n SessionTitleUpdatedNotificationSchema,\n McpStatusChangedNotificationSchema,\n AssistantTextDeltaNotificationSchema,\n ThinkingTextDeltaNotificationSchema,\n SessionTokenUsageChangedNotificationSchema,\n MissionStateChangedNotificationSchema,\n MissionFeaturesChangedNotificationSchema,\n MissionProgressEntryNotificationSchema,\n MissionHeartbeatNotificationSchema,\n MissionWorkerStartedNotificationSchema,\n MissionWorkerCompletedNotificationSchema,\n McpAuthRequiredNotificationSchema,\n McpAuthCompletedNotificationSchema,\n] as const;\n\n/** Discriminated union over all 20 session notification types. */\nexport const SessionNotificationPayloadSchema = z.discriminatedUnion(\n \"type\",\n SessionNotificationSchemaList,\n);\n\nexport type SessionNotificationPayload = z.infer<\n typeof SessionNotificationPayloadSchema\n>;\n\n/** Parameters for session notification (wraps the discriminated union). */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const SessionNotificationParamsSchema: z.ZodType<any> = z\n .object({\n notification: SessionNotificationPayloadSchema,\n })\n .passthrough();\n\nexport type SessionNotificationParams = {\n notification: SessionNotificationPayload;\n [key: string]: unknown;\n};\n\n/** Full session notification with JSON-RPC envelope. */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const SessionNotificationSchema: z.ZodType<any> =\n JsonRpcNotificationSchema.extend({\n method: z.literal(DroidClientMethod.SESSION_NOTIFICATION),\n params: SessionNotificationParamsSchema,\n });\n\nexport type SessionNotification = z.output<typeof JsonRpcNotificationSchema> & {\n method: \"droid.session_notification\";\n params: SessionNotificationParams;\n};\n\n// ---------------------------------------------------------------------------\n// Tool confirmation details\n// ---------------------------------------------------------------------------\n\nexport const EditToolConfirmationDetailsSchema = z\n .object({\n type: z.literal(ToolConfirmationType.Edit),\n filePath: z.string(),\n fileName: z.string(),\n oldContent: z.string().optional(),\n newContent: z.string().optional(),\n })\n .passthrough();\n\nexport type EditToolConfirmationDetails = z.infer<\n typeof EditToolConfirmationDetailsSchema\n>;\n\nexport const ExecuteToolConfirmationDetailsSchema = z\n .object({\n type: z.literal(ToolConfirmationType.Execute),\n fullCommand: z.string(),\n command: z.string(),\n extractedCommands: z.array(z.string()).optional(),\n impactLevel: z.string().optional(),\n })\n .passthrough();\n\nexport type ExecuteToolConfirmationDetails = z.infer<\n typeof ExecuteToolConfirmationDetailsSchema\n>;\n\nexport const CreateToolConfirmationDetailsSchema = z\n .object({\n type: z.literal(ToolConfirmationType.Create),\n filePath: z.string(),\n fileName: z.string(),\n content: z.string(),\n })\n .passthrough();\n\nexport type CreateToolConfirmationDetails = z.infer<\n typeof CreateToolConfirmationDetailsSchema\n>;\n\nexport const AskUserQuestionSchema = z\n .object({\n index: z.number(),\n topic: z.string(),\n question: z.string(),\n options: z.array(z.string()),\n })\n .passthrough();\n\nexport type AskUserQuestion = z.infer<typeof AskUserQuestionSchema>;\n\nexport const AskUserConfirmationDetailsSchema = z\n .object({\n type: z.literal(ToolConfirmationType.AskUser),\n questionnaire: z.string(),\n parsed: z\n .object({\n questions: z.array(AskUserQuestionSchema),\n })\n .optional(),\n parseError: z\n .object({\n message: z.string(),\n line: z.number().optional(),\n })\n .optional(),\n })\n .passthrough();\n\nexport type AskUserConfirmationDetails = z.infer<\n typeof AskUserConfirmationDetailsSchema\n>;\n\nexport const ExitSpecModeConfirmationDetailsSchema = z\n .object({\n type: z.literal(ToolConfirmationType.ExitSpecMode),\n plan: z.string(),\n title: z.string().optional(),\n optionNames: z.array(z.string()).optional(),\n })\n .passthrough();\n\nexport type ExitSpecModeConfirmationDetails = z.infer<\n typeof ExitSpecModeConfirmationDetailsSchema\n>;\n\nexport const ProposeMissionConfirmationDetailsSchema = z\n .object({\n type: z.literal(ToolConfirmationType.ProposeMission),\n proposal: z.string(),\n title: z.string().optional(),\n })\n .passthrough();\n\nexport type ProposeMissionConfirmationDetails = z.infer<\n typeof ProposeMissionConfirmationDetailsSchema\n>;\n\nexport const StartMissionRunConfirmationDetailsSchema = z\n .object({\n type: z.literal(ToolConfirmationType.StartMissionRun),\n runningMissionCount: z.number(),\n runningMissionSessionIds: z.array(z.string()),\n })\n .passthrough();\n\nexport type StartMissionRunConfirmationDetails = z.infer<\n typeof StartMissionRunConfirmationDetailsSchema\n>;\n\nexport const ApplyPatchToolConfirmationDetailsSchema = z\n .object({\n type: z.literal(ToolConfirmationType.ApplyPatch),\n filePath: z.string(),\n fileName: z.string(),\n patchContent: z.string(),\n oldContent: z.string().optional(),\n newContent: z.string().optional(),\n })\n .passthrough();\n\nexport type ApplyPatchToolConfirmationDetails = z.infer<\n typeof ApplyPatchToolConfirmationDetailsSchema\n>;\n\nexport const McpToolConfirmationDetailsSchema = z\n .object({\n type: z.literal(ToolConfirmationType.McpTool),\n toolName: z.string(),\n impactLevel: z.string(),\n })\n .passthrough();\n\nexport type McpToolConfirmationDetails = z.infer<\n typeof McpToolConfirmationDetailsSchema\n>;\n\n/** Discriminated union over tool confirmation detail types. */\nexport const ToolConfirmationDetailsSchema = z.discriminatedUnion(\"type\", [\n EditToolConfirmationDetailsSchema,\n ExecuteToolConfirmationDetailsSchema,\n CreateToolConfirmationDetailsSchema,\n AskUserConfirmationDetailsSchema,\n ExitSpecModeConfirmationDetailsSchema,\n ProposeMissionConfirmationDetailsSchema,\n StartMissionRunConfirmationDetailsSchema,\n ApplyPatchToolConfirmationDetailsSchema,\n McpToolConfirmationDetailsSchema,\n]);\n\nexport type ToolConfirmationDetails = z.infer<\n typeof ToolConfirmationDetailsSchema\n>;\n\n/** Tool confirmation information (toolUse + confirmationType + details). */\nexport const ToolConfirmationInfoSchema = z\n .object({\n toolUse: ToolUseSchema,\n confirmationType: z.nativeEnum(ToolConfirmationType),\n details: ToolConfirmationDetailsSchema,\n })\n .passthrough();\n\nexport type ToolConfirmationInfo = z.infer<typeof ToolConfirmationInfoSchema>;\n\n// ---------------------------------------------------------------------------\n// RequestPermissionRequest (server → client)\n// ---------------------------------------------------------------------------\n\n/** Parameters for droid.request_permission request. */\nexport const RequestPermissionRequestParamsSchema = z\n .object({\n toolUses: z.array(ToolConfirmationInfoSchema),\n options: z.array(ToolConfirmationListItemSchema),\n })\n .passthrough();\n\nexport type RequestPermissionRequestParams = z.infer<\n typeof RequestPermissionRequestParamsSchema\n>;\n\n/** Request for permission from the server (server → client). */\nexport const RequestPermissionRequestSchema = JsonRpcRequestSchema.extend({\n method: z.literal(DroidClientMethod.REQUEST_PERMISSION),\n params: RequestPermissionRequestParamsSchema,\n});\n\nexport type RequestPermissionRequest = z.infer<\n typeof RequestPermissionRequestSchema\n>;\n\n/** Result for droid.request_permission response. */\nexport const RequestPermissionResultSchema = z\n .object({\n selectedOption: z.nativeEnum(ToolConfirmationOutcome),\n })\n .strict();\n\nexport type RequestPermissionResult = z.infer<\n typeof RequestPermissionResultSchema\n>;\n\n/** Response to droid.request_permission. */\nexport const RequestPermissionResponseSchema = z.union([\n JsonRpcResponseSuccessSchema.extend({\n result: RequestPermissionResultSchema,\n }),\n JsonRpcResponseFailureSchema,\n]);\n\nexport type RequestPermissionResponse = z.infer<\n typeof RequestPermissionResponseSchema\n>;\n\n// ---------------------------------------------------------------------------\n// AskUserRequest (server → client)\n// ---------------------------------------------------------------------------\n\n/** Parameters for droid.ask_user request. */\nexport const AskUserRequestParamsSchema = z\n .object({\n toolCallId: z.string(),\n questions: z.array(AskUserQuestionSchema),\n })\n .passthrough();\n\nexport type AskUserRequestParams = z.infer<typeof AskUserRequestParamsSchema>;\n\n/** Ask user request from the server (server → client). */\nexport const AskUserRequestSchema = JsonRpcRequestSchema.extend({\n method: z.literal(DroidClientMethod.ASK_USER),\n params: AskUserRequestParamsSchema,\n});\n\nexport type AskUserRequest = z.infer<typeof AskUserRequestSchema>;\n\n/** A collected answer from the user. */\nexport const AskUserCollectedAnswerSchema = z\n .object({\n index: z.number(),\n question: z.string(),\n answer: z.string(),\n })\n .strict();\n\nexport type AskUserCollectedAnswer = z.infer<\n typeof AskUserCollectedAnswerSchema\n>;\n\n/** Result for droid.ask_user response. */\nexport const AskUserResultSchema = z\n .object({\n cancelled: z.boolean().optional(),\n answers: z.array(AskUserCollectedAnswerSchema),\n })\n .strict();\n\nexport type AskUserResult = z.infer<typeof AskUserResultSchema>;\n\n/** Response to droid.ask_user. */\nexport const AskUserResponseSchema = z.union([\n JsonRpcResponseSuccessSchema.extend({ result: AskUserResultSchema }),\n JsonRpcResponseFailureSchema,\n]);\n\nexport type AskUserResponse = z.infer<typeof AskUserResponseSchema>;\n\n// ---------------------------------------------------------------------------\n// CliRequestOrNotification discriminated union\n// ---------------------------------------------------------------------------\n\n/** Union over all 3 server → client methods. */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const CliRequestOrNotificationSchema: z.ZodType<any> = z.union([\n SessionNotificationSchema,\n RequestPermissionRequestSchema,\n AskUserRequestSchema,\n]);\n\nexport type CliRequestOrNotification =\n | SessionNotification\n | RequestPermissionRequest\n | AskUserRequest;\n","/**\n * Error class hierarchy for the Factory Droid SDK.\n *\n * All SDK errors extend Error directly (no MetaError dependency).\n * Each error class sets its `name` property to the class name for\n * reliable `instanceof` checks and readable stack traces.\n */\n\n/**\n * Raised when a connection to the droid process fails.\n *\n * Carries optional context about the working directory and executable path\n * that were used when attempting to spawn the process.\n */\nexport class ConnectionError extends Error {\n /** The working directory used when spawning the process. */\n readonly cwd: string;\n\n /** The executable path used when spawning the process. */\n readonly execPath: string;\n\n constructor(message: string, options?: { cwd?: string; execPath?: string }) {\n super(message);\n this.name = \"ConnectionError\";\n this.cwd = options?.cwd ?? \"\";\n this.execPath = options?.execPath ?? \"\";\n Object.setPrototypeOf(this, ConnectionError.prototype);\n }\n}\n\n/**\n * Raised when a JSON-RPC protocol error occurs.\n *\n * Carries the optional JSON-RPC error code and any additional data\n * returned in the error response.\n */\nexport class ProtocolError extends Error {\n /** The JSON-RPC error code, if available. */\n readonly code: number | undefined;\n\n /** Additional error data from the JSON-RPC response. */\n readonly data: unknown;\n\n constructor(\n message: string,\n options?: { code?: number; data?: unknown },\n ) {\n super(message);\n this.name = \"ProtocolError\";\n this.code = options?.code;\n this.data = options?.data;\n Object.setPrototypeOf(this, ProtocolError.prototype);\n }\n}\n\n/**\n * Base error for session-related errors.\n */\nexport class SessionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"SessionError\";\n Object.setPrototypeOf(this, SessionError.prototype);\n }\n}\n\n/**\n * Raised when a session cannot be found.\n *\n * Constructs a default message of \"Session not found: {sessionId}\".\n */\nexport class SessionNotFoundError extends SessionError {\n /** The ID of the session that was not found. */\n readonly sessionId: string;\n\n constructor(sessionId: string) {\n super(`Session not found: ${sessionId}`);\n this.name = \"SessionNotFoundError\";\n this.sessionId = sessionId;\n Object.setPrototypeOf(this, SessionNotFoundError.prototype);\n }\n}\n\n/**\n * Raised when a request to the droid process times out.\n */\nexport class TimeoutError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"TimeoutError\";\n Object.setPrototypeOf(this, TimeoutError.prototype);\n }\n}\n\n/**\n * Raised when the droid subprocess exits unexpectedly.\n *\n * Carries the exit code (if the process exited normally) and the signal\n * name (if the process was killed by a signal).\n */\nexport class ProcessExitError extends Error {\n /** The exit code of the process, or null if terminated by signal. */\n readonly exitCode: number | null;\n\n /** The signal that terminated the process, or null if exited normally. */\n readonly signal: string | null;\n\n constructor(\n message: string,\n options?: { exitCode?: number | null; signal?: string | null },\n ) {\n super(message);\n this.name = \"ProcessExitError\";\n this.exitCode = options?.exitCode ?? null;\n this.signal = options?.signal ?? null;\n Object.setPrototypeOf(this, ProcessExitError.prototype);\n }\n}\n","/**\n * ProcessTransport — subprocess-based transport for the Factory Droid SDK.\n *\n * Spawns `droid exec --input-format stream-jsonrpc --output-format stream-jsonrpc`\n * as a child process and communicates via newline-delimited JSON (JSONL) over\n * stdin/stdout.\n */\n\nimport { type ChildProcess, spawn } from \"node:child_process\";\nimport * as readline from \"node:readline\";\n\nimport { ConnectionError, ProcessExitError } from \"./errors.js\";\nimport type {\n DroidClientTransport,\n ErrorCallback,\n MessageCallback,\n ProcessTransportOptions,\n} from \"./types.js\";\n\n/** Default arguments for `droid exec`. */\nconst DEFAULT_EXEC_ARGS = [\n \"exec\",\n \"--input-format\",\n \"stream-jsonrpc\",\n \"--output-format\",\n \"stream-jsonrpc\",\n];\n\n/** Default grace period in milliseconds before escalating SIGTERM → SIGKILL. */\nconst DEFAULT_GRACE_PERIOD_MS = 5_000;\n\n/**\n * Transport that communicates via JSONL over stdin/stdout of a spawned\n * `droid exec` child process.\n *\n * Key behaviors:\n * - JSONL framing (one JSON object per newline-terminated line)\n * - Write serialization via a promise chain to prevent interleaving\n * - Process lifecycle management (SIGTERM → grace period → SIGKILL)\n * - Reconnection after close via `connect()`\n * - Non-JSON stdout lines are silently skipped\n * - Fires `onError` with `ProcessExitError` on abnormal exit\n */\nexport class ProcessTransport implements DroidClientTransport {\n private readonly execPath: string;\n private readonly execArgs: string[];\n private readonly cwd: string | undefined;\n private readonly env: Record<string, string> | undefined;\n private readonly gracePeriodMs: number;\n\n private childProcess: ChildProcess | null = null;\n private readlineInterface: readline.Interface | null = null;\n private messageHandler: MessageCallback | null = null;\n private errorHandler: ErrorCallback | null = null;\n\n /**\n * Sticky error from a process error or unexpected exit. Once set,\n * all subsequent `send()` calls throw immediately.\n */\n private processError: Error | null = null;\n\n /** Promise-chain serializer for stdin writes. */\n private writeChain: Promise<void> = Promise.resolve();\n\n private _isConnected = false;\n private isClosing = false;\n\n constructor(options: ProcessTransportOptions = {}) {\n this.execPath = options.execPath ?? \"droid\";\n this.execArgs = options.execArgs\n ? [...options.execArgs]\n : [...DEFAULT_EXEC_ARGS];\n this.cwd = options.cwd;\n this.env = options.env;\n this.gracePeriodMs =\n (options.gracePeriod ?? DEFAULT_GRACE_PERIOD_MS / 1_000) * 1_000;\n }\n\n // -----------------------------------------------------------------------\n // DroidClientTransport interface\n // -----------------------------------------------------------------------\n\n get isConnected(): boolean {\n return this._isConnected;\n }\n\n async connect(): Promise<void> {\n if (this._isConnected) {\n throw new ConnectionError(\"Transport already connected\", {\n execPath: this.execPath,\n });\n }\n\n // Reset state for (re)connection\n this.processError = null;\n this.isClosing = false;\n this.writeChain = Promise.resolve();\n\n const mergedEnv = this.env\n ? { ...process.env, ...this.env }\n : undefined;\n\n try {\n this.childProcess = spawn(this.execPath, this.execArgs, {\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n cwd: this.cwd,\n env: mergedEnv,\n });\n } catch (err: unknown) {\n const message =\n err instanceof Error\n ? `Failed to start droid process: ${err.message}`\n : \"Failed to start droid process\";\n throw new ConnectionError(message, {\n execPath: this.execPath,\n cwd: this.cwd,\n });\n }\n\n this._isConnected = true;\n this.setupHandlers();\n }\n\n send(message: object): void {\n if (this.processError) {\n throw this.processError;\n }\n if (\n !this._isConnected ||\n !this.childProcess ||\n !this.childProcess.stdin\n ) {\n throw new ConnectionError(\"Transport not connected\", {\n execPath: this.execPath,\n });\n }\n\n const line = JSON.stringify(message) + \"\\n\";\n\n // Chain writes to prevent interleaving on concurrent calls.\n const previousChain = this.writeChain;\n\n this.writeChain = (async () => {\n // Wait for the previous write to finish (ignore its error — it's\n // already been reported to the caller of the previous send()).\n await previousChain.catch(() => {});\n\n if (\n !this.childProcess ||\n !this.childProcess.stdin ||\n this.childProcess.killed ||\n this.isClosing\n ) {\n throw new ConnectionError(\"Process disconnected before write\", {\n execPath: this.execPath,\n });\n }\n\n if (this.processError) {\n throw this.processError;\n }\n\n await new Promise<void>((resolve, reject) => {\n if (!this.childProcess || !this.childProcess.stdin) {\n reject(\n new ConnectionError(\"Process stdin unavailable\", {\n execPath: this.execPath,\n }),\n );\n return;\n }\n\n const stdin = this.childProcess.stdin;\n if (\"writable\" in stdin && !stdin.writable) {\n reject(\n new ConnectionError(\"Process stdin is not writable\", {\n execPath: this.execPath,\n }),\n );\n return;\n }\n\n stdin.write(line, (error) => {\n if (error) {\n const msg = error.message || String(error);\n if (msg.includes(\"EPIPE\") || msg.includes(\"ECONNRESET\")) {\n reject(\n new ConnectionError(\"Process stdin closed during write\", {\n execPath: this.execPath,\n }),\n );\n } else {\n reject(\n new ConnectionError(\n `Failed to write to process stdin: ${msg}`,\n { execPath: this.execPath },\n ),\n );\n }\n } else {\n resolve();\n }\n });\n });\n })();\n }\n\n onMessage(callback: MessageCallback): void {\n this.messageHandler = callback;\n }\n\n onError(callback: ErrorCallback): void {\n this.errorHandler = callback;\n }\n\n async close(): Promise<void> {\n if (this.isClosing) {\n return;\n }\n\n this.isClosing = true;\n this._isConnected = false;\n\n const proc = this.childProcess;\n this.childProcess = null;\n\n if (this.readlineInterface) {\n this.readlineInterface.close();\n this.readlineInterface = null;\n }\n\n if (proc && proc.exitCode === null && !proc.killed) {\n await new Promise<void>((resolve) => {\n const timeout = setTimeout(() => {\n // Escalate to SIGKILL\n if (proc.exitCode === null && !proc.killed) {\n try {\n proc.kill(\"SIGKILL\");\n } catch {\n // Process may already be gone\n }\n }\n }, this.gracePeriodMs);\n\n proc.once(\"exit\", () => {\n clearTimeout(timeout);\n resolve();\n });\n\n // Close stdin first, then SIGTERM\n if (proc.stdin) {\n try {\n proc.stdin.end();\n } catch {\n // Ignore\n }\n }\n\n try {\n proc.kill(\"SIGTERM\");\n } catch {\n // Process may already be gone — resolve immediately\n clearTimeout(timeout);\n resolve();\n }\n });\n }\n\n // Reset closing flag so reconnection via connect() is possible\n this.isClosing = false;\n }\n\n // -----------------------------------------------------------------------\n // Private helpers\n // -----------------------------------------------------------------------\n\n private setupHandlers(): void {\n const proc = this.childProcess;\n if (!proc || !proc.stdout) {\n return;\n }\n\n this.readlineInterface = readline.createInterface({\n input: proc.stdout,\n crlfDelay: Infinity,\n });\n\n this.readlineInterface.on(\"line\", (line) => {\n const trimmed = line.trim();\n if (!trimmed) {\n return;\n }\n\n // Only attempt to parse lines that look like JSON objects / arrays\n if (trimmed.startsWith(\"{\") || trimmed.startsWith(\"[\")) {\n try {\n const parsed: unknown = JSON.parse(trimmed);\n if (this.messageHandler && typeof parsed === \"object\" && parsed !== null) {\n this.messageHandler(parsed as object);\n }\n } catch {\n // Malformed JSON — skip silently\n }\n }\n // Non-JSON lines (e.g. debug output from the subprocess) are silently skipped\n });\n\n // Handle spawn errors (ENOENT etc.)\n proc.on(\"error\", (error) => {\n this.processError = new ConnectionError(\n `Failed to start droid process: ${error.message}`,\n {\n execPath: this.execPath,\n cwd: this.cwd,\n },\n );\n this._isConnected = false;\n if (!this.isClosing && this.errorHandler) {\n this.errorHandler(this.processError);\n }\n });\n\n // Handle process exit\n proc.on(\"exit\", (code, signal) => {\n if (this.readlineInterface) {\n this.readlineInterface.close();\n this.readlineInterface = null;\n }\n\n this._isConnected = false;\n\n if (!this.isClosing) {\n const exitCode = code ?? null;\n const exitSignal = signal ?? null;\n\n let message: string;\n if (exitSignal) {\n message = `Droid process was killed (${exitSignal})`;\n } else if (exitCode !== null && exitCode !== 0) {\n message = `Droid process exited unexpectedly (exit code ${exitCode})`;\n } else if (exitCode === 0) {\n message = \"Droid process exited normally\";\n } else {\n message = \"Droid process exited unexpectedly\";\n }\n\n this.processError = new ProcessExitError(message, {\n exitCode,\n signal: exitSignal,\n });\n\n if (this.errorHandler) {\n this.errorHandler(this.processError);\n }\n }\n });\n }\n}\n","/**\n * JSON-RPC 2.0 protocol engine for the Factory Droid SDK.\n *\n * Sits between the transport layer and the client API. Handles:\n *\n * - Envelope construction for outbound requests\n * - Request/response correlation via pending promises keyed by UUID\n * - Configurable per-request timeouts\n * - Notification dispatch to registered listeners with optional type filtering\n * - Server→client request handling (permission, ask_user)\n * - Error code mapping (ENTITY_NOT_FOUND → SessionNotFoundError)\n * - Sticky transport error: once a transport error fires, all\n * pending and subsequent requests are immediately rejected\n * - Edge cases: unknown response IDs, duplicate response IDs,\n * malformed responses, null-id error responses\n */\n\nimport { v4 as uuidv4 } from \"uuid\";\n\nimport {\n ConnectionError,\n ProtocolError,\n SessionNotFoundError,\n TimeoutError,\n} from \"./errors.js\";\nimport {\n DEFAULT_REQUEST_TIMEOUT,\n FACTORY_PROTOCOL_VERSION,\n JSONRPC_VERSION,\n LEGACY_FACTORY_API_VERSION,\n} from \"./schemas/constants.js\";\nimport {\n DroidClientMethod,\n JsonRpcErrorCode,\n} from \"./schemas/enums.js\";\nimport type { DroidClientTransport } from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * Handler for server→client permission requests.\n * Receives request params and returns the selected ToolConfirmationOutcome string.\n */\nexport type PermissionHandler = (\n params: Record<string, unknown>,\n) => string | Promise<string>;\n\n/**\n * Handler for server→client ask-user requests.\n * Receives request params and returns a result with cancelled flag and answers.\n */\nexport type AskUserHandler = (\n params: Record<string, unknown>,\n) => Record<string, unknown> | Promise<Record<string, unknown>>;\n\n/**\n * Callback for incoming notification messages.\n */\nexport type NotificationCallback = (notification: Record<string, unknown>) => void;\n\n/**\n * Optional filter for notification listeners.\n */\nexport interface NotificationFilter {\n /** Only dispatch notifications whose `params.notification.type` matches. */\n type?: string;\n}\n\n/**\n * Internal state for a pending request awaiting a response.\n */\ninterface PendingRequest {\n readonly method: string;\n readonly requestId: string;\n readonly params: Record<string, unknown>;\n readonly resolve: (value: Record<string, unknown>) => void;\n readonly reject: (reason: Error) => void;\n readonly timer: ReturnType<typeof setTimeout>;\n}\n\n/**\n * Internal entry in the notification listener registry.\n */\ninterface NotificationListener {\n readonly callback: NotificationCallback;\n readonly filter?: NotificationFilter;\n}\n\n// ---------------------------------------------------------------------------\n// ProtocolEngine\n// ---------------------------------------------------------------------------\n\n/**\n * JSON-RPC 2.0 protocol engine.\n *\n * Manages request/response correlation, timeout handling, notification\n * dispatch, server→client request handling, and error mapping.\n *\n * After construction the engine immediately registers itself on the\n * transport's `onMessage` and `onError` callbacks.\n *\n * @example\n * ```ts\n * const engine = new ProtocolEngine({ transport });\n * const result = await engine.sendRequest(\"droid.list_skills\", {});\n * engine.close();\n * ```\n */\nexport class ProtocolEngine {\n private readonly _transport: DroidClientTransport;\n private readonly _defaultTimeout: number;\n\n /** Pending requests keyed by UUID string. */\n private readonly _pendingRequests = new Map<string, PendingRequest>();\n\n /** Notification listener registry. */\n private readonly _notificationListeners = new Set<NotificationListener>();\n\n /** Server→client request handlers. */\n private _permissionHandler: PermissionHandler | null = null;\n private _askUserHandler: AskUserHandler | null = null;\n\n /** Sticky transport error — once set, all requests fail immediately. */\n private _transportError: Error | null = null;\n\n /** Closed flag — once true, new requests are rejected. */\n private _closed = false;\n\n /**\n * Create a new ProtocolEngine.\n *\n * @param options.transport - A connected DroidClientTransport implementation.\n * @param options.defaultTimeout - Default timeout in ms for sendRequest (default 30 000).\n */\n constructor(options: {\n transport: DroidClientTransport;\n defaultTimeout?: number;\n }) {\n this._transport = options.transport;\n this._defaultTimeout = options.defaultTimeout ?? DEFAULT_REQUEST_TIMEOUT;\n\n // Wire up transport callbacks\n this._transport.onMessage((message: object) => {\n this._handleMessage(message as Record<string, unknown>);\n });\n this._transport.onError((error: Error) => {\n this._handleTransportError(error);\n });\n }\n\n // ------------------------------------------------------------------\n // Public API: Sending requests\n // ------------------------------------------------------------------\n\n /**\n * Send a JSON-RPC request and wait for the response.\n *\n * Constructs the full envelope, registers a pending promise, sends\n * via transport, and returns the parsed response `result` field.\n *\n * @param method - The RPC method name (e.g. `\"droid.list_skills\"`).\n * @param params - Method parameters object.\n * @param timeout - Timeout in ms. Defaults to `defaultTimeout`.\n * @returns The `result` field from the JSON-RPC success response.\n * @throws {ConnectionError} If the engine is closed.\n * @throws {ConnectionError} If the transport has a sticky error.\n * @throws {TimeoutError} If no response arrives within the timeout.\n * @throws {ProtocolError} If the response contains a protocol error.\n * @throws {SessionNotFoundError} If error code is ENTITY_NOT_FOUND.\n */\n async sendRequest(\n method: string,\n params: Record<string, unknown>,\n timeout?: number,\n ): Promise<Record<string, unknown>> {\n // Check closed state\n if (this._closed) {\n throw new ConnectionError(\"Protocol engine is closed\");\n }\n\n // Check sticky transport error\n if (this._transportError !== null) {\n throw new ConnectionError(\n `Transport error: ${this._transportError.message}`,\n );\n }\n\n const effectiveTimeout = timeout ?? this._defaultTimeout;\n const requestId = uuidv4();\n\n // Build envelope\n const envelope: Record<string, unknown> = {\n jsonrpc: JSONRPC_VERSION,\n factoryApiVersion: LEGACY_FACTORY_API_VERSION,\n factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,\n type: \"request\",\n id: requestId,\n method,\n params,\n };\n\n // Create a promise that will be resolved when we get a matching response\n return new Promise<Record<string, unknown>>((resolve, reject) => {\n // Set up timeout\n const timer = setTimeout(() => {\n this._pendingRequests.delete(requestId);\n reject(\n new TimeoutError(\n `Request ${method} timed out after ${effectiveTimeout}ms`,\n ),\n );\n }, effectiveTimeout);\n\n // Store as pending\n const pending: PendingRequest = {\n method,\n requestId,\n params,\n resolve,\n reject,\n timer,\n };\n this._pendingRequests.set(requestId, pending);\n\n // Send via transport\n try {\n this._transport.send(envelope);\n } catch (sendError) {\n // Clean up pending and reject\n clearTimeout(timer);\n this._pendingRequests.delete(requestId);\n if (sendError instanceof Error) {\n reject(\n new ConnectionError(`Failed to send request: ${sendError.message}`),\n );\n } else {\n reject(new ConnectionError(\"Failed to send request\"));\n }\n }\n });\n }\n\n // ------------------------------------------------------------------\n // Public API: Notification listeners\n // ------------------------------------------------------------------\n\n /**\n * Register a callback for incoming notification messages.\n *\n * Multiple listeners can be registered. Each receives the full\n * parsed notification object.\n *\n * @param callback - Invoked with the notification object.\n * @param filter - Optional filter to only receive specific notification types.\n * @returns An unsubscribe function. Calling it again is safe (no-op).\n */\n onNotification(\n callback: NotificationCallback,\n filter?: NotificationFilter,\n ): () => void {\n const listener: NotificationListener = { callback, filter };\n this._notificationListeners.add(listener);\n\n let unsubscribed = false;\n return () => {\n if (!unsubscribed) {\n unsubscribed = true;\n this._notificationListeners.delete(listener);\n }\n };\n }\n\n // ------------------------------------------------------------------\n // Public API: Server→client request handlers\n // ------------------------------------------------------------------\n\n /**\n * Register a handler for server→client permission requests.\n *\n * The handler receives the request params and should return a\n * ToolConfirmationOutcome string value.\n *\n * Replaces any previously registered handler.\n */\n setPermissionHandler(handler: PermissionHandler): void {\n this._permissionHandler = handler;\n }\n\n /**\n * Remove the permission request handler (restores default Cancel).\n */\n clearPermissionHandler(): void {\n this._permissionHandler = null;\n }\n\n /**\n * Register a handler for server→client ask-user requests.\n *\n * The handler receives the request params and should return\n * a result object with `cancelled` and `answers` keys.\n *\n * Replaces any previously registered handler.\n */\n setAskUserHandler(handler: AskUserHandler): void {\n this._askUserHandler = handler;\n }\n\n /**\n * Remove the ask-user request handler (restores default cancelled=true).\n */\n clearAskUserHandler(): void {\n this._askUserHandler = null;\n }\n\n // ------------------------------------------------------------------\n // Public API: Health check\n // ------------------------------------------------------------------\n\n /**\n * Whether the engine is in a healthy state — not closed and no\n * sticky transport error.\n */\n get isHealthy(): boolean {\n return !this._closed && this._transportError === null;\n }\n\n // ------------------------------------------------------------------\n // Public API: Close\n // ------------------------------------------------------------------\n\n /**\n * Close the protocol engine.\n *\n * Rejects all pending requests, closes the transport, and prevents\n * new requests. Idempotent — safe to call multiple times.\n */\n async close(): Promise<void> {\n if (this._closed) {\n return;\n }\n this._closed = true;\n\n // Reject all pending\n const error = new ConnectionError(\n \"Protocol engine closed: pending requests cancelled\",\n );\n this._rejectAllPending(error);\n\n // Clear handlers and listeners\n this._permissionHandler = null;\n this._askUserHandler = null;\n this._notificationListeners.clear();\n\n // Close the transport\n await this._transport.close();\n }\n\n // ------------------------------------------------------------------\n // Internal: Message handling\n // ------------------------------------------------------------------\n\n /**\n * Handle an incoming parsed message from the transport.\n * Dispatches to response handler, notification handler, or\n * server→client request handler based on message type.\n */\n private _handleMessage(parsed: Record<string, unknown>): void {\n const msgType = parsed[\"type\"];\n\n if (msgType === \"response\") {\n this._handleResponse(parsed);\n } else if (msgType === \"notification\") {\n this._handleNotification(parsed);\n } else if (msgType === \"request\") {\n // Server→client request — handle asynchronously\n void this._handleServerRequest(parsed);\n } else {\n // Fallback detection by content\n if (\"result\" in parsed || \"error\" in parsed) {\n this._handleResponse(parsed);\n } else if (\"method\" in parsed && !(\"id\" in parsed)) {\n this._handleNotification(parsed);\n } else if (\"method\" in parsed && \"id\" in parsed) {\n void this._handleServerRequest(parsed);\n }\n // else: unknown format — silently ignore\n }\n }\n\n /**\n * Handle an incoming response message.\n * Matches by ID to resolve the correct pending Promise.\n */\n private _handleResponse(response: Record<string, unknown>): void {\n const responseId = response[\"id\"] as string | null | undefined;\n\n // Null-id error response — log but don't crash\n if (responseId == null) {\n return;\n }\n\n const pending = this._pendingRequests.get(responseId);\n\n if (pending == null) {\n // Unknown response ID — already timed out or duplicate\n return;\n }\n\n // Remove from pending and clear its timeout\n this._pendingRequests.delete(responseId);\n clearTimeout(pending.timer);\n\n // Check for error response and map to exceptions\n const errorObj = response[\"error\"];\n if (errorObj != null && typeof errorObj === \"object\") {\n const error = errorObj as Record<string, unknown>;\n const code = error[\"code\"] as number | undefined;\n const message = (error[\"message\"] as string) ?? \"Unknown error\";\n const data = error[\"data\"];\n\n if (code === JsonRpcErrorCode.ENTITY_NOT_FOUND) {\n // Extract sessionId from the original request params\n const sessionId = String(\n pending.params[\"sessionId\"] ?? pending.requestId,\n );\n pending.reject(new SessionNotFoundError(sessionId));\n return;\n }\n\n pending.reject(new ProtocolError(message, { code, data }));\n return;\n }\n\n // Resolve with the full response\n pending.resolve(response as Record<string, unknown>);\n }\n\n /**\n * Handle an incoming notification message.\n * Dispatches to all registered notification listeners that match.\n */\n private _handleNotification(notification: Record<string, unknown>): void {\n // Extract the notification type for filtering\n const params = notification[\"params\"] as Record<string, unknown> | undefined;\n const innerNotification = params?.[\"notification\"] as\n | Record<string, unknown>\n | undefined;\n const notificationType = innerNotification?.[\"type\"] as string | undefined;\n\n for (const listener of this._notificationListeners) {\n // Apply type filter if present\n if (\n listener.filter?.type != null &&\n listener.filter.type !== notificationType\n ) {\n continue;\n }\n\n try {\n listener.callback(notification);\n } catch {\n // Notification listener raised — don't crash the engine\n }\n }\n }\n\n /**\n * Handle an incoming server→client request.\n * Dispatches to the appropriate handler based on the method field.\n */\n private async _handleServerRequest(\n request: Record<string, unknown>,\n ): Promise<void> {\n const method = request[\"method\"] as string;\n const requestId = request[\"id\"] as string;\n const params = (request[\"params\"] as Record<string, unknown>) ?? {};\n\n if (method === DroidClientMethod.REQUEST_PERMISSION) {\n await this._handlePermissionRequest(requestId, params);\n } else if (method === DroidClientMethod.ASK_USER) {\n await this._handleAskUserRequest(requestId, params);\n }\n // Unknown server→client methods are silently ignored\n }\n\n /**\n * Handle droid.request_permission server→client request.\n */\n private async _handlePermissionRequest(\n requestId: string,\n params: Record<string, unknown>,\n ): Promise<void> {\n const handler = this._permissionHandler;\n\n if (handler == null) {\n // Default: Cancel\n this._sendResponse(requestId, { selectedOption: \"cancel\" });\n return;\n }\n\n try {\n const selectedOption = await Promise.resolve(handler(params));\n this._sendResponse(requestId, { selectedOption });\n } catch (exc) {\n const errorMessage =\n exc instanceof Error ? exc.message : String(exc);\n this._sendErrorResponse(\n requestId,\n JsonRpcErrorCode.INTERNAL_ERROR,\n \"Failed to handle permission request\",\n errorMessage,\n );\n }\n }\n\n /**\n * Handle droid.ask_user server→client request.\n */\n private async _handleAskUserRequest(\n requestId: string,\n params: Record<string, unknown>,\n ): Promise<void> {\n const handler = this._askUserHandler;\n\n if (handler == null) {\n // Default: cancelled=true\n this._sendResponse(requestId, { cancelled: true, answers: [] });\n return;\n }\n\n try {\n const result = await Promise.resolve(handler(params));\n this._sendResponse(requestId, result);\n } catch (exc) {\n const errorMessage =\n exc instanceof Error ? exc.message : String(exc);\n this._sendErrorResponse(\n requestId,\n JsonRpcErrorCode.INTERNAL_ERROR,\n \"Failed to handle ask-user request\",\n errorMessage,\n );\n }\n }\n\n // ------------------------------------------------------------------\n // Internal: Transport error handling\n // ------------------------------------------------------------------\n\n /**\n * Handle a transport error.\n * Sets the sticky transport error and rejects all pending requests.\n * The original error is preserved as `cause` on the ConnectionError.\n */\n private _handleTransportError(error: Error): void {\n this._transportError = error;\n const connectionError = new ConnectionError(\n `Transport error: ${error.message}`,\n );\n connectionError.cause = error;\n this._rejectAllPending(connectionError);\n }\n\n // ------------------------------------------------------------------\n // Internal: Response helpers\n // ------------------------------------------------------------------\n\n /**\n * Send a JSON-RPC success response back to the server.\n */\n private _sendResponse(\n requestId: string,\n result: Record<string, unknown>,\n ): void {\n const response: Record<string, unknown> = {\n jsonrpc: JSONRPC_VERSION,\n factoryApiVersion: LEGACY_FACTORY_API_VERSION,\n factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,\n type: \"response\",\n id: requestId,\n result,\n };\n try {\n this._transport.send(response);\n } catch {\n // Failed to send response — log but don't crash\n }\n }\n\n /**\n * Send a JSON-RPC error response back to the server.\n */\n private _sendErrorResponse(\n requestId: string,\n code: number,\n message: string,\n data?: unknown,\n ): void {\n const errorObj: Record<string, unknown> = { code, message };\n if (data !== undefined) {\n errorObj[\"data\"] = data;\n }\n\n const response: Record<string, unknown> = {\n jsonrpc: JSONRPC_VERSION,\n factoryApiVersion: LEGACY_FACTORY_API_VERSION,\n factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,\n type: \"response\",\n id: requestId,\n error: errorObj,\n };\n try {\n this._transport.send(response);\n } catch {\n // Failed to send error response — don't crash\n }\n }\n\n /**\n * Reject all pending requests with the given error.\n */\n private _rejectAllPending(error: Error): void {\n const pending = new Map(this._pendingRequests);\n this._pendingRequests.clear();\n\n for (const req of pending.values()) {\n clearTimeout(req.timer);\n req.reject(error);\n }\n }\n}\n","/**\n * DroidClient — high-level typed client for the Factory Droid SDK.\n *\n * Wraps a {@link ProtocolEngine} and provides typed async methods for all\n * 19 `droid.*` JSON-RPC methods, notification subscription with type\n * filtering, and permission/ask-user handler registration.\n *\n * Built on top of the `ProtocolEngine` and a `DroidClientTransport`\n * implementation.\n */\n\nimport { ConnectionError, SessionError } from \"./errors.js\";\nimport {\n ProtocolEngine,\n type NotificationCallback,\n type NotificationFilter,\n} from \"./protocol.js\";\nimport { DroidServerMethod } from \"./schemas/enums.js\";\nimport {\n MCP_AUTH_TIMEOUT,\n SESSION_INIT_TIMEOUT,\n} from \"./schemas/constants.js\";\nimport type {\n AddMcpServerRequestParams,\n AddMcpServerResult,\n AddUserMessageRequestParams,\n AddUserMessageResult,\n AuthenticateMcpServerRequestParams,\n AuthenticateMcpServerResult,\n CancelMcpAuthRequestParams,\n CancelMcpAuthResult,\n ClearMcpAuthRequestParams,\n ClearMcpAuthResult,\n InitializeSessionRequestParams,\n InitializeSessionResult,\n InterruptSessionResult,\n KillWorkerSessionRequestParams,\n KillWorkerSessionResult,\n ListMcpRegistryResult,\n ListMcpServersResult,\n ListMcpToolsResult,\n ListSkillsResult,\n LoadSessionRequestParams,\n LoadSessionResult,\n RemoveMcpServerRequestParams,\n RemoveMcpServerResult,\n SubmitBugReportRequestParams,\n SubmitBugReportResult,\n SubmitMcpAuthCodeRequestParams,\n SubmitMcpAuthCodeResult,\n ToggleMcpServerRequestParams,\n ToggleMcpServerResult,\n ToggleMcpToolRequestParams,\n ToggleMcpToolResult,\n UpdateSessionSettingsRequestParams,\n UpdateSessionSettingsResult,\n} from \"./schemas/client.js\";\nimport type { DroidClientTransport } from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * Handler for server→client permission requests at the client level.\n * Receives the full request params and returns a ToolConfirmationOutcome string.\n */\nexport type ClientPermissionHandler = (\n params: Record<string, unknown>,\n) => string | Promise<string>;\n\n/**\n * Handler for server→client ask-user requests at the client level.\n * Receives the full request params and returns a result object.\n */\nexport type ClientAskUserHandler = (\n params: Record<string, unknown>,\n) => Record<string, unknown> | Promise<Record<string, unknown>>;\n\n/**\n * Options for constructing a DroidClient.\n */\nexport interface DroidClientOptions {\n /** A connected DroidClientTransport implementation. */\n transport: DroidClientTransport;\n\n /** Default request timeout in ms. Defaults to 30 000. */\n defaultTimeout?: number;\n}\n\n// ---------------------------------------------------------------------------\n// DroidClient\n// ---------------------------------------------------------------------------\n\n/**\n * High-level typed client for the Factory Droid SDK.\n *\n * Provides async methods for all 19 `droid.*` JSON-RPC operations,\n * notification subscription with optional type filtering, and handler\n * registration for server→client requests (permissions, ask-user).\n *\n * @example\n * ```ts\n * const transport = new InMemoryTransport();\n * await transport.connect();\n * const client = new DroidClient({ transport });\n *\n * const result = await client.initializeSession({\n * machineId: \"test\",\n * cwd: \"/tmp\",\n * });\n *\n * await client.close();\n * ```\n */\nexport class DroidClient {\n private readonly _engine: ProtocolEngine;\n private _sessionId: string | null = null;\n private _closed = false;\n\n /**\n * Client-level notification listeners.\n * Each entry is [callback, optional type filter string].\n */\n private readonly _notificationListeners: Array<{\n callback: NotificationCallback;\n typeFilter?: string;\n }> = [];\n\n /** Client-level permission handler. */\n private _permissionHandler: ClientPermissionHandler | null = null;\n\n /** Client-level ask-user handler. */\n private _askUserHandler: ClientAskUserHandler | null = null;\n\n constructor(options: DroidClientOptions) {\n this._engine = new ProtocolEngine({\n transport: options.transport,\n defaultTimeout: options.defaultTimeout,\n });\n\n // Wire up protocol engine's notification dispatch to client-level listeners\n this._engine.onNotification((notification) => {\n this._dispatchNotification(notification);\n });\n\n // Wire up protocol engine's server→client request handlers\n // to client-level dispatch methods\n this._engine.setPermissionHandler((params) =>\n this._dispatchPermissionRequest(params),\n );\n this._engine.setAskUserHandler((params) =>\n this._dispatchAskUserRequest(params),\n );\n }\n\n // ------------------------------------------------------------------\n // Properties\n // ------------------------------------------------------------------\n\n /**\n * Current session ID, or `null` if no session is active.\n */\n get sessionId(): string | null {\n return this._sessionId;\n }\n\n /**\n * Whether the client is in a healthy state — not closed and no\n * transport errors have occurred. Returns false after transport\n * disconnect/error.\n */\n get isConnected(): boolean {\n return !this._closed && this._engine.isHealthy;\n }\n\n // ------------------------------------------------------------------\n // Session lifecycle methods\n // ------------------------------------------------------------------\n\n /**\n * Initialize a new session.\n *\n * Sends `droid.initialize_session` with extended timeout. On success,\n * stores the session ID internally and returns the typed result.\n */\n async initializeSession(\n params: InitializeSessionRequestParams,\n ): Promise<InitializeSessionResult> {\n this._ensureNotClosed();\n\n const response = await this._engine.sendRequest(\n DroidServerMethod.INITIALIZE_SESSION,\n params as unknown as Record<string, unknown>,\n SESSION_INIT_TIMEOUT,\n );\n\n const result = (response as Record<string, unknown>)[\"result\"] as\n | InitializeSessionResult\n | undefined;\n if (result) {\n this._sessionId = result.sessionId;\n return result;\n }\n\n // If the response has the result at top level (protocol engine returns full response)\n if (\"sessionId\" in response) {\n this._sessionId = (response as Record<string, unknown>)[\n \"sessionId\"\n ] as string;\n return response as unknown as InitializeSessionResult;\n }\n\n return response as unknown as InitializeSessionResult;\n }\n\n /**\n * Load an existing session.\n *\n * Sends `droid.load_session`. SessionNotFoundError is thrown for\n * non-existent sessions (mapped from ENTITY_NOT_FOUND by the protocol engine).\n */\n async loadSession(\n params: LoadSessionRequestParams,\n ): Promise<LoadSessionResult> {\n this._ensureNotClosed();\n\n const response = await this._engine.sendRequest(\n DroidServerMethod.LOAD_SESSION,\n params as unknown as Record<string, unknown>,\n SESSION_INIT_TIMEOUT,\n );\n\n const result = (response as Record<string, unknown>)[\"result\"] as\n | LoadSessionResult\n | undefined;\n if (result) {\n this._sessionId = params.sessionId;\n return result;\n }\n\n this._sessionId = params.sessionId;\n return response as unknown as LoadSessionResult;\n }\n\n /**\n * Add a user message to the active session.\n *\n * Sends `droid.add_user_message` with text and optional images/files.\n */\n async addUserMessage(\n params: Pick<AddUserMessageRequestParams, \"text\"> &\n Partial<Pick<AddUserMessageRequestParams, \"images\" | \"files\" | \"messageId\">>,\n ): Promise<AddUserMessageResult> {\n this._ensureNotClosed();\n this._ensureSession();\n\n const response = await this._engine.sendRequest(\n DroidServerMethod.ADD_USER_MESSAGE,\n params as unknown as Record<string, unknown>,\n );\n\n const result = (response as Record<string, unknown>)[\"result\"];\n return (result ?? response) as unknown as AddUserMessageResult;\n }\n\n /**\n * Interrupt the current session.\n *\n * Sends `droid.interrupt_session` with empty params.\n */\n async interruptSession(): Promise<InterruptSessionResult> {\n this._ensureNotClosed();\n this._ensureSession();\n\n const response = await this._engine.sendRequest(\n DroidServerMethod.INTERRUPT_SESSION,\n {},\n );\n\n const result = (response as Record<string, unknown>)[\"result\"];\n return (result ?? response) as unknown as InterruptSessionResult;\n }\n\n /**\n * Kill a worker session.\n *\n * Sends `droid.kill_worker_session`.\n */\n async killWorkerSession(\n params: KillWorkerSessionRequestParams,\n ): Promise<KillWorkerSessionResult> {\n this._ensureNotClosed();\n this._ensureSession();\n\n const response = await this._engine.sendRequest(\n DroidServerMethod.KILL_WORKER_SESSION,\n params as unknown as Record<string, unknown>,\n );\n\n const result = (response as Record<string, unknown>)[\"result\"];\n return (result ?? response) as unknown as KillWorkerSessionResult;\n }\n\n /**\n * Update session settings.\n *\n * Sends `droid.update_session_settings` with the provided partial settings.\n */\n async updateSessionSettings(\n params: Partial<UpdateSessionSettingsRequestParams>,\n ): Promise<UpdateSessionSettingsResult> {\n this._ensureNotClosed();\n this._ensureSession();\n\n const response = await this._engine.sendRequest(\n DroidServerMethod.UPDATE_SESSION_SETTINGS,\n params as unknown as Record<string, unknown>,\n );\n\n const result = (response as Record<string, unknown>)[\"result\"];\n return (result ?? response) as unknown as UpdateSessionSettingsResult;\n }\n\n // ------------------------------------------------------------------\n // MCP methods\n // ------------------------------------------------------------------\n\n /**\n * Toggle an MCP server on or off.\n */\n async toggleMcpServer(\n params: ToggleMcpServerRequestParams,\n ): Promise<ToggleMcpServerResult> {\n this._ensureNotClosed();\n this._ensureSession();\n\n const response = await this._engine.sendRequest(\n DroidServerMethod.TOGGLE_MCP_SERVER,\n params as unknown as Record<string, unknown>,\n );\n\n const result = (response as Record<string, unknown>)[\"result\"];\n return (result ?? response) as unknown as ToggleMcpServerResult;\n }\n\n /**\n * Authenticate an MCP server (OAuth flow).\n * Uses extended timeout (300s) since OAuth requires user interaction.\n */\n async authenticateMcpServer(\n params: AuthenticateMcpServerRequestParams,\n ): Promise<AuthenticateMcpServerResult> {\n this._ensureNotClosed();\n this._ensureSession();\n\n const response = await this._engine.sendRequest(\n DroidServerMethod.AUTHENTICATE_MCP_SERVER,\n params as unknown as Record<string, unknown>,\n MCP_AUTH_TIMEOUT,\n );\n\n const result = (response as Record<string, unknown>)[\"result\"];\n return (result ?? response) as unknown as AuthenticateMcpServerResult;\n }\n\n /**\n * Cancel an in-progress MCP authentication.\n */\n async cancelMcpAuth(\n params: CancelMcpAuthRequestParams,\n ): Promise<CancelMcpAuthResult> {\n this._ensureNotClosed();\n this._ensureSession();\n\n const response = await this._engine.sendRequest(\n DroidServerMethod.CANCEL_MCP_AUTH,\n params as unknown as Record<string, unknown>,\n );\n\n const result = (response as Record<string, unknown>)[\"result\"];\n return (result ?? response) as unknown as CancelMcpAuthResult;\n }\n\n /**\n * Clear stored MCP authentication tokens.\n */\n async clearMcpAuth(\n params: ClearMcpAuthRequestParams,\n ): Promise<ClearMcpAuthResult> {\n this._ensureNotClosed();\n this._ensureSession();\n\n const response = await this._engine.sendRequest(\n DroidServerMethod.CLEAR_MCP_AUTH,\n params as unknown as Record<string, unknown>,\n );\n\n const result = (response as Record<string, unknown>)[\"result\"];\n return (result ?? response) as unknown as ClearMcpAuthResult;\n }\n\n /**\n * Submit an MCP authentication code (OAuth callback).\n */\n async submitMcpAuthCode(\n params: SubmitMcpAuthCodeRequestParams,\n ): Promise<SubmitMcpAuthCodeResult> {\n this._ensureNotClosed();\n this._ensureSession();\n\n const response = await this._engine.sendRequest(\n DroidServerMethod.SUBMIT_MCP_AUTH_CODE,\n params as unknown as Record<string, unknown>,\n );\n\n const result = (response as Record<string, unknown>)[\"result\"];\n return (result ?? response) as unknown as SubmitMcpAuthCodeResult;\n }\n\n /**\n * Add an MCP server.\n */\n async addMcpServer(\n params: AddMcpServerRequestParams,\n ): Promise<AddMcpServerResult> {\n this._ensureNotClosed();\n this._ensureSession();\n\n const response = await this._engine.sendRequest(\n DroidServerMethod.ADD_MCP_SERVER,\n params as unknown as Record<string, unknown>,\n );\n\n const result = (response as Record<string, unknown>)[\"result\"];\n return (result ?? response) as unknown as AddMcpServerResult;\n }\n\n /**\n * Remove an MCP server.\n */\n async removeMcpServer(\n params: RemoveMcpServerRequestParams,\n ): Promise<RemoveMcpServerResult> {\n this._ensureNotClosed();\n this._ensureSession();\n\n const response = await this._engine.sendRequest(\n DroidServerMethod.REMOVE_MCP_SERVER,\n params as unknown as Record<string, unknown>,\n );\n\n const result = (response as Record<string, unknown>)[\"result\"];\n return (result ?? response) as unknown as RemoveMcpServerResult;\n }\n\n /**\n * List available MCP registry servers.\n */\n async listMcpRegistry(): Promise<ListMcpRegistryResult> {\n this._ensureNotClosed();\n this._ensureSession();\n\n const response = await this._engine.sendRequest(\n DroidServerMethod.LIST_MCP_REGISTRY,\n {},\n );\n\n const result = (response as Record<string, unknown>)[\"result\"];\n return (result ?? response) as unknown as ListMcpRegistryResult;\n }\n\n /**\n * List available MCP tools.\n */\n async listMcpTools(): Promise<ListMcpToolsResult> {\n this._ensureNotClosed();\n this._ensureSession();\n\n const response = await this._engine.sendRequest(\n DroidServerMethod.LIST_MCP_TOOLS,\n {},\n );\n\n const result = (response as Record<string, unknown>)[\"result\"];\n return (result ?? response) as unknown as ListMcpToolsResult;\n }\n\n /**\n * List MCP servers with status and summary.\n */\n async listMcpServers(): Promise<ListMcpServersResult> {\n this._ensureNotClosed();\n this._ensureSession();\n\n const response = await this._engine.sendRequest(\n DroidServerMethod.LIST_MCP_SERVERS,\n {},\n );\n\n const result = (response as Record<string, unknown>)[\"result\"];\n return (result ?? response) as unknown as ListMcpServersResult;\n }\n\n /**\n * Toggle an MCP tool on or off.\n */\n async toggleMcpTool(\n params: ToggleMcpToolRequestParams,\n ): Promise<ToggleMcpToolResult> {\n this._ensureNotClosed();\n this._ensureSession();\n\n const response = await this._engine.sendRequest(\n DroidServerMethod.TOGGLE_MCP_TOOL,\n params as unknown as Record<string, unknown>,\n );\n\n const result = (response as Record<string, unknown>)[\"result\"];\n return (result ?? response) as unknown as ToggleMcpToolResult;\n }\n\n // ------------------------------------------------------------------\n // Skills and bug report methods\n // ------------------------------------------------------------------\n\n /**\n * List available skills.\n */\n async listSkills(): Promise<ListSkillsResult> {\n this._ensureNotClosed();\n this._ensureSession();\n\n const response = await this._engine.sendRequest(\n DroidServerMethod.LIST_SKILLS,\n {},\n );\n\n const result = (response as Record<string, unknown>)[\"result\"];\n return (result ?? response) as unknown as ListSkillsResult;\n }\n\n /**\n * Submit a bug report.\n */\n async submitBugReport(\n params: SubmitBugReportRequestParams,\n ): Promise<SubmitBugReportResult> {\n this._ensureNotClosed();\n this._ensureSession();\n\n const response = await this._engine.sendRequest(\n DroidServerMethod.SUBMIT_BUG_REPORT,\n params as unknown as Record<string, unknown>,\n );\n\n const result = (response as Record<string, unknown>)[\"result\"];\n return (result ?? response) as unknown as SubmitBugReportResult;\n }\n\n // ------------------------------------------------------------------\n // Notification subscription\n // ------------------------------------------------------------------\n\n /**\n * Register a callback for incoming notification messages.\n *\n * Multiple listeners can be registered. Each receives the full parsed\n * notification object. Optionally filter by notification type.\n *\n * Listener exceptions are isolated — if one raises, others still receive\n * the event and the engine continues.\n *\n * @param callback - Invoked with the notification object.\n * @param filter - Optional filter to only receive specific notification types.\n * @returns An unsubscribe function. Calling it again is safe (no-op).\n */\n onNotification(\n callback: NotificationCallback,\n filter?: NotificationFilter,\n ): () => void {\n const entry = {\n callback,\n typeFilter: filter?.type,\n };\n this._notificationListeners.push(entry);\n\n let unsubscribed = false;\n return () => {\n if (!unsubscribed) {\n unsubscribed = true;\n const idx = this._notificationListeners.indexOf(entry);\n if (idx !== -1) {\n this._notificationListeners.splice(idx, 1);\n }\n }\n };\n }\n\n // ------------------------------------------------------------------\n // Permission/ask-user handler registration\n // ------------------------------------------------------------------\n\n /**\n * Register a handler for server→client permission requests.\n *\n * The handler receives the request params and should return a\n * ToolConfirmationOutcome string value. Async handlers are awaited.\n * Replaces any previously registered handler.\n */\n setPermissionHandler(handler: ClientPermissionHandler): void {\n this._permissionHandler = handler;\n }\n\n /**\n * Remove the permission request handler.\n * Restores default behavior: return \"cancel\".\n */\n clearPermissionHandler(): void {\n this._permissionHandler = null;\n }\n\n /**\n * Register a handler for server→client ask-user requests.\n *\n * The handler receives the request params and should return a result\n * object with `cancelled` and `answers` keys. Async handlers are awaited.\n * Replaces any previously registered handler.\n */\n setAskUserHandler(handler: ClientAskUserHandler): void {\n this._askUserHandler = handler;\n }\n\n /**\n * Remove the ask-user request handler.\n * Restores default behavior: return `{ cancelled: true, answers: [] }`.\n */\n clearAskUserHandler(): void {\n this._askUserHandler = null;\n }\n\n // ------------------------------------------------------------------\n // Lifecycle\n // ------------------------------------------------------------------\n\n /**\n * Close the client and release all resources.\n *\n * Rejects pending requests, clears handlers and listeners, and closes\n * the protocol engine. Idempotent — safe to call multiple times.\n *\n * After close, all method calls throw ConnectionError immediately.\n */\n async close(): Promise<void> {\n if (this._closed) {\n return;\n }\n this._closed = true;\n\n // Clear client-level state\n this._notificationListeners.length = 0;\n this._permissionHandler = null;\n this._askUserHandler = null;\n\n // Close the protocol engine (which closes the transport)\n await this._engine.close();\n }\n\n // ------------------------------------------------------------------\n // Internal: dispatch methods\n // ------------------------------------------------------------------\n\n /**\n * Dispatch a notification to all registered client-level listeners.\n * Filters by notification type if a type filter is set.\n * Exception in one listener does not affect others.\n */\n private _dispatchNotification(notification: Record<string, unknown>): void {\n // Extract the notification type from the payload\n const params = notification[\"params\"] as\n | Record<string, unknown>\n | undefined;\n const innerNotification = params?.[\"notification\"] as\n | Record<string, unknown>\n | undefined;\n const notificationType = innerNotification?.[\"type\"] as string | undefined;\n\n // Iterate over a copy in case listeners unsubscribe during iteration\n const listeners = [...this._notificationListeners];\n for (const listener of listeners) {\n // Apply type filter if present\n if (\n listener.typeFilter != null &&\n listener.typeFilter !== notificationType\n ) {\n continue;\n }\n\n try {\n listener.callback(notification);\n } catch {\n // Notification listener raised — don't crash the client\n }\n }\n }\n\n /**\n * Dispatch to the client-level permission handler.\n * If no handler is set, returns the default \"cancel\" outcome.\n * If handler throws, the error propagates to the protocol engine\n * which sends an error response.\n */\n private _dispatchPermissionRequest(\n params: Record<string, unknown>,\n ): string | Promise<string> {\n const handler = this._permissionHandler;\n if (handler == null) {\n return \"cancel\";\n }\n return handler(params);\n }\n\n /**\n * Dispatch to the client-level ask-user handler.\n * If no handler is set, returns the default cancelled response.\n * If handler throws, the error propagates to the protocol engine\n * which sends an error response.\n */\n private _dispatchAskUserRequest(\n params: Record<string, unknown>,\n ): Record<string, unknown> | Promise<Record<string, unknown>> {\n const handler = this._askUserHandler;\n if (handler == null) {\n return { cancelled: true, answers: [] };\n }\n return handler(params);\n }\n\n // ------------------------------------------------------------------\n // Internal: guards\n // ------------------------------------------------------------------\n\n /**\n * Throw ConnectionError if the client has been closed.\n */\n private _ensureNotClosed(): void {\n if (this._closed) {\n throw new ConnectionError(\n \"Client has been closed. Create a new DroidClient instance to reconnect.\",\n );\n }\n }\n\n /**\n * Throw SessionError if no active session.\n */\n private _ensureSession(): void {\n if (this._sessionId == null) {\n throw new SessionError(\n \"No active session. Call initializeSession or loadSession first.\",\n );\n }\n }\n}\n","/**\n * Typed stream message interfaces and notification-to-stream converter.\n *\n * Defines 22 DroidMessage types as TypeScript interfaces with a discriminated\n * `type` field, plus a notification converter and working-state tracker for\n * TurnComplete emission.\n *\n * Reference: Python SDK stream.py\n */\n\nimport type {\n McpServerStatusInfo,\n McpStatusSummary,\n MissionFeature,\n ProgressLogEntry,\n SettingsUpdatedPayload,\n TokenUsage,\n ToolProgressUpdate,\n} from \"./schemas/index.js\";\n\nimport {\n DroidWorkingState,\n McpAuthOutcome,\n MissionState,\n SessionNotificationType,\n ToolConfirmationOutcome,\n} from \"./schemas/index.js\";\n\n// ---------------------------------------------------------------------------\n// 22 DroidMessage interfaces — discriminated on `type`\n// ---------------------------------------------------------------------------\n\n/** A delta of assistant-generated text (streaming token). */\nexport interface AssistantTextDelta {\n readonly type: \"assistant_text_delta\";\n readonly messageId: string;\n readonly blockIndex: number;\n readonly text: string;\n}\n\n/** A delta of assistant thinking/reasoning text. */\nexport interface ThinkingTextDelta {\n readonly type: \"thinking_text_delta\";\n readonly messageId: string;\n readonly blockIndex: number;\n readonly text: string;\n}\n\n/** A tool invocation issued by the assistant (from create_message). */\nexport interface ToolUse {\n readonly type: \"tool_use\";\n readonly toolName: string;\n readonly toolInput: Record<string, unknown>;\n readonly toolUseId: string;\n}\n\n/** The result returned from a tool execution. */\nexport interface ToolResult {\n readonly type: \"tool_result\";\n readonly toolUseId: string;\n readonly content: string | unknown[];\n readonly isError: boolean;\n}\n\n/** A streaming progress update from a tool execution. */\nexport interface ToolProgress {\n readonly type: \"tool_progress\";\n readonly toolUseId: string;\n readonly toolName: string;\n readonly content: string;\n readonly update: ToolProgressUpdate;\n}\n\n/** The droid working state has changed. */\nexport interface WorkingStateChanged {\n readonly type: \"working_state_changed\";\n readonly state: DroidWorkingState;\n}\n\n/** Updated token usage counters for the session. */\nexport interface TokenUsageUpdate {\n readonly type: \"token_usage_update\";\n readonly inputTokens: number;\n readonly outputTokens: number;\n readonly cacheReadTokens: number;\n readonly cacheWriteTokens: number;\n readonly thinkingTokens: number;\n}\n\n/** A full assistant message was created (may contain tool_use blocks). */\nexport interface CreateMessage {\n readonly type: \"create_message\";\n readonly messageId: string;\n readonly role: string;\n readonly content: unknown[];\n readonly parentId?: string;\n}\n\n/** A permission request was resolved. */\nexport interface PermissionResolved {\n readonly type: \"permission_resolved\";\n readonly requestId: string;\n readonly toolUseIds: string[];\n readonly selectedOption: ToolConfirmationOutcome;\n}\n\n/** Session settings were updated. */\nexport interface SettingsUpdated {\n readonly type: \"settings_updated\";\n readonly settings: SettingsUpdatedPayload;\n}\n\n/** The session title was updated. */\nexport interface SessionTitleUpdated {\n readonly type: \"session_title_updated\";\n readonly title: string;\n}\n\n/** MCP server status changed. */\nexport interface McpStatusChanged {\n readonly type: \"mcp_status_changed\";\n readonly servers: McpServerStatusInfo[];\n readonly summary: McpStatusSummary;\n}\n\n/** Mission state changed. */\nexport interface MissionStateChanged {\n readonly type: \"mission_state_changed\";\n readonly state: MissionState;\n}\n\n/** Mission features changed. */\nexport interface MissionFeaturesChanged {\n readonly type: \"mission_features_changed\";\n readonly features: MissionFeature[];\n}\n\n/** Mission progress entry. */\nexport interface MissionProgressEntry {\n readonly type: \"mission_progress_entry\";\n readonly progressLog: ProgressLogEntry[];\n}\n\n/** Mission heartbeat. */\nexport interface MissionHeartbeat {\n readonly type: \"mission_heartbeat\";\n readonly timestamp: string;\n}\n\n/** A mission worker started. */\nexport interface MissionWorkerStarted {\n readonly type: \"mission_worker_started\";\n readonly workerSessionId: string;\n}\n\n/** A mission worker completed. */\nexport interface MissionWorkerCompleted {\n readonly type: \"mission_worker_completed\";\n readonly workerSessionId: string;\n readonly exitCode: number;\n}\n\n/** MCP authentication is required. */\nexport interface McpAuthRequired {\n readonly type: \"mcp_auth_required\";\n readonly serverName: string;\n readonly authUrl: string;\n readonly message: string;\n readonly state: string;\n}\n\n/** MCP authentication completed. */\nexport interface McpAuthCompleted {\n readonly type: \"mcp_auth_completed\";\n readonly serverName: string;\n readonly outcome: McpAuthOutcome;\n readonly message: string;\n}\n\n/** An error event from the droid process. */\nexport interface ErrorEvent {\n readonly type: \"error\";\n readonly message: string;\n readonly errorType: string;\n readonly timestamp: string;\n}\n\n/** Sentinel yielded when the agent turn finishes (returns to Idle). */\nexport interface TurnComplete {\n readonly type: \"turn_complete\";\n readonly tokenUsage: TokenUsageUpdate | null;\n}\n\n// ---------------------------------------------------------------------------\n// DroidMessage union\n// ---------------------------------------------------------------------------\n\n/** Discriminated union of all 22 stream message types. */\nexport type DroidMessage =\n | AssistantTextDelta\n | ThinkingTextDelta\n | ToolUse\n | ToolResult\n | ToolProgress\n | WorkingStateChanged\n | TokenUsageUpdate\n | CreateMessage\n | PermissionResolved\n | SettingsUpdated\n | SessionTitleUpdated\n | McpStatusChanged\n | MissionStateChanged\n | MissionFeaturesChanged\n | MissionProgressEntry\n | MissionHeartbeat\n | MissionWorkerStarted\n | MissionWorkerCompleted\n | McpAuthRequired\n | McpAuthCompleted\n | ErrorEvent\n | TurnComplete;\n\n// ---------------------------------------------------------------------------\n// Notification payload type (matches SessionNotificationPayload)\n// ---------------------------------------------------------------------------\n\n/**\n * A notification payload object as received from the protocol layer.\n * Must have at least a `type` string field. Other properties are\n * notification-type-specific.\n */\ninterface NotificationPayload {\n type: string;\n [key: string]: unknown;\n}\n\n// ---------------------------------------------------------------------------\n// Converter: notification → DroidMessage(s)\n// ---------------------------------------------------------------------------\n\n/**\n * Convert a server session notification payload to the corresponding\n * DroidMessage(s).\n *\n * For `create_message` notifications containing tool_use content blocks,\n * a list of ToolUse messages is returned (one per tool_use block), followed\n * by a single CreateMessage. For all other notification types a single\n * DroidMessage is returned, or `null` if the notification type is unknown.\n *\n * Unknown notification types return `null` and log a warning to the console.\n *\n * @param notification - A notification payload from `SessionNotification.params.notification`.\n * @returns A single DroidMessage, an array of DroidMessages, or `null` for unknown types.\n */\nexport function convertNotificationToStreamMessage(\n notification: NotificationPayload,\n): DroidMessage | DroidMessage[] | null {\n switch (notification.type) {\n case SessionNotificationType.ASSISTANT_TEXT_DELTA:\n return {\n type: \"assistant_text_delta\",\n messageId: notification.messageId as string,\n blockIndex: notification.blockIndex as number,\n text: notification.textDelta as string,\n };\n\n case SessionNotificationType.THINKING_TEXT_DELTA:\n return {\n type: \"thinking_text_delta\",\n messageId: notification.messageId as string,\n blockIndex: notification.blockIndex as number,\n text: notification.textDelta as string,\n };\n\n case SessionNotificationType.TOOL_RESULT:\n return {\n type: \"tool_result\",\n toolUseId: notification.toolUseId as string,\n content: normalizeToolResultContent(notification.content),\n isError: Boolean(notification.isError),\n };\n\n case SessionNotificationType.TOOL_PROGRESS_UPDATE: {\n const update = notification.update as ToolProgressUpdate;\n const text = update?.text ?? update?.status ?? update?.details ?? \"\";\n return {\n type: \"tool_progress\",\n toolUseId: notification.toolUseId as string,\n toolName: notification.toolName as string,\n content: text,\n update,\n };\n }\n\n case SessionNotificationType.DROID_WORKING_STATE_CHANGED:\n return {\n type: \"working_state_changed\",\n state: notification.newState as DroidWorkingState,\n };\n\n case SessionNotificationType.SESSION_TOKEN_USAGE_CHANGED: {\n const tu = notification.tokenUsage as TokenUsage;\n return {\n type: \"token_usage_update\",\n inputTokens: tu.inputTokens,\n outputTokens: tu.outputTokens,\n cacheReadTokens: tu.cacheReadTokens,\n cacheWriteTokens: tu.cacheCreationTokens,\n thinkingTokens: tu.thinkingTokens,\n };\n }\n\n case SessionNotificationType.CREATE_MESSAGE: {\n const msg = notification.message as {\n id: string;\n role: string;\n content: Array<{ type: string; id?: string; name?: string; input?: Record<string, unknown>; [key: string]: unknown }>;\n };\n const messages: DroidMessage[] = [];\n\n // Extract ToolUse messages from tool_use content blocks\n if (msg.content && Array.isArray(msg.content)) {\n for (const block of msg.content) {\n if (block.type === \"tool_use\") {\n messages.push({\n type: \"tool_use\",\n toolName: block.name as string,\n toolInput: (block.input ?? {}) as Record<string, unknown>,\n toolUseId: block.id as string,\n });\n }\n }\n }\n\n // Always emit CreateMessage\n messages.push({\n type: \"create_message\",\n messageId: msg.id,\n role: msg.role,\n content: msg.content ?? [],\n parentId: notification.parentId as string | undefined,\n });\n\n return messages;\n }\n\n case SessionNotificationType.ERROR:\n return {\n type: \"error\",\n message: notification.message as string,\n errorType: notification.errorType as string,\n timestamp: notification.timestamp as string,\n };\n\n case SessionNotificationType.PERMISSION_RESOLVED:\n return {\n type: \"permission_resolved\",\n requestId: notification.requestId as string,\n toolUseIds: notification.toolUseIds as string[],\n selectedOption: notification.selectedOption as ToolConfirmationOutcome,\n };\n\n case SessionNotificationType.SETTINGS_UPDATED:\n return {\n type: \"settings_updated\",\n settings: notification.settings as SettingsUpdatedPayload,\n };\n\n case SessionNotificationType.SESSION_TITLE_UPDATED:\n return {\n type: \"session_title_updated\",\n title: notification.title as string,\n };\n\n case SessionNotificationType.MCP_STATUS_CHANGED:\n return {\n type: \"mcp_status_changed\",\n servers: notification.servers as McpServerStatusInfo[],\n summary: notification.summary as McpStatusSummary,\n };\n\n case SessionNotificationType.MISSION_STATE_CHANGED:\n return {\n type: \"mission_state_changed\",\n state: notification.state as MissionState,\n };\n\n case SessionNotificationType.MISSION_FEATURES_CHANGED:\n return {\n type: \"mission_features_changed\",\n features: notification.features as MissionFeature[],\n };\n\n case SessionNotificationType.MISSION_PROGRESS_ENTRY:\n return {\n type: \"mission_progress_entry\",\n progressLog: notification.progressLog as ProgressLogEntry[],\n };\n\n case SessionNotificationType.MISSION_HEARTBEAT:\n return {\n type: \"mission_heartbeat\",\n timestamp: notification.timestamp as string,\n };\n\n case SessionNotificationType.MISSION_WORKER_STARTED:\n return {\n type: \"mission_worker_started\",\n workerSessionId: notification.workerSessionId as string,\n };\n\n case SessionNotificationType.MISSION_WORKER_COMPLETED:\n return {\n type: \"mission_worker_completed\",\n workerSessionId: notification.workerSessionId as string,\n exitCode: notification.exitCode as number,\n };\n\n case SessionNotificationType.MCP_AUTH_REQUIRED:\n return {\n type: \"mcp_auth_required\",\n serverName: notification.serverName as string,\n authUrl: notification.authUrl as string,\n message: notification.message as string,\n state: notification.state as string,\n };\n\n case SessionNotificationType.MCP_AUTH_COMPLETED:\n return {\n type: \"mcp_auth_completed\",\n serverName: notification.serverName as string,\n outcome: notification.outcome as McpAuthOutcome,\n message: notification.message as string,\n };\n\n default:\n // Unknown notification type — log warning and return null\n console.warn(\n `[droid-sdk] Unknown notification type: ${String(notification.type)}`,\n );\n return null;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Working state tracker for TurnComplete emission\n// ---------------------------------------------------------------------------\n\n/**\n * Tracks working state transitions to detect when an agent turn completes\n * (transitions from a non-idle state back to idle).\n *\n * Each `stream()` call should create a fresh StreamStateTracker so that\n * multi-turn sessions track state independently.\n *\n * Rules:\n * - TurnComplete is emitted when state goes non-idle → idle\n * - Initial idle does NOT emit TurnComplete\n * - TurnComplete carries the last-seen TokenUsageUpdate (or null)\n */\nexport class StreamStateTracker {\n /** Whether we have ever seen a non-idle state. */\n private hasBeenNonIdle = false;\n\n /** Last-seen token usage update (to attach to TurnComplete). */\n private lastTokenUsage: TokenUsageUpdate | null = null;\n\n /**\n * Process a DroidMessage and return any additional messages that should be\n * emitted (e.g. TurnComplete sentinel).\n *\n * @param message - The DroidMessage to process.\n * @returns An array of additional messages to emit (may be empty).\n */\n processMessage(message: DroidMessage): DroidMessage[] {\n const additional: DroidMessage[] = [];\n\n if (message.type === \"token_usage_update\") {\n this.lastTokenUsage = message;\n }\n\n if (message.type === \"working_state_changed\") {\n if (message.state !== DroidWorkingState.Idle) {\n this.hasBeenNonIdle = true;\n } else if (this.hasBeenNonIdle) {\n // Non-idle → Idle transition: emit TurnComplete\n additional.push({\n type: \"turn_complete\",\n tokenUsage: this.lastTokenUsage,\n });\n // Reset so that subsequent idle→idle does NOT emit duplicate TurnComplete\n this.hasBeenNonIdle = false;\n }\n // If state is Idle but we were never non-idle, do nothing\n // (initial idle does NOT emit TurnComplete)\n }\n\n return additional;\n }\n\n /**\n * Reset the tracker for a new turn/stream call.\n */\n reset(): void {\n this.hasBeenNonIdle = false;\n this.lastTokenUsage = null;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction normalizeToolResultContent(content: unknown): string | unknown[] {\n if (content == null) {\n return \"\";\n }\n if (typeof content === \"string\") {\n return content;\n }\n if (Array.isArray(content)) {\n return content as unknown[];\n }\n return String(content);\n}\n","/**\n * Top-level `query()` convenience function and supporting types.\n *\n * Provides a high-level async generator that hides the full session lifecycle\n * (spawn → connect → initialize → message → yield → close), modeled after\n * the Claude Agent SDK and the Python Droid SDK's `query()` pattern.\n *\n * @example\n * ```ts\n * import { query } from \"@factory-ai/droid-sdk\";\n *\n * const stream = query({ prompt: \"Fix the bug in main.ts\", cwd: \"/my/project\" });\n *\n * for await (const msg of stream) {\n * if (msg.type === \"assistant_text_delta\") {\n * process.stdout.write(msg.text);\n * }\n * }\n * ```\n */\n\nimport { DroidClient } from \"./client.js\";\nimport type { ClientPermissionHandler, ClientAskUserHandler } from \"./client.js\";\nimport {\n convertNotificationToStreamMessage,\n StreamStateTracker,\n} from \"./stream.js\";\nimport type { DroidMessage } from \"./stream.js\";\nimport { ProcessTransport } from \"./transport.js\";\nimport type { DroidClientTransport, ProcessTransportOptions } from \"./types.js\";\nimport type {\n InitializeSessionRequestParams,\n} from \"./schemas/client.js\";\nimport type {\n AutonomyLevel,\n DroidInteractionMode,\n ReasoningEffort,\n} from \"./schemas/enums.js\";\n\n// ---------------------------------------------------------------------------\n// QueryOptions\n// ---------------------------------------------------------------------------\n\n/**\n * Options for the `query()` convenience function.\n */\nexport interface QueryOptions {\n /** The user prompt to send. */\n prompt: string;\n\n /** Working directory for the session. Defaults to `\".\"`. */\n cwd?: string;\n\n /** Machine identifier. Defaults to `\"default\"`. */\n machineId?: string;\n\n /** LLM model identifier. */\n modelId?: string;\n\n /** Autonomy level for the session. */\n autonomyLevel?: AutonomyLevel;\n\n /** Interaction mode for the session. */\n interactionMode?: DroidInteractionMode;\n\n /** Reasoning effort level. */\n reasoningEffort?: ReasoningEffort;\n\n /** MCP server configurations for the session. */\n mcpServers?: Array<Record<string, unknown>>;\n\n /** Additional tool IDs to enable. */\n enabledToolIds?: string[];\n\n /** Path to the `droid` executable. Defaults to `\"droid\"`. */\n execPath?: string;\n\n /** Additional arguments for the droid executable. */\n execArgs?: string[];\n\n /** Additional environment variables for the subprocess. */\n env?: Record<string, string>;\n\n /** Permission handler for tool confirmations. */\n permissionHandler?: ClientPermissionHandler;\n\n /** Ask-user handler for interactive questions. */\n askUserHandler?: ClientAskUserHandler;\n\n /**\n * An already-connected transport to use instead of spawning a process.\n * When provided, `execPath`, `execArgs`, `env`, and `cwd` (for transport) are ignored.\n * The transport will still be closed when the query completes.\n */\n transport?: DroidClientTransport;\n\n /** AbortSignal for external cancellation. */\n abortSignal?: AbortSignal;\n}\n\n// ---------------------------------------------------------------------------\n// DroidQuery\n// ---------------------------------------------------------------------------\n\n/**\n * An async generator of {@link DroidMessage} events with additional control\n * methods for interrupting or aborting the query.\n *\n * Extends AsyncGenerator<DroidMessage> with:\n * - `interrupt()` — sends an interrupt request to pause the agent gracefully\n * - `abort()` — forcefully closes the transport/kills the subprocess\n * - `sessionId` — the session ID assigned during initialization\n */\nexport interface DroidQuery extends AsyncGenerator<DroidMessage, void, undefined> {\n /** Send an interrupt_session request. The stream continues until the agent stops. */\n interrupt(): Promise<void>;\n\n /** Forcefully close the transport. The generator terminates immediately. */\n abort(): void;\n\n /**\n * The session ID, available after initialization.\n * Returns `null` if the session hasn't been initialized yet.\n */\n readonly sessionId: string | null;\n}\n\n// ---------------------------------------------------------------------------\n// query() implementation\n// ---------------------------------------------------------------------------\n\n/**\n * Top-level convenience function that spawns a droid process, initializes\n * a session, sends the user prompt, and yields {@link DroidMessage} events.\n *\n * All resources (transport, client) are cleaned up in a finally block,\n * even if the caller breaks out of the generator early or an error occurs.\n *\n * @param options - Query configuration including the prompt and optional session settings.\n * @returns A {@link DroidQuery} async generator with interrupt/abort/sessionId.\n *\n * @example\n * ```ts\n * const stream = query({ prompt: \"Hello\", cwd: \"/tmp\" });\n *\n * for await (const msg of stream) {\n * if (msg.type === \"assistant_text_delta\") {\n * process.stdout.write(msg.text);\n * }\n * if (msg.type === \"turn_complete\") {\n * console.log(\"\\nDone! Tokens:\", msg.tokenUsage);\n * }\n * }\n *\n * // Or with interrupt:\n * const q = query({ prompt: \"Write a long essay\" });\n * setTimeout(() => q.interrupt(), 5000);\n * for await (const msg of q) { ... }\n * ```\n */\nexport function query(options: QueryOptions): DroidQuery {\n let transport: DroidClientTransport | null = null;\n let client: DroidClient | null = null;\n let sessionId: string | null = null;\n let aborted = false;\n\n // Message queue for notification → stream bridging\n const messageQueue: DroidMessage[] = [];\n let resolveWaiting: (() => void) | null = null;\n let streamDone = false;\n\n /**\n * Push a message into the queue and wake the consumer if waiting.\n */\n function enqueueMessage(msg: DroidMessage): void {\n messageQueue.push(msg);\n if (resolveWaiting) {\n const resolve = resolveWaiting;\n resolveWaiting = null;\n resolve();\n }\n }\n\n /**\n * Signal that streaming is complete.\n */\n function signalDone(): void {\n streamDone = true;\n if (resolveWaiting) {\n const resolve = resolveWaiting;\n resolveWaiting = null;\n resolve();\n }\n }\n\n /**\n * The core async generator that drives the query lifecycle.\n */\n async function* generateMessages(): AsyncGenerator<DroidMessage, void, undefined> {\n // 1. Create transport\n if (options.transport) {\n transport = options.transport;\n } else {\n const transportOptions: ProcessTransportOptions = {\n execPath: options.execPath,\n execArgs: options.execArgs,\n cwd: options.cwd,\n env: options.env,\n };\n const processTransport = new ProcessTransport(transportOptions);\n await processTransport.connect();\n transport = processTransport;\n }\n\n // 2. Create client\n client = new DroidClient({ transport });\n\n // 3. Set up handlers if provided\n if (options.permissionHandler) {\n client.setPermissionHandler(options.permissionHandler);\n }\n if (options.askUserHandler) {\n client.setAskUserHandler(options.askUserHandler);\n }\n\n // 4. Set up notification → stream bridging\n const stateTracker = new StreamStateTracker();\n\n client.onNotification((notification) => {\n // Extract the inner notification payload\n const params = notification[\"params\"] as Record<string, unknown> | undefined;\n const innerNotification = params?.[\"notification\"] as Record<string, unknown> | undefined;\n\n if (!innerNotification) {\n return;\n }\n\n const converted = convertNotificationToStreamMessage(\n innerNotification as { type: string; [key: string]: unknown },\n );\n\n if (converted === null) {\n return;\n }\n\n const messages = Array.isArray(converted) ? converted : [converted];\n\n for (const msg of messages) {\n enqueueMessage(msg);\n\n // Check for TurnComplete via state tracker\n const additional = stateTracker.processMessage(msg);\n for (const extra of additional) {\n enqueueMessage(extra);\n if (extra.type === \"turn_complete\") {\n signalDone();\n }\n }\n }\n });\n\n // 5. Initialize session\n const initParams: Record<string, unknown> = {\n machineId: options.machineId ?? \"default\",\n cwd: options.cwd ?? \".\",\n };\n\n if (options.modelId !== undefined) {\n initParams.modelId = options.modelId;\n }\n if (options.autonomyLevel !== undefined) {\n initParams.autonomyLevel = options.autonomyLevel;\n }\n if (options.interactionMode !== undefined) {\n initParams.interactionMode = options.interactionMode;\n }\n if (options.reasoningEffort !== undefined) {\n initParams.reasoningEffort = options.reasoningEffort;\n }\n if (options.mcpServers !== undefined) {\n initParams.mcpServers = options.mcpServers;\n }\n if (options.enabledToolIds !== undefined) {\n initParams.enabledToolIds = options.enabledToolIds;\n }\n\n const initResult = await client.initializeSession(\n initParams as unknown as InitializeSessionRequestParams,\n );\n sessionId = initResult.sessionId;\n\n // 6. Send the user message\n await client.addUserMessage({ text: options.prompt });\n\n // 7. Yield messages from the queue until done\n try {\n while (true) {\n // If aborted externally, stop\n if (aborted) {\n return;\n }\n\n // Process any queued messages\n while (messageQueue.length > 0) {\n const msg = messageQueue.shift()!;\n yield msg;\n\n if (msg.type === \"turn_complete\") {\n return;\n }\n }\n\n // Check if we're done (TurnComplete already yielded above)\n if (streamDone && messageQueue.length === 0) {\n return;\n }\n\n // Wait for more messages\n await new Promise<void>((resolve) => {\n resolveWaiting = resolve;\n });\n }\n } finally {\n // Cleanup is handled by the wrapper\n }\n }\n\n // Create the underlying generator\n const generator = generateMessages();\n\n // Wrap it with cleanup in finally\n async function* wrappedGenerator(): AsyncGenerator<DroidMessage, void, undefined> {\n try {\n yield* generator;\n } finally {\n // Always close transport on exit (even on early break)\n if (client) {\n try {\n await client.close();\n } catch {\n // Best-effort cleanup\n }\n client = null;\n } else if (transport) {\n try {\n await transport.close();\n } catch {\n // Best-effort cleanup\n }\n }\n transport = null;\n }\n }\n\n const wrapped = wrappedGenerator();\n\n // Create the DroidQuery interface by adding control methods to the generator.\n // Use Object.defineProperties so that `sessionId` is a live getter\n // (Object.assign would snapshot the value at assignment time).\n const droidQuery = wrapped as DroidQuery;\n\n Object.defineProperties(droidQuery, {\n interrupt: {\n value: async function interrupt(): Promise<void> {\n if (client && !aborted) {\n await client.interruptSession();\n }\n },\n writable: false,\n enumerable: true,\n },\n abort: {\n value: function abort(): void {\n aborted = true;\n signalDone();\n if (client) {\n // Fire-and-forget close\n void client.close().catch(() => {});\n client = null;\n } else if (transport) {\n void transport.close().catch(() => {});\n }\n transport = null;\n },\n writable: false,\n enumerable: true,\n },\n sessionId: {\n get(): string | null {\n return sessionId;\n },\n enumerable: true,\n },\n });\n\n return droidQuery;\n}\n","/**\n * Multi-turn session API for the Factory Droid SDK.\n *\n * Provides `createSession()` and `resumeSession()` factory functions that\n * return a {@link DroidSession} for multi-turn conversations with the droid\n * process. Each session manages its own transport and client lifecycle.\n *\n * @example\n * ```ts\n * import { createSession } from \"@factory-ai/droid-sdk\";\n *\n * const session = await createSession({ cwd: \"/my/project\" });\n *\n * // Streaming turn\n * for await (const msg of session.stream(\"Fix the bug in main.ts\")) {\n * if (msg.type === \"assistant_text_delta\") {\n * process.stdout.write(msg.text);\n * }\n * }\n *\n * // Non-streaming turn\n * const result = await session.send(\"Now write tests for it\");\n * console.log(result.text);\n *\n * await session.close();\n * ```\n */\n\nimport { DroidClient } from \"./client.js\";\nimport type {\n ClientAskUserHandler,\n ClientPermissionHandler,\n} from \"./client.js\";\nimport { ConnectionError } from \"./errors.js\";\nimport {\n convertNotificationToStreamMessage,\n StreamStateTracker,\n} from \"./stream.js\";\nimport type { DroidMessage, TokenUsageUpdate } from \"./stream.js\";\nimport { ProcessTransport } from \"./transport.js\";\nimport type { DroidClientTransport, ProcessTransportOptions } from \"./types.js\";\nimport type {\n AddMcpServerRequestParams,\n AddMcpServerResult,\n AuthenticateMcpServerRequestParams,\n AuthenticateMcpServerResult,\n InitializeSessionRequestParams,\n InitializeSessionResult,\n ListMcpServersResult,\n ListMcpToolsResult,\n ListSkillsResult,\n LoadSessionRequestParams,\n LoadSessionResult,\n RemoveMcpServerRequestParams,\n RemoveMcpServerResult,\n ToggleMcpServerRequestParams,\n ToggleMcpServerResult,\n UpdateSessionSettingsRequestParams,\n UpdateSessionSettingsResult,\n} from \"./schemas/client.js\";\nimport type {\n AutonomyLevel,\n DroidInteractionMode,\n ReasoningEffort,\n} from \"./schemas/enums.js\";\nimport type { NotificationCallback, NotificationFilter } from \"./protocol.js\";\n\n// ---------------------------------------------------------------------------\n// DroidResult\n// ---------------------------------------------------------------------------\n\n/**\n * Aggregated result from a non-streaming `session.send()` call.\n *\n * Contains the concatenated assistant text, all messages received during\n * the turn, and the final token usage.\n */\nexport interface DroidResult {\n /** Concatenated text from all `assistant_text_delta` messages. */\n text: string;\n\n /** All DroidMessage objects received during the turn. */\n messages: DroidMessage[];\n\n /** Final token usage from the turn, or null if no token usage was reported. */\n tokenUsage: TokenUsageUpdate | null;\n}\n\n// ---------------------------------------------------------------------------\n// SessionOptions\n// ---------------------------------------------------------------------------\n\n/**\n * Options for `createSession()`.\n */\nexport interface CreateSessionOptions {\n /** Working directory for the session. Defaults to `\".\"`. */\n cwd?: string;\n\n /** Machine identifier. Defaults to `\"default\"`. */\n machineId?: string;\n\n /** LLM model identifier. */\n modelId?: string;\n\n /** Autonomy level for the session. */\n autonomyLevel?: AutonomyLevel;\n\n /** Interaction mode for the session. */\n interactionMode?: DroidInteractionMode;\n\n /** Reasoning effort level. */\n reasoningEffort?: ReasoningEffort;\n\n /** MCP server configurations for the session. */\n mcpServers?: Array<Record<string, unknown>>;\n\n /** Additional tool IDs to enable. */\n enabledToolIds?: string[];\n\n /** Path to the `droid` executable. Defaults to `\"droid\"`. */\n execPath?: string;\n\n /** Additional arguments for the droid executable. */\n execArgs?: string[];\n\n /** Additional environment variables for the subprocess. */\n env?: Record<string, string>;\n\n /** Permission handler for tool confirmations. */\n permissionHandler?: ClientPermissionHandler;\n\n /** Ask-user handler for interactive questions. */\n askUserHandler?: ClientAskUserHandler;\n\n /**\n * An already-connected transport to use instead of spawning a process.\n * When provided, `execPath`, `execArgs`, `env`, and `cwd` (for transport) are ignored.\n */\n transport?: DroidClientTransport;\n}\n\n/**\n * Options for `resumeSession()`.\n */\nexport interface ResumeSessionOptions {\n /** Path to the `droid` executable. Defaults to `\"droid\"`. */\n execPath?: string;\n\n /** Additional arguments for the droid executable. */\n execArgs?: string[];\n\n /** Working directory for the subprocess. */\n cwd?: string;\n\n /** Additional environment variables for the subprocess. */\n env?: Record<string, string>;\n\n /** MCP server configurations. */\n mcpServers?: Array<Record<string, unknown>>;\n\n /** Permission handler for tool confirmations. */\n permissionHandler?: ClientPermissionHandler;\n\n /** Ask-user handler for interactive questions. */\n askUserHandler?: ClientAskUserHandler;\n\n /**\n * An already-connected transport to use instead of spawning a process.\n */\n transport?: DroidClientTransport;\n}\n\n/**\n * Options for `session.stream()` and `session.send()`.\n */\nexport interface MessageOptions {\n /** Optional images to include with the message. */\n images?: Array<Record<string, unknown>>;\n\n /** Optional files to include with the message. */\n files?: Array<Record<string, unknown>>;\n}\n\n// ---------------------------------------------------------------------------\n// DroidSession\n// ---------------------------------------------------------------------------\n\n/**\n * A multi-turn session connected to a droid process.\n *\n * Provides methods for sending messages (streaming and non-streaming),\n * managing MCP servers, updating settings, and controlling the session\n * lifecycle.\n *\n * Create instances via {@link createSession} or {@link resumeSession}.\n */\nexport class DroidSession {\n private _client: DroidClient;\n private _sessionId: string;\n private _initResult: InitializeSessionResult | LoadSessionResult;\n private _closed = false;\n\n /** @internal */\n constructor(\n client: DroidClient,\n sessionId: string,\n initResult: InitializeSessionResult | LoadSessionResult,\n ) {\n this._client = client;\n this._sessionId = sessionId;\n this._initResult = initResult;\n }\n\n // ------------------------------------------------------------------\n // Properties\n // ------------------------------------------------------------------\n\n /** The session ID. */\n get sessionId(): string {\n return this._sessionId;\n }\n\n /** The result from session initialization or loading. */\n get initResult(): InitializeSessionResult | LoadSessionResult {\n return this._initResult;\n }\n\n // ------------------------------------------------------------------\n // Messaging\n // ------------------------------------------------------------------\n\n /**\n * Send a message and return a streaming async generator of DroidMessage events.\n *\n * The generator yields messages until a TurnComplete event is received,\n * signaling the end of the agent's turn.\n *\n * @param text - The user message text.\n * @param options - Optional images/files to include.\n * @returns An async generator yielding DroidMessage events.\n */\n async *stream(\n text: string,\n options?: MessageOptions,\n ): AsyncGenerator<DroidMessage, void, undefined> {\n this._ensureNotClosed();\n\n // Message queue for notification → stream bridging\n const messageQueue: DroidMessage[] = [];\n let resolveWaiting: (() => void) | null = null;\n let streamDone = false;\n\n function enqueueMessage(msg: DroidMessage): void {\n messageQueue.push(msg);\n if (resolveWaiting) {\n const resolve = resolveWaiting;\n resolveWaiting = null;\n resolve();\n }\n }\n\n function signalDone(): void {\n streamDone = true;\n if (resolveWaiting) {\n const resolve = resolveWaiting;\n resolveWaiting = null;\n resolve();\n }\n }\n\n // Fresh state tracker for this turn\n const stateTracker = new StreamStateTracker();\n\n // Subscribe to notifications for this turn\n const unsubscribe = this._client.onNotification((notification) => {\n const params = notification[\"params\"] as Record<string, unknown> | undefined;\n const innerNotification = params?.[\"notification\"] as Record<string, unknown> | undefined;\n\n if (!innerNotification) {\n return;\n }\n\n const converted = convertNotificationToStreamMessage(\n innerNotification as { type: string; [key: string]: unknown },\n );\n\n if (converted === null) {\n return;\n }\n\n const messages = Array.isArray(converted) ? converted : [converted];\n\n for (const msg of messages) {\n enqueueMessage(msg);\n\n const additional = stateTracker.processMessage(msg);\n for (const extra of additional) {\n enqueueMessage(extra);\n if (extra.type === \"turn_complete\") {\n signalDone();\n }\n }\n }\n });\n\n try {\n // Send the user message\n await this._client.addUserMessage({\n text,\n images: options?.images as never,\n files: options?.files as never,\n });\n\n // Yield messages until TurnComplete\n while (true) {\n while (messageQueue.length > 0) {\n const msg = messageQueue.shift()!;\n yield msg;\n\n if (msg.type === \"turn_complete\") {\n return;\n }\n }\n\n if (streamDone && messageQueue.length === 0) {\n return;\n }\n\n await new Promise<void>((resolve) => {\n resolveWaiting = resolve;\n });\n }\n } finally {\n unsubscribe();\n }\n }\n\n /**\n * Send a message and collect the complete response (non-streaming).\n *\n * Internally consumes all stream messages and returns an aggregated\n * {@link DroidResult} with the concatenated text, all messages, and\n * final token usage.\n *\n * @param text - The user message text.\n * @param options - Optional images/files to include.\n * @returns Aggregated result with text, messages, and token usage.\n */\n async send(\n text: string,\n options?: MessageOptions,\n ): Promise<DroidResult> {\n this._ensureNotClosed();\n\n const messages: DroidMessage[] = [];\n let fullText = \"\";\n let lastTokenUsage: TokenUsageUpdate | null = null;\n\n for await (const msg of this.stream(text, options)) {\n messages.push(msg);\n\n if (msg.type === \"assistant_text_delta\") {\n fullText += msg.text;\n }\n\n if (msg.type === \"token_usage_update\") {\n lastTokenUsage = msg;\n }\n\n if (msg.type === \"turn_complete\" && msg.tokenUsage) {\n lastTokenUsage = msg.tokenUsage;\n }\n }\n\n return {\n text: fullText,\n messages,\n tokenUsage: lastTokenUsage,\n };\n }\n\n // ------------------------------------------------------------------\n // Session control\n // ------------------------------------------------------------------\n\n /**\n * Interrupt the current agent turn.\n *\n * Sends an interrupt request. The agent will stop after completing\n * its current operation.\n */\n async interrupt(): Promise<void> {\n this._ensureNotClosed();\n await this._client.interruptSession();\n }\n\n /**\n * Close the session and release all resources.\n *\n * Closes the underlying transport and rejects any pending requests.\n * After close, the session cannot be used.\n */\n async close(): Promise<void> {\n if (this._closed) {\n return;\n }\n this._closed = true;\n await this._client.close();\n }\n\n // ------------------------------------------------------------------\n // Settings\n // ------------------------------------------------------------------\n\n /**\n * Update session settings (model, reasoning effort, autonomy, etc.).\n *\n * @param params - Partial settings to update.\n */\n async updateSettings(\n params: Partial<UpdateSessionSettingsRequestParams>,\n ): Promise<UpdateSessionSettingsResult> {\n this._ensureNotClosed();\n return this._client.updateSessionSettings(params);\n }\n\n // ------------------------------------------------------------------\n // MCP methods\n // ------------------------------------------------------------------\n\n /**\n * Add an MCP server to the session.\n */\n async addMcpServer(\n params: AddMcpServerRequestParams,\n ): Promise<AddMcpServerResult> {\n this._ensureNotClosed();\n return this._client.addMcpServer(params);\n }\n\n /**\n * Remove an MCP server from the session.\n */\n async removeMcpServer(\n params: RemoveMcpServerRequestParams,\n ): Promise<RemoveMcpServerResult> {\n this._ensureNotClosed();\n return this._client.removeMcpServer(params);\n }\n\n /**\n * Toggle an MCP server on or off.\n */\n async toggleMcpServer(\n params: ToggleMcpServerRequestParams,\n ): Promise<ToggleMcpServerResult> {\n this._ensureNotClosed();\n return this._client.toggleMcpServer(params);\n }\n\n /**\n * List MCP servers and their status.\n */\n async listMcpServers(): Promise<ListMcpServersResult> {\n this._ensureNotClosed();\n return this._client.listMcpServers();\n }\n\n /**\n * List available MCP tools.\n */\n async listMcpTools(): Promise<ListMcpToolsResult> {\n this._ensureNotClosed();\n return this._client.listMcpTools();\n }\n\n /**\n * Authenticate an MCP server (OAuth flow).\n */\n async authenticateMcpServer(\n params: AuthenticateMcpServerRequestParams,\n ): Promise<AuthenticateMcpServerResult> {\n this._ensureNotClosed();\n return this._client.authenticateMcpServer(params);\n }\n\n // ------------------------------------------------------------------\n // Skills\n // ------------------------------------------------------------------\n\n /**\n * List available skills.\n */\n async listSkills(): Promise<ListSkillsResult> {\n this._ensureNotClosed();\n return this._client.listSkills();\n }\n\n // ------------------------------------------------------------------\n // Notification subscription\n // ------------------------------------------------------------------\n\n /**\n * Register a callback for incoming notification messages.\n *\n * @param callback - Invoked with the notification object.\n * @param filter - Optional filter to only receive specific notification types.\n * @returns An unsubscribe function.\n */\n onNotification(\n callback: NotificationCallback,\n filter?: NotificationFilter,\n ): () => void {\n return this._client.onNotification(callback, filter);\n }\n\n // ------------------------------------------------------------------\n // Internal\n // ------------------------------------------------------------------\n\n private _ensureNotClosed(): void {\n if (this._closed) {\n throw new ConnectionError(\n \"Session has been closed. Create a new session to continue.\",\n );\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Factory functions\n// ---------------------------------------------------------------------------\n\n/**\n * Create a new droid session.\n *\n * Spawns a transport, creates a client, initializes a new session, and\n * returns a {@link DroidSession} ready for multi-turn interaction.\n *\n * @param options - Session configuration.\n * @returns A connected DroidSession.\n *\n * @example\n * ```ts\n * const session = await createSession({ cwd: \"/my/project\" });\n * const result = await session.send(\"List all TypeScript files\");\n * console.log(result.text);\n * await session.close();\n * ```\n */\nexport async function createSession(\n options: CreateSessionOptions = {},\n): Promise<DroidSession> {\n // 1. Create transport\n let transport: DroidClientTransport;\n if (options.transport) {\n transport = options.transport;\n } else {\n const transportOptions: ProcessTransportOptions = {\n execPath: options.execPath,\n execArgs: options.execArgs,\n cwd: options.cwd,\n env: options.env,\n };\n const processTransport = new ProcessTransport(transportOptions);\n await processTransport.connect();\n transport = processTransport;\n }\n\n // 2. Create client\n const client = new DroidClient({ transport });\n\n // 3. Set up handlers\n if (options.permissionHandler) {\n client.setPermissionHandler(options.permissionHandler);\n }\n if (options.askUserHandler) {\n client.setAskUserHandler(options.askUserHandler);\n }\n\n // 4. Initialize session\n const initParams: Record<string, unknown> = {\n machineId: options.machineId ?? \"default\",\n cwd: options.cwd ?? \".\",\n };\n\n if (options.modelId !== undefined) {\n initParams.modelId = options.modelId;\n }\n if (options.autonomyLevel !== undefined) {\n initParams.autonomyLevel = options.autonomyLevel;\n }\n if (options.interactionMode !== undefined) {\n initParams.interactionMode = options.interactionMode;\n }\n if (options.reasoningEffort !== undefined) {\n initParams.reasoningEffort = options.reasoningEffort;\n }\n if (options.mcpServers !== undefined) {\n initParams.mcpServers = options.mcpServers;\n }\n if (options.enabledToolIds !== undefined) {\n initParams.enabledToolIds = options.enabledToolIds;\n }\n\n try {\n const initResult = await client.initializeSession(\n initParams as unknown as InitializeSessionRequestParams,\n );\n\n return new DroidSession(client, initResult.sessionId, initResult);\n } catch (error) {\n // Clean up on init failure\n try {\n await client.close();\n } catch {\n // Best-effort cleanup\n }\n throw error;\n }\n}\n\n/**\n * Resume an existing droid session.\n *\n * Spawns a transport, creates a client, loads the existing session by ID,\n * and returns a {@link DroidSession} ready for multi-turn interaction.\n *\n * @param sessionId - The ID of the session to resume.\n * @param options - Optional configuration for the transport and handlers.\n * @returns A connected DroidSession.\n * @throws {SessionNotFoundError} If the session ID does not exist.\n *\n * @example\n * ```ts\n * const session = await resumeSession(\"sess-abc123\");\n * const result = await session.send(\"Continue where we left off\");\n * console.log(result.text);\n * await session.close();\n * ```\n */\nexport async function resumeSession(\n sessionId: string,\n options: ResumeSessionOptions = {},\n): Promise<DroidSession> {\n // 1. Create transport\n let transport: DroidClientTransport;\n if (options.transport) {\n transport = options.transport;\n } else {\n const transportOptions: ProcessTransportOptions = {\n execPath: options.execPath,\n execArgs: options.execArgs,\n cwd: options.cwd,\n env: options.env,\n };\n const processTransport = new ProcessTransport(transportOptions);\n await processTransport.connect();\n transport = processTransport;\n }\n\n // 2. Create client\n const client = new DroidClient({ transport });\n\n // 3. Set up handlers\n if (options.permissionHandler) {\n client.setPermissionHandler(options.permissionHandler);\n }\n if (options.askUserHandler) {\n client.setAskUserHandler(options.askUserHandler);\n }\n\n // 4. Load session\n const loadParams: LoadSessionRequestParams = {\n sessionId,\n mcpServers: options.mcpServers as never,\n };\n\n try {\n const loadResult = await client.loadSession(loadParams);\n return new DroidSession(client, sessionId, loadResult);\n } catch (error) {\n // Clean up on load failure\n try {\n await client.close();\n } catch {\n // Best-effort cleanup\n }\n throw error;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;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d;AAGA,QAAM,SAAS,IAAI,YAAY,EAAE,UAAU,CAAC;AAG5C,MAAI,QAAQ,mBAAmB;AAC7B,WAAO,qBAAqB,QAAQ,iBAAiB;AAAA,EACvD;AACA,MAAI,QAAQ,gBAAgB;AAC1B,WAAO,kBAAkB,QAAQ,cAAc;AAAA,EACjD;AAGA,QAAM,aAAuC;AAAA,IAC3C;AAAA,IACA,YAAY,QAAQ;AAAA,EACtB;AAEA,MAAI;AACF,UAAM,aAAa,MAAM,OAAO,YAAY,UAAU;AACtD,WAAO,IAAI,aAAa,QAAQ,WAAW,UAAU;AAAA,EACvD,SAAS,OAAO;AAEd,QAAI;AACF,YAAM,OAAO,MAAM;AAAA,IACrB,QAAQ;AAAA,IAER;AACA,UAAM;AAAA,EACR;AACF;","names":["DroidServerMethod","DroidClientMethod","SessionNotificationType","ToolConfirmationOutcome","ToolConfirmationType","DroidWorkingState","DroidErrorType","McpServerStatus","McpServerType","McpStatus","McpAuthOutcome","DecompSessionType","MissionState","FeatureStatus","FeatureSuccessState","IssueSeverity","DismissalType","ProgressLogEntryType","DroidInteractionMode","AutonomyLevel","AutonomyMode","ReasoningEffort","ModelProvider","JsonRpcErrorCode","JsonRpcMessageType","SettingsLevel","SkillLocation","import_zod","import_zod","import_zod","import_zod","import_zod","uuidv4"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/schemas/enums.ts","../src/schemas/constants.ts","../src/schemas/shared.ts","../src/schemas/messages.ts","../src/schemas/mcp.ts","../src/schemas/mission.ts","../src/schemas/client.ts","../src/schemas/server.ts","../src/errors.ts","../src/transport.ts","../src/protocol.ts","../src/client.ts","../src/stream.ts","../src/query.ts","../src/session.ts"],"sourcesContent":["// @factory/droid-sdk - TypeScript SDK for the Factory Droid CLI\n// This is the public API barrel file.\n\n// --- Schemas (enums, constants, Zod schemas, types) ---\nexport * from \"./schemas/index.js\";\n\n// --- Errors ---\nexport * from \"./errors.js\";\n\n// --- Transport types ---\nexport * from \"./types.js\";\nexport { ProcessTransport } from \"./transport.js\";\n\n// --- Protocol engine ---\nexport { ProtocolEngine } from \"./protocol.js\";\nexport type {\n AskUserHandler,\n NotificationCallback,\n NotificationFilter,\n PermissionHandler,\n} from \"./protocol.js\";\n\n// --- Client ---\nexport { DroidClient } from \"./client.js\";\nexport type {\n ClientAskUserHandler,\n ClientPermissionHandler,\n DroidClientOptions,\n} from \"./client.js\";\n\n// --- Stream message types and converter ---\nexport {\n convertNotificationToStreamMessage,\n StreamStateTracker,\n} from \"./stream.js\";\nexport type {\n AssistantTextDelta,\n ThinkingTextDelta,\n ToolUse,\n ToolResult,\n ToolProgress,\n WorkingStateChanged,\n TokenUsageUpdate,\n CreateMessage,\n PermissionResolved,\n SettingsUpdated,\n SessionTitleUpdated,\n McpStatusChanged,\n MissionStateChanged,\n MissionFeaturesChanged,\n MissionProgressEntry,\n MissionHeartbeat,\n MissionWorkerStarted,\n MissionWorkerCompleted,\n McpAuthRequired,\n McpAuthCompleted,\n ErrorEvent,\n TurnComplete,\n DroidMessage,\n} from \"./stream.js\";\n\n// --- High-level API: query ---\nexport { query } from \"./query.js\";\nexport type { QueryOptions, DroidQuery } from \"./query.js\";\n\n// --- High-level API: session ---\nexport { createSession, resumeSession, DroidSession } from \"./session.js\";\nexport type {\n CreateSessionOptions,\n ResumeSessionOptions,\n MessageOptions,\n DroidResult,\n} from \"./session.js\";\n","/**\n * All protocol enums for the Factory Droid SDK.\n *\n * Ported from:\n * - packages/common/src/droid/enums.ts\n * - packages/common/src/shared/enums.ts\n * - packages/common/src/llm/enums.ts\n * - packages/common/src/settings/enums.ts\n */\n\n/** Droid server methods (client → server communication). */\nexport enum DroidServerMethod {\n INITIALIZE_SESSION = \"droid.initialize_session\",\n LOAD_SESSION = \"droid.load_session\",\n ADD_USER_MESSAGE = \"droid.add_user_message\",\n INTERRUPT_SESSION = \"droid.interrupt_session\",\n KILL_WORKER_SESSION = \"droid.kill_worker_session\",\n UPDATE_SESSION_SETTINGS = \"droid.update_session_settings\",\n TOGGLE_MCP_SERVER = \"droid.toggle_mcp_server\",\n AUTHENTICATE_MCP_SERVER = \"droid.authenticate_mcp_server\",\n CANCEL_MCP_AUTH = \"droid.cancel_mcp_auth\",\n CLEAR_MCP_AUTH = \"droid.clear_mcp_auth\",\n ADD_MCP_SERVER = \"droid.add_mcp_server\",\n REMOVE_MCP_SERVER = \"droid.remove_mcp_server\",\n LIST_MCP_REGISTRY = \"droid.list_mcp_registry\",\n LIST_MCP_TOOLS = \"droid.list_mcp_tools\",\n LIST_MCP_SERVERS = \"droid.list_mcp_servers\",\n TOGGLE_MCP_TOOL = \"droid.toggle_mcp_tool\",\n SUBMIT_MCP_AUTH_CODE = \"droid.submit_mcp_auth_code\",\n LIST_SKILLS = \"droid.list_skills\",\n SUBMIT_BUG_REPORT = \"droid.submit_bug_report\",\n}\n\n/** Droid client methods (server → client communication). */\nexport enum DroidClientMethod {\n SESSION_NOTIFICATION = \"droid.session_notification\",\n REQUEST_PERMISSION = \"droid.request_permission\",\n ASK_USER = \"droid.ask_user\",\n}\n\n/** Session notification types. */\nexport enum SessionNotificationType {\n TOOL_RESULT = \"tool_result\",\n TOOL_PROGRESS_UPDATE = \"tool_progress_update\",\n CREATE_MESSAGE = \"create_message\",\n ERROR = \"error\",\n DROID_WORKING_STATE_CHANGED = \"droid_working_state_changed\",\n PERMISSION_RESOLVED = \"permission_resolved\",\n SETTINGS_UPDATED = \"settings_updated\",\n SESSION_TITLE_UPDATED = \"session_title_updated\",\n MCP_STATUS_CHANGED = \"mcp_status_changed\",\n ASSISTANT_TEXT_DELTA = \"assistant_text_delta\",\n THINKING_TEXT_DELTA = \"thinking_text_delta\",\n SESSION_TOKEN_USAGE_CHANGED = \"session_token_usage_changed\",\n MISSION_STATE_CHANGED = \"mission_state_changed\",\n MISSION_FEATURES_CHANGED = \"mission_features_changed\",\n MISSION_PROGRESS_ENTRY = \"mission_progress_entry\",\n MISSION_HEARTBEAT = \"mission_heartbeat\",\n MISSION_WORKER_STARTED = \"mission_worker_started\",\n MISSION_WORKER_COMPLETED = \"mission_worker_completed\",\n MCP_AUTH_REQUIRED = \"mcp_auth_required\",\n MCP_AUTH_COMPLETED = \"mcp_auth_completed\",\n}\n\n/** Tool confirmation outcome options (possible user responses to permission requests). */\nexport enum ToolConfirmationOutcome {\n ProceedOnce = \"proceed_once\",\n ProceedAlways = \"proceed_always\",\n ProceedAutoRun = \"proceed_auto_run\",\n ProceedAutoRunLow = \"proceed_auto_run_low\",\n ProceedAutoRunMedium = \"proceed_auto_run_medium\",\n ProceedAutoRunHigh = \"proceed_auto_run_high\",\n ProceedEdit = \"proceed_edit\",\n Cancel = \"cancel\",\n}\n\n/** Tool confirmation type (which tool is requesting permission). */\nexport enum ToolConfirmationType {\n Edit = \"edit\",\n Execute = \"exec\",\n Create = \"create\",\n AskUser = \"ask_user\",\n ExitSpecMode = \"exit_spec_mode\",\n ProposeMission = \"propose_mission\",\n StartMissionRun = \"start_mission_run\",\n ApplyPatch = \"apply_patch\",\n McpTool = \"mcp_tool\",\n}\n\n/** Droid working state (represents what the agent is currently doing). */\nexport enum DroidWorkingState {\n Idle = \"idle\",\n StreamingAssistantMessage = \"streaming_assistant_message\",\n WaitingForToolConfirmation = \"waiting_for_tool_confirmation\",\n ExecutingTool = \"executing_tool\",\n CompactingConversation = \"compacting_conversation\",\n}\n\n/** Error types for error notifications. */\nexport enum DroidErrorType {\n CONNECTION_ERROR = \"ConnectionError\",\n PROTOCOL_ERROR = \"ProtocolError\",\n SESSION_ERROR = \"SessionError\",\n TIMEOUT_ERROR = \"TimeoutError\",\n DROID_CLIENT_ERROR = \"DroidClientError\",\n PROCESS_EXIT_ERROR = \"ProcessExitError\",\n ERROR = \"Error\",\n}\n\n/** MCP server connection status. */\nexport enum McpServerStatus {\n Connecting = \"connecting\",\n Connected = \"connected\",\n Disconnected = \"disconnected\",\n Failed = \"failed\",\n Disabled = \"disabled\",\n}\n\n/** MCP server transport type. */\nexport enum McpServerType {\n Stdio = \"stdio\",\n Http = \"http\",\n Sse = \"sse\",\n}\n\n/** Overall MCP initialization status. */\nexport enum McpStatus {\n NotInitialized = \"not-initialized\",\n Initializing = \"initializing\",\n Ready = \"ready\",\n NoServers = \"no-servers\",\n Failed = \"failed\",\n}\n\n/** MCP authentication outcome. */\nexport enum McpAuthOutcome {\n Success = \"success\",\n Cancelled = \"cancelled\",\n Failed = \"failed\",\n}\n\n/** Session type for mission decomposition (orchestrator manages workers). */\nexport enum DecompSessionType {\n Orchestrator = \"orchestrator\",\n Worker = \"worker\",\n}\n\n/** Mission state enum (used by orchestrator mission runner). */\nexport enum MissionState {\n AwaitingInput = \"awaiting_input\",\n Initializing = \"initializing\",\n Running = \"running\",\n Paused = \"paused\",\n OrchestratorTurn = \"orchestrator_turn\",\n Completed = \"completed\",\n}\n\n/** Feature status enum (mirrors orchestrator feature lifecycle). */\nexport enum FeatureStatus {\n Pending = \"pending\",\n InProgress = \"in_progress\",\n Completed = \"completed\",\n Cancelled = \"cancelled\",\n}\n\n/** Success state for feature completion. */\nexport enum FeatureSuccessState {\n Success = \"success\",\n Partial = \"partial\",\n Failure = \"failure\",\n}\n\n/** Issue severity for discovered issues. */\nexport enum IssueSeverity {\n Blocking = \"blocking\",\n NonBlocking = \"non_blocking\",\n Suggestion = \"suggestion\",\n}\n\n/** Dismissal item type. */\nexport enum DismissalType {\n DiscoveredIssue = \"discovered_issue\",\n CriticalContext = \"critical_context\",\n IncompleteWork = \"incomplete_work\",\n}\n\n/** Progress log entry type. */\nexport enum ProgressLogEntryType {\n MissionAccepted = \"mission_accepted\",\n MissionPaused = \"mission_paused\",\n MissionResumed = \"mission_resumed\",\n MissionRunStarted = \"mission_run_started\",\n WorkerStarted = \"worker_started\",\n WorkerSelectedFeature = \"worker_selected_feature\",\n WorkerCompleted = \"worker_completed\",\n WorkerFailed = \"worker_failed\",\n WorkerPaused = \"worker_paused\",\n HandoffItemsDismissed = \"handoff_items_dismissed\",\n MilestoneValidationTriggered = \"milestone_validation_triggered\",\n}\n\n/**\n * The interaction mode determines how Droid operates.\n * - Auto: Droid can execute actions based on autonomy level\n * - Spec: Droid is in planning/research mode only (read-only operations)\n * - AGI: Droid orchestrates missions with read-only tools and orchestrator controls\n */\nexport enum DroidInteractionMode {\n Auto = \"auto\",\n Spec = \"spec\",\n AGI = \"agi\",\n}\n\n/**\n * Autonomy level determines what actions Droid can perform without user confirmation.\n * - Off: User controls all actions (confirmation required for everything)\n * - Low: Allow file edits and read-only commands\n * - Medium: Allow reversible commands\n * - High: Allow all commands without prompts\n */\nexport enum AutonomyLevel {\n Off = \"off\",\n Low = \"low\",\n Medium = \"medium\",\n High = \"high\",\n}\n\n/**\n * Combined autonomy mode for backward compatibility.\n * @deprecated Use DroidInteractionMode + AutonomyLevel instead.\n */\nexport enum AutonomyMode {\n Normal = \"normal\",\n Spec = \"spec\",\n AutoLow = \"auto-low\",\n AutoMedium = \"auto-medium\",\n AutoHigh = \"auto-high\",\n}\n\n/** Reasoning effort levels for LLMs. */\nexport enum ReasoningEffort {\n None = \"none\",\n Dynamic = \"dynamic\",\n Off = \"off\",\n Minimal = \"minimal\",\n Low = \"low\",\n Medium = \"medium\",\n High = \"high\",\n ExtraHigh = \"xhigh\",\n Max = \"max\",\n}\n\n/** Model provider identifiers. */\nexport enum ModelProvider {\n ANTHROPIC = \"anthropic\",\n OPENAI = \"openai\",\n GENERIC_CHAT_COMPLETION_API = \"generic-chat-completion-api\",\n FACTORY = \"factory\",\n GOOGLE = \"google\",\n XAI = \"xai\",\n VOYAGE = \"voyage\",\n}\n\n/** Standard JSON-RPC 2.0 error codes. */\nexport enum JsonRpcErrorCode {\n PARSE_ERROR = -32700,\n INVALID_REQUEST = -32600,\n METHOD_NOT_FOUND = -32601,\n INVALID_PARAMS = -32602,\n INTERNAL_ERROR = -32603,\n AUTHENTICATION_ERROR = -32001,\n ENTITY_NOT_FOUND = -32004,\n SESSION_DISCONNECTED = -32005,\n}\n\n/** JSON-RPC message type discriminator. */\nexport enum JsonRpcMessageType {\n Request = \"request\",\n Response = \"response\",\n Notification = \"notification\",\n}\n\n/**\n * Settings hierarchy level enum.\n * Precedence order (highest to lowest): Org → Runtime → Folder → Project → User\n */\nexport enum SettingsLevel {\n Org = \"org\",\n Runtime = \"runtime\",\n User = \"user\",\n Project = \"project\",\n Folder = \"folder\",\n Dynamic = \"dynamic\",\n BuiltIn = \"builtin\",\n}\n\n/** Skill file location type. */\nexport enum SkillLocation {\n Project = \"project\",\n Personal = \"personal\",\n Builtin = \"builtin\",\n}\n","/**\n * Protocol version constants for the Factory Droid SDK.\n */\n\n/** JSON-RPC protocol version. */\nexport const JSONRPC_VERSION = \"2.0\" as const;\n\n/**\n * Legacy Factory API version for backward compatibility.\n * @deprecated Use FACTORY_PROTOCOL_VERSION for runtime compatibility instead.\n */\nexport const LEGACY_FACTORY_API_VERSION = \"1.0.0\" as const;\n\n/** Current Factory protocol version. */\nexport const FACTORY_PROTOCOL_VERSION = \"1.2.0\" as const;\n\n/** HTTP header identifying the Factory client type. */\nexport const FACTORY_CLIENT_HEADER = \"X-Factory-Client\" as const;\n\n/** HTTP header identifying the Factory client version. */\nexport const FACTORY_CLIENT_VERSION = \"X-Client-Version\" as const;\n\n/** Default request timeout in milliseconds (30s). */\nexport const DEFAULT_REQUEST_TIMEOUT = 30_000;\n\n/** Session initialization timeout in milliseconds (60s). */\nexport const SESSION_INIT_TIMEOUT = 60_000;\n\n/** MCP authentication timeout in milliseconds (300s). */\nexport const MCP_AUTH_TIMEOUT = 300_000;\n","/**\n * JSON-RPC 2.0 base schemas for the Factory Droid protocol.\n *\n * Ported from: packages/common/src/shared/schemas.ts\n */\n\nimport { z } from \"zod\";\n\nimport { JSONRPC_VERSION, LEGACY_FACTORY_API_VERSION } from \"./constants.js\";\nimport { JsonRpcErrorCode } from \"./enums.js\";\n\n// ---------------------------------------------------------------------------\n// Trace context metadata\n// ---------------------------------------------------------------------------\n\n/** Trace context metadata for distributed tracing propagation. */\nexport const TraceContextMetaSchema = z.object({\n traceparent: z.string().optional(),\n tracestate: z.string().optional(),\n});\n\nexport type TraceContextMeta = z.infer<typeof TraceContextMetaSchema>;\n\n// ---------------------------------------------------------------------------\n// JSON-RPC envelope\n// ---------------------------------------------------------------------------\n\n/** JSON-RPC 2.0 envelope with Factory protocol extensions. */\nexport const JsonRpcEnvelopeSchema = z.object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n factoryApiVersion: z.literal(LEGACY_FACTORY_API_VERSION),\n factoryProtocolVersion: z.string().optional(),\n _meta: TraceContextMetaSchema.optional(),\n});\n\nexport type JsonRpcEnvelope = z.infer<typeof JsonRpcEnvelopeSchema>;\n\n// ---------------------------------------------------------------------------\n// JSON-RPC error\n// ---------------------------------------------------------------------------\n\n/** JSON-RPC 2.0 error object. */\nexport const JsonRpcErrorSchema = z.object({\n code: z.nativeEnum(JsonRpcErrorCode),\n message: z.string(),\n data: z.unknown().optional(),\n});\n\nexport type JsonRpcError = z.infer<typeof JsonRpcErrorSchema>;\n\n// ---------------------------------------------------------------------------\n// Base message schemas (without envelope)\n// ---------------------------------------------------------------------------\n\n/** Base JSON-RPC request. */\nexport const BaseRequestSchema = z.object({\n type: z.literal(\"request\"),\n id: z.string(),\n method: z.string(),\n params: z.unknown().optional(),\n});\n\nexport type BaseRequest = z.infer<typeof BaseRequestSchema>;\n\n/** Base JSON-RPC success response. */\nexport const BaseResponseSuccessSchema = z.object({\n type: z.literal(\"response\"),\n id: z.string(),\n result: z.unknown(),\n});\n\nexport type BaseResponseSuccess = z.infer<typeof BaseResponseSuccessSchema>;\n\n/** Base JSON-RPC failure response. */\nexport const BaseResponseFailureSchema = z.object({\n type: z.literal(\"response\"),\n id: z.string().nullable(),\n error: JsonRpcErrorSchema,\n});\n\nexport type BaseResponseFailure = z.infer<typeof BaseResponseFailureSchema>;\n\n/** Base JSON-RPC notification. */\nexport const BaseNotificationSchema = z.object({\n type: z.literal(\"notification\"),\n method: z.string(),\n params: z.unknown().optional(),\n});\n\nexport type BaseNotification = z.infer<typeof BaseNotificationSchema>;\n\n// ---------------------------------------------------------------------------\n// Combined models (Envelope + Base)\n// ---------------------------------------------------------------------------\n\n/** Full JSON-RPC request with envelope fields. */\nexport const JsonRpcRequestSchema = JsonRpcEnvelopeSchema.extend(\n BaseRequestSchema.shape,\n);\n\nexport type JsonRpcRequest = z.infer<typeof JsonRpcRequestSchema>;\n\n/** Full JSON-RPC success response with envelope fields. */\nexport const JsonRpcResponseSuccessSchema = JsonRpcEnvelopeSchema.extend(\n BaseResponseSuccessSchema.shape,\n);\n\nexport type JsonRpcResponseSuccess = z.infer<\n typeof JsonRpcResponseSuccessSchema\n>;\n\n/** Full JSON-RPC failure response with envelope fields. */\nexport const JsonRpcResponseFailureSchema = JsonRpcEnvelopeSchema.extend(\n BaseResponseFailureSchema.shape,\n);\n\nexport type JsonRpcResponseFailure = z.infer<\n typeof JsonRpcResponseFailureSchema\n>;\n\n/** Full JSON-RPC notification with envelope fields. */\nexport const JsonRpcNotificationSchema = JsonRpcEnvelopeSchema.extend(\n BaseNotificationSchema.shape,\n);\n\nexport type JsonRpcNotification = z.infer<typeof JsonRpcNotificationSchema>;\n\n/** JSON-RPC response (success or failure). */\nexport const JsonRpcResponseSchema = z.union([\n JsonRpcResponseFailureSchema,\n JsonRpcResponseSuccessSchema,\n]);\n\nexport type JsonRpcResponse = z.infer<typeof JsonRpcResponseSchema>;\n\n/** Discriminated union for initial message type routing. */\nexport const JsonRpcMessageSchema = z.discriminatedUnion(\"type\", [\n JsonRpcRequestSchema,\n JsonRpcEnvelopeSchema.extend({\n type: z.literal(\"response\"),\n id: z.string().nullable(),\n result: z.unknown().optional(),\n error: JsonRpcErrorSchema.optional(),\n }),\n JsonRpcNotificationSchema,\n]);\n\nexport type JsonRpcMessage = z.infer<typeof JsonRpcMessageSchema>;\n","/**\n * Message content block schemas for the Factory Droid protocol.\n *\n * Ported from: packages/common/src/sessionV2/messages/schemas.ts\n */\n\nimport { z } from \"zod\";\n\n// ---------------------------------------------------------------------------\n// Content block schemas\n// ---------------------------------------------------------------------------\n\n/** Text content block. */\nexport const TextBlockSchema = z\n .object({\n type: z.literal(\"text\"),\n text: z.string(),\n id: z.string().optional(),\n })\n .passthrough();\n\nexport type TextBlock = z.infer<typeof TextBlockSchema>;\n\n/** Base64-encoded image source. */\nexport const Base64ImageSourceSchema = z\n .object({\n type: z.literal(\"base64\"),\n data: z.string(),\n mediaType: z.enum([\"image/jpeg\", \"image/png\", \"image/gif\", \"image/webp\"]),\n })\n .passthrough();\n\nexport type Base64ImageSource = z.infer<typeof Base64ImageSourceSchema>;\n\n/** Image content block. */\nexport const ImageBlockSchema = z\n .object({\n type: z.literal(\"image\"),\n source: Base64ImageSourceSchema,\n id: z.string().optional(),\n })\n .passthrough();\n\nexport type ImageBlock = z.infer<typeof ImageBlockSchema>;\n\n/** Thinking content block. */\nexport const ThinkingBlockSchema = z\n .object({\n type: z.literal(\"thinking\"),\n signature: z.string(),\n thinking: z.string(),\n id: z.string().optional(),\n signatureProvider: z.string().optional(),\n })\n .passthrough();\n\nexport type ThinkingBlock = z.infer<typeof ThinkingBlockSchema>;\n\n/** Redacted thinking content block. */\nexport const RedactedThinkingBlockSchema = z\n .object({\n type: z.literal(\"redacted_thinking\"),\n data: z.string(),\n id: z.string().optional(),\n })\n .passthrough();\n\nexport type RedactedThinkingBlock = z.infer<typeof RedactedThinkingBlockSchema>;\n\n/** Tool use content block. */\nexport const ToolUseBlockSchema = z\n .object({\n type: z.literal(\"tool_use\"),\n id: z.string(),\n input: z.record(z.unknown()),\n name: z.string(),\n thoughtSignature: z.string().optional(),\n })\n .passthrough();\n\nexport type ToolUseBlock = z.infer<typeof ToolUseBlockSchema>;\n\n/** Tool result content block. */\nexport const ToolResultBlockSchema = z\n .object({\n type: z.literal(\"tool_result\"),\n toolUseId: z.string(),\n content: z.union([z.string(), z.array(z.unknown())]).optional(),\n isError: z.boolean().optional(),\n id: z.string().optional(),\n })\n .passthrough();\n\nexport type ToolResultBlock = z.infer<typeof ToolResultBlockSchema>;\n\n/** Document content block. */\nexport const DocumentBlockSchema = z\n .object({\n type: z.literal(\"document\"),\n source: z.record(z.unknown()),\n id: z.string().optional(),\n })\n .passthrough();\n\nexport type DocumentBlock = z.infer<typeof DocumentBlockSchema>;\n\n/** Discriminated union over all content block types. */\nexport const ContentBlockSchema = z.discriminatedUnion(\"type\", [\n TextBlockSchema,\n ImageBlockSchema,\n ThinkingBlockSchema,\n RedactedThinkingBlockSchema,\n ToolUseBlockSchema,\n ToolResultBlockSchema,\n DocumentBlockSchema,\n]);\n\nexport type ContentBlock = z.infer<typeof ContentBlockSchema>;\n\n// ---------------------------------------------------------------------------\n// FactoryDroidMessage\n// ---------------------------------------------------------------------------\n\n/** Factory Droid message schema (used in CreateMessageNotification and session data). */\nexport const FactoryDroidMessageSchema = z\n .object({\n id: z.string(),\n role: z.enum([\"user\", \"assistant\", \"tool\", \"system\"]),\n content: z.array(ContentBlockSchema),\n createdAt: z.number(),\n updatedAt: z.number(),\n parentId: z.string().optional(),\n visibility: z.enum([\"both\", \"llm_only\", \"user_only\"]).optional(),\n isError: z.boolean().optional(),\n })\n .passthrough();\n\nexport type FactoryDroidMessage = z.infer<typeof FactoryDroidMessageSchema>;\n\n/** Document source for user messages (PDF or plain text). */\nexport const DocumentSourceSchema = z\n .object({\n type: z.string(),\n mediaType: z.string(),\n data: z.string(),\n name: z.string().optional(),\n mime: z.string().optional(),\n })\n .strict();\n\nexport type DocumentSource = z.infer<typeof DocumentSourceSchema>;\n","/**\n * MCP entity schemas for the Factory Droid protocol.\n *\n * Ported from: packages/common/src/droid/schemas/mcp.ts\n */\n\nimport { z } from \"zod\";\n\nimport { McpServerStatus, McpServerType, SettingsLevel, ToolConfirmationOutcome } from \"./enums.js\";\n\n// ---------------------------------------------------------------------------\n// MCP server config field schemas\n// ---------------------------------------------------------------------------\n\n/** Stdio MCP server configuration fields. */\nexport const McpStdioServerConfigFieldsSchema = z.object({\n command: z.string().optional(),\n args: z.array(z.string()).optional(),\n});\n\nexport type McpStdioServerConfigFields = z.infer<\n typeof McpStdioServerConfigFieldsSchema\n>;\n\n/** HTTP MCP server configuration fields. */\nexport const McpHttpServerConfigFieldsSchema = z.object({\n url: z.string().optional(),\n});\n\nexport type McpHttpServerConfigFields = z.infer<\n typeof McpHttpServerConfigFieldsSchema\n>;\n\n/** SSE MCP server configuration fields. */\nexport const McpSseServerConfigFieldsSchema = z.object({\n url: z.string(),\n headers: z.record(z.string()).optional(),\n});\n\nexport type McpSseServerConfigFields = z.infer<\n typeof McpSseServerConfigFieldsSchema\n>;\n\n// ---------------------------------------------------------------------------\n// MCP server status and summary\n// ---------------------------------------------------------------------------\n\n/** MCP server status information. */\nexport const McpServerStatusInfoSchema = z\n .object({\n name: z.string(),\n status: z.nativeEnum(McpServerStatus),\n source: z.nativeEnum(SettingsLevel),\n isManaged: z.boolean(),\n error: z.string().optional(),\n toolCount: z.number().optional(),\n serverType: z.nativeEnum(McpServerType).optional(),\n hasAuthTokens: z.boolean().optional(),\n })\n .passthrough();\n\nexport type McpServerStatusInfo = z.infer<typeof McpServerStatusInfoSchema>;\n\n/** MCP status summary. */\nexport const McpStatusSummarySchema = z\n .object({\n total: z.number(),\n connected: z.number(),\n connecting: z.number(),\n failed: z.number(),\n disabled: z.number().optional(),\n })\n .passthrough();\n\nexport type McpStatusSummary = z.infer<typeof McpStatusSummarySchema>;\n\n// ---------------------------------------------------------------------------\n// MCP registry server\n// ---------------------------------------------------------------------------\n\n/** MCP registry server entity. */\nexport const McpRegistryServerSchema = z\n .object({\n name: z.string(),\n description: z.string(),\n type: z.nativeEnum(McpServerType),\n // Stdio config fields\n command: z.string().optional(),\n args: z.array(z.string()).optional(),\n // HTTP config fields\n url: z.string().optional(),\n // Additional metadata\n note: z.string().optional(),\n logoUrl: z.string().optional(),\n })\n .passthrough();\n\nexport type McpRegistryServer = z.infer<typeof McpRegistryServerSchema>;\n\n// ---------------------------------------------------------------------------\n// MCP tool info\n// ---------------------------------------------------------------------------\n\n/** JSON Schema subset for MCP tool input parameters. */\nexport const McpToolInputSchemaSchema = z\n .object({\n type: z.string().optional(),\n properties: z.record(z.unknown()).optional(),\n required: z.array(z.string()).optional(),\n })\n .passthrough();\n\nexport type McpToolInputSchema = z.infer<typeof McpToolInputSchemaSchema>;\n\n/** MCP tool information entity. */\nexport const McpToolInfoSchema = z\n .object({\n serverName: z.string(),\n name: z.string(),\n description: z.string().optional(),\n isEnabled: z.boolean(),\n isReadOnly: z.boolean().optional(),\n inputSchema: McpToolInputSchemaSchema.optional(),\n })\n .passthrough();\n\nexport type McpToolInfo = z.infer<typeof McpToolInfoSchema>;\n\n// ---------------------------------------------------------------------------\n// Tool confirmation list item\n// ---------------------------------------------------------------------------\n\n/** Selectable list item for tool confirmation prompts. */\nexport const ToolConfirmationListItemSchema = z\n .object({\n label: z.string(),\n value: z.nativeEnum(ToolConfirmationOutcome),\n })\n .passthrough();\n\nexport type ToolConfirmationListItem = z.infer<\n typeof ToolConfirmationListItemSchema\n>;\n","/**\n * Mission decomposition schemas for the Factory Droid protocol.\n *\n * Ported from: packages/common/src/droid/schemas/mission-decomposition.ts\n */\n\nimport { z } from \"zod\";\n\nimport {\n DismissalType,\n FeatureStatus,\n FeatureSuccessState,\n IssueSeverity,\n ProgressLogEntryType,\n} from \"./enums.js\";\n\n// ---------------------------------------------------------------------------\n// Feature schema\n// ---------------------------------------------------------------------------\n\n/** Mission feature schema. */\nexport const MissionFeatureSchema = z\n .object({\n id: z.string(),\n description: z.string(),\n status: z.nativeEnum(FeatureStatus),\n skillName: z.string(),\n preconditions: z.array(z.string()),\n expectedBehavior: z.array(z.string()),\n verificationSteps: z.array(z.string()),\n fulfills: z.array(z.string()).optional(),\n milestone: z.string().optional(),\n workerSessionIds: z.array(z.string()).optional(),\n currentWorkerSessionId: z.string().nullable().optional(),\n completedWorkerSessionId: z.string().nullable().optional(),\n })\n .passthrough();\n\nexport type MissionFeature = z.infer<typeof MissionFeatureSchema>;\n\n// ---------------------------------------------------------------------------\n// Handoff-related schemas\n// ---------------------------------------------------------------------------\n\nexport const FeatureSuccessStateSchema = z.nativeEnum(FeatureSuccessState);\n\n/** Discovered issue during feature implementation. */\nexport const DiscoveredIssueSchema = z\n .object({\n severity: z.nativeEnum(IssueSeverity),\n description: z.string(),\n suggestedFix: z.string().optional(),\n })\n .passthrough();\n\nexport type DiscoveredIssue = z.infer<typeof DiscoveredIssueSchema>;\n\n/** A command run during verification. */\nexport const VerificationCommandSchema = z\n .object({\n command: z.string(),\n exitCode: z.number(),\n observation: z.string(),\n })\n .passthrough();\n\nexport type VerificationCommand = z.infer<typeof VerificationCommandSchema>;\n\n/** An interactive check performed during verification. */\nexport const InteractiveCheckSchema = z\n .object({\n action: z.string(),\n observed: z.string(),\n })\n .passthrough();\n\nexport type InteractiveCheck = z.infer<typeof InteractiveCheckSchema>;\n\n/** Verification performed during feature implementation. */\nexport const VerificationSchema = z\n .object({\n commandsRun: z.array(VerificationCommandSchema),\n interactiveChecks: z.array(InteractiveCheckSchema).optional(),\n })\n .passthrough();\n\nexport type Verification = z.infer<typeof VerificationSchema>;\n\n/** A single test case. */\nexport const TestCaseSchema = z\n .object({\n name: z.string(),\n verifies: z.string(),\n })\n .passthrough();\n\nexport type TestCase = z.infer<typeof TestCaseSchema>;\n\n/** A test file with its test cases. */\nexport const TestFileSchema = z\n .object({\n file: z.string(),\n cases: z.array(TestCaseSchema),\n })\n .passthrough();\n\nexport type TestFile = z.infer<typeof TestFileSchema>;\n\n/** Test information for a feature implementation. */\nexport const TestsSchema = z\n .object({\n added: z.array(TestFileSchema),\n updated: z.array(z.string()).optional(),\n coverage: z.string(),\n })\n .passthrough();\n\nexport type Tests = z.infer<typeof TestsSchema>;\n\n/** A deviation from the skill procedure. */\nexport const SkillDeviationSchema = z\n .object({\n step: z.string(),\n whatIDidInstead: z.string(),\n why: z.string(),\n })\n .passthrough();\n\nexport type SkillDeviation = z.infer<typeof SkillDeviationSchema>;\n\n/** Feedback on the skill procedure. */\nexport const SkillFeedbackSchema = z\n .object({\n followedProcedure: z.boolean(),\n deviations: z.array(SkillDeviationSchema),\n suggestedChanges: z.array(z.string()).optional(),\n })\n .passthrough();\n\nexport type SkillFeedback = z.infer<typeof SkillFeedbackSchema>;\n\n/** Worker handoff information. */\nexport const HandoffSchema = z\n .object({\n salientSummary: z.string().optional(),\n whatWasImplemented: z.string(),\n whatWasLeftUndone: z.string(),\n verification: VerificationSchema,\n tests: TestsSchema,\n discoveredIssues: z.array(DiscoveredIssueSchema),\n skillFeedback: SkillFeedbackSchema.optional(),\n })\n .passthrough();\n\nexport type Handoff = z.infer<typeof HandoffSchema>;\n\n/** A record of a dismissed handoff item. */\nexport const DismissalRecordSchema = z\n .object({\n type: z.nativeEnum(DismissalType),\n sourceFeatureId: z.string(),\n summary: z.string(),\n justification: z.string(),\n })\n .passthrough();\n\nexport type DismissalRecord = z.infer<typeof DismissalRecordSchema>;\n\n// ---------------------------------------------------------------------------\n// Progress log entry schemas\n// ---------------------------------------------------------------------------\n\nconst BaseProgressLogEntrySchema = z.object({\n timestamp: z.string(),\n});\n\nexport const MissionAcceptedEntrySchema = BaseProgressLogEntrySchema.extend({\n type: z.literal(ProgressLogEntryType.MissionAccepted),\n title: z.string(),\n}).passthrough();\n\nexport type MissionAcceptedEntry = z.infer<typeof MissionAcceptedEntrySchema>;\n\nexport const MissionPausedEntrySchema = BaseProgressLogEntrySchema.extend({\n type: z.literal(ProgressLogEntryType.MissionPaused),\n}).passthrough();\n\nexport type MissionPausedEntry = z.infer<typeof MissionPausedEntrySchema>;\n\nexport const MissionResumedEntrySchema = BaseProgressLogEntrySchema.extend({\n type: z.literal(ProgressLogEntryType.MissionResumed),\n}).passthrough();\n\nexport type MissionResumedEntry = z.infer<typeof MissionResumedEntrySchema>;\n\nexport const MissionRunStartedEntrySchema = BaseProgressLogEntrySchema.extend({\n type: z.literal(ProgressLogEntryType.MissionRunStarted),\n message: z.string().optional(),\n}).passthrough();\n\nexport type MissionRunStartedEntry = z.infer<\n typeof MissionRunStartedEntrySchema\n>;\n\nexport const WorkerStartedEntrySchema = BaseProgressLogEntrySchema.extend({\n type: z.literal(ProgressLogEntryType.WorkerStarted),\n workerSessionId: z.string(),\n spawnId: z.string(),\n featureId: z.string().optional(),\n}).passthrough();\n\nexport type WorkerStartedEntry = z.infer<typeof WorkerStartedEntrySchema>;\n\nexport const WorkerSelectedFeatureEntrySchema =\n BaseProgressLogEntrySchema.extend({\n type: z.literal(ProgressLogEntryType.WorkerSelectedFeature),\n workerSessionId: z.string(),\n featureId: z.string(),\n }).passthrough();\n\nexport type WorkerSelectedFeatureEntry = z.infer<\n typeof WorkerSelectedFeatureEntrySchema\n>;\n\nexport const WorkerCompletedEntrySchema = BaseProgressLogEntrySchema.extend({\n type: z.literal(ProgressLogEntryType.WorkerCompleted),\n workerSessionId: z.string(),\n featureId: z.string(),\n successState: FeatureSuccessStateSchema,\n returnToOrchestrator: z.boolean(),\n commitId: z.string().optional(),\n exitCode: z.number(),\n validatorsPassed: z.boolean().optional(),\n handoff: HandoffSchema.optional(),\n}).passthrough();\n\nexport type WorkerCompletedEntry = z.infer<typeof WorkerCompletedEntrySchema>;\n\nexport const WorkerFailedEntrySchema = BaseProgressLogEntrySchema.extend({\n type: z.literal(ProgressLogEntryType.WorkerFailed),\n workerSessionId: z.string().optional(),\n spawnId: z.string(),\n exitCode: z.number().optional(),\n reason: z.string(),\n}).passthrough();\n\nexport type WorkerFailedEntry = z.infer<typeof WorkerFailedEntrySchema>;\n\nexport const WorkerPausedEntrySchema = BaseProgressLogEntrySchema.extend({\n type: z.literal(ProgressLogEntryType.WorkerPaused),\n workerSessionId: z.string(),\n featureId: z.string().optional(),\n}).passthrough();\n\nexport type WorkerPausedEntry = z.infer<typeof WorkerPausedEntrySchema>;\n\nexport const HandoffItemsDismissedEntrySchema =\n BaseProgressLogEntrySchema.extend({\n type: z.literal(ProgressLogEntryType.HandoffItemsDismissed),\n dismissals: z.array(DismissalRecordSchema).optional(),\n }).passthrough();\n\nexport type HandoffItemsDismissedEntry = z.infer<\n typeof HandoffItemsDismissedEntrySchema\n>;\n\nexport const MilestoneValidationTriggeredEntrySchema =\n BaseProgressLogEntrySchema.extend({\n type: z.literal(ProgressLogEntryType.MilestoneValidationTriggered),\n milestone: z.string(),\n featureId: z.string(),\n }).passthrough();\n\nexport type MilestoneValidationTriggeredEntry = z.infer<\n typeof MilestoneValidationTriggeredEntrySchema\n>;\n\n/** Discriminated union over all 11 progress log entry types. */\nexport const ProgressLogEntrySchema = z.discriminatedUnion(\"type\", [\n MissionAcceptedEntrySchema,\n MissionPausedEntrySchema,\n MissionResumedEntrySchema,\n MissionRunStartedEntrySchema,\n WorkerStartedEntrySchema,\n WorkerSelectedFeatureEntrySchema,\n WorkerCompletedEntrySchema,\n WorkerFailedEntrySchema,\n WorkerPausedEntrySchema,\n HandoffItemsDismissedEntrySchema,\n MilestoneValidationTriggeredEntrySchema,\n]);\n\nexport type ProgressLogEntry = z.infer<typeof ProgressLogEntrySchema>;\n","/**\n * Client→server request/response schemas for the Factory Droid protocol.\n *\n * All 19 client→server RPC method request/response pairs.\n *\n * Ported from: packages/common/src/droid/schemas/client.ts\n */\n\nimport { z } from \"zod\";\n\nimport {\n AutonomyLevel,\n AutonomyMode,\n DecompSessionType,\n DroidInteractionMode,\n DroidServerMethod,\n McpServerType,\n MissionState,\n ModelProvider,\n ReasoningEffort,\n SettingsLevel,\n SkillLocation,\n} from \"./enums.js\";\nimport {\n McpRegistryServerSchema,\n McpServerStatusInfoSchema,\n McpStatusSummarySchema,\n McpToolInfoSchema,\n} from \"./mcp.js\";\nimport { Base64ImageSourceSchema, DocumentSourceSchema } from \"./messages.js\";\nimport { MissionFeatureSchema, ProgressLogEntrySchema } from \"./mission.js\";\nimport {\n type JsonRpcResponseFailure,\n JsonRpcRequestSchema,\n JsonRpcResponseFailureSchema,\n JsonRpcResponseSuccessSchema,\n} from \"./shared.js\";\n\n// ---------------------------------------------------------------------------\n// Supporting types\n// ---------------------------------------------------------------------------\n\n/** Session tag metadata. */\nexport const SessionTagSchema = z\n .object({\n name: z.string(),\n metadata: z.record(z.string()).optional(),\n })\n .strict();\n\nexport type SessionTag = z.infer<typeof SessionTagSchema>;\n\n/** Session source information. */\nexport const SessionSourceSchema = z\n .object({\n platform: z.string(),\n })\n .passthrough();\n\nexport type SessionSource = z.infer<typeof SessionSourceSchema>;\n\n/** Stdio MCP server configuration for initialization. */\nexport const StdioMcpConfigSchema = z\n .object({\n name: z.string(),\n command: z.string(),\n args: z.array(z.string()).default([]),\n env: z.record(z.string()).optional().default({}),\n })\n .strict();\n\nexport type StdioMcpConfig = z.infer<typeof StdioMcpConfigSchema>;\n\n/** HTTP header for MCP server configuration. */\nexport const HttpHeaderSchema = z\n .object({\n name: z.string(),\n value: z.string(),\n })\n .strict();\n\nexport type HttpHeader = z.infer<typeof HttpHeaderSchema>;\n\n/** HTTP MCP server configuration for initialization. */\nexport const HttpMcpConfigSchema = z\n .object({\n type: z.literal(\"http\"),\n name: z.string(),\n url: z.string().url(),\n headers: HttpHeaderSchema.array().default([]),\n })\n .strict();\n\nexport type HttpMcpConfig = z.infer<typeof HttpMcpConfigSchema>;\n\n/** SSE MCP server configuration for initialization. */\nexport const SseMcpConfigSchema = z\n .object({\n type: z.literal(\"sse\"),\n name: z.string(),\n url: z.string().url(),\n headers: HttpHeaderSchema.array().default([]),\n })\n .strict();\n\nexport type SseMcpConfig = z.infer<typeof SseMcpConfigSchema>;\n\n/** Union of MCP server configs. */\nexport const McpServerConfigSchema = z.union([\n StdioMcpConfigSchema,\n HttpMcpConfigSchema,\n SseMcpConfigSchema,\n]);\n\nexport type McpServerConfig = z.infer<typeof McpServerConfigSchema>;\n\n/** Session settings returned in init/load results. */\nexport const SessionSettingsSchema = z\n .object({\n modelId: z.string(),\n reasoningEffort: z.nativeEnum(ReasoningEffort),\n autonomyMode: z.nativeEnum(AutonomyMode).optional(),\n interactionMode: z.nativeEnum(DroidInteractionMode).optional().catch(undefined),\n autonomyLevel: z.nativeEnum(AutonomyLevel).optional().catch(undefined),\n specModeModelId: z.string().optional(),\n specModeReasoningEffort: z.nativeEnum(ReasoningEffort).optional(),\n })\n .passthrough();\n\nexport type SessionSettings = z.infer<typeof SessionSettingsSchema>;\n\n/** Git repository information. */\nexport const GitRepoInfoSchema = z\n .object({\n owner: z.string().optional(),\n repoName: z.string(),\n })\n .passthrough();\n\nexport type GitRepoInfo = z.infer<typeof GitRepoInfoSchema>;\n\n/** Available model configuration returned in session init/load responses. */\nexport const AvailableModelConfigSchema = z\n .object({\n id: z.string(),\n modelId: z.string().optional(),\n displayName: z.string(),\n shortDisplayName: z.string(),\n modelProvider: z.nativeEnum(ModelProvider),\n supportedReasoningEfforts: z.array(z.nativeEnum(ReasoningEffort)),\n defaultReasoningEffort: z.nativeEnum(ReasoningEffort),\n isCustom: z.boolean().default(false),\n noImageSupport: z.boolean().optional(),\n supportsPDFs: z.boolean().optional(),\n tier: z.string().optional(),\n tokenMultiplier: z.number().optional(),\n promoLabel: z.string().optional(),\n featureFlag: z.record(z.unknown()).optional(),\n usesUSBasedInference: z.boolean().optional(),\n })\n .passthrough();\n\nexport type AvailableModelConfig = z.infer<typeof AvailableModelConfigSchema>;\n\n/** Token usage information for a session. */\nexport const TokenUsageSchema = z\n .object({\n inputTokens: z.number(),\n outputTokens: z.number(),\n cacheCreationTokens: z.number(),\n cacheReadTokens: z.number(),\n thinkingTokens: z.number(),\n })\n .passthrough();\n\nexport type TokenUsage = z.infer<typeof TokenUsageSchema>;\n\n/** Worker state information for mission snapshots. */\nexport const WorkerStateInfoSchema = z\n .object({\n startedAt: z.string(),\n completedAt: z.string().optional(),\n exitCode: z.number().optional(),\n })\n .passthrough();\n\nexport type WorkerStateInfo = z.infer<typeof WorkerStateInfoSchema>;\n\n/** Skill resource file in a skill folder. */\nexport const SkillResourceSchema = z\n .object({\n name: z.string(),\n path: z.string(),\n type: z.enum([\"reference\", \"asset\"]),\n })\n .passthrough();\n\nexport type SkillResource = z.infer<typeof SkillResourceSchema>;\n\n/** Skill information returned by list_skills. */\nexport const SkillInfoSchema = z\n .object({\n name: z.string(),\n description: z.string().optional(),\n location: z.nativeEnum(SkillLocation),\n filePath: z.string(),\n enabled: z.boolean().optional(),\n userInvocable: z.boolean().optional(),\n version: z.string().optional(),\n content: z.string().optional(),\n resources: z.array(SkillResourceSchema).optional(),\n })\n .passthrough();\n\nexport type SkillInfo = z.infer<typeof SkillInfoSchema>;\n\n// ---------------------------------------------------------------------------\n// Request params schemas\n// ---------------------------------------------------------------------------\n\n/** Parameters for droid.initialize_session request. */\nexport const InitializeSessionRequestParamsSchema = z\n .object({\n machineId: z.string(),\n cwd: z.string(),\n workspaceId: z.string().optional(),\n sessionId: z.string().optional(),\n mcpServers: z.array(McpServerConfigSchema).optional(),\n autonomyMode: z.nativeEnum(AutonomyMode).optional(),\n interactionMode: z.nativeEnum(DroidInteractionMode).optional().catch(undefined),\n autonomyLevel: z.nativeEnum(AutonomyLevel).optional().catch(undefined),\n modelId: z.string().optional(),\n reasoningEffort: z.nativeEnum(ReasoningEffort).optional(),\n specModeModelId: z.string().optional(),\n specModeReasoningEffort: z.nativeEnum(ReasoningEffort).optional(),\n decompSessionType: z.nativeEnum(DecompSessionType).optional(),\n decompMissionId: z.string().optional(),\n skipPermissionsUnsafe: z.boolean().optional(),\n enabledToolIds: z.array(z.string()).optional(),\n sessionLocation: z.string().optional(),\n sessionSource: SessionSourceSchema.optional(),\n tags: z.array(SessionTagSchema).optional(),\n mcpOAuthCallbackUri: z.string().optional(),\n })\n .strict();\n\nexport type InitializeSessionRequestParams = z.infer<\n typeof InitializeSessionRequestParamsSchema\n>;\n\n/** Parameters for droid.load_session request. */\nexport const LoadSessionRequestParamsSchema = z\n .object({\n sessionId: z.string(),\n mcpServers: z.array(McpServerConfigSchema).optional(),\n mcpOAuthCallbackUri: z.string().optional(),\n })\n .strict();\n\nexport type LoadSessionRequestParams = z.infer<\n typeof LoadSessionRequestParamsSchema\n>;\n\n/** Parameters for droid.add_user_message request. */\nexport const AddUserMessageRequestParamsSchema = z\n .object({\n messageId: z.string().optional(),\n text: z.string(),\n images: z.array(Base64ImageSourceSchema).optional(),\n files: z.array(DocumentSourceSchema).optional(),\n })\n .strict();\n\nexport type AddUserMessageRequestParams = z.infer<\n typeof AddUserMessageRequestParamsSchema\n>;\n\n/** Parameters for droid.interrupt_session request (empty). */\nexport const InterruptSessionRequestParamsSchema = z.object({}).strict();\n\nexport type InterruptSessionRequestParams = z.infer<\n typeof InterruptSessionRequestParamsSchema\n>;\n\n/** Parameters for droid.kill_worker_session request. */\nexport const KillWorkerSessionRequestParamsSchema = z\n .object({\n workerSessionId: z.string(),\n })\n .strict();\n\nexport type KillWorkerSessionRequestParams = z.infer<\n typeof KillWorkerSessionRequestParamsSchema\n>;\n\n/** Parameters for droid.update_session_settings request. */\nexport const UpdateSessionSettingsRequestParamsSchema = z\n .object({\n modelId: z.string().optional(),\n reasoningEffort: z.nativeEnum(ReasoningEffort).optional(),\n autonomyMode: z.nativeEnum(AutonomyMode).optional(),\n interactionMode: z.nativeEnum(DroidInteractionMode).optional().catch(undefined),\n autonomyLevel: z.nativeEnum(AutonomyLevel).optional().catch(undefined),\n specModeModelId: z.string().nullable().optional(),\n specModeReasoningEffort: z.nativeEnum(ReasoningEffort).nullable().optional(),\n })\n .strict();\n\nexport type UpdateSessionSettingsRequestParams = z.infer<\n typeof UpdateSessionSettingsRequestParamsSchema\n>;\n\n/** Parameters for droid.toggle_mcp_server request. */\nexport const ToggleMcpServerRequestParamsSchema = z\n .object({\n serverName: z.string(),\n enabled: z.boolean(),\n settingsLevel: z.literal(SettingsLevel.User),\n })\n .strict();\n\nexport type ToggleMcpServerRequestParams = z.infer<\n typeof ToggleMcpServerRequestParamsSchema\n>;\n\n/** Parameters for droid.authenticate_mcp_server request. */\nexport const AuthenticateMcpServerRequestParamsSchema = z\n .object({\n serverName: z.string(),\n })\n .strict();\n\nexport type AuthenticateMcpServerRequestParams = z.infer<\n typeof AuthenticateMcpServerRequestParamsSchema\n>;\n\n/** Parameters for droid.cancel_mcp_auth request. */\nexport const CancelMcpAuthRequestParamsSchema = z\n .object({\n serverName: z.string(),\n })\n .strict();\n\nexport type CancelMcpAuthRequestParams = z.infer<\n typeof CancelMcpAuthRequestParamsSchema\n>;\n\n/** Parameters for droid.clear_mcp_auth request. */\nexport const ClearMcpAuthRequestParamsSchema = z\n .object({\n serverName: z.string(),\n })\n .strict();\n\nexport type ClearMcpAuthRequestParams = z.infer<\n typeof ClearMcpAuthRequestParamsSchema\n>;\n\n/** Parameters for droid.submit_mcp_auth_code request. */\nexport const SubmitMcpAuthCodeRequestParamsSchema = z\n .object({\n serverName: z.string(),\n code: z.string(),\n state: z.string(),\n })\n .strict();\n\nexport type SubmitMcpAuthCodeRequestParams = z.infer<\n typeof SubmitMcpAuthCodeRequestParamsSchema\n>;\n\n/** Parameters for droid.add_mcp_server request. */\nexport const AddMcpServerRequestParamsSchema = z\n .object({\n name: z.string(),\n type: z.nativeEnum(McpServerType),\n url: z.string().optional(),\n headers: z.record(z.string()).optional(),\n command: z.string().optional(),\n args: z.array(z.string()).optional(),\n env: z.record(z.string()).optional(),\n })\n .strict();\n\nexport type AddMcpServerRequestParams = z.infer<\n typeof AddMcpServerRequestParamsSchema\n>;\n\n/** Parameters for droid.remove_mcp_server request. */\nexport const RemoveMcpServerRequestParamsSchema = z\n .object({\n serverName: z.string(),\n settingsLevel: z.literal(SettingsLevel.User),\n })\n .strict();\n\nexport type RemoveMcpServerRequestParams = z.infer<\n typeof RemoveMcpServerRequestParamsSchema\n>;\n\n/** Parameters for droid.list_mcp_registry request (empty). */\nexport const ListMcpRegistryRequestParamsSchema = z.object({}).strict();\n\nexport type ListMcpRegistryRequestParams = z.infer<\n typeof ListMcpRegistryRequestParamsSchema\n>;\n\n/** Parameters for droid.list_mcp_tools request (empty). */\nexport const ListMcpToolsRequestParamsSchema = z.object({}).strict();\n\nexport type ListMcpToolsRequestParams = z.infer<\n typeof ListMcpToolsRequestParamsSchema\n>;\n\n/** Parameters for droid.list_mcp_servers request (empty). */\nexport const ListMcpServersRequestParamsSchema = z.object({}).strict();\n\nexport type ListMcpServersRequestParams = z.infer<\n typeof ListMcpServersRequestParamsSchema\n>;\n\n/** Parameters for droid.toggle_mcp_tool request. */\nexport const ToggleMcpToolRequestParamsSchema = z\n .object({\n serverName: z.string(),\n toolName: z.string(),\n enabled: z.boolean(),\n })\n .strict();\n\nexport type ToggleMcpToolRequestParams = z.infer<\n typeof ToggleMcpToolRequestParamsSchema\n>;\n\n/** Parameters for droid.list_skills request (empty). */\nexport const ListSkillsRequestParamsSchema = z.object({}).strict();\n\nexport type ListSkillsRequestParams = z.infer<\n typeof ListSkillsRequestParamsSchema\n>;\n\n/** Parameters for droid.submit_bug_report request. */\nexport const SubmitBugReportRequestParamsSchema = z\n .object({\n userComment: z.string(),\n clientLogs: z.string().optional(),\n })\n .strict();\n\nexport type SubmitBugReportRequestParams = z.infer<\n typeof SubmitBugReportRequestParamsSchema\n>;\n\n// ---------------------------------------------------------------------------\n// Full request schemas (JsonRpcRequest + method literal + typed params)\n// ---------------------------------------------------------------------------\n\nexport const InitializeSessionRequestSchema = JsonRpcRequestSchema.extend({\n method: z.literal(DroidServerMethod.INITIALIZE_SESSION),\n params: InitializeSessionRequestParamsSchema,\n});\n\nexport type InitializeSessionRequest = z.infer<typeof InitializeSessionRequestSchema>;\n\nexport const LoadSessionRequestSchema = JsonRpcRequestSchema.extend({\n method: z.literal(DroidServerMethod.LOAD_SESSION),\n params: LoadSessionRequestParamsSchema,\n});\n\nexport type LoadSessionRequest = z.infer<typeof LoadSessionRequestSchema>;\n\nexport const AddUserMessageRequestSchema = JsonRpcRequestSchema.extend({\n method: z.literal(DroidServerMethod.ADD_USER_MESSAGE),\n params: AddUserMessageRequestParamsSchema,\n});\n\nexport type AddUserMessageRequest = z.infer<typeof AddUserMessageRequestSchema>;\n\nexport const InterruptSessionRequestSchema = JsonRpcRequestSchema.extend({\n method: z.literal(DroidServerMethod.INTERRUPT_SESSION),\n params: InterruptSessionRequestParamsSchema,\n});\n\nexport type InterruptSessionRequest = z.infer<typeof InterruptSessionRequestSchema>;\n\nexport const KillWorkerSessionRequestSchema = JsonRpcRequestSchema.extend({\n method: z.literal(DroidServerMethod.KILL_WORKER_SESSION),\n params: KillWorkerSessionRequestParamsSchema,\n});\n\nexport type KillWorkerSessionRequest = z.infer<typeof KillWorkerSessionRequestSchema>;\n\nexport const UpdateSessionSettingsRequestSchema = JsonRpcRequestSchema.extend({\n method: z.literal(DroidServerMethod.UPDATE_SESSION_SETTINGS),\n params: UpdateSessionSettingsRequestParamsSchema,\n});\n\nexport type UpdateSessionSettingsRequest = z.infer<typeof UpdateSessionSettingsRequestSchema>;\n\nexport const ToggleMcpServerRequestSchema = JsonRpcRequestSchema.extend({\n method: z.literal(DroidServerMethod.TOGGLE_MCP_SERVER),\n params: ToggleMcpServerRequestParamsSchema,\n});\n\nexport type ToggleMcpServerRequest = z.infer<typeof ToggleMcpServerRequestSchema>;\n\nexport const AuthenticateMcpServerRequestSchema = JsonRpcRequestSchema.extend({\n method: z.literal(DroidServerMethod.AUTHENTICATE_MCP_SERVER),\n params: AuthenticateMcpServerRequestParamsSchema,\n});\n\nexport type AuthenticateMcpServerRequest = z.infer<typeof AuthenticateMcpServerRequestSchema>;\n\nexport const CancelMcpAuthRequestSchema = JsonRpcRequestSchema.extend({\n method: z.literal(DroidServerMethod.CANCEL_MCP_AUTH),\n params: CancelMcpAuthRequestParamsSchema,\n});\n\nexport type CancelMcpAuthRequest = z.infer<typeof CancelMcpAuthRequestSchema>;\n\nexport const ClearMcpAuthRequestSchema = JsonRpcRequestSchema.extend({\n method: z.literal(DroidServerMethod.CLEAR_MCP_AUTH),\n params: ClearMcpAuthRequestParamsSchema,\n});\n\nexport type ClearMcpAuthRequest = z.infer<typeof ClearMcpAuthRequestSchema>;\n\nexport const SubmitMcpAuthCodeRequestSchema = JsonRpcRequestSchema.extend({\n method: z.literal(DroidServerMethod.SUBMIT_MCP_AUTH_CODE),\n params: SubmitMcpAuthCodeRequestParamsSchema,\n});\n\nexport type SubmitMcpAuthCodeRequest = z.infer<typeof SubmitMcpAuthCodeRequestSchema>;\n\nexport const AddMcpServerRequestSchema = JsonRpcRequestSchema.extend({\n method: z.literal(DroidServerMethod.ADD_MCP_SERVER),\n params: AddMcpServerRequestParamsSchema,\n});\n\nexport type AddMcpServerRequest = z.infer<typeof AddMcpServerRequestSchema>;\n\nexport const RemoveMcpServerRequestSchema = JsonRpcRequestSchema.extend({\n method: z.literal(DroidServerMethod.REMOVE_MCP_SERVER),\n params: RemoveMcpServerRequestParamsSchema,\n});\n\nexport type RemoveMcpServerRequest = z.infer<typeof RemoveMcpServerRequestSchema>;\n\nexport const ListMcpRegistryRequestSchema = JsonRpcRequestSchema.extend({\n method: z.literal(DroidServerMethod.LIST_MCP_REGISTRY),\n params: ListMcpRegistryRequestParamsSchema,\n});\n\nexport type ListMcpRegistryRequest = z.infer<typeof ListMcpRegistryRequestSchema>;\n\nexport const ListMcpToolsRequestSchema = JsonRpcRequestSchema.extend({\n method: z.literal(DroidServerMethod.LIST_MCP_TOOLS),\n params: ListMcpToolsRequestParamsSchema,\n});\n\nexport type ListMcpToolsRequest = z.infer<typeof ListMcpToolsRequestSchema>;\n\nexport const ListMcpServersRequestSchema = JsonRpcRequestSchema.extend({\n method: z.literal(DroidServerMethod.LIST_MCP_SERVERS),\n params: ListMcpServersRequestParamsSchema,\n});\n\nexport type ListMcpServersRequest = z.infer<typeof ListMcpServersRequestSchema>;\n\nexport const ToggleMcpToolRequestSchema = JsonRpcRequestSchema.extend({\n method: z.literal(DroidServerMethod.TOGGLE_MCP_TOOL),\n params: ToggleMcpToolRequestParamsSchema,\n});\n\nexport type ToggleMcpToolRequest = z.infer<typeof ToggleMcpToolRequestSchema>;\n\nexport const ListSkillsRequestSchema = JsonRpcRequestSchema.extend({\n method: z.literal(DroidServerMethod.LIST_SKILLS),\n params: ListSkillsRequestParamsSchema,\n});\n\nexport type ListSkillsRequest = z.infer<typeof ListSkillsRequestSchema>;\n\nexport const SubmitBugReportRequestSchema = JsonRpcRequestSchema.extend({\n method: z.literal(DroidServerMethod.SUBMIT_BUG_REPORT),\n params: SubmitBugReportRequestParamsSchema,\n});\n\nexport type SubmitBugReportRequest = z.infer<typeof SubmitBugReportRequestSchema>;\n\n/** Discriminated union over all 19 client→server request types. */\nexport const ClientRequestSchema = z.discriminatedUnion(\"method\", [\n InitializeSessionRequestSchema,\n LoadSessionRequestSchema,\n AddUserMessageRequestSchema,\n InterruptSessionRequestSchema,\n KillWorkerSessionRequestSchema,\n UpdateSessionSettingsRequestSchema,\n ToggleMcpServerRequestSchema,\n AuthenticateMcpServerRequestSchema,\n CancelMcpAuthRequestSchema,\n ClearMcpAuthRequestSchema,\n SubmitMcpAuthCodeRequestSchema,\n AddMcpServerRequestSchema,\n RemoveMcpServerRequestSchema,\n ListMcpRegistryRequestSchema,\n ListMcpToolsRequestSchema,\n ListMcpServersRequestSchema,\n ToggleMcpToolRequestSchema,\n ListSkillsRequestSchema,\n SubmitBugReportRequestSchema,\n]);\n\nexport type ClientRequest = z.infer<typeof ClientRequestSchema>;\n\n// ---------------------------------------------------------------------------\n// Result schemas (all use passthrough for forward-compatibility)\n// ---------------------------------------------------------------------------\n\n/** Mission state snapshot (for orchestrator sessions). */\nexport const MissionSnapshotSchema = z\n .object({\n state: z.nativeEnum(MissionState),\n features: z.array(MissionFeatureSchema),\n progressLog: z.array(ProgressLogEntrySchema),\n workerSessionIds: z.array(z.string()),\n workerStates: z.record(WorkerStateInfoSchema).optional(),\n tokenUsage: TokenUsageSchema.optional(),\n tokenUsageBySessionId: z.record(TokenUsageSchema).optional(),\n })\n .passthrough();\n\nexport type MissionSnapshot = z.infer<typeof MissionSnapshotSchema>;\n\n/** Result for droid.initialize_session response. */\nexport const InitializeSessionResultSchema = z\n .object({\n sessionId: z.string(),\n session: z.record(z.unknown()),\n mcpServers: z.array(McpServerConfigSchema).optional(),\n settings: SessionSettingsSchema,\n gitRepo: GitRepoInfoSchema.optional(),\n availableModels: z.array(AvailableModelConfigSchema).optional(),\n })\n .passthrough();\n\nexport type InitializeSessionResult = z.infer<\n typeof InitializeSessionResultSchema\n>;\n\n/** Result for droid.load_session response. */\nexport const LoadSessionResultSchema = z\n .object({\n session: z.record(z.unknown()),\n mcpServers: z.array(McpServerConfigSchema).optional(),\n pendingPermissions: z.array(z.record(z.unknown())).optional(),\n pendingAskUserRequests: z.array(z.record(z.unknown())).optional(),\n settings: SessionSettingsSchema,\n isAgentLoopInProgress: z.boolean().optional(),\n queuedMessages: z.array(z.record(z.unknown())).optional(),\n gitRepo: GitRepoInfoSchema.optional(),\n cwd: z.string().optional(),\n callingSessionId: z.string().optional(),\n callingToolUseId: z.string().optional(),\n availableModels: z.array(AvailableModelConfigSchema).optional(),\n tokenUsage: TokenUsageSchema.optional(),\n mission: MissionSnapshotSchema.optional(),\n decompSessionType: z.nativeEnum(DecompSessionType).optional(),\n })\n .passthrough();\n\nexport type LoadSessionResult = z.infer<typeof LoadSessionResultSchema>;\n\n/** Result for droid.add_user_message response (empty). */\nexport const AddUserMessageResultSchema = z.object({}).passthrough();\n\nexport type AddUserMessageResult = z.infer<typeof AddUserMessageResultSchema>;\n\n/** Result for droid.interrupt_session response (empty). */\nexport const InterruptSessionResultSchema = z.object({}).passthrough();\n\nexport type InterruptSessionResult = z.infer<\n typeof InterruptSessionResultSchema\n>;\n\n/** Result for droid.kill_worker_session response (empty). */\nexport const KillWorkerSessionResultSchema = z.object({}).passthrough();\n\nexport type KillWorkerSessionResult = z.infer<\n typeof KillWorkerSessionResultSchema\n>;\n\n/** Result for droid.update_session_settings response (empty). */\nexport const UpdateSessionSettingsResultSchema = z.object({}).passthrough();\n\nexport type UpdateSessionSettingsResult = z.infer<\n typeof UpdateSessionSettingsResultSchema\n>;\n\n/** Result for droid.toggle_mcp_server response. */\nexport const ToggleMcpServerResultSchema = z\n .object({ success: z.boolean() })\n .passthrough();\n\nexport type ToggleMcpServerResult = z.infer<typeof ToggleMcpServerResultSchema>;\n\n/** Result for droid.authenticate_mcp_server response. */\nexport const AuthenticateMcpServerResultSchema = z\n .object({ success: z.boolean() })\n .passthrough();\n\nexport type AuthenticateMcpServerResult = z.infer<\n typeof AuthenticateMcpServerResultSchema\n>;\n\n/** Result for droid.cancel_mcp_auth response. */\nexport const CancelMcpAuthResultSchema = z\n .object({ success: z.boolean() })\n .passthrough();\n\nexport type CancelMcpAuthResult = z.infer<typeof CancelMcpAuthResultSchema>;\n\n/** Result for droid.clear_mcp_auth response. */\nexport const ClearMcpAuthResultSchema = z\n .object({ success: z.boolean() })\n .passthrough();\n\nexport type ClearMcpAuthResult = z.infer<typeof ClearMcpAuthResultSchema>;\n\n/** Result for droid.submit_mcp_auth_code response. */\nexport const SubmitMcpAuthCodeResultSchema = z\n .object({ success: z.boolean() })\n .passthrough();\n\nexport type SubmitMcpAuthCodeResult = z.infer<\n typeof SubmitMcpAuthCodeResultSchema\n>;\n\n/** Result for droid.add_mcp_server response. */\nexport const AddMcpServerResultSchema = z\n .object({ success: z.boolean() })\n .passthrough();\n\nexport type AddMcpServerResult = z.infer<typeof AddMcpServerResultSchema>;\n\n/** Result for droid.remove_mcp_server response. */\nexport const RemoveMcpServerResultSchema = z\n .object({ success: z.boolean() })\n .passthrough();\n\nexport type RemoveMcpServerResult = z.infer<typeof RemoveMcpServerResultSchema>;\n\n/** Result for droid.list_mcp_registry response. */\nexport const ListMcpRegistryResultSchema = z\n .object({ servers: z.array(McpRegistryServerSchema) })\n .passthrough();\n\nexport type ListMcpRegistryResult = z.infer<typeof ListMcpRegistryResultSchema>;\n\n/** Result for droid.list_mcp_tools response. */\nexport const ListMcpToolsResultSchema = z\n .object({ tools: z.array(McpToolInfoSchema) })\n .passthrough();\n\nexport type ListMcpToolsResult = z.infer<typeof ListMcpToolsResultSchema>;\n\n/** Result for droid.list_mcp_servers response. */\nexport const ListMcpServersResultSchema = z\n .object({\n servers: z.array(McpServerStatusInfoSchema),\n summary: McpStatusSummarySchema,\n })\n .passthrough();\n\nexport type ListMcpServersResult = z.infer<typeof ListMcpServersResultSchema>;\n\n/** Result for droid.toggle_mcp_tool response. */\nexport const ToggleMcpToolResultSchema = z\n .object({ success: z.boolean() })\n .passthrough();\n\nexport type ToggleMcpToolResult = z.infer<typeof ToggleMcpToolResultSchema>;\n\n/** Result for droid.list_skills response. */\nexport const ListSkillsResultSchema = z\n .object({ skills: z.array(SkillInfoSchema) })\n .passthrough();\n\nexport type ListSkillsResult = z.infer<typeof ListSkillsResultSchema>;\n\n/** Result for droid.submit_bug_report response. */\nexport const SubmitBugReportResultSchema = z\n .object({ bugReportId: z.string() })\n .passthrough();\n\nexport type SubmitBugReportResult = z.infer<typeof SubmitBugReportResultSchema>;\n\n// ---------------------------------------------------------------------------\n// Response schemas (union of success | failure)\n// ---------------------------------------------------------------------------\n\nexport const InitializeSessionResponseSchema = z.union([\n JsonRpcResponseSuccessSchema.extend({\n result: InitializeSessionResultSchema,\n }),\n JsonRpcResponseFailureSchema,\n]);\n\nexport type InitializeSessionResponse = z.infer<typeof InitializeSessionResponseSchema>;\n\n/** Concrete type for LoadSessionResponse (avoids TS7056 deep inference). */\nexport type LoadSessionResponse =\n | (Omit<z.infer<typeof JsonRpcResponseSuccessSchema>, \"result\"> & { result: LoadSessionResult })\n | JsonRpcResponseFailure;\n\nconst _LoadSessionResponseSchema = z.union([\n JsonRpcResponseSuccessSchema.extend({ result: LoadSessionResultSchema }),\n JsonRpcResponseFailureSchema,\n]);\n\nexport const LoadSessionResponseSchema: z.ZodType<\n LoadSessionResponse,\n z.ZodTypeDef,\n unknown\n> = _LoadSessionResponseSchema as z.ZodType<LoadSessionResponse, z.ZodTypeDef, unknown>;\n\nexport const AddUserMessageResponseSchema = z.union([\n JsonRpcResponseSuccessSchema.extend({ result: AddUserMessageResultSchema }),\n JsonRpcResponseFailureSchema,\n]);\n\nexport type AddUserMessageResponse = z.infer<typeof AddUserMessageResponseSchema>;\n\nexport const InterruptSessionResponseSchema = z.union([\n JsonRpcResponseSuccessSchema.extend({\n result: InterruptSessionResultSchema,\n }),\n JsonRpcResponseFailureSchema,\n]);\n\nexport type InterruptSessionResponse = z.infer<typeof InterruptSessionResponseSchema>;\n\nexport const KillWorkerSessionResponseSchema = z.union([\n JsonRpcResponseSuccessSchema.extend({\n result: KillWorkerSessionResultSchema,\n }),\n JsonRpcResponseFailureSchema,\n]);\n\nexport type KillWorkerSessionResponse = z.infer<typeof KillWorkerSessionResponseSchema>;\n\nexport const UpdateSessionSettingsResponseSchema = z.union([\n JsonRpcResponseSuccessSchema.extend({\n result: UpdateSessionSettingsResultSchema,\n }),\n JsonRpcResponseFailureSchema,\n]);\n\nexport type UpdateSessionSettingsResponse = z.infer<typeof UpdateSessionSettingsResponseSchema>;\n\nexport const ToggleMcpServerResponseSchema = z.union([\n JsonRpcResponseSuccessSchema.extend({\n result: ToggleMcpServerResultSchema,\n }),\n JsonRpcResponseFailureSchema,\n]);\n\nexport type ToggleMcpServerResponse = z.infer<typeof ToggleMcpServerResponseSchema>;\n\nexport const AuthenticateMcpServerResponseSchema = z.union([\n JsonRpcResponseSuccessSchema.extend({\n result: AuthenticateMcpServerResultSchema,\n }),\n JsonRpcResponseFailureSchema,\n]);\n\nexport type AuthenticateMcpServerResponse = z.infer<typeof AuthenticateMcpServerResponseSchema>;\n\nexport const CancelMcpAuthResponseSchema = z.union([\n JsonRpcResponseSuccessSchema.extend({ result: CancelMcpAuthResultSchema }),\n JsonRpcResponseFailureSchema,\n]);\n\nexport type CancelMcpAuthResponse = z.infer<typeof CancelMcpAuthResponseSchema>;\n\nexport const ClearMcpAuthResponseSchema = z.union([\n JsonRpcResponseSuccessSchema.extend({ result: ClearMcpAuthResultSchema }),\n JsonRpcResponseFailureSchema,\n]);\n\nexport type ClearMcpAuthResponse = z.infer<typeof ClearMcpAuthResponseSchema>;\n\nexport const SubmitMcpAuthCodeResponseSchema = z.union([\n JsonRpcResponseSuccessSchema.extend({\n result: SubmitMcpAuthCodeResultSchema,\n }),\n JsonRpcResponseFailureSchema,\n]);\n\nexport type SubmitMcpAuthCodeResponse = z.infer<typeof SubmitMcpAuthCodeResponseSchema>;\n\nexport const AddMcpServerResponseSchema = z.union([\n JsonRpcResponseSuccessSchema.extend({ result: AddMcpServerResultSchema }),\n JsonRpcResponseFailureSchema,\n]);\n\nexport type AddMcpServerResponse = z.infer<typeof AddMcpServerResponseSchema>;\n\nexport const RemoveMcpServerResponseSchema = z.union([\n JsonRpcResponseSuccessSchema.extend({ result: RemoveMcpServerResultSchema }),\n JsonRpcResponseFailureSchema,\n]);\n\nexport type RemoveMcpServerResponse = z.infer<typeof RemoveMcpServerResponseSchema>;\n\nexport const ListMcpRegistryResponseSchema = z.union([\n JsonRpcResponseSuccessSchema.extend({\n result: ListMcpRegistryResultSchema,\n }),\n JsonRpcResponseFailureSchema,\n]);\n\nexport type ListMcpRegistryResponse = z.infer<typeof ListMcpRegistryResponseSchema>;\n\nexport const ListMcpToolsResponseSchema = z.union([\n JsonRpcResponseSuccessSchema.extend({ result: ListMcpToolsResultSchema }),\n JsonRpcResponseFailureSchema,\n]);\n\nexport type ListMcpToolsResponse = z.infer<typeof ListMcpToolsResponseSchema>;\n\nexport const ListMcpServersResponseSchema = z.union([\n JsonRpcResponseSuccessSchema.extend({ result: ListMcpServersResultSchema }),\n JsonRpcResponseFailureSchema,\n]);\n\nexport type ListMcpServersResponse = z.infer<typeof ListMcpServersResponseSchema>;\n\nexport const ToggleMcpToolResponseSchema = z.union([\n JsonRpcResponseSuccessSchema.extend({ result: ToggleMcpToolResultSchema }),\n JsonRpcResponseFailureSchema,\n]);\n\nexport type ToggleMcpToolResponse = z.infer<typeof ToggleMcpToolResponseSchema>;\n\nexport const ListSkillsResponseSchema = z.union([\n JsonRpcResponseSuccessSchema.extend({ result: ListSkillsResultSchema }),\n JsonRpcResponseFailureSchema,\n]);\n\nexport type ListSkillsResponse = z.infer<typeof ListSkillsResponseSchema>;\n\nexport const SubmitBugReportResponseSchema = z.union([\n JsonRpcResponseSuccessSchema.extend({ result: SubmitBugReportResultSchema }),\n JsonRpcResponseFailureSchema,\n]);\n\nexport type SubmitBugReportResponse = z.infer<typeof SubmitBugReportResponseSchema>;\n","/**\n * Server→client schemas: notification payloads, permission requests, and ask-user requests.\n *\n * Ported from: packages/common/src/droid/schemas/cli.ts\n */\n\nimport { z } from \"zod\";\n\nimport { TokenUsageSchema } from \"./client.js\";\nimport {\n AutonomyLevel,\n AutonomyMode,\n DroidClientMethod,\n DroidErrorType,\n DroidInteractionMode,\n DroidWorkingState,\n McpAuthOutcome,\n MissionState,\n ReasoningEffort,\n SessionNotificationType,\n ToolConfirmationOutcome,\n ToolConfirmationType,\n} from \"./enums.js\";\nimport { FactoryDroidMessageSchema } from \"./messages.js\";\nimport {\n McpServerStatusInfoSchema,\n McpStatusSummarySchema,\n ToolConfirmationListItemSchema,\n} from \"./mcp.js\";\nimport { MissionFeatureSchema, ProgressLogEntrySchema } from \"./mission.js\";\nimport {\n JsonRpcNotificationSchema,\n JsonRpcRequestSchema,\n JsonRpcResponseFailureSchema,\n JsonRpcResponseSuccessSchema,\n} from \"./shared.js\";\n\n// ---------------------------------------------------------------------------\n// Supporting types for notification payloads\n// ---------------------------------------------------------------------------\n\n/** Tool use block (from ToolUseSchema in sessionV2/messages). */\nexport const ToolUseSchema = z\n .object({\n type: z.literal(\"tool_use\"),\n id: z.string(),\n input: z.record(z.unknown()),\n name: z.string(),\n thoughtSignature: z.string().optional(),\n })\n .passthrough();\n\nexport type ToolUse = z.infer<typeof ToolUseSchema>;\n\n/** Error detail object within an ErrorNotification. */\nexport const ErrorDetailSchema = z\n .object({\n name: z.string(),\n message: z.string(),\n })\n .passthrough();\n\nexport type ErrorDetail = z.infer<typeof ErrorDetailSchema>;\n\n/** Streaming update from subagent tool calls. */\nexport const ToolProgressUpdateSchema = z\n .object({\n type: z.enum([\"tool_call\", \"tool_result\", \"error\", \"status\", \"message\"]),\n toolName: z.string().optional(),\n status: z.string().optional(),\n details: z.string().optional(),\n text: z.string().optional(),\n error: z.string().optional(),\n timestamp: z.number().optional(),\n parameters: z.record(z.unknown()).optional(),\n valueSnippet: z.string().optional(),\n subagentSessionId: z.string().optional(),\n })\n .passthrough();\n\nexport type ToolProgressUpdate = z.infer<typeof ToolProgressUpdateSchema>;\n\n/** Settings payload within SettingsUpdatedNotification. */\nexport const SettingsUpdatedPayloadSchema = z\n .object({\n autonomyMode: z.nativeEnum(AutonomyMode).optional(),\n interactionMode: z.nativeEnum(DroidInteractionMode).optional().catch(undefined),\n autonomyLevel: z.nativeEnum(AutonomyLevel).optional().catch(undefined),\n modelId: z.string().optional(),\n reasoningEffort: z.nativeEnum(ReasoningEffort).optional(),\n specModeModelId: z.string().optional(),\n specModeReasoningEffort: z.nativeEnum(ReasoningEffort).optional(),\n })\n .passthrough();\n\nexport type SettingsUpdatedPayload = z.infer<\n typeof SettingsUpdatedPayloadSchema\n>;\n\n// ---------------------------------------------------------------------------\n// 20 notification payload types\n// ---------------------------------------------------------------------------\n\n/** Tool result notification. */\nexport const ToolResultNotificationSchema = z\n .object({\n type: z.literal(SessionNotificationType.TOOL_RESULT),\n messageId: z.string(),\n toolUseId: z.string(),\n content: z.unknown().optional(),\n isError: z.boolean().optional(),\n id: z.string().optional(),\n })\n .passthrough();\n\nexport type ToolResultNotification = z.infer<\n typeof ToolResultNotificationSchema\n>;\n\n/** Tool progress update notification. */\nexport const ToolProgressUpdateNotificationSchema = z\n .object({\n type: z.literal(SessionNotificationType.TOOL_PROGRESS_UPDATE),\n toolUseId: z.string(),\n toolName: z.string(),\n update: ToolProgressUpdateSchema,\n })\n .passthrough();\n\nexport type ToolProgressUpdateNotification = z.infer<\n typeof ToolProgressUpdateNotificationSchema\n>;\n\n/** Create message notification. */\nexport const CreateMessageNotificationSchema = z\n .object({\n type: z.literal(SessionNotificationType.CREATE_MESSAGE),\n message: FactoryDroidMessageSchema,\n parentId: z.string().optional(),\n requestId: z.string().optional(),\n })\n .passthrough();\n\nexport type CreateMessageNotification = z.infer<\n typeof CreateMessageNotificationSchema\n>;\n\n/** Error notification. */\nexport const ErrorNotificationSchema = z\n .object({\n type: z.literal(SessionNotificationType.ERROR),\n message: z.string(),\n errorType: z.nativeEnum(DroidErrorType),\n timestamp: z.string(),\n error: ErrorDetailSchema.optional(),\n })\n .passthrough();\n\nexport type ErrorNotification = z.infer<typeof ErrorNotificationSchema>;\n\n/** Droid working state changed notification. */\nexport const DroidWorkingStateChangedNotificationSchema = z\n .object({\n type: z.literal(SessionNotificationType.DROID_WORKING_STATE_CHANGED),\n newState: z.nativeEnum(DroidWorkingState),\n })\n .passthrough();\n\nexport type DroidWorkingStateChangedNotification = z.infer<\n typeof DroidWorkingStateChangedNotificationSchema\n>;\n\n/** Permission resolved notification. */\nexport const PermissionResolvedNotificationSchema = z\n .object({\n type: z.literal(SessionNotificationType.PERMISSION_RESOLVED),\n requestId: z.string(),\n toolUseIds: z.array(z.string()),\n selectedOption: z.nativeEnum(ToolConfirmationOutcome),\n })\n .passthrough();\n\nexport type PermissionResolvedNotification = z.infer<\n typeof PermissionResolvedNotificationSchema\n>;\n\n/** Settings updated notification. */\nexport const SettingsUpdatedNotificationSchema = z\n .object({\n type: z.literal(SessionNotificationType.SETTINGS_UPDATED),\n settings: SettingsUpdatedPayloadSchema,\n })\n .passthrough();\n\nexport type SettingsUpdatedNotification = z.infer<\n typeof SettingsUpdatedNotificationSchema\n>;\n\n/** Session title updated notification. */\nexport const SessionTitleUpdatedNotificationSchema = z\n .object({\n type: z.literal(SessionNotificationType.SESSION_TITLE_UPDATED),\n title: z.string(),\n })\n .passthrough();\n\nexport type SessionTitleUpdatedNotification = z.infer<\n typeof SessionTitleUpdatedNotificationSchema\n>;\n\n/** MCP status changed notification. */\nexport const McpStatusChangedNotificationSchema = z\n .object({\n type: z.literal(SessionNotificationType.MCP_STATUS_CHANGED),\n servers: z.array(McpServerStatusInfoSchema),\n summary: McpStatusSummarySchema,\n })\n .passthrough();\n\nexport type McpStatusChangedNotification = z.infer<\n typeof McpStatusChangedNotificationSchema\n>;\n\n/** Assistant text delta notification (streaming token). */\nexport const AssistantTextDeltaNotificationSchema = z\n .object({\n type: z.literal(SessionNotificationType.ASSISTANT_TEXT_DELTA),\n messageId: z.string(),\n blockIndex: z.number(),\n textDelta: z.string(),\n })\n .passthrough();\n\nexport type AssistantTextDeltaNotification = z.infer<\n typeof AssistantTextDeltaNotificationSchema\n>;\n\n/** Thinking text delta notification (streaming thinking token). */\nexport const ThinkingTextDeltaNotificationSchema = z\n .object({\n type: z.literal(SessionNotificationType.THINKING_TEXT_DELTA),\n messageId: z.string(),\n blockIndex: z.number(),\n textDelta: z.string(),\n })\n .passthrough();\n\nexport type ThinkingTextDeltaNotification = z.infer<\n typeof ThinkingTextDeltaNotificationSchema\n>;\n\n/** Session token usage changed notification. */\nexport const SessionTokenUsageChangedNotificationSchema = z\n .object({\n type: z.literal(SessionNotificationType.SESSION_TOKEN_USAGE_CHANGED),\n sessionId: z.string(),\n tokenUsage: TokenUsageSchema,\n })\n .passthrough();\n\nexport type SessionTokenUsageChangedNotification = z.infer<\n typeof SessionTokenUsageChangedNotificationSchema\n>;\n\n/** Mission state changed notification. */\nexport const MissionStateChangedNotificationSchema = z\n .object({\n type: z.literal(SessionNotificationType.MISSION_STATE_CHANGED),\n state: z.nativeEnum(MissionState),\n })\n .passthrough();\n\nexport type MissionStateChangedNotification = z.infer<\n typeof MissionStateChangedNotificationSchema\n>;\n\n/** Mission features changed notification. */\nexport const MissionFeaturesChangedNotificationSchema = z\n .object({\n type: z.literal(SessionNotificationType.MISSION_FEATURES_CHANGED),\n features: z.array(MissionFeatureSchema),\n })\n .passthrough();\n\nexport type MissionFeaturesChangedNotification = z.infer<\n typeof MissionFeaturesChangedNotificationSchema\n>;\n\n/** Mission progress entry notification. */\nexport const MissionProgressEntryNotificationSchema = z\n .object({\n type: z.literal(SessionNotificationType.MISSION_PROGRESS_ENTRY),\n progressLog: z.array(ProgressLogEntrySchema),\n })\n .passthrough();\n\nexport type MissionProgressEntryNotification = z.infer<\n typeof MissionProgressEntryNotificationSchema\n>;\n\n/** Mission heartbeat notification. */\nexport const MissionHeartbeatNotificationSchema = z\n .object({\n type: z.literal(SessionNotificationType.MISSION_HEARTBEAT),\n timestamp: z.string(),\n })\n .passthrough();\n\nexport type MissionHeartbeatNotification = z.infer<\n typeof MissionHeartbeatNotificationSchema\n>;\n\n/** Mission worker started notification. */\nexport const MissionWorkerStartedNotificationSchema = z\n .object({\n type: z.literal(SessionNotificationType.MISSION_WORKER_STARTED),\n workerSessionId: z.string(),\n })\n .passthrough();\n\nexport type MissionWorkerStartedNotification = z.infer<\n typeof MissionWorkerStartedNotificationSchema\n>;\n\n/** Mission worker completed notification. */\nexport const MissionWorkerCompletedNotificationSchema = z\n .object({\n type: z.literal(SessionNotificationType.MISSION_WORKER_COMPLETED),\n workerSessionId: z.string(),\n exitCode: z.number(),\n })\n .passthrough();\n\nexport type MissionWorkerCompletedNotification = z.infer<\n typeof MissionWorkerCompletedNotificationSchema\n>;\n\n/** MCP authentication required notification. */\nexport const McpAuthRequiredNotificationSchema = z\n .object({\n type: z.literal(SessionNotificationType.MCP_AUTH_REQUIRED),\n serverName: z.string(),\n authUrl: z.string(),\n message: z.string(),\n state: z.string(),\n })\n .passthrough();\n\nexport type McpAuthRequiredNotification = z.infer<\n typeof McpAuthRequiredNotificationSchema\n>;\n\n/** MCP authentication completed notification. */\nexport const McpAuthCompletedNotificationSchema = z\n .object({\n type: z.literal(SessionNotificationType.MCP_AUTH_COMPLETED),\n serverName: z.string(),\n outcome: z.nativeEnum(McpAuthOutcome),\n message: z.string(),\n })\n .passthrough();\n\nexport type McpAuthCompletedNotification = z.infer<\n typeof McpAuthCompletedNotificationSchema\n>;\n\n// ---------------------------------------------------------------------------\n// SessionNotification discriminated union\n// ---------------------------------------------------------------------------\n\n/** List of all session notification schemas (for discriminatedUnion). */\nexport const SessionNotificationSchemaList = [\n ToolResultNotificationSchema,\n ToolProgressUpdateNotificationSchema,\n CreateMessageNotificationSchema,\n ErrorNotificationSchema,\n DroidWorkingStateChangedNotificationSchema,\n PermissionResolvedNotificationSchema,\n SettingsUpdatedNotificationSchema,\n SessionTitleUpdatedNotificationSchema,\n McpStatusChangedNotificationSchema,\n AssistantTextDeltaNotificationSchema,\n ThinkingTextDeltaNotificationSchema,\n SessionTokenUsageChangedNotificationSchema,\n MissionStateChangedNotificationSchema,\n MissionFeaturesChangedNotificationSchema,\n MissionProgressEntryNotificationSchema,\n MissionHeartbeatNotificationSchema,\n MissionWorkerStartedNotificationSchema,\n MissionWorkerCompletedNotificationSchema,\n McpAuthRequiredNotificationSchema,\n McpAuthCompletedNotificationSchema,\n] as const;\n\n/** Discriminated union over all 20 session notification types. */\nexport const SessionNotificationPayloadSchema = z.discriminatedUnion(\n \"type\",\n SessionNotificationSchemaList,\n);\n\nexport type SessionNotificationPayload = z.infer<\n typeof SessionNotificationPayloadSchema\n>;\n\n/** Parameters for session notification (wraps the discriminated union). */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const SessionNotificationParamsSchema: z.ZodType<any> = z\n .object({\n notification: SessionNotificationPayloadSchema,\n })\n .passthrough();\n\nexport type SessionNotificationParams = {\n notification: SessionNotificationPayload;\n [key: string]: unknown;\n};\n\n/** Full session notification with JSON-RPC envelope. */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const SessionNotificationSchema: z.ZodType<any> =\n JsonRpcNotificationSchema.extend({\n method: z.literal(DroidClientMethod.SESSION_NOTIFICATION),\n params: SessionNotificationParamsSchema,\n });\n\nexport type SessionNotification = z.output<typeof JsonRpcNotificationSchema> & {\n method: \"droid.session_notification\";\n params: SessionNotificationParams;\n};\n\n// ---------------------------------------------------------------------------\n// Tool confirmation details\n// ---------------------------------------------------------------------------\n\nexport const EditToolConfirmationDetailsSchema = z\n .object({\n type: z.literal(ToolConfirmationType.Edit),\n filePath: z.string(),\n fileName: z.string(),\n oldContent: z.string().optional(),\n newContent: z.string().optional(),\n })\n .passthrough();\n\nexport type EditToolConfirmationDetails = z.infer<\n typeof EditToolConfirmationDetailsSchema\n>;\n\nexport const ExecuteToolConfirmationDetailsSchema = z\n .object({\n type: z.literal(ToolConfirmationType.Execute),\n fullCommand: z.string(),\n command: z.string(),\n extractedCommands: z.array(z.string()).optional(),\n impactLevel: z.string().optional(),\n })\n .passthrough();\n\nexport type ExecuteToolConfirmationDetails = z.infer<\n typeof ExecuteToolConfirmationDetailsSchema\n>;\n\nexport const CreateToolConfirmationDetailsSchema = z\n .object({\n type: z.literal(ToolConfirmationType.Create),\n filePath: z.string(),\n fileName: z.string(),\n content: z.string(),\n })\n .passthrough();\n\nexport type CreateToolConfirmationDetails = z.infer<\n typeof CreateToolConfirmationDetailsSchema\n>;\n\nexport const AskUserQuestionSchema = z\n .object({\n index: z.number(),\n topic: z.string(),\n question: z.string(),\n options: z.array(z.string()),\n })\n .passthrough();\n\nexport type AskUserQuestion = z.infer<typeof AskUserQuestionSchema>;\n\nexport const AskUserConfirmationDetailsSchema = z\n .object({\n type: z.literal(ToolConfirmationType.AskUser),\n questionnaire: z.string(),\n parsed: z\n .object({\n questions: z.array(AskUserQuestionSchema),\n })\n .optional(),\n parseError: z\n .object({\n message: z.string(),\n line: z.number().optional(),\n })\n .optional(),\n })\n .passthrough();\n\nexport type AskUserConfirmationDetails = z.infer<\n typeof AskUserConfirmationDetailsSchema\n>;\n\nexport const ExitSpecModeConfirmationDetailsSchema = z\n .object({\n type: z.literal(ToolConfirmationType.ExitSpecMode),\n plan: z.string(),\n title: z.string().optional(),\n optionNames: z.array(z.string()).optional(),\n })\n .passthrough();\n\nexport type ExitSpecModeConfirmationDetails = z.infer<\n typeof ExitSpecModeConfirmationDetailsSchema\n>;\n\nexport const ProposeMissionConfirmationDetailsSchema = z\n .object({\n type: z.literal(ToolConfirmationType.ProposeMission),\n proposal: z.string(),\n title: z.string().optional(),\n })\n .passthrough();\n\nexport type ProposeMissionConfirmationDetails = z.infer<\n typeof ProposeMissionConfirmationDetailsSchema\n>;\n\nexport const StartMissionRunConfirmationDetailsSchema = z\n .object({\n type: z.literal(ToolConfirmationType.StartMissionRun),\n runningMissionCount: z.number(),\n runningMissionSessionIds: z.array(z.string()),\n })\n .passthrough();\n\nexport type StartMissionRunConfirmationDetails = z.infer<\n typeof StartMissionRunConfirmationDetailsSchema\n>;\n\nexport const ApplyPatchToolConfirmationDetailsSchema = z\n .object({\n type: z.literal(ToolConfirmationType.ApplyPatch),\n filePath: z.string(),\n fileName: z.string(),\n patchContent: z.string(),\n oldContent: z.string().optional(),\n newContent: z.string().optional(),\n })\n .passthrough();\n\nexport type ApplyPatchToolConfirmationDetails = z.infer<\n typeof ApplyPatchToolConfirmationDetailsSchema\n>;\n\nexport const McpToolConfirmationDetailsSchema = z\n .object({\n type: z.literal(ToolConfirmationType.McpTool),\n toolName: z.string(),\n impactLevel: z.string(),\n })\n .passthrough();\n\nexport type McpToolConfirmationDetails = z.infer<\n typeof McpToolConfirmationDetailsSchema\n>;\n\n/** Discriminated union over tool confirmation detail types. */\nexport const ToolConfirmationDetailsSchema = z.discriminatedUnion(\"type\", [\n EditToolConfirmationDetailsSchema,\n ExecuteToolConfirmationDetailsSchema,\n CreateToolConfirmationDetailsSchema,\n AskUserConfirmationDetailsSchema,\n ExitSpecModeConfirmationDetailsSchema,\n ProposeMissionConfirmationDetailsSchema,\n StartMissionRunConfirmationDetailsSchema,\n ApplyPatchToolConfirmationDetailsSchema,\n McpToolConfirmationDetailsSchema,\n]);\n\nexport type ToolConfirmationDetails = z.infer<\n typeof ToolConfirmationDetailsSchema\n>;\n\n/** Tool confirmation information (toolUse + confirmationType + details). */\nexport const ToolConfirmationInfoSchema = z\n .object({\n toolUse: ToolUseSchema,\n confirmationType: z.nativeEnum(ToolConfirmationType),\n details: ToolConfirmationDetailsSchema,\n })\n .passthrough();\n\nexport type ToolConfirmationInfo = z.infer<typeof ToolConfirmationInfoSchema>;\n\n// ---------------------------------------------------------------------------\n// RequestPermissionRequest (server → client)\n// ---------------------------------------------------------------------------\n\n/** Parameters for droid.request_permission request. */\nexport const RequestPermissionRequestParamsSchema = z\n .object({\n toolUses: z.array(ToolConfirmationInfoSchema),\n options: z.array(ToolConfirmationListItemSchema),\n })\n .passthrough();\n\nexport type RequestPermissionRequestParams = z.infer<\n typeof RequestPermissionRequestParamsSchema\n>;\n\n/** Request for permission from the server (server → client). */\nexport const RequestPermissionRequestSchema = JsonRpcRequestSchema.extend({\n method: z.literal(DroidClientMethod.REQUEST_PERMISSION),\n params: RequestPermissionRequestParamsSchema,\n});\n\nexport type RequestPermissionRequest = z.infer<\n typeof RequestPermissionRequestSchema\n>;\n\n/** Result for droid.request_permission response. */\nexport const RequestPermissionResultSchema = z\n .object({\n selectedOption: z.nativeEnum(ToolConfirmationOutcome),\n })\n .strict();\n\nexport type RequestPermissionResult = z.infer<\n typeof RequestPermissionResultSchema\n>;\n\n/** Response to droid.request_permission. */\nexport const RequestPermissionResponseSchema = z.union([\n JsonRpcResponseSuccessSchema.extend({\n result: RequestPermissionResultSchema,\n }),\n JsonRpcResponseFailureSchema,\n]);\n\nexport type RequestPermissionResponse = z.infer<\n typeof RequestPermissionResponseSchema\n>;\n\n// ---------------------------------------------------------------------------\n// AskUserRequest (server → client)\n// ---------------------------------------------------------------------------\n\n/** Parameters for droid.ask_user request. */\nexport const AskUserRequestParamsSchema = z\n .object({\n toolCallId: z.string(),\n questions: z.array(AskUserQuestionSchema),\n })\n .passthrough();\n\nexport type AskUserRequestParams = z.infer<typeof AskUserRequestParamsSchema>;\n\n/** Ask user request from the server (server → client). */\nexport const AskUserRequestSchema = JsonRpcRequestSchema.extend({\n method: z.literal(DroidClientMethod.ASK_USER),\n params: AskUserRequestParamsSchema,\n});\n\nexport type AskUserRequest = z.infer<typeof AskUserRequestSchema>;\n\n/** A collected answer from the user. */\nexport const AskUserCollectedAnswerSchema = z\n .object({\n index: z.number(),\n question: z.string(),\n answer: z.string(),\n })\n .strict();\n\nexport type AskUserCollectedAnswer = z.infer<\n typeof AskUserCollectedAnswerSchema\n>;\n\n/** Result for droid.ask_user response. */\nexport const AskUserResultSchema = z\n .object({\n cancelled: z.boolean().optional(),\n answers: z.array(AskUserCollectedAnswerSchema),\n })\n .strict();\n\nexport type AskUserResult = z.infer<typeof AskUserResultSchema>;\n\n/** Response to droid.ask_user. */\nexport const AskUserResponseSchema = z.union([\n JsonRpcResponseSuccessSchema.extend({ result: AskUserResultSchema }),\n JsonRpcResponseFailureSchema,\n]);\n\nexport type AskUserResponse = z.infer<typeof AskUserResponseSchema>;\n\n// ---------------------------------------------------------------------------\n// CliRequestOrNotification discriminated union\n// ---------------------------------------------------------------------------\n\n/** Union over all 3 server → client methods. */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const CliRequestOrNotificationSchema: z.ZodType<any> = z.union([\n SessionNotificationSchema,\n RequestPermissionRequestSchema,\n AskUserRequestSchema,\n]);\n\nexport type CliRequestOrNotification =\n | SessionNotification\n | RequestPermissionRequest\n | AskUserRequest;\n","/**\n * Error class hierarchy for the Factory Droid SDK.\n *\n * All SDK errors extend Error directly (no MetaError dependency).\n * Each error class sets its `name` property to the class name for\n * reliable `instanceof` checks and readable stack traces.\n */\n\n/**\n * Raised when a connection to the droid process fails.\n *\n * Carries optional context about the working directory and executable path\n * that were used when attempting to spawn the process.\n */\nexport class ConnectionError extends Error {\n /** The working directory used when spawning the process. */\n readonly cwd: string;\n\n /** The executable path used when spawning the process. */\n readonly execPath: string;\n\n constructor(message: string, options?: { cwd?: string; execPath?: string }) {\n super(message);\n this.name = \"ConnectionError\";\n this.cwd = options?.cwd ?? \"\";\n this.execPath = options?.execPath ?? \"\";\n Object.setPrototypeOf(this, ConnectionError.prototype);\n }\n}\n\n/**\n * Raised when a JSON-RPC protocol error occurs.\n *\n * Carries the optional JSON-RPC error code and any additional data\n * returned in the error response.\n */\nexport class ProtocolError extends Error {\n /** The JSON-RPC error code, if available. */\n readonly code: number | undefined;\n\n /** Additional error data from the JSON-RPC response. */\n readonly data: unknown;\n\n constructor(\n message: string,\n options?: { code?: number; data?: unknown },\n ) {\n super(message);\n this.name = \"ProtocolError\";\n this.code = options?.code;\n this.data = options?.data;\n Object.setPrototypeOf(this, ProtocolError.prototype);\n }\n}\n\n/**\n * Base error for session-related errors.\n */\nexport class SessionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"SessionError\";\n Object.setPrototypeOf(this, SessionError.prototype);\n }\n}\n\n/**\n * Raised when a session cannot be found.\n *\n * Constructs a default message of \"Session not found: {sessionId}\".\n */\nexport class SessionNotFoundError extends SessionError {\n /** The ID of the session that was not found. */\n readonly sessionId: string;\n\n constructor(sessionId: string) {\n super(`Session not found: ${sessionId}`);\n this.name = \"SessionNotFoundError\";\n this.sessionId = sessionId;\n Object.setPrototypeOf(this, SessionNotFoundError.prototype);\n }\n}\n\n/**\n * Raised when a request to the droid process times out.\n */\nexport class TimeoutError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"TimeoutError\";\n Object.setPrototypeOf(this, TimeoutError.prototype);\n }\n}\n\n/**\n * Raised when the droid subprocess exits unexpectedly.\n *\n * Carries the exit code (if the process exited normally) and the signal\n * name (if the process was killed by a signal).\n */\nexport class ProcessExitError extends Error {\n /** The exit code of the process, or null if terminated by signal. */\n readonly exitCode: number | null;\n\n /** The signal that terminated the process, or null if exited normally. */\n readonly signal: string | null;\n\n constructor(\n message: string,\n options?: { exitCode?: number | null; signal?: string | null },\n ) {\n super(message);\n this.name = \"ProcessExitError\";\n this.exitCode = options?.exitCode ?? null;\n this.signal = options?.signal ?? null;\n Object.setPrototypeOf(this, ProcessExitError.prototype);\n }\n}\n","/**\n * ProcessTransport — subprocess-based transport for the Factory Droid SDK.\n *\n * Spawns `droid exec --input-format stream-jsonrpc --output-format stream-jsonrpc`\n * as a child process and communicates via newline-delimited JSON (JSONL) over\n * stdin/stdout.\n */\n\nimport { type ChildProcess, spawn } from \"node:child_process\";\nimport * as readline from \"node:readline\";\n\nimport { ConnectionError, ProcessExitError } from \"./errors.js\";\nimport type {\n DroidClientTransport,\n ErrorCallback,\n MessageCallback,\n ProcessTransportOptions,\n} from \"./types.js\";\n\n/** Default arguments for `droid exec`. */\nconst DEFAULT_EXEC_ARGS = [\n \"exec\",\n \"--input-format\",\n \"stream-jsonrpc\",\n \"--output-format\",\n \"stream-jsonrpc\",\n];\n\n/** Default grace period in milliseconds before escalating SIGTERM → SIGKILL. */\nconst DEFAULT_GRACE_PERIOD_MS = 5_000;\n\n/**\n * Transport that communicates via JSONL over stdin/stdout of a spawned\n * `droid exec` child process.\n *\n * Key behaviors:\n * - JSONL framing (one JSON object per newline-terminated line)\n * - Write serialization via a promise chain to prevent interleaving\n * - Process lifecycle management (SIGTERM → grace period → SIGKILL)\n * - Reconnection after close via `connect()`\n * - Non-JSON stdout lines are silently skipped\n * - Fires `onError` with `ProcessExitError` on abnormal exit\n */\nexport class ProcessTransport implements DroidClientTransport {\n private readonly execPath: string;\n private readonly execArgs: string[];\n private readonly cwd: string | undefined;\n private readonly env: Record<string, string> | undefined;\n private readonly gracePeriodMs: number;\n\n private childProcess: ChildProcess | null = null;\n private readlineInterface: readline.Interface | null = null;\n private messageHandler: MessageCallback | null = null;\n private errorHandler: ErrorCallback | null = null;\n\n /**\n * Sticky error from a process error or unexpected exit. Once set,\n * all subsequent `send()` calls throw immediately.\n */\n private processError: Error | null = null;\n\n /** Promise-chain serializer for stdin writes. */\n private writeChain: Promise<void> = Promise.resolve();\n\n private _isConnected = false;\n private isClosing = false;\n\n constructor(options: ProcessTransportOptions = {}) {\n this.execPath = options.execPath ?? \"droid\";\n this.execArgs = options.execArgs\n ? [...options.execArgs]\n : [...DEFAULT_EXEC_ARGS];\n this.cwd = options.cwd;\n this.env = options.env;\n this.gracePeriodMs =\n (options.gracePeriod ?? DEFAULT_GRACE_PERIOD_MS / 1_000) * 1_000;\n }\n\n // -----------------------------------------------------------------------\n // DroidClientTransport interface\n // -----------------------------------------------------------------------\n\n get isConnected(): boolean {\n return this._isConnected;\n }\n\n async connect(): Promise<void> {\n if (this._isConnected) {\n throw new ConnectionError(\"Transport already connected\", {\n execPath: this.execPath,\n });\n }\n\n // Reset state for (re)connection\n this.processError = null;\n this.isClosing = false;\n this.writeChain = Promise.resolve();\n\n const mergedEnv = this.env\n ? { ...process.env, ...this.env }\n : undefined;\n\n try {\n this.childProcess = spawn(this.execPath, this.execArgs, {\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n cwd: this.cwd,\n env: mergedEnv,\n });\n } catch (err: unknown) {\n const message =\n err instanceof Error\n ? `Failed to start droid process: ${err.message}`\n : \"Failed to start droid process\";\n throw new ConnectionError(message, {\n execPath: this.execPath,\n cwd: this.cwd,\n });\n }\n\n this._isConnected = true;\n this.setupHandlers();\n }\n\n send(message: object): void {\n if (this.processError) {\n throw this.processError;\n }\n if (\n !this._isConnected ||\n !this.childProcess ||\n !this.childProcess.stdin\n ) {\n throw new ConnectionError(\"Transport not connected\", {\n execPath: this.execPath,\n });\n }\n\n const line = JSON.stringify(message) + \"\\n\";\n\n // Chain writes to prevent interleaving on concurrent calls.\n const previousChain = this.writeChain;\n\n this.writeChain = (async () => {\n // Wait for the previous write to finish (ignore its error — it's\n // already been reported to the caller of the previous send()).\n await previousChain.catch(() => {});\n\n if (\n !this.childProcess ||\n !this.childProcess.stdin ||\n this.childProcess.killed ||\n this.isClosing\n ) {\n throw new ConnectionError(\"Process disconnected before write\", {\n execPath: this.execPath,\n });\n }\n\n if (this.processError) {\n throw this.processError;\n }\n\n await new Promise<void>((resolve, reject) => {\n if (!this.childProcess || !this.childProcess.stdin) {\n reject(\n new ConnectionError(\"Process stdin unavailable\", {\n execPath: this.execPath,\n }),\n );\n return;\n }\n\n const stdin = this.childProcess.stdin;\n if (\"writable\" in stdin && !stdin.writable) {\n reject(\n new ConnectionError(\"Process stdin is not writable\", {\n execPath: this.execPath,\n }),\n );\n return;\n }\n\n stdin.write(line, (error) => {\n if (error) {\n const msg = error.message || String(error);\n if (msg.includes(\"EPIPE\") || msg.includes(\"ECONNRESET\")) {\n reject(\n new ConnectionError(\"Process stdin closed during write\", {\n execPath: this.execPath,\n }),\n );\n } else {\n reject(\n new ConnectionError(\n `Failed to write to process stdin: ${msg}`,\n { execPath: this.execPath },\n ),\n );\n }\n } else {\n resolve();\n }\n });\n });\n })();\n }\n\n onMessage(callback: MessageCallback): void {\n this.messageHandler = callback;\n }\n\n onError(callback: ErrorCallback): void {\n this.errorHandler = callback;\n }\n\n async close(): Promise<void> {\n if (this.isClosing) {\n return;\n }\n\n this.isClosing = true;\n this._isConnected = false;\n\n const proc = this.childProcess;\n this.childProcess = null;\n\n if (this.readlineInterface) {\n this.readlineInterface.close();\n this.readlineInterface = null;\n }\n\n if (proc && proc.exitCode === null && !proc.killed) {\n await new Promise<void>((resolve) => {\n const timeout = setTimeout(() => {\n // Escalate to SIGKILL\n if (proc.exitCode === null && !proc.killed) {\n try {\n proc.kill(\"SIGKILL\");\n } catch {\n // Process may already be gone\n }\n }\n }, this.gracePeriodMs);\n\n proc.once(\"exit\", () => {\n clearTimeout(timeout);\n resolve();\n });\n\n // Close stdin first, then SIGTERM\n if (proc.stdin) {\n try {\n proc.stdin.end();\n } catch {\n // Ignore\n }\n }\n\n try {\n proc.kill(\"SIGTERM\");\n } catch {\n // Process may already be gone — resolve immediately\n clearTimeout(timeout);\n resolve();\n }\n });\n }\n\n // Reset closing flag so reconnection via connect() is possible\n this.isClosing = false;\n }\n\n // -----------------------------------------------------------------------\n // Private helpers\n // -----------------------------------------------------------------------\n\n private setupHandlers(): void {\n const proc = this.childProcess;\n if (!proc || !proc.stdout) {\n return;\n }\n\n this.readlineInterface = readline.createInterface({\n input: proc.stdout,\n crlfDelay: Infinity,\n });\n\n this.readlineInterface.on(\"line\", (line) => {\n const trimmed = line.trim();\n if (!trimmed) {\n return;\n }\n\n // Only attempt to parse lines that look like JSON objects / arrays\n if (trimmed.startsWith(\"{\") || trimmed.startsWith(\"[\")) {\n try {\n const parsed: unknown = JSON.parse(trimmed);\n if (this.messageHandler && typeof parsed === \"object\" && parsed !== null) {\n this.messageHandler(parsed as object);\n }\n } catch {\n // Malformed JSON — skip silently\n }\n }\n // Non-JSON lines (e.g. debug output from the subprocess) are silently skipped\n });\n\n // Handle spawn errors (ENOENT etc.)\n proc.on(\"error\", (error) => {\n this.processError = new ConnectionError(\n `Failed to start droid process: ${error.message}`,\n {\n execPath: this.execPath,\n cwd: this.cwd,\n },\n );\n this._isConnected = false;\n if (!this.isClosing && this.errorHandler) {\n this.errorHandler(this.processError);\n }\n });\n\n // Handle process exit\n proc.on(\"exit\", (code, signal) => {\n if (this.readlineInterface) {\n this.readlineInterface.close();\n this.readlineInterface = null;\n }\n\n this._isConnected = false;\n\n if (!this.isClosing) {\n const exitCode = code ?? null;\n const exitSignal = signal ?? null;\n\n let message: string;\n if (exitSignal) {\n message = `Droid process was killed (${exitSignal})`;\n } else if (exitCode !== null && exitCode !== 0) {\n message = `Droid process exited unexpectedly (exit code ${exitCode})`;\n } else if (exitCode === 0) {\n message = \"Droid process exited normally\";\n } else {\n message = \"Droid process exited unexpectedly\";\n }\n\n this.processError = new ProcessExitError(message, {\n exitCode,\n signal: exitSignal,\n });\n\n if (this.errorHandler) {\n this.errorHandler(this.processError);\n }\n }\n });\n }\n}\n","/**\n * JSON-RPC 2.0 protocol engine for the Factory Droid SDK.\n *\n * Sits between the transport layer and the client API. Handles:\n *\n * - Envelope construction for outbound requests\n * - Request/response correlation via pending promises keyed by UUID\n * - Configurable per-request timeouts\n * - Notification dispatch to registered listeners with optional type filtering\n * - Server→client request handling (permission, ask_user)\n * - Error code mapping (ENTITY_NOT_FOUND → SessionNotFoundError)\n * - Sticky transport error: once a transport error fires, all\n * pending and subsequent requests are immediately rejected\n * - Edge cases: unknown response IDs, duplicate response IDs,\n * malformed responses, null-id error responses\n */\n\nimport { v4 as uuidv4 } from \"uuid\";\n\nimport {\n ConnectionError,\n ProtocolError,\n SessionNotFoundError,\n TimeoutError,\n} from \"./errors.js\";\nimport {\n DEFAULT_REQUEST_TIMEOUT,\n FACTORY_PROTOCOL_VERSION,\n JSONRPC_VERSION,\n LEGACY_FACTORY_API_VERSION,\n} from \"./schemas/constants.js\";\nimport {\n DroidClientMethod,\n JsonRpcErrorCode,\n} from \"./schemas/enums.js\";\nimport type { DroidClientTransport } from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * Handler for server→client permission requests.\n * Receives request params and returns the selected ToolConfirmationOutcome string.\n */\nexport type PermissionHandler = (\n params: Record<string, unknown>,\n) => string | Promise<string>;\n\n/**\n * Handler for server→client ask-user requests.\n * Receives request params and returns a result with cancelled flag and answers.\n */\nexport type AskUserHandler = (\n params: Record<string, unknown>,\n) => Record<string, unknown> | Promise<Record<string, unknown>>;\n\n/**\n * Callback for incoming notification messages.\n */\nexport type NotificationCallback = (notification: Record<string, unknown>) => void;\n\n/**\n * Optional filter for notification listeners.\n */\nexport interface NotificationFilter {\n /** Only dispatch notifications whose `params.notification.type` matches. */\n type?: string;\n}\n\n/**\n * Internal state for a pending request awaiting a response.\n */\ninterface PendingRequest {\n readonly method: string;\n readonly requestId: string;\n readonly params: Record<string, unknown>;\n readonly resolve: (value: Record<string, unknown>) => void;\n readonly reject: (reason: Error) => void;\n readonly timer: ReturnType<typeof setTimeout>;\n}\n\n/**\n * Internal entry in the notification listener registry.\n */\ninterface NotificationListener {\n readonly callback: NotificationCallback;\n readonly filter?: NotificationFilter;\n}\n\n// ---------------------------------------------------------------------------\n// ProtocolEngine\n// ---------------------------------------------------------------------------\n\n/**\n * JSON-RPC 2.0 protocol engine.\n *\n * Manages request/response correlation, timeout handling, notification\n * dispatch, server→client request handling, and error mapping.\n *\n * After construction the engine immediately registers itself on the\n * transport's `onMessage` and `onError` callbacks.\n *\n * @example\n * ```ts\n * const engine = new ProtocolEngine({ transport });\n * const result = await engine.sendRequest(\"droid.list_skills\", {});\n * engine.close();\n * ```\n */\nexport class ProtocolEngine {\n private readonly _transport: DroidClientTransport;\n private readonly _defaultTimeout: number;\n\n /** Pending requests keyed by UUID string. */\n private readonly _pendingRequests = new Map<string, PendingRequest>();\n\n /** Notification listener registry. */\n private readonly _notificationListeners = new Set<NotificationListener>();\n\n /** Server→client request handlers. */\n private _permissionHandler: PermissionHandler | null = null;\n private _askUserHandler: AskUserHandler | null = null;\n\n /** Sticky transport error — once set, all requests fail immediately. */\n private _transportError: Error | null = null;\n\n /** Closed flag — once true, new requests are rejected. */\n private _closed = false;\n\n /**\n * Create a new ProtocolEngine.\n *\n * @param options.transport - A connected DroidClientTransport implementation.\n * @param options.defaultTimeout - Default timeout in ms for sendRequest (default 30 000).\n */\n constructor(options: {\n transport: DroidClientTransport;\n defaultTimeout?: number;\n }) {\n this._transport = options.transport;\n this._defaultTimeout = options.defaultTimeout ?? DEFAULT_REQUEST_TIMEOUT;\n\n // Wire up transport callbacks\n this._transport.onMessage((message: object) => {\n this._handleMessage(message as Record<string, unknown>);\n });\n this._transport.onError((error: Error) => {\n this._handleTransportError(error);\n });\n }\n\n // ------------------------------------------------------------------\n // Public API: Sending requests\n // ------------------------------------------------------------------\n\n /**\n * Send a JSON-RPC request and wait for the response.\n *\n * Constructs the full envelope, registers a pending promise, sends\n * via transport, and returns the parsed response `result` field.\n *\n * @param method - The RPC method name (e.g. `\"droid.list_skills\"`).\n * @param params - Method parameters object.\n * @param timeout - Timeout in ms. Defaults to `defaultTimeout`.\n * @returns The `result` field from the JSON-RPC success response.\n * @throws {ConnectionError} If the engine is closed.\n * @throws {ConnectionError} If the transport has a sticky error.\n * @throws {TimeoutError} If no response arrives within the timeout.\n * @throws {ProtocolError} If the response contains a protocol error.\n * @throws {SessionNotFoundError} If error code is ENTITY_NOT_FOUND.\n */\n async sendRequest(\n method: string,\n params: Record<string, unknown>,\n timeout?: number,\n ): Promise<Record<string, unknown>> {\n // Check closed state\n if (this._closed) {\n throw new ConnectionError(\"Protocol engine is closed\");\n }\n\n // Check sticky transport error\n if (this._transportError !== null) {\n throw new ConnectionError(\n `Transport error: ${this._transportError.message}`,\n );\n }\n\n const effectiveTimeout = timeout ?? this._defaultTimeout;\n const requestId = uuidv4();\n\n // Build envelope\n const envelope: Record<string, unknown> = {\n jsonrpc: JSONRPC_VERSION,\n factoryApiVersion: LEGACY_FACTORY_API_VERSION,\n factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,\n type: \"request\",\n id: requestId,\n method,\n params,\n };\n\n // Create a promise that will be resolved when we get a matching response\n return new Promise<Record<string, unknown>>((resolve, reject) => {\n // Set up timeout\n const timer = setTimeout(() => {\n this._pendingRequests.delete(requestId);\n reject(\n new TimeoutError(\n `Request ${method} timed out after ${effectiveTimeout}ms`,\n ),\n );\n }, effectiveTimeout);\n\n // Store as pending\n const pending: PendingRequest = {\n method,\n requestId,\n params,\n resolve,\n reject,\n timer,\n };\n this._pendingRequests.set(requestId, pending);\n\n // Send via transport\n try {\n this._transport.send(envelope);\n } catch (sendError) {\n // Clean up pending and reject\n clearTimeout(timer);\n this._pendingRequests.delete(requestId);\n if (sendError instanceof Error) {\n reject(\n new ConnectionError(`Failed to send request: ${sendError.message}`),\n );\n } else {\n reject(new ConnectionError(\"Failed to send request\"));\n }\n }\n });\n }\n\n // ------------------------------------------------------------------\n // Public API: Notification listeners\n // ------------------------------------------------------------------\n\n /**\n * Register a callback for incoming notification messages.\n *\n * Multiple listeners can be registered. Each receives the full\n * parsed notification object.\n *\n * @param callback - Invoked with the notification object.\n * @param filter - Optional filter to only receive specific notification types.\n * @returns An unsubscribe function. Calling it again is safe (no-op).\n */\n onNotification(\n callback: NotificationCallback,\n filter?: NotificationFilter,\n ): () => void {\n const listener: NotificationListener = { callback, filter };\n this._notificationListeners.add(listener);\n\n let unsubscribed = false;\n return () => {\n if (!unsubscribed) {\n unsubscribed = true;\n this._notificationListeners.delete(listener);\n }\n };\n }\n\n // ------------------------------------------------------------------\n // Public API: Server→client request handlers\n // ------------------------------------------------------------------\n\n /**\n * Register a handler for server→client permission requests.\n *\n * The handler receives the request params and should return a\n * ToolConfirmationOutcome string value.\n *\n * Replaces any previously registered handler.\n */\n setPermissionHandler(handler: PermissionHandler): void {\n this._permissionHandler = handler;\n }\n\n /**\n * Remove the permission request handler (restores default Cancel).\n */\n clearPermissionHandler(): void {\n this._permissionHandler = null;\n }\n\n /**\n * Register a handler for server→client ask-user requests.\n *\n * The handler receives the request params and should return\n * a result object with `cancelled` and `answers` keys.\n *\n * Replaces any previously registered handler.\n */\n setAskUserHandler(handler: AskUserHandler): void {\n this._askUserHandler = handler;\n }\n\n /**\n * Remove the ask-user request handler (restores default cancelled=true).\n */\n clearAskUserHandler(): void {\n this._askUserHandler = null;\n }\n\n // ------------------------------------------------------------------\n // Public API: Health check\n // ------------------------------------------------------------------\n\n /**\n * Whether the engine is in a healthy state — not closed and no\n * sticky transport error.\n */\n get isHealthy(): boolean {\n return !this._closed && this._transportError === null;\n }\n\n // ------------------------------------------------------------------\n // Public API: Close\n // ------------------------------------------------------------------\n\n /**\n * Close the protocol engine.\n *\n * Rejects all pending requests, closes the transport, and prevents\n * new requests. Idempotent — safe to call multiple times.\n */\n async close(): Promise<void> {\n if (this._closed) {\n return;\n }\n this._closed = true;\n\n // Reject all pending\n const error = new ConnectionError(\n \"Protocol engine closed: pending requests cancelled\",\n );\n this._rejectAllPending(error);\n\n // Clear handlers and listeners\n this._permissionHandler = null;\n this._askUserHandler = null;\n this._notificationListeners.clear();\n\n // Close the transport\n await this._transport.close();\n }\n\n // ------------------------------------------------------------------\n // Internal: Message handling\n // ------------------------------------------------------------------\n\n /**\n * Handle an incoming parsed message from the transport.\n * Dispatches to response handler, notification handler, or\n * server→client request handler based on message type.\n */\n private _handleMessage(parsed: Record<string, unknown>): void {\n const msgType = parsed[\"type\"];\n\n if (msgType === \"response\") {\n this._handleResponse(parsed);\n } else if (msgType === \"notification\") {\n this._handleNotification(parsed);\n } else if (msgType === \"request\") {\n // Server→client request — handle asynchronously\n void this._handleServerRequest(parsed);\n } else {\n // Fallback detection by content\n if (\"result\" in parsed || \"error\" in parsed) {\n this._handleResponse(parsed);\n } else if (\"method\" in parsed && !(\"id\" in parsed)) {\n this._handleNotification(parsed);\n } else if (\"method\" in parsed && \"id\" in parsed) {\n void this._handleServerRequest(parsed);\n }\n // else: unknown format — silently ignore\n }\n }\n\n /**\n * Handle an incoming response message.\n * Matches by ID to resolve the correct pending Promise.\n */\n private _handleResponse(response: Record<string, unknown>): void {\n const responseId = response[\"id\"] as string | null | undefined;\n\n // Null-id error response — log but don't crash\n if (responseId == null) {\n return;\n }\n\n const pending = this._pendingRequests.get(responseId);\n\n if (pending == null) {\n // Unknown response ID — already timed out or duplicate\n return;\n }\n\n // Remove from pending and clear its timeout\n this._pendingRequests.delete(responseId);\n clearTimeout(pending.timer);\n\n // Check for error response and map to exceptions\n const errorObj = response[\"error\"];\n if (errorObj != null && typeof errorObj === \"object\") {\n const error = errorObj as Record<string, unknown>;\n const code = error[\"code\"] as number | undefined;\n const message = (error[\"message\"] as string) ?? \"Unknown error\";\n const data = error[\"data\"];\n\n if (code === JsonRpcErrorCode.ENTITY_NOT_FOUND) {\n // Extract sessionId from the original request params\n const sessionId = String(\n pending.params[\"sessionId\"] ?? pending.requestId,\n );\n pending.reject(new SessionNotFoundError(sessionId));\n return;\n }\n\n pending.reject(new ProtocolError(message, { code, data }));\n return;\n }\n\n // Resolve with the full response\n pending.resolve(response as Record<string, unknown>);\n }\n\n /**\n * Handle an incoming notification message.\n * Dispatches to all registered notification listeners that match.\n */\n private _handleNotification(notification: Record<string, unknown>): void {\n // Extract the notification type for filtering\n const params = notification[\"params\"] as Record<string, unknown> | undefined;\n const innerNotification = params?.[\"notification\"] as\n | Record<string, unknown>\n | undefined;\n const notificationType = innerNotification?.[\"type\"] as string | undefined;\n\n for (const listener of this._notificationListeners) {\n // Apply type filter if present\n if (\n listener.filter?.type != null &&\n listener.filter.type !== notificationType\n ) {\n continue;\n }\n\n try {\n listener.callback(notification);\n } catch {\n // Notification listener raised — don't crash the engine\n }\n }\n }\n\n /**\n * Handle an incoming server→client request.\n * Dispatches to the appropriate handler based on the method field.\n */\n private async _handleServerRequest(\n request: Record<string, unknown>,\n ): Promise<void> {\n const method = request[\"method\"] as string;\n const requestId = request[\"id\"] as string;\n const params = (request[\"params\"] as Record<string, unknown>) ?? {};\n\n if (method === DroidClientMethod.REQUEST_PERMISSION) {\n await this._handlePermissionRequest(requestId, params);\n } else if (method === DroidClientMethod.ASK_USER) {\n await this._handleAskUserRequest(requestId, params);\n }\n // Unknown server→client methods are silently ignored\n }\n\n /**\n * Handle droid.request_permission server→client request.\n */\n private async _handlePermissionRequest(\n requestId: string,\n params: Record<string, unknown>,\n ): Promise<void> {\n const handler = this._permissionHandler;\n\n if (handler == null) {\n // Default: Cancel\n this._sendResponse(requestId, { selectedOption: \"cancel\" });\n return;\n }\n\n try {\n const selectedOption = await Promise.resolve(handler(params));\n this._sendResponse(requestId, { selectedOption });\n } catch (exc) {\n const errorMessage =\n exc instanceof Error ? exc.message : String(exc);\n this._sendErrorResponse(\n requestId,\n JsonRpcErrorCode.INTERNAL_ERROR,\n \"Failed to handle permission request\",\n errorMessage,\n );\n }\n }\n\n /**\n * Handle droid.ask_user server→client request.\n */\n private async _handleAskUserRequest(\n requestId: string,\n params: Record<string, unknown>,\n ): Promise<void> {\n const handler = this._askUserHandler;\n\n if (handler == null) {\n // Default: cancelled=true\n this._sendResponse(requestId, { cancelled: true, answers: [] });\n return;\n }\n\n try {\n const result = await Promise.resolve(handler(params));\n this._sendResponse(requestId, result);\n } catch (exc) {\n const errorMessage =\n exc instanceof Error ? exc.message : String(exc);\n this._sendErrorResponse(\n requestId,\n JsonRpcErrorCode.INTERNAL_ERROR,\n \"Failed to handle ask-user request\",\n errorMessage,\n );\n }\n }\n\n // ------------------------------------------------------------------\n // Internal: Transport error handling\n // ------------------------------------------------------------------\n\n /**\n * Handle a transport error.\n * Sets the sticky transport error and rejects all pending requests.\n * The original error is preserved as `cause` on the ConnectionError.\n */\n private _handleTransportError(error: Error): void {\n this._transportError = error;\n const connectionError = new ConnectionError(\n `Transport error: ${error.message}`,\n );\n connectionError.cause = error;\n this._rejectAllPending(connectionError);\n }\n\n // ------------------------------------------------------------------\n // Internal: Response helpers\n // ------------------------------------------------------------------\n\n /**\n * Send a JSON-RPC success response back to the server.\n */\n private _sendResponse(\n requestId: string,\n result: Record<string, unknown>,\n ): void {\n const response: Record<string, unknown> = {\n jsonrpc: JSONRPC_VERSION,\n factoryApiVersion: LEGACY_FACTORY_API_VERSION,\n factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,\n type: \"response\",\n id: requestId,\n result,\n };\n try {\n this._transport.send(response);\n } catch {\n // Failed to send response — log but don't crash\n }\n }\n\n /**\n * Send a JSON-RPC error response back to the server.\n */\n private _sendErrorResponse(\n requestId: string,\n code: number,\n message: string,\n data?: unknown,\n ): void {\n const errorObj: Record<string, unknown> = { code, message };\n if (data !== undefined) {\n errorObj[\"data\"] = data;\n }\n\n const response: Record<string, unknown> = {\n jsonrpc: JSONRPC_VERSION,\n factoryApiVersion: LEGACY_FACTORY_API_VERSION,\n factoryProtocolVersion: FACTORY_PROTOCOL_VERSION,\n type: \"response\",\n id: requestId,\n error: errorObj,\n };\n try {\n this._transport.send(response);\n } catch {\n // Failed to send error response — don't crash\n }\n }\n\n /**\n * Reject all pending requests with the given error.\n */\n private _rejectAllPending(error: Error): void {\n const pending = new Map(this._pendingRequests);\n this._pendingRequests.clear();\n\n for (const req of pending.values()) {\n clearTimeout(req.timer);\n req.reject(error);\n }\n }\n}\n","/**\n * DroidClient — high-level typed client for the Factory Droid SDK.\n *\n * Wraps a {@link ProtocolEngine} and provides typed async methods for all\n * 19 `droid.*` JSON-RPC methods, notification subscription with type\n * filtering, and permission/ask-user handler registration.\n *\n * Built on top of the `ProtocolEngine` and a `DroidClientTransport`\n * implementation.\n */\n\nimport { ConnectionError, SessionError } from \"./errors.js\";\nimport {\n ProtocolEngine,\n type NotificationCallback,\n type NotificationFilter,\n} from \"./protocol.js\";\nimport { DroidServerMethod } from \"./schemas/enums.js\";\nimport {\n MCP_AUTH_TIMEOUT,\n SESSION_INIT_TIMEOUT,\n} from \"./schemas/constants.js\";\nimport type {\n AddMcpServerRequestParams,\n AddMcpServerResult,\n AddUserMessageRequestParams,\n AddUserMessageResult,\n AuthenticateMcpServerRequestParams,\n AuthenticateMcpServerResult,\n CancelMcpAuthRequestParams,\n CancelMcpAuthResult,\n ClearMcpAuthRequestParams,\n ClearMcpAuthResult,\n InitializeSessionRequestParams,\n InitializeSessionResult,\n InterruptSessionResult,\n KillWorkerSessionRequestParams,\n KillWorkerSessionResult,\n ListMcpRegistryResult,\n ListMcpServersResult,\n ListMcpToolsResult,\n ListSkillsResult,\n LoadSessionRequestParams,\n LoadSessionResult,\n RemoveMcpServerRequestParams,\n RemoveMcpServerResult,\n SubmitBugReportRequestParams,\n SubmitBugReportResult,\n SubmitMcpAuthCodeRequestParams,\n SubmitMcpAuthCodeResult,\n ToggleMcpServerRequestParams,\n ToggleMcpServerResult,\n ToggleMcpToolRequestParams,\n ToggleMcpToolResult,\n UpdateSessionSettingsRequestParams,\n UpdateSessionSettingsResult,\n} from \"./schemas/client.js\";\nimport type { DroidClientTransport } from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * Handler for server→client permission requests at the client level.\n * Receives the full request params and returns a ToolConfirmationOutcome string.\n */\nexport type ClientPermissionHandler = (\n params: Record<string, unknown>,\n) => string | Promise<string>;\n\n/**\n * Handler for server→client ask-user requests at the client level.\n * Receives the full request params and returns a result object.\n */\nexport type ClientAskUserHandler = (\n params: Record<string, unknown>,\n) => Record<string, unknown> | Promise<Record<string, unknown>>;\n\n/**\n * Options for constructing a DroidClient.\n */\nexport interface DroidClientOptions {\n /** A connected DroidClientTransport implementation. */\n transport: DroidClientTransport;\n\n /** Default request timeout in ms. Defaults to 30 000. */\n defaultTimeout?: number;\n}\n\n// ---------------------------------------------------------------------------\n// DroidClient\n// ---------------------------------------------------------------------------\n\n/**\n * High-level typed client for the Factory Droid SDK.\n *\n * Provides async methods for all 19 `droid.*` JSON-RPC operations,\n * notification subscription with optional type filtering, and handler\n * registration for server→client requests (permissions, ask-user).\n *\n * @example\n * ```ts\n * const transport = new InMemoryTransport();\n * await transport.connect();\n * const client = new DroidClient({ transport });\n *\n * const result = await client.initializeSession({\n * machineId: \"test\",\n * cwd: \"/tmp\",\n * });\n *\n * await client.close();\n * ```\n */\nexport class DroidClient {\n private readonly _engine: ProtocolEngine;\n private _sessionId: string | null = null;\n private _closed = false;\n\n /**\n * Client-level notification listeners.\n * Each entry is [callback, optional type filter string].\n */\n private readonly _notificationListeners: Array<{\n callback: NotificationCallback;\n typeFilter?: string;\n }> = [];\n\n /** Client-level permission handler. */\n private _permissionHandler: ClientPermissionHandler | null = null;\n\n /** Client-level ask-user handler. */\n private _askUserHandler: ClientAskUserHandler | null = null;\n\n constructor(options: DroidClientOptions) {\n this._engine = new ProtocolEngine({\n transport: options.transport,\n defaultTimeout: options.defaultTimeout,\n });\n\n // Wire up protocol engine's notification dispatch to client-level listeners\n this._engine.onNotification((notification) => {\n this._dispatchNotification(notification);\n });\n\n // Wire up protocol engine's server→client request handlers\n // to client-level dispatch methods\n this._engine.setPermissionHandler((params) =>\n this._dispatchPermissionRequest(params),\n );\n this._engine.setAskUserHandler((params) =>\n this._dispatchAskUserRequest(params),\n );\n }\n\n // ------------------------------------------------------------------\n // Properties\n // ------------------------------------------------------------------\n\n /**\n * Current session ID, or `null` if no session is active.\n */\n get sessionId(): string | null {\n return this._sessionId;\n }\n\n /**\n * Whether the client is in a healthy state — not closed and no\n * transport errors have occurred. Returns false after transport\n * disconnect/error.\n */\n get isConnected(): boolean {\n return !this._closed && this._engine.isHealthy;\n }\n\n // ------------------------------------------------------------------\n // Session lifecycle methods\n // ------------------------------------------------------------------\n\n /**\n * Initialize a new session.\n *\n * Sends `droid.initialize_session` with extended timeout. On success,\n * stores the session ID internally and returns the typed result.\n */\n async initializeSession(\n params: InitializeSessionRequestParams,\n ): Promise<InitializeSessionResult> {\n this._ensureNotClosed();\n\n const response = await this._engine.sendRequest(\n DroidServerMethod.INITIALIZE_SESSION,\n params as unknown as Record<string, unknown>,\n SESSION_INIT_TIMEOUT,\n );\n\n const result = (response as Record<string, unknown>)[\"result\"] as\n | InitializeSessionResult\n | undefined;\n if (result) {\n this._sessionId = result.sessionId;\n return result;\n }\n\n // If the response has the result at top level (protocol engine returns full response)\n if (\"sessionId\" in response) {\n this._sessionId = (response as Record<string, unknown>)[\n \"sessionId\"\n ] as string;\n return response as unknown as InitializeSessionResult;\n }\n\n return response as unknown as InitializeSessionResult;\n }\n\n /**\n * Load an existing session.\n *\n * Sends `droid.load_session`. SessionNotFoundError is thrown for\n * non-existent sessions (mapped from ENTITY_NOT_FOUND by the protocol engine).\n */\n async loadSession(\n params: LoadSessionRequestParams,\n ): Promise<LoadSessionResult> {\n this._ensureNotClosed();\n\n const response = await this._engine.sendRequest(\n DroidServerMethod.LOAD_SESSION,\n params as unknown as Record<string, unknown>,\n SESSION_INIT_TIMEOUT,\n );\n\n const result = (response as Record<string, unknown>)[\"result\"] as\n | LoadSessionResult\n | undefined;\n if (result) {\n this._sessionId = params.sessionId;\n return result;\n }\n\n this._sessionId = params.sessionId;\n return response as unknown as LoadSessionResult;\n }\n\n /**\n * Add a user message to the active session.\n *\n * Sends `droid.add_user_message` with text and optional images/files.\n */\n async addUserMessage(\n params: Pick<AddUserMessageRequestParams, \"text\"> &\n Partial<Pick<AddUserMessageRequestParams, \"images\" | \"files\" | \"messageId\">>,\n ): Promise<AddUserMessageResult> {\n this._ensureNotClosed();\n this._ensureSession();\n\n const response = await this._engine.sendRequest(\n DroidServerMethod.ADD_USER_MESSAGE,\n params as unknown as Record<string, unknown>,\n );\n\n const result = (response as Record<string, unknown>)[\"result\"];\n return (result ?? response) as unknown as AddUserMessageResult;\n }\n\n /**\n * Interrupt the current session.\n *\n * Sends `droid.interrupt_session` with empty params.\n */\n async interruptSession(): Promise<InterruptSessionResult> {\n this._ensureNotClosed();\n this._ensureSession();\n\n const response = await this._engine.sendRequest(\n DroidServerMethod.INTERRUPT_SESSION,\n {},\n );\n\n const result = (response as Record<string, unknown>)[\"result\"];\n return (result ?? response) as unknown as InterruptSessionResult;\n }\n\n /**\n * Kill a worker session.\n *\n * Sends `droid.kill_worker_session`.\n */\n async killWorkerSession(\n params: KillWorkerSessionRequestParams,\n ): Promise<KillWorkerSessionResult> {\n this._ensureNotClosed();\n this._ensureSession();\n\n const response = await this._engine.sendRequest(\n DroidServerMethod.KILL_WORKER_SESSION,\n params as unknown as Record<string, unknown>,\n );\n\n const result = (response as Record<string, unknown>)[\"result\"];\n return (result ?? response) as unknown as KillWorkerSessionResult;\n }\n\n /**\n * Update session settings.\n *\n * Sends `droid.update_session_settings` with the provided partial settings.\n */\n async updateSessionSettings(\n params: Partial<UpdateSessionSettingsRequestParams>,\n ): Promise<UpdateSessionSettingsResult> {\n this._ensureNotClosed();\n this._ensureSession();\n\n const response = await this._engine.sendRequest(\n DroidServerMethod.UPDATE_SESSION_SETTINGS,\n params as unknown as Record<string, unknown>,\n );\n\n const result = (response as Record<string, unknown>)[\"result\"];\n return (result ?? response) as unknown as UpdateSessionSettingsResult;\n }\n\n // ------------------------------------------------------------------\n // MCP methods\n // ------------------------------------------------------------------\n\n /**\n * Toggle an MCP server on or off.\n */\n async toggleMcpServer(\n params: ToggleMcpServerRequestParams,\n ): Promise<ToggleMcpServerResult> {\n this._ensureNotClosed();\n this._ensureSession();\n\n const response = await this._engine.sendRequest(\n DroidServerMethod.TOGGLE_MCP_SERVER,\n params as unknown as Record<string, unknown>,\n );\n\n const result = (response as Record<string, unknown>)[\"result\"];\n return (result ?? response) as unknown as ToggleMcpServerResult;\n }\n\n /**\n * Authenticate an MCP server (OAuth flow).\n * Uses extended timeout (300s) since OAuth requires user interaction.\n */\n async authenticateMcpServer(\n params: AuthenticateMcpServerRequestParams,\n ): Promise<AuthenticateMcpServerResult> {\n this._ensureNotClosed();\n this._ensureSession();\n\n const response = await this._engine.sendRequest(\n DroidServerMethod.AUTHENTICATE_MCP_SERVER,\n params as unknown as Record<string, unknown>,\n MCP_AUTH_TIMEOUT,\n );\n\n const result = (response as Record<string, unknown>)[\"result\"];\n return (result ?? response) as unknown as AuthenticateMcpServerResult;\n }\n\n /**\n * Cancel an in-progress MCP authentication.\n */\n async cancelMcpAuth(\n params: CancelMcpAuthRequestParams,\n ): Promise<CancelMcpAuthResult> {\n this._ensureNotClosed();\n this._ensureSession();\n\n const response = await this._engine.sendRequest(\n DroidServerMethod.CANCEL_MCP_AUTH,\n params as unknown as Record<string, unknown>,\n );\n\n const result = (response as Record<string, unknown>)[\"result\"];\n return (result ?? response) as unknown as CancelMcpAuthResult;\n }\n\n /**\n * Clear stored MCP authentication tokens.\n */\n async clearMcpAuth(\n params: ClearMcpAuthRequestParams,\n ): Promise<ClearMcpAuthResult> {\n this._ensureNotClosed();\n this._ensureSession();\n\n const response = await this._engine.sendRequest(\n DroidServerMethod.CLEAR_MCP_AUTH,\n params as unknown as Record<string, unknown>,\n );\n\n const result = (response as Record<string, unknown>)[\"result\"];\n return (result ?? response) as unknown as ClearMcpAuthResult;\n }\n\n /**\n * Submit an MCP authentication code (OAuth callback).\n */\n async submitMcpAuthCode(\n params: SubmitMcpAuthCodeRequestParams,\n ): Promise<SubmitMcpAuthCodeResult> {\n this._ensureNotClosed();\n this._ensureSession();\n\n const response = await this._engine.sendRequest(\n DroidServerMethod.SUBMIT_MCP_AUTH_CODE,\n params as unknown as Record<string, unknown>,\n );\n\n const result = (response as Record<string, unknown>)[\"result\"];\n return (result ?? response) as unknown as SubmitMcpAuthCodeResult;\n }\n\n /**\n * Add an MCP server.\n */\n async addMcpServer(\n params: AddMcpServerRequestParams,\n ): Promise<AddMcpServerResult> {\n this._ensureNotClosed();\n this._ensureSession();\n\n const response = await this._engine.sendRequest(\n DroidServerMethod.ADD_MCP_SERVER,\n params as unknown as Record<string, unknown>,\n );\n\n const result = (response as Record<string, unknown>)[\"result\"];\n return (result ?? response) as unknown as AddMcpServerResult;\n }\n\n /**\n * Remove an MCP server.\n */\n async removeMcpServer(\n params: RemoveMcpServerRequestParams,\n ): Promise<RemoveMcpServerResult> {\n this._ensureNotClosed();\n this._ensureSession();\n\n const response = await this._engine.sendRequest(\n DroidServerMethod.REMOVE_MCP_SERVER,\n params as unknown as Record<string, unknown>,\n );\n\n const result = (response as Record<string, unknown>)[\"result\"];\n return (result ?? response) as unknown as RemoveMcpServerResult;\n }\n\n /**\n * List available MCP registry servers.\n */\n async listMcpRegistry(): Promise<ListMcpRegistryResult> {\n this._ensureNotClosed();\n this._ensureSession();\n\n const response = await this._engine.sendRequest(\n DroidServerMethod.LIST_MCP_REGISTRY,\n {},\n );\n\n const result = (response as Record<string, unknown>)[\"result\"];\n return (result ?? response) as unknown as ListMcpRegistryResult;\n }\n\n /**\n * List available MCP tools.\n */\n async listMcpTools(): Promise<ListMcpToolsResult> {\n this._ensureNotClosed();\n this._ensureSession();\n\n const response = await this._engine.sendRequest(\n DroidServerMethod.LIST_MCP_TOOLS,\n {},\n );\n\n const result = (response as Record<string, unknown>)[\"result\"];\n return (result ?? response) as unknown as ListMcpToolsResult;\n }\n\n /**\n * List MCP servers with status and summary.\n */\n async listMcpServers(): Promise<ListMcpServersResult> {\n this._ensureNotClosed();\n this._ensureSession();\n\n const response = await this._engine.sendRequest(\n DroidServerMethod.LIST_MCP_SERVERS,\n {},\n );\n\n const result = (response as Record<string, unknown>)[\"result\"];\n return (result ?? response) as unknown as ListMcpServersResult;\n }\n\n /**\n * Toggle an MCP tool on or off.\n */\n async toggleMcpTool(\n params: ToggleMcpToolRequestParams,\n ): Promise<ToggleMcpToolResult> {\n this._ensureNotClosed();\n this._ensureSession();\n\n const response = await this._engine.sendRequest(\n DroidServerMethod.TOGGLE_MCP_TOOL,\n params as unknown as Record<string, unknown>,\n );\n\n const result = (response as Record<string, unknown>)[\"result\"];\n return (result ?? response) as unknown as ToggleMcpToolResult;\n }\n\n // ------------------------------------------------------------------\n // Skills and bug report methods\n // ------------------------------------------------------------------\n\n /**\n * List available skills.\n */\n async listSkills(): Promise<ListSkillsResult> {\n this._ensureNotClosed();\n this._ensureSession();\n\n const response = await this._engine.sendRequest(\n DroidServerMethod.LIST_SKILLS,\n {},\n );\n\n const result = (response as Record<string, unknown>)[\"result\"];\n return (result ?? response) as unknown as ListSkillsResult;\n }\n\n /**\n * Submit a bug report.\n */\n async submitBugReport(\n params: SubmitBugReportRequestParams,\n ): Promise<SubmitBugReportResult> {\n this._ensureNotClosed();\n this._ensureSession();\n\n const response = await this._engine.sendRequest(\n DroidServerMethod.SUBMIT_BUG_REPORT,\n params as unknown as Record<string, unknown>,\n );\n\n const result = (response as Record<string, unknown>)[\"result\"];\n return (result ?? response) as unknown as SubmitBugReportResult;\n }\n\n // ------------------------------------------------------------------\n // Notification subscription\n // ------------------------------------------------------------------\n\n /**\n * Register a callback for incoming notification messages.\n *\n * Multiple listeners can be registered. Each receives the full parsed\n * notification object. Optionally filter by notification type.\n *\n * Listener exceptions are isolated — if one raises, others still receive\n * the event and the engine continues.\n *\n * @param callback - Invoked with the notification object.\n * @param filter - Optional filter to only receive specific notification types.\n * @returns An unsubscribe function. Calling it again is safe (no-op).\n */\n onNotification(\n callback: NotificationCallback,\n filter?: NotificationFilter,\n ): () => void {\n const entry = {\n callback,\n typeFilter: filter?.type,\n };\n this._notificationListeners.push(entry);\n\n let unsubscribed = false;\n return () => {\n if (!unsubscribed) {\n unsubscribed = true;\n const idx = this._notificationListeners.indexOf(entry);\n if (idx !== -1) {\n this._notificationListeners.splice(idx, 1);\n }\n }\n };\n }\n\n // ------------------------------------------------------------------\n // Permission/ask-user handler registration\n // ------------------------------------------------------------------\n\n /**\n * Register a handler for server→client permission requests.\n *\n * The handler receives the request params and should return a\n * ToolConfirmationOutcome string value. Async handlers are awaited.\n * Replaces any previously registered handler.\n */\n setPermissionHandler(handler: ClientPermissionHandler): void {\n this._permissionHandler = handler;\n }\n\n /**\n * Remove the permission request handler.\n * Restores default behavior: return \"cancel\".\n */\n clearPermissionHandler(): void {\n this._permissionHandler = null;\n }\n\n /**\n * Register a handler for server→client ask-user requests.\n *\n * The handler receives the request params and should return a result\n * object with `cancelled` and `answers` keys. Async handlers are awaited.\n * Replaces any previously registered handler.\n */\n setAskUserHandler(handler: ClientAskUserHandler): void {\n this._askUserHandler = handler;\n }\n\n /**\n * Remove the ask-user request handler.\n * Restores default behavior: return `{ cancelled: true, answers: [] }`.\n */\n clearAskUserHandler(): void {\n this._askUserHandler = null;\n }\n\n // ------------------------------------------------------------------\n // Lifecycle\n // ------------------------------------------------------------------\n\n /**\n * Close the client and release all resources.\n *\n * Rejects pending requests, clears handlers and listeners, and closes\n * the protocol engine. Idempotent — safe to call multiple times.\n *\n * After close, all method calls throw ConnectionError immediately.\n */\n async close(): Promise<void> {\n if (this._closed) {\n return;\n }\n this._closed = true;\n\n // Clear client-level state\n this._notificationListeners.length = 0;\n this._permissionHandler = null;\n this._askUserHandler = null;\n\n // Close the protocol engine (which closes the transport)\n await this._engine.close();\n }\n\n // ------------------------------------------------------------------\n // Internal: dispatch methods\n // ------------------------------------------------------------------\n\n /**\n * Dispatch a notification to all registered client-level listeners.\n * Filters by notification type if a type filter is set.\n * Exception in one listener does not affect others.\n */\n private _dispatchNotification(notification: Record<string, unknown>): void {\n // Extract the notification type from the payload\n const params = notification[\"params\"] as\n | Record<string, unknown>\n | undefined;\n const innerNotification = params?.[\"notification\"] as\n | Record<string, unknown>\n | undefined;\n const notificationType = innerNotification?.[\"type\"] as string | undefined;\n\n // Iterate over a copy in case listeners unsubscribe during iteration\n const listeners = [...this._notificationListeners];\n for (const listener of listeners) {\n // Apply type filter if present\n if (\n listener.typeFilter != null &&\n listener.typeFilter !== notificationType\n ) {\n continue;\n }\n\n try {\n listener.callback(notification);\n } catch {\n // Notification listener raised — don't crash the client\n }\n }\n }\n\n /**\n * Dispatch to the client-level permission handler.\n * If no handler is set, returns the default \"cancel\" outcome.\n * If handler throws, the error propagates to the protocol engine\n * which sends an error response.\n */\n private _dispatchPermissionRequest(\n params: Record<string, unknown>,\n ): string | Promise<string> {\n const handler = this._permissionHandler;\n if (handler == null) {\n return \"cancel\";\n }\n return handler(params);\n }\n\n /**\n * Dispatch to the client-level ask-user handler.\n * If no handler is set, returns the default cancelled response.\n * If handler throws, the error propagates to the protocol engine\n * which sends an error response.\n */\n private _dispatchAskUserRequest(\n params: Record<string, unknown>,\n ): Record<string, unknown> | Promise<Record<string, unknown>> {\n const handler = this._askUserHandler;\n if (handler == null) {\n return { cancelled: true, answers: [] };\n }\n return handler(params);\n }\n\n // ------------------------------------------------------------------\n // Internal: guards\n // ------------------------------------------------------------------\n\n /**\n * Throw ConnectionError if the client has been closed.\n */\n private _ensureNotClosed(): void {\n if (this._closed) {\n throw new ConnectionError(\n \"Client has been closed. Create a new DroidClient instance to reconnect.\",\n );\n }\n }\n\n /**\n * Throw SessionError if no active session.\n */\n private _ensureSession(): void {\n if (this._sessionId == null) {\n throw new SessionError(\n \"No active session. Call initializeSession or loadSession first.\",\n );\n }\n }\n}\n","/**\n * Typed stream message interfaces and notification-to-stream converter.\n *\n * Defines 22 DroidMessage types as TypeScript interfaces with a discriminated\n * `type` field, plus a notification converter and working-state tracker for\n * TurnComplete emission.\n *\n * Reference: Python SDK stream.py\n */\n\nimport type {\n McpServerStatusInfo,\n McpStatusSummary,\n MissionFeature,\n ProgressLogEntry,\n SettingsUpdatedPayload,\n TokenUsage,\n ToolProgressUpdate,\n} from \"./schemas/index.js\";\n\nimport {\n DroidWorkingState,\n McpAuthOutcome,\n MissionState,\n SessionNotificationType,\n ToolConfirmationOutcome,\n} from \"./schemas/index.js\";\n\n// ---------------------------------------------------------------------------\n// 22 DroidMessage interfaces — discriminated on `type`\n// ---------------------------------------------------------------------------\n\n/** A delta of assistant-generated text (streaming token). */\nexport interface AssistantTextDelta {\n readonly type: \"assistant_text_delta\";\n readonly messageId: string;\n readonly blockIndex: number;\n readonly text: string;\n}\n\n/** A delta of assistant thinking/reasoning text. */\nexport interface ThinkingTextDelta {\n readonly type: \"thinking_text_delta\";\n readonly messageId: string;\n readonly blockIndex: number;\n readonly text: string;\n}\n\n/** A tool invocation issued by the assistant (from create_message). */\nexport interface ToolUse {\n readonly type: \"tool_use\";\n readonly toolName: string;\n readonly toolInput: Record<string, unknown>;\n readonly toolUseId: string;\n}\n\n/** The result returned from a tool execution. */\nexport interface ToolResult {\n readonly type: \"tool_result\";\n readonly toolUseId: string;\n readonly content: string | unknown[];\n readonly isError: boolean;\n}\n\n/** A streaming progress update from a tool execution. */\nexport interface ToolProgress {\n readonly type: \"tool_progress\";\n readonly toolUseId: string;\n readonly toolName: string;\n readonly content: string;\n readonly update: ToolProgressUpdate;\n}\n\n/** The droid working state has changed. */\nexport interface WorkingStateChanged {\n readonly type: \"working_state_changed\";\n readonly state: DroidWorkingState;\n}\n\n/** Updated token usage counters for the session. */\nexport interface TokenUsageUpdate {\n readonly type: \"token_usage_update\";\n readonly inputTokens: number;\n readonly outputTokens: number;\n readonly cacheReadTokens: number;\n readonly cacheWriteTokens: number;\n readonly thinkingTokens: number;\n}\n\n/** A full assistant message was created (may contain tool_use blocks). */\nexport interface CreateMessage {\n readonly type: \"create_message\";\n readonly messageId: string;\n readonly role: string;\n readonly content: unknown[];\n readonly parentId?: string;\n}\n\n/** A permission request was resolved. */\nexport interface PermissionResolved {\n readonly type: \"permission_resolved\";\n readonly requestId: string;\n readonly toolUseIds: string[];\n readonly selectedOption: ToolConfirmationOutcome;\n}\n\n/** Session settings were updated. */\nexport interface SettingsUpdated {\n readonly type: \"settings_updated\";\n readonly settings: SettingsUpdatedPayload;\n}\n\n/** The session title was updated. */\nexport interface SessionTitleUpdated {\n readonly type: \"session_title_updated\";\n readonly title: string;\n}\n\n/** MCP server status changed. */\nexport interface McpStatusChanged {\n readonly type: \"mcp_status_changed\";\n readonly servers: McpServerStatusInfo[];\n readonly summary: McpStatusSummary;\n}\n\n/** Mission state changed. */\nexport interface MissionStateChanged {\n readonly type: \"mission_state_changed\";\n readonly state: MissionState;\n}\n\n/** Mission features changed. */\nexport interface MissionFeaturesChanged {\n readonly type: \"mission_features_changed\";\n readonly features: MissionFeature[];\n}\n\n/** Mission progress entry. */\nexport interface MissionProgressEntry {\n readonly type: \"mission_progress_entry\";\n readonly progressLog: ProgressLogEntry[];\n}\n\n/** Mission heartbeat. */\nexport interface MissionHeartbeat {\n readonly type: \"mission_heartbeat\";\n readonly timestamp: string;\n}\n\n/** A mission worker started. */\nexport interface MissionWorkerStarted {\n readonly type: \"mission_worker_started\";\n readonly workerSessionId: string;\n}\n\n/** A mission worker completed. */\nexport interface MissionWorkerCompleted {\n readonly type: \"mission_worker_completed\";\n readonly workerSessionId: string;\n readonly exitCode: number;\n}\n\n/** MCP authentication is required. */\nexport interface McpAuthRequired {\n readonly type: \"mcp_auth_required\";\n readonly serverName: string;\n readonly authUrl: string;\n readonly message: string;\n readonly state: string;\n}\n\n/** MCP authentication completed. */\nexport interface McpAuthCompleted {\n readonly type: \"mcp_auth_completed\";\n readonly serverName: string;\n readonly outcome: McpAuthOutcome;\n readonly message: string;\n}\n\n/** An error event from the droid process. */\nexport interface ErrorEvent {\n readonly type: \"error\";\n readonly message: string;\n readonly errorType: string;\n readonly timestamp: string;\n}\n\n/** Sentinel yielded when the agent turn finishes (returns to Idle). */\nexport interface TurnComplete {\n readonly type: \"turn_complete\";\n readonly tokenUsage: TokenUsageUpdate | null;\n}\n\n// ---------------------------------------------------------------------------\n// DroidMessage union\n// ---------------------------------------------------------------------------\n\n/** Discriminated union of all 22 stream message types. */\nexport type DroidMessage =\n | AssistantTextDelta\n | ThinkingTextDelta\n | ToolUse\n | ToolResult\n | ToolProgress\n | WorkingStateChanged\n | TokenUsageUpdate\n | CreateMessage\n | PermissionResolved\n | SettingsUpdated\n | SessionTitleUpdated\n | McpStatusChanged\n | MissionStateChanged\n | MissionFeaturesChanged\n | MissionProgressEntry\n | MissionHeartbeat\n | MissionWorkerStarted\n | MissionWorkerCompleted\n | McpAuthRequired\n | McpAuthCompleted\n | ErrorEvent\n | TurnComplete;\n\n// ---------------------------------------------------------------------------\n// Notification payload type (matches SessionNotificationPayload)\n// ---------------------------------------------------------------------------\n\n/**\n * A notification payload object as received from the protocol layer.\n * Must have at least a `type` string field. Other properties are\n * notification-type-specific.\n */\ninterface NotificationPayload {\n type: string;\n [key: string]: unknown;\n}\n\n// ---------------------------------------------------------------------------\n// Converter: notification → DroidMessage(s)\n// ---------------------------------------------------------------------------\n\n/**\n * Convert a server session notification payload to the corresponding\n * DroidMessage(s).\n *\n * For `create_message` notifications containing tool_use content blocks,\n * a list of ToolUse messages is returned (one per tool_use block), followed\n * by a single CreateMessage. For all other notification types a single\n * DroidMessage is returned, or `null` if the notification type is unknown.\n *\n * Unknown notification types return `null` and log a warning to the console.\n *\n * @param notification - A notification payload from `SessionNotification.params.notification`.\n * @returns A single DroidMessage, an array of DroidMessages, or `null` for unknown types.\n */\nexport function convertNotificationToStreamMessage(\n notification: NotificationPayload,\n): DroidMessage | DroidMessage[] | null {\n switch (notification.type) {\n case SessionNotificationType.ASSISTANT_TEXT_DELTA:\n return {\n type: \"assistant_text_delta\",\n messageId: notification.messageId as string,\n blockIndex: notification.blockIndex as number,\n text: notification.textDelta as string,\n };\n\n case SessionNotificationType.THINKING_TEXT_DELTA:\n return {\n type: \"thinking_text_delta\",\n messageId: notification.messageId as string,\n blockIndex: notification.blockIndex as number,\n text: notification.textDelta as string,\n };\n\n case SessionNotificationType.TOOL_RESULT:\n return {\n type: \"tool_result\",\n toolUseId: notification.toolUseId as string,\n content: normalizeToolResultContent(notification.content),\n isError: Boolean(notification.isError),\n };\n\n case SessionNotificationType.TOOL_PROGRESS_UPDATE: {\n const update = notification.update as ToolProgressUpdate;\n const text = update?.text ?? update?.status ?? update?.details ?? \"\";\n return {\n type: \"tool_progress\",\n toolUseId: notification.toolUseId as string,\n toolName: notification.toolName as string,\n content: text,\n update,\n };\n }\n\n case SessionNotificationType.DROID_WORKING_STATE_CHANGED:\n return {\n type: \"working_state_changed\",\n state: notification.newState as DroidWorkingState,\n };\n\n case SessionNotificationType.SESSION_TOKEN_USAGE_CHANGED: {\n const tu = notification.tokenUsage as TokenUsage;\n return {\n type: \"token_usage_update\",\n inputTokens: tu.inputTokens,\n outputTokens: tu.outputTokens,\n cacheReadTokens: tu.cacheReadTokens,\n cacheWriteTokens: tu.cacheCreationTokens,\n thinkingTokens: tu.thinkingTokens,\n };\n }\n\n case SessionNotificationType.CREATE_MESSAGE: {\n const msg = notification.message as {\n id: string;\n role: string;\n content: Array<{ type: string; id?: string; name?: string; input?: Record<string, unknown>; [key: string]: unknown }>;\n };\n const messages: DroidMessage[] = [];\n\n // Extract ToolUse messages from tool_use content blocks\n if (msg.content && Array.isArray(msg.content)) {\n for (const block of msg.content) {\n if (block.type === \"tool_use\") {\n messages.push({\n type: \"tool_use\",\n toolName: block.name as string,\n toolInput: (block.input ?? {}) as Record<string, unknown>,\n toolUseId: block.id as string,\n });\n }\n }\n }\n\n // Always emit CreateMessage\n messages.push({\n type: \"create_message\",\n messageId: msg.id,\n role: msg.role,\n content: msg.content ?? [],\n parentId: notification.parentId as string | undefined,\n });\n\n return messages;\n }\n\n case SessionNotificationType.ERROR:\n return {\n type: \"error\",\n message: notification.message as string,\n errorType: notification.errorType as string,\n timestamp: notification.timestamp as string,\n };\n\n case SessionNotificationType.PERMISSION_RESOLVED:\n return {\n type: \"permission_resolved\",\n requestId: notification.requestId as string,\n toolUseIds: notification.toolUseIds as string[],\n selectedOption: notification.selectedOption as ToolConfirmationOutcome,\n };\n\n case SessionNotificationType.SETTINGS_UPDATED:\n return {\n type: \"settings_updated\",\n settings: notification.settings as SettingsUpdatedPayload,\n };\n\n case SessionNotificationType.SESSION_TITLE_UPDATED:\n return {\n type: \"session_title_updated\",\n title: notification.title as string,\n };\n\n case SessionNotificationType.MCP_STATUS_CHANGED:\n return {\n type: \"mcp_status_changed\",\n servers: notification.servers as McpServerStatusInfo[],\n summary: notification.summary as McpStatusSummary,\n };\n\n case SessionNotificationType.MISSION_STATE_CHANGED:\n return {\n type: \"mission_state_changed\",\n state: notification.state as MissionState,\n };\n\n case SessionNotificationType.MISSION_FEATURES_CHANGED:\n return {\n type: \"mission_features_changed\",\n features: notification.features as MissionFeature[],\n };\n\n case SessionNotificationType.MISSION_PROGRESS_ENTRY:\n return {\n type: \"mission_progress_entry\",\n progressLog: notification.progressLog as ProgressLogEntry[],\n };\n\n case SessionNotificationType.MISSION_HEARTBEAT:\n return {\n type: \"mission_heartbeat\",\n timestamp: notification.timestamp as string,\n };\n\n case SessionNotificationType.MISSION_WORKER_STARTED:\n return {\n type: \"mission_worker_started\",\n workerSessionId: notification.workerSessionId as string,\n };\n\n case SessionNotificationType.MISSION_WORKER_COMPLETED:\n return {\n type: \"mission_worker_completed\",\n workerSessionId: notification.workerSessionId as string,\n exitCode: notification.exitCode as number,\n };\n\n case SessionNotificationType.MCP_AUTH_REQUIRED:\n return {\n type: \"mcp_auth_required\",\n serverName: notification.serverName as string,\n authUrl: notification.authUrl as string,\n message: notification.message as string,\n state: notification.state as string,\n };\n\n case SessionNotificationType.MCP_AUTH_COMPLETED:\n return {\n type: \"mcp_auth_completed\",\n serverName: notification.serverName as string,\n outcome: notification.outcome as McpAuthOutcome,\n message: notification.message as string,\n };\n\n default:\n // Unknown notification type — log warning and return null\n console.warn(\n `[droid-sdk] Unknown notification type: ${String(notification.type)}`,\n );\n return null;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Working state tracker for TurnComplete emission\n// ---------------------------------------------------------------------------\n\n/**\n * Tracks working state transitions to detect when an agent turn completes\n * (transitions from a non-idle state back to idle).\n *\n * Each `stream()` call should create a fresh StreamStateTracker so that\n * multi-turn sessions track state independently.\n *\n * Rules:\n * - TurnComplete is emitted when state goes non-idle → idle\n * - Initial idle does NOT emit TurnComplete\n * - TurnComplete carries the last-seen TokenUsageUpdate (or null)\n */\nexport class StreamStateTracker {\n /** Whether we have ever seen a non-idle state. */\n private hasBeenNonIdle = false;\n\n /** Last-seen token usage update (to attach to TurnComplete). */\n private lastTokenUsage: TokenUsageUpdate | null = null;\n\n /**\n * Process a DroidMessage and return any additional messages that should be\n * emitted (e.g. TurnComplete sentinel).\n *\n * @param message - The DroidMessage to process.\n * @returns An array of additional messages to emit (may be empty).\n */\n processMessage(message: DroidMessage): DroidMessage[] {\n const additional: DroidMessage[] = [];\n\n if (message.type === \"token_usage_update\") {\n this.lastTokenUsage = message;\n }\n\n if (message.type === \"working_state_changed\") {\n if (message.state !== DroidWorkingState.Idle) {\n this.hasBeenNonIdle = true;\n } else if (this.hasBeenNonIdle) {\n // Non-idle → Idle transition: emit TurnComplete\n additional.push({\n type: \"turn_complete\",\n tokenUsage: this.lastTokenUsage,\n });\n // Reset so that subsequent idle→idle does NOT emit duplicate TurnComplete\n this.hasBeenNonIdle = false;\n }\n // If state is Idle but we were never non-idle, do nothing\n // (initial idle does NOT emit TurnComplete)\n }\n\n return additional;\n }\n\n /**\n * Reset the tracker for a new turn/stream call.\n */\n reset(): void {\n this.hasBeenNonIdle = false;\n this.lastTokenUsage = null;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction normalizeToolResultContent(content: unknown): string | unknown[] {\n if (content == null) {\n return \"\";\n }\n if (typeof content === \"string\") {\n return content;\n }\n if (Array.isArray(content)) {\n return content as unknown[];\n }\n return String(content);\n}\n","/**\n * Top-level `query()` convenience function and supporting types.\n *\n * Provides a high-level async generator that hides the full session lifecycle\n * (spawn → connect → initialize → message → yield → close), modeled after\n * the Claude Agent SDK and the Python Droid SDK's `query()` pattern.\n *\n * @example\n * ```ts\n * import { query } from \"@factory/droid-sdk\";\n *\n * const stream = query({ prompt: \"Fix the bug in main.ts\", cwd: \"/my/project\" });\n *\n * for await (const msg of stream) {\n * if (msg.type === \"assistant_text_delta\") {\n * process.stdout.write(msg.text);\n * }\n * }\n * ```\n */\n\nimport { DroidClient } from \"./client.js\";\nimport type { ClientPermissionHandler, ClientAskUserHandler } from \"./client.js\";\nimport {\n convertNotificationToStreamMessage,\n StreamStateTracker,\n} from \"./stream.js\";\nimport type { DroidMessage } from \"./stream.js\";\nimport { ProcessTransport } from \"./transport.js\";\nimport type { DroidClientTransport, ProcessTransportOptions } from \"./types.js\";\nimport type {\n InitializeSessionRequestParams,\n} from \"./schemas/client.js\";\nimport type {\n AutonomyLevel,\n DroidInteractionMode,\n ReasoningEffort,\n} from \"./schemas/enums.js\";\n\n// ---------------------------------------------------------------------------\n// QueryOptions\n// ---------------------------------------------------------------------------\n\n/**\n * Options for the `query()` convenience function.\n */\nexport interface QueryOptions {\n /** The user prompt to send. */\n prompt: string;\n\n /** Working directory for the session. Defaults to `\".\"`. */\n cwd?: string;\n\n /** Machine identifier. Defaults to `\"default\"`. */\n machineId?: string;\n\n /** LLM model identifier. */\n modelId?: string;\n\n /** Autonomy level for the session. */\n autonomyLevel?: AutonomyLevel;\n\n /** Interaction mode for the session. */\n interactionMode?: DroidInteractionMode;\n\n /** Reasoning effort level. */\n reasoningEffort?: ReasoningEffort;\n\n /** MCP server configurations for the session. */\n mcpServers?: Array<Record<string, unknown>>;\n\n /** Additional tool IDs to enable. */\n enabledToolIds?: string[];\n\n /** Path to the `droid` executable. Defaults to `\"droid\"`. */\n execPath?: string;\n\n /** Additional arguments for the droid executable. */\n execArgs?: string[];\n\n /** Additional environment variables for the subprocess. */\n env?: Record<string, string>;\n\n /** Permission handler for tool confirmations. */\n permissionHandler?: ClientPermissionHandler;\n\n /** Ask-user handler for interactive questions. */\n askUserHandler?: ClientAskUserHandler;\n\n /**\n * An already-connected transport to use instead of spawning a process.\n * When provided, `execPath`, `execArgs`, `env`, and `cwd` (for transport) are ignored.\n * The transport will still be closed when the query completes.\n */\n transport?: DroidClientTransport;\n\n /** AbortSignal for external cancellation. */\n abortSignal?: AbortSignal;\n}\n\n// ---------------------------------------------------------------------------\n// DroidQuery\n// ---------------------------------------------------------------------------\n\n/**\n * An async generator of {@link DroidMessage} events with additional control\n * methods for interrupting or aborting the query.\n *\n * Extends AsyncGenerator<DroidMessage> with:\n * - `interrupt()` — sends an interrupt request to pause the agent gracefully\n * - `abort()` — forcefully closes the transport/kills the subprocess\n * - `sessionId` — the session ID assigned during initialization\n */\nexport interface DroidQuery extends AsyncGenerator<DroidMessage, void, undefined> {\n /** Send an interrupt_session request. The stream continues until the agent stops. */\n interrupt(): Promise<void>;\n\n /** Forcefully close the transport. The generator terminates immediately. */\n abort(): void;\n\n /**\n * The session ID, available after initialization.\n * Returns `null` if the session hasn't been initialized yet.\n */\n readonly sessionId: string | null;\n}\n\n// ---------------------------------------------------------------------------\n// query() implementation\n// ---------------------------------------------------------------------------\n\n/**\n * Top-level convenience function that spawns a droid process, initializes\n * a session, sends the user prompt, and yields {@link DroidMessage} events.\n *\n * All resources (transport, client) are cleaned up in a finally block,\n * even if the caller breaks out of the generator early or an error occurs.\n *\n * @param options - Query configuration including the prompt and optional session settings.\n * @returns A {@link DroidQuery} async generator with interrupt/abort/sessionId.\n *\n * @example\n * ```ts\n * const stream = query({ prompt: \"Hello\", cwd: \"/tmp\" });\n *\n * for await (const msg of stream) {\n * if (msg.type === \"assistant_text_delta\") {\n * process.stdout.write(msg.text);\n * }\n * if (msg.type === \"turn_complete\") {\n * console.log(\"\\nDone! Tokens:\", msg.tokenUsage);\n * }\n * }\n *\n * // Or with interrupt:\n * const q = query({ prompt: \"Write a long essay\" });\n * setTimeout(() => q.interrupt(), 5000);\n * for await (const msg of q) { ... }\n * ```\n */\nexport function query(options: QueryOptions): DroidQuery {\n let transport: DroidClientTransport | null = null;\n let client: DroidClient | null = null;\n let sessionId: string | null = null;\n let aborted = false;\n\n // Message queue for notification → stream bridging\n const messageQueue: DroidMessage[] = [];\n let resolveWaiting: (() => void) | null = null;\n let streamDone = false;\n\n /**\n * Push a message into the queue and wake the consumer if waiting.\n */\n function enqueueMessage(msg: DroidMessage): void {\n messageQueue.push(msg);\n if (resolveWaiting) {\n const resolve = resolveWaiting;\n resolveWaiting = null;\n resolve();\n }\n }\n\n /**\n * Signal that streaming is complete.\n */\n function signalDone(): void {\n streamDone = true;\n if (resolveWaiting) {\n const resolve = resolveWaiting;\n resolveWaiting = null;\n resolve();\n }\n }\n\n /**\n * The core async generator that drives the query lifecycle.\n */\n async function* generateMessages(): AsyncGenerator<DroidMessage, void, undefined> {\n // 1. Create transport\n if (options.transport) {\n transport = options.transport;\n } else {\n const transportOptions: ProcessTransportOptions = {\n execPath: options.execPath,\n execArgs: options.execArgs,\n cwd: options.cwd,\n env: options.env,\n };\n const processTransport = new ProcessTransport(transportOptions);\n await processTransport.connect();\n transport = processTransport;\n }\n\n // 2. Create client\n client = new DroidClient({ transport });\n\n // 3. Set up handlers if provided\n if (options.permissionHandler) {\n client.setPermissionHandler(options.permissionHandler);\n }\n if (options.askUserHandler) {\n client.setAskUserHandler(options.askUserHandler);\n }\n\n // 4. Set up notification → stream bridging\n const stateTracker = new StreamStateTracker();\n\n client.onNotification((notification) => {\n // Extract the inner notification payload\n const params = notification[\"params\"] as Record<string, unknown> | undefined;\n const innerNotification = params?.[\"notification\"] as Record<string, unknown> | undefined;\n\n if (!innerNotification) {\n return;\n }\n\n const converted = convertNotificationToStreamMessage(\n innerNotification as { type: string; [key: string]: unknown },\n );\n\n if (converted === null) {\n return;\n }\n\n const messages = Array.isArray(converted) ? converted : [converted];\n\n for (const msg of messages) {\n enqueueMessage(msg);\n\n // Check for TurnComplete via state tracker\n const additional = stateTracker.processMessage(msg);\n for (const extra of additional) {\n enqueueMessage(extra);\n if (extra.type === \"turn_complete\") {\n signalDone();\n }\n }\n }\n });\n\n // 5. Initialize session\n const initParams: Record<string, unknown> = {\n machineId: options.machineId ?? \"default\",\n cwd: options.cwd ?? \".\",\n };\n\n if (options.modelId !== undefined) {\n initParams.modelId = options.modelId;\n }\n if (options.autonomyLevel !== undefined) {\n initParams.autonomyLevel = options.autonomyLevel;\n }\n if (options.interactionMode !== undefined) {\n initParams.interactionMode = options.interactionMode;\n }\n if (options.reasoningEffort !== undefined) {\n initParams.reasoningEffort = options.reasoningEffort;\n }\n if (options.mcpServers !== undefined) {\n initParams.mcpServers = options.mcpServers;\n }\n if (options.enabledToolIds !== undefined) {\n initParams.enabledToolIds = options.enabledToolIds;\n }\n\n const initResult = await client.initializeSession(\n initParams as unknown as InitializeSessionRequestParams,\n );\n sessionId = initResult.sessionId;\n\n // 6. Send the user message\n await client.addUserMessage({ text: options.prompt });\n\n // 7. Yield messages from the queue until done\n try {\n while (true) {\n // If aborted externally, stop\n if (aborted) {\n return;\n }\n\n // Process any queued messages\n while (messageQueue.length > 0) {\n const msg = messageQueue.shift()!;\n yield msg;\n\n if (msg.type === \"turn_complete\") {\n return;\n }\n }\n\n // Check if we're done (TurnComplete already yielded above)\n if (streamDone && messageQueue.length === 0) {\n return;\n }\n\n // Wait for more messages\n await new Promise<void>((resolve) => {\n resolveWaiting = resolve;\n });\n }\n } finally {\n // Cleanup is handled by the wrapper\n }\n }\n\n // Create the underlying generator\n const generator = generateMessages();\n\n // Wrap it with cleanup in finally\n async function* wrappedGenerator(): AsyncGenerator<DroidMessage, void, undefined> {\n try {\n yield* generator;\n } finally {\n // Always close transport on exit (even on early break)\n if (client) {\n try {\n await client.close();\n } catch {\n // Best-effort cleanup\n }\n client = null;\n } else if (transport) {\n try {\n await transport.close();\n } catch {\n // Best-effort cleanup\n }\n }\n transport = null;\n }\n }\n\n const wrapped = wrappedGenerator();\n\n // Create the DroidQuery interface by adding control methods to the generator.\n // Use Object.defineProperties so that `sessionId` is a live getter\n // (Object.assign would snapshot the value at assignment time).\n const droidQuery = wrapped as DroidQuery;\n\n Object.defineProperties(droidQuery, {\n interrupt: {\n value: async function interrupt(): Promise<void> {\n if (client && !aborted) {\n await client.interruptSession();\n }\n },\n writable: false,\n enumerable: true,\n },\n abort: {\n value: function abort(): void {\n aborted = true;\n signalDone();\n if (client) {\n // Fire-and-forget close\n void client.close().catch(() => {});\n client = null;\n } else if (transport) {\n void transport.close().catch(() => {});\n }\n transport = null;\n },\n writable: false,\n enumerable: true,\n },\n sessionId: {\n get(): string | null {\n return sessionId;\n },\n enumerable: true,\n },\n });\n\n return droidQuery;\n}\n","/**\n * Multi-turn session API for the Factory Droid SDK.\n *\n * Provides `createSession()` and `resumeSession()` factory functions that\n * return a {@link DroidSession} for multi-turn conversations with the droid\n * process. Each session manages its own transport and client lifecycle.\n *\n * @example\n * ```ts\n * import { createSession } from \"@factory/droid-sdk\";\n *\n * const session = await createSession({ cwd: \"/my/project\" });\n *\n * // Streaming turn\n * for await (const msg of session.stream(\"Fix the bug in main.ts\")) {\n * if (msg.type === \"assistant_text_delta\") {\n * process.stdout.write(msg.text);\n * }\n * }\n *\n * // Non-streaming turn\n * const result = await session.send(\"Now write tests for it\");\n * console.log(result.text);\n *\n * await session.close();\n * ```\n */\n\nimport { DroidClient } from \"./client.js\";\nimport type {\n ClientAskUserHandler,\n ClientPermissionHandler,\n} from \"./client.js\";\nimport { ConnectionError } from \"./errors.js\";\nimport {\n convertNotificationToStreamMessage,\n StreamStateTracker,\n} from \"./stream.js\";\nimport type { DroidMessage, TokenUsageUpdate } from \"./stream.js\";\nimport { ProcessTransport } from \"./transport.js\";\nimport type { DroidClientTransport, ProcessTransportOptions } from \"./types.js\";\nimport type {\n AddMcpServerRequestParams,\n AddMcpServerResult,\n AuthenticateMcpServerRequestParams,\n AuthenticateMcpServerResult,\n InitializeSessionRequestParams,\n InitializeSessionResult,\n ListMcpServersResult,\n ListMcpToolsResult,\n ListSkillsResult,\n LoadSessionRequestParams,\n LoadSessionResult,\n RemoveMcpServerRequestParams,\n RemoveMcpServerResult,\n ToggleMcpServerRequestParams,\n ToggleMcpServerResult,\n UpdateSessionSettingsRequestParams,\n UpdateSessionSettingsResult,\n} from \"./schemas/client.js\";\nimport type {\n AutonomyLevel,\n DroidInteractionMode,\n ReasoningEffort,\n} from \"./schemas/enums.js\";\nimport type { NotificationCallback, NotificationFilter } from \"./protocol.js\";\n\n// ---------------------------------------------------------------------------\n// DroidResult\n// ---------------------------------------------------------------------------\n\n/**\n * Aggregated result from a non-streaming `session.send()` call.\n *\n * Contains the concatenated assistant text, all messages received during\n * the turn, and the final token usage.\n */\nexport interface DroidResult {\n /** Concatenated text from all `assistant_text_delta` messages. */\n text: string;\n\n /** All DroidMessage objects received during the turn. */\n messages: DroidMessage[];\n\n /** Final token usage from the turn, or null if no token usage was reported. */\n tokenUsage: TokenUsageUpdate | null;\n}\n\n// ---------------------------------------------------------------------------\n// SessionOptions\n// ---------------------------------------------------------------------------\n\n/**\n * Options for `createSession()`.\n */\nexport interface CreateSessionOptions {\n /** Working directory for the session. Defaults to `\".\"`. */\n cwd?: string;\n\n /** Machine identifier. Defaults to `\"default\"`. */\n machineId?: string;\n\n /** LLM model identifier. */\n modelId?: string;\n\n /** Autonomy level for the session. */\n autonomyLevel?: AutonomyLevel;\n\n /** Interaction mode for the session. */\n interactionMode?: DroidInteractionMode;\n\n /** Reasoning effort level. */\n reasoningEffort?: ReasoningEffort;\n\n /** MCP server configurations for the session. */\n mcpServers?: Array<Record<string, unknown>>;\n\n /** Additional tool IDs to enable. */\n enabledToolIds?: string[];\n\n /** Path to the `droid` executable. Defaults to `\"droid\"`. */\n execPath?: string;\n\n /** Additional arguments for the droid executable. */\n execArgs?: string[];\n\n /** Additional environment variables for the subprocess. */\n env?: Record<string, string>;\n\n /** Permission handler for tool confirmations. */\n permissionHandler?: ClientPermissionHandler;\n\n /** Ask-user handler for interactive questions. */\n askUserHandler?: ClientAskUserHandler;\n\n /**\n * An already-connected transport to use instead of spawning a process.\n * When provided, `execPath`, `execArgs`, `env`, and `cwd` (for transport) are ignored.\n */\n transport?: DroidClientTransport;\n}\n\n/**\n * Options for `resumeSession()`.\n */\nexport interface ResumeSessionOptions {\n /** Path to the `droid` executable. Defaults to `\"droid\"`. */\n execPath?: string;\n\n /** Additional arguments for the droid executable. */\n execArgs?: string[];\n\n /** Working directory for the subprocess. */\n cwd?: string;\n\n /** Additional environment variables for the subprocess. */\n env?: Record<string, string>;\n\n /** MCP server configurations. */\n mcpServers?: Array<Record<string, unknown>>;\n\n /** Permission handler for tool confirmations. */\n permissionHandler?: ClientPermissionHandler;\n\n /** Ask-user handler for interactive questions. */\n askUserHandler?: ClientAskUserHandler;\n\n /**\n * An already-connected transport to use instead of spawning a process.\n */\n transport?: DroidClientTransport;\n}\n\n/**\n * Options for `session.stream()` and `session.send()`.\n */\nexport interface MessageOptions {\n /** Optional images to include with the message. */\n images?: Array<Record<string, unknown>>;\n\n /** Optional files to include with the message. */\n files?: Array<Record<string, unknown>>;\n}\n\n// ---------------------------------------------------------------------------\n// DroidSession\n// ---------------------------------------------------------------------------\n\n/**\n * A multi-turn session connected to a droid process.\n *\n * Provides methods for sending messages (streaming and non-streaming),\n * managing MCP servers, updating settings, and controlling the session\n * lifecycle.\n *\n * Create instances via {@link createSession} or {@link resumeSession}.\n */\nexport class DroidSession {\n private _client: DroidClient;\n private _sessionId: string;\n private _initResult: InitializeSessionResult | LoadSessionResult;\n private _closed = false;\n\n /** @internal */\n constructor(\n client: DroidClient,\n sessionId: string,\n initResult: InitializeSessionResult | LoadSessionResult,\n ) {\n this._client = client;\n this._sessionId = sessionId;\n this._initResult = initResult;\n }\n\n // ------------------------------------------------------------------\n // Properties\n // ------------------------------------------------------------------\n\n /** The session ID. */\n get sessionId(): string {\n return this._sessionId;\n }\n\n /** The result from session initialization or loading. */\n get initResult(): InitializeSessionResult | LoadSessionResult {\n return this._initResult;\n }\n\n // ------------------------------------------------------------------\n // Messaging\n // ------------------------------------------------------------------\n\n /**\n * Send a message and return a streaming async generator of DroidMessage events.\n *\n * The generator yields messages until a TurnComplete event is received,\n * signaling the end of the agent's turn.\n *\n * @param text - The user message text.\n * @param options - Optional images/files to include.\n * @returns An async generator yielding DroidMessage events.\n */\n async *stream(\n text: string,\n options?: MessageOptions,\n ): AsyncGenerator<DroidMessage, void, undefined> {\n this._ensureNotClosed();\n\n // Message queue for notification → stream bridging\n const messageQueue: DroidMessage[] = [];\n let resolveWaiting: (() => void) | null = null;\n let streamDone = false;\n\n function enqueueMessage(msg: DroidMessage): void {\n messageQueue.push(msg);\n if (resolveWaiting) {\n const resolve = resolveWaiting;\n resolveWaiting = null;\n resolve();\n }\n }\n\n function signalDone(): void {\n streamDone = true;\n if (resolveWaiting) {\n const resolve = resolveWaiting;\n resolveWaiting = null;\n resolve();\n }\n }\n\n // Fresh state tracker for this turn\n const stateTracker = new StreamStateTracker();\n\n // Subscribe to notifications for this turn\n const unsubscribe = this._client.onNotification((notification) => {\n const params = notification[\"params\"] as Record<string, unknown> | undefined;\n const innerNotification = params?.[\"notification\"] as Record<string, unknown> | undefined;\n\n if (!innerNotification) {\n return;\n }\n\n const converted = convertNotificationToStreamMessage(\n innerNotification as { type: string; [key: string]: unknown },\n );\n\n if (converted === null) {\n return;\n }\n\n const messages = Array.isArray(converted) ? converted : [converted];\n\n for (const msg of messages) {\n enqueueMessage(msg);\n\n const additional = stateTracker.processMessage(msg);\n for (const extra of additional) {\n enqueueMessage(extra);\n if (extra.type === \"turn_complete\") {\n signalDone();\n }\n }\n }\n });\n\n try {\n // Send the user message\n await this._client.addUserMessage({\n text,\n images: options?.images as never,\n files: options?.files as never,\n });\n\n // Yield messages until TurnComplete\n while (true) {\n while (messageQueue.length > 0) {\n const msg = messageQueue.shift()!;\n yield msg;\n\n if (msg.type === \"turn_complete\") {\n return;\n }\n }\n\n if (streamDone && messageQueue.length === 0) {\n return;\n }\n\n await new Promise<void>((resolve) => {\n resolveWaiting = resolve;\n });\n }\n } finally {\n unsubscribe();\n }\n }\n\n /**\n * Send a message and collect the complete response (non-streaming).\n *\n * Internally consumes all stream messages and returns an aggregated\n * {@link DroidResult} with the concatenated text, all messages, and\n * final token usage.\n *\n * @param text - The user message text.\n * @param options - Optional images/files to include.\n * @returns Aggregated result with text, messages, and token usage.\n */\n async send(\n text: string,\n options?: MessageOptions,\n ): Promise<DroidResult> {\n this._ensureNotClosed();\n\n const messages: DroidMessage[] = [];\n let fullText = \"\";\n let lastTokenUsage: TokenUsageUpdate | null = null;\n\n for await (const msg of this.stream(text, options)) {\n messages.push(msg);\n\n if (msg.type === \"assistant_text_delta\") {\n fullText += msg.text;\n }\n\n if (msg.type === \"token_usage_update\") {\n lastTokenUsage = msg;\n }\n\n if (msg.type === \"turn_complete\" && msg.tokenUsage) {\n lastTokenUsage = msg.tokenUsage;\n }\n }\n\n return {\n text: fullText,\n messages,\n tokenUsage: lastTokenUsage,\n };\n }\n\n // ------------------------------------------------------------------\n // Session control\n // ------------------------------------------------------------------\n\n /**\n * Interrupt the current agent turn.\n *\n * Sends an interrupt request. The agent will stop after completing\n * its current operation.\n */\n async interrupt(): Promise<void> {\n this._ensureNotClosed();\n await this._client.interruptSession();\n }\n\n /**\n * Close the session and release all resources.\n *\n * Closes the underlying transport and rejects any pending requests.\n * After close, the session cannot be used.\n */\n async close(): Promise<void> {\n if (this._closed) {\n return;\n }\n this._closed = true;\n await this._client.close();\n }\n\n // ------------------------------------------------------------------\n // Settings\n // ------------------------------------------------------------------\n\n /**\n * Update session settings (model, reasoning effort, autonomy, etc.).\n *\n * @param params - Partial settings to update.\n */\n async updateSettings(\n params: Partial<UpdateSessionSettingsRequestParams>,\n ): Promise<UpdateSessionSettingsResult> {\n this._ensureNotClosed();\n return this._client.updateSessionSettings(params);\n }\n\n // ------------------------------------------------------------------\n // MCP methods\n // ------------------------------------------------------------------\n\n /**\n * Add an MCP server to the session.\n */\n async addMcpServer(\n params: AddMcpServerRequestParams,\n ): Promise<AddMcpServerResult> {\n this._ensureNotClosed();\n return this._client.addMcpServer(params);\n }\n\n /**\n * Remove an MCP server from the session.\n */\n async removeMcpServer(\n params: RemoveMcpServerRequestParams,\n ): Promise<RemoveMcpServerResult> {\n this._ensureNotClosed();\n return this._client.removeMcpServer(params);\n }\n\n /**\n * Toggle an MCP server on or off.\n */\n async toggleMcpServer(\n params: ToggleMcpServerRequestParams,\n ): Promise<ToggleMcpServerResult> {\n this._ensureNotClosed();\n return this._client.toggleMcpServer(params);\n }\n\n /**\n * List MCP servers and their status.\n */\n async listMcpServers(): Promise<ListMcpServersResult> {\n this._ensureNotClosed();\n return this._client.listMcpServers();\n }\n\n /**\n * List available MCP tools.\n */\n async listMcpTools(): Promise<ListMcpToolsResult> {\n this._ensureNotClosed();\n return this._client.listMcpTools();\n }\n\n /**\n * Authenticate an MCP server (OAuth flow).\n */\n async authenticateMcpServer(\n params: AuthenticateMcpServerRequestParams,\n ): Promise<AuthenticateMcpServerResult> {\n this._ensureNotClosed();\n return this._client.authenticateMcpServer(params);\n }\n\n // ------------------------------------------------------------------\n // Skills\n // ------------------------------------------------------------------\n\n /**\n * List available skills.\n */\n async listSkills(): Promise<ListSkillsResult> {\n this._ensureNotClosed();\n return this._client.listSkills();\n }\n\n // ------------------------------------------------------------------\n // Notification subscription\n // ------------------------------------------------------------------\n\n /**\n * Register a callback for incoming notification messages.\n *\n * @param callback - Invoked with the notification object.\n * @param filter - Optional filter to only receive specific notification types.\n * @returns An unsubscribe function.\n */\n onNotification(\n callback: NotificationCallback,\n filter?: NotificationFilter,\n ): () => void {\n return this._client.onNotification(callback, filter);\n }\n\n // ------------------------------------------------------------------\n // Internal\n // ------------------------------------------------------------------\n\n private _ensureNotClosed(): void {\n if (this._closed) {\n throw new ConnectionError(\n \"Session has been closed. Create a new session to continue.\",\n );\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Factory functions\n// ---------------------------------------------------------------------------\n\n/**\n * Create a new droid session.\n *\n * Spawns a transport, creates a client, initializes a new session, and\n * returns a {@link DroidSession} ready for multi-turn interaction.\n *\n * @param options - Session configuration.\n * @returns A connected DroidSession.\n *\n * @example\n * ```ts\n * const session = await createSession({ cwd: \"/my/project\" });\n * const result = await session.send(\"List all TypeScript files\");\n * console.log(result.text);\n * await session.close();\n * ```\n */\nexport async function createSession(\n options: CreateSessionOptions = {},\n): Promise<DroidSession> {\n // 1. Create transport\n let transport: DroidClientTransport;\n if (options.transport) {\n transport = options.transport;\n } else {\n const transportOptions: ProcessTransportOptions = {\n execPath: options.execPath,\n execArgs: options.execArgs,\n cwd: options.cwd,\n env: options.env,\n };\n const processTransport = new ProcessTransport(transportOptions);\n await processTransport.connect();\n transport = processTransport;\n }\n\n // 2. Create client\n const client = new DroidClient({ transport });\n\n // 3. Set up handlers\n if (options.permissionHandler) {\n client.setPermissionHandler(options.permissionHandler);\n }\n if (options.askUserHandler) {\n client.setAskUserHandler(options.askUserHandler);\n }\n\n // 4. Initialize session\n const initParams: Record<string, unknown> = {\n machineId: options.machineId ?? \"default\",\n cwd: options.cwd ?? \".\",\n };\n\n if (options.modelId !== undefined) {\n initParams.modelId = options.modelId;\n }\n if (options.autonomyLevel !== undefined) {\n initParams.autonomyLevel = options.autonomyLevel;\n }\n if (options.interactionMode !== undefined) {\n initParams.interactionMode = options.interactionMode;\n }\n if (options.reasoningEffort !== undefined) {\n initParams.reasoningEffort = options.reasoningEffort;\n }\n if (options.mcpServers !== undefined) {\n initParams.mcpServers = options.mcpServers;\n }\n if (options.enabledToolIds !== undefined) {\n initParams.enabledToolIds = options.enabledToolIds;\n }\n\n try {\n const initResult = await client.initializeSession(\n initParams as unknown as InitializeSessionRequestParams,\n );\n\n return new DroidSession(client, initResult.sessionId, initResult);\n } catch (error) {\n // Clean up on init failure\n try {\n await client.close();\n } catch {\n // Best-effort cleanup\n }\n throw error;\n }\n}\n\n/**\n * Resume an existing droid session.\n *\n * Spawns a transport, creates a client, loads the existing session by ID,\n * and returns a {@link DroidSession} ready for multi-turn interaction.\n *\n * @param sessionId - The ID of the session to resume.\n * @param options - Optional configuration for the transport and handlers.\n * @returns A connected DroidSession.\n * @throws {SessionNotFoundError} If the session ID does not exist.\n *\n * @example\n * ```ts\n * const session = await resumeSession(\"sess-abc123\");\n * const result = await session.send(\"Continue where we left off\");\n * console.log(result.text);\n * await session.close();\n * ```\n */\nexport async function resumeSession(\n sessionId: string,\n options: ResumeSessionOptions = {},\n): Promise<DroidSession> {\n // 1. Create transport\n let transport: DroidClientTransport;\n if (options.transport) {\n transport = options.transport;\n } else {\n const transportOptions: ProcessTransportOptions = {\n execPath: options.execPath,\n execArgs: options.execArgs,\n cwd: options.cwd,\n env: options.env,\n };\n const processTransport = new ProcessTransport(transportOptions);\n await processTransport.connect();\n transport = processTransport;\n }\n\n // 2. Create client\n const client = new DroidClient({ transport });\n\n // 3. Set up handlers\n if (options.permissionHandler) {\n client.setPermissionHandler(options.permissionHandler);\n }\n if (options.askUserHandler) {\n client.setAskUserHandler(options.askUserHandler);\n }\n\n // 4. Load session\n const loadParams: LoadSessionRequestParams = {\n sessionId,\n mcpServers: options.mcpServers as never,\n };\n\n try {\n const loadResult = await client.loadSession(loadParams);\n return new DroidSession(client, sessionId, loadResult);\n } catch (error) {\n // Clean up on load failure\n try {\n await client.close();\n } catch {\n // Best-effort cleanup\n }\n throw error;\n }\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;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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,aAAa,QAAQ;AAAA,EAClC;AACA,MAAI,QAAQ,mBAAmB,QAAW;AACxC,eAAW,iBAAiB,QAAQ;AAAA,EACtC;AAEA,MAAI;AACF,UAAM,aAAa,MAAM,OAAO;AAAA,MAC9B;AAAA,IACF;AAEA,WAAO,IAAI,aAAa,QAAQ,WAAW,WAAW,UAAU;AAAA,EAClE,SAAS,OAAO;AAEd,QAAI;AACF,YAAM,OAAO,MAAM;AAAA,IACrB,QAAQ;AAAA,IAER;AACA,UAAM;AAAA,EACR;AACF;AAqBA,eAAsB,cACpB,WACA,UAAgC,CAAC,GACV;AAEvB,MAAI;AACJ,MAAI,QAAQ,WAAW;AACrB,gBAAY,QAAQ;AAAA,EACtB,OAAO;AACL,UAAM,mBAA4C;AAAA,MAChD,UAAU,QAAQ;AAAA,MAClB,UAAU,QAAQ;AAAA,MAClB,KAAK,QAAQ;AAAA,MACb,KAAK,QAAQ;AAAA,IACf;AACA,UAAM,mBAAmB,IAAI,iBAAiB,gBAAgB;AAC9D,UAAM,iBAAiB,QAAQ;AAC/B,gBAAY;AAAA,EACd;AAGA,QAAM,SAAS,IAAI,YAAY,EAAE,UAAU,CAAC;AAG5C,MAAI,QAAQ,mBAAmB;AAC7B,WAAO,qBAAqB,QAAQ,iBAAiB;AAAA,EACvD;AACA,MAAI,QAAQ,gBAAgB;AAC1B,WAAO,kBAAkB,QAAQ,cAAc;AAAA,EACjD;AAGA,QAAM,aAAuC;AAAA,IAC3C;AAAA,IACA,YAAY,QAAQ;AAAA,EACtB;AAEA,MAAI;AACF,UAAM,aAAa,MAAM,OAAO,YAAY,UAAU;AACtD,WAAO,IAAI,aAAa,QAAQ,WAAW,UAAU;AAAA,EACvD,SAAS,OAAO;AAEd,QAAI;AACF,YAAM,OAAO,MAAM;AAAA,IACrB,QAAQ;AAAA,IAER;AACA,UAAM;AAAA,EACR;AACF;","names":["DroidServerMethod","DroidClientMethod","SessionNotificationType","ToolConfirmationOutcome","ToolConfirmationType","DroidWorkingState","DroidErrorType","McpServerStatus","McpServerType","McpStatus","McpAuthOutcome","DecompSessionType","MissionState","FeatureStatus","FeatureSuccessState","IssueSeverity","DismissalType","ProgressLogEntryType","DroidInteractionMode","AutonomyLevel","AutonomyMode","ReasoningEffort","ModelProvider","JsonRpcErrorCode","JsonRpcMessageType","SettingsLevel","SkillLocation","import_zod","import_zod","import_zod","import_zod","import_zod","uuidv4"]}