@sandbaseai/cli 0.1.14 → 0.3.6
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.
- package/LICENSE +200 -2
- package/README.de.md +143 -0
- package/README.es.md +146 -0
- package/README.fr.md +143 -0
- package/README.ja.md +209 -0
- package/README.ko.md +148 -0
- package/README.md +377 -6
- package/README.pt-BR.md +146 -0
- package/README.zh-CN.md +295 -0
- package/assets/mcp-bridge.mjs +142 -19
- package/dist/a1-adapters.d.ts +1 -0
- package/dist/a1-adapters.js +12 -2
- package/dist/adapters/index.js +3 -1
- package/dist/agent/client.d.ts +79 -0
- package/dist/agent/client.js +274 -0
- package/dist/agent/commands.d.ts +28 -0
- package/dist/agent/commands.js +627 -0
- package/dist/agent/probe.d.ts +6 -0
- package/dist/agent/probe.js +25 -0
- package/dist/agent/update.d.ts +5 -0
- package/dist/agent/update.js +64 -0
- package/dist/cli.js +78 -46
- package/dist/commands.d.ts +6 -0
- package/dist/commands.js +82 -6
- package/dist/skills.js +2 -2
- package/llms-install.md +76 -0
- package/package.json +30 -5
- package/skills/sandbase/SKILL.md +263 -0
- package/skills/sandbase/skill.json +19 -0
- package/assets/skills/sandbase/SKILL.md +0 -201
|
@@ -0,0 +1,627 @@
|
|
|
1
|
+
// Shell transport for agents: discover → inspect → run → runs get, plus
|
|
2
|
+
// balance and key management. Mirrors the sandbase_* MCP tools one-to-one so an
|
|
3
|
+
// agent without MCP (or with a broken MCP session) still has a working path,
|
|
4
|
+
// and so large results can go straight to disk with -o instead of the context.
|
|
5
|
+
import { constants as fsConstants } from "node:fs";
|
|
6
|
+
import { access, readFile, rm, stat, writeFile } from "node:fs/promises";
|
|
7
|
+
import { basename, dirname, extname, resolve as resolvePath } from "node:path";
|
|
8
|
+
import { parseArgs } from "node:util";
|
|
9
|
+
import { atomicWrite } from "../fs-safe.js";
|
|
10
|
+
import { CONNECT_COMMAND, describeNetworkFailure, httpError, keyFilePath, keysUrl, readStoredKey, resolveEndpoint, SandBaseError, SandBaseMCPClient, toolOutput, validMcpUrl } from "./client.js";
|
|
11
|
+
import { updateNotice } from "./update.js";
|
|
12
|
+
export const agentCommands = ["discover", "inspect", "run", "runs", "upload", "balance", "keys"];
|
|
13
|
+
export function isAgentCommand(value) { return agentCommands.includes(value); }
|
|
14
|
+
export const agentUsage = `SandBase agent commands (same capabilities as the sandbase_* MCP tools):
|
|
15
|
+
sandbase discover -q "<what you need>" [-t llm|api|multimodal|embedding|service] [--vendor <slug>] [-l 10] [-j]
|
|
16
|
+
sandbase inspect <tool_name> [-j]
|
|
17
|
+
sandbase run <tool_name> [-i '<json>' | -f input.json] [-w] [--timeout 300] [-o result.json] [-j]
|
|
18
|
+
sandbase runs get -r <run_id> [--service <svc_id>] [-w] [--timeout 300] [-o result.json] [-j]
|
|
19
|
+
sandbase runs list [-l 10] [--model <model>] [--service <svc_id>] [-j]
|
|
20
|
+
sandbase upload <file> [-j] (local image/audio/video → public URL for tools that take a URL)
|
|
21
|
+
sandbase balance [-j]
|
|
22
|
+
sandbase keys add -k - (reads the key from stdin) | keys list | keys remove
|
|
23
|
+
Global: --client <client> picks a connected client's credential; SANDBASE_API_KEY overrides all; -j prints JSON.`;
|
|
24
|
+
// Only an explicit failure ends a run as failed; any status we do not know
|
|
25
|
+
// (IN_QUEUE, created, unknown, …) is treated as still running so agents poll
|
|
26
|
+
// instead of giving up or paying for a re-run.
|
|
27
|
+
const SUCCEEDED = new Set(["completed", "succeeded", "success", "done"]);
|
|
28
|
+
const FAILED = new Set(["failed", "failure", "error", "errored", "cancelled", "canceled", "timeout", "timed_out", "expired", "rejected", "blocked", "stopped"]);
|
|
29
|
+
function phaseOf(status) { const value = String(status ?? "").toLowerCase(); return SUCCEEDED.has(value) ? "succeeded" : FAILED.has(value) ? "failed" : "running"; }
|
|
30
|
+
function hasOutput(view) { return view.output !== undefined && view.output !== null; }
|
|
31
|
+
class Output {
|
|
32
|
+
json;
|
|
33
|
+
out;
|
|
34
|
+
err;
|
|
35
|
+
notes = [];
|
|
36
|
+
constructor(json, out, err) {
|
|
37
|
+
this.json = json;
|
|
38
|
+
this.out = out;
|
|
39
|
+
this.err = err;
|
|
40
|
+
}
|
|
41
|
+
print(text) { this.out(text); }
|
|
42
|
+
data(value) { this.out(JSON.stringify(this.notes.length ? { ...value, notes: this.notes } : value, null, 2)); }
|
|
43
|
+
error(error) {
|
|
44
|
+
if (this.json)
|
|
45
|
+
this.out(JSON.stringify({ error: { code: error.code, message: error.message, ...(error.hint ? { hint: error.hint } : {}) }, ...(error.runId ? { run_id: error.runId } : {}), ...(this.notes.length ? { notes: this.notes } : {}) }, null, 2));
|
|
46
|
+
else
|
|
47
|
+
this.err(`Error [${error.code}]: ${error.message}${error.runId ? `\nRun: ${error.runId}` : ""}${error.hint ? `\nNext: ${error.hint}` : ""}`);
|
|
48
|
+
}
|
|
49
|
+
notice(text) { if (this.json)
|
|
50
|
+
this.notes.push(text);
|
|
51
|
+
else
|
|
52
|
+
this.err(text); }
|
|
53
|
+
/** Always stderr (also in -j mode), so stdout stays parseable. */
|
|
54
|
+
progress(text) { this.err(text); }
|
|
55
|
+
}
|
|
56
|
+
function truncate(value, width) { const flat = value.replace(/\s+/g, " ").trim(); return flat.length > width ? `${flat.slice(0, width - 1)}…` : flat; }
|
|
57
|
+
function table(headers, rows) {
|
|
58
|
+
const widths = headers.map((header, i) => Math.max(header.length, ...rows.map(row => (row[i] || "").length)));
|
|
59
|
+
const line = (cells) => cells.map((cell, i) => i === cells.length - 1 ? cell : cell.padEnd(widths[i])).join(" ").trimEnd();
|
|
60
|
+
return [line(headers), ...rows.map(line)].join("\n");
|
|
61
|
+
}
|
|
62
|
+
function trimNumber(value) { const text = String(value); return /^-?\d+(\.\d+)?$/.test(text) ? String(Number(text)) : text; }
|
|
63
|
+
export function formatPrice(pricing) {
|
|
64
|
+
if (!pricing || typeof pricing !== "object")
|
|
65
|
+
return "see inspect";
|
|
66
|
+
const p = pricing;
|
|
67
|
+
if (p.input_per_million !== undefined || p.output_per_million !== undefined)
|
|
68
|
+
return `$${trimNumber(p.input_per_million ?? "?")}/$${trimNumber(p.output_per_million ?? "?")} per 1M tok`;
|
|
69
|
+
if (p.base_price !== undefined && Number(p.base_price) > 0)
|
|
70
|
+
return `$${trimNumber(p.base_price)}/call`;
|
|
71
|
+
if (typeof p.formula === "string" && p.formula)
|
|
72
|
+
return "formula (see inspect)";
|
|
73
|
+
return "see inspect";
|
|
74
|
+
}
|
|
75
|
+
function hintLines(hints) {
|
|
76
|
+
if (!hints)
|
|
77
|
+
return [];
|
|
78
|
+
if (Array.isArray(hints))
|
|
79
|
+
return hints.filter(item => item !== undefined && item !== null).map(item => typeof item === "string" ? item : JSON.stringify(item));
|
|
80
|
+
if (typeof hints === "object")
|
|
81
|
+
return Object.entries(hints).map(([key, value]) => `${key}: ${typeof value === "string" ? value : JSON.stringify(value)}`);
|
|
82
|
+
return [String(hints)];
|
|
83
|
+
}
|
|
84
|
+
function printHints(out, ...sources) { const lines = sources.flatMap(hintLines); if (lines.length)
|
|
85
|
+
out.print(["", "Hints:", ...lines.map(line => ` - ${line}`)].join("\n")); }
|
|
86
|
+
/**
|
|
87
|
+
* Files the run produced. The server returns media outputs as `[{url, …}]`
|
|
88
|
+
* (content_type is only added when it can be inferred), so an entry counts as a
|
|
89
|
+
* file when it has a `url` and carries no content of its own. A scraped page's
|
|
90
|
+
* `{url, markdown}`, a tweet row, or a nested avatar is content, not a file.
|
|
91
|
+
*/
|
|
92
|
+
export function generatedFiles(output) {
|
|
93
|
+
const isUrl = (value) => typeof value === "string" && /^https?:\/\/\S+$/.test(value);
|
|
94
|
+
// Keys that make an object a data row rather than a produced file.
|
|
95
|
+
const contentKeys = ["text", "markdown", "md", "html", "content", "title", "body", "snippet", "caption", "summary", "data", "items", "results", "children", "comments", "author", "user"];
|
|
96
|
+
const fileEntry = (entry) => {
|
|
97
|
+
if (isUrl(entry))
|
|
98
|
+
return entry;
|
|
99
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry))
|
|
100
|
+
return undefined;
|
|
101
|
+
const record = entry;
|
|
102
|
+
if (!isUrl(record.url))
|
|
103
|
+
return undefined;
|
|
104
|
+
return contentKeys.some(key => record[key] !== undefined) ? undefined : record.url;
|
|
105
|
+
};
|
|
106
|
+
const list = (value) => {
|
|
107
|
+
const entries = Array.isArray(value) ? value : [value];
|
|
108
|
+
return entries.map(fileEntry).filter((url) => !!url);
|
|
109
|
+
};
|
|
110
|
+
let files = list(output);
|
|
111
|
+
// {images: [{url}], seed: 1} / {video: {url}}: a media-named key holds the files.
|
|
112
|
+
if (!files.length && output && typeof output === "object" && !Array.isArray(output)) {
|
|
113
|
+
for (const [key, value] of Object.entries(output)) {
|
|
114
|
+
if (/^(image|video|audio|file|media|clip|frame)s?$/i.test(key))
|
|
115
|
+
files = files.concat(list(value));
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return [...new Set(files)].slice(0, 20);
|
|
119
|
+
}
|
|
120
|
+
function shellQuote(value) { return `'${value.replace(/'/g, `'\\''`)}'`; }
|
|
121
|
+
const commonOptions = { json: { type: "boolean", short: "j" }, client: { type: "string" }, help: { type: "boolean", short: "h" } };
|
|
122
|
+
function parse(argv, options) {
|
|
123
|
+
try {
|
|
124
|
+
return parseArgs({ args: argv, options: { ...commonOptions, ...options }, allowPositionals: true, strict: true });
|
|
125
|
+
}
|
|
126
|
+
catch (error) {
|
|
127
|
+
throw new SandBaseError("USAGE", error instanceof Error ? error.message : "Invalid arguments.", `Usage:\n${agentUsage}`);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
function parseJsonObject(text, label) {
|
|
131
|
+
let value;
|
|
132
|
+
try {
|
|
133
|
+
value = JSON.parse(text);
|
|
134
|
+
}
|
|
135
|
+
catch {
|
|
136
|
+
throw new SandBaseError("USAGE", `${label} is not valid JSON.`, `Use ${label === "--input" ? "-i" : "-f"} '{"key": "value"}' with the fields from \`sandbase inspect <tool_name>\`.`);
|
|
137
|
+
}
|
|
138
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
139
|
+
throw new SandBaseError("USAGE", `${label} must be a JSON object.`, "Pass an object such as '{\"prompt\": \"...\"}'.");
|
|
140
|
+
return value;
|
|
141
|
+
}
|
|
142
|
+
function positiveSeconds(value, fallback) {
|
|
143
|
+
if (value === undefined)
|
|
144
|
+
return fallback;
|
|
145
|
+
const seconds = Number(value);
|
|
146
|
+
if (!Number.isFinite(seconds) || seconds <= 0)
|
|
147
|
+
throw new SandBaseError("USAGE", "--timeout must be a positive number of seconds.");
|
|
148
|
+
return Math.min(seconds, 3600);
|
|
149
|
+
}
|
|
150
|
+
async function writeResult(path, output) {
|
|
151
|
+
await writeFile(path, typeof output === "string" ? output : `${JSON.stringify(output ?? null, null, 2)}\n`, "utf8");
|
|
152
|
+
}
|
|
153
|
+
function runViewFromRun(data, tool) {
|
|
154
|
+
const runId = (data.run_id ?? data.prediction_id ?? data.taskId ?? data.id);
|
|
155
|
+
// No status and no run id means a synchronous tool answered directly (possibly plain text).
|
|
156
|
+
const syncOutput = data.status === undefined && !runId;
|
|
157
|
+
const output = data.output !== undefined ? data.output : syncOutput ? (Object.keys(data).length === 1 && "text" in data ? data.text : data) : undefined;
|
|
158
|
+
return { ...(runId ? { run_id: String(runId) } : {}), ...(data.service_id ? { service_id: String(data.service_id) } : {}), tool, status: String(data.status ?? (syncOutput ? "completed" : "running")), ...(output !== undefined ? { output } : {}), ...(data.error !== undefined ? { error: data.error } : {}), ...(data.cost !== undefined ? { cost: data.cost } : {}), ...(data.cost_status !== undefined ? { cost_status: data.cost_status } : {}), ...(data.hints !== undefined ? { hints: data.hints } : {}) };
|
|
159
|
+
}
|
|
160
|
+
/** Fail before spending money when -o cannot be written. */
|
|
161
|
+
async function assertWritableOutput(path) {
|
|
162
|
+
if (!path)
|
|
163
|
+
return;
|
|
164
|
+
try {
|
|
165
|
+
await access(dirname(resolvePath(path)), fsConstants.W_OK);
|
|
166
|
+
}
|
|
167
|
+
catch {
|
|
168
|
+
throw new SandBaseError("USAGE", `Cannot write the output file ${path}: its directory does not exist or is not writable.`, "Pick a writable path for -o; nothing was run.");
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
/** After a run was accepted, every failure must still tell the agent how to resume it instead of re-running (and paying) again. */
|
|
172
|
+
function withRunContext(error, view) {
|
|
173
|
+
const resume = `sandbase runs get -r ${view.run_id}${view.service_id ? ` --service ${view.service_id}` : ""} -w`;
|
|
174
|
+
if (error instanceof SandBaseError)
|
|
175
|
+
return new SandBaseError(error.code, error.message, `${error.hint ? `${error.hint} ` : ""}The run ${view.run_id} was already started; resume with \`${resume}\` instead of running it again.`, error.status, view.run_id);
|
|
176
|
+
return new SandBaseError("TOOL_ERROR", error instanceof Error ? error.message : "Unknown failure", `The run ${view.run_id} was already started; resume with \`${resume}\`.`, undefined, view.run_id);
|
|
177
|
+
}
|
|
178
|
+
/** One status read: sandbase_run_get for status/cost, then MCP tasks/result for the output of finished model runs. */
|
|
179
|
+
async function readRun(client, runId, serviceId) {
|
|
180
|
+
const { data } = await client.tool("sandbase_run_get", { run_id: runId, ...(serviceId ? { service_id: serviceId } : {}) });
|
|
181
|
+
const view = { run_id: runId, ...(serviceId ? { service_id: serviceId } : {}), status: String(data.status ?? "unknown"), ...(data.model ? { tool: String(data.model) } : {}), ...(data.cost !== undefined ? { cost: data.cost } : {}), ...(data.hints !== undefined ? { hints: data.hints } : {}) };
|
|
182
|
+
if (data.output !== undefined && data.output !== null)
|
|
183
|
+
view.output = data.output;
|
|
184
|
+
else if (serviceId && (data.items !== undefined || data.result !== undefined))
|
|
185
|
+
view.output = data.items ?? data.result;
|
|
186
|
+
if (data.error !== undefined && data.error !== null)
|
|
187
|
+
view.error = data.error;
|
|
188
|
+
if (!serviceId && phaseOf(view.status) !== "running" && !hasOutput(view)) {
|
|
189
|
+
try {
|
|
190
|
+
const result = await client.rpc("tasks/result", { taskId: runId });
|
|
191
|
+
if (!result?.task) {
|
|
192
|
+
const task = toolOutput(result).data;
|
|
193
|
+
if (task.output !== undefined && task.output !== null)
|
|
194
|
+
view.output = task.output;
|
|
195
|
+
if (task.error !== undefined && task.error !== null && view.error === undefined)
|
|
196
|
+
view.error = task.error;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
catch { /* older servers: status and cost are still accurate */ }
|
|
200
|
+
}
|
|
201
|
+
return view;
|
|
202
|
+
}
|
|
203
|
+
async function pollRun(client, initial, timeoutSeconds, deps) {
|
|
204
|
+
if (!initial.run_id)
|
|
205
|
+
return initial;
|
|
206
|
+
const deadline = deps.now() + timeoutSeconds * 1000;
|
|
207
|
+
let view = initial, delay = 1000, emptyCompletions = 0;
|
|
208
|
+
for (;;) {
|
|
209
|
+
const phase = phaseOf(view.status);
|
|
210
|
+
// A completed media run reports no output while its files are transferred:
|
|
211
|
+
// keep waiting for those until the timeout; other empty completions (e.g. no
|
|
212
|
+
// stored output) settle after a few reads.
|
|
213
|
+
const transferring = phase === "succeeded" && !hasOutput(view) && /still being transferred/i.test(JSON.stringify(view.hints ?? ""));
|
|
214
|
+
if (phase === "failed" || (phase === "succeeded" && !transferring && (hasOutput(view) || emptyCompletions >= 3)))
|
|
215
|
+
return view;
|
|
216
|
+
if (phase === "succeeded" && !transferring)
|
|
217
|
+
emptyCompletions++;
|
|
218
|
+
if (deps.now() + delay > deadline)
|
|
219
|
+
return { ...view, timed_out: true };
|
|
220
|
+
await deps.sleep(delay);
|
|
221
|
+
delay = Math.min(Math.round(delay * 1.5), 10_000);
|
|
222
|
+
const next = await readRun(client, initial.run_id, initial.service_id);
|
|
223
|
+
const tool = view.tool ?? next.tool;
|
|
224
|
+
// Hints describe the latest state only; a stale "still in progress" must not survive completion.
|
|
225
|
+
const { hints: _staleHints, ...rest } = view;
|
|
226
|
+
view = { ...rest, ...next, ...(tool ? { tool } : {}) };
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
function printRun(out, view, outputFile) {
|
|
230
|
+
const phase = phaseOf(view.status);
|
|
231
|
+
const lines = [`Run: ${view.run_id ?? "(synchronous)"}${view.tool ? ` tool=${view.tool}` : ""}`, `Status: ${view.status}${view.timed_out ? " (still running when --timeout elapsed)" : ""}`];
|
|
232
|
+
if (view.cost !== undefined && view.cost !== null && view.cost !== "")
|
|
233
|
+
lines.push(`Cost: $${trimNumber(view.cost)}`);
|
|
234
|
+
if (view.error !== undefined && view.error !== null)
|
|
235
|
+
lines.push(`Error: ${typeof view.error === "string" ? view.error : JSON.stringify(view.error)}`);
|
|
236
|
+
if (view.idempotency_key)
|
|
237
|
+
lines.push(`Idempotency key: ${view.idempotency_key} (reuse it with the same input when retrying this service run)`);
|
|
238
|
+
if (view.cost === undefined && view.cost_status === "settling")
|
|
239
|
+
lines.push("Cost: settling (see `sandbase runs list` shortly)");
|
|
240
|
+
if (phase === "succeeded" && hasOutput(view)) {
|
|
241
|
+
const files = generatedFiles(view.output);
|
|
242
|
+
if (files.length)
|
|
243
|
+
lines.push("Files:", ...files.map(url => ` ${url}`));
|
|
244
|
+
if (outputFile)
|
|
245
|
+
lines.push(`Saved output to ${outputFile}`);
|
|
246
|
+
else {
|
|
247
|
+
const text = typeof view.output === "string" ? view.output : JSON.stringify(view.output, null, 2);
|
|
248
|
+
lines.push("Output:", text.length > 6000 ? `${text.slice(0, 6000)}\n…(truncated ${text.length - 6000} chars; rerun \`sandbase runs get -r ${view.run_id ?? "<run_id>"} -o result.json\` to save everything)` : text);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
if (phase === "running" && view.run_id)
|
|
252
|
+
lines.push(`Next: sandbase runs get -r ${view.run_id}${view.service_id ? ` --service ${view.service_id}` : ""} -w${outputFile ? ` -o ${outputFile}` : ""} (poll every 5-10s; runs take 1-300s)`);
|
|
253
|
+
if (phase === "succeeded" && !hasOutput(view) && view.run_id)
|
|
254
|
+
lines.push(`Output is not available yet. Retry: sandbase runs get -r ${view.run_id}${view.service_id ? ` --service ${view.service_id}` : ""}${outputFile ? ` -o ${outputFile}` : ""}`);
|
|
255
|
+
out.print(lines.join("\n"));
|
|
256
|
+
printHints(out, view.hints);
|
|
257
|
+
}
|
|
258
|
+
async function finishRun(out, view, outputFile) {
|
|
259
|
+
const phase = phaseOf(view.status);
|
|
260
|
+
const saved = !!outputFile && phase === "succeeded" && hasOutput(view);
|
|
261
|
+
if (saved)
|
|
262
|
+
await writeResult(outputFile, view.output);
|
|
263
|
+
if (out.json) {
|
|
264
|
+
// With -o the output goes to disk only, so a large result never enters the agent's context.
|
|
265
|
+
const value = { ...view };
|
|
266
|
+
if (saved) {
|
|
267
|
+
delete value.output;
|
|
268
|
+
value.output_file = outputFile;
|
|
269
|
+
}
|
|
270
|
+
out.data(value);
|
|
271
|
+
}
|
|
272
|
+
else
|
|
273
|
+
printRun(out, view, saved ? outputFile : undefined);
|
|
274
|
+
return phase === "failed" ? 1 : 0;
|
|
275
|
+
}
|
|
276
|
+
async function client(values, env, fetchImpl) {
|
|
277
|
+
const endpoint = await resolveEndpoint(values.client ? { client: values.client } : {}, env);
|
|
278
|
+
return new SandBaseMCPClient(endpoint, fetchImpl, 120_000, env);
|
|
279
|
+
}
|
|
280
|
+
async function discover(argv, out, env, fetchImpl) {
|
|
281
|
+
const { values, positionals } = parse(argv, { query: { type: "string", short: "q" }, type: { type: "string", short: "t" }, vendor: { type: "string" }, limit: { type: "string", short: "l" } });
|
|
282
|
+
const q = (values.query ?? positionals.join(" ")).trim();
|
|
283
|
+
const limit = values.limit === undefined ? 10 : Number(values.limit);
|
|
284
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > 100)
|
|
285
|
+
throw new SandBaseError("USAGE", "--limit must be an integer between 1 and 100.");
|
|
286
|
+
if (!q && !values.type && !values.vendor)
|
|
287
|
+
throw new SandBaseError("USAGE", "Describe what you need with -q.", 'Example: sandbase discover -q "twitter posts" (short noun phrases work best; Chinese works too)');
|
|
288
|
+
const api = await client(values, env, fetchImpl);
|
|
289
|
+
const { data } = await api.tool("sandbase_discover", { ...(q ? { q } : {}), ...(values.type ? { type: values.type } : {}), ...(values.vendor ? { vendor: values.vendor } : {}), limit });
|
|
290
|
+
const items = (Array.isArray(data.data) ? data.data : []);
|
|
291
|
+
if (out.json) {
|
|
292
|
+
out.data(data);
|
|
293
|
+
return 0;
|
|
294
|
+
}
|
|
295
|
+
if (!items.length) {
|
|
296
|
+
out.print(`No tools matched "${q}". Try a shorter noun phrase, a synonym, or filter with -t.`);
|
|
297
|
+
printHints(out, data.hints, data.warnings);
|
|
298
|
+
return 0;
|
|
299
|
+
}
|
|
300
|
+
const rows = items.map(item => [String(item.tool_name ?? item.name ?? item.id ?? ""), String(item.category ?? item.type ?? ""), String(item.vendor ?? item.vendor_slug ?? ""), formatPrice(item.pricing), truncate(String(item.description ?? ""), 60)]);
|
|
301
|
+
out.print([`Found ${items.length} tool${items.length === 1 ? "" : "s"}${q ? ` for "${q}"` : ""}:`, "", table(["TOOL", "TYPE", "VENDOR", "PRICE", "DESCRIPTION"], rows), "", "Next: sandbase inspect <TOOL> (input schema, exact price, and a ready-to-run command)"].join("\n"));
|
|
302
|
+
printHints(out, data.hints, data.warnings);
|
|
303
|
+
return 0;
|
|
304
|
+
}
|
|
305
|
+
/** Resolve a root-level local $ref (#/components/schemas/X, #/$defs/X, #/definitions/X) so agents see real fields. */
|
|
306
|
+
export function resolveSchema(schema) {
|
|
307
|
+
let current = (schema && typeof schema === "object" ? schema : {});
|
|
308
|
+
const root = current;
|
|
309
|
+
for (let depth = 0; depth < 5 && typeof current.$ref === "string"; depth++) {
|
|
310
|
+
const path = current.$ref.replace(/^#\//, "").split("/").map(part => part.replace(/~1/g, "/").replace(/~0/g, "~"));
|
|
311
|
+
if (!current.$ref.startsWith("#/"))
|
|
312
|
+
break;
|
|
313
|
+
let target = root;
|
|
314
|
+
for (const part of path)
|
|
315
|
+
target = target && typeof target === "object" ? target[part] : undefined;
|
|
316
|
+
if (!target || typeof target !== "object")
|
|
317
|
+
break;
|
|
318
|
+
current = target;
|
|
319
|
+
}
|
|
320
|
+
return current;
|
|
321
|
+
}
|
|
322
|
+
function schemaRows(schema) {
|
|
323
|
+
const value = resolveSchema(schema);
|
|
324
|
+
const required = new Set(Array.isArray(value.required) ? value.required : []);
|
|
325
|
+
const rows = [], example = {};
|
|
326
|
+
for (const [name, prop] of Object.entries(value.properties || {})) {
|
|
327
|
+
const type = Array.isArray(prop.type) ? prop.type.join("|") : String(prop.type ?? (prop.enum ? "enum" : "any"));
|
|
328
|
+
const extras = [prop.enum ? `one of: ${prop.enum.join(", ")}` : "", prop.default !== undefined ? `default: ${JSON.stringify(prop.default)}` : ""].filter(Boolean).join("; ");
|
|
329
|
+
rows.push([name, type, required.has(name) ? "yes" : "", truncate([String(prop.description ?? ""), extras].filter(Boolean).join(" — "), 90)]);
|
|
330
|
+
if (required.has(name))
|
|
331
|
+
example[name] = prop.example ?? prop.default ?? (Array.isArray(prop.enum) ? prop.enum[0] : type === "integer" || type === "number" ? 1 : type === "boolean" ? true : type === "array" ? [] : `<${name}>`);
|
|
332
|
+
}
|
|
333
|
+
return { rows, example };
|
|
334
|
+
}
|
|
335
|
+
async function inspect(argv, out, env, fetchImpl) {
|
|
336
|
+
const { values, positionals } = parse(argv, { name: { type: "string", short: "n" } });
|
|
337
|
+
const name = (values.name ?? positionals[0] ?? "").trim();
|
|
338
|
+
if (!name)
|
|
339
|
+
throw new SandBaseError("USAGE", "Pass the tool name from discover.", "Example: sandbase inspect sandbase_twitter_web_search_timeline");
|
|
340
|
+
const api = await client(values, env, fetchImpl);
|
|
341
|
+
const { data } = await api.tool("sandbase_inspect", { name });
|
|
342
|
+
const tool = String(data.tool_name ?? data.name ?? name);
|
|
343
|
+
const rawSchema = data.inputSchema ?? data.input_schema;
|
|
344
|
+
const { rows, example } = schemaRows(rawSchema);
|
|
345
|
+
if (out.json) {
|
|
346
|
+
const resolved = resolveSchema(rawSchema);
|
|
347
|
+
out.data({ ...data, ...(resolved !== rawSchema ? { inputSchema: resolved } : {}), example_arguments: example, cli: `sandbase run ${tool} -i ${shellQuote(JSON.stringify(example))}` });
|
|
348
|
+
return 0;
|
|
349
|
+
}
|
|
350
|
+
const pricing = (data.pricing || {});
|
|
351
|
+
const priceLine = [formatPrice(pricing), typeof pricing.formula === "string" && pricing.formula ? `formula: ${pricing.formula}` : ""].filter(Boolean).join(" ");
|
|
352
|
+
const meta = [data.model, data.category ?? data.type, data.vendor].filter(Boolean).join(" · ");
|
|
353
|
+
const lines = [`${tool}${meta ? ` (${meta})` : ""}`, String(data.description ?? "").trim(), "", `Price: ${priceLine}`];
|
|
354
|
+
lines.push("", rows.length ? `Input (send as JSON with -i):\n${table(["FIELD", "TYPE", "REQUIRED", "DESCRIPTION"], rows)}` : "Input: no parameters.");
|
|
355
|
+
lines.push("", "Run:", ` sandbase run ${tool} -i ${shellQuote(JSON.stringify(example))}${/video|image|audio|music|speech/i.test(`${data.category ?? ""} ${data.description ?? ""} ${tool}`) ? " -w -o result.json" : ""}`);
|
|
356
|
+
lines.push(`MCP: sandbase_run ${JSON.stringify({ name: tool, arguments: example })}`);
|
|
357
|
+
out.print(lines.join("\n"));
|
|
358
|
+
printHints(out, data.hints, data.notes);
|
|
359
|
+
return 0;
|
|
360
|
+
}
|
|
361
|
+
async function run(argv, out, env, deps, fetchImpl) {
|
|
362
|
+
const { values, positionals } = parse(argv, { input: { type: "string", short: "i" }, file: { type: "string", short: "f" }, wait: { type: "boolean", short: "w" }, timeout: { type: "string" }, output: { type: "string", short: "o" } });
|
|
363
|
+
const name = (positionals[0] ?? "").trim();
|
|
364
|
+
if (!name)
|
|
365
|
+
throw new SandBaseError("USAGE", "Pass the tool name to run.", "Example: sandbase run sandbase_twitter_web_search_timeline -i '{\"keyword\":\"AI agents\"}'");
|
|
366
|
+
if (values.input && values.file)
|
|
367
|
+
throw new SandBaseError("USAGE", "Use either -i or -f, not both.");
|
|
368
|
+
const timeout = positiveSeconds(values.timeout, 300);
|
|
369
|
+
let args = {};
|
|
370
|
+
if (values.input)
|
|
371
|
+
args = parseJsonObject(values.input, "--input");
|
|
372
|
+
if (values.file) {
|
|
373
|
+
let text;
|
|
374
|
+
try {
|
|
375
|
+
text = await readFile(values.file, "utf8");
|
|
376
|
+
}
|
|
377
|
+
catch {
|
|
378
|
+
throw new SandBaseError("USAGE", `Cannot read input file ${values.file}.`);
|
|
379
|
+
}
|
|
380
|
+
args = parseJsonObject(text, "--file");
|
|
381
|
+
}
|
|
382
|
+
const generatedKey = name.startsWith("svc_") && typeof args.idempotency_key !== "string" ? `cli-${deps.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}` : undefined;
|
|
383
|
+
if (generatedKey)
|
|
384
|
+
args = { ...args, idempotency_key: generatedKey };
|
|
385
|
+
await assertWritableOutput(values.output);
|
|
386
|
+
const api = await client(values, env, fetchImpl);
|
|
387
|
+
let view;
|
|
388
|
+
try {
|
|
389
|
+
const { data } = await api.tool("sandbase_run", { name, arguments: args });
|
|
390
|
+
view = runViewFromRun(data, name);
|
|
391
|
+
}
|
|
392
|
+
catch (error) {
|
|
393
|
+
// A run that started and then failed is a result (exit 1), not a transport error.
|
|
394
|
+
if (error instanceof SandBaseError && error.code === "RUN_FAILED")
|
|
395
|
+
return finishRun(out, { ...(error.runId ? { run_id: error.runId } : {}), tool: name, status: "failed", error: error.message, ...(error.hint ? { hints: [error.hint] } : {}) }, values.output);
|
|
396
|
+
throw error;
|
|
397
|
+
}
|
|
398
|
+
if (name.startsWith("svc_") && !view.service_id)
|
|
399
|
+
view.service_id = name;
|
|
400
|
+
if (typeof args.idempotency_key === "string" && view.service_id)
|
|
401
|
+
view.idempotency_key = args.idempotency_key;
|
|
402
|
+
if (!view.run_id)
|
|
403
|
+
return finishRun(out, view, values.output);
|
|
404
|
+
try {
|
|
405
|
+
if (values.wait && phaseOf(view.status) === "running") {
|
|
406
|
+
// stderr, also in -j mode: an agent whose shell times out still sees the run id to resume.
|
|
407
|
+
out.progress(`Run ${view.run_id} started; waiting for the result (up to ${timeout}s). If interrupted, resume with: sandbase runs get -r ${view.run_id}${view.service_id ? ` --service ${view.service_id}` : ""} -w${values.output ? ` -o ${values.output}` : ""}`);
|
|
408
|
+
view = await pollRun(api, view, timeout, deps);
|
|
409
|
+
}
|
|
410
|
+
else if (phaseOf(view.status) !== "running" && view.cost === undefined && !view.service_id) {
|
|
411
|
+
try {
|
|
412
|
+
const { data: detail } = await api.tool("sandbase_run_get", { run_id: view.run_id });
|
|
413
|
+
if (detail.cost !== undefined)
|
|
414
|
+
view.cost = detail.cost;
|
|
415
|
+
}
|
|
416
|
+
catch { /* cost is informational */ }
|
|
417
|
+
}
|
|
418
|
+
return await finishRun(out, view, values.output);
|
|
419
|
+
}
|
|
420
|
+
catch (error) {
|
|
421
|
+
throw withRunContext(error, view);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
async function runs(argv, out, env, deps, fetchImpl) {
|
|
425
|
+
const [sub, ...rest] = argv;
|
|
426
|
+
if (sub === "get") {
|
|
427
|
+
const { values, positionals } = parse(rest, { run: { type: "string", short: "r" }, service: { type: "string" }, wait: { type: "boolean", short: "w" }, timeout: { type: "string" }, output: { type: "string", short: "o" } });
|
|
428
|
+
const runId = (values.run ?? positionals[0] ?? "").trim();
|
|
429
|
+
if (!runId)
|
|
430
|
+
throw new SandBaseError("USAGE", "Pass the run id with -r.", "Example: sandbase runs get -r pred_abc123 -w -o result.json");
|
|
431
|
+
const timeout = positiveSeconds(values.timeout, 300);
|
|
432
|
+
await assertWritableOutput(values.output);
|
|
433
|
+
const api = await client(values, env, fetchImpl);
|
|
434
|
+
let view = await readRun(api, runId, values.service);
|
|
435
|
+
try {
|
|
436
|
+
if (values.wait)
|
|
437
|
+
view = await pollRun(api, view, timeout, deps);
|
|
438
|
+
return await finishRun(out, view, values.output);
|
|
439
|
+
}
|
|
440
|
+
catch (error) {
|
|
441
|
+
throw withRunContext(error, view);
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
if (sub === "list") {
|
|
445
|
+
const { values } = parse(rest, { limit: { type: "string", short: "l" }, model: { type: "string" }, service: { type: "string" } });
|
|
446
|
+
const limit = values.limit === undefined ? 10 : Number(values.limit);
|
|
447
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > 50)
|
|
448
|
+
throw new SandBaseError("USAGE", "--limit must be an integer between 1 and 50.");
|
|
449
|
+
const api = await client(values, env, fetchImpl);
|
|
450
|
+
const { data } = await api.tool("sandbase_runs", { limit, ...(values.model ? { model: values.model } : {}), ...(values.service ? { service_id: values.service } : {}) });
|
|
451
|
+
if (out.json) {
|
|
452
|
+
out.data(data);
|
|
453
|
+
return 0;
|
|
454
|
+
}
|
|
455
|
+
const items = (Array.isArray(data.runs) ? data.runs : Array.isArray(data.data) ? data.data : Array.isArray(data.items) ? data.items : []);
|
|
456
|
+
if (!items.length) {
|
|
457
|
+
out.print("No runs yet.");
|
|
458
|
+
return 0;
|
|
459
|
+
}
|
|
460
|
+
out.print(table(["RUN", "MODEL", "STATUS", "COST", "CREATED"], items.map(item => [String(item.id ?? item.run_id ?? ""), String(item.model ?? item.service_id ?? ""), String(item.status ?? ""), item.cost === undefined ? "" : `$${trimNumber(item.cost)}`, String(item.created_at ?? "")])));
|
|
461
|
+
return 0;
|
|
462
|
+
}
|
|
463
|
+
throw new SandBaseError("USAGE", "Use `sandbase runs get -r <run_id>` or `sandbase runs list`.");
|
|
464
|
+
}
|
|
465
|
+
// What /v1/upload accepts, by extension. Server limits are 20/50/500 MB; video is
|
|
466
|
+
// capped at 100 MB here because the API sits behind Cloudflare's request-body limit.
|
|
467
|
+
const MB = 1024 * 1024;
|
|
468
|
+
const uploadTypes = {
|
|
469
|
+
".jpg": { mime: "image/jpeg", kind: "image", max: 20 * MB }, ".jpeg": { mime: "image/jpeg", kind: "image", max: 20 * MB }, ".png": { mime: "image/png", kind: "image", max: 20 * MB }, ".webp": { mime: "image/webp", kind: "image", max: 20 * MB }, ".gif": { mime: "image/gif", kind: "image", max: 20 * MB },
|
|
470
|
+
".mp3": { mime: "audio/mpeg", kind: "audio", max: 50 * MB }, ".m4a": { mime: "audio/mp4", kind: "audio", max: 50 * MB }, ".wav": { mime: "audio/wav", kind: "audio", max: 50 * MB }, ".ogg": { mime: "audio/ogg", kind: "audio", max: 50 * MB }, ".aac": { mime: "audio/aac", kind: "audio", max: 50 * MB }, ".flac": { mime: "audio/flac", kind: "audio", max: 50 * MB },
|
|
471
|
+
".mp4": { mime: "video/mp4", kind: "video", max: 100 * MB }, ".mov": { mime: "video/quicktime", kind: "video", max: 100 * MB }, ".webm": { mime: "video/webm", kind: "video", max: 100 * MB },
|
|
472
|
+
};
|
|
473
|
+
export function uploadUrlFor(mcpUrl) { const url = new URL(mcpUrl); url.pathname = url.pathname.replace(/\/mcp$/, "/upload"); url.search = ""; return url.href; }
|
|
474
|
+
async function upload(argv, out, env, fetchImpl) {
|
|
475
|
+
const { values, positionals } = parse(argv, { file: { type: "string", short: "f" } });
|
|
476
|
+
const path = (values.file ?? positionals[0] ?? "").trim();
|
|
477
|
+
if (!path)
|
|
478
|
+
throw new SandBaseError("USAGE", "Pass the local file to upload.", "Example: sandbase upload ./photo.png");
|
|
479
|
+
const type = uploadTypes[extname(path).toLowerCase()];
|
|
480
|
+
if (!type)
|
|
481
|
+
throw new SandBaseError("USAGE", `Cannot upload ${basename(path)}: only images (jpg, png, webp, gif), audio (mp3, m4a, wav, ogg, aac, flac) and video (mp4, mov, webm) are accepted.`);
|
|
482
|
+
let size;
|
|
483
|
+
try {
|
|
484
|
+
const info = await stat(path);
|
|
485
|
+
if (!info.isFile())
|
|
486
|
+
throw new Error("not a file");
|
|
487
|
+
size = info.size;
|
|
488
|
+
}
|
|
489
|
+
catch {
|
|
490
|
+
throw new SandBaseError("USAGE", `Cannot read ${path}: it does not exist or is not a file.`);
|
|
491
|
+
}
|
|
492
|
+
if (size > type.max)
|
|
493
|
+
throw new SandBaseError("USAGE", `${basename(path)} is ${Math.ceil(size / MB)} MB; the ${type.kind} limit is ${type.max / MB} MB.`, type.kind === "video" ? "Trim or compress the video, or pass a URL where it is already hosted." : "Compress the file, or pass a URL where it is already hosted.");
|
|
494
|
+
const endpoint = await resolveEndpoint(values.client ? { client: values.client } : {}, env);
|
|
495
|
+
const target = uploadUrlFor(endpoint.url);
|
|
496
|
+
const host = new URL(target).host;
|
|
497
|
+
const form = new FormData();
|
|
498
|
+
form.append("file", new Blob([await readFile(path)], { type: type.mime }), basename(path));
|
|
499
|
+
let response;
|
|
500
|
+
try {
|
|
501
|
+
response = await (fetchImpl ?? globalThis.fetch)(target, { method: "POST", headers: { authorization: `Bearer ${endpoint.credential}`, "x-sandbase-client": "cli" }, body: form, signal: AbortSignal.timeout(600_000) });
|
|
502
|
+
}
|
|
503
|
+
catch (error) {
|
|
504
|
+
throw new SandBaseError("NETWORK", `Upload to ${host} failed (${describeNetworkFailure(error)}).`, "Check the network, then retry; nothing is billed for uploads.");
|
|
505
|
+
}
|
|
506
|
+
const text = await response.text();
|
|
507
|
+
if (response.status === 403 && /insufficient_scope/.test(text))
|
|
508
|
+
throw new SandBaseError("FORBIDDEN", `This sign-in cannot upload files on ${host} yet (403).`, `Ask the user for a full API key from ${keysUrl(env)} and run the upload with SANDBASE_API_KEY set (never paste the key into chat).`, 403);
|
|
509
|
+
if (response.status === 404)
|
|
510
|
+
throw new SandBaseError("NOT_FOUND", `${host} does not accept file uploads (404).`, "Pass a URL where the file is already hosted instead.", 404);
|
|
511
|
+
if (!response.ok)
|
|
512
|
+
throw httpError(response.status, text, host, env);
|
|
513
|
+
let data;
|
|
514
|
+
try {
|
|
515
|
+
data = JSON.parse(text);
|
|
516
|
+
}
|
|
517
|
+
catch {
|
|
518
|
+
data = {};
|
|
519
|
+
}
|
|
520
|
+
const inner = (data.data && typeof data.data === "object" ? data.data : data);
|
|
521
|
+
if (typeof inner.url !== "string" || !inner.url)
|
|
522
|
+
throw new SandBaseError("INVALID_RESPONSE", `Expected an uploaded file URL from ${host}.`, "Retry once; run `sandbase doctor` if it persists.");
|
|
523
|
+
if (out.json) {
|
|
524
|
+
out.data(inner);
|
|
525
|
+
return 0;
|
|
526
|
+
}
|
|
527
|
+
out.print([`Uploaded ${basename(path)} (${inner.type ?? type.mime}, ${Math.max(1, Math.round(size / 1024))} KB)`, `URL: ${inner.url}`, ...(inner.duration_seconds ? [`Duration: ${trimNumber(inner.duration_seconds)}s`] : []), "", "Pass this URL to the tool's image/audio/video URL field. Anyone with the URL can read the file."].join("\n"));
|
|
528
|
+
return 0;
|
|
529
|
+
}
|
|
530
|
+
async function balance(argv, out, env, fetchImpl) {
|
|
531
|
+
const { values } = parse(argv, {});
|
|
532
|
+
const api = await client(values, env, fetchImpl);
|
|
533
|
+
const { data } = await api.tool("sandbase_account", {});
|
|
534
|
+
if (out.json) {
|
|
535
|
+
out.data(data);
|
|
536
|
+
return 0;
|
|
537
|
+
}
|
|
538
|
+
out.print(`Balance: $${trimNumber(data.balance ?? "?")} ${String(data.currency ?? "USD")}${data.credit_limit ? ` (credit limit $${trimNumber(data.credit_limit)})` : ""}`);
|
|
539
|
+
printHints(out, data.hints);
|
|
540
|
+
return 0;
|
|
541
|
+
}
|
|
542
|
+
/** Shows at most a quarter of the key (capped at 6 chars) so short keys are not mostly revealed. */
|
|
543
|
+
export function maskKey(key) {
|
|
544
|
+
const visible = Math.min(6, Math.floor(key.length / 4));
|
|
545
|
+
return visible >= 2 ? `${key.slice(0, Math.ceil(visible / 2) + 1)}…${key.slice(-Math.floor(visible / 2))}` : "…";
|
|
546
|
+
}
|
|
547
|
+
async function readStdin() {
|
|
548
|
+
if (process.stdin.isTTY)
|
|
549
|
+
return "";
|
|
550
|
+
const chunks = [];
|
|
551
|
+
for await (const chunk of process.stdin)
|
|
552
|
+
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
553
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
554
|
+
}
|
|
555
|
+
async function keys(argv, out, env, deps) {
|
|
556
|
+
const [sub, ...rest] = argv;
|
|
557
|
+
if (sub === "add") {
|
|
558
|
+
const { values } = parse(rest, { key: { type: "string", short: "k" }, url: { type: "string" } });
|
|
559
|
+
// `-k -` (or no -k with piped stdin) keeps the key out of shell history, `ps`, and agent transcripts.
|
|
560
|
+
const key = (values.key === "-" || (values.key === undefined && deps.stdin) ? await (deps.stdin ?? readStdin)() : values.key ?? "").trim();
|
|
561
|
+
if (!key)
|
|
562
|
+
throw new SandBaseError("USAGE", "Pass the API key on stdin (`sandbase keys add -k -`) or with -k.", `Create one at ${keysUrl(env)}. Never paste API keys into an AI chat.`);
|
|
563
|
+
if (values.url && !validMcpUrl(values.url))
|
|
564
|
+
throw new SandBaseError("USAGE", "--url must be an http(s) URL ending in /v1/mcp.");
|
|
565
|
+
await atomicWrite(keyFilePath(env), JSON.stringify({ key, ...(values.url ? { mcpUrl: values.url } : {}), addedAt: new Date().toISOString() }, null, 2) + "\n", 0o600);
|
|
566
|
+
const masked = maskKey(key);
|
|
567
|
+
if (out.json)
|
|
568
|
+
out.data({ saved: true, key: masked, path: keyFilePath(env) });
|
|
569
|
+
else
|
|
570
|
+
out.print(`Saved API key ${masked} to ${keyFilePath(env)} (mode 600). Verify with: sandbase balance`);
|
|
571
|
+
return 0;
|
|
572
|
+
}
|
|
573
|
+
if (sub === "list") {
|
|
574
|
+
parse(rest, {});
|
|
575
|
+
const stored = await readStoredKey(env);
|
|
576
|
+
const entries = [...(env.SANDBASE_API_KEY ? [{ source: "env:SANDBASE_API_KEY", key: maskKey(env.SANDBASE_API_KEY), active: true }] : []), ...(stored ? [{ source: "keys", key: maskKey(stored.key), active: !env.SANDBASE_API_KEY }] : [])];
|
|
577
|
+
if (out.json) {
|
|
578
|
+
out.data({ keys: entries });
|
|
579
|
+
return 0;
|
|
580
|
+
}
|
|
581
|
+
out.print(entries.length ? table(["SOURCE", "KEY", "ACTIVE"], entries.map(entry => [entry.source, entry.key, entry.active ? "yes" : ""])) : `No API key stored. Connected clients from \`${CONNECT_COMMAND}\` are used automatically.`);
|
|
582
|
+
return 0;
|
|
583
|
+
}
|
|
584
|
+
if (sub === "remove") {
|
|
585
|
+
parse(rest, {});
|
|
586
|
+
await rm(keyFilePath(env), { force: true });
|
|
587
|
+
if (out.json)
|
|
588
|
+
out.data({ removed: true });
|
|
589
|
+
else
|
|
590
|
+
out.print("Removed the stored API key.");
|
|
591
|
+
return 0;
|
|
592
|
+
}
|
|
593
|
+
throw new SandBaseError("USAGE", "Use `sandbase keys add -k <key>`, `sandbase keys list`, or `sandbase keys remove`.");
|
|
594
|
+
}
|
|
595
|
+
export async function runAgentCommand(command, argv, deps = {}) {
|
|
596
|
+
const env = deps.env || process.env;
|
|
597
|
+
const json = argv.includes("-j") || argv.includes("--json");
|
|
598
|
+
const out = new Output(json, deps.out || (text => process.stdout.write(`${text}\n`)), deps.err || (text => process.stderr.write(`${text}\n`)));
|
|
599
|
+
const timing = { sleep: deps.sleep || (ms => new Promise(resolve => setTimeout(resolve, ms))), now: deps.now || Date.now };
|
|
600
|
+
const pendingNotice = command === "keys" ? Promise.resolve(undefined) : updateNotice(env);
|
|
601
|
+
if (argv.includes("-h") || argv.includes("--help")) {
|
|
602
|
+
out.print(agentUsage);
|
|
603
|
+
return 0;
|
|
604
|
+
}
|
|
605
|
+
let code;
|
|
606
|
+
try {
|
|
607
|
+
const notice = async () => { const text = await Promise.race([pendingNotice, new Promise(resolve => setTimeout(() => resolve(undefined), 2500).unref())]); if (text)
|
|
608
|
+
out.notice(text); };
|
|
609
|
+
if (json)
|
|
610
|
+
await notice();
|
|
611
|
+
code = command === "discover" ? await discover(argv, out, env, deps.fetchImpl)
|
|
612
|
+
: command === "inspect" ? await inspect(argv, out, env, deps.fetchImpl)
|
|
613
|
+
: command === "run" ? await run(argv, out, env, timing, deps.fetchImpl)
|
|
614
|
+
: command === "runs" ? await runs(argv, out, env, timing, deps.fetchImpl)
|
|
615
|
+
: command === "upload" ? await upload(argv, out, env, deps.fetchImpl)
|
|
616
|
+
: command === "balance" ? await balance(argv, out, env, deps.fetchImpl)
|
|
617
|
+
: await keys(argv, out, env, deps);
|
|
618
|
+
if (!json)
|
|
619
|
+
await notice();
|
|
620
|
+
}
|
|
621
|
+
catch (error) {
|
|
622
|
+
const failure = error instanceof SandBaseError ? error : new SandBaseError("TOOL_ERROR", (error instanceof Error ? error.message : "Unknown failure").replace(/(?:sk|cln)-[A-Za-z0-9_-]+/g, "[REDACTED]"));
|
|
623
|
+
out.error(failure);
|
|
624
|
+
code = failure.code === "USAGE" ? 2 : 1;
|
|
625
|
+
}
|
|
626
|
+
return code;
|
|
627
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { type FetchLike } from "./client.js";
|
|
2
|
+
export interface ProbeResult {
|
|
3
|
+
ok: boolean;
|
|
4
|
+
line: string;
|
|
5
|
+
}
|
|
6
|
+
export declare function probeEndpoint(label: string, credential: string, mcpUrl: string, env?: NodeJS.ProcessEnv, fetchImpl?: FetchLike, timeoutMs?: number): Promise<ProbeResult>;
|