@episoda/mcp 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +8677 -0
- package/dist/cli.js.map +1 -0
- package/dist/dev-server.js +7159 -0
- package/dist/dev-server.js.map +1 -0
- package/dist/git-server.js +7181 -0
- package/dist/git-server.js.map +1 -0
- package/dist/workflow-server.js +7469 -0
- package/dist/workflow-server.js.map +1 -0
- package/package.json +36 -0
package/dist/cli.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../core/src/command-protocol.ts","../../core/src/git-validator.ts","../../core/src/git-parser.ts","../../core/src/git-executor.ts","../../../node_modules/.pnpm/ws@8.18.3/node_modules/ws/lib/constants.js","../../../node_modules/.pnpm/ws@8.18.3/node_modules/ws/lib/buffer-util.js","../../../node_modules/.pnpm/ws@8.18.3/node_modules/ws/lib/limiter.js","../../../node_modules/.pnpm/ws@8.18.3/node_modules/ws/lib/permessage-deflate.js","../../../node_modules/.pnpm/ws@8.18.3/node_modules/ws/lib/validation.js","../../../node_modules/.pnpm/ws@8.18.3/node_modules/ws/lib/receiver.js","../../../node_modules/.pnpm/ws@8.18.3/node_modules/ws/lib/sender.js","../../../node_modules/.pnpm/ws@8.18.3/node_modules/ws/lib/event-target.js","../../../node_modules/.pnpm/ws@8.18.3/node_modules/ws/lib/extension.js","../../../node_modules/.pnpm/ws@8.18.3/node_modules/ws/lib/websocket.js","../../../node_modules/.pnpm/ws@8.18.3/node_modules/ws/lib/stream.js","../../../node_modules/.pnpm/ws@8.18.3/node_modules/ws/lib/subprotocol.js","../../../node_modules/.pnpm/ws@8.18.3/node_modules/ws/lib/websocket-server.js","../../../node_modules/.pnpm/ws@8.18.3/node_modules/ws/index.js","../../core/src/version.ts","../../core/src/websocket-client.ts","../../core/src/auth.ts","../../core/src/errors.ts","../../core/src/index.ts","../src/runtime-config.ts","../src/workflow-server.ts","../src/git-server.ts","../src/dev-server.ts","../src/cli.ts"],"sourcesContent":["/**\n * Command Protocol Types for Episoda Local Development\n *\n * IMPORTANT: These types are LOCKED for Phase 2 concurrent development.\n * DO NOT modify after EP589-1 is complete without coordinating with all agents.\n *\n * These types are interface-agnostic and used by both:\n * - episoda CLI (current)\n * - @episoda/mcp-local-dev (future)\n */\n\n/**\n * EP912: Agent commands for local AI agent execution (Claude Code, Codex, etc.)\n * Server sends these to daemon to manage local agent sessions\n * EP1126: Added full OAuth credential fields for proper Claude Code authentication\n * EP1133: Added multi-provider support (Claude + Codex)\n * EP1152: Added preferredModel for per-user model selection\n * EP1146: Added GitHub token for MCP server integration\n * EP1173: Added autonomousMode for permission-free execution\n * EP1233: Added mcpMode for conditional MCP server registration\n */\nexport type AgentProvider = 'claude' | 'codex'\n\n/**\n * EP1233: MCP server registration mode\n * - 'exec': All MCP servers (workflow + git + dev) - for doing/review modules\n * - 'planning': workflow + github only - for backlog/ready/done modules\n * - Backward compatible: 'full' -> exec, 'standard' -> planning\n */\nexport type AgentMcpMode = 'exec' | 'planning' | 'full' | 'standard'\n\nexport type AgentCommand =\n | {\n action: 'start'\n sessionId: string // Session ID from agent_sessions\n moduleId: string // Module UUID\n moduleUid: string // Module UID (e.g., EP912) for logging\n projectId: string // Project ID for routing consistency\n provider?: AgentProvider // EP1133: Which AI provider to use (defaults to 'claude')\n autonomousMode?: boolean // EP1173: Skip permission prompts (Claude: --dangerously-skip-permissions)\n canWrite?: boolean // EP1205: Whether the session can make file changes (false for non-holders)\n readOnlyReason?: string // EP1205: Reason for read-only mode (shown to agent)\n sessionContext?: 'project_root' | 'worktree' // EP1205: Working directory selection - 'worktree' = module worktree, 'project_root' = project root\n mcpMode?: AgentMcpMode // EP1233: MCP server mode - exec for doing/review, planning otherwise\n // EP1227: Slugs for cloud project path resolution (daemon resolves ~/episoda/{workspace}/{project}/)\n workspaceSlug?: string\n projectSlug?: string\n message: string // Initial user message to send to agent\n credentials: { // Credentials fetched server-side for security\n oauthToken: string // OAuth access_token from provider\n refreshToken?: string // Refresh token for token renewal\n expiresAt?: number // Token expiry timestamp (ms since epoch)\n scopes?: string[] // OAuth scopes granted\n // Codex-specific fields (EP1133)\n idToken?: string // Codex id_token from OpenAI OAuth\n accountId?: string // Codex account_id from OpenAI\n // EP1152: User's preferred model for this provider\n preferredModel?: string // e.g., 'claude-opus-4-5-20251101' or 'o3'\n // EP1146: GitHub MCP integration\n githubToken?: string // GitHub App installation token for MCP server\n githubTokenExpiresAt?: number // Token expiry timestamp (ms since epoch)\n }\n systemPrompt?: string // Optional system prompt to inject\n }\n | {\n action: 'message'\n sessionId: string\n moduleId: string\n moduleUid: string // Module UID (e.g., EP912) for logging consistency\n projectId: string // Project ID for routing (defensive - in case session lost)\n provider?: AgentProvider // EP1133: Which AI provider (for logging/routing)\n canWrite?: boolean // EP1205: Whether the session can make file changes\n readOnlyReason?: string // EP1205: Reason for read-only mode\n sessionContext?: 'project_root' | 'worktree' // EP1205: Working directory selection - 'worktree' = module worktree, 'project_root' = project root\n // EP1227: Slugs for cloud project path resolution (daemon resolves ~/episoda/{workspace}/{project}/)\n workspaceSlug?: string\n projectSlug?: string\n message: string // User message to send to agent\n claudeSessionId?: string // For --resume on subsequent messages (backward compat)\n agentSessionId?: string // EP1133: Generic session ID for resume\n // EP1251: Credentials for token refresh on resume (GitHub tokens expire after ~1 hour)\n credentials?: {\n githubToken?: string // Fresh GitHub App installation token\n githubTokenExpiresAt?: number\n }\n }\n | {\n action: 'abort'\n sessionId: string // Session to abort\n }\n | {\n action: 'stop'\n sessionId: string // Session to stop gracefully\n }\n\n/**\n * EP912: Result of agent operations (streaming)\n *\n * Unlike other results, agent results are sent multiple times during execution:\n * - 'started' once when session begins\n * - 'chunk' many times as Claude outputs\n * - 'complete' or 'error' once when done\n * - 'aborted' if user cancels\n */\nexport type AgentResult = {\n success: boolean\n error?: string\n status: 'started' | 'chunk' | 'tool_use' | 'tool_result' | 'complete' | 'error' | 'aborted'\n sessionId: string\n // chunk data\n chunk?: string\n // EP1236: tool_use data - emitted when agent invokes a tool\n toolUse?: {\n id: string // Claude's tool_use ID (e.g., 'toolu_01ABC')\n name: string // Tool name (e.g., 'Read', 'Write', 'Bash')\n input: Record<string, unknown> // Tool input parameters\n }\n // EP1311: tool_result data - emitted when agent returns tool output\n toolResult?: {\n id: string // Claude's tool_use ID (matches toolUse.id when available)\n name?: string // Optional tool name if available\n output: unknown // Tool output payload\n }\n // complete data\n claudeSessionId?: string // For --resume on subsequent messages\n}\n\n/**\n * EP672: Tunnel commands for local dev preview\n * Server sends these to daemon to start/stop Cloudflare tunnels\n */\nexport type TunnelCommand =\n | {\n action: 'start'\n moduleUid: string // Module UID to associate with tunnel\n projectUid: string // Project UID for preview URL construction\n port?: number // Local port to tunnel (default: 3000)\n }\n | {\n action: 'stop'\n moduleUid: string // Module UID of tunnel to stop\n }\n\n/**\n * EP672: Result of tunnel operations\n */\nexport type TunnelCommandResult = {\n success: boolean\n error?: string\n // start result\n url?: string // The Cloudflare tunnel URL (internal)\n previewUrl?: string // The unified preview URL (https://{module}-{project}.episoda.site)\n}\n\n/**\n * EP1035: Worktree cleanup command for proper config file updates\n * Server sends this to daemon when a module transitions to done state.\n * The daemon calls WorktreeManager.removeWorktree() which properly updates\n * the local .episoda/config.json file.\n */\nexport type WorktreeCleanupCommand = {\n action: 'cleanup'\n moduleUid: string // Module UID to clean up (e.g., EP100)\n worktreePath: string // Absolute path to the worktree\n force?: boolean // Force removal even with uncommitted changes\n}\n\n/**\n * EP1035: Result of worktree cleanup operations\n */\nexport type WorktreeCleanupResult = {\n success: boolean\n error?: string\n worktreePath?: string // Path that was cleaned up\n}\n\n/**\n * EP808: Remote file/exec commands for local machine access\n * These enable Claude Code on one machine to work with files on another\n */\nexport type RemoteCommand =\n | {\n action: 'file:read'\n path: string\n encoding?: 'utf8' | 'base64'\n maxSize?: number // bytes, default 20MB\n }\n | {\n action: 'file:write'\n path: string\n content: string\n encoding?: 'utf8' | 'base64'\n createDirs?: boolean // create parent directories if needed\n }\n | {\n action: 'file:edit' // EP851: Precise string replacement\n path: string\n oldString: string\n newString: string\n replaceAll?: boolean // replace all occurrences, default false\n }\n | {\n action: 'file:delete' // EP851: Delete file or directory\n path: string\n recursive?: boolean // required for directories\n }\n | {\n action: 'file:mkdir' // EP851: Create directory\n path: string\n mode?: string // Unix permissions, default '0755'\n }\n | {\n action: 'file:list'\n path: string\n recursive?: boolean\n includeHidden?: boolean\n }\n | {\n action: 'file:search'\n pattern: string // glob pattern (e.g., \"*.ts\", \"**/*.json\")\n basePath: string\n maxResults?: number // default 100, max 1000\n }\n | {\n action: 'file:grep'\n pattern: string // regex pattern\n path: string // file or directory to search\n filePattern?: string // filter files (e.g., \"*.ts\")\n caseSensitive?: boolean\n maxResults?: number // default 100, max 1000\n }\n | {\n action: 'exec'\n command: string\n cwd?: string // working directory, defaults to project root\n timeout?: number // milliseconds, default 30000, max 300000\n env?: Record<string, string> // additional environment variables\n }\n // EP1143/K1273: Worktree management for per-user-per-workspace model\n | {\n action: 'worktree:create'\n workspaceSlug: string\n projectSlug: string\n projectId: string\n moduleId: string\n moduleUid: string\n branchName: string\n createBranch: boolean\n repoUrl: string\n tunnelToken?: string\n envVars?: Record<string, string>\n setupScript?: string\n }\n | {\n action: 'worktree:release'\n workspaceSlug: string\n projectSlug: string\n moduleUid: string\n force?: boolean\n cleanupScript?: string\n }\n | {\n action: 'worktree:list'\n workspaceSlug: string\n projectSlug: string\n }\n // EP1144: Project ejection for Tier 1 cleanup\n // EP1199: Renamed from eject_project to project:eject for naming consistency\n | {\n action: 'project:eject'\n workspaceSlug: string\n projectSlug: string\n projectId?: string // EP1144: UUID for artifact persistence\n }\n // EP1199: Project setup for cloud containers (creates project dir, config, artifacts)\n | {\n action: 'project:setup'\n workspaceSlug: string\n projectSlug: string\n projectId: string\n }\n\n/**\n * EP808: Result of remote file/exec operations\n */\nexport type RemoteCommandResult = {\n success: boolean\n error?: string\n // file:read result\n content?: string\n encoding?: 'utf8' | 'base64'\n size?: number\n // file:write result\n bytesWritten?: number\n // file:edit result (EP851)\n replacements?: number\n newSize?: number\n // file:delete result (EP851)\n deleted?: boolean\n pathType?: 'file' | 'directory'\n // file:mkdir result (EP851)\n created?: boolean\n // file:list result\n entries?: Array<{\n name: string\n type: 'file' | 'directory'\n size: number\n }>\n // file:search result\n files?: string[]\n // file:grep result\n matches?: Array<{\n file: string\n line: number\n content: string\n }>\n // exec result\n stdout?: string\n stderr?: string\n exitCode?: number\n timedOut?: boolean\n // EP1199: project:setup result\n projectPath?: string\n artifactsPath?: string\n}\n\n/**\n * EP944: Base options for git commands\n * worktreePath allows routing commands to a specific worktree in worktree mode\n */\nexport type GitCommandOptions = {\n worktreePath?: string // Absolute path to worktree for worktree-mode routing\n}\n\n/**\n * Git command types supported by GitExecutor\n * EP944: All commands can include optional worktreePath for worktree-mode routing\n */\nexport type GitCommand = (\n | { action: 'checkout'; branch: string; create?: boolean }\n | { action: 'create_branch'; branch: string; from?: string }\n | { action: 'commit'; message: string; files?: string[] }\n | { action: 'push'; branch: string; setUpstream?: boolean; force?: boolean }\n | { action: 'status' }\n | { action: 'pull'; branch?: string }\n | { action: 'delete_branch'; branch: string; force?: boolean }\n // EP597: Read operations for production local dev mode\n | { action: 'branch_exists'; branch: string }\n | { action: 'branch_has_commits'; branch: string; baseBranch?: string }\n | { action: 'find_branch_by_prefix'; prefix: string } // EP831: Find branch by prefix\n // EP598: Main branch check for production\n | { action: 'main_branch_check' }\n // EP599: Get commits for branch\n | { action: 'get_commits'; branch: string; limit?: number; baseBranch?: string }\n // EP599: Advanced operations for move-to-module and discard-main-changes\n | { action: 'stash'; operation: 'push' | 'pop' | 'drop' | 'list'; message?: string; includeUntracked?: boolean }\n | { action: 'reset'; mode: 'soft' | 'mixed' | 'hard'; target?: string }\n | { action: 'merge'; branch: string; strategy?: 'ours' | 'theirs'; noEdit?: boolean; abort?: boolean }\n | { action: 'cherry_pick'; sha: string; abort?: boolean }\n | { action: 'clean'; force?: boolean; directories?: boolean }\n | { action: 'add'; files?: string[]; all?: boolean }\n | { action: 'fetch'; remote?: string; branch?: string }\n // EP599-3: Composite operations for complex workflows\n | {\n action: 'move_to_module'\n targetBranch: string\n commitShas?: string[]\n conflictResolution?: 'ours' | 'theirs'\n }\n | {\n action: 'discard_main_changes'\n }\n // EP523: Branch sync operations for keeping branches up-to-date with main\n | {\n action: 'sync_status'\n branch: string\n }\n | {\n action: 'sync_main' // Auto-sync: fetch + pull origin main (for new branch creation)\n }\n | {\n action: 'rebase_branch' // Rebase current branch onto main\n branch: string\n }\n | {\n action: 'rebase_abort'\n }\n | {\n action: 'rebase_continue'\n }\n | {\n action: 'rebase_status' // Check if in rebase state\n }\n // EP944: Worktree operations for local multi-module development\n | {\n action: 'worktree_add'\n path: string // Absolute path for the new worktree\n branch?: string // Branch to checkout in the worktree (optional if detach=true)\n create?: boolean // Create branch if it doesn't exist\n startPoint?: string // EP996: Start point for new branch (e.g., 'origin/main')\n detach?: boolean // Create detached HEAD worktree (git worktree add --detach)\n }\n | {\n action: 'worktree_remove'\n path: string // Absolute path to the worktree to remove\n force?: boolean // Force removal even with uncommitted changes\n }\n | {\n action: 'worktree_list'\n }\n | {\n action: 'worktree_prune'\n }\n // EP1002: Worktree setup command for unified orchestration\n | {\n action: 'worktree_setup'\n path: string // Absolute path to the worktree\n moduleUid: string // Module UID for status updates\n }\n | {\n action: 'clone_bare'\n url: string // Repository URL to clone\n path: string // Absolute path for the bare clone\n }\n // EP944: Project info for worktree mode detection\n | {\n action: 'project_info'\n }\n) & GitCommandOptions // EP944: All commands can include worktreePath for worktree routing\n\n/**\n * Result of executing a git command\n * Returns structured data (not formatted strings) for interface-agnostic use\n */\nexport type ExecutionResult = {\n success: boolean\n output?: string\n error?: ErrorCode\n details?: {\n uncommittedFiles?: string[]\n conflictingFiles?: string[]\n exitCode?: number\n branchName?: string\n // EP597: Branch info for read operations\n branchExists?: boolean\n isLocal?: boolean\n isRemote?: boolean\n hasCommits?: boolean\n // EP598: Main branch check\n currentBranch?: string\n localCommits?: Array<{ sha: string; message: string; author: string }>\n // EP599: Get commits result\n commits?: Array<{\n sha: string\n message: string\n authorName: string\n authorEmail: string\n date: string\n isPushed: boolean\n }>\n // EP599: Advanced operation results\n stashList?: Array<{ index: number; message: string }>\n mergeConflicts?: boolean\n cherryPickConflicts?: boolean\n cleanedFiles?: string[]\n stagedFiles?: string[]\n // EP599-3: Composite operation results\n movedToBranch?: string\n cherryPickedCommits?: string[]\n discardedFiles?: number\n discardedCommits?: number\n hasConflicts?: boolean\n conflictedFiles?: string[]\n // EP523: Branch sync status details\n commitsBehind?: number\n commitsAhead?: number\n isBehind?: boolean\n isAhead?: boolean\n needsSync?: boolean\n // EP523: Rebase status details\n inRebase?: boolean\n rebaseConflicts?: string[]\n // EP944: Worktree operation results\n worktrees?: Array<{\n path: string // Absolute path to worktree\n branch: string // Branch checked out in worktree\n commit: string // Current HEAD commit\n locked?: boolean // Whether worktree is locked\n prunable?: boolean // Whether worktree can be pruned\n }>\n worktreePath?: string // Path of created/removed worktree\n prunedCount?: number // Number of stale worktrees pruned\n // EP1223: Detached HEAD worktree (for planning worktrees)\n detached?: boolean // Whether worktree is detached HEAD\n // EP1002: Worktree setup result properties\n moduleUid?: string // Module UID for setup tracking\n envVarsCount?: number // Number of env vars written\n // EP971: Project info (all projects use worktree architecture)\n projectPath?: string // Root path of the project\n bareRepoPath?: string // Path to .bare directory\n }\n}\n\n/**\n * Standardized error codes for git operations\n * Interfaces can map these to user-friendly messages\n */\nexport type ErrorCode =\n | 'GIT_NOT_INSTALLED'\n | 'NOT_GIT_REPO'\n | 'MERGE_CONFLICT'\n | 'REBASE_CONFLICT' // EP523: Specific error for rebase conflicts\n | 'UNCOMMITTED_CHANGES'\n | 'NETWORK_ERROR'\n | 'AUTH_FAILURE'\n | 'BRANCH_NOT_FOUND'\n | 'BRANCH_ALREADY_EXISTS'\n | 'PUSH_REJECTED'\n | 'COMMAND_TIMEOUT'\n | 'WORKTREE_EXISTS' // EP944: Worktree already exists at path\n | 'WORKTREE_NOT_FOUND' // EP944: Worktree not found at path\n | 'WORKTREE_LOCKED' // EP944: Worktree is locked\n | 'BRANCH_IN_USE' // EP944: Branch already checked out in another worktree\n | 'NOT_IMPLEMENTED' // EP1002: Command not implemented in this context\n | 'SETUP_FAILED' // EP1002: Worktree setup failed\n | 'UNKNOWN_ERROR'\n\n/**\n * EP843: Module state for push-based state sync\n */\nexport type ModuleState = 'backlog' | 'ready' | 'doing' | 'review' | 'done'\n\n/**\n * EP1143: Worktree lifecycle status\n *\n * Aligns with database CHECK constraint (worktrees.status):\n * - pending: Worktree created, awaiting setup\n * - setup: Installing dependencies, running setup scripts\n * - ready: Active and ready for development\n * - error: Setup or operation failed\n * - removing: Being cleaned up\n */\nexport type WorktreeStatus = 'pending' | 'setup' | 'ready' | 'error' | 'removing'\n\n/** Valid worktree status values as array (for runtime validation) */\nexport const WORKTREE_STATUS_VALUES: readonly WorktreeStatus[] = [\n 'pending',\n 'setup',\n 'ready',\n 'error',\n 'removing',\n] as const\n\n/**\n * WebSocket message types for server → CLI communication\n */\nexport type ServerMessage =\n | { type: 'auth_success'; userId: string; projectId: string; workspaceId: string; deviceName?: string; machineUuid?: string; deviceId?: string; flyMachineId?: string } // EP661: deviceName for browser identification, EP726: deviceId (UUID) for unified device identification, EP1091: machineUuid is preferred name (deviceId kept for backward compat), EP735: flyMachineId for sticky session routing\n | { type: 'command'; id: string; command: GitCommand }\n | { type: 'remote_command'; id: string; command: RemoteCommand } // EP808: File/exec commands for remote access\n | { type: 'tunnel_command'; id: string; command: TunnelCommand } // EP672: Tunnel start/stop commands\n | { type: 'agent_command'; id: string; command: AgentCommand } // EP912: Agent commands for local Claude Code execution\n | { type: 'worktree_cleanup_command'; id: string; command: WorktreeCleanupCommand } // EP1035: Worktree cleanup with config update\n | { type: 'ping' }\n | { type: 'error'; code: string; message: string; retryAfter?: number } // EP648: retryAfter in seconds for rate limiting\n | { type: 'shutdown'; message: string; reason?: 'user_requested' | 'server_restart' | 'deployment' }\n // EP843: Push-based state sync - replaces polling for tunnel/commit management\n // EP956: Added checkout_machine_id for multi-machine validation\n | { type: 'module_state_changed'; moduleUid: string; state: ModuleState; previousState: ModuleState; branchName?: string; devMode?: 'local' | 'cloud'; checkoutMachineId?: string | null }\n // EP949: Token refresh for cloud containers - sent during heartbeat when token is expiring\n | { type: 'token_refresh'; accessToken: string; expiresAt: number }\n // EP1095: Machine UUID update - sent after DB lookup completes\n // EP1186: Now includes machineName for user-friendly display in CLI status\n // This provides the local_machine.id (or cloud_container.id) and name to the daemon\n | { type: 'machine_uuid_update'; machineUuid: string; machineName?: string }\n // EP1237: Agent session reconciliation commands from server\n | AgentReconciliationCommands\n\n/**\n * EP1003: Reconciliation report - daemon reports state, server decides actions\n * This replaces autonomous worktree/tunnel creation during reconciliation.\n * Server receives report and sends commands (worktree_add, worktree_setup, tunnel_start, tunnel_stop) as needed.\n */\nexport type ReconciliationReport = {\n projectId: string\n machineId: string\n modules: ReconciliationModuleStatus[]\n /** Tunnels running for modules NOT in expected list (orphans that should be stopped) */\n orphanTunnels?: OrphanTunnelStatus[]\n}\n\n/** EP1003: Orphan tunnel info for cleanup during reconciliation */\nexport type OrphanTunnelStatus = {\n moduleUid: string\n port: number\n}\n\nexport type ReconciliationModuleStatus = {\n moduleUid: string\n moduleState: ModuleState\n // Local state\n worktreeExists: boolean\n worktreePath?: string\n tunnelRunning: boolean\n tunnelPort?: number\n devServerRunning?: boolean\n}\n\n/**\n * EP1237: Agent session reconciliation report\n * Daemon reports active agent sessions to server on connect/reconnect.\n * Server compares with DB state and sends commands to fix mismatches.\n */\nexport type AgentReconciliationReport = {\n projectId: string\n machineId: string\n sessions: AgentSessionStatus[]\n}\n\n/**\n * EP1237: Agent session status reported by daemon\n */\nexport type AgentSessionStatus = {\n sessionId: string\n moduleId: string\n moduleUid?: string\n /** Current local status of the agent session */\n status: 'running' | 'idle' | 'error'\n /** Provider's internal session ID (for Claude --resume) */\n agentSessionId?: string\n /** Last activity timestamp (ISO 8601) */\n lastActivityAt: string\n /** Error message if status is 'error' */\n error?: string\n}\n\n/**\n * EP1237: Commands from server to fix agent session state mismatches\n */\nexport type AgentReconciliationCommands = {\n type: 'agent_reconciliation_commands'\n /** Session IDs that should be aborted (exist locally but not in DB or are orphaned) */\n abort: string[]\n /** Sessions that need to be restarted (exist in DB as 'running' but not locally) */\n restart: Array<{\n sessionId: string\n moduleId: string\n moduleUid: string\n }>\n}\n\n/**\n * WebSocket message types for CLI → server communication\n */\nexport type ClientMessage =\n // EP1119: Added environment field for explicit local/cloud routing (replaces hetzner- prefix hack)\n // - environment: 'local' uses machineId (local_machine.id), 'cloud' uses containerId (cloud_container.id)\n // - containerId is the full UUID, not the truncated hetzner-{8chars} format\n | { type: 'auth'; token: string; version: string; environment?: 'local' | 'cloud'; machineId?: string; containerId?: string; hostname?: string; osPlatform?: string; osArch?: string; daemonPid?: number }\n | { type: 'pong' }\n | { type: 'result'; commandId: string; result: ExecutionResult }\n | { type: 'remote_result'; commandId: string; result: RemoteCommandResult } // EP808: File/exec command results\n | { type: 'tunnel_result'; commandId: string; result: TunnelCommandResult } // EP672: Tunnel command results\n | { type: 'agent_result'; commandId: string; result: AgentResult } // EP912: Agent command results (streaming)\n | { type: 'worktree_cleanup_result'; commandId: string; result: WorktreeCleanupResult } // EP1035: Worktree cleanup result\n | { type: 'status'; connected: boolean; workingDirectory?: string }\n | { type: 'reconciliation_report'; report: ReconciliationReport } // EP1003: Daemon reports state for server-driven reconciliation\n | { type: 'agent_reconciliation_report'; report: AgentReconciliationReport } // EP1237: Daemon reports agent session state\n\n/**\n * CLI connection status\n */\nexport type ConnectionStatus = {\n connected: boolean\n projectId?: string\n connectedAt?: Date\n lastActivity?: Date\n cliVersion?: string\n workingDirectory?: string\n // EP596: Device information\n machineId?: string\n deviceName?: string\n hostname?: string\n osPlatform?: string\n osArch?: string\n // EP602: User info for devices page\n userId?: string\n // EP719: Actual ping/pong timestamp (heartbeat)\n lastPingAt?: Date\n}\n\n/**\n * Configuration stored in .episoda/config.json\n */\nexport type EpisodaConfig = {\n project_id: string\n user_id: string // EP589 Phase 2: Required for WebSocket connection\n workspace_id: string // EP589 Phase 2: Required for WebSocket connection\n // EP956: Slugs for worktree path resolution ~/episoda/{workspace_slug}/{project_slug}/{module}/\n workspace_slug?: string // URL-friendly workspace identifier (e.g., \"acme-corp\")\n project_slug?: string // URL-friendly project identifier (e.g., \"website\")\n access_token: string\n refresh_token?: string // For token refresh\n expires_at?: number // Unix timestamp\n api_url: string\n ws_url?: string // EP1021: Optional WebSocket URL override (bypasses Cloudflare proxy)\n cli_version?: string\n // EP726: Unified device identification\n // EP1091: Renamed device_id → machine_uuid for consistency with platform terminology\n machine_uuid?: string // UUID from local_machine table (preferred, new field)\n device_id?: string // DEPRECATED: Use machine_uuid. Kept for backward compatibility.\n machine_id?: string // CLI-generated ID (hostname-uuid), used for initial device registration\n // EP734: Cached project settings to avoid network fetch on every startup\n project_settings?: {\n local_project_path?: string\n local_server_url?: string\n cached_at: number // Unix timestamp for TTL check\n // EP959-11: Worktree setup configuration\n /** @deprecated EP964: Use worktree_env_vars or worktree_setup_script instead */\n worktree_copy_files?: string[] // DEPRECATED: Files to copy from main worktree\n worktree_setup_script?: string // Commands to run after worktree creation\n worktree_cleanup_script?: string // Commands to run on worktree removal\n worktree_dev_server_script?: string // Command to start dev server\n // EP964: Environment variables to inject into .env during checkout\n worktree_env_vars?: Record<string, string>\n }\n}\n\n/**\n * Command execution options\n */\nexport type ExecutionOptions = {\n timeout?: number // milliseconds\n cwd?: string // working directory\n githubToken?: string // optional GitHub token for auth\n}\n","/**\n * Git Input Validation Utilities\n *\n * Validates git command inputs to prevent injection and ensure safety.\n * Interface-agnostic: Returns boolean/error codes, not formatted messages.\n */\n\nimport { ErrorCode } from './command-protocol'\n\n/**\n * Validate branch name format\n * Git branch naming rules:\n * - Cannot start with - or /\n * - Cannot contain .. or @{ or \\\n * - Cannot end with .lock or /\n * - Cannot contain spaces or control characters\n * - Cannot be just @\n */\nexport function validateBranchName(branchName: string): { valid: boolean; error?: ErrorCode } {\n if (!branchName || branchName.trim().length === 0) {\n return { valid: false, error: 'UNKNOWN_ERROR' }\n }\n\n // Check for invalid characters and patterns\n const invalidPatterns = [\n /^\\-/, // Starts with -\n /^\\//, // Starts with /\n /\\.\\./, // Contains ..\n /@\\{/, // Contains @{\n /\\\\/, // Contains backslash\n /\\.lock$/, // Ends with .lock\n /\\/$/, // Ends with /\n /\\s/, // Contains whitespace\n /[\\x00-\\x1F\\x7F]/, // Contains control characters\n /[\\*\\?\\[\\]~\\^:]/, // Contains special characters\n ]\n\n for (const pattern of invalidPatterns) {\n if (pattern.test(branchName)) {\n return { valid: false, error: 'UNKNOWN_ERROR' }\n }\n }\n\n // Branch name cannot be just @\n if (branchName === '@') {\n return { valid: false, error: 'UNKNOWN_ERROR' }\n }\n\n // Maximum reasonable length (Git allows up to 255, but let's be conservative)\n if (branchName.length > 200) {\n return { valid: false, error: 'UNKNOWN_ERROR' }\n }\n\n return { valid: true }\n}\n\n/**\n * Validate commit message\n * Basic validation to ensure message is not empty\n */\nexport function validateCommitMessage(message: string): { valid: boolean; error?: ErrorCode } {\n if (!message || message.trim().length === 0) {\n return { valid: false, error: 'UNKNOWN_ERROR' }\n }\n\n // Reasonable length check\n if (message.length > 10000) {\n return { valid: false, error: 'UNKNOWN_ERROR' }\n }\n\n return { valid: true }\n}\n\n/**\n * Validate file paths\n * Basic validation to prevent directory traversal\n */\nexport function validateFilePaths(files: string[]): { valid: boolean; error?: ErrorCode } {\n if (!files || files.length === 0) {\n return { valid: true }\n }\n\n for (const file of files) {\n // Check for null bytes (command injection)\n if (file.includes('\\0')) {\n return { valid: false, error: 'UNKNOWN_ERROR' }\n }\n\n // Check for control characters\n if (/[\\x00-\\x1F\\x7F]/.test(file)) {\n return { valid: false, error: 'UNKNOWN_ERROR' }\n }\n\n // Files should not be empty\n if (file.trim().length === 0) {\n return { valid: false, error: 'UNKNOWN_ERROR' }\n }\n }\n\n return { valid: true }\n}\n\n/**\n * Sanitize command arguments to prevent injection\n * Returns sanitized array of arguments\n */\nexport function sanitizeArgs(args: string[]): string[] {\n return args.map(arg => {\n // Remove null bytes\n return arg.replace(/\\0/g, '')\n })\n}\n","/**\n * Git Command Output Parser\n *\n * Parses git command output and error messages into structured data.\n * Interface-agnostic: Returns structured objects, not formatted strings.\n */\n\nimport { ErrorCode } from './command-protocol'\n\n/**\n * Parse git status output to extract uncommitted files\n */\nexport function parseGitStatus(output: string): {\n uncommittedFiles: string[]\n isClean: boolean\n currentBranch?: string\n} {\n const lines = output.split('\\n')\n const uncommittedFiles: string[] = []\n let currentBranch: string | undefined\n\n for (const line of lines) {\n // Porcelain format branch line: ## branch-name or ## HEAD (no branch)\n if (line.startsWith('## ')) {\n const branchInfo = line.substring(3)\n // Extract branch name (handle \"branch...origin/branch\" format)\n const branchMatch = branchInfo.match(/^([^\\s.]+)/)\n if (branchMatch && branchMatch[1]) {\n currentBranch = branchMatch[1] === 'HEAD' ? 'HEAD (detached)' : branchMatch[1]\n }\n continue\n }\n\n // Parse modified/added/deleted files\n // Porcelain format: \"XY filename\" where X is staged, Y is unstaged\n // Format: \" M file.txt\" or \"M file.txt\" or \"?? file.txt\" or \"MM file.txt\"\n if (line.length >= 3) {\n const status = line.substring(0, 2)\n const filePath = line.substring(3).trim()\n\n // Check if there's any status (not all spaces)\n if (status.trim().length > 0 && filePath.length > 0) {\n uncommittedFiles.push(filePath)\n }\n }\n }\n\n const isClean = uncommittedFiles.length === 0\n\n return { uncommittedFiles, isClean, currentBranch }\n}\n\n/**\n * Parse merge conflict output to extract conflicting files\n */\nexport function parseMergeConflicts(output: string): string[] {\n const lines = output.split('\\n')\n const conflictingFiles: string[] = []\n\n for (const line of lines) {\n const trimmed = line.trim()\n\n // Look for conflict markers\n if (trimmed.startsWith('CONFLICT')) {\n // Format: \"CONFLICT (content): Merge conflict in file.txt\"\n const match = trimmed.match(/CONFLICT.*in (.+)$/)\n if (match && match[1]) {\n conflictingFiles.push(match[1])\n }\n }\n\n // Also check for \"both modified\" status\n if (trimmed.startsWith('UU ')) {\n conflictingFiles.push(trimmed.substring(3).trim())\n }\n }\n\n return conflictingFiles\n}\n\n/**\n * Map git error output to ErrorCode\n */\nexport function parseGitError(stderr: string, stdout: string, exitCode: number): ErrorCode {\n const combinedOutput = `${stderr}\\n${stdout}`.toLowerCase()\n\n // Check for git not installed\n if (combinedOutput.includes('git: command not found') ||\n combinedOutput.includes(\"'git' is not recognized\")) {\n return 'GIT_NOT_INSTALLED'\n }\n\n // Check for not a git repository\n if (combinedOutput.includes('not a git repository') ||\n combinedOutput.includes('not a git repo')) {\n return 'NOT_GIT_REPO'\n }\n\n // Check for merge conflicts\n if (combinedOutput.includes('conflict') ||\n combinedOutput.includes('merge conflict') ||\n exitCode === 1 && combinedOutput.includes('automatic merge failed')) {\n return 'MERGE_CONFLICT'\n }\n\n // Check for uncommitted changes\n if (combinedOutput.includes('please commit your changes') ||\n combinedOutput.includes('would be overwritten') ||\n combinedOutput.includes('cannot checkout') && combinedOutput.includes('files would be overwritten')) {\n return 'UNCOMMITTED_CHANGES'\n }\n\n // Check for authentication failures\n if (combinedOutput.includes('authentication failed') ||\n combinedOutput.includes('could not read username') ||\n combinedOutput.includes('permission denied') ||\n combinedOutput.includes('could not read password') ||\n combinedOutput.includes('fatal: authentication failed')) {\n return 'AUTH_FAILURE'\n }\n\n // Check for network errors\n if (combinedOutput.includes('could not resolve host') ||\n combinedOutput.includes('failed to connect') ||\n combinedOutput.includes('network is unreachable') ||\n combinedOutput.includes('connection timed out') ||\n combinedOutput.includes('could not read from remote')) {\n return 'NETWORK_ERROR'\n }\n\n // Check for branch not found\n if (combinedOutput.includes('did not match any file') ||\n combinedOutput.includes('branch') && combinedOutput.includes('not found') ||\n combinedOutput.includes('pathspec') && combinedOutput.includes('did not match')) {\n return 'BRANCH_NOT_FOUND'\n }\n\n // Check for branch already exists\n if (combinedOutput.includes('already exists') ||\n combinedOutput.includes('a branch named') && combinedOutput.includes('already exists')) {\n return 'BRANCH_ALREADY_EXISTS'\n }\n\n // Check for push rejected\n if (combinedOutput.includes('push rejected') ||\n combinedOutput.includes('failed to push') ||\n combinedOutput.includes('rejected') && combinedOutput.includes('non-fast-forward') ||\n combinedOutput.includes('updates were rejected')) {\n return 'PUSH_REJECTED'\n }\n\n // Check for timeout (exit code 124 is GNU timeout, 143 is SIGTERM)\n if (exitCode === 124 || exitCode === 143) {\n return 'COMMAND_TIMEOUT'\n }\n\n // Default to unknown error\n return 'UNKNOWN_ERROR'\n}\n\n/**\n * Extract branch name from git output\n */\nexport function extractBranchName(output: string): string | undefined {\n const lines = output.split('\\n')\n\n for (const line of lines) {\n const trimmed = line.trim()\n\n // Check for \"Switched to branch 'name'\"\n let match = trimmed.match(/Switched to (?:a new )?branch '(.+)'/)\n if (match && match[1]) {\n return match[1]\n }\n\n // Check for \"On branch name\"\n match = trimmed.match(/On branch (.+)/)\n if (match && match[1]) {\n return match[1]\n }\n }\n\n return undefined\n}\n\n/**\n * Check if output indicates detached HEAD state\n */\nexport function isDetachedHead(output: string): boolean {\n return output.toLowerCase().includes('head detached') ||\n output.toLowerCase().includes('you are in \\'detached head\\' state')\n}\n\n/**\n * Parse remote tracking information\n */\nexport function parseRemoteTracking(output: string): {\n hasUpstream: boolean\n remoteBranch?: string\n remote?: string\n} {\n const lines = output.split('\\n')\n\n for (const line of lines) {\n const trimmed = line.trim()\n\n // Check for \"Branch 'name' set up to track remote branch 'remote/branch'\"\n const match = trimmed.match(/set up to track remote branch '(.+?)'(?: from '(.+?)')?/)\n if (match) {\n return {\n hasUpstream: true,\n remoteBranch: match[1],\n remote: match[2] || 'origin'\n }\n }\n\n // Check for existing upstream: \"Your branch is up to date with 'origin/main'\"\n const upstreamMatch = trimmed.match(/(?:up to date with|ahead of|behind) '(.+?)\\/(.+?)'/)\n if (upstreamMatch) {\n return {\n hasUpstream: true,\n remote: upstreamMatch[1],\n remoteBranch: upstreamMatch[2]\n }\n }\n }\n\n return { hasUpstream: false }\n}\n","/**\n * Git Command Executor\n *\n * Executes git commands with error handling and returns structured results.\n * Interface-agnostic: Returns structured data, not formatted strings.\n */\n\nimport { exec } from 'child_process'\nimport { promisify } from 'util'\nimport { GitCommand, ExecutionResult, ExecutionOptions, ErrorCode } from './command-protocol'\nimport {\n validateBranchName,\n validateCommitMessage,\n validateFilePaths,\n sanitizeArgs\n} from './git-validator'\nimport {\n parseGitError,\n parseGitStatus,\n parseMergeConflicts,\n extractBranchName,\n isDetachedHead,\n parseRemoteTracking\n} from './git-parser'\n\nconst execAsync = promisify(exec)\n\n/**\n * Executes git commands with error handling\n *\n * DESIGN PRINCIPLES:\n * - Interface-agnostic: Returns structured data, not formatted strings\n * - No console.log: Let the interface handle output\n * - Error codes: Return error codes, not messages\n * - Reusable: Can be used by CLI, MCP, or any other interface\n */\nexport class GitExecutor {\n /**\n * Execute a git command\n * @param command - The git command to execute\n * @param options - Execution options (timeout, cwd, etc.)\n * @returns Structured result with success/error details\n */\n async execute(\n command: GitCommand,\n options?: ExecutionOptions\n ): Promise<ExecutionResult> {\n try {\n // Validate git is installed\n const gitInstalled = await this.validateGitInstalled()\n if (!gitInstalled) {\n return {\n success: false,\n error: 'GIT_NOT_INSTALLED'\n }\n }\n\n // Determine working directory\n const cwd = options?.cwd || process.cwd()\n\n // Validate this is a git repository (except for init-like commands)\n const isGitRepo = await this.isGitRepository(cwd)\n if (!isGitRepo) {\n return {\n success: false,\n error: 'NOT_GIT_REPO'\n }\n }\n\n // Route to appropriate handler based on action\n switch (command.action) {\n case 'checkout':\n return await this.executeCheckout(command, cwd, options)\n case 'create_branch':\n return await this.executeCreateBranch(command, cwd, options)\n case 'commit':\n return await this.executeCommit(command, cwd, options)\n case 'push':\n return await this.executePush(command, cwd, options)\n case 'status':\n return await this.executeStatus(cwd, options)\n case 'pull':\n return await this.executePull(command, cwd, options)\n case 'delete_branch':\n return await this.executeDeleteBranch(command, cwd, options)\n // EP597: Read operations for production local dev mode\n case 'branch_exists':\n return await this.executeBranchExists(command, cwd, options)\n case 'branch_has_commits':\n return await this.executeBranchHasCommits(command, cwd, options)\n // EP831: Find branch by prefix pattern\n case 'find_branch_by_prefix':\n return await this.executeFindBranchByPrefix(command, cwd, options)\n // EP598: Main branch check for production\n case 'main_branch_check':\n return await this.executeMainBranchCheck(cwd, options)\n // EP599: Get commits for branch\n case 'get_commits':\n return await this.executeGetCommits(command, cwd, options)\n // EP599: Advanced operations for move-to-module and discard-main-changes\n case 'stash':\n return await this.executeStash(command, cwd, options)\n case 'reset':\n return await this.executeReset(command, cwd, options)\n case 'merge':\n return await this.executeMerge(command, cwd, options)\n case 'cherry_pick':\n return await this.executeCherryPick(command, cwd, options)\n case 'clean':\n return await this.executeClean(command, cwd, options)\n case 'add':\n return await this.executeAdd(command, cwd, options)\n case 'fetch':\n return await this.executeFetch(command, cwd, options)\n // EP599-3: Composite operations\n case 'move_to_module':\n return await this.executeMoveToModule(command, cwd, options)\n case 'discard_main_changes':\n return await this.executeDiscardMainChanges(cwd, options)\n // EP523: Branch sync operations\n case 'sync_status':\n return await this.executeSyncStatus(command, cwd, options)\n case 'sync_main':\n return await this.executeSyncMain(cwd, options)\n case 'rebase_branch':\n return await this.executeRebaseBranch(command, cwd, options)\n case 'rebase_abort':\n return await this.executeRebaseAbort(cwd, options)\n case 'rebase_continue':\n return await this.executeRebaseContinue(cwd, options)\n case 'rebase_status':\n return await this.executeRebaseStatus(cwd, options)\n // EP944: Worktree operations\n case 'worktree_add':\n return await this.executeWorktreeAdd(command, cwd, options)\n case 'worktree_remove':\n return await this.executeWorktreeRemove(command, cwd, options)\n case 'worktree_list':\n return await this.executeWorktreeList(cwd, options)\n case 'worktree_prune':\n return await this.executeWorktreePrune(cwd, options)\n // EP1002: Worktree setup command for unified orchestration\n case 'worktree_setup':\n return await this.executeWorktreeSetup(command, cwd, options)\n case 'clone_bare':\n return await this.executeCloneBare(command, options)\n case 'project_info':\n return await this.executeProjectInfo(cwd, options)\n default:\n return {\n success: false,\n error: 'UNKNOWN_ERROR',\n output: 'Unknown command action'\n }\n }\n } catch (error) {\n return {\n success: false,\n error: 'UNKNOWN_ERROR',\n output: error instanceof Error ? error.message : 'Unknown error occurred'\n }\n }\n }\n\n /**\n * Execute checkout command\n */\n private async executeCheckout(\n command: { branch: string; create?: boolean },\n cwd: string,\n options?: ExecutionOptions\n ): Promise<ExecutionResult> {\n // Validate branch name\n const validation = validateBranchName(command.branch)\n if (!validation.valid) {\n return {\n success: false,\n error: validation.error || 'UNKNOWN_ERROR'\n }\n }\n\n // Check for uncommitted changes first\n const statusResult = await this.executeStatus(cwd, options)\n if (statusResult.success && statusResult.details?.uncommittedFiles?.length) {\n return {\n success: false,\n error: 'UNCOMMITTED_CHANGES',\n details: {\n uncommittedFiles: statusResult.details.uncommittedFiles\n }\n }\n }\n\n // Build command\n const args = ['checkout']\n if (command.create) {\n args.push('-b')\n }\n args.push(command.branch)\n\n return await this.runGitCommand(args, cwd, options)\n }\n\n /**\n * Execute create_branch command\n */\n private async executeCreateBranch(\n command: { branch: string; from?: string },\n cwd: string,\n options?: ExecutionOptions\n ): Promise<ExecutionResult> {\n // Validate branch name\n const validation = validateBranchName(command.branch)\n if (!validation.valid) {\n return {\n success: false,\n error: validation.error || 'UNKNOWN_ERROR'\n }\n }\n\n // Validate source branch if provided\n if (command.from) {\n const fromValidation = validateBranchName(command.from)\n if (!fromValidation.valid) {\n return {\n success: false,\n error: fromValidation.error || 'UNKNOWN_ERROR'\n }\n }\n }\n\n // Build command - use checkout -b to create AND checkout the branch\n // This ensures the user is on the new branch immediately\n const args = ['checkout', '-b', command.branch]\n if (command.from) {\n args.push(command.from)\n }\n\n return await this.runGitCommand(args, cwd, options)\n }\n\n /**\n * Execute commit command\n */\n private async executeCommit(\n command: { message: string; files?: string[] },\n cwd: string,\n options?: ExecutionOptions\n ): Promise<ExecutionResult> {\n // Validate commit message\n const validation = validateCommitMessage(command.message)\n if (!validation.valid) {\n return {\n success: false,\n error: validation.error || 'UNKNOWN_ERROR'\n }\n }\n\n // Validate file paths if provided\n if (command.files) {\n const fileValidation = validateFilePaths(command.files)\n if (!fileValidation.valid) {\n return {\n success: false,\n error: fileValidation.error || 'UNKNOWN_ERROR'\n }\n }\n\n // Stage specific files first\n for (const file of command.files) {\n const addResult = await this.runGitCommand(['add', file], cwd, options)\n if (!addResult.success) {\n return addResult\n }\n }\n } else {\n // Stage all changes\n const addResult = await this.runGitCommand(['add', '-A'], cwd, options)\n if (!addResult.success) {\n return addResult\n }\n }\n\n // Execute commit\n const args = ['commit', '-m', command.message]\n return await this.runGitCommand(args, cwd, options)\n }\n\n /**\n * Execute push command\n * EP769: Added force parameter for pushing rebased branches\n */\n private async executePush(\n command: { branch: string; setUpstream?: boolean; force?: boolean },\n cwd: string,\n options?: ExecutionOptions\n ): Promise<ExecutionResult> {\n // Validate branch name\n const validation = validateBranchName(command.branch)\n if (!validation.valid) {\n return {\n success: false,\n error: validation.error || 'UNKNOWN_ERROR'\n }\n }\n\n // Build command\n const args = ['push']\n // EP769: Add --force flag for rebased branches\n if (command.force) {\n args.push('--force')\n }\n if (command.setUpstream) {\n args.push('-u', 'origin', command.branch)\n } else {\n args.push('origin', command.branch)\n }\n\n // Configure git credential helper for GitHub token if provided\n const env = { ...process.env }\n if (options?.githubToken) {\n env.GIT_ASKPASS = 'echo'\n env.GIT_USERNAME = 'x-access-token'\n env.GIT_PASSWORD = options.githubToken\n }\n\n return await this.runGitCommand(args, cwd, { ...options, env })\n }\n\n /**\n * Execute status command\n */\n private async executeStatus(\n cwd: string,\n options?: ExecutionOptions\n ): Promise<ExecutionResult> {\n // EP971: Check if this is a bare repo (git status doesn't work in bare repos)\n try {\n const isBareResult = await execAsync('git rev-parse --is-bare-repository', { cwd, timeout: 5000 })\n if (isBareResult.stdout.trim() === 'true') {\n // In bare repo, get current branch from HEAD ref\n const headResult = await execAsync('git symbolic-ref --short HEAD', { cwd, timeout: 5000 })\n const branchName = headResult.stdout.trim()\n return {\n success: true,\n output: `## ${branchName}`,\n details: {\n uncommittedFiles: [], // No working tree in bare repo\n branchName,\n currentBranch: branchName\n }\n }\n }\n } catch {\n // Not a bare repo or failed to check, continue with normal status\n }\n\n const result = await this.runGitCommand(['status', '--porcelain', '-b'], cwd, options)\n\n if (result.success && result.output) {\n const statusInfo = parseGitStatus(result.output)\n return {\n success: true,\n output: result.output,\n details: {\n uncommittedFiles: statusInfo.uncommittedFiles,\n branchName: statusInfo.currentBranch\n }\n }\n }\n\n return result\n }\n\n /**\n * Execute pull command\n */\n private async executePull(\n command: { branch?: string },\n cwd: string,\n options?: ExecutionOptions\n ): Promise<ExecutionResult> {\n // Validate branch name if provided\n if (command.branch) {\n const validation = validateBranchName(command.branch)\n if (!validation.valid) {\n return {\n success: false,\n error: validation.error || 'UNKNOWN_ERROR'\n }\n }\n }\n\n // Check for uncommitted changes first\n const statusResult = await this.executeStatus(cwd, options)\n if (statusResult.success && statusResult.details?.uncommittedFiles?.length) {\n return {\n success: false,\n error: 'UNCOMMITTED_CHANGES',\n details: {\n uncommittedFiles: statusResult.details.uncommittedFiles\n }\n }\n }\n\n // Build command\n const args = ['pull']\n if (command.branch) {\n args.push('origin', command.branch)\n }\n\n const result = await this.runGitCommand(args, cwd, options)\n\n // Check for merge conflicts\n if (!result.success && result.output) {\n const conflicts = parseMergeConflicts(result.output)\n if (conflicts.length > 0) {\n return {\n success: false,\n error: 'MERGE_CONFLICT',\n output: result.output,\n details: {\n conflictingFiles: conflicts\n }\n }\n }\n }\n\n return result\n }\n\n /**\n * Execute delete_branch command\n */\n private async executeDeleteBranch(\n command: { branch: string; force?: boolean },\n cwd: string,\n options?: ExecutionOptions\n ): Promise<ExecutionResult> {\n // Validate branch name\n const validation = validateBranchName(command.branch)\n if (!validation.valid) {\n return {\n success: false,\n error: validation.error || 'UNKNOWN_ERROR'\n }\n }\n\n // Build command\n const args = ['branch']\n args.push(command.force ? '-D' : '-d')\n args.push(command.branch)\n\n return await this.runGitCommand(args, cwd, options)\n }\n\n /**\n * EP597: Execute branch_exists command\n * Checks if a branch exists locally and/or remotely\n */\n private async executeBranchExists(\n command: { branch: string },\n cwd: string,\n options?: ExecutionOptions\n ): Promise<ExecutionResult> {\n // Validate branch name\n const validation = validateBranchName(command.branch)\n if (!validation.valid) {\n return {\n success: false,\n error: validation.error || 'UNKNOWN_ERROR'\n }\n }\n\n try {\n let isLocal = false\n let isRemote = false\n\n // Check local branches\n try {\n const { stdout: localBranches } = await execAsync('git branch --list', { cwd, timeout: options?.timeout || 10000 })\n isLocal = localBranches.split('\\n').some(line => {\n const branchName = line.replace(/^\\*?\\s*/, '').trim()\n return branchName === command.branch\n })\n } catch {\n // Ignore errors - branch doesn't exist locally\n }\n\n // Check remote branches\n try {\n const { stdout: remoteBranches } = await execAsync(\n `git ls-remote --heads origin ${command.branch}`,\n { cwd, timeout: options?.timeout || 10000 }\n )\n isRemote = remoteBranches.trim().length > 0\n } catch {\n // Ignore errors - can't check remote (might be network issue)\n }\n\n const branchExists = isLocal || isRemote\n\n return {\n success: true,\n output: branchExists ? `Branch ${command.branch} exists` : `Branch ${command.branch} does not exist`,\n details: {\n branchName: command.branch,\n branchExists,\n isLocal,\n isRemote\n }\n }\n } catch (error: any) {\n return {\n success: false,\n error: 'UNKNOWN_ERROR',\n output: error.message || 'Failed to check branch existence'\n }\n }\n }\n\n /**\n * EP597: Execute branch_has_commits command\n * Checks if a branch has commits ahead of the base branch (default: main)\n */\n private async executeBranchHasCommits(\n command: { branch: string; baseBranch?: string },\n cwd: string,\n options?: ExecutionOptions\n ): Promise<ExecutionResult> {\n // Validate branch name\n const validation = validateBranchName(command.branch)\n if (!validation.valid) {\n return {\n success: false,\n error: validation.error || 'UNKNOWN_ERROR'\n }\n }\n\n const baseBranch = command.baseBranch || 'main'\n\n try {\n // Use git cherry to find commits unique to the branch\n // This shows commits on branch that aren't on base\n const { stdout } = await execAsync(\n `git cherry origin/${baseBranch} ${command.branch}`,\n { cwd, timeout: options?.timeout || 10000 }\n )\n\n // git cherry shows lines starting with + for unique commits\n const uniqueCommits = stdout.trim().split('\\n').filter(line => line.startsWith('+'))\n const hasCommits = uniqueCommits.length > 0\n\n return {\n success: true,\n output: hasCommits\n ? `Branch ${command.branch} has ${uniqueCommits.length} commits ahead of ${baseBranch}`\n : `Branch ${command.branch} has no commits ahead of ${baseBranch}`,\n details: {\n branchName: command.branch,\n hasCommits\n }\n }\n } catch (error: any) {\n // If git cherry fails (branch not found, etc.), try alternative method\n try {\n // Alternative: count commits with rev-list\n const { stdout } = await execAsync(\n `git rev-list --count origin/${baseBranch}..${command.branch}`,\n { cwd, timeout: options?.timeout || 10000 }\n )\n\n const commitCount = parseInt(stdout.trim(), 10)\n const hasCommits = commitCount > 0\n\n return {\n success: true,\n output: hasCommits\n ? `Branch ${command.branch} has ${commitCount} commits ahead of ${baseBranch}`\n : `Branch ${command.branch} has no commits ahead of ${baseBranch}`,\n details: {\n branchName: command.branch,\n hasCommits\n }\n }\n } catch {\n // Both methods failed - branch likely doesn't exist or isn't tracked\n return {\n success: false,\n error: 'BRANCH_NOT_FOUND',\n output: error.message || `Failed to check commits for branch ${command.branch}`\n }\n }\n }\n }\n\n /**\n * EP598: Execute main branch check - returns current branch, uncommitted files, and unpushed commits\n */\n\n /**\n * EP831: Find branch by prefix pattern\n * Searches local and remote branches for one matching the prefix\n */\n private async executeFindBranchByPrefix(\n command: { prefix: string },\n cwd: string,\n options?: ExecutionOptions\n ): Promise<ExecutionResult> {\n try {\n const { stdout } = await execAsync(\n 'git branch -a',\n { cwd, timeout: options?.timeout || 10000 }\n )\n\n const prefix = command.prefix\n const branches = stdout.split('\\n')\n .map(line => line.replace(/^[\\s*]*/, '').replace('remotes/origin/', '').trim())\n .filter(branch => branch && !branch.includes('->'))\n\n const matchingBranch = branches.find(branch => branch.startsWith(prefix))\n\n return {\n success: true,\n output: matchingBranch || '',\n details: {\n branchName: matchingBranch || undefined,\n branchExists: !!matchingBranch\n }\n }\n } catch (error: any) {\n return {\n success: false,\n error: 'UNKNOWN_ERROR',\n output: error.message || 'Failed to find branch'\n }\n }\n }\n\n private async executeMainBranchCheck(\n cwd: string,\n options?: ExecutionOptions\n ): Promise<ExecutionResult> {\n try {\n // Get current branch\n let currentBranch = ''\n try {\n const { stdout } = await execAsync('git branch --show-current', { cwd, timeout: options?.timeout || 10000 })\n currentBranch = stdout.trim()\n } catch (error: any) {\n return {\n success: false,\n error: 'UNKNOWN_ERROR',\n output: error.message || 'Failed to get current branch'\n }\n }\n\n // Get uncommitted files\n let uncommittedFiles: string[] = []\n try {\n const { stdout } = await execAsync('git status --porcelain', { cwd, timeout: options?.timeout || 10000 })\n if (stdout) {\n uncommittedFiles = stdout.split('\\n').filter(line => line.trim()).map(line => {\n const parts = line.trim().split(/\\s+/)\n return parts.slice(1).join(' ')\n })\n }\n } catch {\n // Ignore errors - just means no uncommitted changes\n }\n\n // Get unpushed commits (only if on main branch)\n let localCommits: Array<{ sha: string; message: string; author: string }> = []\n if (currentBranch === 'main') {\n try {\n const { stdout } = await execAsync('git log origin/main..HEAD --format=\"%H|%s|%an\"', { cwd, timeout: options?.timeout || 10000 })\n if (stdout) {\n localCommits = stdout.split('\\n').filter(line => line.trim()).map(line => {\n const [sha, message, author] = line.split('|')\n return {\n sha: sha ? sha.substring(0, 8) : '',\n message: message || '',\n author: author || ''\n }\n })\n }\n } catch {\n // Ignore errors - might not have origin/main or no remote\n }\n }\n\n return {\n success: true,\n output: `Branch: ${currentBranch}, Uncommitted: ${uncommittedFiles.length}, Unpushed: ${localCommits.length}`,\n details: {\n currentBranch,\n uncommittedFiles,\n localCommits\n }\n }\n } catch (error: any) {\n return {\n success: false,\n error: 'UNKNOWN_ERROR',\n output: error.message || 'Failed to check main branch'\n }\n }\n }\n\n /**\n * EP599: Execute get_commits command\n * Returns commits for a branch with pushed/unpushed status\n */\n private async executeGetCommits(\n command: { branch: string; limit?: number; baseBranch?: string },\n cwd: string,\n options?: ExecutionOptions\n ): Promise<ExecutionResult> {\n // Validate branch name\n const validation = validateBranchName(command.branch)\n if (!validation.valid) {\n return {\n success: false,\n error: validation.error || 'UNKNOWN_ERROR'\n }\n }\n\n const limit = command.limit || 10\n const baseBranch = command.baseBranch || 'main'\n\n try {\n // Get commits unique to this branch (not in main)\n // EP1031: In worktree setups, local 'main' may not exist, but 'origin/main' does\n // Try origin/baseBranch first (works in worktrees), then fall back to baseBranch\n let stdout: string\n let comparisonSucceeded = false\n\n // Try origin/baseBranch first (works in worktrees where remote refs are shared)\n try {\n const result = await execAsync(\n `git log origin/${baseBranch}..\"${command.branch}\" --pretty=format:\"%H|%an|%ae|%aI|%s\" -n ${limit} --`,\n { cwd, timeout: options?.timeout || 10000 }\n )\n stdout = result.stdout\n comparisonSucceeded = true\n } catch {\n // origin/baseBranch doesn't exist, try local baseBranch\n try {\n const result = await execAsync(\n `git log ${baseBranch}..\"${command.branch}\" --pretty=format:\"%H|%an|%ae|%aI|%s\" -n ${limit} --`,\n { cwd, timeout: options?.timeout || 10000 }\n )\n stdout = result.stdout\n comparisonSucceeded = true\n } catch {\n // Neither origin/baseBranch nor baseBranch exist\n // EP1031: Return empty commits instead of falling back to showing all history\n // This is safer than showing unrelated commits from the branch's full history\n stdout = ''\n comparisonSucceeded = false\n }\n }\n\n // EP1031: Only verify branch exists if comparison failed\n // This handles the case where baseBranch doesn't exist but we should still verify the target branch is valid\n if (!comparisonSucceeded) {\n try {\n await execAsync(\n `git rev-parse --verify \"${command.branch}\"`,\n { cwd, timeout: options?.timeout || 5000 }\n )\n // Branch exists but has no unique commits (comparison base not found)\n // Return empty commits - this is the expected case for a fresh branch\n } catch {\n // Branch doesn't exist\n return {\n success: false,\n error: 'BRANCH_NOT_FOUND',\n output: `Branch ${command.branch} not found locally`\n }\n }\n }\n\n if (!stdout.trim()) {\n return {\n success: true,\n output: 'No commits found',\n details: {\n commits: []\n }\n }\n }\n\n // Parse commits\n const commitLines = stdout.trim().split('\\n')\n\n // Check which commits have been pushed to remote\n let remoteShas: Set<string> = new Set()\n try {\n const { stdout: remoteCommits } = await execAsync(\n `git log \"origin/${command.branch}\" --pretty=format:\"%H\" -n ${limit} --`,\n { cwd, timeout: options?.timeout || 10000 }\n )\n remoteShas = new Set(remoteCommits.trim().split('\\n').filter(Boolean))\n } catch {\n // Remote branch doesn't exist - all commits are local/unpushed\n }\n\n const commits = commitLines.map((line) => {\n const [sha, authorName, authorEmail, date, ...messageParts] = line.split('|')\n const message = messageParts.join('|') // Handle pipes in commit messages\n const isPushed = remoteShas.has(sha)\n\n return {\n sha,\n message,\n authorName,\n authorEmail,\n date,\n isPushed\n }\n })\n\n return {\n success: true,\n output: `Found ${commits.length} commits`,\n details: {\n commits\n }\n }\n } catch (error: any) {\n return {\n success: false,\n error: 'UNKNOWN_ERROR',\n output: error.message || 'Failed to get commits'\n }\n }\n }\n\n // ========================================\n // EP599: Advanced operations for move-to-module and discard-main-changes\n // ========================================\n\n /**\n * Execute git stash operations\n */\n private async executeStash(\n command: { operation: 'push' | 'pop' | 'drop' | 'list'; message?: string; includeUntracked?: boolean },\n cwd: string,\n options?: ExecutionOptions\n ): Promise<ExecutionResult> {\n try {\n const args: string[] = ['stash']\n\n switch (command.operation) {\n case 'push':\n args.push('push')\n if (command.includeUntracked) {\n args.push('--include-untracked')\n }\n if (command.message) {\n args.push('-m', command.message)\n }\n break\n case 'pop':\n args.push('pop')\n break\n case 'drop':\n args.push('drop')\n break\n case 'list':\n args.push('list')\n break\n }\n\n return await this.runGitCommand(args, cwd, options)\n } catch (error: any) {\n return {\n success: false,\n error: 'UNKNOWN_ERROR',\n output: error.message || 'Stash operation failed'\n }\n }\n }\n\n /**\n * Execute git reset\n */\n private async executeReset(\n command: { mode: 'soft' | 'mixed' | 'hard'; target?: string },\n cwd: string,\n options?: ExecutionOptions\n ): Promise<ExecutionResult> {\n try {\n const args = ['reset', `--${command.mode}`]\n if (command.target) {\n args.push(command.target)\n }\n\n return await this.runGitCommand(args, cwd, options)\n } catch (error: any) {\n return {\n success: false,\n error: 'UNKNOWN_ERROR',\n output: error.message || 'Reset failed'\n }\n }\n }\n\n /**\n * Execute git merge\n */\n private async executeMerge(\n command: { branch: string; strategy?: 'ours' | 'theirs'; noEdit?: boolean; abort?: boolean },\n cwd: string,\n options?: ExecutionOptions\n ): Promise<ExecutionResult> {\n try {\n if (command.abort) {\n return await this.runGitCommand(['merge', '--abort'], cwd, options)\n }\n\n // Validate branch name\n const branchValidation = validateBranchName(command.branch)\n if (!branchValidation.valid) {\n return {\n success: false,\n error: 'BRANCH_NOT_FOUND',\n output: branchValidation.error || 'Invalid branch name'\n }\n }\n\n const args = ['merge', command.branch]\n\n if (command.strategy === 'ours') {\n args.push('--strategy=ours')\n } else if (command.strategy === 'theirs') {\n args.push('--strategy-option=theirs')\n }\n\n if (command.noEdit) {\n args.push('--no-edit')\n }\n\n const result = await this.runGitCommand(args, cwd, options)\n\n // Check for merge conflicts\n if (!result.success && result.output?.includes('CONFLICT')) {\n result.details = result.details || {}\n result.details.mergeConflicts = true\n }\n\n return result\n } catch (error: any) {\n return {\n success: false,\n error: 'MERGE_CONFLICT',\n output: error.message || 'Merge failed'\n }\n }\n }\n\n /**\n * Execute git cherry-pick\n */\n private async executeCherryPick(\n command: { sha: string; abort?: boolean },\n cwd: string,\n options?: ExecutionOptions\n ): Promise<ExecutionResult> {\n try {\n if (command.abort) {\n return await this.runGitCommand(['cherry-pick', '--abort'], cwd, options)\n }\n\n const result = await this.runGitCommand(['cherry-pick', command.sha], cwd, options)\n\n // Check for cherry-pick conflicts\n if (!result.success && result.output?.includes('CONFLICT')) {\n result.details = result.details || {}\n result.details.cherryPickConflicts = true\n }\n\n return result\n } catch (error: any) {\n return {\n success: false,\n error: 'MERGE_CONFLICT',\n output: error.message || 'Cherry-pick failed'\n }\n }\n }\n\n /**\n * Execute git clean\n */\n private async executeClean(\n command: { force?: boolean; directories?: boolean },\n cwd: string,\n options?: ExecutionOptions\n ): Promise<ExecutionResult> {\n try {\n const args = ['clean']\n\n if (command.force) {\n args.push('-f')\n }\n if (command.directories) {\n args.push('-d')\n }\n\n return await this.runGitCommand(args, cwd, options)\n } catch (error: any) {\n return {\n success: false,\n error: 'UNKNOWN_ERROR',\n output: error.message || 'Clean failed'\n }\n }\n }\n\n /**\n * Execute git add\n */\n private async executeAdd(\n command: { files?: string[]; all?: boolean },\n cwd: string,\n options?: ExecutionOptions\n ): Promise<ExecutionResult> {\n try {\n const args = ['add']\n\n if (command.all) {\n args.push('-A')\n } else if (command.files && command.files.length > 0) {\n // Validate file paths\n const validation = validateFilePaths(command.files)\n if (!validation.valid) {\n return {\n success: false,\n error: 'UNKNOWN_ERROR',\n output: validation.error || 'Invalid file paths'\n }\n }\n args.push(...command.files)\n } else {\n args.push('-A') // Default to all\n }\n\n return await this.runGitCommand(args, cwd, options)\n } catch (error: any) {\n return {\n success: false,\n error: 'UNKNOWN_ERROR',\n output: error.message || 'Add failed'\n }\n }\n }\n\n /**\n * Execute git fetch\n */\n private async executeFetch(\n command: { remote?: string; branch?: string },\n cwd: string,\n options?: ExecutionOptions\n ): Promise<ExecutionResult> {\n try {\n const args = ['fetch']\n\n if (command.remote) {\n args.push(command.remote)\n if (command.branch) {\n args.push(command.branch)\n }\n } else {\n args.push('origin')\n }\n\n return await this.runGitCommand(args, cwd, options)\n } catch (error: any) {\n return {\n success: false,\n error: 'NETWORK_ERROR',\n output: error.message || 'Fetch failed'\n }\n }\n }\n\n // ========================================\n // EP599-3: Composite operations\n // ========================================\n\n /**\n * Execute move_to_module - composite operation\n * Moves commits/changes to a module branch with conflict handling\n */\n private async executeMoveToModule(\n command: { targetBranch: string; commitShas?: string[]; conflictResolution?: 'ours' | 'theirs' },\n cwd: string,\n options?: ExecutionOptions\n ): Promise<ExecutionResult> {\n const { targetBranch, commitShas, conflictResolution } = command\n let hasStash = false\n const cherryPickedCommits: string[] = []\n\n try {\n // Step 1: Get current branch\n const { stdout: currentBranchOut } = await execAsync('git rev-parse --abbrev-ref HEAD', { cwd })\n const currentBranch = currentBranchOut.trim()\n\n // Step 2: Stash uncommitted changes\n const { stdout: statusOutput } = await execAsync('git status --porcelain', { cwd })\n if (statusOutput.trim()) {\n try {\n await execAsync('git add -A', { cwd })\n const { stdout: stashHash } = await execAsync('git stash create -m \"episoda-move-to-module\"', { cwd })\n if (stashHash && stashHash.trim()) {\n await execAsync(`git stash store -m \"episoda-move-to-module\" ${stashHash.trim()}`, { cwd })\n await execAsync('git reset --hard HEAD', { cwd })\n hasStash = true\n }\n } catch (stashError: any) {\n // Continue without stashing\n }\n }\n\n // Step 3: Switch to main if we have commits to move\n if (commitShas && commitShas.length > 0 && currentBranch !== 'main' && currentBranch !== 'master') {\n await execAsync('git checkout main', { cwd })\n }\n\n // Step 4: Create or checkout target branch\n let branchExists = false\n try {\n await execAsync(`git rev-parse --verify ${targetBranch}`, { cwd })\n branchExists = true\n } catch {\n branchExists = false\n }\n\n if (!branchExists) {\n await execAsync(`git checkout -b ${targetBranch}`, { cwd })\n } else {\n await execAsync(`git checkout ${targetBranch}`, { cwd })\n\n // Try to merge changes from main\n if (currentBranch === 'main' || currentBranch === 'master') {\n try {\n const mergeStrategy = conflictResolution === 'ours' ? '--strategy=ours' :\n conflictResolution === 'theirs' ? '--strategy-option=theirs' : ''\n await execAsync(`git merge ${currentBranch} ${mergeStrategy} --no-edit`, { cwd })\n } catch (mergeError: any) {\n // Check for conflicts\n const { stdout: conflictStatus } = await execAsync('git status --porcelain', { cwd })\n if (conflictStatus.includes('UU ') || conflictStatus.includes('AA ') || conflictStatus.includes('DD ')) {\n const { stdout: conflictFiles } = await execAsync('git diff --name-only --diff-filter=U', { cwd })\n const conflictedFiles = conflictFiles.trim().split('\\n').filter(Boolean)\n\n if (conflictResolution) {\n // Auto-resolve conflicts\n for (const file of conflictedFiles) {\n await execAsync(`git checkout --${conflictResolution} \"${file}\"`, { cwd })\n await execAsync(`git add \"${file}\"`, { cwd })\n }\n await execAsync('git commit --no-edit', { cwd })\n } else {\n // Abort merge and return conflict error\n await execAsync('git merge --abort', { cwd })\n return {\n success: false,\n error: 'MERGE_CONFLICT',\n output: 'Merge conflicts detected',\n details: {\n hasConflicts: true,\n conflictedFiles,\n movedToBranch: targetBranch\n }\n }\n }\n }\n }\n }\n }\n\n // Step 5: Cherry-pick commits if provided\n if (commitShas && commitShas.length > 0 && (currentBranch === 'main' || currentBranch === 'master')) {\n for (const sha of commitShas) {\n try {\n // Check if commit already exists in branch\n const { stdout: logOutput } = await execAsync(\n `git log --format=%H ${targetBranch} | grep ${sha}`,\n { cwd }\n ).catch(() => ({ stdout: '' }))\n\n if (!logOutput.trim()) {\n await execAsync(`git cherry-pick ${sha}`, { cwd })\n cherryPickedCommits.push(sha)\n }\n } catch (err: any) {\n await execAsync('git cherry-pick --abort', { cwd }).catch(() => {})\n }\n }\n\n // Reset main to origin/main\n await execAsync('git checkout main', { cwd })\n await execAsync('git reset --hard origin/main', { cwd })\n await execAsync(`git checkout ${targetBranch}`, { cwd })\n }\n\n // Step 6: Apply stashed changes\n if (hasStash) {\n try {\n await execAsync('git stash pop', { cwd })\n } catch (stashError: any) {\n // Check for stash conflicts\n const { stdout: conflictStatus } = await execAsync('git status --porcelain', { cwd })\n if (conflictStatus.includes('UU ') || conflictStatus.includes('AA ')) {\n if (conflictResolution) {\n const { stdout: conflictFiles } = await execAsync('git diff --name-only --diff-filter=U', { cwd })\n const conflictedFiles = conflictFiles.trim().split('\\n').filter(Boolean)\n for (const file of conflictedFiles) {\n await execAsync(`git checkout --${conflictResolution} \"${file}\"`, { cwd })\n await execAsync(`git add \"${file}\"`, { cwd })\n }\n }\n }\n }\n }\n\n return {\n success: true,\n output: `Successfully moved to branch ${targetBranch}`,\n details: {\n movedToBranch: targetBranch,\n cherryPickedCommits,\n currentBranch: targetBranch\n }\n }\n } catch (error: any) {\n // Try to restore stash if something went wrong\n if (hasStash) {\n try {\n const { stdout: stashList } = await execAsync('git stash list', { cwd })\n if (stashList.includes('episoda-move-to-module')) {\n await execAsync('git stash pop', { cwd })\n }\n } catch (e) {\n // Ignore errors restoring stash\n }\n }\n\n return {\n success: false,\n error: 'UNKNOWN_ERROR',\n output: error.message || 'Move to module failed'\n }\n }\n }\n\n /**\n * Execute discard_main_changes - composite operation\n * Discards all uncommitted files and local commits on main branch\n */\n private async executeDiscardMainChanges(\n cwd: string,\n options?: ExecutionOptions\n ): Promise<ExecutionResult> {\n try {\n // Step 1: Verify we're on main/master\n const { stdout: currentBranchOut } = await execAsync('git rev-parse --abbrev-ref HEAD', { cwd })\n const branch = currentBranchOut.trim()\n\n if (branch !== 'main' && branch !== 'master') {\n return {\n success: false,\n error: 'BRANCH_NOT_FOUND',\n output: `Cannot discard changes - not on main branch. Current branch: ${branch}`\n }\n }\n\n let discardedFiles = 0\n\n // Step 2: Stash uncommitted changes (will be dropped)\n const { stdout: statusOutput } = await execAsync('git status --porcelain', { cwd })\n if (statusOutput.trim()) {\n try {\n await execAsync('git stash --include-untracked', { cwd })\n discardedFiles = statusOutput.trim().split('\\n').length\n } catch (stashError: any) {\n // Continue - might be nothing to stash\n }\n }\n\n // Step 3: Fetch and reset to origin\n await execAsync('git fetch origin', { cwd })\n await execAsync(`git reset --hard origin/${branch}`, { cwd })\n\n // Step 4: Clean untracked files\n try {\n await execAsync('git clean -fd', { cwd })\n } catch (cleanError: any) {\n // Non-critical\n }\n\n // Step 5: Drop the stash\n try {\n await execAsync('git stash drop', { cwd })\n } catch (dropError: any) {\n // Stash might not exist\n }\n\n return {\n success: true,\n output: `Successfully discarded all changes and reset to origin/${branch}`,\n details: {\n currentBranch: branch,\n discardedFiles\n }\n }\n } catch (error: any) {\n return {\n success: false,\n error: 'UNKNOWN_ERROR',\n output: error.message || 'Discard main changes failed'\n }\n }\n }\n\n // ========================================\n // EP523: Branch sync operations\n // ========================================\n\n /**\n * EP523: Get sync status of a branch relative to main\n * Returns how many commits behind/ahead the branch is\n */\n private async executeSyncStatus(\n command: { branch: string },\n cwd: string,\n options?: ExecutionOptions\n ): Promise<ExecutionResult> {\n try {\n // Validate branch name\n const validation = validateBranchName(command.branch)\n if (!validation.valid) {\n return {\n success: false,\n error: validation.error || 'UNKNOWN_ERROR'\n }\n }\n\n // Fetch latest from remote to get accurate counts\n try {\n await execAsync('git fetch origin', { cwd, timeout: options?.timeout || 30000 })\n } catch (fetchError: any) {\n // Network error - return what we can determine locally\n return {\n success: false,\n error: 'NETWORK_ERROR',\n output: 'Unable to fetch from remote. Check your network connection.'\n }\n }\n\n let commitsBehind = 0\n let commitsAhead = 0\n\n // Count commits the branch is BEHIND main (main has commits branch doesn't)\n try {\n const { stdout: behindOutput } = await execAsync(\n `git rev-list --count ${command.branch}..origin/main`,\n { cwd, timeout: options?.timeout || 10000 }\n )\n commitsBehind = parseInt(behindOutput.trim(), 10) || 0\n } catch {\n // Branch might not exist or no common ancestor\n commitsBehind = 0\n }\n\n // Count commits the branch is AHEAD of main (branch has commits main doesn't)\n try {\n const { stdout: aheadOutput } = await execAsync(\n `git rev-list --count origin/main..${command.branch}`,\n { cwd, timeout: options?.timeout || 10000 }\n )\n commitsAhead = parseInt(aheadOutput.trim(), 10) || 0\n } catch {\n // Branch might not exist or no common ancestor\n commitsAhead = 0\n }\n\n const isBehind = commitsBehind > 0\n const isAhead = commitsAhead > 0\n const needsSync = isBehind\n\n return {\n success: true,\n output: isBehind\n ? `Branch ${command.branch} is ${commitsBehind} commit(s) behind main`\n : `Branch ${command.branch} is up to date with main`,\n details: {\n branchName: command.branch,\n commitsBehind,\n commitsAhead,\n isBehind,\n isAhead,\n needsSync\n }\n }\n } catch (error: any) {\n return {\n success: false,\n error: 'UNKNOWN_ERROR',\n output: error.message || 'Failed to check sync status'\n }\n }\n }\n\n /**\n * EP523: Sync local main branch with remote\n * Used before creating new branches to ensure we branch from latest main\n */\n private async executeSyncMain(\n cwd: string,\n options?: ExecutionOptions\n ): Promise<ExecutionResult> {\n try {\n // Get current branch to restore later if needed\n let currentBranch = ''\n try {\n const { stdout } = await execAsync('git branch --show-current', { cwd, timeout: 5000 })\n currentBranch = stdout.trim()\n } catch {\n // Ignore - might be detached HEAD\n }\n\n // Fetch latest from remote\n try {\n await execAsync('git fetch origin main', { cwd, timeout: options?.timeout || 30000 })\n } catch (fetchError: any) {\n return {\n success: false,\n error: 'NETWORK_ERROR',\n output: 'Unable to fetch from remote. Check your network connection.'\n }\n }\n\n // Check if we need to switch to main\n const needsSwitch = currentBranch !== 'main' && currentBranch !== ''\n\n if (needsSwitch) {\n // Check for uncommitted changes first\n const { stdout: statusOutput } = await execAsync('git status --porcelain', { cwd, timeout: 5000 })\n if (statusOutput.trim()) {\n return {\n success: false,\n error: 'UNCOMMITTED_CHANGES',\n output: 'Cannot sync main: you have uncommitted changes. Commit or stash them first.',\n details: {\n uncommittedFiles: statusOutput.trim().split('\\n').map(line => line.slice(3))\n }\n }\n }\n\n // Switch to main\n await execAsync('git checkout main', { cwd, timeout: options?.timeout || 10000 })\n }\n\n // Pull latest main\n try {\n await execAsync('git pull origin main', { cwd, timeout: options?.timeout || 30000 })\n } catch (pullError: any) {\n // Check for conflicts\n if (pullError.message?.includes('CONFLICT') || pullError.stderr?.includes('CONFLICT')) {\n // Abort the merge\n await execAsync('git merge --abort', { cwd, timeout: 5000 }).catch(() => {})\n return {\n success: false,\n error: 'MERGE_CONFLICT',\n output: 'Conflict while syncing main. This is unexpected - main should not have local commits.'\n }\n }\n throw pullError\n }\n\n // Switch back to original branch if we switched\n if (needsSwitch && currentBranch) {\n await execAsync(`git checkout \"${currentBranch}\"`, { cwd, timeout: options?.timeout || 10000 })\n }\n\n return {\n success: true,\n output: 'Successfully synced main with remote',\n details: {\n currentBranch: needsSwitch ? currentBranch : 'main'\n }\n }\n } catch (error: any) {\n return {\n success: false,\n error: 'UNKNOWN_ERROR',\n output: error.message || 'Failed to sync main'\n }\n }\n }\n\n /**\n * EP523: Rebase a branch onto main\n * Used when resuming work on a branch that's behind main\n */\n private async executeRebaseBranch(\n command: { branch: string },\n cwd: string,\n options?: ExecutionOptions\n ): Promise<ExecutionResult> {\n try {\n // Validate branch name\n const validation = validateBranchName(command.branch)\n if (!validation.valid) {\n return {\n success: false,\n error: validation.error || 'UNKNOWN_ERROR'\n }\n }\n\n // Check for uncommitted changes\n const { stdout: statusOutput } = await execAsync('git status --porcelain', { cwd, timeout: 5000 })\n if (statusOutput.trim()) {\n return {\n success: false,\n error: 'UNCOMMITTED_CHANGES',\n output: 'Cannot rebase: you have uncommitted changes. Commit or stash them first.',\n details: {\n uncommittedFiles: statusOutput.trim().split('\\n').map(line => line.slice(3))\n }\n }\n }\n\n // Get current branch\n const { stdout: currentBranchOut } = await execAsync('git branch --show-current', { cwd, timeout: 5000 })\n const currentBranch = currentBranchOut.trim()\n\n // Ensure we're on the target branch\n if (currentBranch !== command.branch) {\n await execAsync(`git checkout \"${command.branch}\"`, { cwd, timeout: options?.timeout || 10000 })\n }\n\n // Fetch latest main\n await execAsync('git fetch origin main', { cwd, timeout: options?.timeout || 30000 })\n\n // Perform rebase\n const rebaseEnv = {\n ...process.env,\n EPISODA_SKIP_CHECKOUT_HOOK: '1'\n }\n\n try {\n await execAsync('git rebase origin/main', {\n cwd,\n timeout: options?.timeout || 60000,\n env: rebaseEnv\n })\n } catch (rebaseError: any) {\n const errorOutput = (rebaseError.stderr || '') + (rebaseError.stdout || '')\n\n // Check for conflicts\n if (errorOutput.includes('CONFLICT') || errorOutput.includes('could not apply')) {\n // Get conflicting files\n let conflictFiles: string[] = []\n try {\n const { stdout: conflictOutput } = await execAsync(\n 'git diff --name-only --diff-filter=U',\n { cwd, timeout: 5000 }\n )\n conflictFiles = conflictOutput.trim().split('\\n').filter(Boolean)\n } catch {\n // Ignore - try alternate method\n try {\n const { stdout: statusOut } = await execAsync('git status --porcelain', { cwd, timeout: 5000 })\n conflictFiles = statusOut\n .trim()\n .split('\\n')\n .filter(line => line.startsWith('UU ') || line.startsWith('AA ') || line.startsWith('DD '))\n .map(line => line.slice(3))\n } catch {\n // Couldn't get conflict files\n }\n }\n\n return {\n success: false,\n error: 'REBASE_CONFLICT',\n output: `Rebase conflict in ${conflictFiles.length} file(s). Resolve conflicts then use rebase_continue, or use rebase_abort to cancel.`,\n details: {\n inRebase: true,\n rebaseConflicts: conflictFiles,\n hasConflicts: true,\n conflictedFiles: conflictFiles\n }\n }\n }\n\n throw rebaseError\n }\n\n return {\n success: true,\n output: `Successfully rebased ${command.branch} onto main`,\n details: {\n branchName: command.branch,\n inRebase: false\n }\n }\n } catch (error: any) {\n return {\n success: false,\n error: 'UNKNOWN_ERROR',\n output: error.message || 'Rebase failed'\n }\n }\n }\n\n /**\n * EP523: Abort an in-progress rebase\n * Returns to the state before rebase was started\n */\n private async executeRebaseAbort(\n cwd: string,\n options?: ExecutionOptions\n ): Promise<ExecutionResult> {\n try {\n await execAsync('git rebase --abort', { cwd, timeout: options?.timeout || 10000 })\n\n return {\n success: true,\n output: 'Rebase aborted. Your branch has been restored to its previous state.',\n details: {\n inRebase: false\n }\n }\n } catch (error: any) {\n // Check if there's no rebase in progress\n if (error.message?.includes('No rebase in progress') || error.stderr?.includes('No rebase in progress')) {\n return {\n success: true,\n output: 'No rebase in progress.',\n details: {\n inRebase: false\n }\n }\n }\n\n return {\n success: false,\n error: 'UNKNOWN_ERROR',\n output: error.message || 'Failed to abort rebase'\n }\n }\n }\n\n /**\n * EP523: Continue a paused rebase after conflicts are resolved\n */\n private async executeRebaseContinue(\n cwd: string,\n options?: ExecutionOptions\n ): Promise<ExecutionResult> {\n try {\n // Stage all resolved files\n await execAsync('git add -A', { cwd, timeout: 5000 })\n\n // Continue the rebase\n await execAsync('git rebase --continue', { cwd, timeout: options?.timeout || 60000 })\n\n return {\n success: true,\n output: 'Rebase continued successfully.',\n details: {\n inRebase: false\n }\n }\n } catch (error: any) {\n const errorOutput = (error.stderr || '') + (error.stdout || '')\n\n // Check if there are still conflicts\n if (errorOutput.includes('CONFLICT') || errorOutput.includes('could not apply')) {\n // Get remaining conflict files\n let conflictFiles: string[] = []\n try {\n const { stdout: conflictOutput } = await execAsync(\n 'git diff --name-only --diff-filter=U',\n { cwd, timeout: 5000 }\n )\n conflictFiles = conflictOutput.trim().split('\\n').filter(Boolean)\n } catch {\n // Ignore\n }\n\n return {\n success: false,\n error: 'REBASE_CONFLICT',\n output: 'More conflicts encountered. Resolve them and try again.',\n details: {\n inRebase: true,\n rebaseConflicts: conflictFiles,\n hasConflicts: true,\n conflictedFiles: conflictFiles\n }\n }\n }\n\n // Check if there's no rebase in progress\n if (errorOutput.includes('No rebase in progress')) {\n return {\n success: true,\n output: 'No rebase in progress.',\n details: {\n inRebase: false\n }\n }\n }\n\n return {\n success: false,\n error: 'UNKNOWN_ERROR',\n output: error.message || 'Failed to continue rebase'\n }\n }\n }\n\n /**\n * EP523: Check if a rebase is currently in progress\n */\n private async executeRebaseStatus(\n cwd: string,\n options?: ExecutionOptions\n ): Promise<ExecutionResult> {\n try {\n // Check for rebase-merge directory (indicates rebase in progress)\n let inRebase = false\n let rebaseConflicts: string[] = []\n\n try {\n const { stdout: gitDir } = await execAsync('git rev-parse --git-dir', { cwd, timeout: 5000 })\n const gitDirPath = gitDir.trim()\n\n // Check for rebase directories\n const fs = await import('fs').then(m => m.promises)\n const rebaseMergePath = `${gitDirPath}/rebase-merge`\n const rebaseApplyPath = `${gitDirPath}/rebase-apply`\n\n try {\n await fs.access(rebaseMergePath)\n inRebase = true\n } catch {\n try {\n await fs.access(rebaseApplyPath)\n inRebase = true\n } catch {\n inRebase = false\n }\n }\n } catch {\n // If we can't determine, check via status\n try {\n const { stdout: statusOutput } = await execAsync('git status', { cwd, timeout: 5000 })\n inRebase = statusOutput.includes('rebase in progress') ||\n statusOutput.includes('interactive rebase in progress') ||\n statusOutput.includes('You are currently rebasing')\n } catch {\n inRebase = false\n }\n }\n\n // If in rebase, get conflict files\n if (inRebase) {\n try {\n const { stdout: conflictOutput } = await execAsync(\n 'git diff --name-only --diff-filter=U',\n { cwd, timeout: 5000 }\n )\n rebaseConflicts = conflictOutput.trim().split('\\n').filter(Boolean)\n } catch {\n // No conflicts or couldn't get them\n }\n }\n\n return {\n success: true,\n output: inRebase\n ? `Rebase in progress with ${rebaseConflicts.length} conflicting file(s)`\n : 'No rebase in progress',\n details: {\n inRebase,\n rebaseConflicts,\n hasConflicts: rebaseConflicts.length > 0\n }\n }\n } catch (error: any) {\n return {\n success: false,\n error: 'UNKNOWN_ERROR',\n output: error.message || 'Failed to check rebase status'\n }\n }\n }\n\n // ========================================\n // EP944: Worktree operations\n // ========================================\n\n /**\n * EP944: Add a new worktree for a branch\n * Creates a new working tree at the specified path\n */\n private async executeWorktreeAdd(\n command: { path: string; branch?: string; create?: boolean; startPoint?: string; detach?: boolean },\n cwd: string,\n options?: ExecutionOptions\n ): Promise<ExecutionResult> {\n try {\n // EP1223: Skip branch validation for detached HEAD\n if (!command.detach && command.branch) {\n // Validate branch name\n const validation = validateBranchName(command.branch)\n if (!validation.valid) {\n return {\n success: false,\n error: validation.error || 'UNKNOWN_ERROR'\n }\n }\n }\n\n // Check if path already exists\n const fs = await import('fs').then(m => m.promises)\n try {\n await fs.access(command.path)\n return {\n success: false,\n error: 'WORKTREE_EXISTS',\n output: `Worktree already exists at path: ${command.path}`\n }\n } catch {\n // Path doesn't exist, which is what we want\n }\n\n // Fetch latest refs from remote to ensure branch exists\n // This is especially important for branches created after the initial clone\n try {\n await this.runGitCommand(['fetch', '--all', '--prune'], cwd, options)\n } catch {\n // Fetch failure is non-fatal - branch may be local or fetch may not be needed\n }\n\n // Build command\n const args = ['worktree', 'add']\n\n // EP1223: Handle detached HEAD for planning worktrees (read-only)\n if (command.detach) {\n args.push('--detach', command.path)\n // Add start point (commit/branch to detach from)\n if (command.startPoint) {\n args.push(command.startPoint)\n } else {\n args.push('HEAD') // Default to current HEAD\n }\n } else if (command.create) {\n args.push('-b', command.branch!, command.path)\n // EP996: Add start point for new branch to ensure fresh base\n if (command.startPoint) {\n args.push(command.startPoint)\n }\n } else {\n args.push(command.path, command.branch!)\n }\n\n const result = await this.runGitCommand(args, cwd, options)\n\n if (result.success) {\n // EP1223: Different output for detached HEAD\n const outputMsg = command.detach\n ? `Created detached worktree at ${command.path} from ${command.startPoint || 'HEAD'}`\n : `Created worktree at ${command.path} for branch ${command.branch}`\n return {\n success: true,\n output: outputMsg,\n details: {\n worktreePath: command.path,\n branchName: command.detach ? undefined : command.branch,\n detached: command.detach\n }\n }\n }\n\n // Check for specific error conditions\n if (result.output?.includes('already checked out')) {\n return {\n success: false,\n error: 'BRANCH_IN_USE',\n output: `Branch '${command.branch}' is already checked out in another worktree`\n }\n }\n\n return result\n } catch (error: any) {\n return {\n success: false,\n error: 'UNKNOWN_ERROR',\n output: error.message || 'Failed to add worktree'\n }\n }\n }\n\n /**\n * EP944: Remove a worktree\n * Removes the working tree at the specified path\n */\n private async executeWorktreeRemove(\n command: { path: string; force?: boolean },\n cwd: string,\n options?: ExecutionOptions\n ): Promise<ExecutionResult> {\n try {\n // Check if path exists\n const fs = await import('fs').then(m => m.promises)\n try {\n await fs.access(command.path)\n } catch {\n return {\n success: false,\n error: 'WORKTREE_NOT_FOUND',\n output: `Worktree not found at path: ${command.path}`\n }\n }\n\n // Check for uncommitted changes (unless force)\n if (!command.force) {\n try {\n const { stdout } = await execAsync('git status --porcelain', {\n cwd: command.path,\n timeout: options?.timeout || 10000\n })\n if (stdout.trim()) {\n return {\n success: false,\n error: 'UNCOMMITTED_CHANGES',\n output: 'Worktree has uncommitted changes. Use force to remove anyway.',\n details: {\n uncommittedFiles: stdout.trim().split('\\n').map(line => line.slice(3))\n }\n }\n }\n } catch {\n // If we can't check status, continue with removal\n }\n }\n\n // Build command\n const args = ['worktree', 'remove']\n if (command.force) {\n args.push('--force')\n }\n args.push(command.path)\n\n const result = await this.runGitCommand(args, cwd, options)\n\n if (result.success) {\n // EP1002: Clean up any remaining gitignored files (e.g., .next/, dist/, node_modules/)\n // git worktree remove only removes git-tracked files, leaving gitignored directories behind\n try {\n await fs.rm(command.path, { recursive: true, force: true })\n } catch {\n // Directory may already be gone if git removed it completely, ignore errors\n }\n\n return {\n success: true,\n output: `Removed worktree at ${command.path}`,\n details: {\n worktreePath: command.path\n }\n }\n }\n\n // Check for locked worktree\n if (result.output?.includes('locked')) {\n return {\n success: false,\n error: 'WORKTREE_LOCKED',\n output: `Worktree at ${command.path} is locked`\n }\n }\n\n return result\n } catch (error: any) {\n return {\n success: false,\n error: 'UNKNOWN_ERROR',\n output: error.message || 'Failed to remove worktree'\n }\n }\n }\n\n /**\n * EP944: List all worktrees\n * Returns information about all worktrees in the repository\n */\n private async executeWorktreeList(\n cwd: string,\n options?: ExecutionOptions\n ): Promise<ExecutionResult> {\n try {\n const { stdout } = await execAsync('git worktree list --porcelain', {\n cwd,\n timeout: options?.timeout || 10000\n })\n\n const worktrees: Array<{\n path: string\n branch: string\n commit: string\n locked?: boolean\n prunable?: boolean\n }> = []\n\n // Parse porcelain output\n // Format:\n // worktree /path/to/worktree\n // HEAD abc123...\n // branch refs/heads/branch-name\n // (blank line)\n const lines = stdout.trim().split('\\n')\n let current: Partial<{\n path: string\n branch: string\n commit: string\n locked: boolean\n prunable: boolean\n }> = {}\n\n for (const line of lines) {\n if (line.startsWith('worktree ')) {\n current.path = line.slice(9)\n } else if (line.startsWith('HEAD ')) {\n current.commit = line.slice(5)\n } else if (line.startsWith('branch ')) {\n // Extract branch name from refs/heads/branch-name\n const refPath = line.slice(7)\n current.branch = refPath.replace('refs/heads/', '')\n } else if (line === 'locked') {\n current.locked = true\n } else if (line === 'prunable') {\n current.prunable = true\n } else if (line.startsWith('detached')) {\n current.branch = 'HEAD (detached)'\n } else if (line === '' && current.path) {\n // End of entry\n worktrees.push({\n path: current.path,\n branch: current.branch || 'unknown',\n commit: current.commit || '',\n locked: current.locked,\n prunable: current.prunable\n })\n current = {}\n }\n }\n\n // Don't forget the last entry if output doesn't end with blank line\n if (current.path) {\n worktrees.push({\n path: current.path,\n branch: current.branch || 'unknown',\n commit: current.commit || '',\n locked: current.locked,\n prunable: current.prunable\n })\n }\n\n return {\n success: true,\n output: `Found ${worktrees.length} worktree(s)`,\n details: {\n worktrees\n }\n }\n } catch (error: any) {\n return {\n success: false,\n error: 'UNKNOWN_ERROR',\n output: error.message || 'Failed to list worktrees'\n }\n }\n }\n\n /**\n * EP944: Prune stale worktrees\n * Removes worktree administrative files for worktrees whose directories are missing\n */\n private async executeWorktreePrune(\n cwd: string,\n options?: ExecutionOptions\n ): Promise<ExecutionResult> {\n try {\n // First get list of prunable worktrees\n const listResult = await this.executeWorktreeList(cwd, options)\n const prunableCount = listResult.details?.worktrees?.filter(w => w.prunable).length || 0\n\n // Run prune\n const result = await this.runGitCommand(['worktree', 'prune'], cwd, options)\n\n if (result.success) {\n return {\n success: true,\n output: prunableCount > 0\n ? `Pruned ${prunableCount} stale worktree(s)`\n : 'No stale worktrees to prune',\n details: {\n prunedCount: prunableCount\n }\n }\n }\n\n return result\n } catch (error: any) {\n return {\n success: false,\n error: 'UNKNOWN_ERROR',\n output: error.message || 'Failed to prune worktrees'\n }\n }\n }\n\n /**\n * EP1002: Worktree setup command stub\n * The actual implementation is in the daemon which intercepts this command.\n * This stub exists for type checking and as a fallback.\n */\n private async executeWorktreeSetup(\n command: { path: string; moduleUid: string },\n cwd: string,\n options?: ExecutionOptions\n ): Promise<ExecutionResult> {\n // This should be intercepted by the daemon before reaching here\n // If we get here, it means the command was routed incorrectly\n return {\n success: false,\n error: 'NOT_IMPLEMENTED',\n output: 'worktree_setup must be handled by the daemon, not GitExecutor'\n }\n }\n\n /**\n * EP944: Clone a repository as a bare repository\n * Used for worktree-based development setup\n */\n private async executeCloneBare(\n command: { url: string; path: string },\n options?: ExecutionOptions\n ): Promise<ExecutionResult> {\n try {\n const fs = await import('fs').then(m => m.promises)\n const path = await import('path')\n\n // Check if path already exists\n try {\n await fs.access(command.path)\n return {\n success: false,\n error: 'BRANCH_ALREADY_EXISTS', // Reusing for path exists\n output: `Directory already exists at path: ${command.path}`\n }\n } catch {\n // Path doesn't exist, which is what we want\n }\n\n // Create parent directory if needed\n const parentDir = path.dirname(command.path)\n try {\n await fs.mkdir(parentDir, { recursive: true })\n } catch {\n // Directory might already exist\n }\n\n // Clone as bare repository\n const { stdout, stderr } = await execAsync(\n `git clone --bare \"${command.url}\" \"${command.path}\"`,\n { timeout: options?.timeout || 120000 } // 2 minutes for clone\n )\n\n // EP1014: Configure fetch refspec for bare repo\n // Without this, `git fetch origin` won't update refs/remotes/origin/* refs\n // This is required for worktree creation to use fresh origin/main\n try {\n await execAsync(\n `git config remote.origin.fetch \"+refs/heads/*:refs/remotes/origin/*\"`,\n { cwd: command.path, timeout: 5000 }\n )\n } catch (configError) {\n // Non-fatal but log it - fetches will need explicit refspecs\n console.error('[git-executor] EP1014: Failed to configure fetch refspec:', configError)\n }\n\n return {\n success: true,\n output: `Cloned bare repository to ${command.path}`,\n details: {\n worktreePath: command.path\n }\n }\n } catch (error: any) {\n // Check for auth errors\n if (error.message?.includes('Authentication') || error.message?.includes('Permission denied')) {\n return {\n success: false,\n error: 'AUTH_FAILURE',\n output: 'Authentication failed. Please check your credentials.'\n }\n }\n\n // Check for network errors\n if (error.message?.includes('Could not resolve') || error.message?.includes('unable to access')) {\n return {\n success: false,\n error: 'NETWORK_ERROR',\n output: 'Network error. Please check your connection.'\n }\n }\n\n return {\n success: false,\n error: 'UNKNOWN_ERROR',\n output: error.message || 'Failed to clone repository'\n }\n }\n }\n\n /**\n * EP944: Get project info including worktree mode\n * Returns information about the project configuration\n */\n private async executeProjectInfo(\n cwd: string,\n options?: ExecutionOptions\n ): Promise<ExecutionResult> {\n try {\n const fs = await import('fs').then(m => m.promises)\n const path = await import('path')\n\n // EP971: All projects use worktree architecture\n // Walk up to find the project root with .bare and .episoda directories\n let currentPath = cwd\n let projectPath = cwd\n let bareRepoPath: string | undefined\n\n for (let i = 0; i < 10; i++) {\n const bareDir = path.join(currentPath, '.bare')\n const episodaDir = path.join(currentPath, '.episoda')\n\n try {\n await fs.access(bareDir)\n await fs.access(episodaDir)\n\n // Found project root\n projectPath = currentPath\n bareRepoPath = bareDir\n break\n } catch {\n // Not found at this level, check parent\n const parentPath = path.dirname(currentPath)\n if (parentPath === currentPath) {\n break // Reached filesystem root\n }\n currentPath = parentPath\n }\n }\n\n return {\n success: true,\n output: bareRepoPath ? 'Episoda project' : 'Git repository',\n details: {\n projectPath,\n bareRepoPath\n }\n }\n } catch (error: any) {\n return {\n success: false,\n error: 'UNKNOWN_ERROR',\n output: error.message || 'Failed to get project info'\n }\n }\n }\n\n /**\n * Run a git command and return structured result\n */\n private async runGitCommand(\n args: string[],\n cwd: string,\n options?: ExecutionOptions & { env?: NodeJS.ProcessEnv }\n ): Promise<ExecutionResult> {\n try {\n // Sanitize arguments\n const sanitizedArgs = sanitizeArgs(args)\n\n // Build command\n const command = ['git', ...sanitizedArgs].join(' ')\n\n // Execute with timeout\n const timeout = options?.timeout || 30000 // 30 second default\n const execOptions = {\n cwd,\n timeout,\n env: options?.env || process.env,\n maxBuffer: 1024 * 1024 * 10 // 10MB buffer\n }\n\n const { stdout, stderr } = await execAsync(command, execOptions)\n\n // Combine output\n const output = (stdout + stderr).trim()\n\n // Extract additional details\n const details: ExecutionResult['details'] = {}\n\n // Try to extract branch name\n const branchName = extractBranchName(output)\n if (branchName) {\n details.branchName = branchName\n }\n\n // Check for detached HEAD\n if (isDetachedHead(output)) {\n details.branchName = 'HEAD (detached)'\n }\n\n return {\n success: true,\n output,\n details: Object.keys(details).length > 0 ? details : undefined\n }\n } catch (error: any) {\n // Parse error\n const stderr = error.stderr || ''\n const stdout = error.stdout || ''\n const exitCode = error.code || 1\n\n // Determine error code\n const errorCode = parseGitError(stderr, stdout, exitCode)\n\n // Extract additional details based on error type\n const details: ExecutionResult['details'] = {\n exitCode\n }\n\n // Parse conflicts if merge conflict\n if (errorCode === 'MERGE_CONFLICT') {\n const conflicts = parseMergeConflicts(stdout + stderr)\n if (conflicts.length > 0) {\n details.conflictingFiles = conflicts\n }\n }\n\n // Parse status for uncommitted changes\n if (errorCode === 'UNCOMMITTED_CHANGES') {\n try {\n const statusResult = await this.executeStatus(cwd, options)\n if (statusResult.details?.uncommittedFiles) {\n details.uncommittedFiles = statusResult.details.uncommittedFiles\n }\n } catch {\n // Ignore errors when getting status\n }\n }\n\n return {\n success: false,\n error: errorCode,\n output: (stdout + stderr).trim(),\n details\n }\n }\n }\n\n /**\n * Validate that git is installed\n */\n private async validateGitInstalled(): Promise<boolean> {\n try {\n await execAsync('git --version', { timeout: 5000 })\n return true\n } catch {\n return false\n }\n }\n\n /**\n * Check if directory is a git repository\n */\n private async isGitRepository(cwd: string): Promise<boolean> {\n try {\n await execAsync('git rev-parse --git-dir', { cwd, timeout: 5000 })\n return true\n } catch {\n return false\n }\n }\n\n /**\n * Detect the git working directory (repository root)\n * @returns Path to the git repository root\n */\n private async detectWorkingDirectory(startPath?: string): Promise<string | null> {\n try {\n const { stdout } = await execAsync('git rev-parse --show-toplevel', {\n cwd: startPath || process.cwd(),\n timeout: 5000\n })\n return stdout.trim()\n } catch {\n return null\n }\n }\n}\n","'use strict';\n\nconst BINARY_TYPES = ['nodebuffer', 'arraybuffer', 'fragments'];\nconst hasBlob = typeof Blob !== 'undefined';\n\nif (hasBlob) BINARY_TYPES.push('blob');\n\nmodule.exports = {\n BINARY_TYPES,\n EMPTY_BUFFER: Buffer.alloc(0),\n GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11',\n hasBlob,\n kForOnEventAttribute: Symbol('kIsForOnEventAttribute'),\n kListener: Symbol('kListener'),\n kStatusCode: Symbol('status-code'),\n kWebSocket: Symbol('websocket'),\n NOOP: () => {}\n};\n","'use strict';\n\nconst { EMPTY_BUFFER } = require('./constants');\n\nconst FastBuffer = Buffer[Symbol.species];\n\n/**\n * Merges an array of buffers into a new buffer.\n *\n * @param {Buffer[]} list The array of buffers to concat\n * @param {Number} totalLength The total length of buffers in the list\n * @return {Buffer} The resulting buffer\n * @public\n */\nfunction concat(list, totalLength) {\n if (list.length === 0) return EMPTY_BUFFER;\n if (list.length === 1) return list[0];\n\n const target = Buffer.allocUnsafe(totalLength);\n let offset = 0;\n\n for (let i = 0; i < list.length; i++) {\n const buf = list[i];\n target.set(buf, offset);\n offset += buf.length;\n }\n\n if (offset < totalLength) {\n return new FastBuffer(target.buffer, target.byteOffset, offset);\n }\n\n return target;\n}\n\n/**\n * Masks a buffer using the given mask.\n *\n * @param {Buffer} source The buffer to mask\n * @param {Buffer} mask The mask to use\n * @param {Buffer} output The buffer where to store the result\n * @param {Number} offset The offset at which to start writing\n * @param {Number} length The number of bytes to mask.\n * @public\n */\nfunction _mask(source, mask, output, offset, length) {\n for (let i = 0; i < length; i++) {\n output[offset + i] = source[i] ^ mask[i & 3];\n }\n}\n\n/**\n * Unmasks a buffer using the given mask.\n *\n * @param {Buffer} buffer The buffer to unmask\n * @param {Buffer} mask The mask to use\n * @public\n */\nfunction _unmask(buffer, mask) {\n for (let i = 0; i < buffer.length; i++) {\n buffer[i] ^= mask[i & 3];\n }\n}\n\n/**\n * Converts a buffer to an `ArrayBuffer`.\n *\n * @param {Buffer} buf The buffer to convert\n * @return {ArrayBuffer} Converted buffer\n * @public\n */\nfunction toArrayBuffer(buf) {\n if (buf.length === buf.buffer.byteLength) {\n return buf.buffer;\n }\n\n return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);\n}\n\n/**\n * Converts `data` to a `Buffer`.\n *\n * @param {*} data The data to convert\n * @return {Buffer} The buffer\n * @throws {TypeError}\n * @public\n */\nfunction toBuffer(data) {\n toBuffer.readOnly = true;\n\n if (Buffer.isBuffer(data)) return data;\n\n let buf;\n\n if (data instanceof ArrayBuffer) {\n buf = new FastBuffer(data);\n } else if (ArrayBuffer.isView(data)) {\n buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);\n } else {\n buf = Buffer.from(data);\n toBuffer.readOnly = false;\n }\n\n return buf;\n}\n\nmodule.exports = {\n concat,\n mask: _mask,\n toArrayBuffer,\n toBuffer,\n unmask: _unmask\n};\n\n/* istanbul ignore else */\nif (!process.env.WS_NO_BUFFER_UTIL) {\n try {\n const bufferUtil = require('bufferutil');\n\n module.exports.mask = function (source, mask, output, offset, length) {\n if (length < 48) _mask(source, mask, output, offset, length);\n else bufferUtil.mask(source, mask, output, offset, length);\n };\n\n module.exports.unmask = function (buffer, mask) {\n if (buffer.length < 32) _unmask(buffer, mask);\n else bufferUtil.unmask(buffer, mask);\n };\n } catch (e) {\n // Continue regardless of the error.\n }\n}\n","'use strict';\n\nconst kDone = Symbol('kDone');\nconst kRun = Symbol('kRun');\n\n/**\n * A very simple job queue with adjustable concurrency. Adapted from\n * https://github.com/STRML/async-limiter\n */\nclass Limiter {\n /**\n * Creates a new `Limiter`.\n *\n * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed\n * to run concurrently\n */\n constructor(concurrency) {\n this[kDone] = () => {\n this.pending--;\n this[kRun]();\n };\n this.concurrency = concurrency || Infinity;\n this.jobs = [];\n this.pending = 0;\n }\n\n /**\n * Adds a job to the queue.\n *\n * @param {Function} job The job to run\n * @public\n */\n add(job) {\n this.jobs.push(job);\n this[kRun]();\n }\n\n /**\n * Removes a job from the queue and runs it if possible.\n *\n * @private\n */\n [kRun]() {\n if (this.pending === this.concurrency) return;\n\n if (this.jobs.length) {\n const job = this.jobs.shift();\n\n this.pending++;\n job(this[kDone]);\n }\n }\n}\n\nmodule.exports = Limiter;\n","'use strict';\n\nconst zlib = require('zlib');\n\nconst bufferUtil = require('./buffer-util');\nconst Limiter = require('./limiter');\nconst { kStatusCode } = require('./constants');\n\nconst FastBuffer = Buffer[Symbol.species];\nconst TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]);\nconst kPerMessageDeflate = Symbol('permessage-deflate');\nconst kTotalLength = Symbol('total-length');\nconst kCallback = Symbol('callback');\nconst kBuffers = Symbol('buffers');\nconst kError = Symbol('error');\n\n//\n// We limit zlib concurrency, which prevents severe memory fragmentation\n// as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913\n// and https://github.com/websockets/ws/issues/1202\n//\n// Intentionally global; it's the global thread pool that's an issue.\n//\nlet zlibLimiter;\n\n/**\n * permessage-deflate implementation.\n */\nclass PerMessageDeflate {\n /**\n * Creates a PerMessageDeflate instance.\n *\n * @param {Object} [options] Configuration options\n * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support\n * for, or request, a custom client window size\n * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/\n * acknowledge disabling of client context takeover\n * @param {Number} [options.concurrencyLimit=10] The number of concurrent\n * calls to zlib\n * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the\n * use of a custom server window size\n * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept\n * disabling of server context takeover\n * @param {Number} [options.threshold=1024] Size (in bytes) below which\n * messages should not be compressed if context takeover is disabled\n * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on\n * deflate\n * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on\n * inflate\n * @param {Boolean} [isServer=false] Create the instance in either server or\n * client mode\n * @param {Number} [maxPayload=0] The maximum allowed message length\n */\n constructor(options, isServer, maxPayload) {\n this._maxPayload = maxPayload | 0;\n this._options = options || {};\n this._threshold =\n this._options.threshold !== undefined ? this._options.threshold : 1024;\n this._isServer = !!isServer;\n this._deflate = null;\n this._inflate = null;\n\n this.params = null;\n\n if (!zlibLimiter) {\n const concurrency =\n this._options.concurrencyLimit !== undefined\n ? this._options.concurrencyLimit\n : 10;\n zlibLimiter = new Limiter(concurrency);\n }\n }\n\n /**\n * @type {String}\n */\n static get extensionName() {\n return 'permessage-deflate';\n }\n\n /**\n * Create an extension negotiation offer.\n *\n * @return {Object} Extension parameters\n * @public\n */\n offer() {\n const params = {};\n\n if (this._options.serverNoContextTakeover) {\n params.server_no_context_takeover = true;\n }\n if (this._options.clientNoContextTakeover) {\n params.client_no_context_takeover = true;\n }\n if (this._options.serverMaxWindowBits) {\n params.server_max_window_bits = this._options.serverMaxWindowBits;\n }\n if (this._options.clientMaxWindowBits) {\n params.client_max_window_bits = this._options.clientMaxWindowBits;\n } else if (this._options.clientMaxWindowBits == null) {\n params.client_max_window_bits = true;\n }\n\n return params;\n }\n\n /**\n * Accept an extension negotiation offer/response.\n *\n * @param {Array} configurations The extension negotiation offers/reponse\n * @return {Object} Accepted configuration\n * @public\n */\n accept(configurations) {\n configurations = this.normalizeParams(configurations);\n\n this.params = this._isServer\n ? this.acceptAsServer(configurations)\n : this.acceptAsClient(configurations);\n\n return this.params;\n }\n\n /**\n * Releases all resources used by the extension.\n *\n * @public\n */\n cleanup() {\n if (this._inflate) {\n this._inflate.close();\n this._inflate = null;\n }\n\n if (this._deflate) {\n const callback = this._deflate[kCallback];\n\n this._deflate.close();\n this._deflate = null;\n\n if (callback) {\n callback(\n new Error(\n 'The deflate stream was closed while data was being processed'\n )\n );\n }\n }\n }\n\n /**\n * Accept an extension negotiation offer.\n *\n * @param {Array} offers The extension negotiation offers\n * @return {Object} Accepted configuration\n * @private\n */\n acceptAsServer(offers) {\n const opts = this._options;\n const accepted = offers.find((params) => {\n if (\n (opts.serverNoContextTakeover === false &&\n params.server_no_context_takeover) ||\n (params.server_max_window_bits &&\n (opts.serverMaxWindowBits === false ||\n (typeof opts.serverMaxWindowBits === 'number' &&\n opts.serverMaxWindowBits > params.server_max_window_bits))) ||\n (typeof opts.clientMaxWindowBits === 'number' &&\n !params.client_max_window_bits)\n ) {\n return false;\n }\n\n return true;\n });\n\n if (!accepted) {\n throw new Error('None of the extension offers can be accepted');\n }\n\n if (opts.serverNoContextTakeover) {\n accepted.server_no_context_takeover = true;\n }\n if (opts.clientNoContextTakeover) {\n accepted.client_no_context_takeover = true;\n }\n if (typeof opts.serverMaxWindowBits === 'number') {\n accepted.server_max_window_bits = opts.serverMaxWindowBits;\n }\n if (typeof opts.clientMaxWindowBits === 'number') {\n accepted.client_max_window_bits = opts.clientMaxWindowBits;\n } else if (\n accepted.client_max_window_bits === true ||\n opts.clientMaxWindowBits === false\n ) {\n delete accepted.client_max_window_bits;\n }\n\n return accepted;\n }\n\n /**\n * Accept the extension negotiation response.\n *\n * @param {Array} response The extension negotiation response\n * @return {Object} Accepted configuration\n * @private\n */\n acceptAsClient(response) {\n const params = response[0];\n\n if (\n this._options.clientNoContextTakeover === false &&\n params.client_no_context_takeover\n ) {\n throw new Error('Unexpected parameter \"client_no_context_takeover\"');\n }\n\n if (!params.client_max_window_bits) {\n if (typeof this._options.clientMaxWindowBits === 'number') {\n params.client_max_window_bits = this._options.clientMaxWindowBits;\n }\n } else if (\n this._options.clientMaxWindowBits === false ||\n (typeof this._options.clientMaxWindowBits === 'number' &&\n params.client_max_window_bits > this._options.clientMaxWindowBits)\n ) {\n throw new Error(\n 'Unexpected or invalid parameter \"client_max_window_bits\"'\n );\n }\n\n return params;\n }\n\n /**\n * Normalize parameters.\n *\n * @param {Array} configurations The extension negotiation offers/reponse\n * @return {Array} The offers/response with normalized parameters\n * @private\n */\n normalizeParams(configurations) {\n configurations.forEach((params) => {\n Object.keys(params).forEach((key) => {\n let value = params[key];\n\n if (value.length > 1) {\n throw new Error(`Parameter \"${key}\" must have only a single value`);\n }\n\n value = value[0];\n\n if (key === 'client_max_window_bits') {\n if (value !== true) {\n const num = +value;\n if (!Number.isInteger(num) || num < 8 || num > 15) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n value = num;\n } else if (!this._isServer) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n } else if (key === 'server_max_window_bits') {\n const num = +value;\n if (!Number.isInteger(num) || num < 8 || num > 15) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n value = num;\n } else if (\n key === 'client_no_context_takeover' ||\n key === 'server_no_context_takeover'\n ) {\n if (value !== true) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n } else {\n throw new Error(`Unknown parameter \"${key}\"`);\n }\n\n params[key] = value;\n });\n });\n\n return configurations;\n }\n\n /**\n * Decompress data. Concurrency limited.\n *\n * @param {Buffer} data Compressed data\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @public\n */\n decompress(data, fin, callback) {\n zlibLimiter.add((done) => {\n this._decompress(data, fin, (err, result) => {\n done();\n callback(err, result);\n });\n });\n }\n\n /**\n * Compress data. Concurrency limited.\n *\n * @param {(Buffer|String)} data Data to compress\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @public\n */\n compress(data, fin, callback) {\n zlibLimiter.add((done) => {\n this._compress(data, fin, (err, result) => {\n done();\n callback(err, result);\n });\n });\n }\n\n /**\n * Decompress data.\n *\n * @param {Buffer} data Compressed data\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @private\n */\n _decompress(data, fin, callback) {\n const endpoint = this._isServer ? 'client' : 'server';\n\n if (!this._inflate) {\n const key = `${endpoint}_max_window_bits`;\n const windowBits =\n typeof this.params[key] !== 'number'\n ? zlib.Z_DEFAULT_WINDOWBITS\n : this.params[key];\n\n this._inflate = zlib.createInflateRaw({\n ...this._options.zlibInflateOptions,\n windowBits\n });\n this._inflate[kPerMessageDeflate] = this;\n this._inflate[kTotalLength] = 0;\n this._inflate[kBuffers] = [];\n this._inflate.on('error', inflateOnError);\n this._inflate.on('data', inflateOnData);\n }\n\n this._inflate[kCallback] = callback;\n\n this._inflate.write(data);\n if (fin) this._inflate.write(TRAILER);\n\n this._inflate.flush(() => {\n const err = this._inflate[kError];\n\n if (err) {\n this._inflate.close();\n this._inflate = null;\n callback(err);\n return;\n }\n\n const data = bufferUtil.concat(\n this._inflate[kBuffers],\n this._inflate[kTotalLength]\n );\n\n if (this._inflate._readableState.endEmitted) {\n this._inflate.close();\n this._inflate = null;\n } else {\n this._inflate[kTotalLength] = 0;\n this._inflate[kBuffers] = [];\n\n if (fin && this.params[`${endpoint}_no_context_takeover`]) {\n this._inflate.reset();\n }\n }\n\n callback(null, data);\n });\n }\n\n /**\n * Compress data.\n *\n * @param {(Buffer|String)} data Data to compress\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @private\n */\n _compress(data, fin, callback) {\n const endpoint = this._isServer ? 'server' : 'client';\n\n if (!this._deflate) {\n const key = `${endpoint}_max_window_bits`;\n const windowBits =\n typeof this.params[key] !== 'number'\n ? zlib.Z_DEFAULT_WINDOWBITS\n : this.params[key];\n\n this._deflate = zlib.createDeflateRaw({\n ...this._options.zlibDeflateOptions,\n windowBits\n });\n\n this._deflate[kTotalLength] = 0;\n this._deflate[kBuffers] = [];\n\n this._deflate.on('data', deflateOnData);\n }\n\n this._deflate[kCallback] = callback;\n\n this._deflate.write(data);\n this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {\n if (!this._deflate) {\n //\n // The deflate stream was closed while data was being processed.\n //\n return;\n }\n\n let data = bufferUtil.concat(\n this._deflate[kBuffers],\n this._deflate[kTotalLength]\n );\n\n if (fin) {\n data = new FastBuffer(data.buffer, data.byteOffset, data.length - 4);\n }\n\n //\n // Ensure that the callback will not be called again in\n // `PerMessageDeflate#cleanup()`.\n //\n this._deflate[kCallback] = null;\n\n this._deflate[kTotalLength] = 0;\n this._deflate[kBuffers] = [];\n\n if (fin && this.params[`${endpoint}_no_context_takeover`]) {\n this._deflate.reset();\n }\n\n callback(null, data);\n });\n }\n}\n\nmodule.exports = PerMessageDeflate;\n\n/**\n * The listener of the `zlib.DeflateRaw` stream `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction deflateOnData(chunk) {\n this[kBuffers].push(chunk);\n this[kTotalLength] += chunk.length;\n}\n\n/**\n * The listener of the `zlib.InflateRaw` stream `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction inflateOnData(chunk) {\n this[kTotalLength] += chunk.length;\n\n if (\n this[kPerMessageDeflate]._maxPayload < 1 ||\n this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload\n ) {\n this[kBuffers].push(chunk);\n return;\n }\n\n this[kError] = new RangeError('Max payload size exceeded');\n this[kError].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH';\n this[kError][kStatusCode] = 1009;\n this.removeListener('data', inflateOnData);\n\n //\n // The choice to employ `zlib.reset()` over `zlib.close()` is dictated by the\n // fact that in Node.js versions prior to 13.10.0, the callback for\n // `zlib.flush()` is not called if `zlib.close()` is used. Utilizing\n // `zlib.reset()` ensures that either the callback is invoked or an error is\n // emitted.\n //\n this.reset();\n}\n\n/**\n * The listener of the `zlib.InflateRaw` stream `'error'` event.\n *\n * @param {Error} err The emitted error\n * @private\n */\nfunction inflateOnError(err) {\n //\n // There is no need to call `Zlib#close()` as the handle is automatically\n // closed when an error is emitted.\n //\n this[kPerMessageDeflate]._inflate = null;\n\n if (this[kError]) {\n this[kCallback](this[kError]);\n return;\n }\n\n err[kStatusCode] = 1007;\n this[kCallback](err);\n}\n","'use strict';\n\nconst { isUtf8 } = require('buffer');\n\nconst { hasBlob } = require('./constants');\n\n//\n// Allowed token characters:\n//\n// '!', '#', '$', '%', '&', ''', '*', '+', '-',\n// '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~'\n//\n// tokenChars[32] === 0 // ' '\n// tokenChars[33] === 1 // '!'\n// tokenChars[34] === 0 // '\"'\n// ...\n//\n// prettier-ignore\nconst tokenChars = [\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31\n 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63\n 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127\n];\n\n/**\n * Checks if a status code is allowed in a close frame.\n *\n * @param {Number} code The status code\n * @return {Boolean} `true` if the status code is valid, else `false`\n * @public\n */\nfunction isValidStatusCode(code) {\n return (\n (code >= 1000 &&\n code <= 1014 &&\n code !== 1004 &&\n code !== 1005 &&\n code !== 1006) ||\n (code >= 3000 && code <= 4999)\n );\n}\n\n/**\n * Checks if a given buffer contains only correct UTF-8.\n * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by\n * Markus Kuhn.\n *\n * @param {Buffer} buf The buffer to check\n * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`\n * @public\n */\nfunction _isValidUTF8(buf) {\n const len = buf.length;\n let i = 0;\n\n while (i < len) {\n if ((buf[i] & 0x80) === 0) {\n // 0xxxxxxx\n i++;\n } else if ((buf[i] & 0xe0) === 0xc0) {\n // 110xxxxx 10xxxxxx\n if (\n i + 1 === len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i] & 0xfe) === 0xc0 // Overlong\n ) {\n return false;\n }\n\n i += 2;\n } else if ((buf[i] & 0xf0) === 0xe0) {\n // 1110xxxx 10xxxxxx 10xxxxxx\n if (\n i + 2 >= len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i + 2] & 0xc0) !== 0x80 ||\n (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong\n (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF)\n ) {\n return false;\n }\n\n i += 3;\n } else if ((buf[i] & 0xf8) === 0xf0) {\n // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\n if (\n i + 3 >= len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i + 2] & 0xc0) !== 0x80 ||\n (buf[i + 3] & 0xc0) !== 0x80 ||\n (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong\n (buf[i] === 0xf4 && buf[i + 1] > 0x8f) ||\n buf[i] > 0xf4 // > U+10FFFF\n ) {\n return false;\n }\n\n i += 4;\n } else {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Determines whether a value is a `Blob`.\n *\n * @param {*} value The value to be tested\n * @return {Boolean} `true` if `value` is a `Blob`, else `false`\n * @private\n */\nfunction isBlob(value) {\n return (\n hasBlob &&\n typeof value === 'object' &&\n typeof value.arrayBuffer === 'function' &&\n typeof value.type === 'string' &&\n typeof value.stream === 'function' &&\n (value[Symbol.toStringTag] === 'Blob' ||\n value[Symbol.toStringTag] === 'File')\n );\n}\n\nmodule.exports = {\n isBlob,\n isValidStatusCode,\n isValidUTF8: _isValidUTF8,\n tokenChars\n};\n\nif (isUtf8) {\n module.exports.isValidUTF8 = function (buf) {\n return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);\n };\n} /* istanbul ignore else */ else if (!process.env.WS_NO_UTF_8_VALIDATE) {\n try {\n const isValidUTF8 = require('utf-8-validate');\n\n module.exports.isValidUTF8 = function (buf) {\n return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);\n };\n } catch (e) {\n // Continue regardless of the error.\n }\n}\n","'use strict';\n\nconst { Writable } = require('stream');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst {\n BINARY_TYPES,\n EMPTY_BUFFER,\n kStatusCode,\n kWebSocket\n} = require('./constants');\nconst { concat, toArrayBuffer, unmask } = require('./buffer-util');\nconst { isValidStatusCode, isValidUTF8 } = require('./validation');\n\nconst FastBuffer = Buffer[Symbol.species];\n\nconst GET_INFO = 0;\nconst GET_PAYLOAD_LENGTH_16 = 1;\nconst GET_PAYLOAD_LENGTH_64 = 2;\nconst GET_MASK = 3;\nconst GET_DATA = 4;\nconst INFLATING = 5;\nconst DEFER_EVENT = 6;\n\n/**\n * HyBi Receiver implementation.\n *\n * @extends Writable\n */\nclass Receiver extends Writable {\n /**\n * Creates a Receiver instance.\n *\n * @param {Object} [options] Options object\n * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether\n * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted\n * multiple times in the same tick\n * @param {String} [options.binaryType=nodebuffer] The type for binary data\n * @param {Object} [options.extensions] An object containing the negotiated\n * extensions\n * @param {Boolean} [options.isServer=false] Specifies whether to operate in\n * client or server mode\n * @param {Number} [options.maxPayload=0] The maximum allowed message length\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n */\n constructor(options = {}) {\n super();\n\n this._allowSynchronousEvents =\n options.allowSynchronousEvents !== undefined\n ? options.allowSynchronousEvents\n : true;\n this._binaryType = options.binaryType || BINARY_TYPES[0];\n this._extensions = options.extensions || {};\n this._isServer = !!options.isServer;\n this._maxPayload = options.maxPayload | 0;\n this._skipUTF8Validation = !!options.skipUTF8Validation;\n this[kWebSocket] = undefined;\n\n this._bufferedBytes = 0;\n this._buffers = [];\n\n this._compressed = false;\n this._payloadLength = 0;\n this._mask = undefined;\n this._fragmented = 0;\n this._masked = false;\n this._fin = false;\n this._opcode = 0;\n\n this._totalPayloadLength = 0;\n this._messageLength = 0;\n this._fragments = [];\n\n this._errored = false;\n this._loop = false;\n this._state = GET_INFO;\n }\n\n /**\n * Implements `Writable.prototype._write()`.\n *\n * @param {Buffer} chunk The chunk of data to write\n * @param {String} encoding The character encoding of `chunk`\n * @param {Function} cb Callback\n * @private\n */\n _write(chunk, encoding, cb) {\n if (this._opcode === 0x08 && this._state == GET_INFO) return cb();\n\n this._bufferedBytes += chunk.length;\n this._buffers.push(chunk);\n this.startLoop(cb);\n }\n\n /**\n * Consumes `n` bytes from the buffered data.\n *\n * @param {Number} n The number of bytes to consume\n * @return {Buffer} The consumed bytes\n * @private\n */\n consume(n) {\n this._bufferedBytes -= n;\n\n if (n === this._buffers[0].length) return this._buffers.shift();\n\n if (n < this._buffers[0].length) {\n const buf = this._buffers[0];\n this._buffers[0] = new FastBuffer(\n buf.buffer,\n buf.byteOffset + n,\n buf.length - n\n );\n\n return new FastBuffer(buf.buffer, buf.byteOffset, n);\n }\n\n const dst = Buffer.allocUnsafe(n);\n\n do {\n const buf = this._buffers[0];\n const offset = dst.length - n;\n\n if (n >= buf.length) {\n dst.set(this._buffers.shift(), offset);\n } else {\n dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);\n this._buffers[0] = new FastBuffer(\n buf.buffer,\n buf.byteOffset + n,\n buf.length - n\n );\n }\n\n n -= buf.length;\n } while (n > 0);\n\n return dst;\n }\n\n /**\n * Starts the parsing loop.\n *\n * @param {Function} cb Callback\n * @private\n */\n startLoop(cb) {\n this._loop = true;\n\n do {\n switch (this._state) {\n case GET_INFO:\n this.getInfo(cb);\n break;\n case GET_PAYLOAD_LENGTH_16:\n this.getPayloadLength16(cb);\n break;\n case GET_PAYLOAD_LENGTH_64:\n this.getPayloadLength64(cb);\n break;\n case GET_MASK:\n this.getMask();\n break;\n case GET_DATA:\n this.getData(cb);\n break;\n case INFLATING:\n case DEFER_EVENT:\n this._loop = false;\n return;\n }\n } while (this._loop);\n\n if (!this._errored) cb();\n }\n\n /**\n * Reads the first two bytes of a frame.\n *\n * @param {Function} cb Callback\n * @private\n */\n getInfo(cb) {\n if (this._bufferedBytes < 2) {\n this._loop = false;\n return;\n }\n\n const buf = this.consume(2);\n\n if ((buf[0] & 0x30) !== 0x00) {\n const error = this.createError(\n RangeError,\n 'RSV2 and RSV3 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_2_3'\n );\n\n cb(error);\n return;\n }\n\n const compressed = (buf[0] & 0x40) === 0x40;\n\n if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {\n const error = this.createError(\n RangeError,\n 'RSV1 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_1'\n );\n\n cb(error);\n return;\n }\n\n this._fin = (buf[0] & 0x80) === 0x80;\n this._opcode = buf[0] & 0x0f;\n this._payloadLength = buf[1] & 0x7f;\n\n if (this._opcode === 0x00) {\n if (compressed) {\n const error = this.createError(\n RangeError,\n 'RSV1 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_1'\n );\n\n cb(error);\n return;\n }\n\n if (!this._fragmented) {\n const error = this.createError(\n RangeError,\n 'invalid opcode 0',\n true,\n 1002,\n 'WS_ERR_INVALID_OPCODE'\n );\n\n cb(error);\n return;\n }\n\n this._opcode = this._fragmented;\n } else if (this._opcode === 0x01 || this._opcode === 0x02) {\n if (this._fragmented) {\n const error = this.createError(\n RangeError,\n `invalid opcode ${this._opcode}`,\n true,\n 1002,\n 'WS_ERR_INVALID_OPCODE'\n );\n\n cb(error);\n return;\n }\n\n this._compressed = compressed;\n } else if (this._opcode > 0x07 && this._opcode < 0x0b) {\n if (!this._fin) {\n const error = this.createError(\n RangeError,\n 'FIN must be set',\n true,\n 1002,\n 'WS_ERR_EXPECTED_FIN'\n );\n\n cb(error);\n return;\n }\n\n if (compressed) {\n const error = this.createError(\n RangeError,\n 'RSV1 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_1'\n );\n\n cb(error);\n return;\n }\n\n if (\n this._payloadLength > 0x7d ||\n (this._opcode === 0x08 && this._payloadLength === 1)\n ) {\n const error = this.createError(\n RangeError,\n `invalid payload length ${this._payloadLength}`,\n true,\n 1002,\n 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH'\n );\n\n cb(error);\n return;\n }\n } else {\n const error = this.createError(\n RangeError,\n `invalid opcode ${this._opcode}`,\n true,\n 1002,\n 'WS_ERR_INVALID_OPCODE'\n );\n\n cb(error);\n return;\n }\n\n if (!this._fin && !this._fragmented) this._fragmented = this._opcode;\n this._masked = (buf[1] & 0x80) === 0x80;\n\n if (this._isServer) {\n if (!this._masked) {\n const error = this.createError(\n RangeError,\n 'MASK must be set',\n true,\n 1002,\n 'WS_ERR_EXPECTED_MASK'\n );\n\n cb(error);\n return;\n }\n } else if (this._masked) {\n const error = this.createError(\n RangeError,\n 'MASK must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_MASK'\n );\n\n cb(error);\n return;\n }\n\n if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;\n else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;\n else this.haveLength(cb);\n }\n\n /**\n * Gets extended payload length (7+16).\n *\n * @param {Function} cb Callback\n * @private\n */\n getPayloadLength16(cb) {\n if (this._bufferedBytes < 2) {\n this._loop = false;\n return;\n }\n\n this._payloadLength = this.consume(2).readUInt16BE(0);\n this.haveLength(cb);\n }\n\n /**\n * Gets extended payload length (7+64).\n *\n * @param {Function} cb Callback\n * @private\n */\n getPayloadLength64(cb) {\n if (this._bufferedBytes < 8) {\n this._loop = false;\n return;\n }\n\n const buf = this.consume(8);\n const num = buf.readUInt32BE(0);\n\n //\n // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned\n // if payload length is greater than this number.\n //\n if (num > Math.pow(2, 53 - 32) - 1) {\n const error = this.createError(\n RangeError,\n 'Unsupported WebSocket frame: payload length > 2^53 - 1',\n false,\n 1009,\n 'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH'\n );\n\n cb(error);\n return;\n }\n\n this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);\n this.haveLength(cb);\n }\n\n /**\n * Payload length has been read.\n *\n * @param {Function} cb Callback\n * @private\n */\n haveLength(cb) {\n if (this._payloadLength && this._opcode < 0x08) {\n this._totalPayloadLength += this._payloadLength;\n if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {\n const error = this.createError(\n RangeError,\n 'Max payload size exceeded',\n false,\n 1009,\n 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'\n );\n\n cb(error);\n return;\n }\n }\n\n if (this._masked) this._state = GET_MASK;\n else this._state = GET_DATA;\n }\n\n /**\n * Reads mask bytes.\n *\n * @private\n */\n getMask() {\n if (this._bufferedBytes < 4) {\n this._loop = false;\n return;\n }\n\n this._mask = this.consume(4);\n this._state = GET_DATA;\n }\n\n /**\n * Reads data bytes.\n *\n * @param {Function} cb Callback\n * @private\n */\n getData(cb) {\n let data = EMPTY_BUFFER;\n\n if (this._payloadLength) {\n if (this._bufferedBytes < this._payloadLength) {\n this._loop = false;\n return;\n }\n\n data = this.consume(this._payloadLength);\n\n if (\n this._masked &&\n (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0\n ) {\n unmask(data, this._mask);\n }\n }\n\n if (this._opcode > 0x07) {\n this.controlMessage(data, cb);\n return;\n }\n\n if (this._compressed) {\n this._state = INFLATING;\n this.decompress(data, cb);\n return;\n }\n\n if (data.length) {\n //\n // This message is not compressed so its length is the sum of the payload\n // length of all fragments.\n //\n this._messageLength = this._totalPayloadLength;\n this._fragments.push(data);\n }\n\n this.dataMessage(cb);\n }\n\n /**\n * Decompresses data.\n *\n * @param {Buffer} data Compressed data\n * @param {Function} cb Callback\n * @private\n */\n decompress(data, cb) {\n const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n\n perMessageDeflate.decompress(data, this._fin, (err, buf) => {\n if (err) return cb(err);\n\n if (buf.length) {\n this._messageLength += buf.length;\n if (this._messageLength > this._maxPayload && this._maxPayload > 0) {\n const error = this.createError(\n RangeError,\n 'Max payload size exceeded',\n false,\n 1009,\n 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'\n );\n\n cb(error);\n return;\n }\n\n this._fragments.push(buf);\n }\n\n this.dataMessage(cb);\n if (this._state === GET_INFO) this.startLoop(cb);\n });\n }\n\n /**\n * Handles a data message.\n *\n * @param {Function} cb Callback\n * @private\n */\n dataMessage(cb) {\n if (!this._fin) {\n this._state = GET_INFO;\n return;\n }\n\n const messageLength = this._messageLength;\n const fragments = this._fragments;\n\n this._totalPayloadLength = 0;\n this._messageLength = 0;\n this._fragmented = 0;\n this._fragments = [];\n\n if (this._opcode === 2) {\n let data;\n\n if (this._binaryType === 'nodebuffer') {\n data = concat(fragments, messageLength);\n } else if (this._binaryType === 'arraybuffer') {\n data = toArrayBuffer(concat(fragments, messageLength));\n } else if (this._binaryType === 'blob') {\n data = new Blob(fragments);\n } else {\n data = fragments;\n }\n\n if (this._allowSynchronousEvents) {\n this.emit('message', data, true);\n this._state = GET_INFO;\n } else {\n this._state = DEFER_EVENT;\n setImmediate(() => {\n this.emit('message', data, true);\n this._state = GET_INFO;\n this.startLoop(cb);\n });\n }\n } else {\n const buf = concat(fragments, messageLength);\n\n if (!this._skipUTF8Validation && !isValidUTF8(buf)) {\n const error = this.createError(\n Error,\n 'invalid UTF-8 sequence',\n true,\n 1007,\n 'WS_ERR_INVALID_UTF8'\n );\n\n cb(error);\n return;\n }\n\n if (this._state === INFLATING || this._allowSynchronousEvents) {\n this.emit('message', buf, false);\n this._state = GET_INFO;\n } else {\n this._state = DEFER_EVENT;\n setImmediate(() => {\n this.emit('message', buf, false);\n this._state = GET_INFO;\n this.startLoop(cb);\n });\n }\n }\n }\n\n /**\n * Handles a control message.\n *\n * @param {Buffer} data Data to handle\n * @return {(Error|RangeError|undefined)} A possible error\n * @private\n */\n controlMessage(data, cb) {\n if (this._opcode === 0x08) {\n if (data.length === 0) {\n this._loop = false;\n this.emit('conclude', 1005, EMPTY_BUFFER);\n this.end();\n } else {\n const code = data.readUInt16BE(0);\n\n if (!isValidStatusCode(code)) {\n const error = this.createError(\n RangeError,\n `invalid status code ${code}`,\n true,\n 1002,\n 'WS_ERR_INVALID_CLOSE_CODE'\n );\n\n cb(error);\n return;\n }\n\n const buf = new FastBuffer(\n data.buffer,\n data.byteOffset + 2,\n data.length - 2\n );\n\n if (!this._skipUTF8Validation && !isValidUTF8(buf)) {\n const error = this.createError(\n Error,\n 'invalid UTF-8 sequence',\n true,\n 1007,\n 'WS_ERR_INVALID_UTF8'\n );\n\n cb(error);\n return;\n }\n\n this._loop = false;\n this.emit('conclude', code, buf);\n this.end();\n }\n\n this._state = GET_INFO;\n return;\n }\n\n if (this._allowSynchronousEvents) {\n this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);\n this._state = GET_INFO;\n } else {\n this._state = DEFER_EVENT;\n setImmediate(() => {\n this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);\n this._state = GET_INFO;\n this.startLoop(cb);\n });\n }\n }\n\n /**\n * Builds an error object.\n *\n * @param {function(new:Error|RangeError)} ErrorCtor The error constructor\n * @param {String} message The error message\n * @param {Boolean} prefix Specifies whether or not to add a default prefix to\n * `message`\n * @param {Number} statusCode The status code\n * @param {String} errorCode The exposed error code\n * @return {(Error|RangeError)} The error\n * @private\n */\n createError(ErrorCtor, message, prefix, statusCode, errorCode) {\n this._loop = false;\n this._errored = true;\n\n const err = new ErrorCtor(\n prefix ? `Invalid WebSocket frame: ${message}` : message\n );\n\n Error.captureStackTrace(err, this.createError);\n err.code = errorCode;\n err[kStatusCode] = statusCode;\n return err;\n }\n}\n\nmodule.exports = Receiver;\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^Duplex\" }] */\n\n'use strict';\n\nconst { Duplex } = require('stream');\nconst { randomFillSync } = require('crypto');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst { EMPTY_BUFFER, kWebSocket, NOOP } = require('./constants');\nconst { isBlob, isValidStatusCode } = require('./validation');\nconst { mask: applyMask, toBuffer } = require('./buffer-util');\n\nconst kByteLength = Symbol('kByteLength');\nconst maskBuffer = Buffer.alloc(4);\nconst RANDOM_POOL_SIZE = 8 * 1024;\nlet randomPool;\nlet randomPoolPointer = RANDOM_POOL_SIZE;\n\nconst DEFAULT = 0;\nconst DEFLATING = 1;\nconst GET_BLOB_DATA = 2;\n\n/**\n * HyBi Sender implementation.\n */\nclass Sender {\n /**\n * Creates a Sender instance.\n *\n * @param {Duplex} socket The connection socket\n * @param {Object} [extensions] An object containing the negotiated extensions\n * @param {Function} [generateMask] The function used to generate the masking\n * key\n */\n constructor(socket, extensions, generateMask) {\n this._extensions = extensions || {};\n\n if (generateMask) {\n this._generateMask = generateMask;\n this._maskBuffer = Buffer.alloc(4);\n }\n\n this._socket = socket;\n\n this._firstFragment = true;\n this._compress = false;\n\n this._bufferedBytes = 0;\n this._queue = [];\n this._state = DEFAULT;\n this.onerror = NOOP;\n this[kWebSocket] = undefined;\n }\n\n /**\n * Frames a piece of data according to the HyBi WebSocket protocol.\n *\n * @param {(Buffer|String)} data The data to frame\n * @param {Object} options Options object\n * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n * FIN bit\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Buffer} [options.maskBuffer] The buffer used to store the masking\n * key\n * @param {Number} options.opcode The opcode\n * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n * modified\n * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n * RSV1 bit\n * @return {(Buffer|String)[]} The framed data\n * @public\n */\n static frame(data, options) {\n let mask;\n let merge = false;\n let offset = 2;\n let skipMasking = false;\n\n if (options.mask) {\n mask = options.maskBuffer || maskBuffer;\n\n if (options.generateMask) {\n options.generateMask(mask);\n } else {\n if (randomPoolPointer === RANDOM_POOL_SIZE) {\n /* istanbul ignore else */\n if (randomPool === undefined) {\n //\n // This is lazily initialized because server-sent frames must not\n // be masked so it may never be used.\n //\n randomPool = Buffer.alloc(RANDOM_POOL_SIZE);\n }\n\n randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);\n randomPoolPointer = 0;\n }\n\n mask[0] = randomPool[randomPoolPointer++];\n mask[1] = randomPool[randomPoolPointer++];\n mask[2] = randomPool[randomPoolPointer++];\n mask[3] = randomPool[randomPoolPointer++];\n }\n\n skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;\n offset = 6;\n }\n\n let dataLength;\n\n if (typeof data === 'string') {\n if (\n (!options.mask || skipMasking) &&\n options[kByteLength] !== undefined\n ) {\n dataLength = options[kByteLength];\n } else {\n data = Buffer.from(data);\n dataLength = data.length;\n }\n } else {\n dataLength = data.length;\n merge = options.mask && options.readOnly && !skipMasking;\n }\n\n let payloadLength = dataLength;\n\n if (dataLength >= 65536) {\n offset += 8;\n payloadLength = 127;\n } else if (dataLength > 125) {\n offset += 2;\n payloadLength = 126;\n }\n\n const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);\n\n target[0] = options.fin ? options.opcode | 0x80 : options.opcode;\n if (options.rsv1) target[0] |= 0x40;\n\n target[1] = payloadLength;\n\n if (payloadLength === 126) {\n target.writeUInt16BE(dataLength, 2);\n } else if (payloadLength === 127) {\n target[2] = target[3] = 0;\n target.writeUIntBE(dataLength, 4, 6);\n }\n\n if (!options.mask) return [target, data];\n\n target[1] |= 0x80;\n target[offset - 4] = mask[0];\n target[offset - 3] = mask[1];\n target[offset - 2] = mask[2];\n target[offset - 1] = mask[3];\n\n if (skipMasking) return [target, data];\n\n if (merge) {\n applyMask(data, mask, target, offset, dataLength);\n return [target];\n }\n\n applyMask(data, mask, data, 0, dataLength);\n return [target, data];\n }\n\n /**\n * Sends a close message to the other peer.\n *\n * @param {Number} [code] The status code component of the body\n * @param {(String|Buffer)} [data] The message component of the body\n * @param {Boolean} [mask=false] Specifies whether or not to mask the message\n * @param {Function} [cb] Callback\n * @public\n */\n close(code, data, mask, cb) {\n let buf;\n\n if (code === undefined) {\n buf = EMPTY_BUFFER;\n } else if (typeof code !== 'number' || !isValidStatusCode(code)) {\n throw new TypeError('First argument must be a valid error code number');\n } else if (data === undefined || !data.length) {\n buf = Buffer.allocUnsafe(2);\n buf.writeUInt16BE(code, 0);\n } else {\n const length = Buffer.byteLength(data);\n\n if (length > 123) {\n throw new RangeError('The message must not be greater than 123 bytes');\n }\n\n buf = Buffer.allocUnsafe(2 + length);\n buf.writeUInt16BE(code, 0);\n\n if (typeof data === 'string') {\n buf.write(data, 2);\n } else {\n buf.set(data, 2);\n }\n }\n\n const options = {\n [kByteLength]: buf.length,\n fin: true,\n generateMask: this._generateMask,\n mask,\n maskBuffer: this._maskBuffer,\n opcode: 0x08,\n readOnly: false,\n rsv1: false\n };\n\n if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, buf, false, options, cb]);\n } else {\n this.sendFrame(Sender.frame(buf, options), cb);\n }\n }\n\n /**\n * Sends a ping message to the other peer.\n *\n * @param {*} data The message to send\n * @param {Boolean} [mask=false] Specifies whether or not to mask `data`\n * @param {Function} [cb] Callback\n * @public\n */\n ping(data, mask, cb) {\n let byteLength;\n let readOnly;\n\n if (typeof data === 'string') {\n byteLength = Buffer.byteLength(data);\n readOnly = false;\n } else if (isBlob(data)) {\n byteLength = data.size;\n readOnly = false;\n } else {\n data = toBuffer(data);\n byteLength = data.length;\n readOnly = toBuffer.readOnly;\n }\n\n if (byteLength > 125) {\n throw new RangeError('The data size must not be greater than 125 bytes');\n }\n\n const options = {\n [kByteLength]: byteLength,\n fin: true,\n generateMask: this._generateMask,\n mask,\n maskBuffer: this._maskBuffer,\n opcode: 0x09,\n readOnly,\n rsv1: false\n };\n\n if (isBlob(data)) {\n if (this._state !== DEFAULT) {\n this.enqueue([this.getBlobData, data, false, options, cb]);\n } else {\n this.getBlobData(data, false, options, cb);\n }\n } else if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, data, false, options, cb]);\n } else {\n this.sendFrame(Sender.frame(data, options), cb);\n }\n }\n\n /**\n * Sends a pong message to the other peer.\n *\n * @param {*} data The message to send\n * @param {Boolean} [mask=false] Specifies whether or not to mask `data`\n * @param {Function} [cb] Callback\n * @public\n */\n pong(data, mask, cb) {\n let byteLength;\n let readOnly;\n\n if (typeof data === 'string') {\n byteLength = Buffer.byteLength(data);\n readOnly = false;\n } else if (isBlob(data)) {\n byteLength = data.size;\n readOnly = false;\n } else {\n data = toBuffer(data);\n byteLength = data.length;\n readOnly = toBuffer.readOnly;\n }\n\n if (byteLength > 125) {\n throw new RangeError('The data size must not be greater than 125 bytes');\n }\n\n const options = {\n [kByteLength]: byteLength,\n fin: true,\n generateMask: this._generateMask,\n mask,\n maskBuffer: this._maskBuffer,\n opcode: 0x0a,\n readOnly,\n rsv1: false\n };\n\n if (isBlob(data)) {\n if (this._state !== DEFAULT) {\n this.enqueue([this.getBlobData, data, false, options, cb]);\n } else {\n this.getBlobData(data, false, options, cb);\n }\n } else if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, data, false, options, cb]);\n } else {\n this.sendFrame(Sender.frame(data, options), cb);\n }\n }\n\n /**\n * Sends a data message to the other peer.\n *\n * @param {*} data The message to send\n * @param {Object} options Options object\n * @param {Boolean} [options.binary=false] Specifies whether `data` is binary\n * or text\n * @param {Boolean} [options.compress=false] Specifies whether or not to\n * compress `data`\n * @param {Boolean} [options.fin=false] Specifies whether the fragment is the\n * last one\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Function} [cb] Callback\n * @public\n */\n send(data, options, cb) {\n const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n let opcode = options.binary ? 2 : 1;\n let rsv1 = options.compress;\n\n let byteLength;\n let readOnly;\n\n if (typeof data === 'string') {\n byteLength = Buffer.byteLength(data);\n readOnly = false;\n } else if (isBlob(data)) {\n byteLength = data.size;\n readOnly = false;\n } else {\n data = toBuffer(data);\n byteLength = data.length;\n readOnly = toBuffer.readOnly;\n }\n\n if (this._firstFragment) {\n this._firstFragment = false;\n if (\n rsv1 &&\n perMessageDeflate &&\n perMessageDeflate.params[\n perMessageDeflate._isServer\n ? 'server_no_context_takeover'\n : 'client_no_context_takeover'\n ]\n ) {\n rsv1 = byteLength >= perMessageDeflate._threshold;\n }\n this._compress = rsv1;\n } else {\n rsv1 = false;\n opcode = 0;\n }\n\n if (options.fin) this._firstFragment = true;\n\n const opts = {\n [kByteLength]: byteLength,\n fin: options.fin,\n generateMask: this._generateMask,\n mask: options.mask,\n maskBuffer: this._maskBuffer,\n opcode,\n readOnly,\n rsv1\n };\n\n if (isBlob(data)) {\n if (this._state !== DEFAULT) {\n this.enqueue([this.getBlobData, data, this._compress, opts, cb]);\n } else {\n this.getBlobData(data, this._compress, opts, cb);\n }\n } else if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, data, this._compress, opts, cb]);\n } else {\n this.dispatch(data, this._compress, opts, cb);\n }\n }\n\n /**\n * Gets the contents of a blob as binary data.\n *\n * @param {Blob} blob The blob\n * @param {Boolean} [compress=false] Specifies whether or not to compress\n * the data\n * @param {Object} options Options object\n * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n * FIN bit\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Buffer} [options.maskBuffer] The buffer used to store the masking\n * key\n * @param {Number} options.opcode The opcode\n * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n * modified\n * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n * RSV1 bit\n * @param {Function} [cb] Callback\n * @private\n */\n getBlobData(blob, compress, options, cb) {\n this._bufferedBytes += options[kByteLength];\n this._state = GET_BLOB_DATA;\n\n blob\n .arrayBuffer()\n .then((arrayBuffer) => {\n if (this._socket.destroyed) {\n const err = new Error(\n 'The socket was closed while the blob was being read'\n );\n\n //\n // `callCallbacks` is called in the next tick to ensure that errors\n // that might be thrown in the callbacks behave like errors thrown\n // outside the promise chain.\n //\n process.nextTick(callCallbacks, this, err, cb);\n return;\n }\n\n this._bufferedBytes -= options[kByteLength];\n const data = toBuffer(arrayBuffer);\n\n if (!compress) {\n this._state = DEFAULT;\n this.sendFrame(Sender.frame(data, options), cb);\n this.dequeue();\n } else {\n this.dispatch(data, compress, options, cb);\n }\n })\n .catch((err) => {\n //\n // `onError` is called in the next tick for the same reason that\n // `callCallbacks` above is.\n //\n process.nextTick(onError, this, err, cb);\n });\n }\n\n /**\n * Dispatches a message.\n *\n * @param {(Buffer|String)} data The message to send\n * @param {Boolean} [compress=false] Specifies whether or not to compress\n * `data`\n * @param {Object} options Options object\n * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n * FIN bit\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Buffer} [options.maskBuffer] The buffer used to store the masking\n * key\n * @param {Number} options.opcode The opcode\n * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n * modified\n * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n * RSV1 bit\n * @param {Function} [cb] Callback\n * @private\n */\n dispatch(data, compress, options, cb) {\n if (!compress) {\n this.sendFrame(Sender.frame(data, options), cb);\n return;\n }\n\n const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n\n this._bufferedBytes += options[kByteLength];\n this._state = DEFLATING;\n perMessageDeflate.compress(data, options.fin, (_, buf) => {\n if (this._socket.destroyed) {\n const err = new Error(\n 'The socket was closed while data was being compressed'\n );\n\n callCallbacks(this, err, cb);\n return;\n }\n\n this._bufferedBytes -= options[kByteLength];\n this._state = DEFAULT;\n options.readOnly = false;\n this.sendFrame(Sender.frame(buf, options), cb);\n this.dequeue();\n });\n }\n\n /**\n * Executes queued send operations.\n *\n * @private\n */\n dequeue() {\n while (this._state === DEFAULT && this._queue.length) {\n const params = this._queue.shift();\n\n this._bufferedBytes -= params[3][kByteLength];\n Reflect.apply(params[0], this, params.slice(1));\n }\n }\n\n /**\n * Enqueues a send operation.\n *\n * @param {Array} params Send operation parameters.\n * @private\n */\n enqueue(params) {\n this._bufferedBytes += params[3][kByteLength];\n this._queue.push(params);\n }\n\n /**\n * Sends a frame.\n *\n * @param {(Buffer | String)[]} list The frame to send\n * @param {Function} [cb] Callback\n * @private\n */\n sendFrame(list, cb) {\n if (list.length === 2) {\n this._socket.cork();\n this._socket.write(list[0]);\n this._socket.write(list[1], cb);\n this._socket.uncork();\n } else {\n this._socket.write(list[0], cb);\n }\n }\n}\n\nmodule.exports = Sender;\n\n/**\n * Calls queued callbacks with an error.\n *\n * @param {Sender} sender The `Sender` instance\n * @param {Error} err The error to call the callbacks with\n * @param {Function} [cb] The first callback\n * @private\n */\nfunction callCallbacks(sender, err, cb) {\n if (typeof cb === 'function') cb(err);\n\n for (let i = 0; i < sender._queue.length; i++) {\n const params = sender._queue[i];\n const callback = params[params.length - 1];\n\n if (typeof callback === 'function') callback(err);\n }\n}\n\n/**\n * Handles a `Sender` error.\n *\n * @param {Sender} sender The `Sender` instance\n * @param {Error} err The error\n * @param {Function} [cb] The first pending callback\n * @private\n */\nfunction onError(sender, err, cb) {\n callCallbacks(sender, err, cb);\n sender.onerror(err);\n}\n","'use strict';\n\nconst { kForOnEventAttribute, kListener } = require('./constants');\n\nconst kCode = Symbol('kCode');\nconst kData = Symbol('kData');\nconst kError = Symbol('kError');\nconst kMessage = Symbol('kMessage');\nconst kReason = Symbol('kReason');\nconst kTarget = Symbol('kTarget');\nconst kType = Symbol('kType');\nconst kWasClean = Symbol('kWasClean');\n\n/**\n * Class representing an event.\n */\nclass Event {\n /**\n * Create a new `Event`.\n *\n * @param {String} type The name of the event\n * @throws {TypeError} If the `type` argument is not specified\n */\n constructor(type) {\n this[kTarget] = null;\n this[kType] = type;\n }\n\n /**\n * @type {*}\n */\n get target() {\n return this[kTarget];\n }\n\n /**\n * @type {String}\n */\n get type() {\n return this[kType];\n }\n}\n\nObject.defineProperty(Event.prototype, 'target', { enumerable: true });\nObject.defineProperty(Event.prototype, 'type', { enumerable: true });\n\n/**\n * Class representing a close event.\n *\n * @extends Event\n */\nclass CloseEvent extends Event {\n /**\n * Create a new `CloseEvent`.\n *\n * @param {String} type The name of the event\n * @param {Object} [options] A dictionary object that allows for setting\n * attributes via object members of the same name\n * @param {Number} [options.code=0] The status code explaining why the\n * connection was closed\n * @param {String} [options.reason=''] A human-readable string explaining why\n * the connection was closed\n * @param {Boolean} [options.wasClean=false] Indicates whether or not the\n * connection was cleanly closed\n */\n constructor(type, options = {}) {\n super(type);\n\n this[kCode] = options.code === undefined ? 0 : options.code;\n this[kReason] = options.reason === undefined ? '' : options.reason;\n this[kWasClean] = options.wasClean === undefined ? false : options.wasClean;\n }\n\n /**\n * @type {Number}\n */\n get code() {\n return this[kCode];\n }\n\n /**\n * @type {String}\n */\n get reason() {\n return this[kReason];\n }\n\n /**\n * @type {Boolean}\n */\n get wasClean() {\n return this[kWasClean];\n }\n}\n\nObject.defineProperty(CloseEvent.prototype, 'code', { enumerable: true });\nObject.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true });\nObject.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true });\n\n/**\n * Class representing an error event.\n *\n * @extends Event\n */\nclass ErrorEvent extends Event {\n /**\n * Create a new `ErrorEvent`.\n *\n * @param {String} type The name of the event\n * @param {Object} [options] A dictionary object that allows for setting\n * attributes via object members of the same name\n * @param {*} [options.error=null] The error that generated this event\n * @param {String} [options.message=''] The error message\n */\n constructor(type, options = {}) {\n super(type);\n\n this[kError] = options.error === undefined ? null : options.error;\n this[kMessage] = options.message === undefined ? '' : options.message;\n }\n\n /**\n * @type {*}\n */\n get error() {\n return this[kError];\n }\n\n /**\n * @type {String}\n */\n get message() {\n return this[kMessage];\n }\n}\n\nObject.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true });\nObject.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true });\n\n/**\n * Class representing a message event.\n *\n * @extends Event\n */\nclass MessageEvent extends Event {\n /**\n * Create a new `MessageEvent`.\n *\n * @param {String} type The name of the event\n * @param {Object} [options] A dictionary object that allows for setting\n * attributes via object members of the same name\n * @param {*} [options.data=null] The message content\n */\n constructor(type, options = {}) {\n super(type);\n\n this[kData] = options.data === undefined ? null : options.data;\n }\n\n /**\n * @type {*}\n */\n get data() {\n return this[kData];\n }\n}\n\nObject.defineProperty(MessageEvent.prototype, 'data', { enumerable: true });\n\n/**\n * This provides methods for emulating the `EventTarget` interface. It's not\n * meant to be used directly.\n *\n * @mixin\n */\nconst EventTarget = {\n /**\n * Register an event listener.\n *\n * @param {String} type A string representing the event type to listen for\n * @param {(Function|Object)} handler The listener to add\n * @param {Object} [options] An options object specifies characteristics about\n * the event listener\n * @param {Boolean} [options.once=false] A `Boolean` indicating that the\n * listener should be invoked at most once after being added. If `true`,\n * the listener would be automatically removed when invoked.\n * @public\n */\n addEventListener(type, handler, options = {}) {\n for (const listener of this.listeners(type)) {\n if (\n !options[kForOnEventAttribute] &&\n listener[kListener] === handler &&\n !listener[kForOnEventAttribute]\n ) {\n return;\n }\n }\n\n let wrapper;\n\n if (type === 'message') {\n wrapper = function onMessage(data, isBinary) {\n const event = new MessageEvent('message', {\n data: isBinary ? data : data.toString()\n });\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else if (type === 'close') {\n wrapper = function onClose(code, message) {\n const event = new CloseEvent('close', {\n code,\n reason: message.toString(),\n wasClean: this._closeFrameReceived && this._closeFrameSent\n });\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else if (type === 'error') {\n wrapper = function onError(error) {\n const event = new ErrorEvent('error', {\n error,\n message: error.message\n });\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else if (type === 'open') {\n wrapper = function onOpen() {\n const event = new Event('open');\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else {\n return;\n }\n\n wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];\n wrapper[kListener] = handler;\n\n if (options.once) {\n this.once(type, wrapper);\n } else {\n this.on(type, wrapper);\n }\n },\n\n /**\n * Remove an event listener.\n *\n * @param {String} type A string representing the event type to remove\n * @param {(Function|Object)} handler The listener to remove\n * @public\n */\n removeEventListener(type, handler) {\n for (const listener of this.listeners(type)) {\n if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {\n this.removeListener(type, listener);\n break;\n }\n }\n }\n};\n\nmodule.exports = {\n CloseEvent,\n ErrorEvent,\n Event,\n EventTarget,\n MessageEvent\n};\n\n/**\n * Call an event listener\n *\n * @param {(Function|Object)} listener The listener to call\n * @param {*} thisArg The value to use as `this`` when calling the listener\n * @param {Event} event The event to pass to the listener\n * @private\n */\nfunction callListener(listener, thisArg, event) {\n if (typeof listener === 'object' && listener.handleEvent) {\n listener.handleEvent.call(listener, event);\n } else {\n listener.call(thisArg, event);\n }\n}\n","'use strict';\n\nconst { tokenChars } = require('./validation');\n\n/**\n * Adds an offer to the map of extension offers or a parameter to the map of\n * parameters.\n *\n * @param {Object} dest The map of extension offers or parameters\n * @param {String} name The extension or parameter name\n * @param {(Object|Boolean|String)} elem The extension parameters or the\n * parameter value\n * @private\n */\nfunction push(dest, name, elem) {\n if (dest[name] === undefined) dest[name] = [elem];\n else dest[name].push(elem);\n}\n\n/**\n * Parses the `Sec-WebSocket-Extensions` header into an object.\n *\n * @param {String} header The field value of the header\n * @return {Object} The parsed object\n * @public\n */\nfunction parse(header) {\n const offers = Object.create(null);\n let params = Object.create(null);\n let mustUnescape = false;\n let isEscaping = false;\n let inQuotes = false;\n let extensionName;\n let paramName;\n let start = -1;\n let code = -1;\n let end = -1;\n let i = 0;\n\n for (; i < header.length; i++) {\n code = header.charCodeAt(i);\n\n if (extensionName === undefined) {\n if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (\n i !== 0 &&\n (code === 0x20 /* ' ' */ || code === 0x09) /* '\\t' */\n ) {\n if (end === -1 && start !== -1) end = i;\n } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n const name = header.slice(start, end);\n if (code === 0x2c) {\n push(offers, name, params);\n params = Object.create(null);\n } else {\n extensionName = name;\n }\n\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n } else if (paramName === undefined) {\n if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (code === 0x20 || code === 0x09) {\n if (end === -1 && start !== -1) end = i;\n } else if (code === 0x3b || code === 0x2c) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n push(params, header.slice(start, end), true);\n if (code === 0x2c) {\n push(offers, extensionName, params);\n params = Object.create(null);\n extensionName = undefined;\n }\n\n start = end = -1;\n } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) {\n paramName = header.slice(start, i);\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n } else {\n //\n // The value of a quoted-string after unescaping must conform to the\n // token ABNF, so only token characters are valid.\n // Ref: https://tools.ietf.org/html/rfc6455#section-9.1\n //\n if (isEscaping) {\n if (tokenChars[code] !== 1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n if (start === -1) start = i;\n else if (!mustUnescape) mustUnescape = true;\n isEscaping = false;\n } else if (inQuotes) {\n if (tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (code === 0x22 /* '\"' */ && start !== -1) {\n inQuotes = false;\n end = i;\n } else if (code === 0x5c /* '\\' */) {\n isEscaping = true;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) {\n inQuotes = true;\n } else if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (start !== -1 && (code === 0x20 || code === 0x09)) {\n if (end === -1) end = i;\n } else if (code === 0x3b || code === 0x2c) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n let value = header.slice(start, end);\n if (mustUnescape) {\n value = value.replace(/\\\\/g, '');\n mustUnescape = false;\n }\n push(params, paramName, value);\n if (code === 0x2c) {\n push(offers, extensionName, params);\n params = Object.create(null);\n extensionName = undefined;\n }\n\n paramName = undefined;\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n }\n }\n\n if (start === -1 || inQuotes || code === 0x20 || code === 0x09) {\n throw new SyntaxError('Unexpected end of input');\n }\n\n if (end === -1) end = i;\n const token = header.slice(start, end);\n if (extensionName === undefined) {\n push(offers, token, params);\n } else {\n if (paramName === undefined) {\n push(params, token, true);\n } else if (mustUnescape) {\n push(params, paramName, token.replace(/\\\\/g, ''));\n } else {\n push(params, paramName, token);\n }\n push(offers, extensionName, params);\n }\n\n return offers;\n}\n\n/**\n * Builds the `Sec-WebSocket-Extensions` header field value.\n *\n * @param {Object} extensions The map of extensions and parameters to format\n * @return {String} A string representing the given object\n * @public\n */\nfunction format(extensions) {\n return Object.keys(extensions)\n .map((extension) => {\n let configurations = extensions[extension];\n if (!Array.isArray(configurations)) configurations = [configurations];\n return configurations\n .map((params) => {\n return [extension]\n .concat(\n Object.keys(params).map((k) => {\n let values = params[k];\n if (!Array.isArray(values)) values = [values];\n return values\n .map((v) => (v === true ? k : `${k}=${v}`))\n .join('; ');\n })\n )\n .join('; ');\n })\n .join(', ');\n })\n .join(', ');\n}\n\nmodule.exports = { format, parse };\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^Duplex|Readable$\", \"caughtErrors\": \"none\" }] */\n\n'use strict';\n\nconst EventEmitter = require('events');\nconst https = require('https');\nconst http = require('http');\nconst net = require('net');\nconst tls = require('tls');\nconst { randomBytes, createHash } = require('crypto');\nconst { Duplex, Readable } = require('stream');\nconst { URL } = require('url');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst Receiver = require('./receiver');\nconst Sender = require('./sender');\nconst { isBlob } = require('./validation');\n\nconst {\n BINARY_TYPES,\n EMPTY_BUFFER,\n GUID,\n kForOnEventAttribute,\n kListener,\n kStatusCode,\n kWebSocket,\n NOOP\n} = require('./constants');\nconst {\n EventTarget: { addEventListener, removeEventListener }\n} = require('./event-target');\nconst { format, parse } = require('./extension');\nconst { toBuffer } = require('./buffer-util');\n\nconst closeTimeout = 30 * 1000;\nconst kAborted = Symbol('kAborted');\nconst protocolVersions = [8, 13];\nconst readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];\nconst subprotocolRegex = /^[!#$%&'*+\\-.0-9A-Z^_`|a-z~]+$/;\n\n/**\n * Class representing a WebSocket.\n *\n * @extends EventEmitter\n */\nclass WebSocket extends EventEmitter {\n /**\n * Create a new `WebSocket`.\n *\n * @param {(String|URL)} address The URL to which to connect\n * @param {(String|String[])} [protocols] The subprotocols\n * @param {Object} [options] Connection options\n */\n constructor(address, protocols, options) {\n super();\n\n this._binaryType = BINARY_TYPES[0];\n this._closeCode = 1006;\n this._closeFrameReceived = false;\n this._closeFrameSent = false;\n this._closeMessage = EMPTY_BUFFER;\n this._closeTimer = null;\n this._errorEmitted = false;\n this._extensions = {};\n this._paused = false;\n this._protocol = '';\n this._readyState = WebSocket.CONNECTING;\n this._receiver = null;\n this._sender = null;\n this._socket = null;\n\n if (address !== null) {\n this._bufferedAmount = 0;\n this._isServer = false;\n this._redirects = 0;\n\n if (protocols === undefined) {\n protocols = [];\n } else if (!Array.isArray(protocols)) {\n if (typeof protocols === 'object' && protocols !== null) {\n options = protocols;\n protocols = [];\n } else {\n protocols = [protocols];\n }\n }\n\n initAsClient(this, address, protocols, options);\n } else {\n this._autoPong = options.autoPong;\n this._isServer = true;\n }\n }\n\n /**\n * For historical reasons, the custom \"nodebuffer\" type is used by the default\n * instead of \"blob\".\n *\n * @type {String}\n */\n get binaryType() {\n return this._binaryType;\n }\n\n set binaryType(type) {\n if (!BINARY_TYPES.includes(type)) return;\n\n this._binaryType = type;\n\n //\n // Allow to change `binaryType` on the fly.\n //\n if (this._receiver) this._receiver._binaryType = type;\n }\n\n /**\n * @type {Number}\n */\n get bufferedAmount() {\n if (!this._socket) return this._bufferedAmount;\n\n return this._socket._writableState.length + this._sender._bufferedBytes;\n }\n\n /**\n * @type {String}\n */\n get extensions() {\n return Object.keys(this._extensions).join();\n }\n\n /**\n * @type {Boolean}\n */\n get isPaused() {\n return this._paused;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onclose() {\n return null;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onerror() {\n return null;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onopen() {\n return null;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onmessage() {\n return null;\n }\n\n /**\n * @type {String}\n */\n get protocol() {\n return this._protocol;\n }\n\n /**\n * @type {Number}\n */\n get readyState() {\n return this._readyState;\n }\n\n /**\n * @type {String}\n */\n get url() {\n return this._url;\n }\n\n /**\n * Set up the socket and the internal resources.\n *\n * @param {Duplex} socket The network socket between the server and client\n * @param {Buffer} head The first packet of the upgraded stream\n * @param {Object} options Options object\n * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether\n * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted\n * multiple times in the same tick\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Number} [options.maxPayload=0] The maximum allowed message size\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n * @private\n */\n setSocket(socket, head, options) {\n const receiver = new Receiver({\n allowSynchronousEvents: options.allowSynchronousEvents,\n binaryType: this.binaryType,\n extensions: this._extensions,\n isServer: this._isServer,\n maxPayload: options.maxPayload,\n skipUTF8Validation: options.skipUTF8Validation\n });\n\n const sender = new Sender(socket, this._extensions, options.generateMask);\n\n this._receiver = receiver;\n this._sender = sender;\n this._socket = socket;\n\n receiver[kWebSocket] = this;\n sender[kWebSocket] = this;\n socket[kWebSocket] = this;\n\n receiver.on('conclude', receiverOnConclude);\n receiver.on('drain', receiverOnDrain);\n receiver.on('error', receiverOnError);\n receiver.on('message', receiverOnMessage);\n receiver.on('ping', receiverOnPing);\n receiver.on('pong', receiverOnPong);\n\n sender.onerror = senderOnError;\n\n //\n // These methods may not be available if `socket` is just a `Duplex`.\n //\n if (socket.setTimeout) socket.setTimeout(0);\n if (socket.setNoDelay) socket.setNoDelay();\n\n if (head.length > 0) socket.unshift(head);\n\n socket.on('close', socketOnClose);\n socket.on('data', socketOnData);\n socket.on('end', socketOnEnd);\n socket.on('error', socketOnError);\n\n this._readyState = WebSocket.OPEN;\n this.emit('open');\n }\n\n /**\n * Emit the `'close'` event.\n *\n * @private\n */\n emitClose() {\n if (!this._socket) {\n this._readyState = WebSocket.CLOSED;\n this.emit('close', this._closeCode, this._closeMessage);\n return;\n }\n\n if (this._extensions[PerMessageDeflate.extensionName]) {\n this._extensions[PerMessageDeflate.extensionName].cleanup();\n }\n\n this._receiver.removeAllListeners();\n this._readyState = WebSocket.CLOSED;\n this.emit('close', this._closeCode, this._closeMessage);\n }\n\n /**\n * Start a closing handshake.\n *\n * +----------+ +-----------+ +----------+\n * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -\n * | +----------+ +-----------+ +----------+ |\n * +----------+ +-----------+ |\n * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING\n * +----------+ +-----------+ |\n * | | | +---+ |\n * +------------------------+-->|fin| - - - -\n * | +---+ | +---+\n * - - - - -|fin|<---------------------+\n * +---+\n *\n * @param {Number} [code] Status code explaining why the connection is closing\n * @param {(String|Buffer)} [data] The reason why the connection is\n * closing\n * @public\n */\n close(code, data) {\n if (this.readyState === WebSocket.CLOSED) return;\n if (this.readyState === WebSocket.CONNECTING) {\n const msg = 'WebSocket was closed before the connection was established';\n abortHandshake(this, this._req, msg);\n return;\n }\n\n if (this.readyState === WebSocket.CLOSING) {\n if (\n this._closeFrameSent &&\n (this._closeFrameReceived || this._receiver._writableState.errorEmitted)\n ) {\n this._socket.end();\n }\n\n return;\n }\n\n this._readyState = WebSocket.CLOSING;\n this._sender.close(code, data, !this._isServer, (err) => {\n //\n // This error is handled by the `'error'` listener on the socket. We only\n // want to know if the close frame has been sent here.\n //\n if (err) return;\n\n this._closeFrameSent = true;\n\n if (\n this._closeFrameReceived ||\n this._receiver._writableState.errorEmitted\n ) {\n this._socket.end();\n }\n });\n\n setCloseTimer(this);\n }\n\n /**\n * Pause the socket.\n *\n * @public\n */\n pause() {\n if (\n this.readyState === WebSocket.CONNECTING ||\n this.readyState === WebSocket.CLOSED\n ) {\n return;\n }\n\n this._paused = true;\n this._socket.pause();\n }\n\n /**\n * Send a ping.\n *\n * @param {*} [data] The data to send\n * @param {Boolean} [mask] Indicates whether or not to mask `data`\n * @param {Function} [cb] Callback which is executed when the ping is sent\n * @public\n */\n ping(data, mask, cb) {\n if (this.readyState === WebSocket.CONNECTING) {\n throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n }\n\n if (typeof data === 'function') {\n cb = data;\n data = mask = undefined;\n } else if (typeof mask === 'function') {\n cb = mask;\n mask = undefined;\n }\n\n if (typeof data === 'number') data = data.toString();\n\n if (this.readyState !== WebSocket.OPEN) {\n sendAfterClose(this, data, cb);\n return;\n }\n\n if (mask === undefined) mask = !this._isServer;\n this._sender.ping(data || EMPTY_BUFFER, mask, cb);\n }\n\n /**\n * Send a pong.\n *\n * @param {*} [data] The data to send\n * @param {Boolean} [mask] Indicates whether or not to mask `data`\n * @param {Function} [cb] Callback which is executed when the pong is sent\n * @public\n */\n pong(data, mask, cb) {\n if (this.readyState === WebSocket.CONNECTING) {\n throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n }\n\n if (typeof data === 'function') {\n cb = data;\n data = mask = undefined;\n } else if (typeof mask === 'function') {\n cb = mask;\n mask = undefined;\n }\n\n if (typeof data === 'number') data = data.toString();\n\n if (this.readyState !== WebSocket.OPEN) {\n sendAfterClose(this, data, cb);\n return;\n }\n\n if (mask === undefined) mask = !this._isServer;\n this._sender.pong(data || EMPTY_BUFFER, mask, cb);\n }\n\n /**\n * Resume the socket.\n *\n * @public\n */\n resume() {\n if (\n this.readyState === WebSocket.CONNECTING ||\n this.readyState === WebSocket.CLOSED\n ) {\n return;\n }\n\n this._paused = false;\n if (!this._receiver._writableState.needDrain) this._socket.resume();\n }\n\n /**\n * Send a data message.\n *\n * @param {*} data The message to send\n * @param {Object} [options] Options object\n * @param {Boolean} [options.binary] Specifies whether `data` is binary or\n * text\n * @param {Boolean} [options.compress] Specifies whether or not to compress\n * `data`\n * @param {Boolean} [options.fin=true] Specifies whether the fragment is the\n * last one\n * @param {Boolean} [options.mask] Specifies whether or not to mask `data`\n * @param {Function} [cb] Callback which is executed when data is written out\n * @public\n */\n send(data, options, cb) {\n if (this.readyState === WebSocket.CONNECTING) {\n throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n }\n\n if (typeof options === 'function') {\n cb = options;\n options = {};\n }\n\n if (typeof data === 'number') data = data.toString();\n\n if (this.readyState !== WebSocket.OPEN) {\n sendAfterClose(this, data, cb);\n return;\n }\n\n const opts = {\n binary: typeof data !== 'string',\n mask: !this._isServer,\n compress: true,\n fin: true,\n ...options\n };\n\n if (!this._extensions[PerMessageDeflate.extensionName]) {\n opts.compress = false;\n }\n\n this._sender.send(data || EMPTY_BUFFER, opts, cb);\n }\n\n /**\n * Forcibly close the connection.\n *\n * @public\n */\n terminate() {\n if (this.readyState === WebSocket.CLOSED) return;\n if (this.readyState === WebSocket.CONNECTING) {\n const msg = 'WebSocket was closed before the connection was established';\n abortHandshake(this, this._req, msg);\n return;\n }\n\n if (this._socket) {\n this._readyState = WebSocket.CLOSING;\n this._socket.destroy();\n }\n }\n}\n\n/**\n * @constant {Number} CONNECTING\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CONNECTING', {\n enumerable: true,\n value: readyStates.indexOf('CONNECTING')\n});\n\n/**\n * @constant {Number} CONNECTING\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CONNECTING', {\n enumerable: true,\n value: readyStates.indexOf('CONNECTING')\n});\n\n/**\n * @constant {Number} OPEN\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'OPEN', {\n enumerable: true,\n value: readyStates.indexOf('OPEN')\n});\n\n/**\n * @constant {Number} OPEN\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'OPEN', {\n enumerable: true,\n value: readyStates.indexOf('OPEN')\n});\n\n/**\n * @constant {Number} CLOSING\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CLOSING', {\n enumerable: true,\n value: readyStates.indexOf('CLOSING')\n});\n\n/**\n * @constant {Number} CLOSING\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CLOSING', {\n enumerable: true,\n value: readyStates.indexOf('CLOSING')\n});\n\n/**\n * @constant {Number} CLOSED\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CLOSED', {\n enumerable: true,\n value: readyStates.indexOf('CLOSED')\n});\n\n/**\n * @constant {Number} CLOSED\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CLOSED', {\n enumerable: true,\n value: readyStates.indexOf('CLOSED')\n});\n\n[\n 'binaryType',\n 'bufferedAmount',\n 'extensions',\n 'isPaused',\n 'protocol',\n 'readyState',\n 'url'\n].forEach((property) => {\n Object.defineProperty(WebSocket.prototype, property, { enumerable: true });\n});\n\n//\n// Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes.\n// See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface\n//\n['open', 'error', 'close', 'message'].forEach((method) => {\n Object.defineProperty(WebSocket.prototype, `on${method}`, {\n enumerable: true,\n get() {\n for (const listener of this.listeners(method)) {\n if (listener[kForOnEventAttribute]) return listener[kListener];\n }\n\n return null;\n },\n set(handler) {\n for (const listener of this.listeners(method)) {\n if (listener[kForOnEventAttribute]) {\n this.removeListener(method, listener);\n break;\n }\n }\n\n if (typeof handler !== 'function') return;\n\n this.addEventListener(method, handler, {\n [kForOnEventAttribute]: true\n });\n }\n });\n});\n\nWebSocket.prototype.addEventListener = addEventListener;\nWebSocket.prototype.removeEventListener = removeEventListener;\n\nmodule.exports = WebSocket;\n\n/**\n * Initialize a WebSocket client.\n *\n * @param {WebSocket} websocket The client to initialize\n * @param {(String|URL)} address The URL to which to connect\n * @param {Array} protocols The subprotocols\n * @param {Object} [options] Connection options\n * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether any\n * of the `'message'`, `'ping'`, and `'pong'` events can be emitted multiple\n * times in the same tick\n * @param {Boolean} [options.autoPong=true] Specifies whether or not to\n * automatically send a pong in response to a ping\n * @param {Function} [options.finishRequest] A function which can be used to\n * customize the headers of each http request before it is sent\n * @param {Boolean} [options.followRedirects=false] Whether or not to follow\n * redirects\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the\n * handshake request\n * @param {Number} [options.maxPayload=104857600] The maximum allowed message\n * size\n * @param {Number} [options.maxRedirects=10] The maximum number of redirects\n * allowed\n * @param {String} [options.origin] Value of the `Origin` or\n * `Sec-WebSocket-Origin` header\n * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable\n * permessage-deflate\n * @param {Number} [options.protocolVersion=13] Value of the\n * `Sec-WebSocket-Version` header\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n * @private\n */\nfunction initAsClient(websocket, address, protocols, options) {\n const opts = {\n allowSynchronousEvents: true,\n autoPong: true,\n protocolVersion: protocolVersions[1],\n maxPayload: 100 * 1024 * 1024,\n skipUTF8Validation: false,\n perMessageDeflate: true,\n followRedirects: false,\n maxRedirects: 10,\n ...options,\n socketPath: undefined,\n hostname: undefined,\n protocol: undefined,\n timeout: undefined,\n method: 'GET',\n host: undefined,\n path: undefined,\n port: undefined\n };\n\n websocket._autoPong = opts.autoPong;\n\n if (!protocolVersions.includes(opts.protocolVersion)) {\n throw new RangeError(\n `Unsupported protocol version: ${opts.protocolVersion} ` +\n `(supported versions: ${protocolVersions.join(', ')})`\n );\n }\n\n let parsedUrl;\n\n if (address instanceof URL) {\n parsedUrl = address;\n } else {\n try {\n parsedUrl = new URL(address);\n } catch (e) {\n throw new SyntaxError(`Invalid URL: ${address}`);\n }\n }\n\n if (parsedUrl.protocol === 'http:') {\n parsedUrl.protocol = 'ws:';\n } else if (parsedUrl.protocol === 'https:') {\n parsedUrl.protocol = 'wss:';\n }\n\n websocket._url = parsedUrl.href;\n\n const isSecure = parsedUrl.protocol === 'wss:';\n const isIpcUrl = parsedUrl.protocol === 'ws+unix:';\n let invalidUrlMessage;\n\n if (parsedUrl.protocol !== 'ws:' && !isSecure && !isIpcUrl) {\n invalidUrlMessage =\n 'The URL\\'s protocol must be one of \"ws:\", \"wss:\", ' +\n '\"http:\", \"https:\", or \"ws+unix:\"';\n } else if (isIpcUrl && !parsedUrl.pathname) {\n invalidUrlMessage = \"The URL's pathname is empty\";\n } else if (parsedUrl.hash) {\n invalidUrlMessage = 'The URL contains a fragment identifier';\n }\n\n if (invalidUrlMessage) {\n const err = new SyntaxError(invalidUrlMessage);\n\n if (websocket._redirects === 0) {\n throw err;\n } else {\n emitErrorAndClose(websocket, err);\n return;\n }\n }\n\n const defaultPort = isSecure ? 443 : 80;\n const key = randomBytes(16).toString('base64');\n const request = isSecure ? https.request : http.request;\n const protocolSet = new Set();\n let perMessageDeflate;\n\n opts.createConnection =\n opts.createConnection || (isSecure ? tlsConnect : netConnect);\n opts.defaultPort = opts.defaultPort || defaultPort;\n opts.port = parsedUrl.port || defaultPort;\n opts.host = parsedUrl.hostname.startsWith('[')\n ? parsedUrl.hostname.slice(1, -1)\n : parsedUrl.hostname;\n opts.headers = {\n ...opts.headers,\n 'Sec-WebSocket-Version': opts.protocolVersion,\n 'Sec-WebSocket-Key': key,\n Connection: 'Upgrade',\n Upgrade: 'websocket'\n };\n opts.path = parsedUrl.pathname + parsedUrl.search;\n opts.timeout = opts.handshakeTimeout;\n\n if (opts.perMessageDeflate) {\n perMessageDeflate = new PerMessageDeflate(\n opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},\n false,\n opts.maxPayload\n );\n opts.headers['Sec-WebSocket-Extensions'] = format({\n [PerMessageDeflate.extensionName]: perMessageDeflate.offer()\n });\n }\n if (protocols.length) {\n for (const protocol of protocols) {\n if (\n typeof protocol !== 'string' ||\n !subprotocolRegex.test(protocol) ||\n protocolSet.has(protocol)\n ) {\n throw new SyntaxError(\n 'An invalid or duplicated subprotocol was specified'\n );\n }\n\n protocolSet.add(protocol);\n }\n\n opts.headers['Sec-WebSocket-Protocol'] = protocols.join(',');\n }\n if (opts.origin) {\n if (opts.protocolVersion < 13) {\n opts.headers['Sec-WebSocket-Origin'] = opts.origin;\n } else {\n opts.headers.Origin = opts.origin;\n }\n }\n if (parsedUrl.username || parsedUrl.password) {\n opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;\n }\n\n if (isIpcUrl) {\n const parts = opts.path.split(':');\n\n opts.socketPath = parts[0];\n opts.path = parts[1];\n }\n\n let req;\n\n if (opts.followRedirects) {\n if (websocket._redirects === 0) {\n websocket._originalIpc = isIpcUrl;\n websocket._originalSecure = isSecure;\n websocket._originalHostOrSocketPath = isIpcUrl\n ? opts.socketPath\n : parsedUrl.host;\n\n const headers = options && options.headers;\n\n //\n // Shallow copy the user provided options so that headers can be changed\n // without mutating the original object.\n //\n options = { ...options, headers: {} };\n\n if (headers) {\n for (const [key, value] of Object.entries(headers)) {\n options.headers[key.toLowerCase()] = value;\n }\n }\n } else if (websocket.listenerCount('redirect') === 0) {\n const isSameHost = isIpcUrl\n ? websocket._originalIpc\n ? opts.socketPath === websocket._originalHostOrSocketPath\n : false\n : websocket._originalIpc\n ? false\n : parsedUrl.host === websocket._originalHostOrSocketPath;\n\n if (!isSameHost || (websocket._originalSecure && !isSecure)) {\n //\n // Match curl 7.77.0 behavior and drop the following headers. These\n // headers are also dropped when following a redirect to a subdomain.\n //\n delete opts.headers.authorization;\n delete opts.headers.cookie;\n\n if (!isSameHost) delete opts.headers.host;\n\n opts.auth = undefined;\n }\n }\n\n //\n // Match curl 7.77.0 behavior and make the first `Authorization` header win.\n // If the `Authorization` header is set, then there is nothing to do as it\n // will take precedence.\n //\n if (opts.auth && !options.headers.authorization) {\n options.headers.authorization =\n 'Basic ' + Buffer.from(opts.auth).toString('base64');\n }\n\n req = websocket._req = request(opts);\n\n if (websocket._redirects) {\n //\n // Unlike what is done for the `'upgrade'` event, no early exit is\n // triggered here if the user calls `websocket.close()` or\n // `websocket.terminate()` from a listener of the `'redirect'` event. This\n // is because the user can also call `request.destroy()` with an error\n // before calling `websocket.close()` or `websocket.terminate()` and this\n // would result in an error being emitted on the `request` object with no\n // `'error'` event listeners attached.\n //\n websocket.emit('redirect', websocket.url, req);\n }\n } else {\n req = websocket._req = request(opts);\n }\n\n if (opts.timeout) {\n req.on('timeout', () => {\n abortHandshake(websocket, req, 'Opening handshake has timed out');\n });\n }\n\n req.on('error', (err) => {\n if (req === null || req[kAborted]) return;\n\n req = websocket._req = null;\n emitErrorAndClose(websocket, err);\n });\n\n req.on('response', (res) => {\n const location = res.headers.location;\n const statusCode = res.statusCode;\n\n if (\n location &&\n opts.followRedirects &&\n statusCode >= 300 &&\n statusCode < 400\n ) {\n if (++websocket._redirects > opts.maxRedirects) {\n abortHandshake(websocket, req, 'Maximum redirects exceeded');\n return;\n }\n\n req.abort();\n\n let addr;\n\n try {\n addr = new URL(location, address);\n } catch (e) {\n const err = new SyntaxError(`Invalid URL: ${location}`);\n emitErrorAndClose(websocket, err);\n return;\n }\n\n initAsClient(websocket, addr, protocols, options);\n } else if (!websocket.emit('unexpected-response', req, res)) {\n abortHandshake(\n websocket,\n req,\n `Unexpected server response: ${res.statusCode}`\n );\n }\n });\n\n req.on('upgrade', (res, socket, head) => {\n websocket.emit('upgrade', res);\n\n //\n // The user may have closed the connection from a listener of the\n // `'upgrade'` event.\n //\n if (websocket.readyState !== WebSocket.CONNECTING) return;\n\n req = websocket._req = null;\n\n const upgrade = res.headers.upgrade;\n\n if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {\n abortHandshake(websocket, socket, 'Invalid Upgrade header');\n return;\n }\n\n const digest = createHash('sha1')\n .update(key + GUID)\n .digest('base64');\n\n if (res.headers['sec-websocket-accept'] !== digest) {\n abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header');\n return;\n }\n\n const serverProt = res.headers['sec-websocket-protocol'];\n let protError;\n\n if (serverProt !== undefined) {\n if (!protocolSet.size) {\n protError = 'Server sent a subprotocol but none was requested';\n } else if (!protocolSet.has(serverProt)) {\n protError = 'Server sent an invalid subprotocol';\n }\n } else if (protocolSet.size) {\n protError = 'Server sent no subprotocol';\n }\n\n if (protError) {\n abortHandshake(websocket, socket, protError);\n return;\n }\n\n if (serverProt) websocket._protocol = serverProt;\n\n const secWebSocketExtensions = res.headers['sec-websocket-extensions'];\n\n if (secWebSocketExtensions !== undefined) {\n if (!perMessageDeflate) {\n const message =\n 'Server sent a Sec-WebSocket-Extensions header but no extension ' +\n 'was requested';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n let extensions;\n\n try {\n extensions = parse(secWebSocketExtensions);\n } catch (err) {\n const message = 'Invalid Sec-WebSocket-Extensions header';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n const extensionNames = Object.keys(extensions);\n\n if (\n extensionNames.length !== 1 ||\n extensionNames[0] !== PerMessageDeflate.extensionName\n ) {\n const message = 'Server indicated an extension that was not requested';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n try {\n perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);\n } catch (err) {\n const message = 'Invalid Sec-WebSocket-Extensions header';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n websocket._extensions[PerMessageDeflate.extensionName] =\n perMessageDeflate;\n }\n\n websocket.setSocket(socket, head, {\n allowSynchronousEvents: opts.allowSynchronousEvents,\n generateMask: opts.generateMask,\n maxPayload: opts.maxPayload,\n skipUTF8Validation: opts.skipUTF8Validation\n });\n });\n\n if (opts.finishRequest) {\n opts.finishRequest(req, websocket);\n } else {\n req.end();\n }\n}\n\n/**\n * Emit the `'error'` and `'close'` events.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {Error} The error to emit\n * @private\n */\nfunction emitErrorAndClose(websocket, err) {\n websocket._readyState = WebSocket.CLOSING;\n //\n // The following assignment is practically useless and is done only for\n // consistency.\n //\n websocket._errorEmitted = true;\n websocket.emit('error', err);\n websocket.emitClose();\n}\n\n/**\n * Create a `net.Socket` and initiate a connection.\n *\n * @param {Object} options Connection options\n * @return {net.Socket} The newly created socket used to start the connection\n * @private\n */\nfunction netConnect(options) {\n options.path = options.socketPath;\n return net.connect(options);\n}\n\n/**\n * Create a `tls.TLSSocket` and initiate a connection.\n *\n * @param {Object} options Connection options\n * @return {tls.TLSSocket} The newly created socket used to start the connection\n * @private\n */\nfunction tlsConnect(options) {\n options.path = undefined;\n\n if (!options.servername && options.servername !== '') {\n options.servername = net.isIP(options.host) ? '' : options.host;\n }\n\n return tls.connect(options);\n}\n\n/**\n * Abort the handshake and emit an error.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to\n * abort or the socket to destroy\n * @param {String} message The error message\n * @private\n */\nfunction abortHandshake(websocket, stream, message) {\n websocket._readyState = WebSocket.CLOSING;\n\n const err = new Error(message);\n Error.captureStackTrace(err, abortHandshake);\n\n if (stream.setHeader) {\n stream[kAborted] = true;\n stream.abort();\n\n if (stream.socket && !stream.socket.destroyed) {\n //\n // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if\n // called after the request completed. See\n // https://github.com/websockets/ws/issues/1869.\n //\n stream.socket.destroy();\n }\n\n process.nextTick(emitErrorAndClose, websocket, err);\n } else {\n stream.destroy(err);\n stream.once('error', websocket.emit.bind(websocket, 'error'));\n stream.once('close', websocket.emitClose.bind(websocket));\n }\n}\n\n/**\n * Handle cases where the `ping()`, `pong()`, or `send()` methods are called\n * when the `readyState` attribute is `CLOSING` or `CLOSED`.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {*} [data] The data to send\n * @param {Function} [cb] Callback\n * @private\n */\nfunction sendAfterClose(websocket, data, cb) {\n if (data) {\n const length = isBlob(data) ? data.size : toBuffer(data).length;\n\n //\n // The `_bufferedAmount` property is used only when the peer is a client and\n // the opening handshake fails. Under these circumstances, in fact, the\n // `setSocket()` method is not called, so the `_socket` and `_sender`\n // properties are set to `null`.\n //\n if (websocket._socket) websocket._sender._bufferedBytes += length;\n else websocket._bufferedAmount += length;\n }\n\n if (cb) {\n const err = new Error(\n `WebSocket is not open: readyState ${websocket.readyState} ` +\n `(${readyStates[websocket.readyState]})`\n );\n process.nextTick(cb, err);\n }\n}\n\n/**\n * The listener of the `Receiver` `'conclude'` event.\n *\n * @param {Number} code The status code\n * @param {Buffer} reason The reason for closing\n * @private\n */\nfunction receiverOnConclude(code, reason) {\n const websocket = this[kWebSocket];\n\n websocket._closeFrameReceived = true;\n websocket._closeMessage = reason;\n websocket._closeCode = code;\n\n if (websocket._socket[kWebSocket] === undefined) return;\n\n websocket._socket.removeListener('data', socketOnData);\n process.nextTick(resume, websocket._socket);\n\n if (code === 1005) websocket.close();\n else websocket.close(code, reason);\n}\n\n/**\n * The listener of the `Receiver` `'drain'` event.\n *\n * @private\n */\nfunction receiverOnDrain() {\n const websocket = this[kWebSocket];\n\n if (!websocket.isPaused) websocket._socket.resume();\n}\n\n/**\n * The listener of the `Receiver` `'error'` event.\n *\n * @param {(RangeError|Error)} err The emitted error\n * @private\n */\nfunction receiverOnError(err) {\n const websocket = this[kWebSocket];\n\n if (websocket._socket[kWebSocket] !== undefined) {\n websocket._socket.removeListener('data', socketOnData);\n\n //\n // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See\n // https://github.com/websockets/ws/issues/1940.\n //\n process.nextTick(resume, websocket._socket);\n\n websocket.close(err[kStatusCode]);\n }\n\n if (!websocket._errorEmitted) {\n websocket._errorEmitted = true;\n websocket.emit('error', err);\n }\n}\n\n/**\n * The listener of the `Receiver` `'finish'` event.\n *\n * @private\n */\nfunction receiverOnFinish() {\n this[kWebSocket].emitClose();\n}\n\n/**\n * The listener of the `Receiver` `'message'` event.\n *\n * @param {Buffer|ArrayBuffer|Buffer[])} data The message\n * @param {Boolean} isBinary Specifies whether the message is binary or not\n * @private\n */\nfunction receiverOnMessage(data, isBinary) {\n this[kWebSocket].emit('message', data, isBinary);\n}\n\n/**\n * The listener of the `Receiver` `'ping'` event.\n *\n * @param {Buffer} data The data included in the ping frame\n * @private\n */\nfunction receiverOnPing(data) {\n const websocket = this[kWebSocket];\n\n if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);\n websocket.emit('ping', data);\n}\n\n/**\n * The listener of the `Receiver` `'pong'` event.\n *\n * @param {Buffer} data The data included in the pong frame\n * @private\n */\nfunction receiverOnPong(data) {\n this[kWebSocket].emit('pong', data);\n}\n\n/**\n * Resume a readable stream\n *\n * @param {Readable} stream The readable stream\n * @private\n */\nfunction resume(stream) {\n stream.resume();\n}\n\n/**\n * The `Sender` error event handler.\n *\n * @param {Error} The error\n * @private\n */\nfunction senderOnError(err) {\n const websocket = this[kWebSocket];\n\n if (websocket.readyState === WebSocket.CLOSED) return;\n if (websocket.readyState === WebSocket.OPEN) {\n websocket._readyState = WebSocket.CLOSING;\n setCloseTimer(websocket);\n }\n\n //\n // `socket.end()` is used instead of `socket.destroy()` to allow the other\n // peer to finish sending queued data. There is no need to set a timer here\n // because `CLOSING` means that it is already set or not needed.\n //\n this._socket.end();\n\n if (!websocket._errorEmitted) {\n websocket._errorEmitted = true;\n websocket.emit('error', err);\n }\n}\n\n/**\n * Set a timer to destroy the underlying raw socket of a WebSocket.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @private\n */\nfunction setCloseTimer(websocket) {\n websocket._closeTimer = setTimeout(\n websocket._socket.destroy.bind(websocket._socket),\n closeTimeout\n );\n}\n\n/**\n * The listener of the socket `'close'` event.\n *\n * @private\n */\nfunction socketOnClose() {\n const websocket = this[kWebSocket];\n\n this.removeListener('close', socketOnClose);\n this.removeListener('data', socketOnData);\n this.removeListener('end', socketOnEnd);\n\n websocket._readyState = WebSocket.CLOSING;\n\n let chunk;\n\n //\n // The close frame might not have been received or the `'end'` event emitted,\n // for example, if the socket was destroyed due to an error. Ensure that the\n // `receiver` stream is closed after writing any remaining buffered data to\n // it. If the readable side of the socket is in flowing mode then there is no\n // buffered data as everything has been already written and `readable.read()`\n // will return `null`. If instead, the socket is paused, any possible buffered\n // data will be read as a single chunk.\n //\n if (\n !this._readableState.endEmitted &&\n !websocket._closeFrameReceived &&\n !websocket._receiver._writableState.errorEmitted &&\n (chunk = websocket._socket.read()) !== null\n ) {\n websocket._receiver.write(chunk);\n }\n\n websocket._receiver.end();\n\n this[kWebSocket] = undefined;\n\n clearTimeout(websocket._closeTimer);\n\n if (\n websocket._receiver._writableState.finished ||\n websocket._receiver._writableState.errorEmitted\n ) {\n websocket.emitClose();\n } else {\n websocket._receiver.on('error', receiverOnFinish);\n websocket._receiver.on('finish', receiverOnFinish);\n }\n}\n\n/**\n * The listener of the socket `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction socketOnData(chunk) {\n if (!this[kWebSocket]._receiver.write(chunk)) {\n this.pause();\n }\n}\n\n/**\n * The listener of the socket `'end'` event.\n *\n * @private\n */\nfunction socketOnEnd() {\n const websocket = this[kWebSocket];\n\n websocket._readyState = WebSocket.CLOSING;\n websocket._receiver.end();\n this.end();\n}\n\n/**\n * The listener of the socket `'error'` event.\n *\n * @private\n */\nfunction socketOnError() {\n const websocket = this[kWebSocket];\n\n this.removeListener('error', socketOnError);\n this.on('error', NOOP);\n\n if (websocket) {\n websocket._readyState = WebSocket.CLOSING;\n this.destroy();\n }\n}\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^WebSocket$\" }] */\n'use strict';\n\nconst WebSocket = require('./websocket');\nconst { Duplex } = require('stream');\n\n/**\n * Emits the `'close'` event on a stream.\n *\n * @param {Duplex} stream The stream.\n * @private\n */\nfunction emitClose(stream) {\n stream.emit('close');\n}\n\n/**\n * The listener of the `'end'` event.\n *\n * @private\n */\nfunction duplexOnEnd() {\n if (!this.destroyed && this._writableState.finished) {\n this.destroy();\n }\n}\n\n/**\n * The listener of the `'error'` event.\n *\n * @param {Error} err The error\n * @private\n */\nfunction duplexOnError(err) {\n this.removeListener('error', duplexOnError);\n this.destroy();\n if (this.listenerCount('error') === 0) {\n // Do not suppress the throwing behavior.\n this.emit('error', err);\n }\n}\n\n/**\n * Wraps a `WebSocket` in a duplex stream.\n *\n * @param {WebSocket} ws The `WebSocket` to wrap\n * @param {Object} [options] The options for the `Duplex` constructor\n * @return {Duplex} The duplex stream\n * @public\n */\nfunction createWebSocketStream(ws, options) {\n let terminateOnDestroy = true;\n\n const duplex = new Duplex({\n ...options,\n autoDestroy: false,\n emitClose: false,\n objectMode: false,\n writableObjectMode: false\n });\n\n ws.on('message', function message(msg, isBinary) {\n const data =\n !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;\n\n if (!duplex.push(data)) ws.pause();\n });\n\n ws.once('error', function error(err) {\n if (duplex.destroyed) return;\n\n // Prevent `ws.terminate()` from being called by `duplex._destroy()`.\n //\n // - If the `'error'` event is emitted before the `'open'` event, then\n // `ws.terminate()` is a noop as no socket is assigned.\n // - Otherwise, the error is re-emitted by the listener of the `'error'`\n // event of the `Receiver` object. The listener already closes the\n // connection by calling `ws.close()`. This allows a close frame to be\n // sent to the other peer. If `ws.terminate()` is called right after this,\n // then the close frame might not be sent.\n terminateOnDestroy = false;\n duplex.destroy(err);\n });\n\n ws.once('close', function close() {\n if (duplex.destroyed) return;\n\n duplex.push(null);\n });\n\n duplex._destroy = function (err, callback) {\n if (ws.readyState === ws.CLOSED) {\n callback(err);\n process.nextTick(emitClose, duplex);\n return;\n }\n\n let called = false;\n\n ws.once('error', function error(err) {\n called = true;\n callback(err);\n });\n\n ws.once('close', function close() {\n if (!called) callback(err);\n process.nextTick(emitClose, duplex);\n });\n\n if (terminateOnDestroy) ws.terminate();\n };\n\n duplex._final = function (callback) {\n if (ws.readyState === ws.CONNECTING) {\n ws.once('open', function open() {\n duplex._final(callback);\n });\n return;\n }\n\n // If the value of the `_socket` property is `null` it means that `ws` is a\n // client websocket and the handshake failed. In fact, when this happens, a\n // socket is never assigned to the websocket. Wait for the `'error'` event\n // that will be emitted by the websocket.\n if (ws._socket === null) return;\n\n if (ws._socket._writableState.finished) {\n callback();\n if (duplex._readableState.endEmitted) duplex.destroy();\n } else {\n ws._socket.once('finish', function finish() {\n // `duplex` is not destroyed here because the `'end'` event will be\n // emitted on `duplex` after this `'finish'` event. The EOF signaling\n // `null` chunk is, in fact, pushed when the websocket emits `'close'`.\n callback();\n });\n ws.close();\n }\n };\n\n duplex._read = function () {\n if (ws.isPaused) ws.resume();\n };\n\n duplex._write = function (chunk, encoding, callback) {\n if (ws.readyState === ws.CONNECTING) {\n ws.once('open', function open() {\n duplex._write(chunk, encoding, callback);\n });\n return;\n }\n\n ws.send(chunk, callback);\n };\n\n duplex.on('end', duplexOnEnd);\n duplex.on('error', duplexOnError);\n return duplex;\n}\n\nmodule.exports = createWebSocketStream;\n","'use strict';\n\nconst { tokenChars } = require('./validation');\n\n/**\n * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names.\n *\n * @param {String} header The field value of the header\n * @return {Set} The subprotocol names\n * @public\n */\nfunction parse(header) {\n const protocols = new Set();\n let start = -1;\n let end = -1;\n let i = 0;\n\n for (i; i < header.length; i++) {\n const code = header.charCodeAt(i);\n\n if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (\n i !== 0 &&\n (code === 0x20 /* ' ' */ || code === 0x09) /* '\\t' */\n ) {\n if (end === -1 && start !== -1) end = i;\n } else if (code === 0x2c /* ',' */) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n\n const protocol = header.slice(start, end);\n\n if (protocols.has(protocol)) {\n throw new SyntaxError(`The \"${protocol}\" subprotocol is duplicated`);\n }\n\n protocols.add(protocol);\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n }\n\n if (start === -1 || end !== -1) {\n throw new SyntaxError('Unexpected end of input');\n }\n\n const protocol = header.slice(start, i);\n\n if (protocols.has(protocol)) {\n throw new SyntaxError(`The \"${protocol}\" subprotocol is duplicated`);\n }\n\n protocols.add(protocol);\n return protocols;\n}\n\nmodule.exports = { parse };\n","/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^Duplex$\", \"caughtErrors\": \"none\" }] */\n\n'use strict';\n\nconst EventEmitter = require('events');\nconst http = require('http');\nconst { Duplex } = require('stream');\nconst { createHash } = require('crypto');\n\nconst extension = require('./extension');\nconst PerMessageDeflate = require('./permessage-deflate');\nconst subprotocol = require('./subprotocol');\nconst WebSocket = require('./websocket');\nconst { GUID, kWebSocket } = require('./constants');\n\nconst keyRegex = /^[+/0-9A-Za-z]{22}==$/;\n\nconst RUNNING = 0;\nconst CLOSING = 1;\nconst CLOSED = 2;\n\n/**\n * Class representing a WebSocket server.\n *\n * @extends EventEmitter\n */\nclass WebSocketServer extends EventEmitter {\n /**\n * Create a `WebSocketServer` instance.\n *\n * @param {Object} options Configuration options\n * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether\n * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted\n * multiple times in the same tick\n * @param {Boolean} [options.autoPong=true] Specifies whether or not to\n * automatically send a pong in response to a ping\n * @param {Number} [options.backlog=511] The maximum length of the queue of\n * pending connections\n * @param {Boolean} [options.clientTracking=true] Specifies whether or not to\n * track clients\n * @param {Function} [options.handleProtocols] A hook to handle protocols\n * @param {String} [options.host] The hostname where to bind the server\n * @param {Number} [options.maxPayload=104857600] The maximum allowed message\n * size\n * @param {Boolean} [options.noServer=false] Enable no server mode\n * @param {String} [options.path] Accept only connections matching this path\n * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable\n * permessage-deflate\n * @param {Number} [options.port] The port where to bind the server\n * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S\n * server to use\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n * @param {Function} [options.verifyClient] A hook to reject connections\n * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`\n * class to use. It must be the `WebSocket` class or class that extends it\n * @param {Function} [callback] A listener for the `listening` event\n */\n constructor(options, callback) {\n super();\n\n options = {\n allowSynchronousEvents: true,\n autoPong: true,\n maxPayload: 100 * 1024 * 1024,\n skipUTF8Validation: false,\n perMessageDeflate: false,\n handleProtocols: null,\n clientTracking: true,\n verifyClient: null,\n noServer: false,\n backlog: null, // use default (511 as implemented in net.js)\n server: null,\n host: null,\n path: null,\n port: null,\n WebSocket,\n ...options\n };\n\n if (\n (options.port == null && !options.server && !options.noServer) ||\n (options.port != null && (options.server || options.noServer)) ||\n (options.server && options.noServer)\n ) {\n throw new TypeError(\n 'One and only one of the \"port\", \"server\", or \"noServer\" options ' +\n 'must be specified'\n );\n }\n\n if (options.port != null) {\n this._server = http.createServer((req, res) => {\n const body = http.STATUS_CODES[426];\n\n res.writeHead(426, {\n 'Content-Length': body.length,\n 'Content-Type': 'text/plain'\n });\n res.end(body);\n });\n this._server.listen(\n options.port,\n options.host,\n options.backlog,\n callback\n );\n } else if (options.server) {\n this._server = options.server;\n }\n\n if (this._server) {\n const emitConnection = this.emit.bind(this, 'connection');\n\n this._removeListeners = addListeners(this._server, {\n listening: this.emit.bind(this, 'listening'),\n error: this.emit.bind(this, 'error'),\n upgrade: (req, socket, head) => {\n this.handleUpgrade(req, socket, head, emitConnection);\n }\n });\n }\n\n if (options.perMessageDeflate === true) options.perMessageDeflate = {};\n if (options.clientTracking) {\n this.clients = new Set();\n this._shouldEmitClose = false;\n }\n\n this.options = options;\n this._state = RUNNING;\n }\n\n /**\n * Returns the bound address, the address family name, and port of the server\n * as reported by the operating system if listening on an IP socket.\n * If the server is listening on a pipe or UNIX domain socket, the name is\n * returned as a string.\n *\n * @return {(Object|String|null)} The address of the server\n * @public\n */\n address() {\n if (this.options.noServer) {\n throw new Error('The server is operating in \"noServer\" mode');\n }\n\n if (!this._server) return null;\n return this._server.address();\n }\n\n /**\n * Stop the server from accepting new connections and emit the `'close'` event\n * when all existing connections are closed.\n *\n * @param {Function} [cb] A one-time listener for the `'close'` event\n * @public\n */\n close(cb) {\n if (this._state === CLOSED) {\n if (cb) {\n this.once('close', () => {\n cb(new Error('The server is not running'));\n });\n }\n\n process.nextTick(emitClose, this);\n return;\n }\n\n if (cb) this.once('close', cb);\n\n if (this._state === CLOSING) return;\n this._state = CLOSING;\n\n if (this.options.noServer || this.options.server) {\n if (this._server) {\n this._removeListeners();\n this._removeListeners = this._server = null;\n }\n\n if (this.clients) {\n if (!this.clients.size) {\n process.nextTick(emitClose, this);\n } else {\n this._shouldEmitClose = true;\n }\n } else {\n process.nextTick(emitClose, this);\n }\n } else {\n const server = this._server;\n\n this._removeListeners();\n this._removeListeners = this._server = null;\n\n //\n // The HTTP/S server was created internally. Close it, and rely on its\n // `'close'` event.\n //\n server.close(() => {\n emitClose(this);\n });\n }\n }\n\n /**\n * See if a given request should be handled by this server instance.\n *\n * @param {http.IncomingMessage} req Request object to inspect\n * @return {Boolean} `true` if the request is valid, else `false`\n * @public\n */\n shouldHandle(req) {\n if (this.options.path) {\n const index = req.url.indexOf('?');\n const pathname = index !== -1 ? req.url.slice(0, index) : req.url;\n\n if (pathname !== this.options.path) return false;\n }\n\n return true;\n }\n\n /**\n * Handle a HTTP Upgrade request.\n *\n * @param {http.IncomingMessage} req The request object\n * @param {Duplex} socket The network socket between the server and client\n * @param {Buffer} head The first packet of the upgraded stream\n * @param {Function} cb Callback\n * @public\n */\n handleUpgrade(req, socket, head, cb) {\n socket.on('error', socketOnError);\n\n const key = req.headers['sec-websocket-key'];\n const upgrade = req.headers.upgrade;\n const version = +req.headers['sec-websocket-version'];\n\n if (req.method !== 'GET') {\n const message = 'Invalid HTTP method';\n abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);\n return;\n }\n\n if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {\n const message = 'Invalid Upgrade header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n\n if (key === undefined || !keyRegex.test(key)) {\n const message = 'Missing or invalid Sec-WebSocket-Key header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n\n if (version !== 13 && version !== 8) {\n const message = 'Missing or invalid Sec-WebSocket-Version header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {\n 'Sec-WebSocket-Version': '13, 8'\n });\n return;\n }\n\n if (!this.shouldHandle(req)) {\n abortHandshake(socket, 400);\n return;\n }\n\n const secWebSocketProtocol = req.headers['sec-websocket-protocol'];\n let protocols = new Set();\n\n if (secWebSocketProtocol !== undefined) {\n try {\n protocols = subprotocol.parse(secWebSocketProtocol);\n } catch (err) {\n const message = 'Invalid Sec-WebSocket-Protocol header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n }\n\n const secWebSocketExtensions = req.headers['sec-websocket-extensions'];\n const extensions = {};\n\n if (\n this.options.perMessageDeflate &&\n secWebSocketExtensions !== undefined\n ) {\n const perMessageDeflate = new PerMessageDeflate(\n this.options.perMessageDeflate,\n true,\n this.options.maxPayload\n );\n\n try {\n const offers = extension.parse(secWebSocketExtensions);\n\n if (offers[PerMessageDeflate.extensionName]) {\n perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);\n extensions[PerMessageDeflate.extensionName] = perMessageDeflate;\n }\n } catch (err) {\n const message =\n 'Invalid or unacceptable Sec-WebSocket-Extensions header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n }\n\n //\n // Optionally call external client verification handler.\n //\n if (this.options.verifyClient) {\n const info = {\n origin:\n req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`],\n secure: !!(req.socket.authorized || req.socket.encrypted),\n req\n };\n\n if (this.options.verifyClient.length === 2) {\n this.options.verifyClient(info, (verified, code, message, headers) => {\n if (!verified) {\n return abortHandshake(socket, code || 401, message, headers);\n }\n\n this.completeUpgrade(\n extensions,\n key,\n protocols,\n req,\n socket,\n head,\n cb\n );\n });\n return;\n }\n\n if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);\n }\n\n this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);\n }\n\n /**\n * Upgrade the connection to WebSocket.\n *\n * @param {Object} extensions The accepted extensions\n * @param {String} key The value of the `Sec-WebSocket-Key` header\n * @param {Set} protocols The subprotocols\n * @param {http.IncomingMessage} req The request object\n * @param {Duplex} socket The network socket between the server and client\n * @param {Buffer} head The first packet of the upgraded stream\n * @param {Function} cb Callback\n * @throws {Error} If called more than once with the same socket\n * @private\n */\n completeUpgrade(extensions, key, protocols, req, socket, head, cb) {\n //\n // Destroy the socket if the client has already sent a FIN packet.\n //\n if (!socket.readable || !socket.writable) return socket.destroy();\n\n if (socket[kWebSocket]) {\n throw new Error(\n 'server.handleUpgrade() was called more than once with the same ' +\n 'socket, possibly due to a misconfiguration'\n );\n }\n\n if (this._state > RUNNING) return abortHandshake(socket, 503);\n\n const digest = createHash('sha1')\n .update(key + GUID)\n .digest('base64');\n\n const headers = [\n 'HTTP/1.1 101 Switching Protocols',\n 'Upgrade: websocket',\n 'Connection: Upgrade',\n `Sec-WebSocket-Accept: ${digest}`\n ];\n\n const ws = new this.options.WebSocket(null, undefined, this.options);\n\n if (protocols.size) {\n //\n // Optionally call external protocol selection handler.\n //\n const protocol = this.options.handleProtocols\n ? this.options.handleProtocols(protocols, req)\n : protocols.values().next().value;\n\n if (protocol) {\n headers.push(`Sec-WebSocket-Protocol: ${protocol}`);\n ws._protocol = protocol;\n }\n }\n\n if (extensions[PerMessageDeflate.extensionName]) {\n const params = extensions[PerMessageDeflate.extensionName].params;\n const value = extension.format({\n [PerMessageDeflate.extensionName]: [params]\n });\n headers.push(`Sec-WebSocket-Extensions: ${value}`);\n ws._extensions = extensions;\n }\n\n //\n // Allow external modification/inspection of handshake headers.\n //\n this.emit('headers', headers, req);\n\n socket.write(headers.concat('\\r\\n').join('\\r\\n'));\n socket.removeListener('error', socketOnError);\n\n ws.setSocket(socket, head, {\n allowSynchronousEvents: this.options.allowSynchronousEvents,\n maxPayload: this.options.maxPayload,\n skipUTF8Validation: this.options.skipUTF8Validation\n });\n\n if (this.clients) {\n this.clients.add(ws);\n ws.on('close', () => {\n this.clients.delete(ws);\n\n if (this._shouldEmitClose && !this.clients.size) {\n process.nextTick(emitClose, this);\n }\n });\n }\n\n cb(ws, req);\n }\n}\n\nmodule.exports = WebSocketServer;\n\n/**\n * Add event listeners on an `EventEmitter` using a map of <event, listener>\n * pairs.\n *\n * @param {EventEmitter} server The event emitter\n * @param {Object.<String, Function>} map The listeners to add\n * @return {Function} A function that will remove the added listeners when\n * called\n * @private\n */\nfunction addListeners(server, map) {\n for (const event of Object.keys(map)) server.on(event, map[event]);\n\n return function removeListeners() {\n for (const event of Object.keys(map)) {\n server.removeListener(event, map[event]);\n }\n };\n}\n\n/**\n * Emit a `'close'` event on an `EventEmitter`.\n *\n * @param {EventEmitter} server The event emitter\n * @private\n */\nfunction emitClose(server) {\n server._state = CLOSED;\n server.emit('close');\n}\n\n/**\n * Handle socket errors.\n *\n * @private\n */\nfunction socketOnError() {\n this.destroy();\n}\n\n/**\n * Close the connection when preconditions are not fulfilled.\n *\n * @param {Duplex} socket The socket of the upgrade request\n * @param {Number} code The HTTP response status code\n * @param {String} [message] The HTTP response body\n * @param {Object} [headers] Additional HTTP response headers\n * @private\n */\nfunction abortHandshake(socket, code, message, headers) {\n //\n // The socket is writable unless the user destroyed or ended it before calling\n // `server.handleUpgrade()` or in the `verifyClient` function, which is a user\n // error. Handling this does not make much sense as the worst that can happen\n // is that some of the data written by the user might be discarded due to the\n // call to `socket.end()` below, which triggers an `'error'` event that in\n // turn causes the socket to be destroyed.\n //\n message = message || http.STATUS_CODES[code];\n headers = {\n Connection: 'close',\n 'Content-Type': 'text/html',\n 'Content-Length': Buffer.byteLength(message),\n ...headers\n };\n\n socket.once('finish', socket.destroy);\n\n socket.end(\n `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\\r\\n` +\n Object.keys(headers)\n .map((h) => `${h}: ${headers[h]}`)\n .join('\\r\\n') +\n '\\r\\n\\r\\n' +\n message\n );\n}\n\n/**\n * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least\n * one listener for it, otherwise call `abortHandshake()`.\n *\n * @param {WebSocketServer} server The WebSocket server\n * @param {http.IncomingMessage} req The request object\n * @param {Duplex} socket The socket of the upgrade request\n * @param {Number} code The HTTP response status code\n * @param {String} message The HTTP response body\n * @param {Object} [headers] The HTTP response headers\n * @private\n */\nfunction abortHandshakeOrEmitwsClientError(\n server,\n req,\n socket,\n code,\n message,\n headers\n) {\n if (server.listenerCount('wsClientError')) {\n const err = new Error(message);\n Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);\n\n server.emit('wsClientError', err, socket, req);\n } else {\n abortHandshake(socket, code, message, headers);\n }\n}\n","'use strict';\n\nconst WebSocket = require('./lib/websocket');\n\nWebSocket.createWebSocketStream = require('./lib/stream');\nWebSocket.Server = require('./lib/websocket-server');\nWebSocket.Receiver = require('./lib/receiver');\nWebSocket.Sender = require('./lib/sender');\n\nWebSocket.WebSocket = WebSocket;\nWebSocket.WebSocketServer = WebSocket.Server;\n\nmodule.exports = WebSocket;\n","/**\n * Version management for @episoda/core\n *\n * EP812: Updated to be bundle-safe. When bundled into CLI by tsup,\n * the package.json path lookup fails because __dirname changes.\n * Now tries package.json first, falls back to hardcoded version.\n *\n * IMPORTANT: Keep FALLBACK_VERSION in sync with package.json version!\n * This should be updated when running `npm version` in the core package.\n */\n\nimport { readFileSync, existsSync } from 'fs'\nimport { join } from 'path'\n\n// Fallback version for bundled usage (update with package.json!)\nconst FALLBACK_VERSION = '0.1.11'\n\nfunction getVersion(): string {\n try {\n // Try to read from package.json (works when running from source)\n const packageJsonPath = join(__dirname, '..', 'package.json')\n if (existsSync(packageJsonPath)) {\n const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8'))\n return packageJson.version\n }\n } catch {\n // Bundled or path doesn't exist - use fallback\n }\n return FALLBACK_VERSION\n}\n\nexport const VERSION: string = getVersion()\n","/**\n * Episoda WebSocket Client\n *\n * EP589-9: Implemented with comprehensive error handling and reconnection logic\n *\n * Provides reliable WebSocket connection to episoda.dev CLI gateway with:\n * - Automatic reconnection with exponential backoff\n * - Heartbeat/ping-pong to keep connection alive\n * - Event-driven architecture for handling server commands\n * - Graceful error handling and recovery\n */\n\nimport WS from 'ws'\nimport https from 'https'\nimport { ServerMessage, ClientMessage, ConnectionStatus } from './command-protocol'\nimport { VERSION } from './version'\n\n// EP801: Create HTTPS agent that forces IPv4 to avoid IPv6 timeout issues\n// Many networks have IPv6 configured but not fully routable, causing connection failures\nconst ipv4Agent = new https.Agent({ family: 4 })\n\n// EP701: Client-side events emitted by EpisodaClient\nexport type DisconnectEvent = {\n type: 'disconnected'\n code: number\n reason: string\n willReconnect: boolean\n}\n\nexport type ClientEvent = ServerMessage | DisconnectEvent\n\nexport type EventHandler = (event: ClientEvent) => void | Promise<void>\n\n// EP605: Reconnection configuration for long-term stability\nconst INITIAL_RECONNECT_DELAY = 1000 // 1 second\nconst MAX_RECONNECT_DELAY = 60000 // 60 seconds standard max\nconst IDLE_RECONNECT_DELAY = 600000 // 10 minutes when idle (no commands for 1+ hour)\nconst MAX_RETRY_DURATION = 6 * 60 * 60 * 1000 // 6 hours maximum retry duration\nconst IDLE_THRESHOLD = 60 * 60 * 1000 // 1 hour - after this, use slower retry\n\n// EP648: Rate limit and rapid reconnect prevention\nconst RATE_LIMIT_BACKOFF = 60000 // 60 seconds when rate limited\nconst RAPID_CLOSE_THRESHOLD = 2000 // If connection closes within 2s, it's likely an error\nconst RAPID_CLOSE_BACKOFF = 30000 // 30 seconds backoff for rapid close scenarios\n\n// EP605: Client-side heartbeat to detect dead connections\n// EP846-7: Aligned to 20s (was 45s) - server is 15s, so intervals don't collide\nconst CLIENT_HEARTBEAT_INTERVAL = 20000 // 20 seconds (offset from server's 15s)\nconst CLIENT_HEARTBEAT_TIMEOUT = 15000 // 15 seconds to wait for pong\n\n// EP606: Connection timeout for initial WebSocket connection\nconst CONNECTION_TIMEOUT = 15000 // 15 seconds to establish connection\n\n// EP1267: Reconnect backoff caps + jitter to avoid thundering herds\nconst MAX_LOCAL_RECONNECT_DELAY = 300000 // 5 minutes max\nconst RECONNECT_JITTER_RATIO = 0.2 // +/-20%\n\n/**\n * WebSocket client for connecting to episoda.dev/cli gateway\n *\n * DESIGN PRINCIPLES:\n * - Reverse WebSocket: Client connects TO server (bypasses NAT/firewall)\n * - Automatic reconnection with exponential backoff\n * - Server-initiated heartbeat via WebSocket ping/pong (15s interval)\n * - Event-driven architecture for handling server commands\n */\nexport class EpisodaClient {\n private ws?: WS\n private eventHandlers: Map<string, EventHandler[]> = new Map()\n private reconnectAttempts = 0\n private reconnectTimeout?: NodeJS.Timeout\n private url = ''\n private token = ''\n private machineId?: string\n private hostname?: string\n private osPlatform?: string\n private osArch?: string\n private daemonPid?: number\n // EP1119: Environment type and container ID for cloud routing\n private environment?: 'local' | 'cloud'\n private containerId?: string\n private isConnected = false\n private isDisconnecting = false\n private isGracefulShutdown = false // Track if shutdown was graceful (server-initiated)\n // EP605: Client-side heartbeat for connection health monitoring\n private heartbeatTimer?: NodeJS.Timeout\n private heartbeatTimeoutTimer?: NodeJS.Timeout\n // EP605: Activity and retry duration tracking\n private lastCommandTime = Date.now() // Track last command for idle detection\n private firstDisconnectTime?: number // Track when reconnection attempts started\n private isIntentionalDisconnect = false // Prevent reconnection after intentional disconnect\n // EP648: Rate limit and rapid reconnect tracking\n private rateLimitBackoffUntil?: number // Timestamp until which we should wait (rate limited)\n private lastConnectAttemptTime = 0 // Track when we last attempted to connect\n private lastErrorCode?: string // Track the last error code received\n // EP1210-6: Track consecutive auth failures for cloud mode\n // After 3 consecutive auth failures, give up (token is likely invalid/expired)\n private consecutiveAuthFailures = 0\n\n /**\n * Connect to episoda.dev WebSocket gateway\n * @param url - WebSocket URL (wss://episoda.dev/cli)\n * @param token - OAuth access token\n * @param machineId - Optional machine identifier for multi-machine support\n * @param deviceInfo - Optional device information (hostname, OS, daemonPid)\n * EP1119: Added environment and containerId for cloud routing\n */\n async connect(\n url: string,\n token: string,\n machineId?: string,\n deviceInfo?: { hostname?: string; osPlatform?: string; osArch?: string; daemonPid?: number; environment?: 'local' | 'cloud'; containerId?: string }\n ): Promise<void> {\n this.url = url\n this.token = token\n this.machineId = machineId\n this.hostname = deviceInfo?.hostname\n this.osPlatform = deviceInfo?.osPlatform\n this.osArch = deviceInfo?.osArch\n this.daemonPid = deviceInfo?.daemonPid\n // EP1119: Store environment and containerId for auth message\n this.environment = deviceInfo?.environment\n this.containerId = deviceInfo?.containerId\n this.isDisconnecting = false\n this.isGracefulShutdown = false // Reset graceful shutdown flag on new connection\n this.isIntentionalDisconnect = false // Allow reconnection on fresh connect\n this.lastConnectAttemptTime = Date.now() // EP648: Track when this connection attempt started\n this.lastErrorCode = undefined // EP648: Clear last error code\n\n // EP816: Close any existing WebSocket before creating a new one\n // This prevents orphaned connections when connect() is called multiple times\n if (this.ws) {\n try {\n this.ws.removeAllListeners() // Prevent close handler from triggering reconnect\n this.ws.terminate()\n } catch {\n // Ignore errors during cleanup\n }\n this.ws = undefined\n }\n\n // Clear any pending reconnect timer to prevent race conditions\n if (this.reconnectTimeout) {\n clearTimeout(this.reconnectTimeout)\n this.reconnectTimeout = undefined\n }\n\n return new Promise((resolve, reject) => {\n // EP606: Connection timeout to prevent hanging indefinitely\n const connectionTimeout = setTimeout(() => {\n if (this.ws) {\n this.ws.terminate()\n }\n reject(new Error(`Connection timeout after ${CONNECTION_TIMEOUT / 1000}s - server may be unreachable`))\n }, CONNECTION_TIMEOUT)\n\n try {\n // EP801: Use IPv4 agent to avoid IPv6 timeout issues on networks with broken IPv6\n this.ws = new WS(url, { agent: ipv4Agent })\n\n // Connection opened\n this.ws.on('open', () => {\n clearTimeout(connectionTimeout) // EP606: Clear timeout on successful connection\n console.log('[EpisodaClient] WebSocket connected')\n this.isConnected = true\n this.reconnectAttempts = 0\n this.firstDisconnectTime = undefined // EP605: Reset retry duration tracking\n this.lastCommandTime = Date.now() // EP605: Reset activity timer\n\n // Send auth message (K722: includes machineId, EP596: includes device info, EP601: includes daemonPid)\n // EP1119: Added environment and containerId for explicit cloud routing (replaces hetzner- prefix hack)\n this.send({\n type: 'auth',\n token,\n version: VERSION,\n environment: this.environment,\n machineId,\n containerId: this.containerId,\n hostname: this.hostname,\n osPlatform: this.osPlatform,\n osArch: this.osArch,\n daemonPid: this.daemonPid\n })\n\n // EP605: Start client-side heartbeat\n this.startHeartbeat()\n\n resolve()\n })\n\n // EP605: Handle pong response from server (for client-initiated pings)\n this.ws.on('pong', () => {\n // Clear the timeout - connection is alive\n if (this.heartbeatTimeoutTimer) {\n clearTimeout(this.heartbeatTimeoutTimer)\n this.heartbeatTimeoutTimer = undefined\n }\n })\n\n // Message received\n this.ws.on('message', (data: WS.Data) => {\n try {\n const message = JSON.parse(data.toString()) as ServerMessage\n this.handleMessage(message)\n } catch (error) {\n console.error('[EpisodaClient] Failed to parse message:', error)\n }\n })\n\n // EP603: Log ping events for debugging connection health\n this.ws.on('ping', () => {\n console.log('[EpisodaClient] Received ping from server')\n })\n\n // Connection closed\n this.ws.on('close', (code: number, reason: Buffer) => {\n console.log(`[EpisodaClient] WebSocket closed: ${code} ${reason.toString()}`)\n this.isConnected = false\n\n const willReconnect = !this.isDisconnecting\n\n // EP701: Emit 'disconnected' event so daemon can clean up connection\n this.emit({\n type: 'disconnected',\n code,\n reason: reason.toString(),\n willReconnect\n })\n\n // Attempt reconnection if not intentional disconnect\n if (willReconnect) {\n this.scheduleReconnect()\n }\n })\n\n // Error occurred\n this.ws.on('error', (error: Error) => {\n console.error('[EpisodaClient] WebSocket error:', error)\n\n if (!this.isConnected) {\n // Connection failed, reject the promise\n clearTimeout(connectionTimeout) // EP606: Clear timeout on error\n reject(error)\n }\n })\n\n } catch (error) {\n clearTimeout(connectionTimeout) // EP606: Clear timeout on exception\n reject(error)\n }\n })\n }\n\n /**\n * Disconnect from the server\n * @param intentional - If true, prevents automatic reconnection (user-initiated disconnect)\n */\n async disconnect(intentional = true): Promise<void> {\n this.isDisconnecting = true\n this.isIntentionalDisconnect = intentional // EP605: Prevent reconnection if user intentionally disconnected\n\n // EP605: Clear all timers\n if (this.reconnectTimeout) {\n clearTimeout(this.reconnectTimeout)\n this.reconnectTimeout = undefined\n }\n\n if (this.heartbeatTimer) {\n clearInterval(this.heartbeatTimer)\n this.heartbeatTimer = undefined\n }\n\n if (this.heartbeatTimeoutTimer) {\n clearTimeout(this.heartbeatTimeoutTimer)\n this.heartbeatTimeoutTimer = undefined\n }\n\n if (this.ws) {\n this.ws.close()\n this.ws = undefined\n }\n\n this.isConnected = false\n }\n\n /**\n * Register an event handler\n * @param event - Event type ('command', 'ping', 'error', 'auth_success')\n * @param handler - Handler function\n */\n on(event: string, handler: EventHandler): void {\n if (!this.eventHandlers.has(event)) {\n this.eventHandlers.set(event, [])\n }\n this.eventHandlers.get(event)!.push(handler)\n }\n\n /**\n * EP812: Register a one-time event handler (removes itself after first call)\n * @param event - Event type\n * @param handler - Handler function\n */\n once(event: string, handler: EventHandler): void {\n const onceHandler: EventHandler = (message) => {\n this.off(event, onceHandler)\n // EP1098: Return the result so async handler errors can be caught by handleMessage\n return handler(message)\n }\n this.on(event, onceHandler)\n }\n\n /**\n * EP812: Remove an event handler\n * @param event - Event type\n * @param handler - Handler function to remove\n */\n off(event: string, handler: EventHandler): void {\n const handlers = this.eventHandlers.get(event)\n if (handlers) {\n const index = handlers.indexOf(handler)\n if (index !== -1) {\n handlers.splice(index, 1)\n }\n }\n }\n\n /**\n * EP1034: Remove all event handlers\n * Useful when completely resetting a client or when the daemon\n * disconnects a project and creates a fresh connection.\n * Note: Internal reconnection (scheduleReconnect) uses the same client instance,\n * so handlers persist across reconnects - this is by design.\n */\n clearAllHandlers(): void {\n this.eventHandlers.clear()\n }\n\n /**\n * Send a message to the server\n * @param message - Client message to send\n * @returns true if message was sent, false if not connected\n *\n * EP1034: Changed to return false instead of throwing when disconnected.\n * This prevents daemon crashes when async operations complete during reconnection.\n */\n async send(message: ClientMessage): Promise<boolean> {\n if (!this.ws || !this.isConnected) {\n console.warn('[EpisodaClient] Cannot send - WebSocket not connected')\n return false\n }\n\n return new Promise((resolve) => {\n this.ws!.send(JSON.stringify(message), (error) => {\n if (error) {\n console.error('[EpisodaClient] Failed to send message:', error)\n resolve(false)\n } else {\n resolve(true)\n }\n })\n })\n }\n\n /**\n * Get current connection status\n */\n getStatus(): ConnectionStatus {\n return {\n connected: this.isConnected\n }\n }\n\n /**\n * EP949: Update the access token (used when server sends token_refresh message)\n * This updates the in-memory token used for reconnection.\n */\n updateToken(newToken: string): void {\n console.log('[EpisodaClient] EP949: Access token updated')\n this.token = newToken\n }\n\n /**\n * EP605: Update last command time to reset idle detection\n * Call this when a command is received/executed\n */\n updateActivity(): void {\n this.lastCommandTime = Date.now()\n }\n\n /**\n * EP701: Emit a client-side event to registered handlers\n * Used for events like 'disconnected' that originate from the client, not server\n * EP1095: Fixed to handle async handlers - catches both sync errors and promise rejections\n */\n private emit(event: ClientEvent): void {\n const handlers = this.eventHandlers.get(event.type) || []\n handlers.forEach(handler => {\n try {\n const result = handler(event)\n // EP1095: If handler returns a promise, catch any rejections\n if (result && typeof result === 'object' && 'catch' in result && typeof result.catch === 'function') {\n (result as Promise<void>).catch(error => {\n console.error(`[EpisodaClient] Async handler error for ${event.type}:`, error)\n })\n }\n } catch (error) {\n console.error(`[EpisodaClient] Handler error for ${event.type}:`, error)\n }\n })\n }\n\n /**\n * Handle incoming message from server\n */\n private handleMessage(message: ServerMessage): void {\n // Special handling for graceful shutdown messages from server\n if (message.type === 'shutdown') {\n console.log('[EpisodaClient] Received graceful shutdown message from server')\n this.isGracefulShutdown = true\n }\n\n // EP648: Handle error messages, especially rate limiting and rapid reconnect\n if (message.type === 'error') {\n const errorMessage = message as ServerMessage & { code?: string; retryAfter?: number }\n this.lastErrorCode = errorMessage.code\n\n if (errorMessage.code === 'RATE_LIMITED' || errorMessage.code === 'TOO_SOON') {\n // Use server-provided retryAfter or default to 60 seconds for rate limit, 5 seconds for too soon\n const defaultRetry = errorMessage.code === 'RATE_LIMITED' ? 60 : 5\n const retryAfterMs = (errorMessage.retryAfter || defaultRetry) * 1000\n this.rateLimitBackoffUntil = Date.now() + retryAfterMs\n console.log(`[EpisodaClient] ${errorMessage.code}: will retry after ${retryAfterMs / 1000}s`)\n }\n\n // EP1210-6: Track consecutive auth failures for cloud mode\n // Auth failures indicate the token is invalid/expired - no point retrying forever\n if (errorMessage.code === 'AUTH_FAILED' || errorMessage.code === 'UNAUTHORIZED' || errorMessage.code === 'INVALID_TOKEN') {\n this.consecutiveAuthFailures++\n console.warn(`[EpisodaClient] Auth failure (${this.consecutiveAuthFailures}): ${errorMessage.code}`)\n }\n }\n\n const handlers = this.eventHandlers.get(message.type) || []\n\n // Execute all handlers for this message type\n // EP1098: Fixed to catch async handler promise rejections (prevents daemon crash on machine_uuid_update)\n handlers.forEach(handler => {\n try {\n const result = handler(message)\n // If handler returns a promise, catch any rejections to prevent unhandled rejection crash\n if (result && typeof result === 'object' && 'catch' in result && typeof result.catch === 'function') {\n (result as Promise<void>).catch(error => {\n console.error(`[EpisodaClient] Async handler error for ${message.type}:`, error)\n })\n }\n } catch (error) {\n console.error(`[EpisodaClient] Handler error for ${message.type}:`, error)\n }\n })\n }\n\n /**\n * Schedule reconnection with simplified retry logic\n *\n * EP843: Simplified from complex exponential backoff to fast-fail approach\n *\n * Strategy:\n * - For graceful shutdown (server restart): Quick retry (500ms, 1s, 2s) up to 3 attempts\n * - For other disconnects: 1 retry after 1 second, then stop\n * - Always respect rate limits from server\n * - Surface errors quickly so user can take action\n *\n * This replaces the previous 6-hour retry with exponential backoff,\n * which masked problems and delayed error visibility.\n */\n private scheduleReconnect(): void {\n const applyJitter = (baseDelay: number): number => {\n const jitter = baseDelay * RECONNECT_JITTER_RATIO\n const randomized = baseDelay + (Math.random() * 2 - 1) * jitter\n return Math.max(250, Math.round(randomized))\n }\n\n // Don't reconnect if user intentionally disconnected\n if (this.isIntentionalDisconnect) {\n console.log('[EpisodaClient] Intentional disconnect - not reconnecting')\n return\n }\n\n // Don't schedule if reconnection is already pending\n if (this.reconnectTimeout) {\n console.log('[EpisodaClient] Reconnection already scheduled, skipping duplicate')\n return\n }\n\n // Clear heartbeat timers before reconnection attempt\n if (this.heartbeatTimer) {\n clearInterval(this.heartbeatTimer)\n this.heartbeatTimer = undefined\n }\n\n if (this.heartbeatTimeoutTimer) {\n clearTimeout(this.heartbeatTimeoutTimer)\n this.heartbeatTimeoutTimer = undefined\n }\n\n // Check if we're still in rate limit backoff period\n if (this.rateLimitBackoffUntil && Date.now() < this.rateLimitBackoffUntil) {\n const waitTime = this.rateLimitBackoffUntil - Date.now()\n console.log(`[EpisodaClient] Rate limited, waiting ${Math.round(waitTime / 1000)}s before retry`)\n this.reconnectAttempts++\n this.reconnectTimeout = setTimeout(() => {\n this.rateLimitBackoffUntil = undefined\n this.scheduleReconnect()\n }, waitTime)\n return\n }\n\n // EP843: Simplified retry logic\n // EP1210-6/EP1267: Never stop reconnecting (except for auth failures in cloud mode)\n let delay: number\n let shouldRetry = true\n\n // EP1210-6: Cloud containers must never give up reconnecting\n // The only way to \"restart\" a cloud container is to recreate it, so we must persist.\n // Only give up after 3 consecutive auth failures (token is likely invalid/expired).\n const isCloudMode = this.environment === 'cloud'\n const MAX_CLOUD_AUTH_FAILURES = 3\n const MAX_CLOUD_RECONNECT_DELAY = 300000 // 5 minutes max delay for cloud\n\n if (isCloudMode) {\n // EP1210-6: Never-give-up reconnection for cloud mode\n if (this.consecutiveAuthFailures >= MAX_CLOUD_AUTH_FAILURES) {\n console.error(`[EpisodaClient] Cloud mode: ${MAX_CLOUD_AUTH_FAILURES} consecutive auth failures - token may be invalid. Giving up.`)\n shouldRetry = false\n } else {\n // Exponential backoff capped at 5 minutes: 1s, 2s, 4s, 8s, ... 300s\n delay = Math.min(1000 * Math.pow(2, this.reconnectAttempts), MAX_CLOUD_RECONNECT_DELAY)\n delay = applyJitter(delay)\n const delayStr = delay >= 60000 ? `${Math.round(delay / 60000)}m` : `${Math.round(delay / 1000)}s`\n console.log(`[EpisodaClient] Cloud mode: reconnecting in ${delayStr}... (attempt ${this.reconnectAttempts + 1}, never giving up)`)\n }\n } else if (this.isGracefulShutdown && this.reconnectAttempts < 7) {\n // Graceful shutdown (server restart): Quick retry burst before falling back to long retry\n // Retry schedule: 500ms, 1s, 2s, 4s, 5s, 5s, 5s = ~22.5s total coverage\n delay = Math.min(500 * Math.pow(2, this.reconnectAttempts), 5000)\n delay = applyJitter(delay)\n console.log(`[EpisodaClient] Server restarting, reconnecting in ${delay}ms (attempt ${this.reconnectAttempts + 1}/7)`)\n } else {\n // EP956/EP1267: Non-graceful disconnects (code 1006 etc): keep retrying with backoff\n // Exponential backoff capped at 5 minutes: 1s, 2s, 4s, 8s, ... 300s\n delay = Math.min(1000 * Math.pow(2, this.reconnectAttempts), MAX_LOCAL_RECONNECT_DELAY)\n delay = applyJitter(delay)\n const delayStr = delay >= 60000 ? `${Math.round(delay / 60000)}m` : `${Math.round(delay / 1000)}s`\n console.log(`[EpisodaClient] Connection lost, retrying in ${delayStr}... (attempt ${this.reconnectAttempts + 1}, retrying until connected)`)\n }\n\n if (!shouldRetry) {\n // Emit disconnected event so daemon can handle it\n this.emit({\n type: 'disconnected',\n code: 1006,\n reason: 'Reconnection attempts exhausted',\n willReconnect: false\n })\n return\n }\n\n this.reconnectAttempts++\n\n this.reconnectTimeout = setTimeout(() => {\n console.log('[EpisodaClient] Attempting reconnection...')\n // EP1119: Include environment and containerId in reconnection\n this.connect(this.url, this.token, this.machineId, {\n hostname: this.hostname,\n osPlatform: this.osPlatform,\n osArch: this.osArch,\n daemonPid: this.daemonPid,\n environment: this.environment,\n containerId: this.containerId\n }).then(() => {\n console.log('[EpisodaClient] Reconnection successful')\n this.reconnectAttempts = 0\n this.isGracefulShutdown = false\n this.firstDisconnectTime = undefined\n this.rateLimitBackoffUntil = undefined\n // EP1210-6: Reset auth failure counter on successful connection\n this.consecutiveAuthFailures = 0\n }).catch(error => {\n console.error('[EpisodaClient] Reconnection failed:', error.message)\n // scheduleReconnect will be called again from the 'close' event\n })\n }, delay!)\n }\n\n /**\n * EP605: Start client-side heartbeat to detect dead connections\n *\n * Sends ping every 45 seconds and expects pong within 15 seconds.\n * If no pong received, terminates connection to trigger reconnection.\n */\n private startHeartbeat(): void {\n // Clear any existing heartbeat\n if (this.heartbeatTimer) {\n clearInterval(this.heartbeatTimer)\n }\n\n this.heartbeatTimer = setInterval(() => {\n if (!this.ws || this.ws.readyState !== WS.OPEN) {\n return\n }\n\n // Send ping\n try {\n this.ws.ping()\n\n // Clear any existing timeout before setting new one (prevents timer leak)\n if (this.heartbeatTimeoutTimer) {\n clearTimeout(this.heartbeatTimeoutTimer)\n }\n\n // Set timeout for pong response\n this.heartbeatTimeoutTimer = setTimeout(() => {\n console.log('[EpisodaClient] Heartbeat timeout - no pong received, terminating connection')\n if (this.ws) {\n this.ws.terminate() // Force close to trigger reconnection\n }\n }, CLIENT_HEARTBEAT_TIMEOUT)\n } catch (error) {\n console.error('[EpisodaClient] Error sending heartbeat ping:', error)\n }\n }, CLIENT_HEARTBEAT_INTERVAL)\n }\n}\n","/**\n * Authentication utilities\n */\n\nimport * as fs from 'fs'\nimport * as path from 'path'\nimport * as os from 'os'\nimport { execSync } from 'child_process'\nimport { EpisodaConfig } from './command-protocol'\n\nconst DEFAULT_CONFIG_FILE = 'config.json'\nlet hasWarnedMissingProjectId = false\nlet hasWarnedMissingRequiredFields = false\n\n/**\n * Get the config directory path\n * Supports EPISODA_CONFIG_DIR env var for running multiple environments\n */\nexport function getConfigDir(): string {\n return process.env.EPISODA_CONFIG_DIR || path.join(os.homedir(), '.episoda')\n}\n\n/**\n * Get the full path to the config file\n */\nexport function getConfigPath(configPath?: string): string {\n if (configPath) {\n return configPath\n }\n return path.join(getConfigDir(), DEFAULT_CONFIG_FILE)\n}\n\n/**\n * Ensure the config directory exists\n *\n * EP798: Also excludes the directory from iCloud/Dropbox sync on macOS\n * to prevent machine-specific files (machine-id, daemon.sock) from syncing.\n */\nfunction ensureConfigDir(configPath: string): void {\n const dir = path.dirname(configPath)\n const isNew = !fs.existsSync(dir)\n\n if (isNew) {\n fs.mkdirSync(dir, { recursive: true, mode: 0o700 })\n }\n\n // EP798: Exclude from cloud sync on macOS\n // Only do this once when directory is created (or if .nosync doesn't exist)\n if (process.platform === 'darwin') {\n const nosyncPath = path.join(dir, '.nosync')\n if (isNew || !fs.existsSync(nosyncPath)) {\n try {\n // Create .nosync file (respected by some cloud services)\n fs.writeFileSync(nosyncPath, '', { mode: 0o600 })\n // Set iCloud-specific exclusion attribute\n execSync(`xattr -w com.apple.fileprovider.ignore 1 \"${dir}\"`, {\n stdio: 'ignore',\n timeout: 5000\n })\n } catch {\n // Ignore errors - xattr may not be available or dir may already be excluded\n }\n }\n }\n}\n\n/**\n * Load configuration from .episoda/config.json or environment variables.\n *\n * EP945: Added environment variable fallback for cloud container mode.\n * EP1143/K1273: Added workspace-level config for per-user-per-workspace containers.\n *\n * Priority:\n * 1. Config file (~/.episoda/config.json) - for local development\n * 2. K1273: Workspace config (~/episoda/{workspace}/.episoda/config.json) - for cloud containers\n * 3. Environment variables - for cloud/container deployment\n */\nexport async function loadConfig(configPath?: string): Promise<EpisodaConfig | null> {\n const fullPath = getConfigPath(configPath)\n const isCloudMode = process.env.EPISODA_MODE === 'cloud'\n\n const readConfigFile = (pathToFile: string): EpisodaConfig | null => {\n if (!fs.existsSync(pathToFile)) {\n return null\n }\n try {\n const content = fs.readFileSync(pathToFile, 'utf8')\n return JSON.parse(content) as EpisodaConfig\n } catch (error) {\n console.error('Error loading config:', error)\n return null\n }\n }\n\n const envValue = (value?: string): string | undefined => {\n if (!value) return undefined\n const trimmed = value.trim()\n return trimmed.length > 0 ? trimmed : undefined\n }\n\n const buildEnvConfig = (): Partial<EpisodaConfig> | null => {\n if (!process.env.EPISODA_ACCESS_TOKEN) {\n return null\n }\n\n const expiresAtEnv = envValue(process.env.EPISODA_ACCESS_TOKEN_EXPIRES_AT)\n const expires_at = expiresAtEnv ? parseInt(expiresAtEnv, 10) : undefined\n\n const config: Partial<EpisodaConfig> = {\n access_token: process.env.EPISODA_ACCESS_TOKEN,\n refresh_token: envValue(process.env.EPISODA_REFRESH_TOKEN),\n expires_at,\n api_url: envValue(process.env.EPISODA_API_URL) || 'https://episoda.dev',\n project_id: envValue(process.env.EPISODA_PROJECT_ID),\n user_id: envValue(process.env.EPISODA_USER_ID),\n workspace_id: envValue(process.env.EPISODA_WORKSPACE_ID),\n workspace_slug: envValue(process.env.EPISODA_WORKSPACE),\n project_slug: envValue(process.env.EPISODA_PROJECT),\n machine_uuid: envValue(process.env.EPISODA_CONTAINER_ID),\n }\n\n return config\n }\n\n const buildWorkspaceConfig = (): Partial<EpisodaConfig> | null => {\n if (!process.env.EPISODA_WORKSPACE) {\n return null\n }\n const homeDir = process.env.HOME || require('os').homedir()\n const workspaceConfigPath = require('path').join(\n homeDir, 'episoda', process.env.EPISODA_WORKSPACE, '.episoda', 'config.json'\n )\n\n if (!fs.existsSync(workspaceConfigPath)) {\n return null\n }\n\n try {\n const content = fs.readFileSync(workspaceConfigPath, 'utf8')\n const workspaceConfig = JSON.parse(content)\n\n const expiresAtEnv = envValue(process.env.EPISODA_ACCESS_TOKEN_EXPIRES_AT)\n\n return {\n access_token: envValue(process.env.EPISODA_ACCESS_TOKEN) || workspaceConfig.accessToken,\n refresh_token: envValue(process.env.EPISODA_REFRESH_TOKEN),\n expires_at: expiresAtEnv ? parseInt(expiresAtEnv, 10) : undefined,\n api_url: envValue(process.env.EPISODA_API_URL) || 'https://episoda.dev',\n user_id: envValue(process.env.EPISODA_USER_ID) || workspaceConfig.userId,\n workspace_id: envValue(process.env.EPISODA_WORKSPACE_ID) || workspaceConfig.workspaceId,\n workspace_slug: envValue(process.env.EPISODA_WORKSPACE) || workspaceConfig.workspaceSlug,\n project_id: envValue(process.env.EPISODA_PROJECT_ID) || workspaceConfig.projectId || workspaceConfig.project_id,\n project_slug: envValue(process.env.EPISODA_PROJECT) || workspaceConfig.projectSlug || workspaceConfig.project_slug,\n machine_uuid: envValue(process.env.EPISODA_CONTAINER_ID) || workspaceConfig.containerId,\n }\n } catch (error) {\n console.error('Error loading workspace config:', error)\n return null\n }\n }\n\n const buildProjectConfig = (): Partial<EpisodaConfig> | null => {\n const workspaceSlug = envValue(process.env.EPISODA_WORKSPACE)\n const projectSlug = envValue(process.env.EPISODA_PROJECT)\n\n if (!workspaceSlug || !projectSlug) {\n return null\n }\n\n const homeDir = process.env.HOME || require('os').homedir()\n const projectConfigPath = require('path').join(\n homeDir, 'episoda', workspaceSlug, projectSlug, '.episoda', 'config.json'\n )\n\n if (!fs.existsSync(projectConfigPath)) {\n return null\n }\n\n try {\n const content = fs.readFileSync(projectConfigPath, 'utf8')\n const projectConfig = JSON.parse(content)\n\n return {\n project_id: projectConfig.projectId || projectConfig.project_id,\n project_slug: projectConfig.projectSlug || projectSlug,\n workspace_slug: projectConfig.workspaceSlug || workspaceSlug,\n }\n } catch (error) {\n console.error('Error loading project config:', error)\n return null\n }\n }\n\n const fileConfig = readConfigFile(fullPath)\n\n if (!isCloudMode) {\n if (fileConfig) {\n return fileConfig\n }\n\n const envConfig = buildEnvConfig()\n if (envConfig) {\n return envConfig as EpisodaConfig\n }\n\n return null\n }\n\n // Cloud mode: merge config file + workspace config + env vars (env wins)\n const workspaceConfig = buildWorkspaceConfig()\n const projectConfig = buildProjectConfig()\n const envConfig = buildEnvConfig()\n\n const mergedConfig: Partial<EpisodaConfig> = {\n ...(fileConfig || {}),\n ...(workspaceConfig || {}),\n ...(projectConfig || {}),\n ...(envConfig || {})\n }\n\n if (Object.keys(mergedConfig).length === 0) {\n return null\n }\n\n const requiredFields: Array<keyof EpisodaConfig> = [\n 'access_token',\n 'api_url',\n 'user_id',\n 'workspace_id'\n ]\n\n const missingFields = requiredFields.filter((field) => !mergedConfig[field])\n if (missingFields.length > 0) {\n if (!hasWarnedMissingRequiredFields) {\n console.warn('[Auth] Cloud config missing required fields', {\n missing: missingFields,\n sources: {\n file: Boolean(fileConfig),\n workspace: Boolean(workspaceConfig),\n project: Boolean(projectConfig),\n env: Boolean(envConfig)\n }\n })\n hasWarnedMissingRequiredFields = true\n }\n return null\n }\n\n if (!mergedConfig.project_id && !hasWarnedMissingProjectId) {\n console.warn('[Auth] Cloud config missing project_id; running in workspace mode')\n hasWarnedMissingProjectId = true\n }\n\n return mergedConfig as EpisodaConfig\n}\n\n/**\n * Save configuration to .episoda/config.json\n */\nexport async function saveConfig(config: EpisodaConfig, configPath?: string): Promise<void> {\n const fullPath = getConfigPath(configPath)\n ensureConfigDir(fullPath)\n\n try {\n const content = JSON.stringify(config, null, 2)\n fs.writeFileSync(fullPath, content, { mode: 0o600 })\n } catch (error) {\n throw new Error(`Failed to save config: ${error instanceof Error ? error.message : String(error)}`)\n }\n}\n\n/**\n * Validate an access token\n */\nexport async function validateToken(token: string): Promise<boolean> {\n // For now, just check if token exists and is non-empty\n // In the future, we can make an API call to validate\n return Boolean(token && token.length > 0)\n}\n","/**\n * Error handling utilities\n */\n\nimport { ErrorCode } from './command-protocol'\n\n/**\n * Custom error class for Episoda operations\n */\nexport class EpisodaError extends Error {\n constructor(\n public code: ErrorCode,\n message: string,\n public details?: Record<string, any>\n ) {\n super(message)\n this.name = 'EpisodaError'\n }\n}\n\n// Note: parseGitError is exported from git-parser.ts\n\n/**\n * Create a user-friendly error message from error code\n * (For CLI use - MCP will format differently)\n */\nexport function formatErrorMessage(code: ErrorCode, details?: Record<string, any>): string {\n const messages: Record<ErrorCode, string> = {\n 'GIT_NOT_INSTALLED': 'Git is not installed or not in PATH',\n 'NOT_GIT_REPO': 'Not a git repository',\n 'MERGE_CONFLICT': 'Merge conflict detected',\n 'REBASE_CONFLICT': 'Rebase conflict detected - resolve conflicts or abort rebase',\n 'UNCOMMITTED_CHANGES': 'Uncommitted changes would be overwritten',\n 'NETWORK_ERROR': 'Network error occurred',\n 'AUTH_FAILURE': 'Authentication failed',\n 'BRANCH_NOT_FOUND': 'Branch not found',\n 'BRANCH_ALREADY_EXISTS': 'Branch already exists',\n 'PUSH_REJECTED': 'Push rejected by remote',\n 'COMMAND_TIMEOUT': 'Command timed out',\n // EP944: Worktree error messages\n 'WORKTREE_EXISTS': 'Worktree already exists at this path',\n 'WORKTREE_NOT_FOUND': 'Worktree not found at this path',\n 'WORKTREE_LOCKED': 'Worktree is locked',\n 'BRANCH_IN_USE': 'Branch is already checked out in another worktree',\n // EP1002: Worktree setup error messages\n 'NOT_IMPLEMENTED': 'Command not implemented in this context',\n 'SETUP_FAILED': 'Worktree setup failed',\n 'UNKNOWN_ERROR': 'Unknown error occurred'\n }\n\n let message = messages[code] || `Error: ${code}`\n\n // Add details if provided\n if (details) {\n if (details.uncommittedFiles && details.uncommittedFiles.length > 0) {\n message += `\\nUncommitted files: ${details.uncommittedFiles.join(', ')}`\n }\n if (details.conflictingFiles && details.conflictingFiles.length > 0) {\n message += `\\nConflicting files: ${details.conflictingFiles.join(', ')}`\n }\n if (details.branchName) {\n message += `\\nBranch: ${details.branchName}`\n }\n }\n\n return message\n}\n","/**\n * @episoda/core\n *\n * Reusable business logic for Episoda local development orchestration.\n * Used by both episoda CLI (current) and @episoda/mcp-local-dev (future).\n *\n * DESIGN PRINCIPLES:\n * - Interface-agnostic: No CLI or MCP-specific code\n * - Structured data: Return objects, not formatted strings\n * - Error codes: Return codes, not messages\n * - Reusable: 80% code reuse target for MCP conversion\n */\n\n// Core types (LOCKED for Phase 2)\nexport * from './command-protocol'\n\n// Business logic classes\nexport { GitExecutor } from './git-executor'\nexport { EpisodaClient, type DisconnectEvent, type ClientEvent, type EventHandler } from './websocket-client'\n\n// Utilities\nexport * from './auth'\nexport * from './errors'\nexport * from './git-validator'\nexport * from './git-parser'\n\n// Package version - single source of truth from package.json\nexport { VERSION } from './version'\n","import { loadConfig } from '@episoda/core'\n\nconst DEFAULT_API_URL = 'https://episoda.dev'\n\nexport interface RuntimeConfig {\n apiUrl: string\n sessionToken: string\n projectId: string\n workspaceId: string\n}\n\nconst normalizeEnv = (value?: string): string | undefined => {\n if (!value) return undefined\n const trimmed = value.trim()\n return trimmed.length > 0 ? trimmed : undefined\n}\n\nconst readEnvConfig = () => ({\n apiUrl: normalizeEnv(process.env.EPISODA_API_URL),\n sessionToken: normalizeEnv(process.env.EPISODA_SESSION_TOKEN),\n projectId: normalizeEnv(process.env.EPISODA_PROJECT_ID),\n workspaceId: normalizeEnv(process.env.EPISODA_WORKSPACE_ID)\n})\n\nconst buildMissingMessage = (missing: string[], apiUrl: string): string => {\n return [\n `[episoda-mcp] Missing auth context: ${missing.join(', ')}`,\n '[episoda-mcp] Set EPISODA_* env vars or run:',\n `[episoda-mcp] episoda auth --api-url ${apiUrl}`\n ].join('\\n')\n}\n\nexport async function resolveRuntimeConfig(): Promise<RuntimeConfig> {\n const envConfig = readEnvConfig()\n\n let fileConfig = null\n if (!envConfig.sessionToken || !envConfig.projectId || !envConfig.workspaceId || !envConfig.apiUrl) {\n fileConfig = await loadConfig()\n }\n\n const resolved: RuntimeConfig = {\n apiUrl: envConfig.apiUrl || fileConfig?.api_url || DEFAULT_API_URL,\n sessionToken: envConfig.sessionToken || fileConfig?.access_token || '',\n projectId: envConfig.projectId || fileConfig?.project_id || '',\n workspaceId: envConfig.workspaceId || fileConfig?.workspace_id || ''\n }\n\n const missing: string[] = []\n if (!resolved.sessionToken) missing.push('EPISODA_SESSION_TOKEN')\n if (!resolved.projectId) missing.push('EPISODA_PROJECT_ID')\n if (!resolved.workspaceId) missing.push('EPISODA_WORKSPACE_ID')\n\n if (missing.length > 0) {\n throw new Error(buildMissingMessage(missing, resolved.apiUrl))\n }\n\n return resolved\n}\n\nexport async function hydrateRuntimeConfig(): Promise<RuntimeConfig> {\n const resolved = await resolveRuntimeConfig()\n\n if (!normalizeEnv(process.env.EPISODA_API_URL)) {\n process.env.EPISODA_API_URL = resolved.apiUrl\n }\n if (!normalizeEnv(process.env.EPISODA_SESSION_TOKEN)) {\n process.env.EPISODA_SESSION_TOKEN = resolved.sessionToken\n }\n if (!normalizeEnv(process.env.EPISODA_PROJECT_ID)) {\n process.env.EPISODA_PROJECT_ID = resolved.projectId\n }\n if (!normalizeEnv(process.env.EPISODA_WORKSPACE_ID)) {\n process.env.EPISODA_WORKSPACE_ID = resolved.workspaceId\n }\n\n return resolved\n}\n","/**\n * EP895-10: Episoda Workflow MCP Server\n *\n * MCP server for Claude Code agents to interact with the Episoda workflow system.\n * Provides tools for:\n * - Task management (create, update, state transitions)\n * - Module management (create, update, state transitions)\n * - Knowledge access (search, get, link)\n *\n * Usage:\n * npx -y @episoda/mcp workflow\n *\n * Required environment variables:\n * EPISODA_API_URL - Base URL for Episoda API (e.g., https://episoda.dev)\n * EPISODA_SESSION_TOKEN - Bearer token for API authentication\n * MODULE_UID - Current module UID (for context)\n */\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'\nimport { z } from 'zod'\nimport { hydrateRuntimeConfig } from './runtime-config.js'\n\n// Environment configuration\nlet EPISODA_API_URL = process.env.EPISODA_API_URL || 'https://episoda.dev'\nlet EPISODA_SESSION_TOKEN = process.env.EPISODA_SESSION_TOKEN || ''\nlet EPISODA_PROJECT_ID = process.env.EPISODA_PROJECT_ID || ''\nlet EPISODA_WORKSPACE_ID = process.env.EPISODA_WORKSPACE_ID || ''\n\n/**\n * Make an authenticated API request\n */\nasync function apiRequest<T>(\n method: 'GET' | 'POST' | 'PATCH' | 'DELETE',\n path: string,\n body?: Record<string, unknown>\n): Promise<T> {\n const url = `${EPISODA_API_URL}${path}`\n const options: RequestInit = {\n method,\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${EPISODA_SESSION_TOKEN}`\n }\n }\n\n if (body && method !== 'GET') {\n options.body = JSON.stringify(body)\n }\n\n if (EPISODA_PROJECT_ID) {\n (options.headers as Record<string, string>)['x-project-id'] = EPISODA_PROJECT_ID\n }\n if (EPISODA_WORKSPACE_ID) {\n (options.headers as Record<string, string>)['x-workspace-id'] = EPISODA_WORKSPACE_ID\n }\n\n const response = await fetch(url, options)\n\n if (!response.ok) {\n const text = await response.text()\n throw new Error(`API error ${response.status}: ${text}`)\n }\n\n return response.json() as Promise<T>\n}\n\n// Create MCP server\nconst server = new McpServer({\n name: 'episoda-workflow',\n version: '1.0.0'\n}, {\n capabilities: {\n tools: {}\n },\n instructions: `\n Episoda Workflow MCP Server\n\n This server provides tools to manage the Episoda development workflow:\n - Tasks: Create, update, and transition task states\n - Modules: Create, update, and transition module states\n - Knowledge: Search, retrieve, and link knowledge documents\n\n Task and module states flow: backlog → doing → review → done\n `\n})\n\n// ============================================\n// Task Management Tools\n// ============================================\n\nserver.registerTool(\n 'create_task',\n {\n description: 'Create a new task within a module',\n inputSchema: {\n module_uid: z.string().describe('The UID of the parent module (e.g., EP584)'),\n title: z.string().describe('Title of the task'),\n description: z.string().optional().describe('Markdown description of the task'),\n type: z.enum(['task', 'bug', 'spike']).optional().describe('Type of task')\n }\n },\n async (args) => {\n interface CreateTaskResponse {\n success: boolean\n task?: { id: string; uid: string; title: string }\n error?: string\n }\n\n const result = await apiRequest<CreateTaskResponse>('POST', '/api/tasks', {\n module_id: args.module_uid, // API expects module_id (accepts both UUID and UID)\n title: args.title,\n description_md: args.description,\n type: args.type || 'task'\n })\n\n if (!result.success) {\n return { content: [{ type: 'text', text: `Error: ${result.error}` }], isError: true }\n }\n\n return {\n content: [{\n type: 'text',\n text: `Created task ${result.task?.uid}: ${result.task?.title}`\n }]\n }\n }\n)\n\nserver.registerTool(\n 'update_task_state',\n {\n description: 'Move a task to a new state (backlog, doing, review, done)',\n inputSchema: {\n task_uid: z.string().describe('The UID of the task (e.g., EP584-1)'),\n state: z.enum(['backlog', 'doing', 'review', 'done']).describe('New state for the task')\n }\n },\n async (args) => {\n interface UpdateTaskResponse {\n success: boolean\n task?: { uid: string; state: string }\n error?: string\n }\n\n const result = await apiRequest<UpdateTaskResponse>('PATCH', `/api/tasks/${args.task_uid}`, {\n state: args.state\n })\n\n if (!result.success) {\n return { content: [{ type: 'text', text: `Error: ${result.error}` }], isError: true }\n }\n\n return {\n content: [{\n type: 'text',\n text: `Task ${args.task_uid} moved to ${args.state}`\n }]\n }\n }\n)\n\nserver.registerTool(\n 'update_task',\n {\n description: 'Update task details (title, description)',\n inputSchema: {\n task_uid: z.string().describe('The UID of the task (e.g., EP584-1)'),\n title: z.string().optional().describe('New title for the task'),\n description: z.string().optional().describe('New markdown description')\n }\n },\n async (args) => {\n interface UpdateTaskResponse {\n success: boolean\n task?: { uid: string; title: string }\n error?: string\n }\n\n const updates: Record<string, string> = {}\n if (args.title) updates.title = args.title\n if (args.description) updates.description_md = args.description\n\n const result = await apiRequest<UpdateTaskResponse>('PATCH', `/api/tasks/${args.task_uid}`, updates)\n\n if (!result.success) {\n return { content: [{ type: 'text', text: `Error: ${result.error}` }], isError: true }\n }\n\n return {\n content: [{\n type: 'text',\n text: `Task ${args.task_uid} updated`\n }]\n }\n }\n)\n\nserver.registerTool(\n 'get_task_details',\n {\n description: 'Get detailed information about a task',\n inputSchema: {\n task_uid: z.string().describe('The UID of the task (e.g., EP584-1)')\n }\n },\n async (args) => {\n interface TaskResponse {\n success: boolean\n task?: {\n uid: string\n title: string\n state: string\n type: string\n description_md: string | null\n module_uid: string\n }\n error?: string\n }\n\n const result = await apiRequest<TaskResponse>('GET', `/api/tasks/${args.task_uid}`)\n\n if (!result.success || !result.task) {\n return { content: [{ type: 'text', text: `Error: ${result.error || 'Task not found'}` }], isError: true }\n }\n\n const task = result.task\n return {\n content: [{\n type: 'text',\n text: `# ${task.uid}: ${task.title}\n\n**State:** ${task.state}\n**Type:** ${task.type}\n**Module:** ${task.module_uid}\n\n${task.description_md || '_No description_'}`\n }]\n }\n }\n)\n\nserver.registerTool(\n 'list_module_tasks',\n {\n description: 'List all tasks for a module',\n inputSchema: {\n module_uid: z.string().describe('The UID of the module (e.g., EP584)')\n }\n },\n async (args) => {\n interface TasksResponse {\n success: boolean\n tasks?: Array<{\n uid: string\n title: string\n state: string\n type: string\n }>\n error?: string\n }\n\n const result = await apiRequest<TasksResponse>('GET', `/api/modules/${args.module_uid}/tasks`)\n\n if (!result.success || !result.tasks) {\n return { content: [{ type: 'text', text: `Error: ${result.error || 'Failed to fetch tasks'}` }], isError: true }\n }\n\n if (result.tasks.length === 0) {\n return { content: [{ type: 'text', text: 'No tasks found for this module.' }] }\n }\n\n const taskList = result.tasks.map(t => {\n const checkbox = t.state === 'done' ? '[x]' : '[ ]'\n const stateLabel = t.state !== 'backlog' ? ` (${t.state})` : ''\n return `- ${checkbox} **${t.uid}**: ${t.title}${stateLabel}`\n }).join('\\n')\n\n return {\n content: [{\n type: 'text',\n text: `# Tasks for ${args.module_uid}\\n\\n${taskList}`\n }]\n }\n }\n)\n\n// ============================================\n// EP1252: Batch Task Tools\n// ============================================\n\nserver.registerTool(\n 'batch_update_task_state',\n {\n description: `Update the state of multiple tasks at once.\n\nUSE THIS WHEN:\n- Marking multiple tasks as done after completing work\n- Moving several tasks to \"doing\" state\n- Bulk state transitions\n\nEFFICIENCY: Single call instead of multiple update_task_state calls.\nReduces latency from ~1.5s (6 calls) to ~300ms (1 call).`,\n inputSchema: {\n task_uids: z.array(z.string()).describe('Array of task UIDs (e.g., [\"EP1252-1\", \"EP1252-2\"])'),\n state: z.enum(['backlog', 'doing', 'done']).describe('New state for all tasks')\n }\n },\n async (args) => {\n interface TaskLookupResponse {\n success: boolean\n tasks?: Array<{ id: string; uid: string }>\n error?: string\n }\n\n interface BatchUpdateResponse {\n success: boolean\n tasks?: Array<{ id: string; uid: string; state: string }>\n summary?: { updated: number; requested: number }\n error?: { message?: string; details?: string }\n }\n\n try {\n // Step 1: Look up task UUIDs from UIDs\n // We need to query each task to get its UUID since the batch endpoint requires UUIDs\n const lookupPromises = args.task_uids.map(uid =>\n apiRequest<{ success: boolean; task?: { id: string; uid: string } }>('GET', `/api/tasks/${uid}`)\n .then(r => r.success && r.task ? { uid, id: r.task.id } : null)\n .catch(() => null)\n )\n\n const lookupResults = await Promise.all(lookupPromises)\n const validTasks = lookupResults.filter((t): t is { uid: string; id: string } => t !== null)\n const notFoundUids = args.task_uids.filter(uid => !validTasks.find(t => t.uid === uid))\n\n if (validTasks.length === 0) {\n return {\n content: [{\n type: 'text',\n text: `Error: None of the specified tasks were found.\\nNot found: ${args.task_uids.join(', ')}`\n }],\n isError: true\n }\n }\n\n // Step 2: Call batch update endpoint with UUIDs\n const updates = validTasks.map(t => ({\n id: t.id,\n state: args.state\n }))\n\n const result = await apiRequest<BatchUpdateResponse>('PATCH', '/api/tasks/batch', {\n updates\n })\n\n if (!result.success) {\n const errorMsg = result.error?.message || result.error?.details || 'Batch update failed'\n return {\n content: [{\n type: 'text',\n text: `Error: ${errorMsg}`\n }],\n isError: true\n }\n }\n\n // Build response\n const updatedUids = validTasks.map(t => t.uid)\n const failedItems = notFoundUids.map(uid => ({ uid, error: 'Task not found' }))\n\n return {\n content: [{\n type: 'text',\n text: `# Batch Update Results\n\n**Updated:** ${updatedUids.length} tasks → ${args.state}\n${updatedUids.map(uid => `- ✓ ${uid}`).join('\\n')}\n\n${failedItems.length > 0 ? `**Failed:** ${failedItems.length} tasks\\n${failedItems.map(f => `- ✗ ${f.uid}: ${f.error}`).join('\\n')}` : ''}`\n }]\n }\n } catch (error) {\n return {\n content: [{\n type: 'text',\n text: `Error: ${error instanceof Error ? error.message : 'Unknown error'}`\n }],\n isError: true\n }\n }\n }\n)\n\nserver.registerTool(\n 'batch_create_tasks',\n {\n description: `Create multiple tasks for a module at once.\n\nUSE THIS WHEN:\n- Setting up tasks for a new module\n- Creating multiple related tasks together\n- Bulk task creation from a plan\n\nEFFICIENCY: Single call instead of multiple create_task calls.`,\n inputSchema: {\n module_uid: z.string().describe('The UID of the parent module (e.g., EP1252)'),\n tasks: z.array(z.object({\n title: z.string().describe('Title of the task'),\n description: z.string().optional().describe('Markdown description'),\n state: z.enum(['backlog', 'doing', 'done']).optional().describe('Initial state (default: backlog)')\n })).describe('Array of tasks to create')\n }\n },\n async (args) => {\n interface BulkCreateResponse {\n success: boolean\n created?: number\n tasks?: Array<{ uid: string; title: string }>\n error?: string\n }\n\n try {\n // Call the bulk create endpoint (accepts module UID directly)\n const result = await apiRequest<BulkCreateResponse>('POST', '/api/tasks/bulk', {\n module_id: args.module_uid,\n tasks: args.tasks.map(t => ({\n title: t.title,\n description_md: t.description,\n state: t.state || 'backlog'\n }))\n })\n\n if (!result.success) {\n return {\n content: [{\n type: 'text',\n text: `Error: ${result.error || 'Bulk create failed'}`\n }],\n isError: true\n }\n }\n\n const createdTasks = result.tasks || []\n\n return {\n content: [{\n type: 'text',\n text: `# Batch Create Results\n\n**Created:** ${result.created || createdTasks.length} tasks for ${args.module_uid}\n\n${createdTasks.map(t => `- ✓ **${t.uid}**: ${t.title}`).join('\\n')}`\n }]\n }\n } catch (error) {\n return {\n content: [{\n type: 'text',\n text: `Error: ${error instanceof Error ? error.message : 'Unknown error'}`\n }],\n isError: true\n }\n }\n }\n)\n\nserver.registerTool(\n 'batch_get_tasks',\n {\n description: `Fetch multiple tasks by UID in a single call.\n\nUSE THIS WHEN:\n- Need details for several specific tasks\n- Checking status of multiple tasks at once\n- Gathering context for a set of tasks\n\nEFFICIENCY: Single MCP call instead of multiple get_task_details calls.`,\n inputSchema: {\n task_uids: z.array(z.string()).describe('Array of task UIDs (e.g., [\"EP1252-1\", \"EP1252-2\"])')\n }\n },\n async (args) => {\n interface TaskResponse {\n success: boolean\n task?: {\n uid: string\n title: string\n state: string\n type: string\n description_md: string | null\n }\n }\n\n try {\n type TaskInfo = NonNullable<TaskResponse['task']>\n\n // Fetch all tasks in parallel\n const fetchPromises = args.task_uids.map(uid =>\n apiRequest<TaskResponse>('GET', `/api/tasks/${uid}`)\n .then(r => r.success && r.task ? { found: true as const, task: r.task } : { found: false as const, uid })\n .catch(() => ({ found: false as const, uid }))\n )\n\n const results = await Promise.all(fetchPromises)\n const foundTasks: TaskInfo[] = []\n const notFoundUids: string[] = []\n\n for (const result of results) {\n if (result.found && result.task) {\n foundTasks.push(result.task as TaskInfo)\n } else if (!result.found) {\n notFoundUids.push(result.uid)\n }\n }\n\n if (foundTasks.length === 0) {\n return {\n content: [{\n type: 'text',\n text: `Error: None of the specified tasks were found.\\nNot found: ${args.task_uids.join(', ')}`\n }],\n isError: true\n }\n }\n\n const taskList = foundTasks.map((task) => {\n const checkbox = task.state === 'done' ? '[x]' : '[ ]'\n const stateLabel = task.state !== 'backlog' ? ` (${task.state})` : ''\n return `- ${checkbox} **${task.uid}**: ${task.title}${stateLabel}`\n }).join('\\n')\n\n return {\n content: [{\n type: 'text',\n text: `# Batch Get Results\n\n**Found:** ${foundTasks.length} tasks\n${taskList}\n\n${notFoundUids.length > 0 ? `**Not found:** ${notFoundUids.join(', ')}` : ''}`\n }]\n }\n } catch (error) {\n return {\n content: [{\n type: 'text',\n text: `Error: ${error instanceof Error ? error.message : 'Unknown error'}`\n }],\n isError: true\n }\n }\n }\n)\n\n// ============================================\n// Module Management Tools\n// ============================================\n\nserver.registerTool(\n 'create_module',\n {\n description: 'Create a new module in the project',\n inputSchema: {\n title: z.string().describe('Title of the module'),\n description: z.string().optional().describe('Markdown description of the module')\n }\n },\n async (args) => {\n interface CreateModuleResponse {\n success: boolean\n module?: { id: string; uid: string; title: string }\n error?: string\n }\n\n const result = await apiRequest<CreateModuleResponse>('POST', '/api/modules', {\n title: args.title,\n description_md: args.description\n })\n\n if (!result.success) {\n return { content: [{ type: 'text', text: `Error: ${result.error}` }], isError: true }\n }\n\n return {\n content: [{\n type: 'text',\n text: `Created module ${result.module?.uid}: ${result.module?.title}`\n }]\n }\n }\n)\n\nserver.registerTool(\n 'update_module',\n {\n description: 'Update module details (title, description)',\n inputSchema: {\n module_uid: z.string().describe('The UID of the module (e.g., EP584)'),\n title: z.string().optional().describe('New title for the module'),\n description: z.string().optional().describe('New markdown description')\n }\n },\n async (args) => {\n interface UpdateModuleResponse {\n success: boolean\n module?: { uid: string; title: string }\n error?: string\n }\n\n const updates: Record<string, string> = {}\n if (args.title) updates.title = args.title\n if (args.description) updates.description_md = args.description\n\n const result = await apiRequest<UpdateModuleResponse>('PATCH', `/api/modules/${args.module_uid}`, updates)\n\n if (!result.success) {\n return { content: [{ type: 'text', text: `Error: ${result.error}` }], isError: true }\n }\n\n return {\n content: [{\n type: 'text',\n text: `Module ${args.module_uid} updated`\n }]\n }\n }\n)\n\nserver.registerTool(\n 'request_review',\n {\n description: 'Move a module to review state',\n inputSchema: {\n module_uid: z.string().describe('The UID of the module (e.g., EP584)')\n }\n },\n async (args) => {\n interface UpdateModuleResponse {\n success: boolean\n module?: { uid: string; state: string }\n error?: string\n }\n\n const result = await apiRequest<UpdateModuleResponse>('PATCH', `/api/modules/${args.module_uid}`, {\n state: 'review'\n })\n\n if (!result.success) {\n return { content: [{ type: 'text', text: `Error: ${result.error}` }], isError: true }\n }\n\n return {\n content: [{\n type: 'text',\n text: `Module ${args.module_uid} moved to review`\n }]\n }\n }\n)\n\nserver.registerTool(\n 'mark_done',\n {\n description: 'Move a module to done state',\n inputSchema: {\n module_uid: z.string().describe('The UID of the module (e.g., EP584)')\n }\n },\n async (args) => {\n interface UpdateModuleResponse {\n success: boolean\n module?: { uid: string; state: string }\n error?: string\n }\n\n const result = await apiRequest<UpdateModuleResponse>('PATCH', `/api/modules/${args.module_uid}`, {\n state: 'done'\n })\n\n if (!result.success) {\n return { content: [{ type: 'text', text: `Error: ${result.error}` }], isError: true }\n }\n\n return {\n content: [{\n type: 'text',\n text: `Module ${args.module_uid} marked as done`\n }]\n }\n }\n)\n\nserver.registerTool(\n 'get_module_details',\n {\n description: 'Get detailed information about a module',\n inputSchema: {\n module_uid: z.string().describe('The UID of the module (e.g., EP584)')\n }\n },\n async (args) => {\n interface ModuleResponse {\n success: boolean\n module?: {\n uid: string\n title: string\n state: string\n description_md: string | null\n branch_name: string | null\n }\n error?: string\n }\n\n const result = await apiRequest<ModuleResponse>('GET', `/api/modules/${args.module_uid}`)\n\n if (!result.success || !result.module) {\n return { content: [{ type: 'text', text: `Error: ${result.error || 'Module not found'}` }], isError: true }\n }\n\n const mod = result.module\n return {\n content: [{\n type: 'text',\n text: `# ${mod.uid}: ${mod.title}\n\n**State:** ${mod.state}\n**Branch:** ${mod.branch_name || '_Not set_'}\n\n${mod.description_md || '_No description_'}`\n }]\n }\n }\n)\n\n// ============================================\n// Knowledge Tools\n// ============================================\n\nserver.registerTool(\n 'get_knowledge',\n {\n description: 'Fetch a knowledge document by ID',\n inputSchema: {\n knowledge_id: z.string().describe('The ID of the knowledge document')\n }\n },\n async (args) => {\n interface KnowledgeResponse {\n success: boolean\n knowledge?: {\n id: string\n title: string\n doc_type: string\n domain: string\n sections: Array<{ heading?: string; content?: string }>\n }\n error?: string\n }\n\n const result = await apiRequest<KnowledgeResponse>('GET', `/api/knowledge/${args.knowledge_id}`)\n\n if (!result.success || !result.knowledge) {\n return { content: [{ type: 'text', text: `Error: ${result.error || 'Knowledge not found'}` }], isError: true }\n }\n\n const doc = result.knowledge\n const sections = doc.sections.map(s => {\n const heading = s.heading ? `## ${s.heading}\\n\\n` : ''\n return `${heading}${s.content || ''}`\n }).join('\\n\\n')\n\n return {\n content: [{\n type: 'text',\n text: `# ${doc.title}\n\n**Type:** ${doc.doc_type} | **Domain:** ${doc.domain}\n\n${sections}`\n }]\n }\n }\n)\n\n// EP1242: Three search tools with clear use cases for AI agents\n\nserver.registerTool(\n 'search_knowledge_semantic',\n {\n description: `Search knowledge using vector similarity (semantic/conceptual matching).\n\nUSE THIS WHEN:\n- Looking for documents about a concept: \"authentication patterns\", \"error handling\"\n- Finding related content even if exact words don't match\n- Discovering documentation about a topic\n\nDO NOT USE WHEN:\n- Looking for a specific document by ID/UID (use get_knowledge)\n- Searching for exact title match (use search_knowledge_text)`,\n inputSchema: {\n query: z.string().describe('Natural language query describing what you\\'re looking for'),\n limit: z.number().optional().describe('Maximum results (default: 10)'),\n threshold: z.number().optional().describe('Minimum similarity 0-1 (default: 0.5, lower = more results)')\n }\n },\n async (args) => {\n interface SemanticSearchResponse {\n success: boolean\n results?: Array<{\n id: string\n uid?: string\n title: string\n doc_type: string\n similarity: number\n markdown?: string\n }>\n query_info?: { took_ms: number }\n error?: string\n }\n\n const result = await apiRequest<SemanticSearchResponse>(\n 'POST',\n '/api/search/semantic',\n {\n query: args.query,\n types: ['knowledge'],\n limit: args.limit || 10,\n threshold: args.threshold || 0.5\n }\n )\n\n if (!result.success || !result.results) {\n return { content: [{ type: 'text', text: `Error: ${result.error || 'Semantic search failed'}` }], isError: true }\n }\n\n if (result.results.length === 0) {\n return { content: [{ type: 'text', text: `No knowledge documents found semantically matching: \"${args.query}\"\\n\\nTry:\\n- Broader search terms\\n- Lower threshold (e.g., 0.3)\\n- Text search for exact matches` }] }\n }\n\n const list = result.results.map(r => {\n const score = Math.round(r.similarity * 100)\n const uid = r.uid ? ` (${r.uid})` : ''\n const snippet = r.markdown ? `\\n ${r.markdown.substring(0, 150)}...` : ''\n return `- **${r.title}**${uid} [${r.doc_type}, ${score}% match]${snippet}`\n }).join('\\n\\n')\n\n const timing = result.query_info ? ` (${result.query_info.took_ms}ms)` : ''\n\n return {\n content: [{\n type: 'text',\n text: `# Semantic Search Results${timing}\\n\\nQuery: \"${args.query}\"\\nFound: ${result.results.length} documents\\n\\n${list}`\n }]\n }\n }\n)\n\nserver.registerTool(\n 'search_knowledge_text',\n {\n description: `Search knowledge using text/keyword matching (fast, exact).\n\nUSE THIS WHEN:\n- Looking for documents by UID: \"K123\", \"K45\"\n- Searching for exact title: \"API Authentication Guide\"\n- Finding documents containing specific terms\n\nDO NOT USE WHEN:\n- Looking for conceptually related content (use search_knowledge_semantic)\n- Want to find documents about a topic without knowing exact words`,\n inputSchema: {\n query: z.string().describe('Text to search for (searches title, UID, domain, content)'),\n limit: z.number().optional().describe('Maximum results (default: 20)')\n }\n },\n async (args) => {\n interface TextSearchResponse {\n success: boolean\n results?: Array<{\n id: string\n uid?: string\n title: string\n doc_type?: string\n type: string\n markdown?: string\n }>\n total?: number\n error?: string\n }\n\n const result = await apiRequest<TextSearchResponse>(\n 'POST',\n '/api/search/text',\n {\n query: args.query,\n types: ['knowledge'],\n limit: args.limit || 20\n }\n )\n\n if (!result.success || !result.results) {\n return { content: [{ type: 'text', text: `Error: ${result.error || 'Text search failed'}` }], isError: true }\n }\n\n if (result.results.length === 0) {\n return { content: [{ type: 'text', text: `No knowledge documents found matching: \"${args.query}\"\\n\\nTry:\\n- Different keywords\\n- Semantic search for conceptual matches` }] }\n }\n\n const list = result.results.map(r => {\n const uid = r.uid ? ` (${r.uid})` : ''\n const docType = r.doc_type ? ` [${r.doc_type}]` : ''\n const snippet = r.markdown ? `\\n ${r.markdown.substring(0, 150)}...` : ''\n return `- **${r.title}**${uid}${docType}${snippet}`\n }).join('\\n\\n')\n\n return {\n content: [{\n type: 'text',\n text: `# Text Search Results\\n\\nQuery: \"${args.query}\"\\nFound: ${result.results.length} of ${result.total || result.results.length} documents\\n\\n${list}`\n }]\n }\n }\n)\n\nserver.registerTool(\n 'search_knowledge_hybrid',\n {\n description: `Search knowledge using both semantic AND text matching (best for general queries).\n\nCombines results using Reciprocal Rank Fusion (RRF) algorithm.\nDocuments that match BOTH semantically and textually rank highest.\n\nUSE THIS WHEN:\n- General search where you want comprehensive results\n- Not sure if semantic or text search is better\n- Want the best of both approaches\n\nThis is the recommended default search for most queries.`,\n inputSchema: {\n query: z.string().describe('Search query (will be used for both semantic and text matching)'),\n limit: z.number().optional().describe('Maximum results (default: 10)')\n }\n },\n async (args) => {\n interface SearchResult {\n id: string\n uid?: string\n title: string\n doc_type?: string\n similarity?: number\n markdown?: string\n }\n\n interface SemanticResponse {\n success: boolean\n results?: SearchResult[]\n error?: string\n }\n\n interface TextResponse {\n success: boolean\n results?: SearchResult[]\n error?: string\n }\n\n // Run both searches in parallel\n const [semanticResult, textResult] = await Promise.all([\n apiRequest<SemanticResponse>('POST', '/api/search/semantic', {\n query: args.query,\n types: ['knowledge'],\n limit: 50,\n threshold: 0.4\n }),\n apiRequest<TextResponse>('POST', '/api/search/text', {\n query: args.query,\n types: ['knowledge'],\n limit: 50\n })\n ])\n\n const semanticResults = semanticResult.success ? (semanticResult.results || []) : []\n const textResults = textResult.success ? (textResult.results || []) : []\n\n // Apply Reciprocal Rank Fusion (RRF) with k=60\n const K = 60\n const scores = new Map<string, { score: number; doc: SearchResult; sources: string[] }>()\n\n // Score semantic results\n semanticResults.forEach((doc, index) => {\n const rrfScore = 1 / (K + index + 1)\n scores.set(doc.id, { score: rrfScore, doc, sources: ['semantic'] })\n })\n\n // Score text results and merge\n textResults.forEach((doc, index) => {\n const rrfScore = 1 / (K + index + 1)\n const existing = scores.get(doc.id)\n if (existing) {\n existing.score += rrfScore\n existing.sources.push('text')\n } else {\n scores.set(doc.id, { score: rrfScore, doc, sources: ['text'] })\n }\n })\n\n // Sort by RRF score and limit\n const limit = args.limit || 10\n const ranked = Array.from(scores.values())\n .sort((a, b) => b.score - a.score)\n .slice(0, limit)\n\n if (ranked.length === 0) {\n return { content: [{ type: 'text', text: `No knowledge documents found for: \"${args.query}\"\\n\\nBoth semantic and text search returned no results.` }] }\n }\n\n const list = ranked.map(({ doc, score, sources }) => {\n const uid = doc.uid ? ` (${doc.uid})` : ''\n const docType = doc.doc_type ? ` [${doc.doc_type}]` : ''\n const matchType = sources.length === 2 ? '⭐ both' : sources[0]\n const snippet = doc.markdown ? `\\n ${doc.markdown.substring(0, 150)}...` : ''\n return `- **${doc.title}**${uid}${docType} (${matchType})${snippet}`\n }).join('\\n\\n')\n\n const bothCount = ranked.filter(r => r.sources.length === 2).length\n\n return {\n content: [{\n type: 'text',\n text: `# Hybrid Search Results (RRF)\\n\\nQuery: \"${args.query}\"\\nFound: ${ranked.length} documents (${bothCount} matched both semantic + text)\\n\\n${list}`\n }]\n }\n }\n)\n\nserver.registerTool(\n 'list_linked_knowledge',\n {\n description: 'List knowledge documents linked to a module',\n inputSchema: {\n module_uid: z.string().describe('The UID of the module (e.g., EP584)')\n }\n },\n async (args) => {\n interface LinkedKnowledgeResponse {\n success: boolean\n knowledge?: Array<{\n id: string\n title: string\n doc_type: string\n }>\n error?: string\n }\n\n const result = await apiRequest<LinkedKnowledgeResponse>(\n 'GET',\n `/api/modules/${args.module_uid}/knowledge`\n )\n\n if (!result.success || !result.knowledge) {\n return { content: [{ type: 'text', text: `Error: ${result.error || 'Failed to fetch knowledge'}` }], isError: true }\n }\n\n if (result.knowledge.length === 0) {\n return { content: [{ type: 'text', text: 'No knowledge documents linked to this module.' }] }\n }\n\n const list = result.knowledge.map(k => `- **${k.title}** (${k.doc_type})`).join('\\n')\n\n return {\n content: [{\n type: 'text',\n text: `# Linked Knowledge for ${args.module_uid}\\n\\n${list}`\n }]\n }\n }\n)\n\nserver.registerTool(\n 'link_knowledge',\n {\n description: 'Link a knowledge document to a module',\n inputSchema: {\n module_uid: z.string().describe('The UID of the module (e.g., EP584)'),\n knowledge_id: z.string().describe('The ID of the knowledge document to link')\n }\n },\n async (args) => {\n interface LinkResponse {\n success: boolean\n error?: string\n }\n\n const result = await apiRequest<LinkResponse>(\n 'POST',\n `/api/modules/${args.module_uid}/knowledge/link`,\n { knowledge_id: args.knowledge_id }\n )\n\n if (!result.success) {\n return { content: [{ type: 'text', text: `Error: ${result.error}` }], isError: true }\n }\n\n return {\n content: [{\n type: 'text',\n text: `Knowledge document linked to module ${args.module_uid}`\n }]\n }\n }\n)\n\n// ============================================\n// Context Tools\n// ============================================\n\nserver.registerTool(\n 'get_module_context',\n {\n description: 'Get the full context for a module (title, tasks, linked knowledge)',\n inputSchema: {\n module_uid: z.string().describe('The UID of the module (e.g., EP584)')\n }\n },\n async (args) => {\n interface ContextResponse {\n success: boolean\n context?: string\n error?: string\n }\n\n // Use the agent-accessible module context API\n const result = await apiRequest<ContextResponse>(\n 'GET',\n `/api/agent/context/module/${args.module_uid}`\n )\n\n if (!result.success || !result.context) {\n return { content: [{ type: 'text', text: `Error: ${result.error || 'Failed to fetch context'}` }], isError: true }\n }\n\n return {\n content: [{\n type: 'text',\n text: result.context\n }]\n }\n }\n)\n\nserver.registerTool(\n 'get_project_context',\n {\n description: 'Get the project-wide context (C2 bundle with active work, priorities)',\n inputSchema: {}\n },\n async () => {\n interface ContextResponse {\n success: boolean\n prompt?: string\n error?: string\n }\n\n // Use the agent-accessible system prompt API\n const result = await apiRequest<ContextResponse>(\n 'GET',\n '/api/agent/context/system'\n )\n\n if (!result.success || !result.prompt) {\n return { content: [{ type: 'text', text: `Error: ${result.error || 'Failed to fetch context'}` }], isError: true }\n }\n\n return {\n content: [{\n type: 'text',\n text: result.prompt\n }]\n }\n }\n)\n\n// ============================================\n// Start Server\n// ============================================\n\nasync function main() {\n const runtimeConfig = await hydrateRuntimeConfig()\n EPISODA_API_URL = runtimeConfig.apiUrl\n EPISODA_SESSION_TOKEN = runtimeConfig.sessionToken\n EPISODA_PROJECT_ID = runtimeConfig.projectId\n EPISODA_WORKSPACE_ID = runtimeConfig.workspaceId\n\n const transport = new StdioServerTransport()\n await server.connect(transport)\n\n // Log to stderr so it doesn't interfere with MCP protocol\n console.error('[episoda-workflow] MCP server started')\n console.error(`[episoda-workflow] API URL: ${EPISODA_API_URL}`)\n console.error(`[episoda-workflow] Token: ${EPISODA_SESSION_TOKEN ? '****' : 'NOT SET'}`)\n}\n\nmain().catch((error) => {\n console.error('[episoda-workflow] Fatal error:', error)\n process.exit(1)\n})\n","/**\n * EP908: Episoda Git MCP Server\n *\n * MCP server for Claude Code agents to perform git operations on dev environments.\n * Provides tools for:\n * - Repository status and info (status, log, diff, branch)\n * - Staging and commits (add, commit, reset)\n * - Remote operations (push, pull, fetch)\n * - Branch management (checkout, create, delete, merge)\n *\n * Usage:\n * npx -y @episoda/mcp git\n *\n * Required environment variables:\n * EPISODA_API_URL - Base URL for Episoda API (e.g., https://episoda.dev)\n * EPISODA_SESSION_TOKEN - Bearer token for API authentication\n *\n * Optional environment variables:\n * MODULE_UID - Module UID (preferred, e.g., EP123) or provide moduleUid per tool call\n * DEV_ENVIRONMENT_ID - UUID of the dev environment (legacy fallback)\n * EPISODA_PROJECT_ID - Project ID (for scoped requests)\n * EPISODA_WORKSPACE_ID - Workspace ID (for scoped requests)\n */\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'\nimport { z } from 'zod'\nimport { hydrateRuntimeConfig } from './runtime-config.js'\n\n// Environment configuration\nlet EPISODA_API_URL = process.env.EPISODA_API_URL || 'https://episoda.dev'\nlet EPISODA_SESSION_TOKEN = process.env.EPISODA_SESSION_TOKEN || ''\nconst DEV_ENVIRONMENT_ID = process.env.DEV_ENVIRONMENT_ID || ''\nconst MODULE_UID = process.env.MODULE_UID || ''\nlet EPISODA_PROJECT_ID = process.env.EPISODA_PROJECT_ID || ''\nlet EPISODA_WORKSPACE_ID = process.env.EPISODA_WORKSPACE_ID || ''\n\nconst targetSchema = {\n moduleUid: z.string().optional().describe('Module UID to target (overrides server default)')\n}\n\ninterface ExecResponse {\n success: boolean\n data?: {\n stdout: string\n stderr: string\n exitCode: number\n timedOut?: boolean\n }\n error?: string\n}\n\n/**\n * Execute a command on the dev environment via unified API\n */\nasync function execCommand(\n command: string,\n options: { cwd?: string; timeout?: number; moduleUid?: string } = {}\n): Promise<ExecResponse> {\n const { cwd, timeout = 30000, moduleUid } = options\n\n const target = moduleUid || MODULE_UID || DEV_ENVIRONMENT_ID\n if (!target) {\n return {\n success: false,\n error: 'Module target missing. Provide moduleUid in the tool call or set MODULE_UID/DEV_ENVIRONMENT_ID.'\n }\n }\n const url = `${EPISODA_API_URL}/api/dev/${target}/exec`\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${EPISODA_SESSION_TOKEN}`\n }\n if (EPISODA_PROJECT_ID) {\n headers['x-project-id'] = EPISODA_PROJECT_ID\n }\n if (EPISODA_WORKSPACE_ID) {\n headers['x-workspace-id'] = EPISODA_WORKSPACE_ID\n }\n\n const response = await fetch(url, {\n method: 'POST',\n headers,\n body: JSON.stringify({ command, cwd, timeout })\n })\n\n if (!response.ok) {\n const text = await response.text()\n return { success: false, error: `API error ${response.status}: ${text}` }\n }\n\n const result = await response.json()\n return result\n}\n\n/**\n * Helper to format git command output for MCP response\n */\nfunction formatGitOutput(result: ExecResponse, errorPrefix: string = 'Git error'): {\n content: Array<{ type: 'text'; text: string }>\n isError?: boolean\n} {\n if (!result.success || !result.data) {\n return {\n content: [{ type: 'text', text: `${errorPrefix}: ${result.error || 'Unknown error'}` }],\n isError: true\n }\n }\n\n const { stdout, stderr, exitCode } = result.data\n\n if (exitCode !== 0) {\n const errorOutput = stderr || stdout || 'Command failed'\n return {\n content: [{ type: 'text', text: `${errorPrefix} (exit ${exitCode}):\\n${errorOutput}` }],\n isError: true\n }\n }\n\n return {\n content: [{ type: 'text', text: stdout || '(no output)' }]\n }\n}\n\n// Create MCP server\nconst server = new McpServer({\n name: 'episoda-git',\n version: '1.0.0'\n}, {\n capabilities: {\n tools: {}\n },\n instructions: `\n Episoda Git MCP Server\n\n This server provides git operations for dev environments (cloud VMs or local machines).\n All commands are executed in the context of the configured dev environment.\n You may pass moduleUid per call to target a specific module.\n\n Categories:\n - Status & Info: git_status, git_log, git_diff, git_show, git_branch_list\n - Staging: git_add, git_reset\n - Commits: git_commit\n - Remote: git_push, git_pull, git_fetch\n - Branches: git_checkout, git_branch_create, git_branch_delete, git_merge\n - Stash: git_stash, git_stash_pop, git_stash_list\n - Worktrees (EP944): git_worktree_list, git_worktree_add, git_worktree_remove, git_worktree_prune\n\n Worktrees allow multiple working directories to share a single repository,\n enabling parallel development on multiple branches/modules simultaneously.\n `\n})\n\n// ============================================\n// Status & Info Tools\n// ============================================\n\nserver.registerTool(\n 'git_status',\n {\n description: 'Show the working tree status (staged, unstaged, untracked files)',\n inputSchema: {\n ...targetSchema,\n cwd: z.string().optional().describe('Working directory path (defaults to repo root)')\n }\n },\n async (args) => {\n const result = await execCommand('git status', { cwd: args.cwd, moduleUid: args.moduleUid })\n return formatGitOutput(result, 'Failed to get git status')\n }\n)\n\nserver.registerTool(\n 'git_log',\n {\n description: 'Show commit logs',\n inputSchema: {\n ...targetSchema,\n count: z.number().optional().describe('Number of commits to show (default: 10)'),\n oneline: z.boolean().optional().describe('Use one-line format (default: true)'),\n branch: z.string().optional().describe('Branch name (default: current branch)'),\n cwd: z.string().optional().describe('Working directory path')\n }\n },\n async (args) => {\n const count = args.count || 10\n const format = args.oneline !== false ? '--oneline' : '--format=medium'\n const branch = args.branch || ''\n\n const result = await execCommand(\n `git log ${format} -n ${count} ${branch}`.trim(),\n { cwd: args.cwd, moduleUid: args.moduleUid }\n )\n return formatGitOutput(result, 'Failed to get git log')\n }\n)\n\nserver.registerTool(\n 'git_diff',\n {\n description: 'Show changes between commits, commit and working tree, etc.',\n inputSchema: {\n ...targetSchema,\n staged: z.boolean().optional().describe('Show staged changes (--cached)'),\n file: z.string().optional().describe('Specific file to diff'),\n commit: z.string().optional().describe('Compare against specific commit'),\n cwd: z.string().optional().describe('Working directory path')\n }\n },\n async (args) => {\n let cmd = 'git diff'\n if (args.staged) cmd += ' --cached'\n if (args.commit) cmd += ` ${args.commit}`\n if (args.file) cmd += ` -- ${args.file}`\n\n const result = await execCommand(cmd, { cwd: args.cwd, moduleUid: args.moduleUid })\n return formatGitOutput(result, 'Failed to get diff')\n }\n)\n\nserver.registerTool(\n 'git_show',\n {\n description: 'Show details of a specific commit',\n inputSchema: {\n ...targetSchema,\n commit: z.string().describe('Commit hash or reference (e.g., HEAD, abc123)'),\n stat: z.boolean().optional().describe('Show diffstat only'),\n cwd: z.string().optional().describe('Working directory path')\n }\n },\n async (args) => {\n let cmd = `git show ${args.commit}`\n if (args.stat) cmd += ' --stat'\n\n const result = await execCommand(cmd, { cwd: args.cwd, moduleUid: args.moduleUid })\n return formatGitOutput(result, 'Failed to show commit')\n }\n)\n\nserver.registerTool(\n 'git_branch_list',\n {\n description: 'List branches',\n inputSchema: {\n ...targetSchema,\n all: z.boolean().optional().describe('Show all branches including remotes'),\n remote: z.boolean().optional().describe('Show only remote branches'),\n cwd: z.string().optional().describe('Working directory path')\n }\n },\n async (args) => {\n let cmd = 'git branch'\n if (args.all) cmd += ' -a'\n else if (args.remote) cmd += ' -r'\n\n const result = await execCommand(cmd, { cwd: args.cwd, moduleUid: args.moduleUid })\n return formatGitOutput(result, 'Failed to list branches')\n }\n)\n\n// ============================================\n// Staging Tools\n// ============================================\n\nserver.registerTool(\n 'git_add',\n {\n description: 'Add file contents to the staging area',\n inputSchema: {\n ...targetSchema,\n files: z.array(z.string()).describe('Files to add (use [\".\"] for all)'),\n cwd: z.string().optional().describe('Working directory path')\n }\n },\n async (args) => {\n const files = args.files.map(f => `\"${f}\"`).join(' ')\n const result = await execCommand(`git add ${files}`, { cwd: args.cwd, moduleUid: args.moduleUid })\n\n if (!result.success || (result.data && result.data.exitCode !== 0)) {\n return formatGitOutput(result, 'Failed to add files')\n }\n\n return {\n content: [{ type: 'text', text: `Added ${args.files.length} file(s) to staging area` }]\n }\n }\n)\n\nserver.registerTool(\n 'git_reset',\n {\n description: 'Unstage files or reset to a commit',\n inputSchema: {\n ...targetSchema,\n files: z.array(z.string()).optional().describe('Files to unstage'),\n hard: z.boolean().optional().describe('Hard reset (WARNING: discards changes)'),\n commit: z.string().optional().describe('Commit to reset to'),\n cwd: z.string().optional().describe('Working directory path')\n }\n },\n async (args) => {\n let cmd = 'git reset'\n if (args.hard) cmd += ' --hard'\n if (args.commit) cmd += ` ${args.commit}`\n if (args.files && args.files.length > 0) {\n cmd += ' -- ' + args.files.map(f => `\"${f}\"`).join(' ')\n }\n\n const result = await execCommand(cmd, { cwd: args.cwd, moduleUid: args.moduleUid })\n return formatGitOutput(result, 'Failed to reset')\n }\n)\n\n// ============================================\n// Commit Tools\n// ============================================\n\nserver.registerTool(\n 'git_commit',\n {\n description: 'Record changes to the repository',\n inputSchema: {\n ...targetSchema,\n message: z.string().describe('Commit message'),\n all: z.boolean().optional().describe('Stage all modified files before commit (-a)'),\n amend: z.boolean().optional().describe('Amend the previous commit'),\n cwd: z.string().optional().describe('Working directory path')\n }\n },\n async (args) => {\n // Escape message for shell\n const escapedMessage = args.message.replace(/'/g, \"'\\\\''\")\n\n let cmd = `git commit -m '${escapedMessage}'`\n if (args.all) cmd = cmd.replace('git commit', 'git commit -a')\n if (args.amend) cmd += ' --amend'\n\n const result = await execCommand(cmd, { cwd: args.cwd, moduleUid: args.moduleUid })\n return formatGitOutput(result, 'Failed to commit')\n }\n)\n\n// ============================================\n// Remote Tools\n// ============================================\n\nserver.registerTool(\n 'git_push',\n {\n description: 'Push commits to remote repository',\n inputSchema: {\n ...targetSchema,\n remote: z.string().optional().describe('Remote name (default: origin)'),\n branch: z.string().optional().describe('Branch name'),\n force: z.boolean().optional().describe('Force push (use with caution!)'),\n setUpstream: z.boolean().optional().describe('Set upstream tracking (-u)'),\n cwd: z.string().optional().describe('Working directory path')\n }\n },\n async (args) => {\n let cmd = 'git push'\n if (args.setUpstream) cmd += ' -u'\n if (args.force) cmd += ' --force-with-lease' // Safer than --force\n if (args.remote) cmd += ` ${args.remote}`\n if (args.branch) cmd += ` ${args.branch}`\n\n const result = await execCommand(cmd, { cwd: args.cwd, timeout: 60000, moduleUid: args.moduleUid })\n return formatGitOutput(result, 'Failed to push')\n }\n)\n\nserver.registerTool(\n 'git_pull',\n {\n description: 'Fetch and integrate changes from remote',\n inputSchema: {\n ...targetSchema,\n remote: z.string().optional().describe('Remote name (default: origin)'),\n branch: z.string().optional().describe('Branch name'),\n rebase: z.boolean().optional().describe('Rebase instead of merge'),\n cwd: z.string().optional().describe('Working directory path')\n }\n },\n async (args) => {\n let cmd = 'git pull'\n if (args.rebase) cmd += ' --rebase'\n if (args.remote) cmd += ` ${args.remote}`\n if (args.branch) cmd += ` ${args.branch}`\n\n const result = await execCommand(cmd, { cwd: args.cwd, timeout: 60000, moduleUid: args.moduleUid })\n return formatGitOutput(result, 'Failed to pull')\n }\n)\n\nserver.registerTool(\n 'git_fetch',\n {\n description: 'Download objects and refs from remote',\n inputSchema: {\n ...targetSchema,\n remote: z.string().optional().describe('Remote name (default: all remotes)'),\n prune: z.boolean().optional().describe('Remove deleted remote branches'),\n cwd: z.string().optional().describe('Working directory path')\n }\n },\n async (args) => {\n let cmd = 'git fetch'\n if (args.prune) cmd += ' --prune'\n if (args.remote) cmd += ` ${args.remote}`\n else cmd += ' --all'\n\n const result = await execCommand(cmd, { cwd: args.cwd, timeout: 60000, moduleUid: args.moduleUid })\n return formatGitOutput(result, 'Failed to fetch')\n }\n)\n\n// ============================================\n// Branch Management Tools\n// ============================================\n\nserver.registerTool(\n 'git_checkout',\n {\n description: 'Switch branches or restore working tree files',\n inputSchema: {\n ...targetSchema,\n target: z.string().describe('Branch name, commit, or file path'),\n create: z.boolean().optional().describe('Create new branch (-b)'),\n cwd: z.string().optional().describe('Working directory path')\n }\n },\n async (args) => {\n let cmd = 'git checkout'\n if (args.create) cmd += ' -b'\n cmd += ` ${args.target}`\n\n const result = await execCommand(cmd, { cwd: args.cwd, moduleUid: args.moduleUid })\n return formatGitOutput(result, 'Failed to checkout')\n }\n)\n\nserver.registerTool(\n 'git_branch_create',\n {\n description: 'Create a new branch',\n inputSchema: {\n ...targetSchema,\n name: z.string().describe('Name for the new branch'),\n startPoint: z.string().optional().describe('Starting commit/branch'),\n checkout: z.boolean().optional().describe('Switch to new branch after creation'),\n cwd: z.string().optional().describe('Working directory path')\n }\n },\n async (args) => {\n let cmd: string\n if (args.checkout) {\n cmd = `git checkout -b ${args.name}`\n } else {\n cmd = `git branch ${args.name}`\n }\n if (args.startPoint) cmd += ` ${args.startPoint}`\n\n const result = await execCommand(cmd, { cwd: args.cwd, moduleUid: args.moduleUid })\n\n if (!result.success || (result.data && result.data.exitCode !== 0)) {\n return formatGitOutput(result, 'Failed to create branch')\n }\n\n return {\n content: [{\n type: 'text',\n text: `Created branch '${args.name}'${args.checkout ? ' and switched to it' : ''}`\n }]\n }\n }\n)\n\nserver.registerTool(\n 'git_branch_delete',\n {\n description: 'Delete a branch',\n inputSchema: {\n ...targetSchema,\n name: z.string().describe('Branch name to delete'),\n force: z.boolean().optional().describe('Force delete unmerged branch (-D)'),\n remote: z.boolean().optional().describe('Delete remote branch'),\n cwd: z.string().optional().describe('Working directory path')\n }\n },\n async (args) => {\n let cmd: string\n if (args.remote) {\n cmd = `git push origin --delete ${args.name}`\n } else {\n cmd = `git branch ${args.force ? '-D' : '-d'} ${args.name}`\n }\n\n const result = await execCommand(cmd, { cwd: args.cwd, moduleUid: args.moduleUid })\n return formatGitOutput(result, 'Failed to delete branch')\n }\n)\n\nserver.registerTool(\n 'git_merge',\n {\n description: 'Join two or more development histories together',\n inputSchema: {\n ...targetSchema,\n branch: z.string().describe('Branch to merge into current branch'),\n noFf: z.boolean().optional().describe('Create merge commit even for fast-forward'),\n squash: z.boolean().optional().describe('Squash commits into single commit'),\n message: z.string().optional().describe('Merge commit message'),\n cwd: z.string().optional().describe('Working directory path')\n }\n },\n async (args) => {\n let cmd = `git merge ${args.branch}`\n if (args.noFf) cmd += ' --no-ff'\n if (args.squash) cmd += ' --squash'\n if (args.message) {\n const escapedMessage = args.message.replace(/'/g, \"'\\\\''\")\n cmd += ` -m '${escapedMessage}'`\n }\n\n const result = await execCommand(cmd, { cwd: args.cwd, moduleUid: args.moduleUid })\n return formatGitOutput(result, 'Failed to merge')\n }\n)\n\n// ============================================\n// Stash Tools\n// ============================================\n\nserver.registerTool(\n 'git_stash',\n {\n description: 'Stash changes in working directory',\n inputSchema: {\n ...targetSchema,\n message: z.string().optional().describe('Description for the stash'),\n includeUntracked: z.boolean().optional().describe('Include untracked files'),\n cwd: z.string().optional().describe('Working directory path')\n }\n },\n async (args) => {\n let cmd = 'git stash push'\n if (args.includeUntracked) cmd += ' --include-untracked'\n if (args.message) {\n const escapedMessage = args.message.replace(/'/g, \"'\\\\''\")\n cmd += ` -m '${escapedMessage}'`\n }\n\n const result = await execCommand(cmd, { cwd: args.cwd, moduleUid: args.moduleUid })\n return formatGitOutput(result, 'Failed to stash')\n }\n)\n\nserver.registerTool(\n 'git_stash_pop',\n {\n description: 'Apply and remove a stash',\n inputSchema: {\n ...targetSchema,\n index: z.number().optional().describe('Stash index (default: 0, most recent)'),\n cwd: z.string().optional().describe('Working directory path')\n }\n },\n async (args) => {\n const stashRef = args.index !== undefined ? `stash@{${args.index}}` : ''\n const result = await execCommand(`git stash pop ${stashRef}`.trim(), { cwd: args.cwd, moduleUid: args.moduleUid })\n return formatGitOutput(result, 'Failed to pop stash')\n }\n)\n\nserver.registerTool(\n 'git_stash_list',\n {\n description: 'List stashed changes',\n inputSchema: {\n ...targetSchema,\n cwd: z.string().optional().describe('Working directory path')\n }\n },\n async (args) => {\n const result = await execCommand('git stash list', { cwd: args.cwd, moduleUid: args.moduleUid })\n return formatGitOutput(result, 'Failed to list stashes')\n }\n)\n\n// ============================================\n// EP944: Worktree Tools\n// ============================================\n\nserver.registerTool(\n 'git_worktree_list',\n {\n description: 'List all worktrees in the repository. Worktrees allow multiple working directories to share a single repository.',\n inputSchema: {\n ...targetSchema,\n cwd: z.string().optional().describe('Working directory path (must be inside a git repo)')\n }\n },\n async (args) => {\n const result = await execCommand('git worktree list', { cwd: args.cwd, moduleUid: args.moduleUid })\n return formatGitOutput(result, 'Failed to list worktrees')\n }\n)\n\nserver.registerTool(\n 'git_worktree_add',\n {\n description: 'Create a new worktree at the specified path for the given branch. This allows working on multiple branches simultaneously.',\n inputSchema: {\n ...targetSchema,\n path: z.string().describe('Path where the new worktree will be created'),\n branch: z.string().describe('Branch to checkout in the new worktree'),\n create: z.boolean().optional().describe('Create a new branch if it does not exist (-b)'),\n cwd: z.string().optional().describe('Working directory path (must be inside a git repo)')\n }\n },\n async (args) => {\n let cmd = 'git worktree add'\n if (args.create) {\n cmd += ` -b ${args.branch} \"${args.path}\"`\n } else {\n cmd += ` \"${args.path}\" ${args.branch}`\n }\n\n const result = await execCommand(cmd, { cwd: args.cwd, moduleUid: args.moduleUid })\n\n if (!result.success || (result.data && result.data.exitCode !== 0)) {\n return formatGitOutput(result, 'Failed to create worktree')\n }\n\n return {\n content: [{\n type: 'text',\n text: `Created worktree at '${args.path}' for branch '${args.branch}'`\n }]\n }\n }\n)\n\nserver.registerTool(\n 'git_worktree_remove',\n {\n description: 'Remove a worktree. The branch is preserved in the repository - only the working directory is removed.',\n inputSchema: {\n ...targetSchema,\n path: z.string().describe('Path of the worktree to remove'),\n force: z.boolean().optional().describe('Force removal even with uncommitted changes'),\n cwd: z.string().optional().describe('Working directory path (must be inside a git repo)')\n }\n },\n async (args) => {\n let cmd = `git worktree remove \"${args.path}\"`\n if (args.force) cmd += ' --force'\n\n const result = await execCommand(cmd, { cwd: args.cwd, moduleUid: args.moduleUid })\n\n if (!result.success || (result.data && result.data.exitCode !== 0)) {\n return formatGitOutput(result, 'Failed to remove worktree')\n }\n\n return {\n content: [{\n type: 'text',\n text: `Removed worktree at '${args.path}'`\n }]\n }\n }\n)\n\nserver.registerTool(\n 'git_worktree_prune',\n {\n description: 'Clean up stale worktree administrative files. Run this if worktrees were manually deleted.',\n inputSchema: {\n ...targetSchema,\n cwd: z.string().optional().describe('Working directory path (must be inside a git repo)')\n }\n },\n async (args) => {\n const result = await execCommand('git worktree prune', { cwd: args.cwd, moduleUid: args.moduleUid })\n\n if (!result.success || (result.data && result.data.exitCode !== 0)) {\n return formatGitOutput(result, 'Failed to prune worktrees')\n }\n\n return {\n content: [{\n type: 'text',\n text: 'Pruned stale worktree entries'\n }]\n }\n }\n)\n\n// ============================================\n// Start Server\n// ============================================\n\nasync function main() {\n const runtimeConfig = await hydrateRuntimeConfig()\n EPISODA_API_URL = runtimeConfig.apiUrl\n EPISODA_SESSION_TOKEN = runtimeConfig.sessionToken\n EPISODA_PROJECT_ID = runtimeConfig.projectId\n EPISODA_WORKSPACE_ID = runtimeConfig.workspaceId\n\n if (!MODULE_UID && !DEV_ENVIRONMENT_ID) {\n console.warn('[episoda-git] Warning: MODULE_UID/DEV_ENVIRONMENT_ID not set. Provide moduleUid per tool call.')\n }\n\n const transport = new StdioServerTransport()\n await server.connect(transport)\n\n const devTarget = MODULE_UID || DEV_ENVIRONMENT_ID || 'NOT SET'\n console.error('[episoda-git] MCP server started')\n console.error(`[episoda-git] API URL: ${EPISODA_API_URL}`)\n console.error(`[episoda-git] Dev Target: ${devTarget}`)\n console.error(`[episoda-git] Token: ${EPISODA_SESSION_TOKEN ? '****' : 'NOT SET'}`)\n}\n\nmain().catch((error) => {\n console.error('[episoda-git] Fatal error:', error)\n process.exit(1)\n})\n","/**\n * EP908: Episoda Dev MCP Server\n *\n * MCP server for Claude Code agents to perform file and environment operations\n * on dev environments (cloud VMs or local machines).\n *\n * Provides tools for:\n * - File operations (read, write, edit, delete, mkdir)\n * - Directory operations (list, search)\n * - Code search (grep)\n * - Command execution\n * - Batch operations\n *\n * Usage:\n * npx -y @episoda/mcp dev\n *\n * Required environment variables:\n * EPISODA_API_URL - Base URL for Episoda API (e.g., https://episoda.dev)\n * EPISODA_SESSION_TOKEN - Bearer token for API authentication\n *\n * Optional environment variables:\n * MODULE_UID - Module UID (preferred, e.g., EP123) or provide moduleUid per tool call\n * DEV_ENVIRONMENT_ID - UUID of the dev environment (legacy fallback)\n * EPISODA_PROJECT_ID - Project ID (for scoped requests)\n * EPISODA_WORKSPACE_ID - Workspace ID (for scoped requests)\n */\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'\nimport { z } from 'zod'\nimport { hydrateRuntimeConfig } from './runtime-config.js'\n\n// Environment configuration\nlet EPISODA_API_URL = process.env.EPISODA_API_URL || 'https://episoda.dev'\nlet EPISODA_SESSION_TOKEN = process.env.EPISODA_SESSION_TOKEN || ''\nconst DEV_ENVIRONMENT_ID = process.env.DEV_ENVIRONMENT_ID || ''\nconst MODULE_UID = process.env.MODULE_UID || ''\nlet EPISODA_PROJECT_ID = process.env.EPISODA_PROJECT_ID || ''\nlet EPISODA_WORKSPACE_ID = process.env.EPISODA_WORKSPACE_ID || ''\n\nconst targetSchema = {\n moduleUid: z.string().optional().describe('Module UID to target (overrides server default)')\n}\n\n/**\n * Make an authenticated API request\n */\nasync function apiRequest<T>(\n method: 'GET' | 'POST' | 'DELETE',\n path: string,\n body?: Record<string, unknown>\n): Promise<T> {\n const url = `${EPISODA_API_URL}${path}`\n const options: RequestInit = {\n method,\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${EPISODA_SESSION_TOKEN}`\n }\n }\n\n if (EPISODA_PROJECT_ID) {\n (options.headers as Record<string, string>)['x-project-id'] = EPISODA_PROJECT_ID\n }\n if (EPISODA_WORKSPACE_ID) {\n (options.headers as Record<string, string>)['x-workspace-id'] = EPISODA_WORKSPACE_ID\n }\n\n if (body && method !== 'GET') {\n options.body = JSON.stringify(body)\n }\n\n const response = await fetch(url, options)\n\n if (!response.ok) {\n const text = await response.text()\n throw new Error(`API error ${response.status}: ${text}`)\n }\n\n return response.json() as Promise<T>\n}\n\n/**\n * Helper to build API path with dev environment ID\n */\nfunction devPath(endpoint: string, overrideTarget?: string): string {\n const target = overrideTarget || MODULE_UID || DEV_ENVIRONMENT_ID\n if (!target) {\n throw new Error('Module target missing. Provide moduleUid in the tool call or set MODULE_UID/DEV_ENVIRONMENT_ID.')\n }\n return `/api/dev/${target}${endpoint}`\n}\n\n// Create MCP server\nconst server = new McpServer({\n name: 'episoda-dev',\n version: '1.0.0'\n}, {\n capabilities: {\n tools: {}\n },\n instructions: `\n Episoda Dev MCP Server\n\n This server provides file and environment operations for dev environments\n (cloud VMs or local machines). All operations execute in the context of\n the configured dev environment.\n You may pass moduleUid per call to target a specific module.\n\n Categories:\n - File Operations: read_file, write_file, edit_file, delete_file\n - Directory Operations: list_directory, mkdir, search_files\n - Code Search: grep\n - Execution: exec_command\n - Batch: batch_operations\n\n All paths should be absolute paths within the dev environment.\n `\n})\n\n// ============================================\n// File Operations\n// ============================================\n\nserver.registerTool(\n 'read_file',\n {\n description: 'Read contents of a file',\n inputSchema: {\n ...targetSchema,\n path: z.string().describe('Absolute path to the file'),\n encoding: z.enum(['utf8', 'base64']).optional().describe('File encoding (default: utf8)')\n }\n },\n async (args) => {\n interface ReadResponse {\n success: boolean\n data?: { content: string }\n error?: string\n }\n\n try {\n const result = await apiRequest<ReadResponse>(\n 'POST',\n devPath('/read-file', args.moduleUid),\n {\n path: args.path,\n encoding: args.encoding || 'utf8'\n }\n )\n\n if (!result.success || !result.data) {\n return {\n content: [{ type: 'text', text: `Error: ${result.error || 'Failed to read file'}` }],\n isError: true\n }\n }\n\n return {\n content: [{ type: 'text', text: result.data.content }]\n }\n } catch (error) {\n return {\n content: [{ type: 'text', text: `Error reading file: ${error}` }],\n isError: true\n }\n }\n }\n)\n\nserver.registerTool(\n 'write_file',\n {\n description: 'Write content to a file (creates or overwrites)',\n inputSchema: {\n ...targetSchema,\n path: z.string().describe('Absolute path to the file'),\n content: z.string().describe('Content to write'),\n encoding: z.enum(['utf8', 'base64']).optional().describe('Content encoding (default: utf8)'),\n createDirs: z.boolean().optional().describe('Create parent directories if missing (default: true)')\n }\n },\n async (args) => {\n interface WriteResponse {\n success: boolean\n data?: { size: number }\n error?: string\n }\n\n try {\n const result = await apiRequest<WriteResponse>(\n 'POST',\n devPath('/write-file', args.moduleUid),\n {\n path: args.path,\n content: args.content,\n encoding: args.encoding || 'utf8',\n createDirs: args.createDirs !== false\n }\n )\n\n if (!result.success) {\n return {\n content: [{ type: 'text', text: `Error: ${result.error || 'Failed to write file'}` }],\n isError: true\n }\n }\n\n return {\n content: [{\n type: 'text',\n text: `Wrote ${result.data?.size || 0} bytes to ${args.path}`\n }]\n }\n } catch (error) {\n return {\n content: [{ type: 'text', text: `Error writing file: ${error}` }],\n isError: true\n }\n }\n }\n)\n\nserver.registerTool(\n 'edit_file',\n {\n description: 'Edit a file by replacing a specific string with another',\n inputSchema: {\n ...targetSchema,\n path: z.string().describe('Absolute path to the file'),\n old_string: z.string().describe('The exact string to find and replace'),\n new_string: z.string().describe('The replacement string'),\n replace_all: z.boolean().optional().describe('Replace all occurrences (default: false, replaces first only)')\n }\n },\n async (args) => {\n interface EditResponse {\n success: boolean\n data?: { replacements: number; newSize: number }\n error?: string\n }\n\n try {\n const result = await apiRequest<EditResponse>(\n 'POST',\n devPath('/edit-file', args.moduleUid),\n {\n path: args.path,\n old_string: args.old_string,\n new_string: args.new_string,\n replace_all: args.replace_all || false\n }\n )\n\n if (!result.success) {\n return {\n content: [{ type: 'text', text: `Error: ${result.error || 'Failed to edit file'}` }],\n isError: true\n }\n }\n\n const replacements = result.data?.replacements || 0\n if (replacements === 0) {\n return {\n content: [{ type: 'text', text: 'Warning: No replacements made (string not found)' }]\n }\n }\n\n return {\n content: [{\n type: 'text',\n text: `Made ${replacements} replacement(s) in ${args.path}`\n }]\n }\n } catch (error) {\n return {\n content: [{ type: 'text', text: `Error editing file: ${error}` }],\n isError: true\n }\n }\n }\n)\n\nserver.registerTool(\n 'delete_file',\n {\n description: 'Delete a file or directory',\n inputSchema: {\n ...targetSchema,\n path: z.string().describe('Absolute path to delete'),\n recursive: z.boolean().optional().describe('Delete directories recursively (default: false)')\n }\n },\n async (args) => {\n interface DeleteResponse {\n success: boolean\n error?: string\n }\n\n try {\n const result = await apiRequest<DeleteResponse>(\n 'DELETE',\n `${devPath('/delete-file', args.moduleUid)}?path=${encodeURIComponent(args.path)}&recursive=${args.recursive || false}`\n )\n\n if (!result.success) {\n return {\n content: [{ type: 'text', text: `Error: ${result.error || 'Failed to delete'}` }],\n isError: true\n }\n }\n\n return {\n content: [{ type: 'text', text: `Deleted ${args.path}` }]\n }\n } catch (error) {\n return {\n content: [{ type: 'text', text: `Error deleting: ${error}` }],\n isError: true\n }\n }\n }\n)\n\n// ============================================\n// Directory Operations\n// ============================================\n\nserver.registerTool(\n 'list_directory',\n {\n description: 'List contents of a directory',\n inputSchema: {\n ...targetSchema,\n path: z.string().describe('Absolute path to directory'),\n recursive: z.boolean().optional().describe('List recursively (default: false)'),\n includeHidden: z.boolean().optional().describe('Include hidden files (default: false)')\n }\n },\n async (args) => {\n interface ListResponse {\n success: boolean\n data?: {\n entries: Array<{\n name: string\n type: 'file' | 'directory'\n size: number\n }>\n }\n error?: string\n }\n\n try {\n const result = await apiRequest<ListResponse>(\n 'POST',\n devPath('/list-dir', args.moduleUid),\n {\n path: args.path,\n recursive: args.recursive || false,\n includeHidden: args.includeHidden || false\n }\n )\n\n if (!result.success || !result.data) {\n return {\n content: [{ type: 'text', text: `Error: ${result.error || 'Failed to list directory'}` }],\n isError: true\n }\n }\n\n if (result.data.entries.length === 0) {\n return {\n content: [{ type: 'text', text: `Directory ${args.path} is empty` }]\n }\n }\n\n const listing = result.data.entries.map(e => {\n const icon = e.type === 'directory' ? '/' : ''\n const size = e.type === 'file' ? ` (${formatSize(e.size)})` : ''\n return `${e.name}${icon}${size}`\n }).join('\\n')\n\n return {\n content: [{ type: 'text', text: listing }]\n }\n } catch (error) {\n return {\n content: [{ type: 'text', text: `Error listing directory: ${error}` }],\n isError: true\n }\n }\n }\n)\n\nserver.registerTool(\n 'mkdir',\n {\n description: 'Create a directory (including parent directories)',\n inputSchema: {\n ...targetSchema,\n path: z.string().describe('Absolute path of directory to create')\n }\n },\n async (args) => {\n interface MkdirResponse {\n success: boolean\n error?: string\n }\n\n try {\n const result = await apiRequest<MkdirResponse>(\n 'POST',\n devPath('/mkdir', args.moduleUid),\n { path: args.path }\n )\n\n if (!result.success) {\n return {\n content: [{ type: 'text', text: `Error: ${result.error || 'Failed to create directory'}` }],\n isError: true\n }\n }\n\n return {\n content: [{ type: 'text', text: `Created directory ${args.path}` }]\n }\n } catch (error) {\n return {\n content: [{ type: 'text', text: `Error creating directory: ${error}` }],\n isError: true\n }\n }\n }\n)\n\nserver.registerTool(\n 'search_files',\n {\n description: 'Search for files by glob pattern',\n inputSchema: {\n ...targetSchema,\n pattern: z.string().describe('Glob pattern (e.g., \"*.ts\", \"**/*.tsx\")'),\n basePath: z.string().describe('Base directory to search from'),\n maxResults: z.number().optional().describe('Maximum results (default: 100)')\n }\n },\n async (args) => {\n interface SearchResponse {\n success: boolean\n data?: { files: string[] }\n error?: string\n }\n\n try {\n const result = await apiRequest<SearchResponse>(\n 'POST',\n devPath('/search-files', args.moduleUid),\n {\n pattern: args.pattern,\n basePath: args.basePath,\n maxResults: args.maxResults || 100\n }\n )\n\n if (!result.success || !result.data) {\n return {\n content: [{ type: 'text', text: `Error: ${result.error || 'Failed to search'}` }],\n isError: true\n }\n }\n\n if (result.data.files.length === 0) {\n return {\n content: [{ type: 'text', text: `No files matching \"${args.pattern}\" found` }]\n }\n }\n\n return {\n content: [{\n type: 'text',\n text: `Found ${result.data.files.length} file(s):\\n${result.data.files.join('\\n')}`\n }]\n }\n } catch (error) {\n return {\n content: [{ type: 'text', text: `Error searching: ${error}` }],\n isError: true\n }\n }\n }\n)\n\n// ============================================\n// Code Search\n// ============================================\n\nserver.registerTool(\n 'grep',\n {\n description: 'Search for pattern in file contents',\n inputSchema: {\n ...targetSchema,\n pattern: z.string().describe('Search pattern (regex supported)'),\n path: z.string().describe('File or directory to search'),\n filePattern: z.string().optional().describe('Filter by file pattern (e.g., \"*.ts\")'),\n caseSensitive: z.boolean().optional().describe('Case sensitive search (default: true)'),\n maxResults: z.number().optional().describe('Maximum results (default: 100)')\n }\n },\n async (args) => {\n interface GrepResponse {\n success: boolean\n data?: {\n matches: Array<{\n file: string\n line: number\n content: string\n }>\n }\n error?: string\n }\n\n try {\n const flags = args.caseSensitive === false ? '-rni' : '-rn'\n const result = await apiRequest<GrepResponse>(\n 'POST',\n devPath('/grep', args.moduleUid),\n {\n pattern: args.pattern,\n path: args.path,\n flags\n }\n )\n\n if (!result.success || !result.data) {\n return {\n content: [{ type: 'text', text: `Error: ${result.error || 'Failed to search'}` }],\n isError: true\n }\n }\n\n if (result.data.matches.length === 0) {\n return {\n content: [{ type: 'text', text: `No matches found for \"${args.pattern}\"` }]\n }\n }\n\n const matches = result.data.matches.map(m =>\n `${m.file}:${m.line}: ${m.content}`\n ).join('\\n')\n\n return {\n content: [{\n type: 'text',\n text: `Found ${result.data.matches.length} match(es):\\n${matches}`\n }]\n }\n } catch (error) {\n return {\n content: [{ type: 'text', text: `Error searching: ${error}` }],\n isError: true\n }\n }\n }\n)\n\n// ============================================\n// Command Execution\n// ============================================\n\nserver.registerTool(\n 'exec_command',\n {\n description: 'Execute a shell command',\n inputSchema: {\n ...targetSchema,\n command: z.string().describe('Command to execute'),\n cwd: z.string().optional().describe('Working directory'),\n timeout: z.number().optional().describe('Timeout in milliseconds (default: 30000)')\n }\n },\n async (args) => {\n interface ExecResponse {\n success: boolean\n data?: {\n stdout: string\n stderr: string\n exitCode: number\n timedOut?: boolean\n }\n error?: string\n }\n\n try {\n const result = await apiRequest<ExecResponse>(\n 'POST',\n devPath('/exec', args.moduleUid),\n {\n command: args.command,\n cwd: args.cwd,\n timeout: args.timeout || 30000\n }\n )\n\n if (!result.success || !result.data) {\n return {\n content: [{ type: 'text', text: `Error: ${result.error || 'Command failed'}` }],\n isError: true\n }\n }\n\n const { stdout, stderr, exitCode, timedOut } = result.data\n\n if (timedOut) {\n return {\n content: [{ type: 'text', text: `Command timed out\\n\\nOutput so far:\\n${stdout}` }],\n isError: true\n }\n }\n\n let output = ''\n if (stdout) output += stdout\n if (stderr) output += `\\n\\nSTDERR:\\n${stderr}`\n if (exitCode !== 0) output += `\\n\\nExit code: ${exitCode}`\n\n return {\n content: [{ type: 'text', text: output || '(no output)' }],\n isError: exitCode !== 0\n }\n } catch (error) {\n return {\n content: [{ type: 'text', text: `Error executing command: ${error}` }],\n isError: true\n }\n }\n }\n)\n\n// ============================================\n// Batch Operations\n// ============================================\n\nserver.registerTool(\n 'batch_operations',\n {\n description: 'Execute multiple file operations in a single request',\n inputSchema: {\n ...targetSchema,\n operations: z.array(z.object({\n type: z.enum(['read', 'write', 'mkdir', 'delete', 'exec']).describe('Operation type'),\n path: z.string().optional().describe('File/directory path'),\n content: z.string().optional().describe('Content for write operations'),\n command: z.string().optional().describe('Command for exec operations'),\n recursive: z.boolean().optional().describe('Recursive flag for delete')\n })).describe('Array of operations to execute'),\n stopOnError: z.boolean().optional().describe('Stop on first error (default: false)')\n }\n },\n async (args) => {\n interface BatchResponse {\n success: boolean\n data?: {\n results: Array<{\n success: boolean\n data?: unknown\n error?: string\n }>\n completedCount: number\n failedCount: number\n }\n error?: string\n }\n\n try {\n const result = await apiRequest<BatchResponse>(\n 'POST',\n devPath('/batch', args.moduleUid),\n {\n operations: args.operations,\n stopOnError: args.stopOnError || false\n }\n )\n\n if (!result.success || !result.data) {\n return {\n content: [{ type: 'text', text: `Error: ${result.error || 'Batch failed'}` }],\n isError: true\n }\n }\n\n const { completedCount, failedCount, results } = result.data\n\n let summary = `Batch complete: ${completedCount} succeeded, ${failedCount} failed\\n\\n`\n\n results.forEach((r, i) => {\n const op = args.operations[i]\n const status = r.success ? 'OK' : 'FAILED'\n summary += `[${i + 1}] ${op.type} ${op.path || op.command || ''}: ${status}`\n if (!r.success && r.error) summary += ` - ${r.error}`\n summary += '\\n'\n })\n\n return {\n content: [{ type: 'text', text: summary }],\n isError: failedCount > 0\n }\n } catch (error) {\n return {\n content: [{ type: 'text', text: `Error executing batch: ${error}` }],\n isError: true\n }\n }\n }\n)\n\n// ============================================\n// Utility Functions\n// ============================================\n\nfunction formatSize(bytes: number): string {\n if (bytes < 1024) return `${bytes}B`\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}KB`\n if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)}MB`\n return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)}GB`\n}\n\n// ============================================\n// Start Server\n// ============================================\n\nasync function main() {\n const runtimeConfig = await hydrateRuntimeConfig()\n EPISODA_API_URL = runtimeConfig.apiUrl\n EPISODA_SESSION_TOKEN = runtimeConfig.sessionToken\n EPISODA_PROJECT_ID = runtimeConfig.projectId\n EPISODA_WORKSPACE_ID = runtimeConfig.workspaceId\n\n if (!MODULE_UID && !DEV_ENVIRONMENT_ID) {\n console.warn('[episoda-dev] Warning: MODULE_UID/DEV_ENVIRONMENT_ID not set. Provide moduleUid per tool call.')\n }\n\n const transport = new StdioServerTransport()\n await server.connect(transport)\n\n const devTarget = MODULE_UID || DEV_ENVIRONMENT_ID || 'NOT SET'\n console.error('[episoda-dev] MCP server started')\n console.error(`[episoda-dev] API URL: ${EPISODA_API_URL}`)\n console.error(`[episoda-dev] Dev Target: ${devTarget}`)\n console.error(`[episoda-dev] Token: ${EPISODA_SESSION_TOKEN ? '****' : 'NOT SET'}`)\n}\n\nmain().catch((error) => {\n console.error('[episoda-dev] Fatal error:', error)\n process.exit(1)\n})\n","const usage = () => {\n console.error('Usage: @episoda/mcp <workflow|git|dev>')\n console.error('Aliases: episoda-workflow, episoda-git, episoda-dev')\n}\n\nasync function main() {\n const [server] = process.argv.slice(2)\n if (!server || server === '-h' || server === '--help' || server === 'help') {\n usage()\n process.exit(server ? 0 : 2)\n }\n\n const normalized = server.toLowerCase()\n\n switch (normalized) {\n case 'workflow':\n case 'episoda-workflow':\n await import('./workflow-server.js')\n break\n case 'git':\n case 'episoda-git':\n await import('./git-server.js')\n break\n case 'dev':\n case 'episoda-dev':\n await import('./dev-server.js')\n break\n default:\n usage()\n process.exit(2)\n }\n}\n\nmain().catch((error) => {\n console.error('[episoda-mcp] Fatal error:', error)\n process.exit(1)\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiiBa,YAAA,yBAAoD;MAC/D;MACA;MACA;MACA;MACA;;;;;;;;;;ACphBF,YAAA,qBAAA;AA0CA,YAAA,wBAAA;AAiBA,YAAA,oBAAA;AA6BA,YAAA,eAAA;AAxFA,aAAgB,mBAAmB,Y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AA,YACzC,SAAS,cAAc;AAAA,UACzB;AAAA,QACF,SAAS,OAAO;AACd,iBAAO;AAAA,YACL,SAAS,CAAC,EAAE,MAAM,QAAQ,MAAM,0BAA0B,KAAK,GAAG,CAAC;AAAA,YACnE,SAAS;AAAA,UACX;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAsCA,IAAAO,MAAK,EAAE,MAAM,CAAC,UAAU;AACtB,cAAQ,MAAM,8BAA8B,KAAK;AACjD,cAAQ,KAAK,CAAC;AAAA,IAChB,CAAC;AAAA;AAAA;;;AClvBD,IAAM,QAAQ,MAAM;AAClB,UAAQ,MAAM,wCAAwC;AACtD,UAAQ,MAAM,qDAAqD;AACrE;AAEA,eAAeG,QAAO;AACpB,QAAM,CAACC,OAAM,IAAI,QAAQ,KAAK,MAAM,CAAC;AACrC,MAAI,CAACA,WAAUA,YAAW,QAAQA,YAAW,YAAYA,YAAW,QAAQ;AAC1E,UAAM;AACN,YAAQ,KAAKA,UAAS,IAAI,CAAC;AAAA,EAC7B;AAEA,QAAM,aAAaA,QAAO,YAAY;AAEtC,UAAQ,YAAY;AAAA,IAClB,KAAK;AAAA,IACL,KAAK;AACH,YAAM;AACN;AAAA,IACF,KAAK;AAAA,IACL,KAAK;AACH,YAAM;AACN;AAAA,IACF,KAAK;AAAA,IACL,KAAK;AACH,YAAM;AACN;AAAA,IACF;AACE,YAAM;AACN,cAAQ,KAAK,CAAC;AAAA,EAClB;AACF;AAEAD,MAAK,EAAE,MAAM,CAAC,UAAU;AACtB,UAAQ,MAAM,8BAA8B,KAAK;AACjD,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["data","key","err","protocol","server","loadConfig","workspaceConfig","projectConfig","envConfig","McpServer","StdioServerTransport","z","EPISODA_API_URL","EPISODA_SESSION_TOKEN","EPISODA_PROJECT_ID","EPISODA_WORKSPACE_ID","main","server","McpServer","StdioServerTransport","z","apiRequest","EPISODA_API_URL","EPISODA_SESSION_TOKEN","EPISODA_PROJECT_ID","EPISODA_WORKSPACE_ID","MODULE_UID","DEV_ENVIRONMENT_ID","main","server","targetSchema","main","server"]}
|