@agentrouter/agentrouter 0.1.12 → 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/dist/index.js DELETED
@@ -1,745 +0,0 @@
1
- export const DEFAULT_AGENTIC_API_BASE_URL = "https://api.agentrouter.to/api/agentic-api";
2
- export const AGENTIC_API_INSTALL_URL = "https://www.agentrouter.to/agentic-api/install";
3
- export const DEFAULT_AGENTROUTER_BASE_URL = DEFAULT_AGENTIC_API_BASE_URL;
4
- export const AGENTROUTER_INSTALL_URL = AGENTIC_API_INSTALL_URL;
5
- function trimBaseUrl(value) {
6
- const normalized = value?.trim();
7
- if (!normalized) {
8
- return DEFAULT_AGENTIC_API_BASE_URL;
9
- }
10
- return normalized
11
- .replace(/\/\/api\.agentdiscuss\.com/i, "//api.agentrouter.to")
12
- .replace(/\/\/docs\.agentdiscuss\.com/i, "//www.agentrouter.to")
13
- .replace(/\/\/www\.agentdiscuss\.com/i, "//www.agentrouter.to")
14
- .replace(/\/\/agentdiscuss\.com/i, "//agentrouter.to")
15
- .replace(/\/\/api\.agentrouter\.com/i, "//api.agentrouter.to")
16
- .replace(/\/\/docs\.agentrouter\.com/i, "//www.agentrouter.to")
17
- .replace(/\/\/www\.agentrouter\.com/i, "//www.agentrouter.to")
18
- .replace(/\/\/agentrouter\.com/i, "//agentrouter.to")
19
- .replace(/\/$/, "");
20
- }
21
- function encodePathSegment(value) {
22
- return encodeURIComponent(value);
23
- }
24
- function isObjectRecord(value) {
25
- return typeof value === "object" && value !== null && !Array.isArray(value);
26
- }
27
- function buildUrl(baseUrl, path, query) {
28
- const normalizedPath = path.startsWith("http://") || path.startsWith("https://")
29
- ? path
30
- : `${baseUrl}${path.startsWith("/") ? path : `/${path}`}`;
31
- const url = new URL(normalizedPath);
32
- if (query) {
33
- for (const [key, value] of Object.entries(query)) {
34
- if (value === null || typeof value === "undefined") {
35
- continue;
36
- }
37
- url.searchParams.set(key, String(value));
38
- }
39
- }
40
- return url.toString();
41
- }
42
- function mergeHeaders(baseHeaders, overrideHeaders) {
43
- const headers = new Headers(baseHeaders);
44
- if (overrideHeaders) {
45
- const nextHeaders = new Headers(overrideHeaders);
46
- nextHeaders.forEach((value, key) => {
47
- headers.set(key, value);
48
- });
49
- }
50
- return headers;
51
- }
52
- function isBodyInitLike(value) {
53
- if (typeof value === "string") {
54
- return true;
55
- }
56
- if (typeof Blob !== "undefined" && value instanceof Blob) {
57
- return true;
58
- }
59
- if (typeof FormData !== "undefined" && value instanceof FormData) {
60
- return true;
61
- }
62
- if (typeof URLSearchParams !== "undefined" &&
63
- value instanceof URLSearchParams) {
64
- return true;
65
- }
66
- if (typeof ArrayBuffer !== "undefined" && value instanceof ArrayBuffer) {
67
- return true;
68
- }
69
- return false;
70
- }
71
- function serializeBody(body, headers) {
72
- if (typeof body === "undefined") {
73
- return undefined;
74
- }
75
- if (isBodyInitLike(body)) {
76
- return body;
77
- }
78
- if (!headers.has("Content-Type")) {
79
- headers.set("Content-Type", "application/json");
80
- }
81
- return JSON.stringify(body);
82
- }
83
- function extractErrorMessage(payload, fallback) {
84
- if (typeof payload.error === "string" && payload.error.trim()) {
85
- return payload.error.trim();
86
- }
87
- if (typeof payload.message === "string" && payload.message.trim()) {
88
- return payload.message.trim();
89
- }
90
- if (Array.isArray(payload.message)) {
91
- const first = payload.message.find((entry) => typeof entry === "string" && entry.trim().length > 0);
92
- if (first) {
93
- return first.trim();
94
- }
95
- }
96
- return fallback;
97
- }
98
- function attachRaw(payload, extra) {
99
- if (isJsonObject(payload)) {
100
- return {
101
- ...payload,
102
- ...extra,
103
- raw: payload,
104
- };
105
- }
106
- return {
107
- ...extra,
108
- data: payload,
109
- raw: payload,
110
- };
111
- }
112
- function isJsonObject(value) {
113
- return typeof value === "object" && value !== null && !Array.isArray(value);
114
- }
115
- function resolveFetchImplementation(fetchImpl) {
116
- if (fetchImpl) {
117
- return fetchImpl;
118
- }
119
- if (typeof fetch === "function") {
120
- return fetch.bind(globalThis);
121
- }
122
- throw new Error("No fetch implementation available. Pass fetch in AgentRouterClient options.");
123
- }
124
- function withTimeoutSignal(signal, timeoutMs) {
125
- if (!timeoutMs || timeoutMs <= 0) {
126
- return {
127
- signal,
128
- cleanup: () => { },
129
- };
130
- }
131
- const controller = new AbortController();
132
- const timeout = setTimeout(() => controller.abort(), timeoutMs);
133
- const abortListener = () => controller.abort();
134
- if (signal) {
135
- if (signal.aborted) {
136
- controller.abort();
137
- }
138
- else {
139
- signal.addEventListener("abort", abortListener, { once: true });
140
- }
141
- }
142
- return {
143
- signal: controller.signal,
144
- cleanup: () => {
145
- clearTimeout(timeout);
146
- signal?.removeEventListener("abort", abortListener);
147
- },
148
- };
149
- }
150
- export class AgentRouterClientError extends Error {
151
- constructor(message, options) {
152
- super(message);
153
- this.name = "AgentRouterClientError";
154
- this.status = options.status;
155
- this.code = options.code;
156
- this.hint = options.hint;
157
- this.details = options.details;
158
- this.rawBody = options.rawBody;
159
- }
160
- }
161
- export class AgentRouterClient {
162
- constructor(options = {}) {
163
- this.raw = {
164
- request: (options) => this.request(options),
165
- };
166
- this.intent = {
167
- resolve: (prompt) => this.request({
168
- path: "/intent/resolve",
169
- method: "POST",
170
- body: {
171
- prompt,
172
- },
173
- authMode: "none",
174
- }),
175
- };
176
- this.catalog = {
177
- domains: {
178
- list: () => this.request({
179
- path: "/domains",
180
- authMode: "none",
181
- }),
182
- get: (domainKey) => this.request({
183
- path: `/domains/${encodePathSegment(domainKey)}`,
184
- authMode: "none",
185
- }),
186
- },
187
- capabilities: {
188
- list: (domainKey) => this.request({
189
- path: `/domains/${encodePathSegment(domainKey)}/capabilities`,
190
- authMode: "none",
191
- }),
192
- get: (domainKey, capabilityId) => this.request({
193
- path: `/domains/${encodePathSegment(domainKey)}/capabilities/` +
194
- encodePathSegment(capabilityId),
195
- authMode: "none",
196
- }),
197
- routes: (domainKey, capabilityId) => this.request({
198
- path: `/domains/${encodePathSegment(domainKey)}/capabilities/` +
199
- `${encodePathSegment(capabilityId)}/routes`,
200
- authMode: "none",
201
- }),
202
- contract: (domainKey, capabilityId) => this.request({
203
- path: `/domains/${encodePathSegment(domainKey)}/capabilities/` +
204
- `${encodePathSegment(capabilityId)}/contract`,
205
- authMode: "none",
206
- }),
207
- routeContext: (domainKey, capabilityId, routeKey) => this.request({
208
- path: `/domains/${encodePathSegment(domainKey)}/capabilities/` +
209
- `${encodePathSegment(capabilityId)}/routes/` +
210
- `${encodePathSegment(routeKey)}/context`,
211
- authMode: "none",
212
- }),
213
- },
214
- routes: {
215
- context: (routeKey) => this.request({
216
- path: `/routes/${encodePathSegment(routeKey)}/context`,
217
- authMode: "none",
218
- }),
219
- },
220
- };
221
- this.capabilities = {
222
- recommend: async ({ domain, capability, input, apiKey, userId, signal, timeoutMs, }) => {
223
- const payload = await this.request({
224
- path: `/domains/${encodePathSegment(domain)}/capabilities/` +
225
- `${encodePathSegment(capability)}/recommend`,
226
- method: "POST",
227
- body: input,
228
- authMode: "apiKey",
229
- apiKey,
230
- userId,
231
- signal,
232
- timeoutMs,
233
- });
234
- return attachRaw(payload, {
235
- domainKey: domain,
236
- capabilityId: capability,
237
- });
238
- },
239
- execute: async ({ domain, capability, input, provider, routeKey, allowFallback, apiKey, userId, signal, timeoutMs, }) => {
240
- const body = {
241
- ...input,
242
- };
243
- if (typeof provider !== "undefined") {
244
- body.provider = provider;
245
- }
246
- if (typeof routeKey !== "undefined") {
247
- body.routeKey = routeKey;
248
- }
249
- if (typeof allowFallback !== "undefined") {
250
- body.allowFallback = allowFallback;
251
- }
252
- const payload = await this.request({
253
- path: `/domains/${encodePathSegment(domain)}/capabilities/` +
254
- `${encodePathSegment(capability)}/execute`,
255
- method: "POST",
256
- body,
257
- authMode: "apiKey",
258
- apiKey,
259
- userId,
260
- signal,
261
- timeoutMs,
262
- });
263
- return attachRaw(payload, {
264
- domainKey: domain,
265
- capabilityId: capability,
266
- });
267
- },
268
- };
269
- this.routing = {
270
- route: async ({ domain, input, apiKey, userId, signal, timeoutMs, }) => {
271
- const payload = await this.request({
272
- path: `/domains/${encodePathSegment(domain)}/route`,
273
- method: "POST",
274
- body: input,
275
- authMode: "apiKey",
276
- apiKey,
277
- userId,
278
- signal,
279
- timeoutMs,
280
- });
281
- return attachRaw(payload, {
282
- domainKey: domain,
283
- });
284
- },
285
- };
286
- this.wallet = {
287
- get: async ({ apiKey, userId, signal, timeoutMs, } = {}) => {
288
- const payload = await this.request({
289
- path: "/wallet",
290
- authMode: "apiKey",
291
- apiKey,
292
- userId,
293
- signal,
294
- timeoutMs,
295
- });
296
- return {
297
- userId: payload.userId,
298
- balanceCredits: payload.balanceCredits,
299
- };
300
- },
301
- };
302
- this.usage = {
303
- list: async ({ limit, apiKey, userId, signal, timeoutMs, } = {}) => {
304
- const payload = await this.request({
305
- path: "/usage",
306
- query: typeof limit === "number" ? { limit } : undefined,
307
- authMode: "apiKey",
308
- apiKey,
309
- userId,
310
- signal,
311
- timeoutMs,
312
- });
313
- return {
314
- userId: payload.userId,
315
- items: payload.items,
316
- };
317
- },
318
- };
319
- this.auth = {
320
- getGoogleOAuthUrl: async () => {
321
- const payload = await this.request({
322
- path: "/auth/google/oauth",
323
- authMode: "none",
324
- });
325
- return payload.url;
326
- },
327
- authorizeGoogle: async (code) => {
328
- const payload = await this.request({
329
- path: "/auth/authorize",
330
- method: "POST",
331
- body: {
332
- provider: "google",
333
- payload: {
334
- code,
335
- },
336
- },
337
- authMode: "none",
338
- });
339
- return {
340
- sessionToken: payload.sessionToken,
341
- account: payload.account,
342
- apiKey: payload.apiKey,
343
- balanceCredits: payload.balanceCredits,
344
- starterCreditsGranted: payload.starterCreditsGranted,
345
- starterCreditsAmount: payload.starterCreditsAmount,
346
- };
347
- },
348
- getSession: async (sessionToken) => {
349
- const resolvedSessionToken = sessionToken?.trim() || this.sessionToken;
350
- if (!resolvedSessionToken) {
351
- throw new Error("Missing session token. Pass sessionToken to getSession or set it in AgentRouterClient options.");
352
- }
353
- const payload = await this.request({
354
- path: "/auth/me",
355
- authMode: "session",
356
- sessionToken: resolvedSessionToken,
357
- });
358
- return {
359
- sessionToken: resolvedSessionToken,
360
- account: payload.account,
361
- apiKey: payload.apiKey,
362
- balanceCredits: payload.balanceCredits,
363
- starterCreditsGranted: payload.starterCreditsGranted,
364
- starterCreditsAmount: payload.starterCreditsAmount,
365
- };
366
- },
367
- };
368
- this.email = {
369
- send: {
370
- recommend: (input, options = {}) => this.capabilities.recommend({
371
- domain: "email",
372
- capability: "send",
373
- input,
374
- ...options,
375
- }),
376
- execute: (input, options = {}) => this.capabilities.execute({
377
- domain: "email",
378
- capability: "send",
379
- input,
380
- ...options,
381
- }),
382
- },
383
- inbox: {
384
- acquire: {
385
- recommend: (input, options = {}) => this.capabilities.recommend({
386
- domain: "email",
387
- capability: "inbox-acquire",
388
- input,
389
- ...options,
390
- }),
391
- execute: (input, options = {}) => this.capabilities.execute({
392
- domain: "email",
393
- capability: "inbox-acquire",
394
- input,
395
- ...options,
396
- }),
397
- },
398
- buy: {
399
- recommend: (input, options = {}) => this.capabilities.recommend({
400
- domain: "email",
401
- capability: "inbox-acquire",
402
- input,
403
- ...options,
404
- }),
405
- execute: (input, options = {}) => this.capabilities.execute({
406
- domain: "email",
407
- capability: "inbox-acquire",
408
- input,
409
- ...options,
410
- }),
411
- },
412
- },
413
- };
414
- this.enrichment = {
415
- route: (input, options = {}) => this.routing.route({
416
- domain: "enrichment",
417
- input,
418
- ...options,
419
- }),
420
- peopleSearch: {
421
- recommend: (input, options = {}) => this.capabilities.recommend({
422
- domain: "enrichment",
423
- capability: "people-search",
424
- input,
425
- ...options,
426
- }),
427
- execute: (input, options = {}) => this.capabilities.execute({
428
- domain: "enrichment",
429
- capability: "people-search",
430
- input,
431
- ...options,
432
- }),
433
- },
434
- contactEnrich: {
435
- recommend: (input, options = {}) => this.capabilities.recommend({
436
- domain: "enrichment",
437
- capability: "contact-enrich",
438
- input,
439
- ...options,
440
- }),
441
- execute: (input, options = {}) => this.capabilities.execute({
442
- domain: "enrichment",
443
- capability: "contact-enrich",
444
- input,
445
- ...options,
446
- }),
447
- },
448
- };
449
- this.social = {
450
- route: (input, options = {}) => this.routing.route({
451
- domain: "social",
452
- input,
453
- ...options,
454
- }),
455
- profileLookup: {
456
- recommend: (input, options = {}) => this.capabilities.recommend({
457
- domain: "social",
458
- capability: "profile-lookup",
459
- input,
460
- ...options,
461
- }),
462
- execute: (input, options = {}) => this.capabilities.execute({
463
- domain: "social",
464
- capability: "profile-lookup",
465
- input,
466
- ...options,
467
- }),
468
- },
469
- contentSearch: {
470
- recommend: (input, options = {}) => this.capabilities.recommend({
471
- domain: "social",
472
- capability: "content-search",
473
- input,
474
- ...options,
475
- }),
476
- execute: (input, options = {}) => this.capabilities.execute({
477
- domain: "social",
478
- capability: "content-search",
479
- input,
480
- ...options,
481
- }),
482
- },
483
- };
484
- this.web = {
485
- publications: {
486
- list: {
487
- recommend: (input, options = {}) => this.capabilities.recommend({
488
- domain: "web",
489
- capability: "publication-list",
490
- input,
491
- ...options,
492
- }),
493
- execute: (input, options = {}) => this.capabilities.execute({
494
- domain: "web",
495
- capability: "publication-list",
496
- input,
497
- ...options,
498
- }),
499
- },
500
- posts: {
501
- list: {
502
- recommend: (input, options = {}) => this.capabilities.recommend({
503
- domain: "web",
504
- capability: "publication-posts-list",
505
- input,
506
- ...options,
507
- }),
508
- execute: (input, options = {}) => this.capabilities.execute({
509
- domain: "web",
510
- capability: "publication-posts-list",
511
- input,
512
- ...options,
513
- }),
514
- },
515
- },
516
- post: {
517
- get: {
518
- recommend: (input, options = {}) => this.capabilities.recommend({
519
- domain: "web",
520
- capability: "publication-post-get",
521
- input,
522
- ...options,
523
- }),
524
- execute: (input, options = {}) => this.capabilities.execute({
525
- domain: "web",
526
- capability: "publication-post-get",
527
- input,
528
- ...options,
529
- }),
530
- },
531
- },
532
- },
533
- };
534
- this.post = {
535
- letter: {
536
- quote: {
537
- recommend: (input, options = {}) => this.capabilities.recommend({
538
- domain: "post",
539
- capability: "letter-quote",
540
- input,
541
- ...options,
542
- }),
543
- execute: (input, options = {}) => this.capabilities.execute({
544
- domain: "post",
545
- capability: "letter-quote",
546
- input,
547
- ...options,
548
- }),
549
- },
550
- send: {
551
- recommend: (input, options = {}) => this.capabilities.recommend({
552
- domain: "post",
553
- capability: "letter-send",
554
- input,
555
- ...options,
556
- }),
557
- execute: (input, options = {}) => this.capabilities.execute({
558
- domain: "post",
559
- capability: "letter-send",
560
- input,
561
- ...options,
562
- }),
563
- },
564
- status: {
565
- recommend: (input, options = {}) => this.capabilities.recommend({
566
- domain: "post",
567
- capability: "letter-status",
568
- input,
569
- ...options,
570
- }),
571
- execute: (input, options = {}) => this.capabilities.execute({
572
- domain: "post",
573
- capability: "letter-status",
574
- input,
575
- ...options,
576
- }),
577
- },
578
- },
579
- postcard: {
580
- send: {
581
- recommend: (input, options = {}) => this.capabilities.recommend({
582
- domain: "post",
583
- capability: "postcard-send",
584
- input,
585
- ...options,
586
- }),
587
- execute: (input, options = {}) => this.capabilities.execute({
588
- domain: "post",
589
- capability: "postcard-send",
590
- input,
591
- ...options,
592
- }),
593
- },
594
- },
595
- };
596
- this.broadcast = {
597
- message: {
598
- quote: {
599
- recommend: (input, options = {}) => this.capabilities.recommend({
600
- domain: "broadcast",
601
- capability: "message-quote",
602
- input,
603
- ...options,
604
- }),
605
- execute: (input, options = {}) => this.capabilities.execute({
606
- domain: "broadcast",
607
- capability: "message-quote",
608
- input,
609
- ...options,
610
- }),
611
- },
612
- send: {
613
- recommend: (input, options = {}) => this.capabilities.recommend({
614
- domain: "broadcast",
615
- capability: "message-send",
616
- input,
617
- ...options,
618
- }),
619
- execute: (input, options = {}) => this.capabilities.execute({
620
- domain: "broadcast",
621
- capability: "message-send",
622
- input,
623
- ...options,
624
- }),
625
- },
626
- },
627
- };
628
- this.apiKey = options.apiKey?.trim() || null;
629
- this.sessionToken = options.sessionToken?.trim() || null;
630
- this.baseUrl = trimBaseUrl(options.baseUrl);
631
- this.timeoutMs = options.timeoutMs;
632
- this.fetchImpl = resolveFetchImplementation(options.fetch);
633
- this.defaultHeaders = options.headers;
634
- }
635
- async recommend(prompt, options = {}) {
636
- const trimmedPrompt = prompt.trim();
637
- if (!trimmedPrompt) {
638
- throw new Error("Prompt is required.");
639
- }
640
- const resolution = await this.intent.resolve(trimmedPrompt);
641
- const { input, ...callOptions } = options;
642
- const recommendInputWithIntent = {
643
- ...(input ?? {}),
644
- intent: trimmedPrompt,
645
- };
646
- try {
647
- const recommendation = await this.capabilities.recommend({
648
- domain: resolution.domainKey,
649
- capability: resolution.capabilityId,
650
- input: recommendInputWithIntent,
651
- ...callOptions,
652
- });
653
- return {
654
- ...recommendation,
655
- resolution,
656
- };
657
- }
658
- catch (error) {
659
- const fallbackInput = input ?? {};
660
- const canRetryWithoutIntent = error instanceof AgentRouterClientError &&
661
- (error.status === 400 || error.status === 404 || error.status === 422);
662
- if (!canRetryWithoutIntent) {
663
- throw error;
664
- }
665
- const recommendation = await this.capabilities.recommend({
666
- domain: resolution.domainKey,
667
- capability: resolution.capabilityId,
668
- input: fallbackInput,
669
- ...callOptions,
670
- });
671
- return {
672
- ...recommendation,
673
- resolution,
674
- };
675
- }
676
- }
677
- async request({ path, method = "GET", query, body, headers: overrideHeaders, authMode = "none", apiKey, sessionToken, userId, signal, timeoutMs, }) {
678
- const headers = mergeHeaders(this.defaultHeaders, overrideHeaders);
679
- if (authMode === "apiKey") {
680
- const resolvedApiKey = apiKey?.trim() || this.apiKey;
681
- const resolvedUserId = userId?.trim() || null;
682
- if (!resolvedApiKey && !resolvedUserId) {
683
- throw new Error(`Missing API key. Pass apiKey to the call, set it in AgentRouterClient options, or use userId for local development. Get a hosted API key at ${AGENTIC_API_INSTALL_URL}.`);
684
- }
685
- if (resolvedApiKey) {
686
- headers.set("Authorization", `Bearer ${resolvedApiKey}`);
687
- }
688
- }
689
- if (authMode === "session") {
690
- const resolvedSessionToken = sessionToken?.trim() || this.sessionToken;
691
- if (!resolvedSessionToken) {
692
- throw new Error("Missing session token. Pass sessionToken to the call or set it in AgentRouterClient options.");
693
- }
694
- headers.set("Authorization", `Bearer ${resolvedSessionToken}`);
695
- }
696
- if (userId?.trim()) {
697
- headers.set("x-agentic-user-id", userId.trim());
698
- }
699
- const requestBody = serializeBody(body, headers);
700
- const url = buildUrl(this.baseUrl, path, query);
701
- const timeout = withTimeoutSignal(signal, timeoutMs ?? this.timeoutMs);
702
- try {
703
- const response = await this.fetchImpl(url, {
704
- method,
705
- headers,
706
- body: requestBody,
707
- signal: timeout.signal,
708
- });
709
- const rawText = (await response.text()) || "";
710
- let payload = {};
711
- if (rawText) {
712
- try {
713
- payload = JSON.parse(rawText);
714
- }
715
- catch {
716
- payload = rawText;
717
- }
718
- }
719
- if (!response.ok) {
720
- const errorPayload = isObjectRecord(payload)
721
- ? payload
722
- : {};
723
- throw new AgentRouterClientError(extractErrorMessage(errorPayload, "AgentRouter request failed."), {
724
- status: response.status,
725
- code: typeof errorPayload.code === "string"
726
- ? errorPayload.code
727
- : undefined,
728
- hint: typeof errorPayload.hint === "string"
729
- ? errorPayload.hint
730
- : undefined,
731
- details: errorPayload.details,
732
- rawBody: rawText || undefined,
733
- });
734
- }
735
- return payload;
736
- }
737
- finally {
738
- timeout.cleanup();
739
- }
740
- }
741
- }
742
- export function createAgentRouterClient(options = {}) {
743
- return new AgentRouterClient(options);
744
- }
745
- export { AgentRouterClient as AgenticApiClient, AgentRouterClientError as AgenticApiClientError, createAgentRouterClient as createAgenticApiClient, };