@agentrouter/agentrouter 0.1.7

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,563 @@
1
+ import { readFile as readFileFromFs } from "node:fs/promises";
2
+ import process from "node:process";
3
+ import { AGENTIC_API_INSTALL_URL, AgentRouterClient, AgentRouterClientError, DEFAULT_AGENTIC_API_BASE_URL, } from "./index.js";
4
+ const BOOLEAN_FLAGS = new Set(["allow-fallback", "help", "json"]);
5
+ const MULTI_VALUE_FLAGS = new Set(["query"]);
6
+ function createRuntime(io = {}) {
7
+ return {
8
+ env: io.env ?? process.env,
9
+ stdout: io.stdout ?? ((value) => process.stdout.write(value)),
10
+ stderr: io.stderr ?? ((value) => process.stderr.write(value)),
11
+ readFile: io.readFile ?? ((path) => readFileFromFs(path, "utf8")),
12
+ ...(io.fetch ? { fetch: io.fetch } : {}),
13
+ };
14
+ }
15
+ function renderHelp() {
16
+ return `AgentRouter CLI
17
+
18
+ Usage:
19
+ agentrouter wallet [--json]
20
+ agentrouter usage [--limit 20] [--json]
21
+ agentrouter domains list [--json]
22
+ agentrouter domains get <domain> [--json]
23
+ agentrouter capabilities list <domain> [--json]
24
+ agentrouter capabilities get <domain> <capability> [--json]
25
+ agentrouter capabilities routes <domain> <capability> [--json]
26
+ agentrouter capabilities contract <domain> <capability> [--json]
27
+ agentrouter routes context <routeKey> [--json]
28
+ agentrouter recommend <domain> <capability> --input <json|@file> [--json]
29
+ agentrouter execute <domain> <capability> --input <json|@file> [--route-key <key>] [--provider <key>] [--allow-fallback] [--json]
30
+ agentrouter route <domain> --input <json|@file> [--json]
31
+ agentrouter raw <method> <path> [--auth none|api-key|session] [--query key=value] [--input <json|@file>] [--json]
32
+
33
+ Global flags:
34
+ --base-url <url> Default: ${DEFAULT_AGENTIC_API_BASE_URL}
35
+ --api-key <key> Overrides AGENTIC_API_KEY
36
+ --session-token <token> Overrides AGENTIC_API_SESSION_TOKEN
37
+ --user-id <id> Local development fallback identity
38
+ --timeout <ms> Request timeout in milliseconds
39
+ --json Emit structured JSON instead of formatted text
40
+ --help Show this help text
41
+
42
+ Get an API key:
43
+ 1. Sign in at ${AGENTIC_API_INSTALL_URL}
44
+ 2. Copy your API key
45
+ 3. export AGENTIC_API_KEY=your_key_here
46
+
47
+ Environment variables:
48
+ AGENTIC_API_BASE_URL
49
+ AGENTIC_API_KEY
50
+ AGENTIC_API_SESSION_TOKEN
51
+ AGENTIC_API_USER_ID
52
+ AGENTIC_API_TIMEOUT_MS
53
+
54
+ Examples:
55
+ agentrouter domains list
56
+ agentrouter capabilities list email
57
+ agentrouter routes context email.send.resend
58
+ agentrouter recommend email send --input '{"optimizationPreferences":["cost"]}' --json
59
+ agentrouter execute email send --input @send-email.json --route-key email.send.resend --allow-fallback
60
+ agentrouter route enrichment --input '{"intent":"Find the work email for the VP Engineering at Example Corp"}'
61
+ agentrouter raw get /domains/email/capabilities/send/contract
62
+ `;
63
+ }
64
+ function parseArgv(argv) {
65
+ const flags = {
66
+ allowFallback: false,
67
+ help: false,
68
+ json: false,
69
+ query: [],
70
+ };
71
+ const positionals = [];
72
+ for (let index = 0; index < argv.length; index += 1) {
73
+ const token = argv[index];
74
+ if (!token) {
75
+ continue;
76
+ }
77
+ if (token === "-h") {
78
+ flags.help = true;
79
+ continue;
80
+ }
81
+ if (!token.startsWith("--")) {
82
+ positionals.push(token);
83
+ continue;
84
+ }
85
+ const equalIndex = token.indexOf("=");
86
+ const rawName = equalIndex >= 0 ? token.slice(2, equalIndex) : token.slice(2);
87
+ const inlineValue = equalIndex >= 0 ? token.slice(equalIndex + 1) : undefined;
88
+ if (BOOLEAN_FLAGS.has(rawName)) {
89
+ const resolved = inlineValue ?? "true";
90
+ const normalized = resolved.toLowerCase();
91
+ if (normalized !== "true" && normalized !== "false") {
92
+ throw new Error(`Flag --${rawName} only accepts true or false.`);
93
+ }
94
+ const value = normalized === "true";
95
+ if (rawName === "allow-fallback") {
96
+ flags.allowFallback = value;
97
+ }
98
+ if (rawName === "help") {
99
+ flags.help = value;
100
+ }
101
+ if (rawName === "json") {
102
+ flags.json = value;
103
+ }
104
+ continue;
105
+ }
106
+ const nextValue = inlineValue ?? argv[index + 1];
107
+ if (typeof nextValue === "undefined") {
108
+ throw new Error(`Flag --${rawName} requires a value.`);
109
+ }
110
+ if (typeof inlineValue === "undefined") {
111
+ index += 1;
112
+ }
113
+ if (MULTI_VALUE_FLAGS.has(rawName)) {
114
+ flags.query.push(nextValue);
115
+ continue;
116
+ }
117
+ switch (rawName) {
118
+ case "api-key":
119
+ flags.apiKey = nextValue;
120
+ break;
121
+ case "auth":
122
+ flags.auth = nextValue;
123
+ break;
124
+ case "base-url":
125
+ flags.baseUrl = nextValue;
126
+ break;
127
+ case "input":
128
+ flags.input = nextValue;
129
+ break;
130
+ case "limit":
131
+ flags.limit = nextValue;
132
+ break;
133
+ case "provider":
134
+ flags.provider = nextValue;
135
+ break;
136
+ case "route-key":
137
+ flags.routeKey = nextValue;
138
+ break;
139
+ case "session-token":
140
+ flags.sessionToken = nextValue;
141
+ break;
142
+ case "timeout":
143
+ flags.timeout = nextValue;
144
+ break;
145
+ case "user-id":
146
+ flags.userId = nextValue;
147
+ break;
148
+ default:
149
+ throw new Error(`Unknown flag --${rawName}.`);
150
+ }
151
+ }
152
+ return {
153
+ flags,
154
+ positionals,
155
+ };
156
+ }
157
+ function resolveNumber(value, flagName) {
158
+ if (typeof value === "undefined") {
159
+ return undefined;
160
+ }
161
+ const parsed = Number(value);
162
+ if (!Number.isFinite(parsed) || parsed < 0) {
163
+ throw new Error(`Flag ${flagName} must be a non-negative number.`);
164
+ }
165
+ return parsed;
166
+ }
167
+ function resolveInputSource(value, label) {
168
+ if (!value) {
169
+ throw new Error(`Missing ${label}. Pass --input <json> or --input @file.json.`);
170
+ }
171
+ return value;
172
+ }
173
+ async function parseJsonInput(inputValue, runtime) {
174
+ const rawInput = inputValue.startsWith("@")
175
+ ? await runtime.readFile(inputValue.slice(1))
176
+ : inputValue;
177
+ let parsed;
178
+ try {
179
+ parsed = JSON.parse(rawInput);
180
+ }
181
+ catch (error) {
182
+ throw new Error(`Failed to parse JSON input: ${error instanceof Error ? error.message : "Unknown parse error."}`);
183
+ }
184
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
185
+ throw new Error("CLI input JSON must be an object.");
186
+ }
187
+ return parsed;
188
+ }
189
+ function resolveAuthMode(value) {
190
+ const normalized = value?.trim().toLowerCase();
191
+ if (!normalized || normalized === "none") {
192
+ return "none";
193
+ }
194
+ if (normalized === "api-key" || normalized === "apikey") {
195
+ return "apiKey";
196
+ }
197
+ if (normalized === "session") {
198
+ return "session";
199
+ }
200
+ throw new Error("Flag --auth must be one of: none, api-key, session.");
201
+ }
202
+ function parseQueryArgs(values) {
203
+ if (values.length === 0) {
204
+ return undefined;
205
+ }
206
+ const query = {};
207
+ for (const item of values) {
208
+ const equalIndex = item.indexOf("=");
209
+ if (equalIndex <= 0) {
210
+ throw new Error("Each --query value must be in key=value format.");
211
+ }
212
+ const key = item.slice(0, equalIndex).trim();
213
+ const value = item.slice(equalIndex + 1);
214
+ if (!key) {
215
+ throw new Error("Each --query value must include a key before '='.");
216
+ }
217
+ query[key] = value;
218
+ }
219
+ return query;
220
+ }
221
+ function printJson(value, runtime) {
222
+ runtime.stdout(`${JSON.stringify(value, null, 2)}\n`);
223
+ }
224
+ function renderTable(headers, rows) {
225
+ const widths = headers.map((header, index) => Math.max(header.length, ...rows.map((row) => (row[index] ?? "").length)));
226
+ const formatRow = (row) => row.map((cell, index) => cell.padEnd(widths[index] ?? 0)).join(" ").trimEnd();
227
+ return [formatRow(headers), formatRow(widths.map((width) => "-".repeat(width))), ...rows.map(formatRow)].join("\n");
228
+ }
229
+ function formatCredits(value) {
230
+ if (typeof value !== "number") {
231
+ return "-";
232
+ }
233
+ return String(value);
234
+ }
235
+ function formatWallet(wallet) {
236
+ return [
237
+ `userId: ${wallet.userId}`,
238
+ `balanceCredits: ${wallet.balanceCredits}`,
239
+ ].join("\n");
240
+ }
241
+ function formatDomains(domains) {
242
+ return renderTable([
243
+ "domain",
244
+ "status",
245
+ "live/total",
246
+ "startCredits",
247
+ "intentRouting",
248
+ ], domains.map((domain) => [
249
+ domain.domainKey,
250
+ domain.status,
251
+ `${domain.liveCapabilityCount}/${domain.totalCapabilityCount}`,
252
+ formatCredits(domain.startingPriceCredits),
253
+ domain.supportsIntentRouting ? "yes" : "no",
254
+ ]));
255
+ }
256
+ function formatCapabilities(capabilities) {
257
+ return renderTable(["capability", "status", "providers", "startCredits"], capabilities.map((capability) => [
258
+ capability.capabilityId,
259
+ capability.status,
260
+ capability.enabledProviders.join(",") || "-",
261
+ formatCredits(capability.startingPriceCredits),
262
+ ]));
263
+ }
264
+ function formatRoutes(routes) {
265
+ return renderTable(["route", "provider", "mode", "network", "status", "startCredits"], routes.map((route) => [
266
+ route.routeKey,
267
+ route.providerKey,
268
+ route.routeMode,
269
+ route.networkKey,
270
+ route.status,
271
+ String(route.startingCostCredits),
272
+ ]));
273
+ }
274
+ function formatUsage(usage) {
275
+ const rows = usage.items.map((item) => [
276
+ item.requestId,
277
+ item.providerKey,
278
+ item.status,
279
+ String(item.chargedCredits),
280
+ String(item.latencyMs),
281
+ ]);
282
+ return [`userId: ${usage.userId}`, renderTable(["requestId", "provider", "status", "chargedCredits", "latencyMs"], rows)].join("\n");
283
+ }
284
+ function printText(value, runtime) {
285
+ runtime.stdout(`${value}\n`);
286
+ }
287
+ function buildClient(flags, runtime) {
288
+ const timeoutMs = resolveNumber(flags.timeout ?? runtime.env.AGENTIC_API_TIMEOUT_MS, "--timeout");
289
+ return new AgentRouterClient({
290
+ apiKey: flags.apiKey ?? runtime.env.AGENTIC_API_KEY ?? null,
291
+ sessionToken: flags.sessionToken ?? runtime.env.AGENTIC_API_SESSION_TOKEN ?? null,
292
+ baseUrl: flags.baseUrl ?? runtime.env.AGENTIC_API_BASE_URL ?? DEFAULT_AGENTIC_API_BASE_URL,
293
+ ...(typeof timeoutMs === "number" ? { timeoutMs } : {}),
294
+ ...(runtime.fetch ? { fetch: runtime.fetch } : {}),
295
+ });
296
+ }
297
+ function resolveUserId(flags, runtime) {
298
+ const value = flags.userId ?? runtime.env.AGENTIC_API_USER_ID;
299
+ return value?.trim() || undefined;
300
+ }
301
+ function ensureNoUnexpectedArgs(positionals, expected) {
302
+ if (positionals.length > expected) {
303
+ throw new Error("Too many positional arguments. Use --help to inspect CLI usage.");
304
+ }
305
+ }
306
+ async function runDomainsCommand(client, args, flags, runtime) {
307
+ const action = args[0] ?? "list";
308
+ if (action === "list") {
309
+ ensureNoUnexpectedArgs(args, 1);
310
+ const domains = await client.catalog.domains.list();
311
+ if (flags.json) {
312
+ printJson(domains, runtime);
313
+ return;
314
+ }
315
+ printText(formatDomains(domains), runtime);
316
+ return;
317
+ }
318
+ if (action === "get") {
319
+ const domainKey = args[1];
320
+ if (!domainKey) {
321
+ throw new Error("Usage: agentrouter domains get <domain>");
322
+ }
323
+ ensureNoUnexpectedArgs(args, 2);
324
+ const domain = await client.catalog.domains.get(domainKey);
325
+ printJson(domain, runtime);
326
+ return;
327
+ }
328
+ throw new Error("Usage: agentrouter domains [list|get]");
329
+ }
330
+ async function runCapabilitiesCommand(client, args, flags, runtime) {
331
+ const action = args[0];
332
+ if (!action) {
333
+ throw new Error("Usage: agentrouter capabilities <list|get|routes|contract> ...");
334
+ }
335
+ if (action === "list") {
336
+ const domainKey = args[1];
337
+ if (!domainKey) {
338
+ throw new Error("Usage: agentrouter capabilities list <domain>");
339
+ }
340
+ ensureNoUnexpectedArgs(args, 2);
341
+ const capabilities = await client.catalog.capabilities.list(domainKey);
342
+ if (flags.json) {
343
+ printJson(capabilities, runtime);
344
+ return;
345
+ }
346
+ printText(formatCapabilities(capabilities), runtime);
347
+ return;
348
+ }
349
+ if (action === "get") {
350
+ const domainKey = args[1];
351
+ const capabilityId = args[2];
352
+ if (!domainKey || !capabilityId) {
353
+ throw new Error("Usage: agentrouter capabilities get <domain> <capability>");
354
+ }
355
+ ensureNoUnexpectedArgs(args, 3);
356
+ const capability = await client.catalog.capabilities.get(domainKey, capabilityId);
357
+ printJson(capability, runtime);
358
+ return;
359
+ }
360
+ if (action === "routes") {
361
+ const domainKey = args[1];
362
+ const capabilityId = args[2];
363
+ if (!domainKey || !capabilityId) {
364
+ throw new Error("Usage: agentrouter capabilities routes <domain> <capability>");
365
+ }
366
+ ensureNoUnexpectedArgs(args, 3);
367
+ const routes = await client.catalog.capabilities.routes(domainKey, capabilityId);
368
+ if (flags.json) {
369
+ printJson(routes, runtime);
370
+ return;
371
+ }
372
+ printText(formatRoutes(routes), runtime);
373
+ return;
374
+ }
375
+ if (action === "contract") {
376
+ const domainKey = args[1];
377
+ const capabilityId = args[2];
378
+ if (!domainKey || !capabilityId) {
379
+ throw new Error("Usage: agentrouter capabilities contract <domain> <capability>");
380
+ }
381
+ ensureNoUnexpectedArgs(args, 3);
382
+ const contract = await client.catalog.capabilities.contract(domainKey, capabilityId);
383
+ printJson(contract, runtime);
384
+ return;
385
+ }
386
+ throw new Error("Usage: agentrouter capabilities <list|get|routes|contract> ...");
387
+ }
388
+ async function runRoutesCommand(client, args, _flags, runtime) {
389
+ const action = args[0];
390
+ if (!action) {
391
+ throw new Error("Usage: agentrouter routes context <routeKey>");
392
+ }
393
+ if (action === "context") {
394
+ const routeKey = args[1];
395
+ if (!routeKey) {
396
+ throw new Error("Usage: agentrouter routes context <routeKey>");
397
+ }
398
+ ensureNoUnexpectedArgs(args, 2);
399
+ const context = await client.catalog.routes.context(routeKey);
400
+ printJson(context, runtime);
401
+ return;
402
+ }
403
+ throw new Error("Usage: agentrouter routes context <routeKey>");
404
+ }
405
+ async function runRecommendCommand(client, args, flags, runtime) {
406
+ const domainKey = args[0];
407
+ const capabilityId = args[1];
408
+ if (!domainKey || !capabilityId) {
409
+ throw new Error("Usage: agentrouter recommend <domain> <capability> --input <json|@file>");
410
+ }
411
+ ensureNoUnexpectedArgs(args, 2);
412
+ const input = await parseJsonInput(resolveInputSource(flags.input, "request input"), runtime);
413
+ const result = await client.capabilities.recommend({
414
+ domain: domainKey,
415
+ capability: capabilityId,
416
+ input,
417
+ ...(resolveUserId(flags, runtime) ? { userId: resolveUserId(flags, runtime) } : {}),
418
+ });
419
+ printJson(result, runtime);
420
+ }
421
+ async function runExecuteCommand(client, args, flags, runtime) {
422
+ const domainKey = args[0];
423
+ const capabilityId = args[1];
424
+ if (!domainKey || !capabilityId) {
425
+ throw new Error("Usage: agentrouter execute <domain> <capability> --input <json|@file>");
426
+ }
427
+ ensureNoUnexpectedArgs(args, 2);
428
+ const input = await parseJsonInput(resolveInputSource(flags.input, "request input"), runtime);
429
+ const userId = resolveUserId(flags, runtime);
430
+ const result = await client.capabilities.execute({
431
+ domain: domainKey,
432
+ capability: capabilityId,
433
+ input,
434
+ ...(flags.provider ? { provider: flags.provider } : {}),
435
+ ...(flags.routeKey ? { routeKey: flags.routeKey } : {}),
436
+ ...(flags.allowFallback ? { allowFallback: true } : {}),
437
+ ...(userId ? { userId } : {}),
438
+ });
439
+ printJson(result, runtime);
440
+ }
441
+ async function runRouteCommand(client, args, flags, runtime) {
442
+ const domainKey = args[0];
443
+ if (!domainKey) {
444
+ throw new Error("Usage: agentrouter route <domain> --input <json|@file>");
445
+ }
446
+ ensureNoUnexpectedArgs(args, 1);
447
+ const input = await parseJsonInput(resolveInputSource(flags.input, "request input"), runtime);
448
+ const userId = resolveUserId(flags, runtime);
449
+ const result = await client.routing.route({
450
+ domain: domainKey,
451
+ input,
452
+ ...(userId ? { userId } : {}),
453
+ });
454
+ printJson(result, runtime);
455
+ }
456
+ async function runRawCommand(client, args, flags, runtime) {
457
+ const method = args[0]?.toUpperCase();
458
+ const path = args[1];
459
+ if (!method || !path) {
460
+ throw new Error("Usage: agentrouter raw <method> <path> [--input <json|@file>]");
461
+ }
462
+ ensureNoUnexpectedArgs(args, 2);
463
+ const authMode = resolveAuthMode(flags.auth);
464
+ const userId = resolveUserId(flags, runtime);
465
+ const query = parseQueryArgs(flags.query);
466
+ const body = flags.input
467
+ ? await parseJsonInput(resolveInputSource(flags.input, "request input"), runtime)
468
+ : undefined;
469
+ const result = await client.raw.request({
470
+ path,
471
+ method: method,
472
+ ...(query ? { query } : {}),
473
+ ...(body ? { body } : {}),
474
+ authMode,
475
+ ...(userId ? { userId } : {}),
476
+ });
477
+ printJson(result, runtime);
478
+ }
479
+ export async function runAgentRouterCli(argv, io = {}) {
480
+ const runtime = createRuntime(io);
481
+ try {
482
+ const { flags, positionals } = parseArgv(argv);
483
+ if (flags.help || positionals.length === 0) {
484
+ runtime.stdout(renderHelp());
485
+ return 0;
486
+ }
487
+ const client = buildClient(flags, runtime);
488
+ const userId = resolveUserId(flags, runtime);
489
+ const command = positionals[0];
490
+ const rest = positionals.slice(1);
491
+ if (command === "wallet") {
492
+ ensureNoUnexpectedArgs(positionals, 1);
493
+ const wallet = await client.wallet.get(userId ? { userId } : {});
494
+ if (flags.json) {
495
+ printJson(wallet, runtime);
496
+ }
497
+ else {
498
+ printText(formatWallet(wallet), runtime);
499
+ }
500
+ return 0;
501
+ }
502
+ if (command === "usage") {
503
+ ensureNoUnexpectedArgs(positionals, 1);
504
+ const usage = await client.usage.list({
505
+ ...(typeof resolveNumber(flags.limit, "--limit") === "number"
506
+ ? { limit: resolveNumber(flags.limit, "--limit") }
507
+ : {}),
508
+ ...(userId ? { userId } : {}),
509
+ });
510
+ if (flags.json) {
511
+ printJson(usage, runtime);
512
+ }
513
+ else {
514
+ printText(formatUsage(usage), runtime);
515
+ }
516
+ return 0;
517
+ }
518
+ if (command === "domains") {
519
+ await runDomainsCommand(client, rest, flags, runtime);
520
+ return 0;
521
+ }
522
+ if (command === "capabilities") {
523
+ await runCapabilitiesCommand(client, rest, flags, runtime);
524
+ return 0;
525
+ }
526
+ if (command === "routes") {
527
+ await runRoutesCommand(client, rest, flags, runtime);
528
+ return 0;
529
+ }
530
+ if (command === "recommend") {
531
+ await runRecommendCommand(client, rest, flags, runtime);
532
+ return 0;
533
+ }
534
+ if (command === "execute") {
535
+ await runExecuteCommand(client, rest, flags, runtime);
536
+ return 0;
537
+ }
538
+ if (command === "route") {
539
+ await runRouteCommand(client, rest, flags, runtime);
540
+ return 0;
541
+ }
542
+ if (command === "raw") {
543
+ await runRawCommand(client, rest, flags, runtime);
544
+ return 0;
545
+ }
546
+ throw new Error(`Unknown command '${command}'. Use --help to inspect CLI usage.`);
547
+ }
548
+ catch (error) {
549
+ if (error instanceof AgentRouterClientError) {
550
+ runtime.stderr(`AgentRouterClientError ${error.status}: ${error.message}\n`);
551
+ if (error.code) {
552
+ runtime.stderr(`code: ${error.code}\n`);
553
+ }
554
+ if (error.hint) {
555
+ runtime.stderr(`hint: ${error.hint}\n`);
556
+ }
557
+ return 1;
558
+ }
559
+ runtime.stderr(`${error instanceof Error ? error.message : "Unknown CLI error."}\n`);
560
+ return 1;
561
+ }
562
+ }
563
+ export const runAgenticCli = runAgentRouterCli;
package/dist/cli.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ export {};
3
+ //# sourceMappingURL=cli.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":""}
package/dist/cli.js ADDED
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env node
2
+ import process from "node:process";
3
+ import { runAgentRouterCli } from "./cli-core.js";
4
+ runAgentRouterCli(process.argv.slice(2)).then((exitCode) => {
5
+ process.exitCode = exitCode;
6
+ });