forked from vercel-labs/just-bash
-
Notifications
You must be signed in to change notification settings - Fork 0
feat: route all commands through Vercel Sandbox #7
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
sweetmantech
wants to merge
3
commits into
main
Choose a base branch
from
sweetmantech/myc-4221-bash-all-commands-trigger-sandbox-no-split-logic-for-ls-or
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| import { Sandbox } from "@vercel/sandbox"; | ||
|
|
||
| /** | ||
| * Create a Vercel Sandbox and seed it with files. | ||
| */ | ||
| export async function createSandbox( | ||
| files: Array<{ path: string; content: Buffer }> | ||
| ): Promise<Sandbox> { | ||
| const sandbox = await Sandbox.create(); | ||
| if (files.length > 0) { | ||
| await sandbox.writeFiles(files); | ||
| } | ||
| return sandbox; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| import { readdirSync, readFileSync } from "fs"; | ||
| import { join, relative } from "path"; | ||
|
|
||
| /** | ||
| * Recursively read all files from a directory, returning them in the format | ||
| * expected by Sandbox.writeFiles(). | ||
| */ | ||
| export function readSourceFiles( | ||
| dir: string, | ||
| destDir: string, | ||
| baseDir?: string | ||
| ): Array<{ path: string; content: Buffer }> { | ||
| const base = baseDir ?? dir; | ||
| const files: Array<{ path: string; content: Buffer }> = []; | ||
|
|
||
| for (const entry of readdirSync(dir, { withFileTypes: true })) { | ||
| const fullPath = join(dir, entry.name); | ||
| if (entry.isDirectory()) { | ||
| if (entry.name === "node_modules" || entry.name === ".git") continue; | ||
| files.push(...readSourceFiles(fullPath, destDir, base)); | ||
| } else { | ||
| const relPath = relative(base, fullPath); | ||
| files.push({ | ||
| path: join(destDir, relPath), | ||
| content: readFileSync(fullPath), | ||
| }); | ||
| } | ||
| } | ||
|
|
||
| return files; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,116 @@ | ||
| import { Sandbox } from "@vercel/sandbox"; | ||
| import { createSandbox } from "../_lib/createSandbox"; | ||
|
|
||
| const SANDBOX_CWD = "/home/user"; | ||
|
|
||
| async function fetchSourceFiles(): Promise< | ||
| Array<{ path: string; content: Buffer }> | ||
| > { | ||
| const baseUrl = process.env.VERCEL_URL | ||
| ? `https://${process.env.VERCEL_URL}` | ||
| : "http://localhost:3000"; | ||
| const res = await fetch(`${baseUrl}/api/fs`); | ||
| if (!res.ok) return []; | ||
| const filesMap: Record<string, string> = await res.json(); | ||
| return Object.entries(filesMap).map(([path, content]) => ({ | ||
| path: `${SANDBOX_CWD}/${path}`, | ||
| content: Buffer.from(content), | ||
| })); | ||
| } | ||
|
|
||
| async function createAndSeedSandbox(): Promise<Sandbox> { | ||
| let files: Array<{ path: string; content: Buffer }> = []; | ||
| try { | ||
| files = await fetchSourceFiles(); | ||
| } catch { | ||
| // File seeding is best-effort | ||
| } | ||
|
|
||
| const sandbox = await createSandbox(files); | ||
|
|
||
| // Create convenience copies of top-level demo files | ||
| try { | ||
| await sandbox.runCommand({ | ||
| cmd: "bash", | ||
| args: [ | ||
| "-c", | ||
| [ | ||
| `mkdir -p ${SANDBOX_CWD}/dirs/are/fun/author`, | ||
| `cp ${SANDBOX_CWD}/just-bash/README.md ${SANDBOX_CWD}/README.md 2>/dev/null || true`, | ||
| `cp ${SANDBOX_CWD}/just-bash/LICENSE ${SANDBOX_CWD}/LICENSE 2>/dev/null || true`, | ||
| `cp ${SANDBOX_CWD}/just-bash/package.json ${SANDBOX_CWD}/package.json 2>/dev/null || true`, | ||
| `echo 'https://x.com/cramforce' > ${SANDBOX_CWD}/dirs/are/fun/author/info.txt`, | ||
| ].join(" && "), | ||
| ], | ||
| cwd: SANDBOX_CWD, | ||
| }); | ||
| } catch { | ||
| // Best-effort file setup | ||
| } | ||
|
|
||
| return sandbox; | ||
| } | ||
|
|
||
| export async function POST(req: Request) { | ||
| try { | ||
| const authHeader = req.headers.get("Authorization"); | ||
| if (!authHeader?.startsWith("Bearer ")) { | ||
| return Response.json({ error: "Unauthorized" }, { status: 401 }); | ||
| } | ||
|
|
||
| const { command, sandboxId } = await req.json(); | ||
|
|
||
| if (!command || typeof command !== "string") { | ||
| return Response.json({ error: "Command is required" }, { status: 400 }); | ||
| } | ||
|
|
||
| let sandbox: Sandbox; | ||
| let activeSandboxId: string; | ||
|
|
||
| if (sandboxId) { | ||
| try { | ||
| sandbox = await Sandbox.get({ sandboxId }); | ||
| activeSandboxId = sandboxId; | ||
| } catch { | ||
| sandbox = await createAndSeedSandbox(); | ||
| activeSandboxId = sandbox.sandboxId; | ||
| } | ||
| } else { | ||
| sandbox = await createAndSeedSandbox(); | ||
| activeSandboxId = sandbox.sandboxId; | ||
| } | ||
|
|
||
| try { | ||
| const result = await sandbox.runCommand({ | ||
| cmd: "bash", | ||
| args: ["-c", command], | ||
| cwd: SANDBOX_CWD, | ||
| }); | ||
|
|
||
| const stdout = await result.stdout(); | ||
| const stderr = await result.stderr(); | ||
|
|
||
| return Response.json({ | ||
| stdout, | ||
| stderr, | ||
| exitCode: result.exitCode, | ||
| sandboxId: activeSandboxId, | ||
| }); | ||
| } catch (error) { | ||
| return Response.json({ | ||
| stdout: "", | ||
| stderr: error instanceof Error ? error.message : "Execution failed", | ||
| exitCode: 1, | ||
| sandboxId: activeSandboxId, | ||
| }); | ||
| } | ||
| } catch (error) { | ||
| console.error("[/api/exec] Error:", error); | ||
| return Response.json( | ||
| { | ||
| error: error instanceof Error ? error.message : "Internal server error", | ||
| }, | ||
| { status: 500 }, | ||
| ); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
🌐 Web query:
@vercel/sandbox runCommand timeout option documentation💡 Result:
@vercel/sandboxdoes not document atimeoutoption onsandbox.runCommand(...). TherunCommandAPI supports cancellation via anAbortSignal(opts.signal/params.signal), but no per-command timeout field is listed. [1]Timeout is configured at the sandbox level instead:
timeoutwhen callingSandbox.create({ timeout: ... })(milliseconds). [1][2]sandbox.extendTimeout(...). [1][2]Example (per-command “timeout” via
AbortController):Sources: [1] [2]
🏁 Script executed:
Repository: recoupable/bash
Length of output: 80
🏁 Script executed:
Repository: recoupable/bash
Length of output: 1778
🏁 Script executed:
cat -n app/api/exec/route.ts | head -90Repository: recoupable/bash
Length of output: 3389
🏁 Script executed:
Repository: recoupable/bash
Length of output: 1434
Add per-command timeout using
AbortSignalto prevent hanging commands.Currently,
sandbox.runCommand()at line 90 has no timeout protection. While the sandbox has a default 5-minute lifetime, individual commands can hang indefinitely within that window (e.g.,catwith no file,sleep 999999, infinite loops). The@vercel/sandboxSDK supports cancellation viaAbortSignal—useAbortControllerto implement a per-command timeout:Example fix
🤖 Prompt for AI Agents