@agentrouter/agentrouter 0.1.13 → 0.2.0
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/README.md +16 -803
- package/dist/cli.js +3 -4
- package/dist/core.d.ts +28 -0
- package/dist/core.d.ts.map +1 -0
- package/dist/core.js +596 -0
- package/dist/credentials.d.ts +43 -0
- package/dist/credentials.d.ts.map +1 -0
- package/dist/credentials.js +98 -0
- package/dist/login-page.d.ts +2 -0
- package/dist/login-page.d.ts.map +1 -0
- package/dist/login-page.js +45 -0
- package/dist/login.d.ts +23 -0
- package/dist/login.d.ts.map +1 -0
- package/dist/login.js +90 -0
- package/dist/terminal.d.ts +3 -0
- package/dist/terminal.d.ts.map +1 -0
- package/dist/terminal.js +32 -0
- package/icon.svg +11 -0
- package/package.json +9 -17
- package/dist/cli-core.d.ts +0 -13
- package/dist/cli-core.d.ts.map +0 -1
- package/dist/cli-core.js +0 -627
- package/dist/index.d.ts +0 -553
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js +0 -797
package/dist/cli.js
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
process.exitCode = exitCode;
|
|
2
|
+
import { runCli } from "./core.js";
|
|
3
|
+
runCli(process.argv.slice(2), { isTTY: Boolean(process.stdin.isTTY) }).then((code) => {
|
|
4
|
+
process.exitCode = code;
|
|
6
5
|
});
|
package/dist/core.d.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { CLI_VERSION, type Env } from "./credentials.js";
|
|
2
|
+
export { CLI_VERSION };
|
|
3
|
+
/** Oldest HTTP API contract this CLI speaks. New providers never need a new CLI. */
|
|
4
|
+
export declare const MIN_API_VERSION = "v1";
|
|
5
|
+
/** Exit codes are part of the CLI contract; scripts and CI rely on them. */
|
|
6
|
+
export declare const EXIT: {
|
|
7
|
+
readonly ok: 0;
|
|
8
|
+
readonly error: 1;
|
|
9
|
+
readonly usage: 2;
|
|
10
|
+
readonly auth: 3;
|
|
11
|
+
readonly runFailed: 4;
|
|
12
|
+
readonly priceChanged: 5;
|
|
13
|
+
readonly blocked: 6;
|
|
14
|
+
readonly stillRunning: 7;
|
|
15
|
+
readonly outputWriteFailed: 8;
|
|
16
|
+
readonly notFound: 9;
|
|
17
|
+
};
|
|
18
|
+
export interface CliIo {
|
|
19
|
+
env?: Env;
|
|
20
|
+
stdout?: (text: string) => void;
|
|
21
|
+
stderr?: (text: string) => void;
|
|
22
|
+
fetch?: typeof fetch;
|
|
23
|
+
readKey?: () => Promise<string>;
|
|
24
|
+
isTTY?: boolean;
|
|
25
|
+
openBrowser?: boolean;
|
|
26
|
+
}
|
|
27
|
+
export declare function runCli(argv: string[], io?: CliIo): Promise<number>;
|
|
28
|
+
//# sourceMappingURL=core.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"core.d.ts","sourceRoot":"","sources":["../src/core.ts"],"names":[],"mappings":"AAIA,OAAO,EACL,WAAW,EAYX,KAAK,GAAG,EAET,MAAM,kBAAkB,CAAC;AAG1B,OAAO,EAAE,WAAW,EAAE,CAAC;AACvB,oFAAoF;AACpF,eAAO,MAAM,eAAe,OAAO,CAAC;AAEpC,4EAA4E;AAC5E,eAAO,MAAM,IAAI;;;;;;;;;;;CAWP,CAAC;AAEX,MAAM,WAAW,KAAK;IACpB,GAAG,CAAC,EAAE,GAAG,CAAC;IACV,MAAM,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IAChC,MAAM,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IAChC,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;IACrB,OAAO,CAAC,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC,CAAC;IAChC,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,WAAW,CAAC,EAAE,OAAO,CAAC;CACvB;AAyFD,wBAAsB,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,GAAE,KAAU,GAAG,OAAO,CAAC,MAAM,CAAC,CAuc5E"}
|
package/dist/core.js
ADDED
|
@@ -0,0 +1,596 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import { isDeepStrictEqual } from "node:util";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
import { readFile, writeFile } from "node:fs/promises";
|
|
5
|
+
import { CLI_VERSION, DEFAULT_BASE_URL, PRODUCTION_API_ORIGIN, configDir, deleteCredential, loadContracts, invocationPath, loadInvocation, saveInvocation, loadCredential, saveContract, saveCredential } from "./credentials.js";
|
|
6
|
+
import { browserLogin, refreshTokens, revokeToken } from "./login.js";
|
|
7
|
+
export { CLI_VERSION };
|
|
8
|
+
/** Oldest HTTP API contract this CLI speaks. New providers never need a new CLI. */
|
|
9
|
+
export const MIN_API_VERSION = "v1";
|
|
10
|
+
/** Exit codes are part of the CLI contract; scripts and CI rely on them. */
|
|
11
|
+
export const EXIT = {
|
|
12
|
+
ok: 0,
|
|
13
|
+
error: 1,
|
|
14
|
+
usage: 2,
|
|
15
|
+
auth: 3,
|
|
16
|
+
runFailed: 4,
|
|
17
|
+
priceChanged: 5,
|
|
18
|
+
blocked: 6,
|
|
19
|
+
stillRunning: 7,
|
|
20
|
+
outputWriteFailed: 8,
|
|
21
|
+
notFound: 9
|
|
22
|
+
};
|
|
23
|
+
class CliError extends Error {
|
|
24
|
+
constructor(message, exitCode, body) {
|
|
25
|
+
super(message);
|
|
26
|
+
this.exitCode = exitCode;
|
|
27
|
+
this.body = body;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
const API_KEY_FORMAT = /^ar_live_[0-9a-f]{16}_[A-Za-z0-9_-]{32,64}$/;
|
|
31
|
+
const BOOLEAN_FLAGS = new Set(["json", "wait", "help", "no-browser", "no-color", "open", "version"]);
|
|
32
|
+
const REPEATABLE = new Set(["run", "scope"]);
|
|
33
|
+
function parseArgs(argv) {
|
|
34
|
+
const positional = [];
|
|
35
|
+
const flags = { json: false };
|
|
36
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
37
|
+
const arg = argv[index];
|
|
38
|
+
if (!arg.startsWith("--")) {
|
|
39
|
+
positional.push(arg);
|
|
40
|
+
continue;
|
|
41
|
+
}
|
|
42
|
+
const body = arg.slice(2);
|
|
43
|
+
const equals = body.indexOf("=");
|
|
44
|
+
const rawName = equals === -1 ? body : body.slice(0, equals);
|
|
45
|
+
const inline = equals === -1 ? undefined : body.slice(equals + 1);
|
|
46
|
+
if (BOOLEAN_FLAGS.has(rawName)) {
|
|
47
|
+
flags[rawName] = inline === undefined ? true : inline !== "false";
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
const value = inline ?? argv[++index];
|
|
51
|
+
if (value === undefined)
|
|
52
|
+
throw new CliError(`--${rawName} needs a value`, EXIT.usage);
|
|
53
|
+
if (REPEATABLE.has(rawName))
|
|
54
|
+
flags[rawName] = [...(flags[rawName] ?? []), value];
|
|
55
|
+
else
|
|
56
|
+
flags[rawName] = value;
|
|
57
|
+
}
|
|
58
|
+
return { positional, flags };
|
|
59
|
+
}
|
|
60
|
+
const HELP = `AgentRouter CLI ${CLI_VERSION} — find, describe and invoke provider tools with one wallet.
|
|
61
|
+
|
|
62
|
+
Sign in
|
|
63
|
+
agentrouter connect [--no-browser] Connect this machine through browser sign-in (login also works)
|
|
64
|
+
agentrouter logout Forget local credentials and revoke the CLI login
|
|
65
|
+
agentrouter whoami Account, wallet owner, credential and permissions
|
|
66
|
+
agentrouter setup Which entry to use: MCP, CLI or HTTP API
|
|
67
|
+
agentrouter keys list | add <name> [--scope s]... | remove <key_id> | activate <key> | set | clear
|
|
68
|
+
|
|
69
|
+
Use tools
|
|
70
|
+
agentrouter find "<task>" [--limit n] [--provider id] [--category id,id] [--group id,id]
|
|
71
|
+
agentrouter describe <tool_id>
|
|
72
|
+
agentrouter invoke <tool_id> --input <json|@file> [--max-cost-usd 0.05] [--session id]
|
|
73
|
+
[--idempotency-key k] [--wait] [--timeout-ms n] [--output file]
|
|
74
|
+
agentrouter runs get <run_id> [--wait] [--output file]
|
|
75
|
+
agentrouter runs list [--session id] [--status running] [--limit n]
|
|
76
|
+
agentrouter runs stop <run_id>
|
|
77
|
+
|
|
78
|
+
Money and support
|
|
79
|
+
agentrouter balance
|
|
80
|
+
agentrouter topup --amount-usd 10 [--open] Creates a payment link; funds arrive after payment
|
|
81
|
+
agentrouter feedback --text "..." [--run id] [--category c]
|
|
82
|
+
agentrouter tools request --capability "..." --note "..."
|
|
83
|
+
agentrouter dispute create --run <id> [--run <id>] --goal "..." --reason "..." [--evidence "..."]
|
|
84
|
+
agentrouter dispute get <dispute_id>
|
|
85
|
+
agentrouter dispute reply <dispute_id> --evidence "..."
|
|
86
|
+
|
|
87
|
+
Global: --json (stdout is JSON only; progress goes to stderr), --base-url <url>, --api-key <key>
|
|
88
|
+
Env: AGENTROUTER_API_KEY, AGENTROUTER_BASE_URL, AGENTROUTER_CONFIG_DIR
|
|
89
|
+
Exit codes: 0 ok, 1 error, 2 usage, 3 auth, 4 run failed, 5 price/version changed, 6 blocked by
|
|
90
|
+
budget/balance, 7 still running, 8 could not write output file, 9 not found.
|
|
91
|
+
`;
|
|
92
|
+
export async function runCli(argv, io = {}) {
|
|
93
|
+
const env = { ...(io.env ?? process.env) };
|
|
94
|
+
const stdout = io.stdout ?? ((text) => process.stdout.write(text));
|
|
95
|
+
const stderr = io.stderr ?? ((text) => process.stderr.write(text));
|
|
96
|
+
const fetchImpl = io.fetch ?? fetch;
|
|
97
|
+
let parsed;
|
|
98
|
+
try {
|
|
99
|
+
parsed = parseArgs(argv);
|
|
100
|
+
}
|
|
101
|
+
catch (error) {
|
|
102
|
+
stderr(`${error.message}\n`);
|
|
103
|
+
return EXIT.usage;
|
|
104
|
+
}
|
|
105
|
+
const { positional, flags } = parsed;
|
|
106
|
+
const [command, sub, ...rest] = positional;
|
|
107
|
+
const baseUrl = String(flags["base-url"] ?? env.AGENTROUTER_BASE_URL ?? DEFAULT_BASE_URL).replace(/\/$/, "");
|
|
108
|
+
if (!env.AGENTROUTER_CONFIG_DIR && baseUrl !== PRODUCTION_API_ORIGIN) {
|
|
109
|
+
env.AGENTROUTER_CONFIG_DIR = join(configDir(env), encodeURIComponent(baseUrl));
|
|
110
|
+
}
|
|
111
|
+
const info = (line) => stderr(`${line}\n`);
|
|
112
|
+
const print = (value, text) => stdout(flags.json || text === undefined ? `${typeof value === "string" ? value : JSON.stringify(value, null, 2)}\n` : `${text}\n`);
|
|
113
|
+
if ((!command && !flags.version) || flags.help) {
|
|
114
|
+
stdout(HELP);
|
|
115
|
+
return flags.help ? EXIT.ok : EXIT.usage;
|
|
116
|
+
}
|
|
117
|
+
if (flags.version || command === "version") {
|
|
118
|
+
print({ cli_version: CLI_VERSION, api: MIN_API_VERSION }, `agentrouter ${CLI_VERSION} (API ${MIN_API_VERSION})`);
|
|
119
|
+
return EXIT.ok;
|
|
120
|
+
}
|
|
121
|
+
async function credential() {
|
|
122
|
+
if (typeof flags["api-key"] === "string")
|
|
123
|
+
return { token: flags["api-key"], source: "--api-key" };
|
|
124
|
+
if (env.AGENTROUTER_API_KEY)
|
|
125
|
+
return { token: env.AGENTROUTER_API_KEY, source: "AGENTROUTER_API_KEY" };
|
|
126
|
+
const stored = await loadCredential(env);
|
|
127
|
+
if (!stored || stored.baseUrl !== baseUrl) {
|
|
128
|
+
throw new CliError("Not signed in. Run `agentrouter connect` or set AGENTROUTER_API_KEY for CI and scripts.", EXIT.auth);
|
|
129
|
+
}
|
|
130
|
+
if (stored.kind === "api_key")
|
|
131
|
+
return { token: stored.apiKey, source: "stored key" };
|
|
132
|
+
if (stored.expiresAt - 60000 > Date.now())
|
|
133
|
+
return { token: stored.accessToken, source: "browser login" };
|
|
134
|
+
const fresh = await refreshTokens(stored.baseUrl, stored.refreshToken, fetchImpl).catch((error) => {
|
|
135
|
+
throw new CliError(error.message, EXIT.auth);
|
|
136
|
+
});
|
|
137
|
+
await saveCredential(env, { ...stored, accessToken: fresh.accessToken, refreshToken: fresh.refreshToken, expiresAt: Date.now() + fresh.expiresIn * 1000, scope: fresh.scope });
|
|
138
|
+
return { token: fresh.accessToken, source: "browser login" };
|
|
139
|
+
}
|
|
140
|
+
async function http(method, path, body, headers = {}, retrySafe = method === "GET") {
|
|
141
|
+
const { token } = await credential();
|
|
142
|
+
const send = () => fetchImpl(`${baseUrl}${path}`, {
|
|
143
|
+
method,
|
|
144
|
+
headers: { authorization: `Bearer ${token}`, "content-type": "application/json", "x-agentrouter-client": `agentrouter-cli/${CLI_VERSION}`, ...headers },
|
|
145
|
+
body: body === undefined ? undefined : JSON.stringify(body)
|
|
146
|
+
});
|
|
147
|
+
let response;
|
|
148
|
+
try {
|
|
149
|
+
response = await send();
|
|
150
|
+
}
|
|
151
|
+
catch (error) {
|
|
152
|
+
if (!retrySafe)
|
|
153
|
+
throw new CliError(`Network error: ${error.message}`, EXIT.error);
|
|
154
|
+
info("Network error; retrying once with the same idempotency key…");
|
|
155
|
+
response = await send().catch((second) => {
|
|
156
|
+
throw new CliError(`Network error: ${second.message}`, EXIT.error);
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
const text = await response.text();
|
|
160
|
+
let json = null;
|
|
161
|
+
try {
|
|
162
|
+
json = text ? JSON.parse(text) : null;
|
|
163
|
+
}
|
|
164
|
+
catch {
|
|
165
|
+
json = null;
|
|
166
|
+
}
|
|
167
|
+
return { status: response.status, text, json };
|
|
168
|
+
}
|
|
169
|
+
function fail(result) {
|
|
170
|
+
const error = result.json?.error;
|
|
171
|
+
const code = error?.code ?? `HTTP_${result.status}`;
|
|
172
|
+
const exitCode = result.status === 401 || result.status === 403
|
|
173
|
+
? EXIT.auth
|
|
174
|
+
: result.status === 404
|
|
175
|
+
? EXIT.notFound
|
|
176
|
+
: code === "PRICING_CHANGED" || code === "TOOL_VERSION_CHANGED"
|
|
177
|
+
? EXIT.priceChanged
|
|
178
|
+
: result.status === 400
|
|
179
|
+
? EXIT.usage
|
|
180
|
+
: EXIT.error;
|
|
181
|
+
const hints = (error?.hints ?? []).map((hint) => ` → ${hint.message}`).join("\n");
|
|
182
|
+
throw new CliError(`${code}: ${error?.message ?? result.text.slice(0, 300)}${hints ? `\n${hints}` : ""}`, exitCode, result.json ?? result.text);
|
|
183
|
+
}
|
|
184
|
+
async function readInput(raw) {
|
|
185
|
+
if (typeof raw !== "string")
|
|
186
|
+
throw new CliError("--input is required: JSON text or @file.json", EXIT.usage);
|
|
187
|
+
const text = raw.startsWith("@") ? await readFile(raw.slice(1), "utf8") : raw;
|
|
188
|
+
try {
|
|
189
|
+
return JSON.parse(text);
|
|
190
|
+
}
|
|
191
|
+
catch {
|
|
192
|
+
throw new CliError("--input is not valid JSON", EXIT.usage);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
/** Export the exact stored output of an existing run; never re-invokes. */
|
|
196
|
+
async function exportOutput(runId, file) {
|
|
197
|
+
const result = await http("GET", `/v1/runs/${encodeURIComponent(runId)}/result`);
|
|
198
|
+
if (result.status !== 200)
|
|
199
|
+
fail(result);
|
|
200
|
+
try {
|
|
201
|
+
await writeFile(file, result.text);
|
|
202
|
+
info(`Output written to ${file}`);
|
|
203
|
+
}
|
|
204
|
+
catch (error) {
|
|
205
|
+
throw new CliError(`Could not write ${file}: ${error.message}. The run is unaffected; export again with \`agentrouter runs get ${runId} --output <file>\`.`, EXIT.outputWriteFailed);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
function runExit(run) {
|
|
209
|
+
switch (run?.status) {
|
|
210
|
+
case "COMPLETED":
|
|
211
|
+
return EXIT.ok;
|
|
212
|
+
case "RUNNING":
|
|
213
|
+
case "READY":
|
|
214
|
+
case "STOPPING":
|
|
215
|
+
return EXIT.stillRunning;
|
|
216
|
+
case "BLOCKED":
|
|
217
|
+
return EXIT.blocked;
|
|
218
|
+
default:
|
|
219
|
+
return EXIT.runFailed;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
function describeRun(run) {
|
|
223
|
+
const lines = [
|
|
224
|
+
`${run.run_id} ${run.status} ${run.tool_id}`,
|
|
225
|
+
` charge $${run.billing.customer_charge_usd} (${run.billing.reason ?? "pending"}), multiplier ${run.billing.price_multiplier}, max $${run.billing.max_cost_usd}`
|
|
226
|
+
];
|
|
227
|
+
if (run.error)
|
|
228
|
+
lines.push(` error ${run.error.code}: ${run.error.message}`);
|
|
229
|
+
if (run.provider_response?.request_id)
|
|
230
|
+
lines.push(` provider request ${run.provider_response.request_id}`);
|
|
231
|
+
if (!run.result?.inline && run.result?.available)
|
|
232
|
+
lines.push(` output not inlined (${run.result.bytes} bytes): agentrouter runs get ${run.run_id} --output out.json`);
|
|
233
|
+
for (const hint of run.hints ?? [])
|
|
234
|
+
lines.push(` → ${hint.message}`);
|
|
235
|
+
return lines.join("\n");
|
|
236
|
+
}
|
|
237
|
+
async function waitForRun(runId, timeoutMs) {
|
|
238
|
+
const deadline = Date.now() + timeoutMs;
|
|
239
|
+
let result = await http("GET", `/v1/runs/${encodeURIComponent(runId)}`);
|
|
240
|
+
while (result.status === 200 && ["RUNNING", "READY", "STOPPING"].includes(result.json?.status) && Date.now() < deadline) {
|
|
241
|
+
info(`… ${runId} still running`);
|
|
242
|
+
result = await http("GET", `/v1/runs/${encodeURIComponent(runId)}?wait_ms=${Math.min(20000, Math.max(1000, deadline - Date.now()))}`);
|
|
243
|
+
}
|
|
244
|
+
return result;
|
|
245
|
+
}
|
|
246
|
+
try {
|
|
247
|
+
switch (command) {
|
|
248
|
+
case "connect":
|
|
249
|
+
case "login": {
|
|
250
|
+
const connected = (me) => {
|
|
251
|
+
const id = me?.account?.id ?? me?.wallet_owner;
|
|
252
|
+
if (!id)
|
|
253
|
+
throw new CliError("The API did not return an account ID.", EXIT.error);
|
|
254
|
+
print({ connected: true, account: { id, email: me.account?.email ?? null }, base_url: baseUrl }, `Connected as ${me.account?.email ?? id} on ${baseUrl}.`);
|
|
255
|
+
return EXIT.ok;
|
|
256
|
+
};
|
|
257
|
+
if (command === "connect") {
|
|
258
|
+
try {
|
|
259
|
+
const me = await http("GET", "/v1/me");
|
|
260
|
+
if (me.status === 200)
|
|
261
|
+
return connected(me.json);
|
|
262
|
+
if (me.status !== 401)
|
|
263
|
+
fail(me);
|
|
264
|
+
}
|
|
265
|
+
catch (error) {
|
|
266
|
+
if (!(error instanceof CliError && error.exitCode === EXIT.auth))
|
|
267
|
+
throw error;
|
|
268
|
+
}
|
|
269
|
+
if (flags["api-key"] || env.AGENTROUTER_API_KEY)
|
|
270
|
+
throw new CliError("The supplied API key is invalid. Unset it to connect with your browser.", EXIT.auth);
|
|
271
|
+
}
|
|
272
|
+
if (command === "login" && io.isTTY === false && !flags["no-browser"]) {
|
|
273
|
+
info("No interactive terminal: set AGENTROUTER_API_KEY instead of logging in.");
|
|
274
|
+
return EXIT.auth;
|
|
275
|
+
}
|
|
276
|
+
const scopes = ["read", "invoke", "topup", "feedback", "dispute"];
|
|
277
|
+
const result = await browserLogin({ baseUrl, scopes, openBrowser: !flags["no-browser"] && io.openBrowser !== false, timeoutMs: 5 * 60000, fetchImpl, log: info });
|
|
278
|
+
const stored = { kind: "oauth", baseUrl, accessToken: result.accessToken, refreshToken: result.refreshToken, expiresAt: Date.now() + result.expiresIn * 1000, scope: result.scope };
|
|
279
|
+
const path = await saveCredential(env, stored);
|
|
280
|
+
if (command === "connect") {
|
|
281
|
+
const me = await http("GET", "/v1/me");
|
|
282
|
+
if (me.status !== 200)
|
|
283
|
+
fail(me);
|
|
284
|
+
return connected(me.json);
|
|
285
|
+
}
|
|
286
|
+
print({ signed_in: true, scope: result.scope, credentials: path }, `Signed in (${result.scope}). Credentials saved to ${path} (mode 600).`);
|
|
287
|
+
return EXIT.ok;
|
|
288
|
+
}
|
|
289
|
+
case "logout": {
|
|
290
|
+
const stored = await loadCredential(env);
|
|
291
|
+
if (stored && stored.baseUrl !== baseUrl)
|
|
292
|
+
throw new CliError("Saved credentials belong to another API. Use its base URL to log out.", EXIT.auth);
|
|
293
|
+
if (stored?.kind === "oauth")
|
|
294
|
+
await revokeToken(stored.baseUrl, stored.refreshToken, fetchImpl);
|
|
295
|
+
await deleteCredential(env);
|
|
296
|
+
print({ signed_out: true }, "Signed out. API keys you created stay valid until you remove them (agentrouter keys remove).");
|
|
297
|
+
return EXIT.ok;
|
|
298
|
+
}
|
|
299
|
+
case "whoami": {
|
|
300
|
+
const result = await http("GET", "/v1/me");
|
|
301
|
+
if (result.status !== 200)
|
|
302
|
+
fail(result);
|
|
303
|
+
const { source } = await credential();
|
|
304
|
+
const me = result.json;
|
|
305
|
+
print({ ...me, credential_source: source }, `${me.account.email} (wallet ${me.wallet_owner})\n via ${me.caller.type} "${me.caller.name}" [${source}]\n scopes: ${me.scopes.map((s) => s.scope).join(", ")}`);
|
|
306
|
+
return EXIT.ok;
|
|
307
|
+
}
|
|
308
|
+
case "setup": {
|
|
309
|
+
const text = [
|
|
310
|
+
"Pick one entry for an agent; all share the same wallet, runs and prices:",
|
|
311
|
+
" • Your agent host already has the AgentRouter MCP connected → use it; no CLI needed.",
|
|
312
|
+
" • Codex / Claude Code / Cursor → install the AgentRouter plugin (MCP + skill): https://docs.agentrouter.to/integrations/plugin",
|
|
313
|
+
" • Terminal, scripts, files → this CLI: `agentrouter connect`, then find → describe → invoke.",
|
|
314
|
+
" • CI / servers → AGENTROUTER_API_KEY with this CLI or the HTTP API (https://docs.agentrouter.to/api).",
|
|
315
|
+
"MCP and CLI sign in separately; check the wallet with `agentrouter whoami` before mixing them."
|
|
316
|
+
].join("\n");
|
|
317
|
+
print({ entries: ["mcp", "plugin", "cli", "http"] }, text);
|
|
318
|
+
return EXIT.ok;
|
|
319
|
+
}
|
|
320
|
+
case "keys": {
|
|
321
|
+
if ((sub === "set" || sub === "clear") && rest.length)
|
|
322
|
+
throw new CliError("usage: agentrouter keys set | clear", EXIT.usage);
|
|
323
|
+
if (sub === "set") {
|
|
324
|
+
const readKey = io.readKey ?? (await import("./terminal.js")).readKey;
|
|
325
|
+
const apiKey = (await readKey()).trim();
|
|
326
|
+
if (!API_KEY_FORMAT.test(apiKey)) {
|
|
327
|
+
throw new CliError("Enter a complete AgentRouter API key from Settings → API keys.", EXIT.usage);
|
|
328
|
+
}
|
|
329
|
+
const path = await saveCredential(env, { kind: "api_key", baseUrl, apiKey });
|
|
330
|
+
print({ saved: true, path }, `API key saved to ${path}. Run agentrouter whoami to verify your account.`);
|
|
331
|
+
return EXIT.ok;
|
|
332
|
+
}
|
|
333
|
+
if (sub === "clear") {
|
|
334
|
+
if ((await loadCredential(env))?.kind === "oauth")
|
|
335
|
+
throw new CliError("Use agentrouter logout to revoke your browser login.", EXIT.usage);
|
|
336
|
+
await deleteCredential(env);
|
|
337
|
+
print({ cleared: true }, "Local key cleared. To revoke it, open Settings → API keys.");
|
|
338
|
+
return EXIT.ok;
|
|
339
|
+
}
|
|
340
|
+
if (sub === "activate") {
|
|
341
|
+
const key = rest[0];
|
|
342
|
+
if (!key)
|
|
343
|
+
throw new CliError("usage: agentrouter keys activate <ar_live_… key>", EXIT.usage);
|
|
344
|
+
const path = await saveCredential(env, { kind: "api_key", baseUrl, apiKey: key });
|
|
345
|
+
print({ activated: true, credentials: path }, `Key stored in ${path} (mode 600). It is used when AGENTROUTER_API_KEY is not set.`);
|
|
346
|
+
return EXIT.ok;
|
|
347
|
+
}
|
|
348
|
+
if (sub === "list") {
|
|
349
|
+
const result = await http("GET", "/v1/keys");
|
|
350
|
+
if (result.status !== 200)
|
|
351
|
+
fail(result);
|
|
352
|
+
print(result.json, result.json.keys.map((key) => `${key.key_id} ${key.name} ${key.display} ${key.revoked_at ? "revoked" : "active"} [${key.scopes.join(",")}]`).join("\n") || "No keys.");
|
|
353
|
+
return EXIT.ok;
|
|
354
|
+
}
|
|
355
|
+
if (sub === "add") {
|
|
356
|
+
const name = rest[0];
|
|
357
|
+
if (!name)
|
|
358
|
+
throw new CliError("usage: agentrouter keys add <name> [--scope read --scope invoke …]", EXIT.usage);
|
|
359
|
+
const result = await http("POST", "/v1/keys", { name, ...(flags.scope ? { scopes: flags.scope } : {}) });
|
|
360
|
+
if (result.status !== 200 && result.status !== 201)
|
|
361
|
+
fail(result);
|
|
362
|
+
print(result.json, `Created ${result.json.key_id} (${result.json.scopes.join(", ")}).\n${result.json.secret}\nStore it now; it is not shown again.`);
|
|
363
|
+
return EXIT.ok;
|
|
364
|
+
}
|
|
365
|
+
if (sub === "remove") {
|
|
366
|
+
const keyId = rest[0];
|
|
367
|
+
if (!keyId)
|
|
368
|
+
throw new CliError("usage: agentrouter keys remove <key_id>", EXIT.usage);
|
|
369
|
+
const result = await http("DELETE", `/v1/keys/${encodeURIComponent(keyId)}`);
|
|
370
|
+
if (result.status !== 200)
|
|
371
|
+
fail(result);
|
|
372
|
+
print(result.json, `Revoked ${keyId}.`);
|
|
373
|
+
return EXIT.ok;
|
|
374
|
+
}
|
|
375
|
+
throw new CliError("usage: agentrouter keys list | add <name> | remove <key_id> | activate <key> | set | clear", EXIT.usage);
|
|
376
|
+
}
|
|
377
|
+
case "find": {
|
|
378
|
+
const query = [sub, ...rest].filter(Boolean).join(" ");
|
|
379
|
+
if (!query)
|
|
380
|
+
throw new CliError('usage: agentrouter find "<task>"', EXIT.usage);
|
|
381
|
+
const result = await http("POST", "/v1/find", { query, limit: flags.limit ? Number(flags.limit) : undefined, provider: flags.provider, category_ids: typeof flags.category === "string" ? flags.category.split(",").map((id) => id.trim()) : undefined, group_ids: typeof flags.group === "string" ? flags.group.split(",").map((id) => id.trim()) : undefined }, {}, true);
|
|
382
|
+
if (result.status !== 200)
|
|
383
|
+
fail(result);
|
|
384
|
+
const found = result.json;
|
|
385
|
+
const lines = found.tools.map((tool) => `${tool.tool_id.padEnd(34)} ${tool.fit.padEnd(7)} ${tool.price.summary} [health ${tool.health.status}]\n ${tool.summary}`);
|
|
386
|
+
print(found, found.match === "none" ? "No matching tool. Request it: agentrouter tools request --capability \"…\" --note \"…\"" : `match: ${found.match}\n${lines.join("\n")}`);
|
|
387
|
+
return EXIT.ok;
|
|
388
|
+
}
|
|
389
|
+
case "describe": {
|
|
390
|
+
if (!sub)
|
|
391
|
+
throw new CliError("usage: agentrouter describe <tool_id>", EXIT.usage);
|
|
392
|
+
const result = await http("POST", "/v1/describe", { tool_id: sub }, {}, true);
|
|
393
|
+
if (result.status !== 200)
|
|
394
|
+
fail(result);
|
|
395
|
+
const tool = result.json;
|
|
396
|
+
await saveContract(env, `${baseUrl}:${tool.tool_id}`, { toolVersion: tool.tool_version, pricingVersion: tool.pricing.pricing_version, maxPerCallUsd: tool.pricing.max_per_call_usd, describedAt: new Date().toISOString() });
|
|
397
|
+
const required = (tool.input_schema?.required ?? []).join(", ") || "none";
|
|
398
|
+
print(tool, [
|
|
399
|
+
`${tool.tool_id} (${tool.tool_version}) — ${tool.title}`,
|
|
400
|
+
` ${tool.description}`,
|
|
401
|
+
` required input: ${required}`,
|
|
402
|
+
` price: ${tool.pricing.summary} [${tool.pricing.multiplier_label}] pricing_version ${tool.pricing.pricing_version}`,
|
|
403
|
+
` provider errors: ${tool.pricing.rules.provider_error}; empty results: ${tool.pricing.rules.empty_result}`,
|
|
404
|
+
` ${tool.execution.mode === "async" ? "may run long (poll the run)" : "synchronous"}; stoppable: ${tool.execution.stoppable}`,
|
|
405
|
+
` examples: ${JSON.stringify(tool.examples?.[0]?.input ?? {})}`,
|
|
406
|
+
" full schema: agentrouter describe <tool> --json"
|
|
407
|
+
].join("\n"));
|
|
408
|
+
return EXIT.ok;
|
|
409
|
+
}
|
|
410
|
+
case "invoke": {
|
|
411
|
+
if (!sub)
|
|
412
|
+
throw new CliError("usage: agentrouter invoke <tool_id> --input <json|@file>", EXIT.usage);
|
|
413
|
+
const input = await readInput(flags.input);
|
|
414
|
+
const idempotencyKey = typeof flags["idempotency-key"] === "string" ? flags["idempotency-key"] : randomUUID();
|
|
415
|
+
if (!flags["idempotency-key"])
|
|
416
|
+
info(`idempotency key ${idempotencyKey} (reuse it to retry without a second charge)`);
|
|
417
|
+
const me = await http("GET", "/v1/me");
|
|
418
|
+
if (me.status !== 200)
|
|
419
|
+
fail(me);
|
|
420
|
+
if (typeof me.json?.wallet_owner !== "string")
|
|
421
|
+
throw new CliError("The API did not identify the wallet owner", EXIT.error);
|
|
422
|
+
const path = invocationPath(env, baseUrl, me.json.wallet_owner, idempotencyKey);
|
|
423
|
+
const intent = {
|
|
424
|
+
tool_id: sub,
|
|
425
|
+
input,
|
|
426
|
+
...(typeof flags["max-cost-usd"] === "string" ? { max_cost_usd: flags["max-cost-usd"] } : {}),
|
|
427
|
+
...(typeof flags.session === "string" ? { session_id: flags.session } : {})
|
|
428
|
+
};
|
|
429
|
+
let body = await loadInvocation(path);
|
|
430
|
+
if (!body) {
|
|
431
|
+
let contract = (await loadContracts(env))[`${baseUrl}:${sub}`];
|
|
432
|
+
if (!contract) {
|
|
433
|
+
const described = await http("POST", "/v1/describe", { tool_id: sub }, {}, true);
|
|
434
|
+
if (described.status !== 200)
|
|
435
|
+
fail(described);
|
|
436
|
+
contract = { toolVersion: described.json.tool_version, pricingVersion: described.json.pricing.pricing_version, maxPerCallUsd: described.json.pricing.max_per_call_usd, describedAt: new Date().toISOString() };
|
|
437
|
+
await saveContract(env, `${baseUrl}:${sub}`, contract);
|
|
438
|
+
info(`Described ${sub}: ${described.json.pricing.summary}`);
|
|
439
|
+
}
|
|
440
|
+
body = await saveInvocation(env, path, {
|
|
441
|
+
...intent,
|
|
442
|
+
tool_version: contract.toolVersion,
|
|
443
|
+
pricing_version: typeof flags["pricing-version"] === "string" ? flags["pricing-version"] : contract.pricingVersion
|
|
444
|
+
});
|
|
445
|
+
}
|
|
446
|
+
const { tool_version: savedVersion, pricing_version: savedPrice, ...savedIntent } = body;
|
|
447
|
+
if (!isDeepStrictEqual(savedIntent, intent) || (typeof flags["pricing-version"] === "string" && flags["pricing-version"] !== savedPrice)) {
|
|
448
|
+
throw new CliError("This idempotency key already belongs to a different request. Retry the original input/options or use a new key.", EXIT.usage);
|
|
449
|
+
}
|
|
450
|
+
info(`Using saved contract ${savedVersion ?? "unspecified"} / ${savedPrice}`);
|
|
451
|
+
const result = await http("POST", "/v1/invoke", body, { "idempotency-key": idempotencyKey }, true);
|
|
452
|
+
if (result.json?.error && !result.json?.run_id && !result.json?.run) {
|
|
453
|
+
if (result.json.error.code === "PRICING_CHANGED" || result.json.error.code === "TOOL_VERSION_CHANGED") {
|
|
454
|
+
info("The price or version changed since you described this tool. Nothing ran. Review it with `agentrouter describe " + sub + "` and invoke with a new idempotency key.");
|
|
455
|
+
}
|
|
456
|
+
fail(result);
|
|
457
|
+
}
|
|
458
|
+
let final = result;
|
|
459
|
+
if (result.json?.run_id && ["RUNNING", "READY"].includes(result.json.status) && flags.wait) {
|
|
460
|
+
final = await waitForRun(result.json.run_id, Number(flags["timeout-ms"]) || 10 * 60000);
|
|
461
|
+
}
|
|
462
|
+
const run = final.json?.run_id ? final.json : final.json?.run;
|
|
463
|
+
print(final.text, describeRun(run));
|
|
464
|
+
if (typeof flags.output === "string" && run?.result?.available)
|
|
465
|
+
await exportOutput(run.run_id, flags.output);
|
|
466
|
+
return runExit(run);
|
|
467
|
+
}
|
|
468
|
+
case "runs": {
|
|
469
|
+
if (sub === "get") {
|
|
470
|
+
const runId = rest[0];
|
|
471
|
+
if (!runId)
|
|
472
|
+
throw new CliError("usage: agentrouter runs get <run_id> [--wait] [--output file]", EXIT.usage);
|
|
473
|
+
const result = flags.wait ? await waitForRun(runId, Number(flags["timeout-ms"]) || 10 * 60000) : await http("GET", `/v1/runs/${encodeURIComponent(runId)}`);
|
|
474
|
+
if (result.status !== 200)
|
|
475
|
+
fail(result);
|
|
476
|
+
print(result.text, describeRun(result.json));
|
|
477
|
+
if (typeof flags.output === "string") {
|
|
478
|
+
if (!result.json.result?.available)
|
|
479
|
+
throw new CliError("This run has no stored output to export.", EXIT.notFound);
|
|
480
|
+
await exportOutput(runId, flags.output);
|
|
481
|
+
}
|
|
482
|
+
return runExit(result.json);
|
|
483
|
+
}
|
|
484
|
+
if (sub === "list") {
|
|
485
|
+
const query = new URLSearchParams();
|
|
486
|
+
if (typeof flags.session === "string")
|
|
487
|
+
query.set("session_id", flags.session);
|
|
488
|
+
if (typeof flags.status === "string")
|
|
489
|
+
query.set("status", flags.status);
|
|
490
|
+
if (typeof flags.limit === "string")
|
|
491
|
+
query.set("limit", flags.limit);
|
|
492
|
+
const result = await http("GET", `/v1/runs?${query.toString()}`);
|
|
493
|
+
if (result.status !== 200)
|
|
494
|
+
fail(result);
|
|
495
|
+
print(result.json, result.json.runs.map((run) => `${run.run_id} ${run.status.padEnd(9)} ${run.tool_id.padEnd(32)} $${run.billing.customer_charge_usd} ${run.created_at}`).join("\n") || "No runs.");
|
|
496
|
+
return EXIT.ok;
|
|
497
|
+
}
|
|
498
|
+
if (sub === "stop") {
|
|
499
|
+
const runId = rest[0];
|
|
500
|
+
if (!runId)
|
|
501
|
+
throw new CliError("usage: agentrouter runs stop <run_id>", EXIT.usage);
|
|
502
|
+
const result = await http("POST", `/v1/runs/${encodeURIComponent(runId)}/stop`);
|
|
503
|
+
if (result.status !== 200)
|
|
504
|
+
fail(result);
|
|
505
|
+
print(result.text, `Stop requested; status now ${result.json.status}. Check with \`agentrouter runs get ${runId}\`.`);
|
|
506
|
+
return EXIT.ok;
|
|
507
|
+
}
|
|
508
|
+
throw new CliError("usage: agentrouter runs get|list|stop", EXIT.usage);
|
|
509
|
+
}
|
|
510
|
+
case "balance": {
|
|
511
|
+
const result = await http("GET", "/v1/wallet");
|
|
512
|
+
if (result.status !== 200)
|
|
513
|
+
fail(result);
|
|
514
|
+
print(result.json, `Available $${result.json.available_usd} · reserved $${result.json.reserved_usd} (USD)`);
|
|
515
|
+
return EXIT.ok;
|
|
516
|
+
}
|
|
517
|
+
case "topup": {
|
|
518
|
+
const amount = flags["amount-usd"];
|
|
519
|
+
if (typeof amount !== "string")
|
|
520
|
+
throw new CliError("usage: agentrouter topup --amount-usd 10", EXIT.usage);
|
|
521
|
+
const result = await http("POST", "/v1/wallet/topups", { amount_usd: amount });
|
|
522
|
+
if (result.status !== 200 && result.status !== 201)
|
|
523
|
+
fail(result);
|
|
524
|
+
const topup = result.json;
|
|
525
|
+
print(topup, `Pay $${topup.quote.total_usd} ($${topup.quote.amount_usd} to wallet + $${topup.quote.fee_usd} fee):\n${topup.checkout_url}\nThe balance changes only after payment completes.`);
|
|
526
|
+
if (flags.open)
|
|
527
|
+
(await import("./terminal.js")).openInBrowser(topup.checkout_url);
|
|
528
|
+
return EXIT.ok;
|
|
529
|
+
}
|
|
530
|
+
case "feedback": {
|
|
531
|
+
if (typeof flags.text !== "string")
|
|
532
|
+
throw new CliError('usage: agentrouter feedback --text "..." [--run id]', EXIT.usage);
|
|
533
|
+
const result = await http("POST", "/v1/feedback", { kind: "feedback", text: flags.text, run_id: Array.isArray(flags.run) ? flags.run[0] : undefined, category: flags.category });
|
|
534
|
+
if (result.status !== 200 && result.status !== 201)
|
|
535
|
+
fail(result);
|
|
536
|
+
print(result.json, `Recorded ${result.json.feedback_id}. ${result.json.note ?? ""}`);
|
|
537
|
+
return EXIT.ok;
|
|
538
|
+
}
|
|
539
|
+
case "tools": {
|
|
540
|
+
if (sub !== "request" || typeof flags.capability !== "string")
|
|
541
|
+
throw new CliError('usage: agentrouter tools request --capability "..." --note "..."', EXIT.usage);
|
|
542
|
+
const result = await http("POST", "/v1/feedback", { kind: "tool_request", capability: flags.capability, text: typeof flags.note === "string" ? flags.note : flags.capability });
|
|
543
|
+
if (result.status !== 200 && result.status !== 201)
|
|
544
|
+
fail(result);
|
|
545
|
+
print(result.json, `Recorded request ${result.json.feedback_id}. ${result.json.note ?? ""}`);
|
|
546
|
+
return EXIT.ok;
|
|
547
|
+
}
|
|
548
|
+
case "dispute": {
|
|
549
|
+
if (sub === "create") {
|
|
550
|
+
const runs = flags.run ?? [];
|
|
551
|
+
if (runs.length === 0 || typeof flags.goal !== "string" || typeof flags.reason !== "string") {
|
|
552
|
+
throw new CliError('usage: agentrouter dispute create --run <id> --goal "..." --reason "..."', EXIT.usage);
|
|
553
|
+
}
|
|
554
|
+
const result = await http("POST", "/v1/disputes", { run_ids: runs, goal: flags.goal, reason: flags.reason, evidence: flags.evidence, find_query: flags["find-query"] });
|
|
555
|
+
if (result.status !== 200 && result.status !== 201)
|
|
556
|
+
fail(result);
|
|
557
|
+
print(result.json, `Dispute ${result.json.dispute_id} ${result.json.status}. A person reviews it; refunds are not automatic.`);
|
|
558
|
+
return EXIT.ok;
|
|
559
|
+
}
|
|
560
|
+
if (sub === "reply") {
|
|
561
|
+
if (!rest[0] || typeof flags.evidence !== "string")
|
|
562
|
+
throw new CliError('usage: agentrouter dispute reply <dispute_id> --evidence "..."', EXIT.usage);
|
|
563
|
+
const result = await http("POST", `/v1/disputes/${encodeURIComponent(rest[0])}/info`, { evidence: flags.evidence });
|
|
564
|
+
if (result.status !== 200 && result.status !== 201)
|
|
565
|
+
fail(result);
|
|
566
|
+
print(result.json, `${result.json.dispute_id} ${result.json.status}. Information submitted for review.`);
|
|
567
|
+
return EXIT.ok;
|
|
568
|
+
}
|
|
569
|
+
if (sub === "get") {
|
|
570
|
+
if (!rest[0])
|
|
571
|
+
throw new CliError("usage: agentrouter dispute get <dispute_id>", EXIT.usage);
|
|
572
|
+
const result = await http("GET", `/v1/disputes/${encodeURIComponent(rest[0])}`);
|
|
573
|
+
if (result.status !== 200)
|
|
574
|
+
fail(result);
|
|
575
|
+
const request = result.json.status === "NEEDS_INFO" ? [...(result.json.history ?? [])].reverse().find((entry) => entry.to === "NEEDS_INFO")?.note : null;
|
|
576
|
+
print(result.json, `${result.json.dispute_id} ${result.json.status} (refund ${result.json.refund_status})${result.json.decision ? `: ${result.json.decision.reason}` : ""}${request ? `\nReviewer asks: ${request}\nReply with: agentrouter dispute reply ${result.json.dispute_id} --evidence "..."` : ""}`);
|
|
577
|
+
return EXIT.ok;
|
|
578
|
+
}
|
|
579
|
+
throw new CliError("usage: agentrouter dispute create|get|reply", EXIT.usage);
|
|
580
|
+
}
|
|
581
|
+
default:
|
|
582
|
+
stderr(`Unknown command "${command}".\n\n${HELP}`);
|
|
583
|
+
return EXIT.usage;
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
catch (error) {
|
|
587
|
+
if (error instanceof CliError) {
|
|
588
|
+
if (flags.json && error.body !== undefined)
|
|
589
|
+
stdout(`${typeof error.body === "string" ? error.body : JSON.stringify(error.body)}\n`);
|
|
590
|
+
stderr(`${error.message}\n`);
|
|
591
|
+
return error.exitCode;
|
|
592
|
+
}
|
|
593
|
+
stderr(`${error.message}\n`);
|
|
594
|
+
return EXIT.error;
|
|
595
|
+
}
|
|
596
|
+
}
|