Changesets · Branches · Tags · Compare
| Changeset | 54132eb5aa27d4c6b80ec0bf6d7be76f19277956265af83311ecfcc809ae220f |
|---|---|
| Author | Nate Sesti <33237525+sestinj@users.noreply.github.com> · 2025-09-26 17:31 -07:00 |
| Committer | GitHub <noreply@github.com> · 2025-09-26 17:31 -07:00 |
| Parents | 2e6f3439cd00 |
3 files changed
modified extensions/cli/src/commands/remote.test.ts +72 −1
| @@ -145,6 +145,77 @@ | ||
| 145 | 145 | expect(mockConsoleLog).not.toHaveBeenCalled(); |
| 146 | 146 | }); |
| 147 | 147 | |
| 148 | + it("should fetch tunnel and connect when id option is provided", async () => { | |
| 149 | + const agentId = "agent-789"; | |
| 150 | + | |
| 151 | + mockFetch | |
| 152 | + .mockResolvedValueOnce({ | |
| 153 | + ok: true, | |
| 154 | + json: async () => ({ url: "ws://tunnel-url.com", port: 9090 }), | |
| 155 | + }) | |
| 156 | + .mockResolvedValue({ | |
| 157 | + ok: true, | |
| 158 | + json: async () => ({ | |
| 159 | + id: "test-agent-id", | |
| 160 | + url: "ws://test-url.com", | |
| 161 | + port: 8080, | |
| 162 | + }), | |
| 163 | + }); | |
| 164 | + | |
| 165 | + await remote("test prompt", { id: agentId }); | |
| 166 | + | |
| 167 | + expect(mockFetch).toHaveBeenCalledWith( | |
| 168 | + new URL(`agents/${agentId}/tunnel`, mockEnv.env.apiBase), | |
| 169 | + expect.objectContaining({ | |
| 170 | + method: "POST", | |
| 171 | + headers: { | |
| 172 | + "Content-Type": "application/json", | |
| 173 | + Authorization: "Bearer test-token", | |
| 174 | + }, | |
| 175 | + }), | |
| 176 | + ); | |
| 177 | + | |
| 178 | + expect(mockStartRemoteTUIChat.startRemoteTUIChat).toHaveBeenCalledWith( | |
| 179 | + "ws://tunnel-url.com", | |
| 180 | + "test prompt", | |
| 181 | + ); | |
| 182 | + }); | |
| 183 | + | |
| 184 | + it("should output JSON without starting TUI when using --id with --start", async () => { | |
| 185 | + const agentId = "agent-456"; | |
| 186 | + const tunnelResponse = { url: "ws://existing-tunnel.com", port: 7070 }; | |
| 187 | + | |
| 188 | + mockFetch.mockResolvedValueOnce({ | |
| 189 | + ok: true, | |
| 190 | + json: async () => tunnelResponse, | |
| 191 | + }); | |
| 192 | + | |
| 193 | + await remote("test prompt", { id: agentId, start: true }); | |
| 194 | + | |
| 195 | + expect(mockFetch).toHaveBeenCalledWith( | |
| 196 | + new URL(`agents/${agentId}/tunnel`, mockEnv.env.apiBase), | |
| 197 | + expect.objectContaining({ | |
| 198 | + method: "POST", | |
| 199 | + headers: { | |
| 200 | + "Content-Type": "application/json", | |
| 201 | + Authorization: "Bearer test-token", | |
| 202 | + }, | |
| 203 | + }), | |
| 204 | + ); | |
| 205 | + | |
| 206 | + expect(mockStartRemoteTUIChat.startRemoteTUIChat).not.toHaveBeenCalled(); | |
| 207 | + expect(mockConsoleLog).toHaveBeenCalledWith( | |
| 208 | + JSON.stringify({ | |
| 209 | + status: "success", | |
| 210 | + message: "Remote agent tunnel connection details", | |
| 211 | + url: tunnelResponse.url, | |
| 212 | + containerPort: tunnelResponse.port, | |
| 213 | + agentId, | |
| 214 | + mode: "existing_agent", | |
| 215 | + }), | |
| 216 | + ); | |
| 217 | + }); | |
| 218 | + | |
| 148 | 219 | it("should handle proper request body structure with all fields", async () => { |
| 149 | 220 | const testIdempotencyKey = "structured-test-key"; |
| 150 | 221 | |
| @@ -298,10 +369,10 @@ | ||
| 298 | 369 | repoUrl: "https://github.com/user/test-repo.git", |
| 299 | 370 | name: expect.stringMatching(/^devbox-\d+$/), |
| 300 | 371 | prompt: "test prompt", |
| 301 | - idempotencyKey: undefined, | |
| 302 | 372 | agent: undefined, |
| 303 | 373 | config: undefined, |
| 304 | 374 | }); |
| 375 | + expect(requestBody).not.toHaveProperty("idempotencyKey"); | |
| 305 | 376 | }); |
| 306 | 377 | |
| 307 | 378 | describe("start mode (-s / --start flag)", () => { |
modified extensions/cli/src/commands/remote.ts +230 −127
| @@ -9,155 +9,258 @@ | ||
| 9 | 9 | import { logger } from "../util/logger.js"; |
| 10 | 10 | import { readStdinSync } from "../util/stdin.js"; |
| 11 | 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 | + | |
| 12 | 37 | export async function remote( |
| 13 | 38 | prompt: string | undefined, |
| 14 | - options: { | |
| 15 | - url?: string; | |
| 16 | - idempotencyKey?: string; | |
| 17 | - start?: boolean; | |
| 18 | - branch?: string; | |
| 19 | - repo?: string; | |
| 20 | - config?: string; | |
| 21 | - } = {}, | |
| 39 | + options: RemoteCommandOptions = {}, | |
| 22 | 40 | ) { |
| 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; | |
| 41 | + const actualPrompt = resolvePrompt(prompt); | |
| 42 | + | |
| 43 | + try { | |
| 44 | + if (options.url) { | |
| 45 | + await connectToRemoteUrl(options.url, actualPrompt, options.start); | |
| 46 | + return; | |
| 37 | 47 | } |
| 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 | - }), | |
| 48 | + | |
| 49 | + const accessToken = requireAccessToken(); | |
| 50 | + | |
| 51 | + if (options.id) { | |
| 52 | + await connectExistingAgent( | |
| 53 | + options.id, | |
| 54 | + accessToken, | |
| 55 | + actualPrompt, | |
| 56 | + options.start, | |
| 50 | 57 | ); |
| 51 | 58 | return; |
| 52 | 59 | } |
| 53 | 60 | |
| 54 | - console.info( | |
| 55 | - chalk.white(`Connecting to remote environment at: ${options.url}`), | |
| 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}`, | |
| 56 | 164 | ); |
| 165 | + } | |
| 57 | 166 | |
| 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 | - } | |
| 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 | + }); | |
| 68 | 179 | return; |
| 69 | 180 | } |
| 70 | 181 | |
| 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 | - } | |
| 182 | + console.info( | |
| 183 | + chalk.green("✅ Remote development environment created successfully!"), | |
| 184 | + ); | |
| 81 | 185 | |
| 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 | - } | |
| 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 | +} | |
| 97 | 218 | |
| 98 | - const response = await fetch(new URL("agents", env.apiBase), { | |
| 219 | +async function fetchAgentTunnel(agentId: string, accessToken: string) { | |
| 220 | + const response = await fetch( | |
| 221 | + new URL(`agents/${agentId}/tunnel`, env.apiBase), | |
| 222 | + { | |
| 99 | 223 | method: "POST", |
| 100 | 224 | headers: { |
| 101 | 225 | "Content-Type": "application/json", |
| 102 | 226 | Authorization: `Bearer ${accessToken}`, |
| 103 | 227 | }, |
| 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!"), | |
| 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}`, | |
| 134 | 235 | ); |
| 236 | + } | |
| 135 | 237 | |
| 136 | - if (result.url && result.port) { | |
| 137 | - const remoteUrl = result.url; | |
| 138 | - console.info( | |
| 139 | - chalk.white(`Connecting to remote environment at: ${remoteUrl}`), | |
| 140 | - ); | |
| 238 | + return (await response.json()) as TunnelResponse; | |
| 239 | +} | |
| 141 | 240 | |
| 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); | |
| 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(); | |
| 162 | 249 | } |
| 163 | 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 | +} |
modified extensions/cli/src/index.ts +4 −0
| @@ -277,6 +277,10 @@ | ||
| 277 | 277 | "--url <url>", |
| 278 | 278 | "Connect directly to the specified URL instead of creating a new remote environment", |
| 279 | 279 | ) |
| 280 | + .option( | |
| 281 | + "--id <id>", | |
| 282 | + "Connect to an existing remote agent by id and establish a tunnel", | |
| 283 | + ) | |
| 280 | 284 | .option( |
| 281 | 285 | "--idempotency-key <key>", |
| 282 | 286 | "Idempotency key for session management - allows resuming existing sessions", |