Elffuss BraidHub

kikocis/continue public

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