The @packages/ai package provides AI integrations for Answer Overflow, including sandboxed code execution and AI tool creation.
Installation
Overview
This package provides:
- Sandbox environment for safe code execution
- Virtual bash for command execution
- AI tools for sandbox interaction
- Git clone functionality in sandboxes
- MCP server integration
Sandbox Environment
The sandbox provides isolated code execution using OpenCode SDK:
import { createVirtualBash } from "@packages/ai/sandbox";
const bash = await createVirtualBash({
apiKey: process.env.OPENCODE_API_KEY,
workspace: {
name: "my-workspace",
files: {
"index.js": "console.log('Hello, world!');",
},
},
});
const result = await bash.execute("node index.js");
console.log(result.stdout); // "Hello, world!"
Virtual Bash
Create a virtual bash environmentInitial workspace configuration
Initial files to create in the workspace
Returns: VirtualBash instance
VirtualBash API
interface VirtualBash {
execute(command: string): Promise<VirtualBashResult>;
readFile(path: string): Promise<string>;
writeFile(path: string, content: string): Promise<void>;
listFiles(pattern: string): Promise<string[]>;
destroy(): Promise<void>;
}
Example: Execute commands
const bash = await createVirtualBash({ apiKey });
// Run multiple commands
const installResult = await bash.execute("npm install express");
const runResult = await bash.execute("npm start");
// Clean up
await bash.destroy();
VirtualBashResult
Standard output from the command
Standard error from the command
Exit code (0 for success)
Execution duration in milliseconds
Create AI SDK tools that interact with sandboxes:
import { createSandboxTool } from "@packages/ai/tools";
import { z } from "zod";
const executeTool = createSandboxTool({
name: "execute_code",
description: "Execute code in a sandbox",
parameters: z.object({
code: z.string(),
language: z.enum(["javascript", "python", "bash"]),
}),
execute: async ({ code, language }) => {
const bash = await createVirtualBash({ apiKey });
// Write code to file
await bash.writeFile(`script.${language}`, code);
// Execute based on language
const command = language === "python"
? "python script.py"
: language === "javascript"
? "node script.js"
: "bash script.bash";
const result = await bash.execute(command);
await bash.destroy();
return result;
},
});
Create an AI SDK tool for sandbox operationsZod schema for tool parameters
Execution handler: (params) => Promise<ToolResult>
Get a complete set of sandbox tools:
import { createSandboxTools } from "@packages/ai/tools";
const tools = createSandboxTools({
apiKey: process.env.OPENCODE_API_KEY,
workspaceName: "my-workspace",
});
// Returns: { bash, read, write, glob, grep, edit }
Available tools:
Git Clone in Sandbox
Clone Git repositories into sandboxes:
import { createGitCloneCommand } from "@packages/ai/sandbox/git-clone";
const bash = await createVirtualBash({ apiKey });
const cloneCommand = createGitCloneCommand({
url: "https://github.com/user/repo.git",
directory: "./my-repo",
credentials: {
username: "token",
password: process.env.GITHUB_TOKEN,
},
});
const result = await bash.execute(cloneCommand);
Create a Git clone command with credentialsTarget directory (default: inferred from URL)
Git credentials for authentication
Username (use “token” for PAT)
Password or personal access token
Returns: Command string for bash execution
Binary File Detection
Utility to detect binary files:
import { isBinaryFile, BINARY_EXTENSIONS } from "@packages/ai/sandbox";
const isBinary = isBinaryFile("image.png"); // true
const isText = isBinaryFile("script.js"); // false
console.log(BINARY_EXTENSIONS);
// ['.png', '.jpg', '.pdf', '.zip', ...]
MCP Server Integration
Integration with Model Context Protocol servers:
import { createMCPServer } from "@packages/ai/sandbox/mcp-server";
// Connect to MCP server in sandbox
const mcpServer = await createMCPServer({
command: "npx",
args: ["-y", "@modelcontextprotocol/server-filesystem"],
env: {
NODE_ENV: "production",
},
});
// Use MCP tools
const tools = await mcpServer.listTools();
const result = await mcpServer.callTool("read_file", {
path: "/path/to/file",
});
Use Cases
Code Execution Agent
import { Agent } from "@packages/agent";
import { createSandboxTools } from "@packages/ai/tools";
const codeAgent = new Agent(components.agent, {
name: "code-executor",
languageModel: openai.chat("gpt-4o"),
instructions: "You help users run code safely.",
tools: createSandboxTools({
apiKey: process.env.OPENCODE_API_KEY,
}),
});
const { thread } = await codeAgent.createThread(ctx);
const result = await thread.generateText({
prompt: "Write and run a Python script that prints Hello World",
});
Repository Analysis
const bash = await createVirtualBash({ apiKey });
// Clone repo
const cloneCmd = createGitCloneCommand({
url: "https://github.com/user/repo.git",
credentials: { username: "token", password: githubToken },
});
await bash.execute(cloneCmd);
// Analyze
const files = await bash.execute("find . -name '*.ts' | wc -l");
console.log(`TypeScript files: ${files.stdout}`);
await bash.destroy();
Exports
Sandbox tool creation utilities
Virtual bash and sandbox creation
Virtual bash implementation
Dependencies
@opencode-ai/sdk - OpenCode SDK for sandboxing
ai - Vercel AI SDK
just-bash - Bash utilities
zod - Schema validation