@tbdhdev/ami-router-client 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Joshue Abance
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,79 @@
1
- # Temporary Holding Version
1
+ # @tbdhdev/ami-router-client
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ TypeScript and JavaScript client for the [AMI Router](https://github.com/tbdsux/ami-sdk/tree/main/router#readme). The router puts one HTTP API in front of many web search, scrape and research providers: it tries them in the order you set, and falls back to the next one when a provider fails.
4
+
5
+ No runtime dependencies. It runs wherever there's a global `fetch`: Node 18 or later, Deno, Bun and browsers. The package is ESM and includes its type declarations.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install @tbdhdev/ami-router-client
11
+ ```
12
+
13
+ ## Use
14
+
15
+ Create an API key in the router's dashboard, then:
16
+
17
+ ```ts
18
+ import { Client } from "@tbdhdev/ami-router-client";
19
+
20
+ const router = new Client({ apiKey: "ami_...", baseURL: "http://127.0.0.1:8090" });
21
+
22
+ const { results = [] } = await router.search("go generics", { limit: 5 });
23
+ for (const r of results) console.log(r.title, r.url);
24
+
25
+ // Skip the routing order, and include the provider's original response.
26
+ await router.search("go generics", { provider: "exa", raw: true });
27
+
28
+ for await (const chunk of router.answerStream("what is htmx?")) {
29
+ process.stdout.write(chunk.text ?? "");
30
+ }
31
+ ```
32
+
33
+ Replies are the router's JSON, typed: the [router's README](https://github.com/tbdsux/ami-sdk/tree/main/router#responses) describes the fields. The router leaves out empty fields, so most of them are optional.
34
+
35
+ | Method | Endpoint | Resolves to |
36
+ |---|---|---|
37
+ | `search(query, { limit })` | `POST /v1/search` | `SearchReply`: `results` |
38
+ | `scrape(url)` | `POST /v1/scrape` | `ScrapeReply`: `page` |
39
+ | `crawl(url, { limit, resumeId })` | `POST /v1/crawl` | `CrawlReply`: `pages`, `id` |
40
+ | `answer(query)` | `POST /v1/answer` | `AnswerReply`: `content`, `citations` |
41
+ | `research(query, { resumeId })` | `POST /v1/research` | `AnswerReply`: `content`, `citations`, `id` |
42
+ | `answerStream(query)` | `POST /v1/answer`, streamed | an async generator of `Chunk`: `text`, `citations` |
43
+ | `researchStream(query, { resumeId })` | `POST /v1/research`, streamed | an async generator of `Chunk`: `text`, `citations`, `id` |
44
+ | `providers()` | `GET /v1/providers` | the routing order for each endpoint |
45
+
46
+ Every options object also takes `provider`, `raw` and an `AbortSignal` as `signal`. Every reply has `provider`, the one that served the call, and `attempts`, the ones that failed first. Pass `fetch` to the constructor to use your own, for example to add retries.
47
+
48
+ ## Errors
49
+
50
+ - **`RouterError`** means the router couldn't serve the request. `e.status` is the HTTP status, and `e.body` is the router's reply, with `error` and the failed `attempts`.
51
+ - **`PendingError`**, a subclass, means a crawl or research job outlasted the router's long timeout. The job keeps running at the provider, so collect it later instead of paying for a new one:
52
+
53
+ ```ts
54
+ import { PendingError, type AnswerReply } from "@tbdhdev/ami-router-client";
55
+
56
+ let report: AnswerReply;
57
+ try {
58
+ report = await router.research("state of WebAssembly");
59
+ } catch (e) {
60
+ if (!(e instanceof PendingError)) throw e;
61
+ report = await router.research("", { resumeId: e.id, provider: e.provider });
62
+ }
63
+ ```
64
+
65
+ - **A stream that fails partway,** or is cut off before the router finishes it, throws `RouterError` with status 200, after the chunks that arrived.
66
+
67
+ ## Develop
68
+
69
+ Needs Node 22.18 or later, which runs the tests straight from the `.ts` files. The tests run against a fake router.
70
+
71
+ ```bash
72
+ npm ci
73
+ npm test # type-check, then test
74
+ npm run build # bundle into dist/ with tsdown
75
+ ```
76
+
77
+ ## License
78
+
79
+ [MIT](LICENSE)
@@ -0,0 +1,138 @@
1
+ /** A provider that failed before another served the request. */
2
+ export interface Attempt {
3
+ provider: string;
4
+ error: string;
5
+ }
6
+ /** One search hit. */
7
+ export interface SearchResult {
8
+ title: string;
9
+ url: string;
10
+ snippet?: string;
11
+ /** The full page text, when the provider returned it. */
12
+ content?: string;
13
+ }
14
+ /** The content of one scraped or crawled URL. */
15
+ export interface Page {
16
+ url: string;
17
+ title?: string;
18
+ content: string;
19
+ }
20
+ /** A source an answer or report cites. */
21
+ export interface Citation {
22
+ title?: string;
23
+ url: string;
24
+ }
25
+ /** The fields every router reply has. */
26
+ export interface Reply {
27
+ /** The provider that served the request. */
28
+ provider?: string;
29
+ /** Providers that failed first, with their errors. */
30
+ attempts?: Attempt[];
31
+ /** The provider's original response, when `raw` was set. */
32
+ raw?: unknown;
33
+ }
34
+ /** The reply of POST /v1/search. */
35
+ export interface SearchReply extends Reply {
36
+ results?: SearchResult[];
37
+ }
38
+ /** The reply of POST /v1/scrape. */
39
+ export interface ScrapeReply extends Reply {
40
+ page: Page;
41
+ }
42
+ /** The reply of POST /v1/crawl. */
43
+ export interface CrawlReply extends Reply {
44
+ /** The crawl job's ID. */
45
+ id?: string;
46
+ pages?: Page[];
47
+ }
48
+ /** The reply of POST /v1/answer and POST /v1/research. */
49
+ export interface AnswerReply extends Reply {
50
+ /** The research job's ID. */
51
+ id?: string;
52
+ content?: string;
53
+ citations?: Citation[];
54
+ }
55
+ /** One piece of a streamed answer or report. */
56
+ export interface Chunk {
57
+ provider: string;
58
+ /** New text to append. */
59
+ text?: string;
60
+ citations?: Citation[];
61
+ /** The research job's ID, when the provider reports one. */
62
+ id?: string;
63
+ raw?: unknown;
64
+ }
65
+ /** A failed or unfinished reply: the body of a RouterError. */
66
+ export interface ErrorReply extends Reply {
67
+ error?: string;
68
+ pending?: boolean;
69
+ id?: string;
70
+ }
71
+ /** Fields every call takes. */
72
+ export interface Options {
73
+ /** Skips the routing order and uses only this provider. */
74
+ provider?: string;
75
+ /** Includes the provider's original response as `raw`. */
76
+ raw?: boolean;
77
+ signal?: AbortSignal;
78
+ }
79
+ /** Fields that collect a job that threw PendingError. */
80
+ export interface ResumeOptions extends Options {
81
+ /** The job's ID; set `provider` to the job's too. */
82
+ resumeId?: string;
83
+ }
84
+ /** Settings for a Client. */
85
+ export interface ClientOptions {
86
+ /** A key from the router's dashboard. */
87
+ apiKey: string;
88
+ /** The router's address; http://127.0.0.1:8090 by default. */
89
+ baseURL?: string;
90
+ /** Defaults to the global fetch; pass your own for retries or a proxy. */
91
+ fetch?: typeof fetch;
92
+ }
93
+ /** A request the router could not serve. `body` has `error` and the failed `attempts`. */
94
+ export declare class RouterError extends Error {
95
+ /** The HTTP status; 200 for a stream that failed partway. */
96
+ readonly status: number;
97
+ readonly body: ErrorReply;
98
+ constructor(status: number, body: ErrorReply);
99
+ }
100
+ /**
101
+ * A crawl or research job that outlasted the router's long timeout. It keeps
102
+ * running at the provider: collect it with `{ resumeId: e.id, provider: e.provider }`.
103
+ */
104
+ export declare class PendingError extends RouterError {
105
+ readonly id: string;
106
+ readonly provider: string;
107
+ constructor(body: ErrorReply);
108
+ }
109
+ /** Calls one router with one API key. */
110
+ export declare class Client {
111
+ #private;
112
+ readonly apiKey: string;
113
+ readonly baseURL: string;
114
+ readonly fetch: typeof fetch;
115
+ constructor({ apiKey, baseURL, fetch }: ClientOptions);
116
+ /** POST /v1/search. */
117
+ search(query: string, { limit, ...opts }?: Options & {
118
+ limit?: number;
119
+ }): Promise<SearchReply>;
120
+ /** POST /v1/scrape. */
121
+ scrape(url: string, opts?: Options): Promise<ScrapeReply>;
122
+ /** POST /v1/crawl. Throws PendingError for a long job. */
123
+ crawl(url: string, { limit, resumeId, ...opts }?: ResumeOptions & {
124
+ limit?: number;
125
+ }): Promise<CrawlReply>;
126
+ /** POST /v1/answer. */
127
+ answer(query: string, opts?: Options): Promise<AnswerReply>;
128
+ /** POST /v1/research. Throws PendingError for a long job. */
129
+ research(query: string, { resumeId, ...opts }?: ResumeOptions): Promise<AnswerReply>;
130
+ /** Streams an answer as it's generated. */
131
+ answerStream(query: string, opts?: Options): AsyncGenerator<Chunk, void>;
132
+ /** Streams a research report as it's written. */
133
+ researchStream(query: string, { resumeId, ...opts }?: ResumeOptions): AsyncGenerator<Chunk, void>;
134
+ /** GET /v1/providers: the routing order for each endpoint. */
135
+ providers({ signal }?: {
136
+ signal?: AbortSignal;
137
+ }): Promise<Record<string, string[]>>;
138
+ }
package/dist/index.js ADDED
@@ -0,0 +1,183 @@
1
+ // src/index.ts
2
+ /** A request the router could not serve. `body` has `error` and the failed `attempts`. */
3
+ var RouterError = class extends Error {
4
+ /** The HTTP status; 200 for a stream that failed partway. */
5
+ status;
6
+ body;
7
+ constructor(status, body) {
8
+ super(`ami router: ${body.error || JSON.stringify(body)}`);
9
+ this.name = "RouterError";
10
+ this.status = status;
11
+ this.body = body;
12
+ }
13
+ };
14
+ /**
15
+ * A crawl or research job that outlasted the router's long timeout. It keeps
16
+ * running at the provider: collect it with `{ resumeId: e.id, provider: e.provider }`.
17
+ */
18
+ var PendingError = class extends RouterError {
19
+ id;
20
+ provider;
21
+ constructor(body) {
22
+ super(202, {
23
+ error: `job ${body.id} still running at ${body.provider}`,
24
+ ...body
25
+ });
26
+ this.name = "PendingError";
27
+ this.id = body.id ?? "";
28
+ this.provider = body.provider ?? "";
29
+ }
30
+ };
31
+ /** Calls one router with one API key. */
32
+ var Client = class {
33
+ apiKey;
34
+ baseURL;
35
+ fetch;
36
+ constructor({ apiKey, baseURL = "http://127.0.0.1:8090", fetch = globalThis.fetch }) {
37
+ this.apiKey = apiKey;
38
+ this.baseURL = baseURL.replace(/\/+$/, "");
39
+ this.fetch = fetch;
40
+ }
41
+ /** POST /v1/search. */
42
+ search(query, { limit, ...opts } = {}) {
43
+ return this.#post("search", {
44
+ query,
45
+ limit
46
+ }, opts);
47
+ }
48
+ /** POST /v1/scrape. */
49
+ scrape(url, opts = {}) {
50
+ return this.#post("scrape", { url }, opts);
51
+ }
52
+ /** POST /v1/crawl. Throws PendingError for a long job. */
53
+ crawl(url, { limit, resumeId, ...opts } = {}) {
54
+ return this.#post("crawl", {
55
+ url,
56
+ limit,
57
+ resume_id: resumeId
58
+ }, opts);
59
+ }
60
+ /** POST /v1/answer. */
61
+ answer(query, opts = {}) {
62
+ return this.#post("answer", { query }, opts);
63
+ }
64
+ /** POST /v1/research. Throws PendingError for a long job. */
65
+ research(query, { resumeId, ...opts } = {}) {
66
+ return this.#post("research", {
67
+ query,
68
+ resume_id: resumeId
69
+ }, opts);
70
+ }
71
+ /** Streams an answer as it's generated. */
72
+ answerStream(query, opts = {}) {
73
+ return this.#stream("answer", { query }, opts);
74
+ }
75
+ /** Streams a research report as it's written. */
76
+ researchStream(query, { resumeId, ...opts } = {}) {
77
+ return this.#stream("research", {
78
+ query,
79
+ resume_id: resumeId
80
+ }, opts);
81
+ }
82
+ /** GET /v1/providers: the routing order for each endpoint. */
83
+ async providers({ signal } = {}) {
84
+ const res = await this.#send("GET", "/v1/providers", void 0, signal);
85
+ return check(parse(await res.text()), res.status);
86
+ }
87
+ async #send(method, path, body, signal) {
88
+ const headers = { Authorization: `Bearer ${this.apiKey}` };
89
+ if (body) headers["Content-Type"] = "application/json";
90
+ const res = await (0, this.fetch)(this.baseURL + path, {
91
+ method,
92
+ signal,
93
+ headers,
94
+ body: body && JSON.stringify(body)
95
+ });
96
+ if (!res.ok) throw new RouterError(res.status, parse(await res.text()));
97
+ return res;
98
+ }
99
+ async #post(endpoint, body, { provider, raw, signal }) {
100
+ const res = await this.#send("POST", `/v1/${endpoint}`, {
101
+ ...body,
102
+ provider,
103
+ raw
104
+ }, signal);
105
+ return check(parse(await res.text()), res.status);
106
+ }
107
+ async *#stream(endpoint, body, { provider, raw, signal }) {
108
+ const res = await this.#send("POST", `/v1/${endpoint}`, {
109
+ ...body,
110
+ provider,
111
+ raw,
112
+ stream: true
113
+ }, signal);
114
+ if (!res.body || !res.headers.get("content-type")?.toLowerCase().startsWith("text/event-stream")) {
115
+ check(parse(await res.text()), res.status);
116
+ return;
117
+ }
118
+ for await (const { event, data } of events(res.body)) {
119
+ if (event === "done") {
120
+ check(JSON.parse(data), 200);
121
+ return;
122
+ }
123
+ yield JSON.parse(data);
124
+ }
125
+ throw new RouterError(res.status, { error: "stream ended before the done event" });
126
+ }
127
+ };
128
+ /** Throws the failure a 2xx reply or stream event reports, else returns it. */
129
+ function check(body, status = 200) {
130
+ if (body.pending) throw new PendingError(body);
131
+ if (body.error) throw new RouterError(status, body);
132
+ return body;
133
+ }
134
+ /** A reply as an object, even when a proxy in front sent HTML or other non-object text. */
135
+ function parse(text) {
136
+ try {
137
+ const body = JSON.parse(text);
138
+ if (body !== null && typeof body === "object" && !Array.isArray(body)) return body;
139
+ } catch {}
140
+ return { error: text || "empty reply" };
141
+ }
142
+ /**
143
+ * Yields the server-sent events of a body: each one's name and its data lines
144
+ * joined with "\n", as the SSE spec says.
145
+ */
146
+ async function* events(body) {
147
+ let event = "";
148
+ let data = [];
149
+ for await (const line of lines(body)) if (line.startsWith("event:")) event = line.slice(6).trim();
150
+ else if (line.startsWith("data:")) data.push(line.slice(5).replace(/^ /, ""));
151
+ else if (line === "") {
152
+ if (data.length) yield {
153
+ event,
154
+ data: data.join("\n")
155
+ };
156
+ event = "";
157
+ data = [];
158
+ }
159
+ if (data.length) yield {
160
+ event,
161
+ data: data.join("\n")
162
+ };
163
+ }
164
+ /**
165
+ * Yields the lines of a response body, and closes the connection when the
166
+ * caller stops early. It reads by hand because not every browser can iterate
167
+ * a ReadableStream with for await.
168
+ */
169
+ async function* lines(body) {
170
+ const reader = body.pipeThrough(new TextDecoderStream()).getReader();
171
+ let buf = "";
172
+ try {
173
+ for (let r = await reader.read(); !r.done; r = await reader.read()) {
174
+ const parts = (buf + r.value).split("\n");
175
+ buf = parts.pop() ?? "";
176
+ yield* parts.map((l) => l.replace(/\r$/, ""));
177
+ }
178
+ if (buf) yield buf.replace(/\r$/, "");
179
+ } finally {
180
+ reader.cancel().catch(() => {});
181
+ }
182
+ }
183
+ export { Client, PendingError, RouterError };
package/package.json CHANGED
@@ -1,6 +1,38 @@
1
1
  {
2
2
  "name": "@tbdhdev/ami-router-client",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Client for the AMI Router's HTTP API",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/tbdsux/ami-sdk.git",
9
+ "directory": "router-clients/typescript"
10
+ },
11
+ "type": "module",
12
+ "publishConfig": {
13
+ "access": "public"
14
+ },
15
+ "files": [
16
+ "dist"
17
+ ],
18
+ "engines": {
19
+ "node": ">=18"
20
+ },
21
+ "scripts": {
22
+ "build": "tsdown",
23
+ "test": "tsc && node --test",
24
+ "prepack": "tsdown"
25
+ },
26
+ "devDependencies": {
27
+ "@types/node": "^26.6.11",
28
+ "tsdown": "^0.23.8",
29
+ "typescript": "^7.0.2"
30
+ },
31
+ "exports": {
32
+ ".": "./dist/index.js",
33
+ "./package.json": "./package.json"
34
+ },
35
+ "main": "./dist/index.js",
36
+ "module": "./dist/index.js",
37
+ "types": "./dist/index.d.ts"
38
+ }