| 1 | import chalk from "chalk"; |
| 2 | |
| 3 | import { getAccessToken, loadAuthConfig } from "../auth/workos.js"; |
| 4 | import { env } from "../env.js"; |
| 5 | import { telemetryService } from "../telemetry/telemetryService.js"; |
| 6 | import { startRemoteTUIChat } from "../ui/index.js"; |
| 7 | import { gracefulExit } from "../util/exit.js"; |
| 8 | import { getRepoUrl } from "../util/git.js"; |
| 9 | import { logger } from "../util/logger.js"; |
| 10 | import { readStdinSync } from "../util/stdin.js"; |
| 11 | |
| 12 | export async function remote( |
| 13 | prompt: string | undefined, |
| 14 | options: { |
| 15 | url?: string; |
| 16 | idempotencyKey?: string; |
| 17 | start?: boolean; |
| 18 | branch?: string; |
| 19 | repo?: string; |
| 20 | config?: string; |
| 21 | } = {}, |
| 22 | ) { |
| 23 | // Check if prompt should come from stdin instead of parameter |
| 24 | let actualPrompt = prompt; |
| 25 | if (prompt) { |
| 26 | // If prompt is provided, still check for stdin and combine them |
| 27 | const stdinInput = readStdinSync(); |
| 28 | if (stdinInput) { |
| 29 | // Combine stdin and prompt argument - stdin comes first in XML block |
| 30 | actualPrompt = `<stdin>\n${stdinInput}\n</stdin>\n\n${prompt}`; |
| 31 | } |
| 32 | } else { |
| 33 | // Try to read from stdin (for piped input like: echo "hello" | cn remote -s) |
| 34 | const stdinInput = readStdinSync(); |
| 35 | if (stdinInput) { |
| 36 | actualPrompt = stdinInput; |
| 37 | } |
| 38 | } |
| 39 | // If --url is provided, connect directly to that URL |
| 40 | if (options.url) { |
| 41 | if (options.start) { |
| 42 | // In start mode, output connection details as JSON and exit |
| 43 | console.log( |
| 44 | JSON.stringify({ |
| 45 | status: "success", |
| 46 | message: "Remote environment connection details", |
| 47 | url: options.url, |
| 48 | mode: "direct_url", |
| 49 | }), |
| 50 | ); |
| 51 | return; |
| 52 | } |
| 53 | |
| 54 | console.info( |
| 55 | chalk.white(`Connecting to remote environment at: ${options.url}`), |
| 56 | ); |
| 57 | |
| 58 | // Record session start |
| 59 | telemetryService.recordSessionStart(); |
| 60 | telemetryService.startActiveTime(); |
| 61 | |
| 62 | try { |
| 63 | // Start the TUI in remote mode |
| 64 | await startRemoteTUIChat(options.url, actualPrompt); |
| 65 | } finally { |
| 66 | telemetryService.stopActiveTime(); |
| 67 | } |
| 68 | return; |
| 69 | } |
| 70 | |
| 71 | try { |
| 72 | const authConfig = loadAuthConfig(); |
| 73 | |
| 74 | // Check if we have any valid authentication (file-based or environment variable) |
| 75 | if (!authConfig || !getAccessToken(authConfig)) { |
| 76 | console.error( |
| 77 | chalk.red("Not authenticated. Please run 'cn login' first."), |
| 78 | ); |
| 79 | await gracefulExit(1); |
| 80 | } |
| 81 | |
| 82 | const accessToken = getAccessToken(authConfig); |
| 83 | |
| 84 | const requestBody: any = { |
| 85 | repoUrl: options.repo || getRepoUrl(), |
| 86 | name: `devbox-${Date.now()}`, |
| 87 | prompt: actualPrompt, |
| 88 | idempotencyKey: options.idempotencyKey, |
| 89 | agent: options.config, |
| 90 | config: options.config, |
| 91 | }; |
| 92 | |
| 93 | // Add branchName to request body if branch option is provided |
| 94 | if (options.branch) { |
| 95 | requestBody.branchName = options.branch; |
| 96 | } |
| 97 | |
| 98 | const response = await fetch(new URL("agents/devboxes", env.apiBase), { |
| 99 | method: "POST", |
| 100 | headers: { |
| 101 | "Content-Type": "application/json", |
| 102 | Authorization: `Bearer ${accessToken}`, |
| 103 | }, |
| 104 | body: JSON.stringify(requestBody), |
| 105 | }); |
| 106 | |
| 107 | if (!response.ok) { |
| 108 | const errorText = await response.text(); |
| 109 | throw new Error( |
| 110 | `Failed to create remote environment: ${response.status} ${errorText}`, |
| 111 | ); |
| 112 | } |
| 113 | |
| 114 | const result = await response.json(); |
| 115 | |
| 116 | if (options.start) { |
| 117 | // In start mode, output connection details as JSON and exit |
| 118 | console.log( |
| 119 | JSON.stringify({ |
| 120 | status: "success", |
| 121 | message: "Remote development environment created successfully", |
| 122 | url: `${env.appUrl}/agents/${result.id}`, |
| 123 | containerUrl: result.url, |
| 124 | containerPort: result.port, |
| 125 | name: requestBody.name, |
| 126 | mode: "new_environment", |
| 127 | }), |
| 128 | ); |
| 129 | return; |
| 130 | } |
| 131 | |
| 132 | console.info( |
| 133 | chalk.green("✅ Remote development environment created successfully!"), |
| 134 | ); |
| 135 | |
| 136 | if (result.url && result.port) { |
| 137 | const remoteUrl = result.url; |
| 138 | console.info( |
| 139 | chalk.white(`Connecting to remote environment at: ${remoteUrl}`), |
| 140 | ); |
| 141 | |
| 142 | // Record session start |
| 143 | telemetryService.recordSessionStart(); |
| 144 | telemetryService.startActiveTime(); |
| 145 | |
| 146 | try { |
| 147 | // Start the TUI in remote mode (prompt is optional) |
| 148 | await startRemoteTUIChat(remoteUrl, actualPrompt); |
| 149 | } finally { |
| 150 | telemetryService.stopActiveTime(); |
| 151 | } |
| 152 | } else { |
| 153 | throw new Error( |
| 154 | "No URL or port returned from remote environment creation", |
| 155 | ); |
| 156 | } |
| 157 | } catch (error: any) { |
| 158 | logger.error( |
| 159 | chalk.red(`Failed to create remote environment: ${error.message}`), |
| 160 | ); |
| 161 | await gracefulExit(1); |
| 162 | } |
| 163 | } |