-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstart-opencode-daytona.ts
More file actions
514 lines (449 loc) · 15.4 KB
/
start-opencode-daytona.ts
File metadata and controls
514 lines (449 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
import { spawn } from "node:child_process";
import { randomUUID } from "node:crypto";
import process from "node:process";
import { setTimeout as sleep } from "node:timers/promises";
import { parseArgs } from "node:util";
import { Daytona, type Sandbox } from "@daytonaio/sdk";
import { buildInstallOpencodeCommand } from "./opencode-cli.js";
import { loadConfiguredEnv } from "./shpit-config.js";
type CliOptions = {
port: number;
keepSandbox: boolean;
sandboxName?: string;
createTimeoutSec: number;
installTimeoutSec: number;
target?: string;
openUi: boolean;
};
const SANDBOX_LIFECYCLE_POLICY = {
autoStopInterval: 15,
autoArchiveInterval: 30,
autoDeleteInterval: -1,
} as const;
type LogCursor = { value: string };
type DaytonaCompatClient = {
configApi: {
configControllerGetConfig: () => Promise<{
data: {
proxyToolboxUrl?: string;
};
}>;
};
getProxyToolboxUrl: (sandboxId: string, regionId: string) => Promise<string>;
};
function parsePositiveInt(value: string, flag: string): number {
const parsed = Number.parseInt(value, 10);
if (!Number.isFinite(parsed) || parsed <= 0) {
throw new Error(`${flag} must be a positive integer. Received "${value}".`);
}
return parsed;
}
function parsePort(value: string): number {
const parsed = Number.parseInt(value, 10);
if (!Number.isFinite(parsed) || parsed < 1 || parsed > 65535) {
throw new Error(`--port must be between 1 and 65535. Received "${value}".`);
}
return parsed;
}
function parseCliOptions(): CliOptions {
const { values } = parseArgs({
options: {
help: { type: "boolean", short: "h", default: false },
port: { type: "string", short: "p", default: "3000" },
"keep-sandbox": { type: "boolean", default: false },
"sandbox-name": { type: "string" },
"create-timeout-sec": { type: "string", default: "180" },
"install-timeout-sec": { type: "string", default: "900" },
target: { type: "string" },
"no-open": { type: "boolean", default: false },
},
strict: true,
allowPositionals: false,
});
if (values.help) {
console.log(`Usage: bun run start -- [options]
Options:
-p, --port <n> Port to expose OpenCode web server (default: 3000)
--target <name> Daytona target override
--sandbox-name <name> Custom sandbox name
--create-timeout-sec <n> Sandbox creation timeout seconds (default: 180)
--install-timeout-sec <n> OpenCode install timeout seconds (default: 900)
--keep-sandbox Keep sandbox after stopping (default: false)
--no-open Do not auto-open OpenCode URL
-h, --help Show this help
`);
process.exit(0);
}
return {
port: parsePort(values.port),
keepSandbox: values["keep-sandbox"],
sandboxName: values["sandbox-name"],
createTimeoutSec: parsePositiveInt(values["create-timeout-sec"], "--create-timeout-sec"),
installTimeoutSec: parsePositiveInt(values["install-timeout-sec"], "--install-timeout-sec"),
target: values.target,
openUi: !values["no-open"],
};
}
function requireEnv(name: string): string {
const value = process.env[name];
if (!value) {
throw new Error(`Missing required environment variable: ${name}`);
}
return value;
}
function shellEscape(value: string): string {
return `'${value.replace(/'/g, `'"'"'`)}'`;
}
function getPreviewUrlPattern(previewUrl: string, port: number): string {
const asStringPort = `:${port}`;
if (previewUrl.includes(asStringPort)) {
return previewUrl.replace(asStringPort, ":{PORT}");
}
return previewUrl.replace(`${port}`, "{PORT}");
}
function buildOpencodeConfig(previewUrlPattern: string): string {
const prompt = [
"You are running in a Daytona sandbox.",
"Use /home/daytona for file operations unless the task explicitly requires another directory.",
`Services started on localhost inside this sandbox are reachable from outside as: ${previewUrlPattern}.`,
"When you start a server, always provide the preview URL to the user.",
"Start long-running services in the background so the shell stays usable.",
].join(" ");
return JSON.stringify(
{
$schema: "https://opencode.ai/config.json",
default_agent: "daytona",
agent: {
daytona: {
description: "Daytona sandbox-aware coding agent",
mode: "primary",
prompt,
},
},
},
null,
2,
);
}
function extractNewLogChunk(latest: string | undefined, cursor: LogCursor): string {
if (!latest) {
return "";
}
if (latest.startsWith(cursor.value)) {
const next = latest.slice(cursor.value.length);
cursor.value = latest;
return next;
}
cursor.value = latest;
return latest;
}
function rewriteLocalhostUrls(text: string, port: number, previewUrl: string): string {
const regex = new RegExp(
`http:\\/\\/(?:127\\.0\\.0\\.1|0\\.0\\.0\\.0|localhost):${port}(?:\\/[^\\s]*)?`,
"g",
);
return text.replace(regex, (localUrl) => {
try {
const source = new URL(localUrl);
const target = new URL(previewUrl);
target.pathname = source.pathname;
target.search = source.search;
target.hash = source.hash;
return target.toString();
} catch {
return previewUrl;
}
});
}
async function runOpenCommand(command: string, args: string[]): Promise<boolean> {
return await new Promise<boolean>((resolve) => {
let settled = false;
const child = spawn(command, args, { detached: true, stdio: "ignore" });
child.once("error", () => {
if (!settled) {
settled = true;
resolve(false);
}
});
child.once("spawn", () => {
child.unref();
if (!settled) {
settled = true;
resolve(true);
}
});
setTimeout(() => {
if (!settled) {
settled = true;
resolve(false);
}
}, 2000);
});
}
async function tryOpenDesktop(url: string): Promise<boolean> {
if (process.platform !== "darwin") {
return false;
}
return (
(await runOpenCommand("open", ["-a", "OpenCode", url])) ||
(await runOpenCommand("open", ["-a", "OpenCode"]))
);
}
async function tryOpenBrowser(url: string): Promise<boolean> {
if (process.platform === "darwin") {
return await runOpenCommand("open", [url]);
}
if (process.platform === "win32") {
return await runOpenCommand("cmd", ["/c", "start", "", url]);
}
return await runOpenCommand("xdg-open", [url]);
}
async function openUi(url: string): Promise<void> {
if (await tryOpenDesktop(url)) {
console.log("[local] Opened OpenCode desktop app.");
return;
}
if (await tryOpenBrowser(url)) {
console.log("[local] Opened OpenCode web URL in browser.");
return;
}
console.log(`[local] Could not auto-open URL. Open manually: ${url}`);
}
function patchToolboxProxyUrlFallback(daytona: Daytona): void {
const compat = daytona as unknown as DaytonaCompatClient;
const originalResolver = compat.getProxyToolboxUrl.bind(compat);
let cachedFallbackUrl: string | undefined;
compat.getProxyToolboxUrl = async (sandboxId: string, regionId: string): Promise<string> => {
try {
return await originalResolver(sandboxId, regionId);
} catch (error) {
const statusCode = (error as { statusCode?: number } | undefined)?.statusCode;
const message = String((error as { message?: string } | undefined)?.message ?? "");
const isMissingEndpoint = statusCode === 404 || message.includes("toolbox-proxy-url");
if (!isMissingEndpoint) {
throw error;
}
if (!cachedFallbackUrl) {
const configResponse = await compat.configApi.configControllerGetConfig();
const candidate = configResponse.data.proxyToolboxUrl;
if (!candidate) {
throw new Error(
"Daytona server is missing /sandbox/:id/toolbox-proxy-url and /config.proxyToolboxUrl fallback is empty.",
);
}
cachedFallbackUrl = candidate;
console.log(`[local] Using legacy toolbox fallback URL: ${cachedFallbackUrl}`);
}
const fallbackUrl = cachedFallbackUrl;
if (!fallbackUrl) {
throw new Error("Failed to resolve toolbox fallback URL.");
}
return fallbackUrl;
}
};
}
async function runCommand(
sandbox: Sandbox,
command: string,
label: string,
timeoutSec: number,
): Promise<void> {
const result = await sandbox.process.executeCommand(command, undefined, undefined, timeoutSec);
if (result.exitCode !== 0) {
throw new Error(`${label} failed with exit code ${result.exitCode}\n${result.result}`);
}
}
async function streamCommandLogsUntilExit(params: {
sandbox: Sandbox;
sessionId: string;
commandId: string;
port: number;
previewUrl: string;
shouldStop: () => boolean;
}): Promise<number | undefined> {
const { sandbox, sessionId, commandId, port, previewUrl, shouldStop } = params;
const stdoutCursor: LogCursor = { value: "" };
const stderrCursor: LogCursor = { value: "" };
while (true) {
if (shouldStop()) {
return undefined;
}
const [logs, cmd] = await Promise.all([
sandbox.process.getSessionCommandLogs(sessionId, commandId),
sandbox.process.getSessionCommand(sessionId, commandId),
]);
const nextStdout = extractNewLogChunk(logs.stdout, stdoutCursor);
if (nextStdout) {
process.stdout.write(rewriteLocalhostUrls(nextStdout, port, previewUrl));
}
const nextStderr = extractNewLogChunk(logs.stderr, stderrCursor);
if (nextStderr) {
process.stderr.write(rewriteLocalhostUrls(nextStderr, port, previewUrl));
}
if (cmd.exitCode !== undefined) {
return cmd.exitCode;
}
await sleep(1000);
}
}
async function main(): Promise<void> {
const loadedEnv = await loadConfiguredEnv();
if (loadedEnv.keysLoaded.length > 0) {
console.log(
`[local] Loaded ${loadedEnv.keysLoaded.length} env var(s) from config (.env) files.`,
);
}
const options = parseCliOptions();
const apiKey = requireEnv("DAYTONA_API_KEY");
const apiUrl = process.env.DAYTONA_API_URL;
const effectiveTarget = options.target ?? process.env.DAYTONA_TARGET;
const daytona = new Daytona({
apiKey,
apiUrl,
target: effectiveTarget,
});
patchToolboxProxyUrlFallback(daytona);
const opencodeServerPassword = process.env.OPENCODE_SERVER_PASSWORD;
let sandbox: Sandbox | undefined;
let sessionId: string | undefined;
let commandId: string | undefined;
let stopRequested = false;
let cleaningUp = false;
let cleanupOnSignalStarted = false;
const cleanup = async (): Promise<void> => {
if (cleaningUp) {
return;
}
cleaningUp = true;
if (sandbox && sessionId && commandId) {
try {
await sandbox.process.sendSessionCommandInput(sessionId, commandId, "\u0003");
await sleep(250);
} catch {
// Ignore cleanup-time process signaling failures.
}
}
if (sandbox && sessionId) {
try {
await sandbox.process.deleteSession(sessionId);
} catch {
// Ignore session delete failures during cleanup.
}
}
if (sandbox && options.keepSandbox) {
console.log(`[local] Keeping sandbox: ${sandbox.id}`);
return;
}
if (sandbox) {
console.log(`[local] Deleting sandbox: ${sandbox.id}`);
await sandbox.delete();
console.log("[local] Sandbox deleted.");
}
};
const requestStop = (signal: NodeJS.Signals): void => {
if (stopRequested) {
return;
}
stopRequested = true;
console.log(`\n[local] Received ${signal}. Stopping...`);
if (!cleanupOnSignalStarted) {
cleanupOnSignalStarted = true;
void (async () => {
try {
await cleanup();
process.exit(0);
} catch (error) {
const message = error instanceof Error ? (error.stack ?? error.message) : String(error);
console.error(`[local] Cleanup failed after ${signal}: ${message}`);
process.exit(1);
}
})();
}
};
process.on("SIGINT", () => requestStop("SIGINT"));
process.on("SIGTERM", () => requestStop("SIGTERM"));
try {
console.log("[local] Creating Daytona sandbox...");
const createParams = {
name: options.sandboxName,
language: "typescript",
autoStopInterval: SANDBOX_LIFECYCLE_POLICY.autoStopInterval,
autoArchiveInterval: SANDBOX_LIFECYCLE_POLICY.autoArchiveInterval,
autoDeleteInterval: SANDBOX_LIFECYCLE_POLICY.autoDeleteInterval,
};
sandbox = await daytona.create(createParams, { timeout: options.createTimeoutSec });
console.log(`[local] Sandbox ready: ${sandbox.id}`);
const userHome = (await sandbox.getUserHomeDir()) ?? "/home/daytona";
const opencodeConfigPath = `${userHome}/.config/opencode/opencode.json`;
const opencodeConfigDir = `${userHome}/.config/opencode`;
const preview = await sandbox.getPreviewLink(options.port);
const previewUrlPattern = getPreviewUrlPattern(preview.url, options.port);
const configContents = buildOpencodeConfig(previewUrlPattern);
await runCommand(
sandbox,
`mkdir -p ${shellEscape(opencodeConfigDir)}`,
"Prepare OpenCode config directory",
60,
);
await sandbox.fs.uploadFile(Buffer.from(configContents, "utf8"), opencodeConfigPath);
console.log("[local] Installing latest OpenCode CLI in sandbox...");
await runCommand(
sandbox,
buildInstallOpencodeCommand(),
"Install OpenCode CLI",
options.installTimeoutSec,
);
const resolveOpencodeBin =
"if command -v opencode >/dev/null 2>&1; then command -v opencode; " +
'elif [ -x "$HOME/.bun/bin/opencode" ]; then echo "$HOME/.bun/bin/opencode"; ' +
'elif [ -x "$HOME/.local/bin/opencode" ]; then echo "$HOME/.local/bin/opencode"; ' +
'else echo "opencode binary not found in PATH, ~/.bun/bin, or ~/.local/bin" >&2; exit 127; fi';
sessionId = `opencode-${randomUUID().slice(0, 8)}`;
await sandbox.process.createSession(sessionId);
const launchResponse = await sandbox.process.executeSessionCommand(sessionId, {
command:
(opencodeServerPassword
? `OPENCODE_SERVER_PASSWORD=${shellEscape(opencodeServerPassword)} `
: "") +
'OPENCODE_BIN="$(' +
resolveOpencodeBin +
')"; "$OPENCODE_BIN" web --hostname 0.0.0.0 --port ' +
options.port +
" --print-logs",
runAsync: true,
});
commandId = launchResponse.cmdId;
console.log(`[local] OpenCode remote web UI: ${preview.url}`);
console.log(`[local] Session: ${sessionId}`);
if (!opencodeServerPassword) {
console.log("[local] Warning: OPENCODE_SERVER_PASSWORD is not set (web UI is unsecured).");
}
if (options.openUi) {
await openUi(preview.url);
}
console.log(
`[local] Press Ctrl+C to stop${options.keepSandbox ? " (sandbox will be kept)" : ""}.`,
);
const opencodeExitCode = await streamCommandLogsUntilExit({
sandbox,
sessionId,
commandId,
port: options.port,
previewUrl: preview.url,
shouldStop: () => stopRequested,
});
if (opencodeExitCode !== undefined) {
console.log(`[local] OpenCode process exited with code ${opencodeExitCode}.`);
if (opencodeExitCode !== 0) {
throw new Error(`OpenCode exited with non-zero code: ${opencodeExitCode}`);
}
}
} finally {
await cleanup();
}
}
main().catch((error: unknown) => {
const message = error instanceof Error ? (error.stack ?? error.message) : String(error);
console.error(`[local] Failed: ${message}`);
process.exit(1);
});