Skip to main content
The @packages/ai package provides AI integrations for Answer Overflow, including sandboxed code execution and AI tool creation.

Installation

npm install @packages/ai

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

createVirtualBash
function
Create a virtual bash environment
apiKey
string
required
OpenCode API key
workspace
object
Initial workspace configuration
workspace.name
string
Workspace name
workspace.files
Record<string, string>
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

stdout
string
Standard output from the command
stderr
string
Standard error from the command
exitCode
number
Exit code (0 for success)
duration
number
Execution duration in milliseconds

Sandbox Tools

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;
  },
});
createSandboxTool
function
Create an AI SDK tool for sandbox operations
name
string
required
Tool name
description
string
required
What the tool does
parameters
ZodSchema
required
Zod schema for tool parameters
execute
function
required
Execution handler: (params) => Promise<ToolResult>

createSandboxTools

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:
bash
tool
Execute bash commands
read
tool
Read file contents
write
tool
Write files
glob
tool
Search files by pattern
grep
tool
Search file contents
edit
tool
Edit files

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);
createGitCloneCommand
function
Create a Git clone command with credentials
url
string
required
Git repository URL
directory
string
Target directory (default: inferred from URL)
credentials
GitCredentialProvider
Git credentials for authentication
credentials.username
string
Username (use “token” for PAT)
credentials.password
string
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

./tools
module
Sandbox tool creation utilities
./sandbox
module
Virtual bash and sandbox creation
./sandbox/virtual-bash
module
Virtual bash implementation
./sandbox/git-clone
module
Git clone functionality
./sandbox/mcp-server
module
MCP server integration

Dependencies

  • @opencode-ai/sdk - OpenCode SDK for sandboxing
  • ai - Vercel AI SDK
  • just-bash - Bash utilities
  • zod - Schema validation