|
| 1 | +import fs from 'fs'; |
| 2 | +import os from 'os'; |
| 3 | +import path from 'path'; |
| 4 | +import crypto from 'crypto'; |
| 5 | +import { z } from 'zod'; |
| 6 | +import { DynamicStructuredTool, type StructuredToolInterface } from '@langchain/core/tools'; |
| 7 | +import { createErrorResult, type MCPToolResult } from '../Core'; |
| 8 | +import { runProgram, runShellCommand } from './runtime/foreground'; |
| 9 | +import { resolveWorkingDir } from './runtime/workingDir'; |
| 10 | +import { isCommandAvailable } from './runtime/process'; |
| 11 | +import { processManager, formatProcessResult } from './runtime/processManager'; |
| 12 | + |
| 13 | +export enum CodeRuntime { |
| 14 | + Shell = 'shell', |
| 15 | + PowerShell = 'powershell', |
| 16 | + Python = 'python', |
| 17 | + NodeJs = 'nodejs', |
| 18 | +} |
| 19 | + |
| 20 | +export enum CodeToolMode { |
| 21 | + Sync = 'sync', |
| 22 | + Background = 'background', |
| 23 | +} |
| 24 | + |
| 25 | +export { CodeToolMode as ShellToolMode, CodeToolMode as ScriptCodeMode }; |
| 26 | + |
| 27 | +function normalizeStdin(stdin: unknown): string | undefined { |
| 28 | + if (stdin == null) return undefined; |
| 29 | + return typeof stdin === 'string' ? stdin : JSON.stringify(stdin); |
| 30 | +} |
| 31 | + |
| 32 | +function withExecutionMode<T extends z.ZodRawShape>(base: z.ZodObject<T>) { |
| 33 | + return z.discriminatedUnion('mode', [ |
| 34 | + base.extend({ |
| 35 | + mode: z.literal(CodeToolMode.Sync).describe('Run synchronously and return the final output in this tool call'), |
| 36 | + timeout: z.number().optional().default(60000).describe('Timeout in milliseconds, default 60000 (60 s)'), |
| 37 | + }), |
| 38 | + base.extend({ |
| 39 | + mode: z.literal(CodeToolMode.Background).describe('Run in the background and use read_process for later output'), |
| 40 | + yieldMs: z.number().optional().default(1000).describe('How long to wait for immediate completion before returning a processid, default 1000 ms'), |
| 41 | + }), |
| 42 | + ]); |
| 43 | +} |
| 44 | + |
| 45 | +const shellCodeBaseSchema = z.object({ |
| 46 | + code: z.string().min(1).describe('Command or multi-line shell script to run, e.g. "git status", "npm install && npm run build", or a newline-separated script'), |
| 47 | + workingDir: z.string().describe('Absolute path of the working directory'), |
| 48 | + stdin: z.any().optional().describe('Data to pipe into the command via stdin. Prefer a string; objects/arrays are auto-serialized to JSON.'), |
| 49 | +}); |
| 50 | + |
| 51 | +const scriptCodeBaseSchema = z.object({ |
| 52 | + code: z.string().min(1).describe('Script source code to execute; written to a temp file automatically'), |
| 53 | + workingDir: z.string().describe('Absolute path of the working directory for the script'), |
| 54 | + stdin: z.any().optional().describe('Data to pipe into the script via stdin. Prefer a string; objects/arrays are auto-serialized to JSON.'), |
| 55 | +}); |
| 56 | + |
| 57 | +export const shellToolSchema = withExecutionMode(shellCodeBaseSchema); |
| 58 | +export const scriptCodeSchema = withExecutionMode(scriptCodeBaseSchema); |
| 59 | + |
| 60 | +export const readProcessToolSchema = z.object({ |
| 61 | + processId: z.number().int().positive().describe('The numeric processId returned by shell/script mode="background"'), |
| 62 | + yieldMs: z.number().optional().default(1000).describe('How long to wait for new output, default 1000 ms'), |
| 63 | +}); |
| 64 | + |
| 65 | +type ShellToolInput = z.infer<typeof shellToolSchema>; |
| 66 | +type ScriptCodeInput = z.infer<typeof scriptCodeSchema>; |
| 67 | +type ReadProcessToolInput = z.infer<typeof readProcessToolSchema>; |
| 68 | +type CodeToolInput = ShellToolInput | ScriptCodeInput; |
| 69 | + |
| 70 | +export interface ShellToolOptions { |
| 71 | + name?: string; |
| 72 | + description: string; |
| 73 | +} |
| 74 | + |
| 75 | +export interface ReadProcessToolOptions { |
| 76 | + name?: string; |
| 77 | + description: string; |
| 78 | +} |
| 79 | + |
| 80 | +export interface ScriptCodeToolOptions { |
| 81 | + name: string; |
| 82 | + description: string; |
| 83 | + runtime: CodeRuntime; |
| 84 | + interpreter: string; |
| 85 | + preArgs?: string[]; |
| 86 | + ext: string; |
| 87 | +} |
| 88 | + |
| 89 | +interface ExecuteCodeOptions { |
| 90 | + runtime: CodeRuntime; |
| 91 | + label: string; |
| 92 | + interpreter?: string; |
| 93 | + preArgs?: string[]; |
| 94 | + ext?: string; |
| 95 | +} |
| 96 | + |
| 97 | +async function executeCode(input: CodeToolInput, opts: ExecuteCodeOptions): Promise<MCPToolResult> { |
| 98 | + const { cwd, error: cwdError } = await resolveWorkingDir(input.workingDir); |
| 99 | + if (cwdError) return createErrorResult(cwdError); |
| 100 | + |
| 101 | + const stdin = normalizeStdin(input.stdin); |
| 102 | + if (opts.runtime === CodeRuntime.Shell) { |
| 103 | + if (input.mode === CodeToolMode.Background) { |
| 104 | + const result = await processManager.exec(input.code, cwd!, input.yieldMs ?? 1000, stdin); |
| 105 | + return formatProcessResult(result); |
| 106 | + } |
| 107 | + return runShellCommand(input.code, cwd!, input.timeout ?? 60000, `command "${input.code}"`, stdin); |
| 108 | + } |
| 109 | + |
| 110 | + if (!opts.interpreter || !opts.ext) { |
| 111 | + return createErrorResult(`Missing interpreter configuration for ${opts.runtime}`); |
| 112 | + } |
| 113 | + |
| 114 | + const tmpFile = path.join(os.tmpdir(), `sbot_script_${Date.now()}_${crypto.randomBytes(6).toString('hex')}${opts.ext}`); |
| 115 | + try { |
| 116 | + await fs.promises.writeFile(tmpFile, input.code, 'utf8'); |
| 117 | + } catch (e: any) { |
| 118 | + return createErrorResult(`Failed to write temp script: ${e?.message ?? e}`); |
| 119 | + } |
| 120 | + |
| 121 | + let cleanupByBackgroundManager = false; |
| 122 | + const cleanupTempFile = async () => { |
| 123 | + try { await fs.promises.unlink(tmpFile); } catch { /* ignore */ } |
| 124 | + }; |
| 125 | + |
| 126 | + try { |
| 127 | + const runArgs = [...(opts.preArgs ?? []), tmpFile]; |
| 128 | + if (input.mode === CodeToolMode.Background) { |
| 129 | + cleanupByBackgroundManager = true; |
| 130 | + const result = await processManager.runProgram( |
| 131 | + opts.interpreter, |
| 132 | + runArgs, |
| 133 | + cwd!, |
| 134 | + input.yieldMs ?? 1000, |
| 135 | + stdin, |
| 136 | + cleanupTempFile, |
| 137 | + ); |
| 138 | + return formatProcessResult(result); |
| 139 | + } |
| 140 | + return runProgram(opts.interpreter, runArgs, cwd!, input.timeout ?? 60000, opts.label, stdin); |
| 141 | + } finally { |
| 142 | + if (!cleanupByBackgroundManager) await cleanupTempFile(); |
| 143 | + } |
| 144 | +} |
| 145 | + |
| 146 | +export function createShellTool({ name = 'shell', description }: ShellToolOptions): StructuredToolInterface { |
| 147 | + return new DynamicStructuredTool({ |
| 148 | + name, |
| 149 | + description, |
| 150 | + schema: shellToolSchema as any, |
| 151 | + func: async (input: ShellToolInput): Promise<MCPToolResult> => executeCode(input, { |
| 152 | + runtime: CodeRuntime.Shell, |
| 153 | + label: name, |
| 154 | + }), |
| 155 | + }); |
| 156 | +} |
| 157 | + |
| 158 | +export function createScriptCodeTool({ name, description, runtime, interpreter, preArgs = [], ext }: ScriptCodeToolOptions): StructuredToolInterface | null { |
| 159 | + if (!isCommandAvailable(interpreter)) return null; |
| 160 | + return new DynamicStructuredTool({ |
| 161 | + name, |
| 162 | + description, |
| 163 | + schema: scriptCodeSchema as any, |
| 164 | + func: async (input: ScriptCodeInput): Promise<MCPToolResult> => executeCode(input, { |
| 165 | + runtime, |
| 166 | + label: name, |
| 167 | + interpreter, |
| 168 | + preArgs, |
| 169 | + ext, |
| 170 | + }), |
| 171 | + }); |
| 172 | +} |
| 173 | + |
| 174 | +export function createReadProcessTool({ name = 'read_process', description }: ReadProcessToolOptions): StructuredToolInterface { |
| 175 | + return new DynamicStructuredTool({ |
| 176 | + name, |
| 177 | + description, |
| 178 | + schema: readProcessToolSchema as any, |
| 179 | + func: async ({ processId, yieldMs = 1000 }: ReadProcessToolInput): Promise<MCPToolResult> => { |
| 180 | + const result = await processManager.readProcess(processId, yieldMs); |
| 181 | + return formatProcessResult(result); |
| 182 | + }, |
| 183 | + }); |
| 184 | +} |
0 commit comments