| 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 | type RemoteCommandOptions = { |
| 13 | url?: string; |
| 14 | id?: string; |
| 15 | idempotencyKey?: string; |
| 16 | start?: boolean; |
| 17 | branch?: string; |
| 18 | repo?: string; |
| 19 | config?: string; |
| 20 | }; |
| 21 | |
| 22 | type TunnelResponse = { |
| 23 | url: string; |
| 24 | port?: number; |
| 25 | }; |
| 26 | |
| 27 | type AgentCreationResponse = TunnelResponse & { |
| 28 | id: string; |
| 29 | }; |
| 30 | |
| 31 | class AuthenticationRequiredError extends Error { |
| 32 | constructor() { |
| 33 | super("Not authenticated. Please run 'cn login' first."); |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | export async function remote( |
| 38 | prompt: string | undefined, |
| 39 | options: RemoteCommandOptions = {}, |
| 40 | ) { |
| 41 | const actualPrompt = resolvePrompt(prompt); |
| 42 | |
| 43 | try { |
| 44 | if (options.url) { |
| 45 | await connectToRemoteUrl(options.url, actualPrompt, options.start); |
| 46 | return; |
| 47 | } |
| 48 | |
| 49 | const accessToken = requireAccessToken(); |
| 50 | |
| 51 | if (options.id) { |
| 52 | await connectExistingAgent( |
| 53 | options.id, |
| 54 | accessToken, |
| 55 | actualPrompt, |
| 56 | options.start, |
| 57 | ); |
| 58 | return; |
| 59 | } |
| 60 | |
| 61 | await createAndConnectRemoteEnvironment(accessToken, actualPrompt, options); |
| 62 | } catch (error) { |
| 63 | await handleRemoteError(error); |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | function resolvePrompt(prompt: string | undefined): string | undefined { |
| 68 | const stdinInput = readStdinSync(); |
| 69 | |
| 70 | if (!stdinInput) { |
| 71 | return prompt; |
| 72 | } |
| 73 | |
| 74 | if (!prompt) { |
| 75 | return stdinInput; |
| 76 | } |
| 77 | |
| 78 | return `<stdin>\n${stdinInput}\n</stdin>\n\n${prompt}`; |
| 79 | } |
| 80 | |
| 81 | async function connectToRemoteUrl( |
| 82 | remoteUrl: string, |
| 83 | prompt: string | undefined, |
| 84 | startOnly?: boolean, |
| 85 | ) { |
| 86 | if (startOnly) { |
| 87 | printStartJson({ |
| 88 | status: "success", |
| 89 | message: "Remote environment connection details", |
| 90 | url: remoteUrl, |
| 91 | mode: "direct_url", |
| 92 | }); |
| 93 | return; |
| 94 | } |
| 95 | |
| 96 | console.info( |
| 97 | chalk.white(`Connecting to remote environment at: ${remoteUrl}`), |
| 98 | ); |
| 99 | await launchRemoteTUI(remoteUrl, prompt); |
| 100 | } |
| 101 | |
| 102 | function requireAccessToken(): string { |
| 103 | const authConfig = loadAuthConfig(); |
| 104 | |
| 105 | if (!authConfig) { |
| 106 | throw new AuthenticationRequiredError(); |
| 107 | } |
| 108 | |
| 109 | const accessToken = getAccessToken(authConfig); |
| 110 | |
| 111 | if (!accessToken) { |
| 112 | throw new AuthenticationRequiredError(); |
| 113 | } |
| 114 | |
| 115 | return accessToken; |
| 116 | } |
| 117 | |
| 118 | async function connectExistingAgent( |
| 119 | agentId: string, |
| 120 | accessToken: string, |
| 121 | prompt: string | undefined, |
| 122 | startOnly?: boolean, |
| 123 | ) { |
| 124 | const tunnel = await fetchAgentTunnel(agentId, accessToken); |
| 125 | |
| 126 | if (startOnly) { |
| 127 | printStartJson({ |
| 128 | status: "success", |
| 129 | message: "Remote agent tunnel connection details", |
| 130 | url: tunnel.url, |
| 131 | containerPort: tunnel.port, |
| 132 | agentId, |
| 133 | mode: "existing_agent", |
| 134 | }); |
| 135 | return; |
| 136 | } |
| 137 | |
| 138 | console.info( |
| 139 | chalk.white(`Connecting to remote agent tunnel at: ${tunnel.url}`), |
| 140 | ); |
| 141 | await launchRemoteTUI(tunnel.url, prompt); |
| 142 | } |
| 143 | |
| 144 | async function createAndConnectRemoteEnvironment( |
| 145 | accessToken: string, |
| 146 | prompt: string | undefined, |
| 147 | options: RemoteCommandOptions, |
| 148 | ) { |
| 149 | const requestBody = buildAgentRequestBody(options, prompt); |
| 150 | |
| 151 | const response = await fetch(new URL("agents", env.apiBase), { |
| 152 | method: "POST", |
| 153 | headers: { |
| 154 | "Content-Type": "application/json", |
| 155 | Authorization: `Bearer ${accessToken}`, |
| 156 | }, |
| 157 | body: JSON.stringify(requestBody), |
| 158 | }); |
| 159 | |
| 160 | if (!response.ok) { |
| 161 | const errorText = await response.text(); |
| 162 | throw new Error( |
| 163 | `Failed to create remote environment: ${response.status} ${errorText}`, |
| 164 | ); |
| 165 | } |
| 166 | |
| 167 | const result = (await response.json()) as AgentCreationResponse; |
| 168 | |
| 169 | if (options.start) { |
| 170 | printStartJson({ |
| 171 | status: "success", |
| 172 | message: "Remote development environment created successfully", |
| 173 | url: `${env.appUrl}/agents/${result.id}`, |
| 174 | containerUrl: result.url, |
| 175 | containerPort: result.port, |
| 176 | name: requestBody.name, |
| 177 | mode: "new_environment", |
| 178 | }); |
| 179 | return; |
| 180 | } |
| 181 | |
| 182 | console.info( |
| 183 | chalk.green("✅ Remote development environment created successfully!"), |
| 184 | ); |
| 185 | |
| 186 | if (!result.url) { |
| 187 | throw new Error("No URL returned from remote environment creation"); |
| 188 | } |
| 189 | |
| 190 | console.info( |
| 191 | chalk.white(`Connecting to remote environment at: ${result.url}`), |
| 192 | ); |
| 193 | await launchRemoteTUI(result.url, prompt); |
| 194 | } |
| 195 | |
| 196 | function buildAgentRequestBody( |
| 197 | options: RemoteCommandOptions, |
| 198 | prompt: string | undefined, |
| 199 | ) { |
| 200 | const body: Record<string, unknown> = { |
| 201 | repoUrl: options.repo ?? getRepoUrl(), |
| 202 | name: `devbox-${Date.now()}`, |
| 203 | prompt, |
| 204 | agent: options.config, |
| 205 | config: options.config, |
| 206 | }; |
| 207 | |
| 208 | if (options.idempotencyKey) { |
| 209 | body.idempotencyKey = options.idempotencyKey; |
| 210 | } |
| 211 | |
| 212 | if (options.branch) { |
| 213 | body.branchName = options.branch; |
| 214 | } |
| 215 | |
| 216 | return body; |
| 217 | } |
| 218 | |
| 219 | async function fetchAgentTunnel(agentId: string, accessToken: string) { |
| 220 | const response = await fetch( |
| 221 | new URL(`agents/${agentId}/tunnel`, env.apiBase), |
| 222 | { |
| 223 | method: "POST", |
| 224 | headers: { |
| 225 | "Content-Type": "application/json", |
| 226 | Authorization: `Bearer ${accessToken}`, |
| 227 | }, |
| 228 | }, |
| 229 | ); |
| 230 | |
| 231 | if (!response.ok) { |
| 232 | const errorText = await response.text(); |
| 233 | throw new Error( |
| 234 | `Failed to create tunnel for agent ${agentId}: ${response.status} ${errorText}`, |
| 235 | ); |
| 236 | } |
| 237 | |
| 238 | return (await response.json()) as TunnelResponse; |
| 239 | } |
| 240 | |
| 241 | async function launchRemoteTUI(remoteUrl: string, prompt: string | undefined) { |
| 242 | telemetryService.recordSessionStart(); |
| 243 | telemetryService.startActiveTime(); |
| 244 | |
| 245 | try { |
| 246 | await startRemoteTUIChat(remoteUrl, prompt); |
| 247 | } finally { |
| 248 | telemetryService.stopActiveTime(); |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | function printStartJson(payload: Record<string, unknown>) { |
| 253 | console.log(JSON.stringify(payload)); |
| 254 | } |
| 255 | |
| 256 | async function handleRemoteError(error: unknown) { |
| 257 | if (error instanceof AuthenticationRequiredError) { |
| 258 | logger.error(chalk.red(error.message)); |
| 259 | } else if (error instanceof Error) { |
| 260 | logger.error(chalk.red(error.message)); |
| 261 | } else { |
| 262 | logger.error(chalk.red("An unknown error occurred while starting remote")); |
| 263 | } |
| 264 | |
| 265 | await gracefulExit(1); |
| 266 | } |