mirror of
https://github.com/harivansh-afk/sandbox-agent.git
synced 2026-04-19 12:04:12 +00:00
wip
This commit is contained in:
parent
34d4f3693e
commit
29b159ca20
28 changed files with 2138 additions and 395 deletions
28
examples/daytona/daytona.test.ts
Normal file
28
examples/daytona/daytona.test.ts
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
import { describe, it, expect } from "vitest";
|
||||
import { buildHeaders } from "../shared/sandbox-agent-client.ts";
|
||||
import { setupDaytonaSandboxAgent } from "./daytona.ts";
|
||||
|
||||
const shouldRun = Boolean(process.env.DAYTONA_API_KEY);
|
||||
const timeoutMs = Number.parseInt(process.env.SANDBOX_TEST_TIMEOUT_MS || "", 10) || 300_000;
|
||||
|
||||
const testFn = shouldRun ? it : it.skip;
|
||||
|
||||
describe("daytona example", () => {
|
||||
testFn(
|
||||
"starts sandbox-agent and responds to /v1/health",
|
||||
async () => {
|
||||
const { baseUrl, token, extraHeaders, cleanup } = await setupDaytonaSandboxAgent();
|
||||
try {
|
||||
const response = await fetch(`${baseUrl}/v1/health`, {
|
||||
headers: buildHeaders({ token, extraHeaders }),
|
||||
});
|
||||
expect(response.ok).toBe(true);
|
||||
const data = await response.json();
|
||||
expect(data.status).toBe("ok");
|
||||
} finally {
|
||||
await cleanup();
|
||||
}
|
||||
},
|
||||
timeoutMs
|
||||
);
|
||||
});
|
||||
82
examples/daytona/daytona.ts
Normal file
82
examples/daytona/daytona.ts
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
import { Daytona } from "@daytonaio/sdk";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import {
|
||||
ensureUrl,
|
||||
runPrompt,
|
||||
waitForHealth,
|
||||
} from "../shared/sandbox-agent-client.ts";
|
||||
|
||||
const INSTALL_SCRIPT = "curl -fsSL https://releases.rivet.dev/sandbox-agent/latest/install.sh | sh";
|
||||
const DEFAULT_PORT = 3000;
|
||||
|
||||
export async function setupDaytonaSandboxAgent(): Promise<{
|
||||
baseUrl: string;
|
||||
token: string;
|
||||
extraHeaders: Record<string, string>;
|
||||
cleanup: () => Promise<void>;
|
||||
}> {
|
||||
const token = process.env.SANDBOX_TOKEN || "";
|
||||
const port = Number.parseInt(process.env.SANDBOX_PORT || "", 10) || DEFAULT_PORT;
|
||||
const language = process.env.DAYTONA_LANGUAGE || "typescript";
|
||||
|
||||
const daytona = new Daytona();
|
||||
const sandbox = await daytona.create({
|
||||
language,
|
||||
});
|
||||
|
||||
await sandbox.process.executeCommand(`bash -lc "${INSTALL_SCRIPT}"`);
|
||||
|
||||
const tokenFlag = token ? "--token $SANDBOX_TOKEN" : "--no-token";
|
||||
const serverCommand = `nohup sandbox-agent server ${tokenFlag} --host 0.0.0.0 --port ${port} >/tmp/sandbox-agent.log 2>&1 &`;
|
||||
await sandbox.process.executeCommand(`bash -lc "${serverCommand}"`);
|
||||
|
||||
const preview = await sandbox.getPreviewLink(port);
|
||||
const extraHeaders: Record<string, string> = {};
|
||||
if (preview.token) {
|
||||
extraHeaders["x-daytona-preview-token"] = preview.token;
|
||||
}
|
||||
extraHeaders["x-daytona-skip-preview-warning"] = "true";
|
||||
|
||||
const baseUrl = ensureUrl(preview.url);
|
||||
await waitForHealth({ baseUrl, token, extraHeaders });
|
||||
|
||||
const cleanup = async () => {
|
||||
try {
|
||||
await sandbox.delete(60);
|
||||
} catch {
|
||||
// ignore cleanup errors
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
baseUrl,
|
||||
token,
|
||||
extraHeaders,
|
||||
cleanup,
|
||||
};
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const { baseUrl, token, extraHeaders, cleanup } = await setupDaytonaSandboxAgent();
|
||||
|
||||
const exitHandler = async () => {
|
||||
await cleanup();
|
||||
process.exit(0);
|
||||
};
|
||||
|
||||
process.on("SIGINT", () => {
|
||||
void exitHandler();
|
||||
});
|
||||
process.on("SIGTERM", () => {
|
||||
void exitHandler();
|
||||
});
|
||||
|
||||
await runPrompt({ baseUrl, token, extraHeaders });
|
||||
}
|
||||
|
||||
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
||||
main().catch((error) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
28
examples/docker/docker.test.ts
Normal file
28
examples/docker/docker.test.ts
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
import { describe, it, expect } from "vitest";
|
||||
import { buildHeaders } from "../shared/sandbox-agent-client.ts";
|
||||
import { setupDockerSandboxAgent } from "./docker.ts";
|
||||
|
||||
const shouldRun = process.env.RUN_DOCKER_EXAMPLES === "1";
|
||||
const timeoutMs = Number.parseInt(process.env.SANDBOX_TEST_TIMEOUT_MS || "", 10) || 300_000;
|
||||
|
||||
const testFn = shouldRun ? it : it.skip;
|
||||
|
||||
describe("docker example", () => {
|
||||
testFn(
|
||||
"starts sandbox-agent and responds to /v1/health",
|
||||
async () => {
|
||||
const { baseUrl, token, cleanup } = await setupDockerSandboxAgent();
|
||||
try {
|
||||
const response = await fetch(`${baseUrl}/v1/health`, {
|
||||
headers: buildHeaders({ token }),
|
||||
});
|
||||
expect(response.ok).toBe(true);
|
||||
const data = await response.json();
|
||||
expect(data.status).toBe("ok");
|
||||
} finally {
|
||||
await cleanup();
|
||||
}
|
||||
},
|
||||
timeoutMs
|
||||
);
|
||||
});
|
||||
130
examples/docker/docker.ts
Normal file
130
examples/docker/docker.ts
Normal file
|
|
@ -0,0 +1,130 @@
|
|||
import Docker from "dockerode";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import {
|
||||
ensureUrl,
|
||||
runPrompt,
|
||||
waitForHealth,
|
||||
} from "../shared/sandbox-agent-client.ts";
|
||||
|
||||
const INSTALL_SCRIPT = "curl -fsSL https://releases.rivet.dev/sandbox-agent/latest/install.sh | sh";
|
||||
const DEFAULT_IMAGE = "debian:bookworm-slim";
|
||||
const DEFAULT_PORT = 2468;
|
||||
|
||||
async function pullImage(docker: Docker, image: string): Promise<void> {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
docker.pull(image, (error, stream) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
docker.modem.followProgress(stream, (progressError) => {
|
||||
if (progressError) {
|
||||
reject(progressError);
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function ensureImage(docker: Docker, image: string): Promise<void> {
|
||||
try {
|
||||
await docker.getImage(image).inspect();
|
||||
} catch {
|
||||
await pullImage(docker, image);
|
||||
}
|
||||
}
|
||||
|
||||
export async function setupDockerSandboxAgent(): Promise<{
|
||||
baseUrl: string;
|
||||
token: string;
|
||||
cleanup: () => Promise<void>;
|
||||
}> {
|
||||
const token = process.env.SANDBOX_TOKEN || "";
|
||||
const port = Number.parseInt(process.env.SANDBOX_PORT || "", 10) || DEFAULT_PORT;
|
||||
const hostPort = Number.parseInt(process.env.SANDBOX_HOST_PORT || "", 10) || port;
|
||||
const image = process.env.DOCKER_IMAGE || DEFAULT_IMAGE;
|
||||
const containerName = process.env.DOCKER_CONTAINER_NAME;
|
||||
const socketPath = process.env.DOCKER_SOCKET || "/var/run/docker.sock";
|
||||
|
||||
const docker = new Docker({ socketPath });
|
||||
await ensureImage(docker, image);
|
||||
|
||||
const tokenFlag = token ? "--token $SANDBOX_TOKEN" : "--no-token";
|
||||
const command = [
|
||||
"bash",
|
||||
"-lc",
|
||||
[
|
||||
"apt-get update",
|
||||
"apt-get install -y curl ca-certificates",
|
||||
INSTALL_SCRIPT,
|
||||
`sandbox-agent server ${tokenFlag} --host 0.0.0.0 --port ${port}`,
|
||||
].join(" && "),
|
||||
];
|
||||
|
||||
const container = await docker.createContainer({
|
||||
Image: image,
|
||||
Cmd: command,
|
||||
Env: token ? [`SANDBOX_TOKEN=${token}`] : [],
|
||||
ExposedPorts: {
|
||||
[`${port}/tcp`]: {},
|
||||
},
|
||||
HostConfig: {
|
||||
AutoRemove: true,
|
||||
PortBindings: {
|
||||
[`${port}/tcp`]: [{ HostPort: `${hostPort}` }],
|
||||
},
|
||||
},
|
||||
...(containerName ? { name: containerName } : {}),
|
||||
});
|
||||
|
||||
await container.start();
|
||||
|
||||
const baseUrl = ensureUrl(`http://127.0.0.1:${hostPort}`);
|
||||
await waitForHealth({ baseUrl, token });
|
||||
|
||||
const cleanup = async () => {
|
||||
try {
|
||||
await container.stop({ t: 5 });
|
||||
} catch {
|
||||
// ignore stop errors
|
||||
}
|
||||
try {
|
||||
await container.remove({ force: true });
|
||||
} catch {
|
||||
// ignore remove errors
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
baseUrl,
|
||||
token,
|
||||
cleanup,
|
||||
};
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const { baseUrl, token, cleanup } = await setupDockerSandboxAgent();
|
||||
|
||||
const exitHandler = async () => {
|
||||
await cleanup();
|
||||
process.exit(0);
|
||||
};
|
||||
|
||||
process.on("SIGINT", () => {
|
||||
void exitHandler();
|
||||
});
|
||||
process.on("SIGTERM", () => {
|
||||
void exitHandler();
|
||||
});
|
||||
|
||||
await runPrompt({ baseUrl, token });
|
||||
}
|
||||
|
||||
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
||||
main().catch((error) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
28
examples/e2b/e2b.test.ts
Normal file
28
examples/e2b/e2b.test.ts
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
import { describe, it, expect } from "vitest";
|
||||
import { buildHeaders } from "../shared/sandbox-agent-client.ts";
|
||||
import { setupE2BSandboxAgent } from "./e2b.ts";
|
||||
|
||||
const shouldRun = Boolean(process.env.E2B_API_KEY);
|
||||
const timeoutMs = Number.parseInt(process.env.SANDBOX_TEST_TIMEOUT_MS || "", 10) || 300_000;
|
||||
|
||||
const testFn = shouldRun ? it : it.skip;
|
||||
|
||||
describe("e2b example", () => {
|
||||
testFn(
|
||||
"starts sandbox-agent and responds to /v1/health",
|
||||
async () => {
|
||||
const { baseUrl, token, cleanup } = await setupE2BSandboxAgent();
|
||||
try {
|
||||
const response = await fetch(`${baseUrl}/v1/health`, {
|
||||
headers: buildHeaders({ token }),
|
||||
});
|
||||
expect(response.ok).toBe(true);
|
||||
const data = await response.json();
|
||||
expect(data.status).toBe("ok");
|
||||
} finally {
|
||||
await cleanup();
|
||||
}
|
||||
},
|
||||
timeoutMs
|
||||
);
|
||||
});
|
||||
87
examples/e2b/e2b.ts
Normal file
87
examples/e2b/e2b.ts
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
import { Sandbox } from "@e2b/code-interpreter";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import {
|
||||
ensureUrl,
|
||||
runPrompt,
|
||||
waitForHealth,
|
||||
} from "../shared/sandbox-agent-client.ts";
|
||||
|
||||
const INSTALL_SCRIPT = "curl -fsSL https://releases.rivet.dev/sandbox-agent/latest/install.sh | sh";
|
||||
const DEFAULT_PORT = 2468;
|
||||
|
||||
type CommandRunner = (command: string, options?: Record<string, unknown>) => Promise<unknown>;
|
||||
|
||||
function resolveCommandRunner(sandbox: Sandbox): CommandRunner {
|
||||
if (sandbox.commands?.run) {
|
||||
return sandbox.commands.run.bind(sandbox.commands);
|
||||
}
|
||||
if (sandbox.commands?.exec) {
|
||||
return sandbox.commands.exec.bind(sandbox.commands);
|
||||
}
|
||||
throw new Error("E2B SDK does not expose commands.run or commands.exec");
|
||||
}
|
||||
|
||||
export async function setupE2BSandboxAgent(): Promise<{
|
||||
baseUrl: string;
|
||||
token: string;
|
||||
cleanup: () => Promise<void>;
|
||||
}> {
|
||||
const token = process.env.SANDBOX_TOKEN || "";
|
||||
const port = Number.parseInt(process.env.SANDBOX_PORT || "", 10) || DEFAULT_PORT;
|
||||
|
||||
const sandbox = await Sandbox.create({
|
||||
allowInternetAccess: true,
|
||||
envs: token ? { SANDBOX_TOKEN: token } : undefined,
|
||||
});
|
||||
|
||||
const runCommand = resolveCommandRunner(sandbox);
|
||||
|
||||
await runCommand(`bash -lc "${INSTALL_SCRIPT}"`);
|
||||
const tokenFlag = token ? "--token $SANDBOX_TOKEN" : "--no-token";
|
||||
await runCommand(`bash -lc "sandbox-agent server ${tokenFlag} --host 0.0.0.0 --port ${port}"`, {
|
||||
background: true,
|
||||
envs: token ? { SANDBOX_TOKEN: token } : undefined,
|
||||
});
|
||||
|
||||
const baseUrl = ensureUrl(sandbox.getHost(port));
|
||||
await waitForHealth({ baseUrl, token });
|
||||
|
||||
const cleanup = async () => {
|
||||
try {
|
||||
await sandbox.kill();
|
||||
} catch {
|
||||
// ignore cleanup errors
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
baseUrl,
|
||||
token,
|
||||
cleanup,
|
||||
};
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const { baseUrl, token, cleanup } = await setupE2BSandboxAgent();
|
||||
|
||||
const exitHandler = async () => {
|
||||
await cleanup();
|
||||
process.exit(0);
|
||||
};
|
||||
|
||||
process.on("SIGINT", () => {
|
||||
void exitHandler();
|
||||
});
|
||||
process.on("SIGTERM", () => {
|
||||
void exitHandler();
|
||||
});
|
||||
|
||||
await runPrompt({ baseUrl, token });
|
||||
}
|
||||
|
||||
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
||||
main().catch((error) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
25
examples/package.json
Normal file
25
examples/package.json
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
{
|
||||
"name": "sandbox-agent-examples",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"start:docker": "tsx docker/docker.ts",
|
||||
"start:e2b": "tsx e2b/e2b.ts",
|
||||
"start:daytona": "tsx daytona/daytona.ts",
|
||||
"start:vercel": "tsx vercel/vercel-sandbox.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@daytonaio/sdk": "latest",
|
||||
"@e2b/code-interpreter": "latest",
|
||||
"@vercel/sandbox": "latest",
|
||||
"dockerode": "latest"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "latest",
|
||||
"tsx": "latest",
|
||||
"typescript": "latest",
|
||||
"vitest": "latest"
|
||||
}
|
||||
}
|
||||
288
examples/shared/sandbox-agent-client.ts
Normal file
288
examples/shared/sandbox-agent-client.ts
Normal file
|
|
@ -0,0 +1,288 @@
|
|||
import { createInterface } from "node:readline";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { setTimeout as delay } from "node:timers/promises";
|
||||
|
||||
export function normalizeBaseUrl(baseUrl: string): string {
|
||||
return baseUrl.replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
export function ensureUrl(rawUrl: string): string {
|
||||
if (!rawUrl) {
|
||||
throw new Error("Missing sandbox URL");
|
||||
}
|
||||
if (rawUrl.startsWith("http://") || rawUrl.startsWith("https://")) {
|
||||
return rawUrl;
|
||||
}
|
||||
return `https://${rawUrl}`;
|
||||
}
|
||||
|
||||
type HeaderOptions = {
|
||||
token?: string;
|
||||
extraHeaders?: Record<string, string>;
|
||||
contentType?: boolean;
|
||||
};
|
||||
|
||||
export function buildHeaders({ token, extraHeaders, contentType = false }: HeaderOptions): HeadersInit {
|
||||
const headers: Record<string, string> = {
|
||||
...(extraHeaders || {}),
|
||||
};
|
||||
if (token) {
|
||||
headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
if (contentType) {
|
||||
headers["Content-Type"] = "application/json";
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
async function fetchJson(
|
||||
url: string,
|
||||
{
|
||||
token,
|
||||
extraHeaders,
|
||||
method = "GET",
|
||||
body,
|
||||
}: {
|
||||
token?: string;
|
||||
extraHeaders?: Record<string, string>;
|
||||
method?: string;
|
||||
body?: unknown;
|
||||
} = {}
|
||||
): Promise<any> {
|
||||
const headers = buildHeaders({
|
||||
token,
|
||||
extraHeaders,
|
||||
contentType: body !== undefined,
|
||||
});
|
||||
const response = await fetch(url, {
|
||||
method,
|
||||
headers,
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
});
|
||||
const text = await response.text();
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status} ${response.statusText}: ${text}`);
|
||||
}
|
||||
return text ? JSON.parse(text) : {};
|
||||
}
|
||||
|
||||
export async function waitForHealth({
|
||||
baseUrl,
|
||||
token,
|
||||
extraHeaders,
|
||||
timeoutMs = 120_000,
|
||||
}: {
|
||||
baseUrl: string;
|
||||
token?: string;
|
||||
extraHeaders?: Record<string, string>;
|
||||
timeoutMs?: number;
|
||||
}): Promise<void> {
|
||||
const normalized = normalizeBaseUrl(baseUrl);
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
let lastError: unknown;
|
||||
while (Date.now() < deadline) {
|
||||
try {
|
||||
const data = await fetchJson(`${normalized}/v1/health`, { token, extraHeaders });
|
||||
if (data?.status === "ok") {
|
||||
return;
|
||||
}
|
||||
lastError = new Error(`Unexpected health response: ${JSON.stringify(data)}`);
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
}
|
||||
await delay(500);
|
||||
}
|
||||
throw (lastError ?? new Error("Timed out waiting for /v1/health")) as Error;
|
||||
}
|
||||
|
||||
export async function createSession({
|
||||
baseUrl,
|
||||
token,
|
||||
extraHeaders,
|
||||
agentId,
|
||||
agentMode,
|
||||
permissionMode,
|
||||
model,
|
||||
variant,
|
||||
agentVersion,
|
||||
}: {
|
||||
baseUrl: string;
|
||||
token?: string;
|
||||
extraHeaders?: Record<string, string>;
|
||||
agentId?: string;
|
||||
agentMode?: string;
|
||||
permissionMode?: string;
|
||||
model?: string;
|
||||
variant?: string;
|
||||
agentVersion?: string;
|
||||
}): Promise<string> {
|
||||
const normalized = normalizeBaseUrl(baseUrl);
|
||||
const sessionId = randomUUID();
|
||||
const body: Record<string, string> = {
|
||||
agent: agentId || process.env.SANDBOX_AGENT || "codex",
|
||||
};
|
||||
const envAgentMode = agentMode || process.env.SANDBOX_AGENT_MODE;
|
||||
const envPermissionMode = permissionMode || process.env.SANDBOX_PERMISSION_MODE;
|
||||
const envModel = model || process.env.SANDBOX_MODEL;
|
||||
const envVariant = variant || process.env.SANDBOX_VARIANT;
|
||||
const envAgentVersion = agentVersion || process.env.SANDBOX_AGENT_VERSION;
|
||||
|
||||
if (envAgentMode) body.agentMode = envAgentMode;
|
||||
if (envPermissionMode) body.permissionMode = envPermissionMode;
|
||||
if (envModel) body.model = envModel;
|
||||
if (envVariant) body.variant = envVariant;
|
||||
if (envAgentVersion) body.agentVersion = envAgentVersion;
|
||||
|
||||
await fetchJson(`${normalized}/v1/sessions/${sessionId}`, {
|
||||
token,
|
||||
extraHeaders,
|
||||
method: "POST",
|
||||
body,
|
||||
});
|
||||
return sessionId;
|
||||
}
|
||||
|
||||
export async function sendMessage({
|
||||
baseUrl,
|
||||
token,
|
||||
extraHeaders,
|
||||
sessionId,
|
||||
message,
|
||||
}: {
|
||||
baseUrl: string;
|
||||
token?: string;
|
||||
extraHeaders?: Record<string, string>;
|
||||
sessionId: string;
|
||||
message: string;
|
||||
}): Promise<void> {
|
||||
const normalized = normalizeBaseUrl(baseUrl);
|
||||
await fetchJson(`${normalized}/v1/sessions/${sessionId}/messages`, {
|
||||
token,
|
||||
extraHeaders,
|
||||
method: "POST",
|
||||
body: { message },
|
||||
});
|
||||
}
|
||||
|
||||
function extractTextFromItem(item: any): string {
|
||||
if (!item?.content) return "";
|
||||
const textParts = item.content
|
||||
.filter((part: any) => part?.type === "text")
|
||||
.map((part: any) => part.text || "")
|
||||
.join("");
|
||||
if (textParts.trim()) {
|
||||
return textParts;
|
||||
}
|
||||
return JSON.stringify(item.content, null, 2);
|
||||
}
|
||||
|
||||
export async function waitForAssistantComplete({
|
||||
baseUrl,
|
||||
token,
|
||||
extraHeaders,
|
||||
sessionId,
|
||||
offset = 0,
|
||||
timeoutMs = 120_000,
|
||||
}: {
|
||||
baseUrl: string;
|
||||
token?: string;
|
||||
extraHeaders?: Record<string, string>;
|
||||
sessionId: string;
|
||||
offset?: number;
|
||||
timeoutMs?: number;
|
||||
}): Promise<{ text: string; offset: number }> {
|
||||
const normalized = normalizeBaseUrl(baseUrl);
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
let currentOffset = offset;
|
||||
|
||||
while (Date.now() < deadline) {
|
||||
const data = await fetchJson(
|
||||
`${normalized}/v1/sessions/${sessionId}/events?offset=${currentOffset}&limit=100`,
|
||||
{ token, extraHeaders }
|
||||
);
|
||||
|
||||
for (const event of data.events || []) {
|
||||
if (typeof event.sequence === "number") {
|
||||
currentOffset = Math.max(currentOffset, event.sequence);
|
||||
}
|
||||
if (
|
||||
event.type === "item.completed" &&
|
||||
event.data?.item?.kind === "message" &&
|
||||
event.data?.item?.role === "assistant"
|
||||
) {
|
||||
return {
|
||||
text: extractTextFromItem(event.data.item),
|
||||
offset: currentOffset,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (!data.hasMore) {
|
||||
await delay(300);
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error("Timed out waiting for assistant response");
|
||||
}
|
||||
|
||||
export async function runPrompt({
|
||||
baseUrl,
|
||||
token,
|
||||
extraHeaders,
|
||||
agentId,
|
||||
}: {
|
||||
baseUrl: string;
|
||||
token?: string;
|
||||
extraHeaders?: Record<string, string>;
|
||||
agentId?: string;
|
||||
}): Promise<void> {
|
||||
const sessionId = await createSession({ baseUrl, token, extraHeaders, agentId });
|
||||
let offset = 0;
|
||||
|
||||
console.log(`Session ${sessionId} ready. Type /exit to quit.`);
|
||||
|
||||
const rl = createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stdout,
|
||||
prompt: "> ",
|
||||
});
|
||||
|
||||
const handleLine = async (line: string) => {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed) {
|
||||
rl.prompt();
|
||||
return;
|
||||
}
|
||||
if (trimmed === "/exit") {
|
||||
rl.close();
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await sendMessage({ baseUrl, token, extraHeaders, sessionId, message: trimmed });
|
||||
const result = await waitForAssistantComplete({
|
||||
baseUrl,
|
||||
token,
|
||||
extraHeaders,
|
||||
sessionId,
|
||||
offset,
|
||||
});
|
||||
offset = result.offset;
|
||||
process.stdout.write(`${result.text}\n`);
|
||||
} catch (error) {
|
||||
console.error(error instanceof Error ? error.message : error);
|
||||
}
|
||||
|
||||
rl.prompt();
|
||||
};
|
||||
|
||||
rl.on("line", (line) => {
|
||||
void handleLine(line);
|
||||
});
|
||||
|
||||
rl.on("close", () => {
|
||||
process.exit(0);
|
||||
});
|
||||
|
||||
rl.prompt();
|
||||
}
|
||||
13
examples/tsconfig.json
Normal file
13
examples/tsconfig.json
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"lib": ["ES2022", "DOM"],
|
||||
"types": ["node"],
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"noEmit": true
|
||||
},
|
||||
"include": ["**/*.ts"]
|
||||
}
|
||||
34
examples/vercel/vercel-sandbox.test.ts
Normal file
34
examples/vercel/vercel-sandbox.test.ts
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
import { describe, it, expect } from "vitest";
|
||||
import { buildHeaders } from "../shared/sandbox-agent-client.ts";
|
||||
import { setupVercelSandboxAgent } from "./vercel-sandbox.ts";
|
||||
|
||||
const hasOidc = Boolean(process.env.VERCEL_OIDC_TOKEN);
|
||||
const hasAccess = Boolean(
|
||||
process.env.VERCEL_TOKEN &&
|
||||
process.env.VERCEL_TEAM_ID &&
|
||||
process.env.VERCEL_PROJECT_ID
|
||||
);
|
||||
const shouldRun = hasOidc || hasAccess;
|
||||
const timeoutMs = Number.parseInt(process.env.SANDBOX_TEST_TIMEOUT_MS || "", 10) || 300_000;
|
||||
|
||||
const testFn = shouldRun ? it : it.skip;
|
||||
|
||||
describe("vercel sandbox example", () => {
|
||||
testFn(
|
||||
"starts sandbox-agent and responds to /v1/health",
|
||||
async () => {
|
||||
const { baseUrl, token, cleanup } = await setupVercelSandboxAgent();
|
||||
try {
|
||||
const response = await fetch(`${baseUrl}/v1/health`, {
|
||||
headers: buildHeaders({ token }),
|
||||
});
|
||||
expect(response.ok).toBe(true);
|
||||
const data = await response.json();
|
||||
expect(data.status).toBe("ok");
|
||||
} finally {
|
||||
await cleanup();
|
||||
}
|
||||
},
|
||||
timeoutMs
|
||||
);
|
||||
});
|
||||
103
examples/vercel/vercel-sandbox.ts
Normal file
103
examples/vercel/vercel-sandbox.ts
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
import { Sandbox } from "@vercel/sandbox";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import {
|
||||
ensureUrl,
|
||||
runPrompt,
|
||||
waitForHealth,
|
||||
} from "../shared/sandbox-agent-client.ts";
|
||||
|
||||
const INSTALL_SCRIPT = "curl -fsSL https://releases.rivet.dev/sandbox-agent/latest/install.sh | sh";
|
||||
const DEFAULT_PORT = 2468;
|
||||
|
||||
type VercelSandboxOptions = {
|
||||
runtime: string;
|
||||
ports: number[];
|
||||
token?: string;
|
||||
teamId?: string;
|
||||
projectId?: string;
|
||||
};
|
||||
|
||||
export async function setupVercelSandboxAgent(): Promise<{
|
||||
baseUrl: string;
|
||||
token: string;
|
||||
cleanup: () => Promise<void>;
|
||||
}> {
|
||||
const token = process.env.SANDBOX_TOKEN || "";
|
||||
const port = Number.parseInt(process.env.SANDBOX_PORT || "", 10) || DEFAULT_PORT;
|
||||
const runtime = process.env.VERCEL_RUNTIME || "node24";
|
||||
|
||||
const createOptions: VercelSandboxOptions = {
|
||||
runtime,
|
||||
ports: [port],
|
||||
};
|
||||
|
||||
const accessToken = process.env.VERCEL_TOKEN;
|
||||
const teamId = process.env.VERCEL_TEAM_ID;
|
||||
const projectId = process.env.VERCEL_PROJECT_ID;
|
||||
if (accessToken && teamId && projectId) {
|
||||
createOptions.token = accessToken;
|
||||
createOptions.teamId = teamId;
|
||||
createOptions.projectId = projectId;
|
||||
}
|
||||
|
||||
const sandbox = await Sandbox.create(createOptions);
|
||||
|
||||
await sandbox.runCommand({
|
||||
cmd: "bash",
|
||||
args: ["-lc", INSTALL_SCRIPT],
|
||||
sudo: true,
|
||||
});
|
||||
|
||||
const tokenFlag = token ? "--token $SANDBOX_TOKEN" : "--no-token";
|
||||
await sandbox.runCommand({
|
||||
cmd: "bash",
|
||||
args: [
|
||||
"-lc",
|
||||
`SANDBOX_TOKEN=${token} sandbox-agent server ${tokenFlag} --host 0.0.0.0 --port ${port}`,
|
||||
],
|
||||
sudo: true,
|
||||
detached: true,
|
||||
});
|
||||
|
||||
const baseUrl = ensureUrl(sandbox.domain(port));
|
||||
await waitForHealth({ baseUrl, token });
|
||||
|
||||
const cleanup = async () => {
|
||||
try {
|
||||
await sandbox.stop();
|
||||
} catch {
|
||||
// ignore cleanup errors
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
baseUrl,
|
||||
token,
|
||||
cleanup,
|
||||
};
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const { baseUrl, token, cleanup } = await setupVercelSandboxAgent();
|
||||
|
||||
const exitHandler = async () => {
|
||||
await cleanup();
|
||||
process.exit(0);
|
||||
};
|
||||
|
||||
process.on("SIGINT", () => {
|
||||
void exitHandler();
|
||||
});
|
||||
process.on("SIGTERM", () => {
|
||||
void exitHandler();
|
||||
});
|
||||
|
||||
await runPrompt({ baseUrl, token });
|
||||
}
|
||||
|
||||
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
||||
main().catch((error) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
9
examples/vitest.config.ts
Normal file
9
examples/vitest.config.ts
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
import { defineConfig } from "vitest/config";
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
include: ["**/*.test.ts"],
|
||||
testTimeout: 300_000,
|
||||
hookTimeout: 300_000,
|
||||
},
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue