|
| 1 | +# Code Mode — 在 Sandbox 中执行代码片段 |
| 2 | + |
| 3 | +**状态:** TODO |
| 4 | +**日期:** 2026-03-25 |
| 5 | +**背景:** 受 Cloudflare Dynamic Workers 启发,结合 db9 HTTP API 的纯 fetch 可操作性 |
| 6 | + |
| 7 | +--- |
| 8 | + |
| 9 | +## 动机 |
| 10 | + |
| 11 | +当前 `exec()` 执行的是 shell 命令,agent 需要反复来回调用。Code mode 让 agent 生成一段完整的逻辑代码一次性执行,减少 round-trip。 |
| 12 | + |
| 13 | +典型场景:agent 生成一段 JS 代码,通过 db9 HTTP API 做复杂查询和数据处理,一次返回结构化结果。 |
| 14 | + |
| 15 | +## 接口设计(草案) |
| 16 | + |
| 17 | +```typescript |
| 18 | +export interface CodeRunnerSandbox extends Sandbox { |
| 19 | + runCode(code: string, options?: RunCodeOptions): Promise<RunCodeResult> |
| 20 | +} |
| 21 | + |
| 22 | +export interface RunCodeOptions { |
| 23 | + language?: 'javascript' | 'typescript' | 'python' |
| 24 | + timeout?: number |
| 25 | + env?: Record<string, string> // 注入为代码中可访问的 env 对象 |
| 26 | +} |
| 27 | + |
| 28 | +export interface RunCodeResult { |
| 29 | + output: unknown // 代码 return 的值(JSON-serializable) |
| 30 | + stdout: string |
| 31 | + stderr: string |
| 32 | +} |
| 33 | +``` |
| 34 | + |
| 35 | +`code` 是 async function body,可以用 `fetch()` 和 `return`: |
| 36 | + |
| 37 | +```typescript |
| 38 | +const result = await sandbox.runCode(` |
| 39 | + const res = await fetch("https://api.db9.ai/customer/databases/mydb/sql", { |
| 40 | + method: "POST", |
| 41 | + headers: { "Authorization": "Bearer " + env.DB9_TOKEN, "Content-Type": "application/json" }, |
| 42 | + body: JSON.stringify({ query: "SELECT count(*) FROM users" }) |
| 43 | + }) |
| 44 | + return await res.json() |
| 45 | +`, { env: { DB9_TOKEN: 'xxx' } }) |
| 46 | +``` |
| 47 | + |
| 48 | +## Provider 实现差异 |
| 49 | + |
| 50 | +| | cloud / boxlite (VM) | cloudflare (isolate) | |
| 51 | +|--|---------------------|---------------------| |
| 52 | +| 实现 | 包装成 Node.js 脚本,通过 exec 执行 | 包装成 Dynamic Worker module | |
| 53 | +| 启动 | ~50ms | ~5ms | |
| 54 | +| `fetch()` | ✅ | ✅ | |
| 55 | +| `fs` | ✅ | ❌ | |
| 56 | +| `child_process` | ✅ | ❌ | |
| 57 | +| npm 依赖 | require() 可用 | 需预 bundle | |
| 58 | + |
| 59 | +跨 provider 可移植的代码限于:纯计算 + `fetch()` + `return`。 |
| 60 | + |
| 61 | +## Capability |
| 62 | + |
| 63 | +```typescript |
| 64 | +'code.run' // 基础 code mode(fetch + return) |
| 65 | +'code.run.fs' // code 中可用 fs(VM only) |
| 66 | +'code.run.process' // code 中可用 child_process(VM only) |
| 67 | +``` |
| 68 | + |
| 69 | +## 待决策 |
| 70 | + |
| 71 | +1. `code` 参数是 function body 还是完整 ES module? |
| 72 | +2. env 注入方式:全局 `env` 对象 vs `process.env` |
| 73 | +3. 是否需要 `sandbank run` CLI 命令 |
| 74 | +4. 依赖处理:Cloudflare 需要预 bundle,VM 不需要 |
| 75 | +5. 错误处理:代码抛异常时的返回格式 |
0 commit comments