Something went wrong. Try again.
This repository has no description
Something went wrong. Try again.
TypeScript
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475import { getSandbox, Sandbox as NativeSandbox } from "@cloudflare/sandbox";import { SHELL_MAX_MS } from "../shared/shell";import type { Env } from "./personal-agent";
/** One-use execution boundary in the native container's own DO lifetime. */export class Sandbox extends NativeSandbox<Env> { private revoked = false; private claimed = false; private launching = false; private deadline?: ReturnType<typeof setTimeout>;
async execTemporary(command: string, expiresAt: number, id: string) { if (!this.ctx.id.equals(this.env.Sandbox.idFromName(id))) throw new Error("Shell identity mismatch"); if ( !Number.isFinite(expiresAt) || expiresAt <= Date.now() || expiresAt > Date.now() + SHELL_MAX_MS ) throw new Error("Shell lifetime expired"); if (this.claimed) throw new Error("Shell workspace already used"); this.claimed = true; // Native destroy removes container files, not this application-owned key. // A delayed RPC cannot relaunch a container whose lease was already closed. if (this.revoked || (await this.ctx.storage.get("flarebot:invocation"))) throw new Error("Shell workspace already used"); await this.ctx.storage.put("flarebot:invocation", "started"); if (this.revoked) throw new Error("Shell workspace closed"); this.deadline = setTimeout( () => { this.ctx.waitUntil(this.closeTemporary().catch(() => {})); }, Math.max(0, expiresAt - Date.now()), ); this.launching = true; const launch = (async () => { try { const stream = await getSandbox(this.env.Sandbox, id, { enableDefaultSession: false, }).execStream(command, { cwd: "/workspace", timeout: Math.max(1, expiresAt - Date.now()), }); this.launching = false; if (this.revoked || Date.now() >= expiresAt) { await stream.cancel().catch(() => {}); await this.closeTemporary(); throw new Error("Shell workspace closed"); } return stream; } catch { this.launching = false; await this.closeTemporary(); throw new Error("Shell execution unavailable"); } })(); this.ctx.waitUntil( launch.then( () => {}, () => {}, ), ); return launch; }
async closeTemporary() { this.revoked = true; clearTimeout(this.deadline ?? null); await this.ctx.storage.put("flarebot:invocation", "closed"); const launchPending = this.launching; await super.destroy(); return !launchPending && !this.launching; }}