autosnippet
Version:
Extract code patterns into a knowledge base for AI coding assistants
61 lines (60 loc) • 1.85 kB
TypeScript
/**
* SandboxRunner — 工具锻造沙箱验证
*
* 在受限环境中执行锻造的工具代码 + 测试用例,验证安全性和正确性。
* 使用 Node.js vm 模块提供隔离执行环境。
*
* 安全约束:
* - 5s 执行超时
* - 禁止 require/import (无文件系统 / 网络 / 子进程)
* - 内存限制 via vm 上下文隔离
* - 只暴露 console.log, JSON, Math, Date, Array, Object, String 等纯函数
*/
export interface SandboxTestCase {
/** 测试描述 */
description: string;
/** 调用参数 */
input: Record<string, unknown>;
/** 预期输出(用 deepEqual 比较) */
expectedOutput: unknown;
}
export interface SandboxResult {
/** 是否全部通过 */
success: boolean;
/** 各测试用例结果 */
testResults: Array<{
description: string;
passed: boolean;
actualOutput?: unknown;
error?: string;
}>;
/** 总执行时间 (ms) */
executionTime: number;
/** 安全检查结果 */
safetyCheck: {
passed: boolean;
violations: string[];
};
}
export declare class SandboxRunner {
#private;
/**
* 对工具代码进行安全检查
*/
checkSafety(code: string): {
passed: boolean;
violations: string[];
};
/**
* 在沙箱中执行工具代码 + 测试用例
*
* @param code 工具函数代码(应 export default 或赋给 __toolHandler__)
* @param testCases 测试用例
*/
run(code: string, testCases: SandboxTestCase[]): SandboxResult;
/**
* 从验证通过的代码创建可调用 handler
* 返回的 handler 每次调用都在新沙箱中执行(隔离)
*/
createHandler(code: string): (params: Record<string, unknown>, context: Record<string, unknown>) => Promise<unknown>;
}