-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathmain.ts
More file actions
873 lines (783 loc) · 26.1 KB
/
Copy pathmain.ts
File metadata and controls
873 lines (783 loc) · 26.1 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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
import { Hono, type MiddlewareHandler } from "@hono/hono";
import { logger } from "@hono/hono/logger";
import { parseArgs } from "@std/cli";
import * as colors from "@std/fmt/colors";
import { ensureDir } from "@std/fs";
import { dirname, join } from "@std/path";
import denoJSON from "../deno.json" with { type: "json" };
import {
BLOCKS_FOLDER,
DECO_FOLDER,
ENV_SITE_NAME,
} from "../engine/decofile/constants.ts";
import { genMetadata } from "../engine/decofile/fsFolder.ts";
import { bundleApp } from "../scripts/apps/bundle.lib.ts";
import { delay, throttle } from "../utils/async.ts";
import { createAuth } from "./auth.ts";
import {
createDaemonAPIs,
DECO_ENV_NAME,
DECO_HOST,
getSiteName,
SANDBOX_MODE,
setSiteName,
} from "./daemon.ts";
import { watchFS } from "./fs/api.ts";
import { ensureGit, getGitHubPackageTokens, lockerGitAPI } from "./git.ts";
import { logs } from "./loggings/stream.ts";
import { watchMeta } from "./meta.ts";
import {
activityMonitor,
createIdleHandler,
resetActivity,
} from "./monitor.ts";
import { downloadCache } from "./cache.ts";
import { createAIHandlers } from "./ai/handlers.ts";
import { createSandboxHandlers, type DeployParams } from "./sandbox.ts";
import { register, type TunnelConnection } from "./tunnel.ts";
import {
createWorker,
resetWorkerState,
worker,
type WorkerOptions,
} from "./worker.ts";
import { portPool } from "./workers/portpool.ts";
const parsedArgs = parseArgs(Deno.args, {
string: ["build-cmd"],
});
const runCommand = parsedArgs["_"];
const DECO_APP_NAME = Deno.env.get("DECO_APP_NAME");
export const DENO_DEPLOYMENT_ID: string | undefined = Deno.env.get(
"DENO_DEPLOYMENT_ID",
);
const SOURCE_PATH = Deno.env.get("SOURCE_ASSET_PATH");
const DECO_TRANSIENT_ENV = Deno.env.get("DECO_TRANSIENT_ENV") === "true";
const SHOULD_PERSIST = DENO_DEPLOYMENT_ID && SOURCE_PATH && !DECO_TRANSIENT_ENV;
export const VERBOSE: string | undefined = Deno.env.get("VERBOSE") ||
DENO_DEPLOYMENT_ID;
const DENO_AUTH_TOKENS = "DENO_AUTH_TOKENS";
const UNSTABLE_WORKER_RESPAWN_INTERVAL_MS_ENV_NAME =
"UNSTABLE_WORKER_RESPAWN_INTERVAL_MS";
const UNSTABLE_WORKER_RESPAWN_INTERVAL_MS =
Deno.env.get(UNSTABLE_WORKER_RESPAWN_INTERVAL_MS_ENV_NAME) &&
!Number.isNaN(
parseInt(Deno.env.get(UNSTABLE_WORKER_RESPAWN_INTERVAL_MS_ENV_NAME)!, 10),
)
? parseInt(Deno.env.get(UNSTABLE_WORKER_RESPAWN_INTERVAL_MS_ENV_NAME)!, 10)
: undefined; // 1hour
const HAS_PRIVATE_GITHUB_IMPORT = Deno.env.get("HAS_PRIVATE_GITHUB_IMPORT");
const WORKER_PORT = portPool.get();
const [cmd, ...args] = runCommand as string[];
const [buildCmdStr, ...buildArgs] = parsedArgs["build-cmd"]?.split(" ") ?? [];
const buildCmd = buildCmdStr
? new Deno.Command(buildCmdStr, {
args: buildArgs,
stdout: "inherit",
stderr: "inherit",
})
: null;
const getEnvVar = (envName: string, varName: string) =>
Deno.env.get(envName) ? { [varName]: Deno.env.get(envName) } : {};
type RunCmdFactory = (opt?: Pick<Deno.CommandOptions, "env">) => Deno.Command;
const makeRunCmdFactory = (
runCmd: string,
runArgs: string[],
extraEnv?: Record<string, string>,
): RunCmdFactory =>
(opt?: Pick<Deno.CommandOptions, "env">) =>
new Deno.Command(runCmd === "deno" ? Deno.execPath() : runCmd, {
args: runArgs,
stdout: "piped",
stderr: "piped",
env: {
...extraEnv,
...opt?.env,
PORT: `${WORKER_PORT}`,
...getEnvVar(DENO_AUTH_TOKENS, DENO_AUTH_TOKENS),
...getEnvVar("DENO_DIR_RUN", "DENO_DIR"),
},
});
const createRunCmd: RunCmdFactory | null = cmd
? makeRunCmdFactory(cmd, args)
: null;
let lastUpdateEnvUpdate: number | undefined;
const updateDenoAuthTokenEnv = async () => {
if (
!UNSTABLE_WORKER_RESPAWN_INTERVAL_MS ||
(lastUpdateEnvUpdate && Date.now() < lastUpdateEnvUpdate)
) {
return;
}
lastUpdateEnvUpdate = Date.now() + UNSTABLE_WORKER_RESPAWN_INTERVAL_MS;
const appTokens = await getGitHubPackageTokens();
// TODO: handle if DENO_AUTH_TOKENS is already set
Deno.env.set(
DENO_AUTH_TOKENS,
appTokens.map((token) => `${token}@raw.githubusercontent.com`).join(";"),
);
};
if (SANDBOX_MODE && getSiteName()) {
console.error(
`[sandbox] SANDBOX_MODE=true but ${ENV_SITE_NAME} is already set. These are mutually exclusive.`,
);
Deno.exit(1);
}
if (!SANDBOX_MODE && !getSiteName()) {
console.error(
`site name not found. use ${ENV_SITE_NAME} environment variable to set it, or set SANDBOX_MODE=true.`,
);
Deno.exit(1);
}
if (SANDBOX_MODE) {
console.log(
`[sandbox] Starting in sandbox mode. Use POST /sandbox/deploy to assign a site.`,
);
}
// Surface scheduled-restart configuration so it's easy to rule out as the cause
// of "the daemon keeps restarting" reports.
console.log(
`[daemon] ${UNSTABLE_WORKER_RESPAWN_INTERVAL_MS_ENV_NAME}=${
UNSTABLE_WORKER_RESPAWN_INTERVAL_MS ?? "unset"
}`,
);
globalThis.addEventListener(
"unhandledrejection",
(e: { promise: Promise<unknown>; reason: unknown }) => {
console.log("unhandled rejection at:", e.promise, "reason:", e.reason);
},
);
const createBundler = (appName?: string) => {
const bundler = bundleApp(Deno.cwd());
return async () => {
try {
await bundler({ dir: ".", name: appName ?? "site" });
} catch (error) {
console.error("Error while bundling site app", error);
}
};
};
const persist = async () => {
try {
if (!SHOULD_PERSIST) {
return;
}
const start = performance.now();
const outfilePath = join(
dirname(SOURCE_PATH!),
`${DENO_DEPLOYMENT_ID}.tar`,
);
await ensureDir(dirname(outfilePath));
const tar = new Deno.Command("tar", {
cwd: Deno.cwd(),
args: ["-cf", outfilePath, "--exclude=node_modules", "."],
});
const status = await tar.spawn().status;
console.log(
`[tar]: Tarballing took ${(performance.now() - start).toFixed(0)}ms`,
);
if (!status.success) {
throw new Error("Failed to tarball");
}
} catch (error) {
console.error("Error while persisting", error);
}
};
const bundle = createBundler(DECO_APP_NAME);
const genManifestTS = throttle(async () => {
await Promise.all([bundle(), delay(300)]);
});
const genBlocksJSON = throttle(async () => {
await Promise.all([genMetadata(), delay(300)]);
});
const persistState = throttle(async () => {
await Promise.all([persist(), delay(2 * 60 * 1_000)]);
});
// Watch for changes in filesystem
// TODO: we should be able to completely remove this after in some point in the future
const watch = async (signal?: AbortSignal) => {
if (signal?.aborted) return;
const watcher = Deno.watchFs(Deno.cwd(), { recursive: true });
signal?.addEventListener("abort", () => watcher.close(), { once: true });
for await (const event of watcher) {
if (signal?.aborted) break;
using _ = await lockerGitAPI.lock.rlock();
const skip = event.paths.some(
(path) =>
path.includes(".git") || path.includes("node_modules") ||
path.includes(".agent-home") || path.includes(".claude"),
);
if (skip) {
continue;
}
if (VERBOSE) {
console.log(event.kind, ...event.paths);
}
// TODO: remove genBlocksJSON after we stop using old FS API
const isBlockChanged = event.paths.some((path) =>
path.includes(`${DECO_FOLDER}/${BLOCKS_FOLDER}`)
);
if (isBlockChanged) {
genBlocksJSON();
}
/** We should move this to the new FS api */
const codeCreatedOrDeleted = event.kind !== "modify" &&
event.kind !== "access" &&
event.paths.some(
(path) => /\.tsx?$/.test(path) && !path.includes("manifest.gen.ts"),
);
if (codeCreatedOrDeleted) {
genManifestTS();
}
if (HAS_PRIVATE_GITHUB_IMPORT) {
updateDenoAuthTokenEnv();
}
// TODO: We should be able to remove this after we migrate to ebs
persistState();
}
};
const createDeps = (
signal?: AbortSignal,
opts?: { repoUrl?: string; branch?: string },
): MiddlewareHandler & { ready: Promise<void>; ensureStarted: () => void } => {
let ok: Promise<unknown> | null = null;
let readyResolve: () => void;
let readyReject: (err: unknown) => void;
const ready = new Promise<void>((resolve, reject) => {
readyResolve = resolve;
readyReject = reject;
});
const start = async () => {
const siteName = getSiteName();
if (!siteName) {
throw new Error("Cannot initialize deps: site name not set");
}
let start = performance.now();
try {
await ensureGit({
site: siteName,
repoUrl: opts?.repoUrl,
branch: opts?.branch,
});
readyResolve();
} catch (err) {
readyReject(err);
throw err;
}
logs.push({
level: "info",
message: `${colors.bold("[step 1/4]")}: Git setup took ${
(
performance.now() - start
).toFixed(0)
}ms`,
});
if (SANDBOX_MODE) {
start = performance.now();
await downloadCache(siteName).catch((err) => {
console.warn(`[cache] Failed to download build cache: ${err.message}`);
});
logs.push({
level: "info",
message: `${colors.bold("[step 1.5/4]")}: Cache download took ${
(performance.now() - start).toFixed(0)
}ms`,
});
}
start = performance.now();
await genManifestTS();
logs.push({
level: "info",
message: `${colors.bold("[step 2/4]")}: Manifest generation took ${
(
performance.now() - start
).toFixed(0)
}ms`,
});
start = performance.now();
await genBlocksJSON();
logs.push({
level: "info",
message: `${colors.bold("[step 3/4]")}: Blocks metadata generation took ${
(
performance.now() - start
).toFixed(0)
}ms`,
});
watch(signal).catch(console.error);
watchMeta(signal).catch(console.error);
watchFS(signal).catch(console.error);
logs.push({
level: "info",
message: `${
colors.bold(
"[step 4/4]",
)
}: Started file watcher in background`,
});
};
const ensureStarted = () => {
ok ||= start();
};
const middleware: MiddlewareHandler & {
ready: Promise<void>;
ensureStarted: () => void;
} = Object
.assign(
async (
c: Parameters<MiddlewareHandler>[0],
next: () => Promise<void>,
) => {
try {
ensureStarted();
await ok?.then(next);
} catch (err) {
console.log(err);
c.res = new Response("Error while starting global deps", {
status: 424,
});
}
},
{ ready, ensureStarted },
);
return middleware;
};
// Create a function that returns fresh WorkerOptions with new tokens
const makeWorkerOptionsFactory =
(runCmdFactory: RunCmdFactory, gitReady?: Promise<void>) =>
async (): Promise<WorkerOptions> => {
// Wait for git clone to complete before running the factory.
// This ensures dev.ts existence checks and token refreshes happen
// after the repo is available on disk.
if (gitReady) await gitReady;
if (HAS_PRIVATE_GITHUB_IMPORT) {
await updateDenoAuthTokenEnv();
}
if (UNSTABLE_WORKER_RESPAWN_INTERVAL_MS) {
/* TODO: Implement a better approach handling updating child env vars, preventing multiple child processes and with HMR.
* Also should have the git short live auth token to do git operations like: push/pull/rebase. Now, these git operations are guaranted
* because the short live git token is set once in inicialization and respawning
*/
// Kill process to allow restart with new env settings
setTimeout(() => {
Deno.exit(1);
}, UNSTABLE_WORKER_RESPAWN_INTERVAL_MS);
}
return {
command: runCmdFactory(), // This will create a fresh command with new tokens
port: WORKER_PORT,
persist,
};
};
interface SiteAppOptions {
siteName: string;
runCmdFactory?: RunCmdFactory | null;
repoUrl?: string;
branch?: string;
}
interface SiteAppResult {
app: Hono;
dispose: () => Promise<void>;
/** Resolves when git clone/setup is done (before manifest gen). */
gitReady: Promise<void>;
/** Eagerly trigger deps initialization (git clone, manifest gen, etc.). */
ensureStarted: () => void;
}
/**
* Creates a Hono sub-app with all site-specific middleware:
* idle handler, deps (git, manifests, watchers), activity monitor,
* daemon APIs, and worker proxy.
*
* Returns the app and a dispose function to clean up on undeploy.
*/
const createSiteApp = ({
siteName,
runCmdFactory,
repoUrl,
branch,
}: SiteAppOptions): SiteAppResult => {
const ac = new AbortController();
const siteApp = new Hono();
// idle should run even when branch is not active
// When DECO_ENV_NAME is unset, idle reporting is disabled by createIdleHandler
const envName = DECO_ENV_NAME ?? "";
siteApp.get("/deco/_is_idle", createIdleHandler(siteName, envName));
// Globals are started after healthcheck to ensure k8s does not kill the pod before it is ready
const deps = createDeps(ac.signal, { repoUrl, branch });
siteApp.use(deps);
siteApp.use(activityMonitor);
// These are the APIs that communicate with admin UI
siteApp.use(createDaemonAPIs({ build: buildCmd, site: siteName }));
// Workers are only necessary if there needs to have a preview of the site
if (runCmdFactory) {
siteApp.route(
"",
createWorker(makeWorkerOptionsFactory(runCmdFactory, deps.ready)),
);
}
const dispose = async () => {
// 1. Stop the worker subprocess
try {
const w = await Promise.race([
worker().then((w) => w),
new Promise<null>((r) => setTimeout(() => r(null), 1000)),
]);
if (w) {
await w[Symbol.asyncDispose]();
console.log(`[sandbox] Worker subprocess stopped`);
}
} catch {
// Worker may not have been started
}
// 2. Stop all file watchers (prevents manifest gen / HMR triggers)
ac.abort();
console.log(`[sandbox] Watchers stopped`);
// 3. Clean all files in cwd (the cloned site repo)
const cwd = Deno.cwd();
for await (const entry of Deno.readDir(cwd)) {
const path = join(cwd, entry.name);
await Deno.remove(path, { recursive: true }).catch(() => {});
}
console.log(`[sandbox] Cleaned working directory: ${cwd}`);
};
return {
app: siteApp,
dispose,
gitReady: deps.ready,
ensureStarted: deps.ensureStarted,
};
};
const LOCAL_STORAGE_ENV_NAME = "deco_host_env_name";
const stableEnvironmentName = () => {
const savedEnvironment = localStorage.getItem(LOCAL_STORAGE_ENV_NAME);
if (savedEnvironment) {
return savedEnvironment;
}
const newEnvironment = `${crypto.randomUUID().slice(0, 6)}-localhost`;
localStorage.setItem(LOCAL_STORAGE_ENV_NAME, newEnvironment);
return newEnvironment;
};
const port = Number(Deno.env.get("APP_PORT")) || 8000;
const registerTunnel = async (
siteName: string,
envNameOverride?: string,
): Promise<TunnelConnection | null> => {
const env = envNameOverride ??
(DECO_HOST && !DECO_ENV_NAME ? stableEnvironmentName() : DECO_ENV_NAME);
if (env && !Deno.env.has("DECO_PREVIEW")) {
return await register({
site: siteName,
env,
port: `${port}`,
decoHost: DECO_HOST,
});
}
return null;
};
const app = new Hono();
if (VERBOSE) {
app.use(logger());
}
app.get("/_healthcheck", (c) => {
const timestamp = +(c.req.header("x-hc-retry-timestamp") ?? "0");
const attempt = +(c.req.header("x-hc-retry-attempt") ?? "0");
console.log("healthcheck received", {
timestamp: new Date(timestamp).toISOString(),
attempt,
});
return new Response(denoJSON.version, {
status: 200,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET",
"Access-Control-Allow-Headers": "Content-Type",
},
});
});
// k8s liveness probe
app.get("/deco/_liveness", () => new Response("OK", { status: 200 }));
if (SANDBOX_MODE) {
// Sandbox mode: start without a site, deploy later via POST /sandbox/deploy
let currentSite: SiteAppResult | null = null;
let tunnelConn: TunnelConnection | null = null;
let aiHandlers: ReturnType<typeof createAIHandlers> | null = null;
const sandbox = createSandboxHandlers({
onDeploy: async (
{ repo, site, envName, branch, runCommand, envs, task }: DeployParams,
) => {
// Reset idle timer so the newly claimed sandbox starts fresh
resetActivity();
// Set env var so worker subprocesses inherit the site name
Deno.env.set(ENV_SITE_NAME, site);
// Also update the module-level variable so getSiteName() returns the value
setSiteName(site);
// Use run command from deploy request.
// If no runCommand provided, default to Deno runner only if dev.ts exists.
// This prevents a timeout loop when the sandbox is used for non-Deco repos
// (e.g. markdown files, scripts) that have no dev server to start.
//
// The check is intentionally lazy (inside the factory) so it runs after
// git clone has completed, not before.
const runCmdFactory: RunCmdFactory | null = runCommand?.length
? makeRunCmdFactory(runCommand[0], runCommand.slice(1), envs)
: runCommand !== undefined
? null // explicit empty array = caller opted out of a worker
: createRunCmd
? () => {
// Default: start Deno worker only if dev.ts exists in the cloned repo.
// Checked lazily so it runs after git clone has completed.
// Throws if no dev.ts — caught by watchMeta, no worker started.
try {
Deno.statSync(join(Deno.cwd(), "dev.ts"));
} catch {
throw new Error(
"[sandbox] No dev.ts found — not a Deno/Fresh project, skipping worker",
);
}
return createRunCmd!();
}
: null;
currentSite = createSiteApp({
siteName: site,
runCmdFactory,
repoUrl: repo,
branch,
});
// Always create AI handlers — OAuth can be used when no API key is set
aiHandlers = createAIHandlers({
cwd: Deno.cwd(),
apiKey: Deno.env.get("ANTHROPIC_API_KEY") ??
envs?.ANTHROPIC_API_KEY,
githubToken: Deno.env.get("GITHUB_TOKEN"),
extraEnv: envs,
proxyUrl: envs?.ANTHROPIC_PROXY_URL,
proxyToken: envs?.ANTHROPIC_PROXY_TOKEN,
});
const tunnel = await registerTunnel(site, envName).catch((err) => {
console.error("Tunnel registration failed:", err);
return null;
});
tunnelConn = tunnel;
// Auto-create an AI task if task field was provided in deploy request
// Only auto-start prompt/issue tasks if we have an API key (OAuth can't be auto-started)
if (task && aiHandlers && (task.issue || task.prompt)) {
const hasApiKey = Boolean(Deno.env.get("ANTHROPIC_API_KEY")) ||
Boolean(envs?.ANTHROPIC_API_KEY) ||
Boolean(envs?.ANTHROPIC_PROXY_URL);
if (hasApiKey) {
const handlers = aiHandlers;
// Eagerly trigger deps init (git clone, etc.) so the task doesn't wait
// for the first HTTP request to arrive
currentSite.ensureStarted();
// Wait for git clone to finish before starting the AI task,
// since the task needs a valid repo (git rev-parse HEAD, etc.)
currentSite.gitReady.then(async () => {
const ct = await handlers.createTask({
issue: task.issue,
prompt: task.prompt,
shouldCommitChanges: task.shouldCommitChanges,
});
console.log(
`[sandbox] Auto-started AI task ${ct.taskId}${
task.issue ? ` for issue: ${task.issue}` : ""
}`,
);
}).catch((err) => {
console.error(`[sandbox] Auto-start AI task failed:`, err);
});
} else {
console.warn(
`[sandbox] Skipping auto-start: no ANTHROPIC_API_KEY, user needs OAuth first`,
);
}
}
return { domain: tunnel?.domain };
},
onUndeploy: async () => {
// Dispose AI handlers first (kills running tasks)
if (aiHandlers) {
await aiHandlers.dispose();
aiHandlers = null;
console.log(`[sandbox] AI handlers disposed`);
}
if (currentSite) {
await currentSite.dispose();
currentSite = null;
}
if (tunnelConn) {
tunnelConn.close();
tunnelConn = null;
console.log(`[sandbox] Tunnel closed`);
}
// Reset worker state so a subsequent deploy starts fresh
// (workerInitFailed persists across deploys otherwise)
resetWorkerState();
Deno.env.delete(ENV_SITE_NAME);
},
});
app.get("/sandbox/status", sandbox.status);
app.post("/sandbox/deploy", sandbox.deploy);
app.delete("/sandbox/deploy", sandbox.undeploy);
// AI task endpoints (auth-protected, proxied to AI sub-app)
const aiAuth: MiddlewareHandler = async (c, next) => {
const site = getSiteName();
if (!site) {
return c.json({ error: "Not deployed" }, 503);
}
if (!aiHandlers) {
return c.json({ error: "AI integration not available" }, 503);
}
await createAuth({ site })(c, next);
};
for (const pattern of ["/sandbox/tasks", "/sandbox/tasks/*"] as const) {
app.use(pattern, aiAuth);
}
// WebSocket upgrade must be handled directly (not proxied through sub-app)
// because Deno.upgradeWebSocket requires the original server request object.
app.get("/sandbox/tasks/:taskId/ws", (c) => {
if (!aiHandlers) {
return c.json({ error: "Not available" }, 503);
}
const task = aiHandlers.getTask(c.req.param("taskId"));
if (!task) {
return c.json({ error: "Task not found" }, 404);
}
const session = task.session;
if (!session) {
return c.json({ error: "Task has no active session" }, 400);
}
const { socket, response } = Deno.upgradeWebSocket(c.req.raw);
let unsubData: (() => void) | undefined;
let unsubExit: (() => void) | undefined;
socket.onopen = () => {
if (session.status === "exited") {
// Process already finished — replay the full buffer so the client
// can see the output (there's no process to trigger a redraw).
for (const line of session.outputBuffer) {
socket.send(line);
}
socket.send(JSON.stringify({ type: "exit", code: session.exitCode }));
setTimeout(() => {
if (socket.readyState === WebSocket.OPEN) {
socket.close();
}
}, 500);
return;
}
// For running sessions: do NOT replay the output buffer.
// The buffer contains historical screen draws at potentially different
// terminal sizes. Replaying them garbles the TUI (cursor positions,
// partial redraws, etc.). Instead, subscribe to live data only.
// The client sends its dimensions on connect, which triggers a PTY
// resize → Claude Code redraws the current screen cleanly.
unsubData = session.onData((data) => {
if (socket.readyState === WebSocket.OPEN) {
socket.send(data);
}
});
unsubExit = session.onExit((code) => {
if (socket.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify({ type: "exit", code }));
setTimeout(() => {
if (socket.readyState === WebSocket.OPEN) {
socket.close();
}
}, 500);
}
});
};
// Debounce resize on server side to prevent Claude Code redraw storms.
// The first resize is applied immediately (client sends dimensions on
// connect, and we need a fast redraw since we don't replay the buffer).
let resizeTimer: ReturnType<typeof setTimeout> | undefined;
let firstResize = true;
socket.onmessage = (event) => {
try {
const msg = JSON.parse(event.data as string);
if (msg.type === "input" && typeof msg.data === "string") {
session.write(msg.data);
} else if (
msg.type === "resize" && typeof msg.cols === "number" &&
typeof msg.rows === "number"
) {
if (firstResize) {
firstResize = false;
session.resize(msg.cols, msg.rows);
} else {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(() => {
session.resize(msg.cols, msg.rows);
}, 150);
}
}
} catch {
// Ignore malformed messages
}
};
socket.onclose = () => {
clearTimeout(resizeTimer);
unsubData?.();
unsubExit?.();
};
return response;
});
// All other /sandbox/tasks routes → proxy to AI sub-app
for (
const pattern of ["/sandbox/tasks", "/sandbox/tasks/*"] as const
) {
app.all(pattern, (c) => {
if (!aiHandlers) {
return c.json({ error: "Not available" }, 503);
}
const url = new URL(c.req.url);
url.pathname = url.pathname.replace(/^\/sandbox\/tasks/, "") || "/";
const rewritten = new Request(url.toString(), c.req.raw);
return aiHandlers.app.fetch(rewritten);
});
}
// Delegate all other requests to the site app once deployed, or return 503
app.all("*", (c) => {
if (!currentSite) {
return c.json(
{
error:
"Sandbox mode: not deployed yet. POST /sandbox/deploy to assign a site.",
},
503,
);
}
return currentSite.app.fetch(c.req.raw);
});
} else {
// Normal mode: site is known at startup
const siteName = getSiteName();
if (!siteName) {
throw new Error("Site name is required");
}
const { app: siteAppRoutes } = createSiteApp({
siteName,
runCmdFactory: createRunCmd,
});
app.route("", siteAppRoutes);
}
Deno.serve(
{
port,
onListen: async (addr) => {
try {
const siteName = !SANDBOX_MODE ? getSiteName() : undefined;
const tunnel = siteName ? await registerTunnel(siteName) : null;
if (!tunnel) {
const prefix = SANDBOX_MODE ? "[sandbox] " : "";
console.log(
colors.green(
`${prefix}Server running on http://${addr.hostname}:${addr.port}`,
),
);
}
} catch (err) {
console.log(err);
}
},
},
app.fetch,
);