Skip to content

Open source file-system and knowledge based agent template. Build AI agents that stay up to date with your knowledge base

add bash-batch

Hugo Richard1729257a2025
diff --git a/apps/chat/server/api/sandbox/read.post.ts b/apps/chat/server/api/sandbox/read.post.ts
deleted file mode 100644
index 1416970..0000000
--- a/apps/chat/server/api/sandbox/read.post.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-import { z } from 'zod'
-import { useLogger } from 'evlog'
-import { getOrCreateSandbox, read } from '../../utils/sandbox/manager'
-
-const bodySchema = z.object({
- paths: z.array(z.string().min(1)).min(1).max(50),
- sessionId: z.string().optional(),
-})
-
-/**
- * POST /api/sandbox/read
- * Read specific files by path.
- *
- * Body:
- * - paths: string[] - File paths to read (max: 50)
- * - sessionId: string - Optional session ID for sandbox reuse
- */
-export default defineEventHandler(async (event) => {
- const requestLog = useLogger(event)
- const body = await readValidatedBody(event, bodySchema.parse)
-
- requestLog.set({ pathCount: body.paths.length })
-
- // Get or create sandbox
- const sandboxStart = Date.now()
- const { sandbox, sessionId } = await getOrCreateSandbox(body.sessionId)
- const sandboxMs = Date.now() - sandboxStart
-
- requestLog.set({ sandboxMs, sandboxId: sandbox.sandboxId, sessionId })
-
- // Read files
- const readStart = Date.now()
- const files = await read(sandbox, body.paths)
- const readMs = Date.now() - readStart
-
- requestLog.set({ readMs, fileCount: files.length })
-
- return {
- sessionId,
- files,
- }
-})
diff --git a/apps/chat/server/api/sandbox/search-and-read.post.ts b/apps/chat/server/api/sandbox/search-and-read.post.ts
deleted file mode 100644
index 665da6c..0000000
--- a/apps/chat/server/api/sandbox/search-and-read.post.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-import { z } from 'zod'
-import { useLogger } from 'evlog'
-import { getOrCreateSandbox, searchAndRead } from '../../utils/sandbox/manager'
-
-const bodySchema = z.object({
- query: z.string({ error: 'query is required - provide a search term like "useAsyncData" or "middleware"' }).min(1, 'query cannot be empty').max(500),
- limit: z.number().int().min(1).max(100).default(20),
- sessionId: z.string().optional(),
-})
-
-/**
- * POST /api/sandbox/search-and-read
- * Search for content and return matching files.
- *
- * Body:
- * - query: string - Search query (grep pattern)
- * - limit: number - Maximum results (default: 20, max: 100)
- * - sessionId: string - Optional session ID for sandbox reuse
- */
-export default defineEventHandler(async (event) => {
- const requestLog = useLogger(event)
- const body = await readValidatedBody(event, bodySchema.parse)
-
- requestLog.set({ query: body.query, limit: body.limit })
-
- // Get or create sandbox
- const sandboxStart = Date.now()
- const { sandbox, sessionId } = await getOrCreateSandbox(body.sessionId)
- const sandboxMs = Date.now() - sandboxStart
-
- requestLog.set({ sandboxMs, sandboxId: sandbox.sandboxId, sessionId })
-
- // Search and read files
- const searchStart = Date.now()
- const result = await searchAndRead(sandbox, body.query, body.limit)
- const searchMs = Date.now() - searchStart
-
- requestLog.set({
- searchMs,
- matchCount: result.matches.length,
- fileCount: result.files.length,
- })
-
- return {
- sessionId,
- matches: result.matches,
- files: result.files,
- }
-})
diff --git a/apps/chat/server/api/sandbox/shell.post.ts b/apps/chat/server/api/sandbox/shell.post.ts
index 375e6ef..6b6ef31 100644
--- a/apps/chat/server/api/sandbox/shell.post.ts
+++ b/apps/chat/server/api/sandbox/shell.post.ts
@@ -3,11 +3,14 @@ import { useLogger } from 'evlog'
import { getOrCreateSandbox } from '../../utils/sandbox/manager'
const bodySchema = z.object({
- command: z.string({ error: 'command is required' }).min(1, 'command cannot be empty').max(2000),
+ command: z.string().min(1).max(2000).optional(),
+ commands: z.array(z.string().min(1).max(2000)).max(10).optional(),
sessionId: z.string().optional(),
-})
+}).refine(
+ data => (data.command && !data.commands) || (!data.command && data.commands),
+ { message: 'Provide either "command" or "commands", not both' },
+)
-// Commands that could be dangerous
const BLOCKED_PATTERNS = [
/\brm\s+-rf?\b/i,
/\brmdir\b/i,
@@ -21,76 +24,90 @@ const BLOCKED_PATTERNS = [
/\bnc\b/i,
/\bssh\b/i,
/\bgit\b/i,
- />\s*\//, // redirect to absolute path
+ />\s*\//,
/\bdd\b/i,
/\bkill\b/i,
/\bpkill\b/i,
]
-/**
- * POST /api/sandbox/shell
- * Run a shell command in the sandbox.
- *
- * Body:
- * - command: string - Shell command to execute
- * - sessionId: string - Optional session ID for sandbox reuse
- */
-export default defineEventHandler(async (event) => {
- const requestLog = useLogger(event)
- const body = await readValidatedBody(event, bodySchema.parse)
+const MAX_OUTPUT = 50000
- // Check for blocked patterns
+function validateCommand(command: string): void {
for (const pattern of BLOCKED_PATTERNS) {
- if (pattern.test(body.command)) {
+ if (pattern.test(command)) {
throw createError({
statusCode: 400,
- message: 'Command contains blocked pattern',
+ message: `Command contains blocked pattern: ${command.slice(0, 50)}`,
})
}
}
+}
+
+function truncateOutput(output: string): string {
+ if (output.length > MAX_OUTPUT) {
+ return `${output.slice(0, MAX_OUTPUT)}\n... (truncated, ${output.length} total chars)`
+ }
+ return output
+}
+
+interface CommandResult {
+ command: string
+ stdout: string
+ stderr: string
+ exitCode: number
+ execMs: number
+}
+
+export default defineEventHandler(async (event) => {
+ const requestLog = useLogger(event)
+ const body = await readValidatedBody(event, bodySchema.parse)
- requestLog.set({ command: body.command.slice(0, 100) })
+ const commands = body.commands || [body.command!]
+
+ for (const cmd of commands) {
+ validateCommand(cmd)
+ }
+
+ const isBatch = commands.length > 1
+ requestLog.set({ commandCount: commands.length, isBatch })
- // Get or create sandbox
const sandboxStart = Date.now()
const { sandbox, sessionId } = await getOrCreateSandbox(body.sessionId)
- const sandboxMs = Date.now() - sandboxStart
-
- requestLog.set({ sandboxMs, sandboxId: sandbox.sandboxId, sessionId })
-
- // Execute command
- const execStart = Date.now()
- const result = await sandbox.runCommand({
- cmd: 'bash',
- args: ['-c', body.command],
- cwd: '/vercel/sandbox',
- })
-
- const stdout = await result.stdout()
- const stderr = await result.stderr()
- const { exitCode } = result
- const execMs = Date.now() - execStart
-
- // Limit output size to prevent token explosion
- const MAX_OUTPUT = 50000 // ~50KB
- const truncatedStdout = stdout.length > MAX_OUTPUT
- ? `${stdout.slice(0, MAX_OUTPUT)}\n... (truncated, ${stdout.length} total chars)`
- : stdout
- const truncatedStderr = stderr.length > MAX_OUTPUT
- ? `${stderr.slice(0, MAX_OUTPUT)}\n... (truncated, ${stderr.length} total chars)`
- : stderr
-
- requestLog.set({
- execMs,
- exitCode,
- stdoutLen: stdout.length,
- stderrLen: stderr.length,
- })
+ requestLog.set({ sandboxMs: Date.now() - sandboxStart, sandboxId: sandbox.sandboxId, sessionId })
+
+ const results: CommandResult[] = []
+
+ for (const command of commands) {
+ const execStart = Date.now()
+ const result = await sandbox.runCommand({
+ cmd: 'bash',
+ args: ['-c', command],
+ cwd: '/vercel/sandbox',
+ })
+
+ results.push({
+ command,
+ stdout: truncateOutput(await result.stdout()),
+ stderr: truncateOutput(await result.stderr()),
+ exitCode: result.exitCode,
+ execMs: Date.now() - execStart,
+ })
+ }
+
+ requestLog.set({ totalExecMs: results.reduce((sum, r) => sum + r.execMs, 0), commandsExecuted: results.length })
+
+ if (!isBatch) {
+ const r = results[0]!
+ return { sessionId, stdout: r.stdout, stderr: r.stderr, exitCode: r.exitCode }
+ }
return {
sessionId,
- stdout: truncatedStdout,
- stderr: truncatedStderr,
- exitCode,
+ results: results.map(r => ({
+ command: r.command,
+ stdout: r.stdout,
+ stderr: r.stderr,
+ exitCode: r.exitCode,
+ })),
}
})
diff --git a/apps/chat/server/api/sandbox/snapshot.post.ts b/apps/chat/server/api/sandbox/snapshot.post.ts
index 0160082..e375f2c 100644
--- a/apps/chat/server/api/sandbox/snapshot.post.ts
+++ b/apps/chat/server/api/sandbox/snapshot.post.ts
@@ -1,28 +1,16 @@
import { start } from 'workflow/api'
import { createSnapshot } from '../../workflows/create-snapshot'
-/**
- * POST /api/sandbox/snapshot
- * Create a new sandbox snapshot from the documentation repository.
- *
- * This workflow:
- * 1. Creates a sandbox from the GitHub snapshot repo
- * 2. Takes a snapshot for instant startup
- * 3. Stores the snapshot ID in KV storage
- */
export default defineEventHandler(async () => {
const config = useRuntimeConfig()
- const snapshotConfig = {
- githubToken: config.github.token,
- snapshotRepo: config.github.snapshotRepo,
- snapshotBranch: config.github.snapshotBranch,
- }
+ await start(createSnapshot, [
+ {
+ githubToken: config.github.token,
+ snapshotRepo: config.github.snapshotRepo,
+ snapshotBranch: config.github.snapshotBranch,
+ }
+ ])
- await start(createSnapshot, [snapshotConfig])
-
- return {
- status: 'started',
- message: 'Snapshot workflow started.',
- }
+ return { status: 'started', message: 'Snapshot workflow started.' }
})
diff --git a/apps/chat/server/utils/sandbox/manager.ts b/apps/chat/server/utils/sandbox/manager.ts
index 718bc6a..fa62aad 100644
--- a/apps/chat/server/utils/sandbox/manager.ts
+++ b/apps/chat/server/utils/sandbox/manager.ts
@@ -1,13 +1,12 @@
import { Sandbox } from '@vercel/sandbox'
import { createError, log } from 'evlog'
-import type { ActiveSandbox, FileContent, SearchAndReadResult, SearchResult, SandboxManagerConfig, SnapshotMetadata } from './types'
+import type { ActiveSandbox, SandboxManagerConfig, SnapshotMetadata } from './types'
import { getCurrentSnapshot, setCurrentSnapshot } from './snapshot'
import { deleteSandboxSession, generateSessionId, getSandboxSession, setSandboxSession, touchSandboxSession } from './session'
-const DEFAULT_SESSION_TTL_MS = 30 * 60 * 1000 // 30 minutes
-const SANDBOX_TIMEOUT_MS = 5 * 60 * 1000 // 5 minutes
+const DEFAULT_SESSION_TTL_MS = 30 * 60 * 1000
+const SANDBOX_TIMEOUT_MS = 5 * 60 * 1000
-/** Returns sandbox configuration from runtime environment */
function getConfig(): SandboxManagerConfig {
const config = useRuntimeConfig()
return {
@@ -18,7 +17,6 @@ function getConfig(): SandboxManagerConfig {
}
}
-/** Creates git source config with optional authentication for private repos */
function getGitSourceOptions(repoUrl: string, branch: string, githubToken?: string) {
const source: {
type: 'git'
@@ -32,7 +30,6 @@ function getGitSourceOptions(repoUrl: string, branch: string, githubToken?: stri
revision: branch,
}
- // Add GitHub credentials for private repos
if (githubToken) {
source.username = 'x-access-token'
source.password = githubToken
@@ -41,41 +38,29 @@ function getGitSourceOptions(repoUrl: string, branch: string, githubToken?: stri
return source
}
-/** Creates and initializes sandbox from snapshot ID */
async function createSandboxFromSnapshot(snapshotId: string): Promise<Sandbox> {
log.info('sandbox', `Creating sandbox from snapshot: ${snapshotId}`)
const startTime = Date.now()
const sandbox = await Sandbox.create({
- source: {
- type: 'snapshot',
- snapshotId,
- },
+ source: { type: 'snapshot', snapshotId },
timeout: SANDBOX_TIMEOUT_MS,
runtime: 'node24',
})
- const durationMs = Date.now() - startTime
- log.info('sandbox', `Sandbox created: ${sandbox.sandboxId} (${durationMs}ms)`)
+ log.info('sandbox', `Sandbox created: ${sandbox.sandboxId} (${Date.now() - startTime}ms)`)
return sandbox
}
-/** Returns sandbox if running, null otherwise */
async function getSandboxById(sandboxId: string): Promise<Sandbox | null> {
try {
const sandbox = await Sandbox.get({ sandboxId })
-
- if (sandbox.status !== 'running') {
- return null
- }
-
- return sandbox
+ return sandbox.status === 'running' ? sandbox : null
} catch {
return null
}
}
-/** Creates sandbox from git repository and returns snapshot ID */
export async function createSnapshotFromRepo(repoUrl: string, branch: string = 'main'): Promise<string> {
const config = getConfig()
@@ -89,36 +74,31 @@ export async function createSnapshotFromRepo(repoUrl: string, branch: string = '
log.info('sandbox', `Sandbox created: ${sandbox.sandboxId}, taking snapshot...`)
- // Take snapshot (this also stops the sandbox)
const snapshot = await sandbox.snapshot()
log.info('sandbox', `Snapshot created: ${snapshot.snapshotId}`)
return snapshot.snapshotId
}
-/** Returns current snapshot ID or creates one from configured repo */
async function getOrCreateSnapshot(): Promise<string> {
const config = getConfig()
- // Check if snapshot exists
const snapshot = await getCurrentSnapshot()
if (snapshot) {
return snapshot.snapshotId
}
- // No snapshot exists, create one from the repo
if (!config.snapshotRepo) {
throw createError({
message: 'No snapshot available',
why: 'NUXT_GITHUB_SNAPSHOT_REPO environment variable is not configured',
- fix: 'Set NUXT_GITHUB_SNAPSHOT_REPO to your snapshot repository (e.g., "owner/repo")',
+ fix: 'Set NUXT_GITHUB_SNAPSHOT_REPO to your snapshot repository',
})
}
const repoUrl = `https://github.com/${config.snapshotRepo}.git`
const snapshotId = await createSnapshotFromRepo(repoUrl, config.snapshotBranch)
- // Save the snapshot metadata
const metadata: SnapshotMetadata = {
snapshotId,
createdAt: Date.now(),
@@ -130,23 +110,19 @@ async function getOrCreateSnapshot(): Promise<string> {
return snapshotId
}
-/** Returns active sandbox for session, reusing existing or creating new. Auto-creates snapshot if needed */
export async function getOrCreateSandbox(sessionId?: string): Promise<ActiveSandbox> {
const config = getConfig()
const startTime = Date.now()
- // If session ID provided, try to get existing sandbox
if (sessionId) {
const session = await getSandboxSession(sessionId)
if (session) {
const sandbox = await getSandboxById(session.sandboxId)
if (sandbox) {
- const reuseMs = Date.now() - startTime
- log.info('sandbox', `Reusing sandbox ${sandbox.sandboxId} for session ${sessionId} (${reuseMs}ms)`)
+ log.info('sandbox', `Reusing sandbox ${sandbox.sandboxId} for session ${sessionId} (${Date.now() - startTime}ms)`)
await touchSandboxSession(sessionId, config.sessionTtlMs)
return { sandbox, session, sessionId }
}
- // Sandbox no longer available, clean up session
await deleteSandboxSession(sessionId)
}
}
@@ -165,232 +141,7 @@ export async function getOrCreateSandbox(sessionId?: string): Promise<ActiveSand
config.sessionTtlMs,
)
- const createMs = Date.now() - startTime
- log.info('sandbox', `New sandbox created for session ${newSessionId} (${createMs}ms)`)
+ log.info('sandbox', `New sandbox created for session ${newSessionId} (${Date.now() - startTime}ms)`)
return { sandbox, session, sessionId: newSessionId }
}
-
-/**
- * Search files in sandbox using grep (more widely available than ripgrep)
- */
-export async function search(
- sandbox: Sandbox,
- query: string,
- limit: number = 20,
-): Promise<SearchResult[]> {
- log.info('sandbox', `Searching for: ${query}`)
- const startTime = Date.now()
-
- // Use grep for searching (-r recursive, -n line numbers, -i case insensitive, -l list files)
- const result = await sandbox.runCommand({
- cmd: 'grep',
- args: [
- '-r', // Recursive
- '-n', // Line numbers
- '-i', // Case insensitive
- '-H', // Print filename
- '--include=*.md',
- '--include=*.yaml',
- '--include=*.yml',
- '--include=*.json',
- '--include=*.ts',
- '--include=*.js',
- query,
- '.',
- ],
- cwd: '/vercel/sandbox',
- })
-
- const grepMs = Date.now() - startTime
-
- const stdout = await result.stdout()
- const stderr = await result.stderr()
-
- if (stderr) {
- log.error('sandbox', `grep stderr: ${stderr}`)
- }
-
- const lines = stdout.split('\n').filter(Boolean).slice(0, limit)
-
- const results: SearchResult[] = []
- for (const line of lines) {
- // grep output format: ./path/to/file:lineNumber:content
- const match = line.match(/^\.\/(.+?):(\d+):(.*)$/)
- if (match && match[1] && match[2] && match[3]) {
- results.push({
- path: match[1],
- lineNumber: parseInt(match[2], 10),
- content: match[3].trim(),
- })
- }
- }
-
- log.info('sandbox', `Found ${results.length} matches (grep: ${grepMs}ms)`)
- return results
-}
-
-/** Reads files at paths from sandbox and returns contents, in parallel for better performance */
-export async function read(
- sandbox: Sandbox,
- paths: string[],
-): Promise<FileContent[]> {
- log.info('sandbox', `Reading ${paths.length} files`)
- const startTime = Date.now()
-
- const files = await Promise.all(paths.map(async (path) => {
- try {
- const buffer = await sandbox.readFileToBuffer({
- path,
- cwd: '/vercel/sandbox',
- })
-
- if (buffer) {
- return {
- path,
- content: buffer.toString('utf-8'),
- }
- }
- } catch {
- log.error('sandbox', `Failed to read file: ${path}`)
- }
- return null
- }))
-
- // Filter out any failed reads (nulls)
- const filteredFiles = files.filter((f): f is FileContent => !!f)
-
- const readMs = Date.now() - startTime
- log.info('sandbox', `Read ${filteredFiles.length} files successfully (${readMs}ms)`)
- return filteredFiles
-}
-
-/**
- * Searches for query and returns matches with context snippets.
- *
- * Optimizations:
- * 1. Occurrence-based ranking - files with more matches are more relevant
- * 2. Limited file reads - only top 3 most relevant files
- * 3. Context snippets - only lines around matches, not full files
- */
-export async function searchAndRead(
- sandbox: Sandbox,
- query: string,
- limit: number = 20,
-): Promise<SearchAndReadResult> {
- // Search for matches
- const matches = await search(sandbox, query, limit)
-
- if (matches.length === 0) {
- return { matches: [], files: [] }
- }
-
- // Count occurrences per file and rank by relevance
- const fileOccurrences = new Map<string, number>()
- for (const match of matches) {
- fileOccurrences.set(match.path, (fileOccurrences.get(match.path) || 0) + 1)
- }
-
- // Sort files by occurrence count (most relevant first)
- const rankedFiles = [...fileOccurrences.entries()]
- .sort((a, b) => b[1] - a[1])
- .map(([path]) => path)
-
- // Only read top 3 most relevant files (to avoid context explosion)
- const topFiles = rankedFiles.slice(0, 3)
-
- log.info('sandbox', `Ranked ${rankedFiles.length} files, reading top ${topFiles.length}`)
-
- // Read files with context snippets instead of full content
- const files = await readWithContext(sandbox, topFiles, matches)
-
- return { matches, files }
-}
-
-/**
- * Read files but only include lines around matches (context snippets).
- * This prevents context explosion from large files.
- */
-async function readWithContext(
- sandbox: Sandbox,
- paths: string[],
- matches: SearchResult[],
- contextLines: number = 10,
-): Promise<FileContent[]> {
- const startTime = Date.now()
-
- const files = await Promise.all(paths.map(async (path) => {
- try {
- const buffer = await sandbox.readFileToBuffer({
- path,
- cwd: '/vercel/sandbox',
- })
-
- if (!buffer) {
- return null
- }
-
- const fullContent = buffer.toString('utf-8')
- const lines = fullContent.split('\n')
-
- // Get line numbers with matches in this file
- const matchLines = matches
- .filter(m => m.path === path)
- .map(m => m.lineNumber)
-
- // Build a set of lines to include (match lines + context)
- const linesToInclude = new Set<number>()
- for (const lineNum of matchLines) {
- for (let i = Math.max(1, lineNum - contextLines); i <= Math.min(lines.length, lineNum + contextLines); i++) {
- linesToInclude.add(i)
- }
- }
-
- // Build content with only relevant lines
- // Group consecutive lines into snippets
- const sortedLines = [...linesToInclude].sort((a, b) => a - b)
- const snippets: string[] = []
- let currentSnippet: string[] = []
- let lastLine = -1
-
- for (const lineNum of sortedLines) {
- if (lastLine !== -1 && lineNum > lastLine + 1) {
- // Gap in lines - save current snippet and start new one
- if (currentSnippet.length > 0) {
- snippets.push(currentSnippet.join('\n'))
- currentSnippet = []
- }
- snippets.push('...')
- }
-
- const lineContent = lines[lineNum - 1] // 0-indexed
- if (lineContent !== undefined) {
- currentSnippet.push(`${lineNum}: ${lineContent}`)
- }
- lastLine = lineNum
- }
-
- // Don't forget the last snippet
- if (currentSnippet.length > 0) {
- snippets.push(currentSnippet.join('\n'))
- }
-
- const contextContent = snippets.join('\n')
-
- return {
- path,
- content: contextContent,
- matchCount: matchLines.length,
- totalLines: lines.length,
- }
- } catch {
- return null
- }
- }))
-
- const filteredFiles: FileContent[] = files.filter((f) => f !== null)
- const readMs = Date.now() - startTime
-
- log.info('sandbox', `Read ${filteredFiles.length} files with context (${readMs}ms)`)
- return filteredFiles
-}
diff --git a/apps/chat/server/utils/sandbox/types.ts b/apps/chat/server/utils/sandbox/types.ts
index 24ac7e8..d30ca61 100644
--- a/apps/chat/server/utils/sandbox/types.ts
+++ b/apps/chat/server/utils/sandbox/types.ts
@@ -1,8 +1,5 @@
import type { Sandbox } from '@vercel/sandbox'
-/**
- * Sandbox session stored in KV
- */
export interface SandboxSession {
sandboxId: string
snapshotId: string
@@ -11,9 +8,6 @@ export interface SandboxSession {
expiresAt: number
}
-/**
- * Snapshot metadata stored in KV
- */
export interface SnapshotMetadata {
snapshotId: string
createdAt: number
@@ -21,60 +15,19 @@ export interface SnapshotMetadata {
commitSha?: string
}
-/**
- * Search result from grep
- */
-export interface SearchResult {
- path: string
- lineNumber: number
- content: string
-}
-
-/**
- * File content with path and optional metadata
- */
-export interface FileContent {
- path: string
- content: string
- /** Number of matches in this file (for context snippets) */
- matchCount?: number
- /** Total lines in the file (for context snippets) */
- totalLines?: number
-}
-
-/**
- * Search and read combined result
- */
-export interface SearchAndReadResult {
- matches: SearchResult[]
- files: FileContent[]
-}
-
-/**
- * Sandbox manager configuration
- * Uses Vercel OIDC token automatically.
- */
export interface SandboxManagerConfig {
- // GitHub authentication for private repos
githubToken?: string
- // Snapshot repository configuration
snapshotRepo: string
snapshotBranch?: string
sessionTtlMs?: number
}
-/**
- * Active sandbox instance with metadata
- */
export interface ActiveSandbox {
sandbox: Sandbox
session: SandboxSession
sessionId: string
}
-/**
- * KV storage keys
- */
export const KV_KEYS = {
CURRENT_SNAPSHOT: 'snapshot:current',
SNAPSHOT_STATUS_CACHE: 'snapshot:status-cache',
diff --git a/packages/sdk/src/client.ts b/packages/sdk/src/client.ts
index 86b09bc..3cef8bd 100644
--- a/packages/sdk/src/client.ts
+++ b/packages/sdk/src/client.ts
@@ -1,6 +1,7 @@
import { createError } from 'evlog'
import type {
SavoirConfig,
+ ShellBatchResponse,
ShellResponse,
SnapshotResponse,
SourcesResponse,
@@ -148,6 +149,16 @@ export class SavoirClient {
})
}
+ /**
+ * Run multiple bash commands in sequence (batch mode)
+ * More efficient than multiple single calls as sandbox is reused
+ */
+ async bashBatch(commands: string[]): Promise<ShellBatchResponse> {
+ return await this.post<ShellBatchResponse>('/api/sandbox/shell', {
+ commands,
+ })
+ }
+
/**
* Get list of configured sources
*/
diff --git a/packages/sdk/src/index.ts b/packages/sdk/src/index.ts
index de99b0c..67b5c57 100644
--- a/packages/sdk/src/index.ts
+++ b/packages/sdk/src/index.ts
@@ -1,8 +1,8 @@
import { SavoirClient } from './client'
-import { createBashTool } from './tools'
-import type { SavoirConfig, ToolCallCallback } from './types'
+import { createBashBatchTool, createBashTool } from './tools'
+import type { SavoirConfig } from './types'
-export type { SavoirConfig, ShellResponse, SyncOptions, SyncResponse, SnapshotResponse, GitHubSource, YouTubeSource, SourcesResponse, SyncSourceResponse, ToolCallInfo, ToolCallCallback, ToolCallState } from './types'
+export type { SavoirConfig, ShellResponse, ShellBatchResponse, ShellCommandResult, SyncOptions, SyncResponse, SnapshotResponse, GitHubSource, YouTubeSource, SourcesResponse, SyncSourceResponse, ToolCallInfo, ToolCallCallback, ToolCallState } from './types'
export { SavoirError, NetworkError } from './errors'
export { SavoirClient } from './client'
@@ -19,8 +19,10 @@ export interface Savoir {
* AI SDK tools
*/
tools: {
- /** Execute bash commands in the sandbox */
+ /** Execute a single bash command in the sandbox */
bash: ReturnType<typeof createBashTool>
+ /** Execute multiple bash commands in one request (more efficient) */
+ bash_batch: ReturnType<typeof createBashBatchTool>
}
/**
@@ -66,6 +68,7 @@ export function createSavoir(config: SavoirConfig): Savoir {
client,
tools: {
bash: createBashTool(client, onToolCall),
+ bash_batch: createBashBatchTool(client, onToolCall),
},
getSessionId: () => client.getSessionId(),
setSessionId: (sessionId: string) => client.setSessionId(sessionId),
diff --git a/packages/sdk/src/tools/index.ts b/packages/sdk/src/tools/index.ts
index 96f5848..929f6b7 100644
--- a/packages/sdk/src/tools/index.ts
+++ b/packages/sdk/src/tools/index.ts
@@ -1 +1 @@
-export { createBashTool } from './shell'
+export { createBashTool, createBashBatchTool } from './shell'
diff --git a/packages/sdk/src/tools/shell.ts b/packages/sdk/src/tools/shell.ts
index 361abca..de7ab05 100644
--- a/packages/sdk/src/tools/shell.ts
+++ b/packages/sdk/src/tools/shell.ts
@@ -4,7 +4,7 @@ import type { SavoirClient } from '../client'
import type { ToolCallCallback } from '../types'
/**
- * Create the bash tool for AI SDK - runs commands in the sandbox
+ * Create the bash tool for AI SDK - runs a single command in the sandbox
*/
export function createBashTool(client: SavoirClient, onToolCall?: ToolCallCallback) {
return tool({
@@ -39,3 +39,45 @@ Use standard Unix commands to explore and read files.`,
},
})
}
+
+/**
+ * Create the bash_batch tool for AI SDK - runs multiple commands in one API call
+ */
+export function createBashBatchTool(client: SavoirClient, onToolCall?: ToolCallCallback) {
+ return tool({
+ description: `Execute multiple bash commands in the documentation sandbox in a single request.
+More efficient than multiple single bash calls. Commands run sequentially.
+Use when you need to run several related commands (e.g., list + read multiple files).
+Maximum 10 commands per batch.`,
+ inputSchema: z.object({
+ commands: z.array(z.string()).min(1).max(10).describe('Array of bash commands to execute'),
+ }),
+ onInputAvailable: ({ toolCallId, input }) => {
+ onToolCall?.({
+ toolCallId,
+ toolName: 'bash_batch',
+ args: input,
+ state: 'loading',
+ })
+ },
+ execute: async ({ commands }, { toolCallId }) => {
+ const result = await client.bashBatch(commands)
+
+ onToolCall?.({
+ toolCallId,
+ toolName: 'bash_batch',
+ args: { commands },
+ state: 'done',
+ })
+
+ return {
+ results: result.results.map(r => ({
+ command: r.command,
+ stdout: r.stdout,
+ stderr: r.stderr,
+ exitCode: r.exitCode,
+ })),
+ }
+ },
+ })
+}
diff --git a/packages/sdk/src/types.ts b/packages/sdk/src/types.ts
index 3be55cb..74e78ca 100644
--- a/packages/sdk/src/types.ts
+++ b/packages/sdk/src/types.ts
@@ -86,7 +86,7 @@ export interface ReadResponse {
}
/**
- * Response from the shell endpoint
+ * Response from the shell endpoint (single command)
*/
export interface ShellResponse {
sessionId: string
@@ -95,6 +95,24 @@ export interface ShellResponse {
exitCode: number
}
+/**
+ * Single command result in batch response
+ */
+export interface ShellCommandResult {
+ command: string
+ stdout: string
+ stderr: string
+ exitCode: number
+}
+
+/**
+ * Response from the shell endpoint (batch commands)
+ */
+export interface ShellBatchResponse {
+ sessionId: string
+ results: ShellCommandResult[]
+}
+
/**
* Error response from the Savoir API
*/