@sandbaseai/cli 0.1.13 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,295 @@
1
+ <p align="center">
2
+ <h1 align="center">@sandbaseai/cli</h1>
3
+ <p align="center">
4
+ <strong>让你的 AI 助手拥有超能力。一行命令,2,000+ AI 模型与 API。</strong>
5
+ </p>
6
+ <p align="center">
7
+ <a href="./README.md">English</a> | 中文 | <a href="./README.ja.md">日本語</a> | <a href="./README.ko.md">한국어</a> | <a href="./README.es.md">Español</a> | <a href="./README.fr.md">Français</a> | <a href="./README.de.md">Deutsch</a> | <a href="./README.pt-BR.md">Português</a>
8
+ </p>
9
+ <p align="center">
10
+ <a href="https://github.com/sandbaseai/cli/releases/latest"><img alt="GitHub Release" src="https://img.shields.io/github/v/release/sandbaseai/cli"></a>
11
+ <a href="https://github.com/sandbaseai/cli/actions/workflows/ci.yml"><img alt="CI" src="https://github.com/sandbaseai/cli/actions/workflows/ci.yml/badge.svg"></a>
12
+ <a href="https://registry.modelcontextprotocol.io/v0.1/servers?search=io.github.sandbaseai%2Fcli"><img alt="官方 MCP Registry" src="https://img.shields.io/badge/MCP%20Registry-%E5%B7%B2%E6%94%B6%E5%BD%95-5a67d8"></a>
13
+ <a href="https://tensorblock.co/mcp/servers/github-sandbaseai-cli-c4e113db"><img alt="TensorBlock MCP Index 已收录" src="https://mcp-index.tensorblock.co/v1/servers/github-sandbaseai-cli-c4e113db/badge.svg"></a>
14
+ <a href="https://github.com/sandbaseai/cli/blob/main/LICENSE"><img alt="开源许可" src="https://img.shields.io/github/license/sandbaseai/cli"></a>
15
+ <a href="https://github.com/sandbaseai/cli/stargazers"><img alt="GitHub Stars" src="https://img.shields.io/github/stars/sandbaseai/cli?style=social"></a>
16
+ </p>
17
+ </p>
18
+
19
+ <p align="center">
20
+ <img src="https://raw.githubusercontent.com/sandbaseai/cli/main/.github/assets/sandbase-cli-hero.webp" alt="SandBase CLI 安全连接 AI 客户端与模型、API、媒体、数据和沙箱" width="100%">
21
+ </p>
22
+
23
+ ---
24
+
25
+ 你的 AI 编程助手很聪明,但它被困在一个盒子里。它不能搜索网页、查看社交媒体、生成图片、或获取实时数据 — 除非你自己逐个对接每个 API。
26
+
27
+ **SandBase 改变了这一切。** 一行命令,通过 [Model Context Protocol](https://modelcontextprotocol.io) 将你的 Agent 连接到 2,000+ AI 模型与 API。不用管理 API Key,不用折腾配置。
28
+
29
+ 在 macOS 或 Linux 上使用官方 Homebrew Formula:
30
+
31
+ ```sh
32
+ brew install sandbaseai/tap/sandbaseai-cli
33
+ sandbase connect
34
+ ```
35
+
36
+ 或者直接运行不可变的 v0.1.17 发布包:
37
+
38
+ ```sh
39
+ npx -y https://github.com/sandbaseai/cli/releases/download/v0.1.17/sandbaseai-cli-0.1.17.tgz connect
40
+ ```
41
+
42
+ 想先验证兼容性、暂不登录也不修改本地配置?运行只读目录命令,确认当前版本支持的 25 个客户端:
43
+
44
+ ```sh
45
+ npx -y https://github.com/sandbaseai/cli/releases/download/v0.1.17/sandbaseai-cli-0.1.17.tgz catalog --json
46
+ ```
47
+
48
+ <p align="center">
49
+ <a href="https://static.sandbase.ai/blog/screenshots/sandbase-cli-mcp-bridge-25-ai-clients/catalog-audit-5eea5978a1ed.webp"><img src="https://static.sandbase.ai/blog/screenshots/sandbase-cli-mcp-bridge-25-ai-clients/catalog-audit-5eea5978a1ed.webp" alt="SandBase CLI v0.1.17 只读目录审计显示 25 个客户端目标" width="49%"></a>
50
+ <a href="https://static.sandbase.ai/blog/screenshots/sandbase-cli-mcp-bridge-25-ai-clients/doctor-readback-3c86ac73e463.webp"><img src="https://static.sandbase.ai/blog/screenshots/sandbase-cli-mcp-bridge-25-ai-clients/doctor-readback-3c86ac73e463.webp" alt="SandBase CLI v0.1.17 doctor 对空白隔离配置按预期安全失败" width="49%"></a>
51
+ </p>
52
+ <p align="center"><sub>来自不可变 v0.1.17 发布包的证据:不写配置的目录审计,以及针对空白隔离配置的受限 doctor 检查。</sub></p>
53
+
54
+ 这里使用的是不可变的 GitHub `v0.1.17` 发布包;其 SHA-256 为
55
+ `1ad535b2899ca460b57b3c268aef278fee28fd28e649a89b92951514fd71fffa`。
56
+ 目前 npm 的 `latest` 标签仍是 v0.1.14,因此在可信发布启用完成前,请使用上面的版本化 GitHub 地址。
57
+
58
+ 项目已进入[官方 MCP Registry](https://registry.modelcontextprotocol.io/v0.1/servers/io.github.sandbaseai%2Fcli/versions/0.1.17),并被[中国独立开发者项目(程序员版)](https://github.com/1c7/chinese-independent-developer/blob/master/pages/README-Programmer-Edition.md#sandbase---github)独立收录。
59
+
60
+ 查看[中文项目页](https://sandbaseai.github.io/cli/zh/)和[中文工作流指南](https://github.com/sandbaseai/cli/discussions/48)。如果 SandBase CLI 对你有帮助,请[给仓库一个 Star](https://github.com/sandbaseai/cli),让更多开发者发现它。
61
+
62
+ 就这样。你的 Agent 现在能访问一切。
63
+
64
+ ## SandBase 开源技术栈
65
+
66
+ - **[SandBase Harness](https://github.com/sandbaseai/sandbase-harness)** — 自托管 Agent Runtime,提供持久会话、沙箱隔离、审批、审计与回放。
67
+ - **[SandBase Agent Skills](https://github.com/sandbaseai/sandbase-skills)** — 88 个可安装 Skills,覆盖研究、社交情报、营销和商业工作流。
68
+ - **[SandBase for Codex](https://github.com/sandbaseai/sandbase-codex-plugin)** — 官方 Codex 插件,封装 SandBase MCP 桥接器和引导式 Agent Skill。
69
+
70
+ ---
71
+
72
+ ## 一套可验证的 Agent 工作流
73
+
74
+ 连接后,让 Agent 按以下顺序工作,而不是直接猜测模型名称、输入字段或费用:
75
+
76
+ 1. 使用 `sandbase_discover` 按任务或能力搜索候选模型与 API。
77
+ 2. 使用 `sandbase_inspect` 读取当前输入 Schema、价格和执行要求。
78
+ 3. 确认模型、参数和可能费用后,再使用 `sandbase_run` 执行。
79
+ 4. 对异步任务使用 `sandbase_run_get` 查询状态和结果。
80
+ 5. 使用 `sandbase_runs` 查看最近运行、状态与实际费用。
81
+ 6. 使用 `sandbase_account` 检查账户余额。
82
+
83
+ 例如,你可以要求:
84
+
85
+ > 搜索适合生成产品演示图的模型。先比较输入字段和当前价格,只展示候选项,不要执行。
86
+
87
+ 选择模型后再明确要求执行。模型目录、Schema、价格和运行结果都会变化,因此应以工具当次返回的数据为准。不要把示例输出当作实时结果。
88
+
89
+ ---
90
+
91
+ ## 包含什么
92
+
93
+ | 分类 | 工具 | 能做什么 |
94
+ |------|------|----------|
95
+ | **网页搜索** | Google、Exa、Tavily、Scholar | 实时搜索任何信息 |
96
+ | **社交媒体** | Twitter/X、YouTube、Reddit、Instagram、TikTok、小红书、微博、B站 | 监控趋势、获取帖子、分析内容 |
97
+ | **网页抓取** | Firecrawl、Exa Content | 从任何公开网页提取数据 |
98
+ | **AI 模型** | GPT-4o、Claude、Gemini、DeepSeek、Qwen、Llama | 调用任何模型,无需自己管 Key |
99
+ | **图像生成** | Flux、DALL-E、Ideogram、Recraft | Logo、插画、原型图 |
100
+ | **视频生成** | Kling、MiniMax、Runway、Luma | 短视频、动画 |
101
+ | **音频** | ElevenLabs、Whisper | 文字转语音、语音转文字 |
102
+ | **电商** | 淘宝、Amazon | 选品调研、价格对比 |
103
+ | **金融** | 股票行情、公司信息 | 市场研究与分析 |
104
+
105
+ ---
106
+
107
+ ## 支持的客户端(25 个目标)
108
+
109
+ 兼容所有主流 AI 编程工具:
110
+
111
+ | 自动配置 | 手动配置 |
112
+ |---------|---------|
113
+ | Cursor、Cursor CLI | ChatGPT |
114
+ | Claude Code | Claude Desktop |
115
+ | Codex | |
116
+ | Kiro IDE、Kiro CLI | |
117
+ | Windsurf | |
118
+ | Gemini CLI | |
119
+ | Amp | |
120
+ | Warp | |
121
+ | OpenCode、Qwen Code、Kimi CLI | |
122
+ | Hermes、OpenClaw | |
123
+
124
+ 无需登录或修改任何文件,即可预览完整兼容性目录:
125
+
126
+ ```sh
127
+ npx -y https://github.com/sandbaseai/cli/releases/download/v0.1.17/sandbaseai-cli-0.1.17.tgz catalog --json
128
+ ```
129
+
130
+ ```sh
131
+ # 一次连接所有检测到的客户端
132
+ npx -y https://github.com/sandbaseai/cli/releases/download/v0.1.17/sandbaseai-cli-0.1.17.tgz connect
133
+
134
+ # 或者指定某个客户端
135
+ npx -y https://github.com/sandbaseai/cli/releases/download/v0.1.17/sandbaseai-cli-0.1.17.tgz connect --client cursor
136
+ ```
137
+
138
+ ### OpenClaw 快速开始
139
+
140
+ 直接指定 OpenClaw,并在使用前让 CLI 回读验证由 SandBase 管理的 MCP 服务与 Skill:
141
+
142
+ ```sh
143
+ npx -y https://github.com/sandbaseai/cli/releases/download/v0.1.17/sandbaseai-cli-0.1.17.tgz connect --client openclaw
144
+ npx -y https://github.com/sandbaseai/cli/releases/download/v0.1.17/sandbaseai-cli-0.1.17.tgz doctor --client openclaw
145
+ ```
146
+
147
+ 当 `doctor` 确认凭证、MCP bridge 和 Skill 均已配置后,重启 OpenClaw,
148
+ 再用自然语言提出一个需要 SandBase 的请求。如果 OpenClaw 中已经存在一个并非
149
+ SandBase 管理、但同样名为 `sandbase` 的 MCP 服务,安装器会保持原样,不会覆盖。
150
+ 以后若要移除由 SandBase 管理的 MCP 条目和本地凭证:
151
+
152
+ ```sh
153
+ npx -y https://github.com/sandbaseai/cli/releases/download/v0.1.17/sandbaseai-cli-0.1.17.tgz unregister --client openclaw
154
+ ```
155
+
156
+ OpenClaw 目前没有受支持的 Skill 移除命令,因此 `unregister` 会明确报告这一限制,
157
+ 并保留已经验证过身份的 SandBase Skill。
158
+
159
+ ### Hermes 快速开始
160
+
161
+ SandBase 可以在同一次授权事务中安装由它管理的 Hermes Skill 和本地 MCP 条目:
162
+
163
+ ```sh
164
+ npx -y https://github.com/sandbaseai/cli/releases/download/v0.1.17/sandbaseai-cli-0.1.17.tgz connect --client hermes
165
+ npx -y https://github.com/sandbaseai/cli/releases/download/v0.1.17/sandbaseai-cli-0.1.17.tgz doctor --client hermes
166
+ ```
167
+
168
+ `doctor` 会验证所有权明确的本地凭证、MCP 条目与 Skill。随后重启 Hermes,
169
+ 在新的客户端会话中确认原生发现,再使用 SandBase Skill 或 MCP 工具。如果已经存在
170
+ 一个并非 SandBase 管理、但同样名为 `sandbase` 的 MCP 条目,安装器会保持原样。
171
+ 若要只移除由 SandBase 管理的 Hermes 配置、Skill 和本地凭证,同时保留供其他客户端
172
+ 共用的 bridge:
173
+
174
+ ```sh
175
+ npx -y https://github.com/sandbaseai/cli/releases/download/v0.1.17/sandbaseai-cli-0.1.17.tgz unregister --client hermes
176
+ ```
177
+
178
+ 该集成已被独立收录于
179
+ [Hermes Atlas](https://github.com/ksimback/hermes-ecosystem) 和
180
+ [Awesome Hermes Agent](https://github.com/0xNyk/awesome-hermes-agent#integrations--bridges)。
181
+
182
+ ---
183
+
184
+ ## 工作原理
185
+
186
+ ```
187
+ ┌─────────────────┐ ┌───────────────┐ ┌────────────────────┐
188
+ │ 你的 Agent │ MCP │ 本地 Bridge │ HTTPS │ SandBase API │
189
+ │ (Cursor 等) │────────▶│ (按需启动) │────────▶│ 2,000+ 模型/API │
190
+ │ │◀────────│ │◀────────│ │
191
+ └─────────────────┘ └───────────────┘ └────────────────────┘
192
+ ```
193
+
194
+ 1. 运行 `connect` → 浏览器打开授权 → 你点击同意
195
+ 2. API Key 本地保存(权限 `0600`)
196
+ 3. 自动为你的客户端写入 MCP 配置
197
+ 4. Agent 按需调用工具。没有后台进程。
198
+
199
+ ---
200
+
201
+ ## 命令
202
+
203
+ ### CLI 命令
204
+
205
+ ```sh
206
+ sandbase connect [--client <name>] # 授权 + 配置
207
+ sandbase setup # 升级后:刷新本地 bridge 与 Skill,并测试连通性
208
+ sandbase doctor [--client <name>] # 本地检查 + 一次真实的 SandBase 往返请求
209
+ sandbase unregister [--client <name>] # 移除配置
210
+ sandbase catalog --json # 列出所有支持的客户端
211
+ ```
212
+
213
+ ### Agent 命令(Shell 通道,与 MCP 工具能力一致)
214
+
215
+ 没有 MCP、或 MCP 会话异常时,Agent 可以直接在 Shell 里使用同一套目录。凭据自动复用 `connect` 的浏览器登录结果(也可用 `SANDBASE_API_KEY` 或 `sandbase keys add -k <key>`)。
216
+
217
+ ```sh
218
+ sandbase discover -q "推特搜索" # 搜索;-t api|llm|multimodal|embedding|service
219
+ sandbase inspect sandbase_twitter_web_search_timeline # 参数、价格、可直接运行的命令
220
+ sandbase run sandbase_twitter_web_search_timeline -i '{"keyword":"AI agents"}'
221
+ sandbase run <视频工具> -i '{"prompt":"..."}' -w -o result.json # 带退避等待完成,结果写入文件
222
+ sandbase runs get -r <run_id> -w -o result.json # 续查长任务,不要重新运行
223
+ sandbase runs list | sandbase balance
224
+ ```
225
+
226
+ `-j` 输出 JSON;错误格式为 `{"error":{"code","message","hint"}}`,`hint` 给出下一步。退出码:`0` 成功或仍在运行,`1` 失败(含任务失败),`2` 参数错误。
227
+
228
+ `api.sandbase.ai` 不可达时,CLI 与 MCP bridge 会自动切换到 `www.sandbase.ai`;bridge 会继续展示 SandBase 工具,并返回可执行的错误提示,而不是让客户端丢掉整个 server。
229
+
230
+ ### MCP 工具(连接后你的 Agent 可以使用)
231
+
232
+ | 工具 | 用途 |
233
+ |------|------|
234
+ | `sandbase_discover` | 搜索全部 2,000+ 可用 AI 模型与 API |
235
+ | `sandbase_inspect` | 获取输入参数、定价和调用模板 |
236
+ | `sandbase_run` | 执行模型或 API |
237
+ | `sandbase_run_get` | 轮询异步任务状态/结果(视频生成等) |
238
+ | `sandbase_runs` | 查看最近的 API 调用记录和费用 |
239
+ | `sandbase_account` | 查看账户余额(免费,不扣费) |
240
+
241
+ **Agent 自动遵循的调用流程:**
242
+
243
+ ```
244
+ discover → inspect → run
245
+ ```
246
+
247
+ ```
248
+ 1. sandbase_discover(q: "推特搜索") → 找到匹配的工具
249
+ 2. sandbase_inspect(name: "twitter_timeline") → 获取参数定义 + 定价
250
+ 3. sandbase_run(name: "twitter_timeline", ...) → 执行并返回数据
251
+ ```
252
+
253
+ ---
254
+
255
+ ## 安全性
256
+
257
+ - **URL 和 CLI 参数中没有任何密钥** — OAuth device flow + PKCE
258
+ - **受限文件权限** — 凭据以 `0600` 存储
259
+ - **所有权感知更新** — 保留现有 JSONC 注释以及用户自行管理的 MCP 配置项
260
+ - **精确回滚** — 失败或执行 `unregister` 时,只移除由 SandBase 创建的配置
261
+ - **随时吊销** — [SandBase Dashboard](https://sandbase.ai/console/keys) 一键操作
262
+
263
+ ---
264
+
265
+ ## 开始使用
266
+
267
+ ```sh
268
+ npx -y https://github.com/sandbaseai/cli/releases/download/v0.1.17/sandbaseai-cli-0.1.17.tgz connect
269
+ ```
270
+
271
+ 然后让你的 Agent 做一些它以前做不到的事。
272
+
273
+ **[注册免费账号 →](https://sandbase.ai)**
274
+
275
+ 如果 SandBase 帮你节省了配置时间,欢迎[为项目点个 Star](https://github.com/sandbaseai/cli)——这会让更多 Agent 用户发现它。
276
+
277
+ ---
278
+
279
+ ## 链接
280
+
281
+ - [SandBase 平台](https://sandbase.ai)
282
+ - [文档](https://www.sandbase.ai/docs/)
283
+ - [官方 MCP Registry 收录](https://registry.modelcontextprotocol.io/v0.1/servers?search=io.github.sandbaseai%2Fcli)
284
+ - [Glama MCP Connector 收录](https://glama.ai/mcp/connectors/io.github.sandbaseai/cli)
285
+ - [官方 Registry 社区技术展示](https://github.com/modelcontextprotocol/registry/discussions/1584)
286
+ - 六工具实战指南:[中文](https://github.com/sandbaseai/cli/discussions/48) · [English](https://github.com/sandbaseai/cli/discussions/47)
287
+ - [VaultPlane MCP 目录收录](https://www.vaultplane.com/server/sandbase-cli)
288
+ - [AIMCP 目录收录](https://www.aimcp.info/zh/g/522d366e-114b-4d90-9f1a-552b4b3a9c86)
289
+ - [中国独立开发者项目(程序员版)收录](https://github.com/1c7/chinese-independent-developer/blob/master/pages/README-Programmer-Edition.md#sandbase---github)
290
+ - [npm 包](https://www.npmjs.com/package/@sandbaseai/cli)
291
+ - [控制台](https://sandbase.ai/console)
292
+
293
+ ## 开源协议
294
+
295
+ Apache-2.0
@@ -1,16 +1,42 @@
1
1
  #!/usr/bin/env node
2
- import { readFile } from "node:fs/promises";
2
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
3
3
  import { homedir } from "node:os";
4
4
  import { join } from "node:path";
5
5
  import { pathToFileURL } from "node:url";
6
6
 
7
7
  // This file is both the installed standalone bridge and the runtime loaded by
8
8
  // dist/cli.js. Keep the proxy implementation here so the two launchers cannot
9
- // drift.
9
+ // drift. It must stay dependency-free: it is copied to ~/.sandbase/bin.
10
+ //
11
+ // Agent-facing guarantees:
12
+ // 1. The SandBase server and its tools stay visible even when the network is
13
+ // down (initialize/tools/list are answered locally), so the client never
14
+ // silently drops the server.
15
+ // 2. Every tool failure reaches the model as an `isError` tool result that
16
+ // names the cause and the next step, instead of an opaque protocol error.
17
+ // 3. The API is reached only at api.sandbase.ai (the single API host); a
18
+ // transport failure keeps the server usable via the offline responder.
10
19
  const allowedClients = new Set(["codex", "claude-code", "cursor", "gemini-cli", "hermes", "openclaw", "opencode", "qwen-code", "windsurf", "cursor-cli", "kimi-cli", "kiro", "kiro-cli", "amp", "crush", "iflow-cli", "warp", "claude-desktop", "cowork", "antigravity", "trae", "qoder", "workbuddy", "pi"]);
20
+ const BILLING_URL = "https://www.sandbase.ai/console/billing";
21
+ const RECONNECT = "npx -y @sandbaseai/cli@latest connect";
22
+ // Tool calls get no bridge-side deadline (long synchronous tools must be able to
23
+ // finish); control-plane methods are bounded so offline detection stays quick.
24
+ const CONTROL_TIMEOUT_MS = 60_000;
25
+
26
+ // Used only when SandBase is unreachable and no tools/list was ever cached.
27
+ const offlineTools = [
28
+ { name: "sandbase_discover", title: "Discover", description: "Search SandBase models, APIs, and Agent Services by what you need (e.g. 'twitter posts', 'text to video', '小红书'). Call this before writing a scraper or declaring data inaccessible.", inputSchema: { type: "object", properties: { q: { type: "string" }, type: { type: "string", enum: ["llm", "api", "multimodal", "embedding", "service"] }, vendor: { type: "string" }, limit: { type: "integer" } }, additionalProperties: false } },
29
+ { name: "sandbase_inspect", title: "Inspect", description: "Get a tool's input schema, price, and a ready-to-run template. Always inspect before running.", inputSchema: { type: "object", properties: { name: { type: "string" } }, required: ["name"], additionalProperties: false } },
30
+ { name: "sandbase_run", title: "Run", description: "Execute a SandBase model, API, or Agent Service with arguments matching the inspected schema.", inputSchema: { type: "object", properties: { name: { type: "string" }, arguments: { type: "object" } }, required: ["name", "arguments"], additionalProperties: false } },
31
+ { name: "sandbase_run_get", title: "Get Run Result", description: "Get the status, cost, and output of an async run.", inputSchema: { type: "object", properties: { run_id: { type: "string" }, service_id: { type: "string" }, cursor: { type: "string" }, limit: { type: "integer" } }, required: ["run_id"], additionalProperties: false } },
32
+ { name: "sandbase_runs", title: "List Runs", description: "List recent runs with cost.", inputSchema: { type: "object", properties: { limit: { type: "integer" }, model: { type: "string" }, service_id: { type: "string" }, offset: { type: "integer" } }, additionalProperties: false } },
33
+ { name: "sandbase_account", title: "Account", description: "Check the SandBase balance. Free.", inputSchema: { type: "object", properties: {}, additionalProperties: false } },
34
+ { name: "sandbase_run_cancel", title: "Cancel Service Run", description: "Request cancellation of an Agent Service run.", inputSchema: { type: "object", properties: { service_id: { type: "string" }, run_id: { type: "string" }, idempotency_key: { type: "string" } }, required: ["service_id", "run_id", "idempotency_key"], additionalProperties: false } },
35
+ ];
11
36
 
12
37
  function bridgeError(message) { return new Error(message); }
13
38
  function responseError(id, message) { return JSON.stringify({ jsonrpc: "2.0", id, error: { code: -32000, message } }) + "\n"; }
39
+ function toolError(id, message) { return JSON.stringify({ jsonrpc: "2.0", id, result: { content: [{ type: "text", text: message }], isError: true } }) + "\n"; }
14
40
  function validEndpoint(value) {
15
41
  try {
16
42
  const url = new URL(value);
@@ -25,24 +51,68 @@ function parseCredential(raw, client) {
25
51
  if (record?.client !== client || typeof record?.credential !== "string" || !record.credential || !mcpUrl) throw bridgeError("SandBase credential is unavailable. Run sandbase connect again.");
26
52
  return { credential: record.credential, mcpUrl };
27
53
  }
28
- function emitPayload(text, contentType, output) {
29
- if (!text.trim()) return;
54
+ export function describeNetworkFailure(error) {
55
+ const code = error?.cause?.code || error?.code || "";
56
+ if (error?.name === "TimeoutError" || error?.name === "AbortError" || code === "UND_ERR_CONNECT_TIMEOUT" || code === "ETIMEDOUT") return "connection timed out";
57
+ if (code === "ENOTFOUND" || code === "EAI_AGAIN") return "DNS lookup failed";
58
+ if (code === "ECONNREFUSED") return "connection refused";
59
+ if (code === "ECONNRESET" || code === "UND_ERR_SOCKET") return "connection reset";
60
+ if (/CERT|SSL|TLS/i.test(code)) return `TLS error (${code})`;
61
+ return code ? `network error (${code})` : "network error";
62
+ }
63
+ /** True when the request provably never reached the server, so another host cannot duplicate work. */
64
+ export function isPreSendFailure(error) {
65
+ const code = error?.cause?.code || error?.code || "";
66
+ return ["UND_ERR_CONNECT_TIMEOUT", "ENOTFOUND", "EAI_AGAIN", "ECONNREFUSED", "EHOSTUNREACH", "ENETUNREACH", "EADDRNOTAVAIL"].includes(code) || /CERT|SSL|TLS/i.test(code);
67
+ }
68
+ /** Starting or cancelling billable work must never be replayed after it may have been sent. */
69
+ export function isIdempotentRequest(request) {
70
+ return request?.method !== "tools/call" || (request?.params?.name !== "sandbase_run" && request?.params?.name !== "sandbase_run_cancel");
71
+ }
72
+ export function hintFor(message) {
73
+ const text = String(message || "").toLowerCase();
74
+ // Auth first: "API key not found" is a sign-in problem, not a misspelled tool.
75
+ if (/unauthori[sz]ed|api key|credential|revoked|expired|authenticat|sign-in|signin/.test(text)) return `The SandBase sign-in is not valid. Ask the user to run \`${RECONNECT}\` in a terminal.`;
76
+ if (/insufficient (balance|credit|funds)|payment required|spending limit|top up/.test(text)) return `Tell the user their SandBase balance is insufficient; they can top up at ${BILLING_URL}.`;
77
+ if (/rate.?limit|too many requests|429/.test(text)) return "Rate limited: wait 10-30 seconds, then retry once.";
78
+ if (/run .*not found|task not found/.test(text)) return "Use the prediction_id/run_id returned by sandbase_run, or list recent runs with sandbase_runs. Agent Service runs also need service_id.";
79
+ if (/invalid service request|unknown tool|tool(?: '[^']*')? (?:was )?not found|model not found|tool name is required/.test(text)) return "Check the exact tool name with sandbase_discover (names look like sandbase_twitter_web_search_timeline), then sandbase_inspect it.";
80
+ if (/invalid (params|arguments|input)|is required|schema|must be|unexpected field|additional propert/.test(text)) return "Call sandbase_inspect for this tool and pass exactly the fields in its inputSchema.";
81
+ if (/capability call failed|upstream|provider|bad gateway|timeout|unavailable/.test(text)) return "The upstream provider failed. Retry once; if it fails again, pick another tool from sandbase_discover.";
82
+ return "";
83
+ }
84
+ function httpFailure(status, text, host) {
85
+ let detail = "";
86
+ try { const parsed = JSON.parse(text); const e = parsed?.error; detail = typeof e === "string" ? e : typeof e?.message === "string" ? e.message : typeof parsed?.message === "string" ? parsed.message : ""; } catch { /* non-JSON gateway body is never forwarded */ }
87
+ const suffix = detail ? `: ${detail.slice(0, 300)}` : "";
88
+ if (status === 401) return `SandBase rejected the saved sign-in (401)${suffix}. Ask the user to run \`${RECONNECT}\` in a terminal to sign in again.`;
89
+ if (status === 402) return `SandBase balance is insufficient or a spending limit was reached (402)${suffix}. The user can top up at ${BILLING_URL}.`;
90
+ if (status === 403) return `This SandBase credential is not allowed for this request (403)${suffix}. Ask the user to run \`${RECONNECT}\`.`;
91
+ if (status === 429) return `SandBase rate limit reached (429)${suffix}. Wait 10-30 seconds, then retry once.`;
92
+ if (status >= 500) return `SandBase returned HTTP ${status} from ${host}${suffix}. Temporary server error: retry in a minute; the user can run \`sandbase doctor\` if it persists.`;
93
+ return `SandBase MCP request failed (${status}) at ${host}${suffix}.${hintFor(detail) ? ` ${hintFor(detail)}` : ""}`;
94
+ }
95
+ function payloadsOf(text, contentType) {
96
+ const out = [];
97
+ if (!text.trim()) return out;
30
98
  if (contentType.includes("text/event-stream")) {
31
99
  for (const line of text.split(/\r?\n/)) {
32
100
  if (!line.startsWith("data:")) continue;
33
101
  const payload = line.slice(5).trim();
34
- if (payload && payload !== "[DONE]") output.write(payload + "\n");
102
+ if (!payload || payload === "[DONE]") continue;
103
+ try { out.push(JSON.parse(payload)); } catch { /* Never forward an untrusted non-JSON body to the client. */ }
35
104
  }
36
- return;
105
+ return out;
37
106
  }
38
- try { output.write(JSON.stringify(JSON.parse(text)) + "\n"); }
107
+ try { out.push(JSON.parse(text)); return out; }
39
108
  catch {
40
109
  for (const line of text.split(/\r?\n/)) {
41
110
  const payload = line.trim();
42
111
  if (!payload) continue;
43
- try { output.write(JSON.stringify(JSON.parse(payload)) + "\n"); } catch { /* Never forward an untrusted non-JSON body to the client. */ }
112
+ try { out.push(JSON.parse(payload)); } catch { /* Never forward an untrusted non-JSON body to the client. */ }
44
113
  }
45
114
  }
115
+ return out;
46
116
  }
47
117
 
48
118
  export async function runMCPBridge(options = {}) {
@@ -54,33 +124,81 @@ export async function runMCPBridge(options = {}) {
54
124
  const fetchImpl = options.fetchImpl || globalThis.fetch;
55
125
  if (!allowedClients.has(client)) throw bridgeError("SandBase bridge client is invalid.");
56
126
 
57
- const store = join(env.SANDBASE_HOME || join(homedir(), ".sandbase"), "credentials.json");
127
+ const home = env.SANDBASE_HOME || join(homedir(), ".sandbase");
58
128
  let raw;
59
- try { raw = await readFile(store, "utf8"); }
129
+ try { raw = await readFile(join(home, "credentials.json"), "utf8"); }
60
130
  catch { throw bridgeError("SandBase credential is unavailable. Run sandbase connect again."); }
61
131
  const record = parseCredential(raw, client);
132
+ const url = record.mcpUrl;
133
+ const host = new URL(url).host;
134
+ const toolsCache = join(home, "cache", "tools.json");
62
135
  let buffer = Buffer.alloc(0);
63
136
  let session;
64
137
 
138
+ const cachedTools = async () => { try { const value = JSON.parse(await readFile(toolsCache, "utf8")); if (Array.isArray(value?.tools) && value.tools.length) return value.tools; } catch { /* fall back to the bundled list */ } return offlineTools; };
139
+ const rememberTools = async tools => { if (!Array.isArray(tools) || !tools.length) return; try { await mkdir(join(home, "cache"), { recursive: true, mode: 0o700 }); const tmp = `${toolsCache}.tmp-${process.pid}`; await writeFile(tmp, JSON.stringify({ savedAt: new Date().toISOString(), tools }) + "\n", { mode: 0o600 }); await rename(tmp, toolsCache); } catch { /* cache is best effort */ } };
140
+
141
+ const offline = async (request, reason) => {
142
+ const id = request.id;
143
+ if (id === undefined) return;
144
+ const message = `SandBase is unreachable from this machine (${reason}). Tell the user to check their network, proxy, or VPN, then run \`sandbase doctor\` in a terminal. Do not retry this call until connectivity is restored.`;
145
+ if (request.method === "initialize") {
146
+ const version = typeof request.params?.protocolVersion === "string" ? request.params.protocolVersion : "2025-06-18";
147
+ output.write(JSON.stringify({ jsonrpc: "2.0", id, result: { protocolVersion: version, capabilities: { tools: { listChanged: false } }, serverInfo: { name: "sandbase", title: "SandBase", version: "bridge-offline" }, instructions: `SandBase tools are available but the service is currently unreachable (${reason}). Tool calls return an error with the fix until connectivity is restored.` } }) + "\n");
148
+ } else if (request.method === "tools/list") output.write(JSON.stringify({ jsonrpc: "2.0", id, result: { tools: await cachedTools() } }) + "\n");
149
+ else if (request.method === "tools/call") output.write(toolError(id, message));
150
+ else if (request.method === "ping") output.write(JSON.stringify({ jsonrpc: "2.0", id, result: {} }) + "\n");
151
+ else output.write(responseError(id, message));
152
+ };
153
+
154
+ const deliver = async (request, payload) => {
155
+ if (request.method === "tools/call" && payload && typeof payload === "object" && payload.error && payload.id === request.id) {
156
+ // Tool execution failures must be visible to the model so it can self-correct.
157
+ const message = typeof payload.error.message === "string" && payload.error.message ? payload.error.message : "SandBase tool call failed";
158
+ const hint = hintFor(message);
159
+ output.write(toolError(request.id, hint ? `${message}. ${hint}` : message));
160
+ return;
161
+ }
162
+ if (request.method === "tools/list" && payload?.id === request.id && Array.isArray(payload?.result?.tools)) await rememberTools(payload.result.tools);
163
+ output.write(JSON.stringify(payload) + "\n");
164
+ };
165
+
65
166
  const forward = async line => {
66
167
  let request;
67
168
  try { request = JSON.parse(line); } catch { return; }
68
169
  if (!request || typeof request !== "object" || Array.isArray(request)) return;
170
+ const idempotent = isIdempotentRequest(request);
171
+ let response;
69
172
  try {
70
173
  const headers = { authorization: `Bearer ${record.credential}`, "content-type": "application/json", accept: "application/json, text/event-stream" };
71
174
  if (session) headers["mcp-session-id"] = session;
72
- const response = await fetchImpl(record.mcpUrl, { method: "POST", headers, body: JSON.stringify(request), ...(signal ? { signal } : {}) });
73
- const nextSession = response.headers.get("mcp-session-id");
74
- if (nextSession) session = nextSession;
75
- const text = await response.text();
76
- if (!response.ok) {
77
- if (request.id !== undefined) output.write(responseError(request.id, `SandBase MCP request failed (${response.status})`));
175
+ const timeout = request.method === "tools/call" ? undefined : AbortSignal.timeout(CONTROL_TIMEOUT_MS);
176
+ const combined = signal && timeout && typeof AbortSignal.any === "function" ? AbortSignal.any([signal, timeout]) : signal || timeout;
177
+ response = await fetchImpl(url, { method: "POST", headers, body: JSON.stringify(request), ...(combined ? { signal: combined } : {}) });
178
+ } catch (error) {
179
+ if (signal?.aborted) return;
180
+ const reason = describeNetworkFailure(error);
181
+ if (!idempotent && !isPreSendFailure(error)) {
182
+ // The run may already be executing; blindly retrying would bill twice.
183
+ if (request.id !== undefined) output.write(toolError(request.id, `The request to ${host} was interrupted after it was sent (${reason}); a run may have started. Do not call sandbase_run again yet: check sandbase_runs for the new run and poll it with sandbase_run_get.`));
78
184
  return;
79
185
  }
80
- emitPayload(text, response.headers.get("content-type") || "", output);
81
- } catch {
82
- if (!signal?.aborted && request.id !== undefined) output.write(responseError(request.id, "SandBase MCP is unavailable"));
186
+ // Transport failure: keep the server usable (tools stay listed, calls get an actionable error).
187
+ await offline(request, `${host}: ${reason}`);
188
+ return;
189
+ }
190
+ const text = await response.text();
191
+ const nextSession = response.headers.get("mcp-session-id");
192
+ if (nextSession) session = nextSession;
193
+ if (!response.ok) {
194
+ if (request.id === undefined) return;
195
+ // Never let a server error during the handshake make the client drop SandBase.
196
+ if (response.status >= 500 && (request.method === "initialize" || request.method === "tools/list")) { await offline(request, `${host}: HTTP ${response.status}`); return; }
197
+ const message = httpFailure(response.status, text, host);
198
+ output.write(request.method === "tools/call" ? toolError(request.id, message) : responseError(request.id, message));
199
+ return;
83
200
  }
201
+ for (const payload of payloadsOf(text, response.headers.get("content-type") || "")) await deliver(request, payload);
84
202
  };
85
203
 
86
204
  const stopInput = () => { if (typeof input.destroy === "function") input.destroy(); };
@@ -1,5 +1,6 @@
1
1
  export declare const a1Clients: readonly ["opencode", "qwen-code", "windsurf"];
2
2
  export type A1Client = typeof a1Clients[number];
3
+ export declare const OWNED_MCP_ENDPOINTS: readonly ["https://api.sandbase.ai/v1/mcp", "https://sandbase.ai/v1/mcp", "https://www.sandbase.ai/v1/mcp"];
3
4
  export declare function isA1Client(client: string): client is A1Client;
4
5
  export interface A1CommandResult {
5
6
  code: number | null;
@@ -5,6 +5,16 @@ import { applyEdits, modify, parse } from "jsonc-parser";
5
5
  import { atomicWrite, backup, readOptional, restore } from "./fs-safe.js";
6
6
  import { configPath, sandbaseHome } from "./paths.js";
7
7
  export const a1Clients = ["opencode", "qwen-code", "windsurf"];
8
+ // Endpoints an installed `sandbase` entry may legitimately point at, used to
9
+ // prove SandBase ownership before touching a client config. The canonical API
10
+ // host leads; the bare and www hosts stay recognized so configs written by
11
+ // older CLI versions (before the api.sandbase.ai migration) are not rejected
12
+ // as foreign on upgrade.
13
+ export const OWNED_MCP_ENDPOINTS = [
14
+ "https://api.sandbase.ai/v1/mcp",
15
+ "https://sandbase.ai/v1/mcp",
16
+ "https://www.sandbase.ai/v1/mcp",
17
+ ];
8
18
  export function isA1Client(client) { return a1Clients.includes(client); }
9
19
  const executable = { opencode: "opencode2", "qwen-code": "qwen" };
10
20
  export const defaultA1Runner = async (client, args) => {
@@ -88,7 +98,7 @@ async function inspectConfig(client, env = process.env, expectedBridge, expected
88
98
  }
89
99
  const servers = root.mcpServers === undefined ? undefined : objectMap(root.mcpServers, client);
90
100
  const entry = servers?.sandbase;
91
- const endpoints = [...new Set(["https://sandbase.ai/v1/mcp", identity?.endpoint?.replace(/\/$/, ""), expectedEndpoint?.replace(/\/$/, "")].filter((value) => !!value))];
101
+ const endpoints = [...new Set([...OWNED_MCP_ENDPOINTS, identity?.endpoint?.replace(/\/$/, ""), expectedEndpoint?.replace(/\/$/, "")].filter((value) => !!value))];
92
102
  const owned = client === "qwen-code" ? qwenOwned(entry, bridges) : windsurfOwned(entry, endpoints, env);
93
103
  if (entry === undefined)
94
104
  return { state: "missing", detail: "SandBase is not registered" };
@@ -202,7 +212,7 @@ export async function installA1(client, bridge, credential, mcpUrl, env = proces
202
212
  const root = parseObject(text, client);
203
213
  const servers = root.mcpServers === undefined ? {} : objectMap(root.mcpServers, client);
204
214
  const existing = servers.sandbase;
205
- if (existing !== undefined && !windsurfOwned(existing, ["https://sandbase.ai/v1/mcp", mcpUrl.replace(/\/$/, "")], env))
215
+ if (existing !== undefined && !windsurfOwned(existing, [...OWNED_MCP_ENDPOINTS, mcpUrl.replace(/\/$/, "")], env))
206
216
  throw new Error("windsurf: the sandbase entry is not SandBase-owned; no changes were made");
207
217
  const desired = { serverUrl: mcpUrl, headers: { Authorization: windsurfAuthorization(env) } };
208
218
  const next = applyJsonc(text, ["mcpServers", "sandbase"], desired);
@@ -72,8 +72,10 @@ export function detectClient(client) {
72
72
  }
73
73
  const start = "# >>> sandbase managed >>>", end = "# <<< sandbase managed <<<";
74
74
  function block(client, bridge) {
75
+ // tool_timeout_sec: Codex cancels tool calls after 60s by default; a sync model
76
+ // (e.g. a long LLM or scrape call) can legitimately take longer.
75
77
  if (client === "codex")
76
- return `${start}\n[mcp_servers.sandbase]\ncommand = "node"\nargs = ["${bridge.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}", "--client", "codex"]\nenv = { SANDBASE_CLI_MANAGED = "1" }\n${end}`;
78
+ return `${start}\n[mcp_servers.sandbase]\ncommand = "node"\nargs = ["${bridge.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}", "--client", "codex"]\ntool_timeout_sec = 1800\nenv = { SANDBASE_CLI_MANAGED = "1" }\n${end}`;
77
79
  return ` ${start}\n sandbase:\n command: node\n args:\n - ${JSON.stringify(bridge)}\n - --client\n - ${client}\n ${end}`;
78
80
  }
79
81
  function managedText(raw, value) { const re = new RegExp(`${start.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}[\\s\\S]*?${end.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`, "m"); return re.test(raw) ? raw.replace(re, value) : raw.replace(/\s*$/, "") + (raw.trim() ? "\n\n" : "") + value + "\n"; }