@supersolutions/super-chat-router 0.1.0 → 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 +8 -3
- package/dist/index.d.ts +6 -1
- package/dist/index.js +126 -42
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -1,8 +1,13 @@
|
|
|
1
1
|
# @supersolutions/super-chat-router
|
|
2
2
|
|
|
3
3
|
`createSuperRouterGateway` is an `InferenceGateway` over the Super Router HTTP API.
|
|
4
|
-
`createSuperRouterProvider` wraps any gateway as a super-chat `Provider
|
|
5
|
-
|
|
6
|
-
|
|
4
|
+
`createSuperRouterProvider` wraps any gateway as a super-chat `Provider`; the request's `model` is the Super Router
|
|
5
|
+
service id. Errors are mapped to `AgentError` kinds; a replayed idempotency key is reported, never passed off as a
|
|
6
|
+
fresh answer.
|
|
7
|
+
|
|
8
|
+
The provider carries text, tool declarations, streaming tool calls, tool results, usage, and images as `https:`
|
|
9
|
+
URLs or base64 PNG, JPEG, GIF and WebP. Files and audio are dropped with a warning. Tool calling needs a Super Router
|
|
10
|
+
TypeScript server that supports it; the Go, Python and Rust data planes refuse these requests. For an older server,
|
|
11
|
+
set `toolCalling: false`.
|
|
7
12
|
|
|
8
13
|
See [docs/PACKAGES.md](../../docs/PACKAGES.md).
|
package/dist/index.d.ts
CHANGED
|
@@ -21,9 +21,14 @@ type SuperRouterProviderConfig = {
|
|
|
21
21
|
defaultMaxOutputTokens?: number;
|
|
22
22
|
/** One key per logical call; reuse it when retrying so the call never bills twice. */
|
|
23
23
|
idempotencyKey?: () => string;
|
|
24
|
+
/**
|
|
25
|
+
* Send tools and images to the router. Default true. Turn it off for a server
|
|
26
|
+
* that predates tool calling: tools are then left out with a warning.
|
|
27
|
+
*/
|
|
28
|
+
toolCalling?: boolean;
|
|
24
29
|
};
|
|
25
30
|
/**
|
|
26
|
-
* A
|
|
31
|
+
* A `Provider` that sends every call through an `InferenceGateway`, with tool calling and images.
|
|
27
32
|
* `NormalizedRequest.model` is the Super Router **service** id, not a raw model name.
|
|
28
33
|
*/
|
|
29
34
|
declare function createSuperRouterProvider(config: SuperRouterProviderConfig): Provider;
|
package/dist/index.js
CHANGED
|
@@ -3,17 +3,23 @@ import {
|
|
|
3
3
|
GatewayError,
|
|
4
4
|
parseSSE
|
|
5
5
|
} from "@supersolutions/super-protocol";
|
|
6
|
-
var body = (request, stream) =>
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
6
|
+
var body = (request, stream) => {
|
|
7
|
+
return JSON.stringify({
|
|
8
|
+
service: request.service,
|
|
9
|
+
...request.service_version ? { service_version: request.service_version } : {},
|
|
10
|
+
customer_id: request.customer_id,
|
|
11
|
+
input: {
|
|
12
|
+
messages: request.messages,
|
|
13
|
+
...request.tools?.length ? { tools: request.tools } : {},
|
|
14
|
+
...request.tools?.length && request.tool_choice !== void 0 ? { tool_choice: request.tool_choice } : {}
|
|
15
|
+
},
|
|
16
|
+
limits: {
|
|
17
|
+
max_output_tokens: request.max_output_tokens ?? 1024,
|
|
18
|
+
...request.timeout_ms ? { timeout_ms: request.timeout_ms } : {}
|
|
19
|
+
},
|
|
20
|
+
stream
|
|
21
|
+
});
|
|
22
|
+
};
|
|
17
23
|
function createSuperRouterGateway(config) {
|
|
18
24
|
const base = config.baseUrl.replace(/\/+$/, "");
|
|
19
25
|
const doFetch = config.fetch ?? fetch;
|
|
@@ -74,9 +80,12 @@ function createSuperRouterGateway(config) {
|
|
|
74
80
|
|
|
75
81
|
// src/provider.ts
|
|
76
82
|
import {
|
|
77
|
-
AgentError
|
|
83
|
+
AgentError,
|
|
84
|
+
repairToolArguments
|
|
78
85
|
} from "@supersolutions/super-chat-core";
|
|
79
|
-
import {
|
|
86
|
+
import {
|
|
87
|
+
GatewayError as GatewayError2
|
|
88
|
+
} from "@supersolutions/super-protocol";
|
|
80
89
|
var noTransport = {
|
|
81
90
|
kind: "custom",
|
|
82
91
|
credentialSafe: true,
|
|
@@ -84,34 +93,80 @@ var noTransport = {
|
|
|
84
93
|
throw new AgentError("not-supported", "The Super Router provider does not use a Transport.");
|
|
85
94
|
}
|
|
86
95
|
};
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
96
|
+
var MAX_TOOL_RESULT_CHARS = 256e3;
|
|
97
|
+
var MAX_TOOL_DESCRIPTION_CHARS = 4096;
|
|
98
|
+
var IMAGE_MEDIA = /^image\/(png|jpeg|gif|webp)$/;
|
|
99
|
+
var wireCallId = (id) => id.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 128) || "call";
|
|
100
|
+
var asText = (output) => typeof output === "string" ? output : JSON.stringify(output) ?? "null";
|
|
101
|
+
function resultText(output) {
|
|
102
|
+
const text = asText(output);
|
|
103
|
+
const marker = "\u2026[truncated]";
|
|
104
|
+
return text.length > MAX_TOOL_RESULT_CHARS ? text.slice(0, MAX_TOOL_RESULT_CHARS - marker.length) + marker : text;
|
|
105
|
+
}
|
|
106
|
+
function argumentsText(input) {
|
|
107
|
+
const object = typeof input === "object" && input !== null && !Array.isArray(input);
|
|
108
|
+
return JSON.stringify(object ? input : input === void 0 || input === null ? {} : { input });
|
|
109
|
+
}
|
|
110
|
+
function imageUrl(part) {
|
|
111
|
+
const { source, mediaType } = part;
|
|
112
|
+
if (source.kind === "url") return source.url.startsWith("https://") || /^data:image\/(png|jpeg|gif|webp);base64,/.test(source.url) ? source.url : void 0;
|
|
113
|
+
if (source.kind === "base64" && mediaType && IMAGE_MEDIA.test(mediaType)) return `data:${mediaType};base64,${source.data}`;
|
|
114
|
+
return void 0;
|
|
95
115
|
}
|
|
96
|
-
function toMessages(req) {
|
|
116
|
+
function toMessages(req, toolCalling) {
|
|
97
117
|
const warnings = [];
|
|
98
118
|
const messages = [];
|
|
99
119
|
if (req.system) messages.push({ role: "system", content: req.system });
|
|
120
|
+
const history = req.messages;
|
|
121
|
+
const called = new Set(history.flatMap((m) => m.parts.flatMap((p) => p.type === "tool-call" ? [p.callId] : [])));
|
|
122
|
+
const answered = new Set(history.flatMap((m) => m.parts.flatMap((p) => p.type === "tool-result" ? [p.callId] : [])));
|
|
100
123
|
let dropped = 0;
|
|
101
|
-
for (const m of
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
124
|
+
for (const m of history) {
|
|
125
|
+
const texts = [];
|
|
126
|
+
const images = [];
|
|
127
|
+
const calls = [];
|
|
128
|
+
const results = [];
|
|
129
|
+
for (const p of m.parts) {
|
|
130
|
+
if (p.type === "text") {
|
|
131
|
+
if (p.text) texts.push(p.text);
|
|
132
|
+
} else if (p.type === "image" && toolCalling) {
|
|
133
|
+
const url = imageUrl(p);
|
|
134
|
+
if (url) images.push({ type: "image", url, ...p.detail ? { detail: p.detail } : {} });
|
|
135
|
+
else dropped += 1;
|
|
136
|
+
} else if (p.type === "tool-call" && toolCalling) {
|
|
137
|
+
if (answered.has(p.callId)) calls.push({ id: wireCallId(p.callId), name: p.name, arguments: argumentsText(p.input) });
|
|
138
|
+
} else if (p.type === "tool-result" && toolCalling) {
|
|
139
|
+
if (called.has(p.callId)) results.push({ role: "tool", tool_call_id: wireCallId(p.callId), content: resultText(p.output), ...p.failure ? { is_error: true } : {} });
|
|
140
|
+
} else if (p.type !== "reasoning" && p.type !== "artifact") {
|
|
141
|
+
dropped += 1;
|
|
142
|
+
}
|
|
105
143
|
}
|
|
106
|
-
const
|
|
107
|
-
|
|
108
|
-
if (
|
|
144
|
+
const text = texts.join("\n");
|
|
145
|
+
if (m.role === "tool") messages.push(...results);
|
|
146
|
+
else if (m.role === "assistant" && calls.length) messages.push({ role: "assistant", ...text ? { content: text } : {}, tool_calls: calls });
|
|
147
|
+
else if (m.role === "user" && images.length) messages.push({ role: "user", content: [...text ? [{ type: "text", text }] : [], ...images] });
|
|
148
|
+
else if (text) messages.push({ role: m.role, content: text });
|
|
149
|
+
if (m.role !== "tool") messages.push(...results);
|
|
109
150
|
}
|
|
110
|
-
if (dropped) warnings.push(`${dropped}
|
|
111
|
-
if (req.tools?.length) warnings.push("Tools were ignored:
|
|
112
|
-
if (!messages.some((m) => m.role !== "system")) throw new AgentError("invalid-request", "Super Router needs at least one user or assistant
|
|
151
|
+
if (dropped) warnings.push(`${dropped} part(s) were dropped: Super Router takes text, tool calls and https or base64 PNG, JPEG, GIF and WebP images.`);
|
|
152
|
+
if (!toolCalling && req.tools?.length) warnings.push("Tools were ignored: tool calling is turned off for this provider.");
|
|
153
|
+
if (!messages.some((m) => m.role !== "system")) throw new AgentError("invalid-request", "Super Router needs at least one user or assistant message.");
|
|
113
154
|
return { messages, warnings };
|
|
114
155
|
}
|
|
156
|
+
function toTools(req) {
|
|
157
|
+
const active = req.activeTools ? new Set(req.activeTools) : void 0;
|
|
158
|
+
const tools = (req.tools ?? []).filter((t) => !active || active.has(t.name)).map((t) => ({
|
|
159
|
+
name: t.name,
|
|
160
|
+
...t.description ? { description: t.description.slice(0, MAX_TOOL_DESCRIPTION_CHARS) } : {},
|
|
161
|
+
input_schema: { ...t.parameters, type: "object" }
|
|
162
|
+
}));
|
|
163
|
+
if (!tools.length) return {};
|
|
164
|
+
const choice = req.toolChoice;
|
|
165
|
+
if (!choice) return { tools };
|
|
166
|
+
if (choice.type !== "tool") return { tools, tool_choice: choice.type };
|
|
167
|
+
return tools.some((t) => t.name === choice.name) ? { tools, tool_choice: { name: choice.name } } : { tools };
|
|
168
|
+
}
|
|
169
|
+
var finishOf = (reason, hasCalls) => reason === "length" ? "length" : reason === "tool_calls" || hasCalls ? "tool-calls" : "stop";
|
|
115
170
|
function toUsage(u) {
|
|
116
171
|
if (!u) return {};
|
|
117
172
|
const inputTokens = u.input + u.cached + u.cache_write;
|
|
@@ -130,12 +185,14 @@ function toError(error, provider) {
|
|
|
130
185
|
function createSuperRouterProvider(config) {
|
|
131
186
|
const id = config.id ?? "super-router";
|
|
132
187
|
const newKey = config.idempotencyKey ?? (() => globalThis.crypto.randomUUID());
|
|
188
|
+
const toolCalling = config.toolCalling !== false;
|
|
133
189
|
const build = (req) => {
|
|
134
|
-
const { messages, warnings } = toMessages(req);
|
|
190
|
+
const { messages, warnings } = toMessages(req, toolCalling);
|
|
135
191
|
const request = {
|
|
136
192
|
service: req.model,
|
|
137
193
|
customer_id: config.customerId,
|
|
138
194
|
messages,
|
|
195
|
+
...toolCalling ? toTools(req) : {},
|
|
139
196
|
max_output_tokens: Math.min(8192, Math.max(1, req.maxOutputTokens ?? config.defaultMaxOutputTokens ?? 1024))
|
|
140
197
|
};
|
|
141
198
|
return { request, warnings };
|
|
@@ -147,9 +204,9 @@ function createSuperRouterProvider(config) {
|
|
|
147
204
|
streaming: true,
|
|
148
205
|
backgroundJobs: false,
|
|
149
206
|
resumableStreams: false,
|
|
150
|
-
tools:
|
|
151
|
-
parallelToolCalls:
|
|
152
|
-
images:
|
|
207
|
+
tools: toolCalling,
|
|
208
|
+
parallelToolCalls: toolCalling,
|
|
209
|
+
images: toolCalling,
|
|
153
210
|
files: false,
|
|
154
211
|
audio: false,
|
|
155
212
|
reasoning: false,
|
|
@@ -166,9 +223,17 @@ function createSuperRouterProvider(config) {
|
|
|
166
223
|
if (!result.output) {
|
|
167
224
|
throw new AgentError("invalid-request", `This idempotency key was already used (request ${result.id}); the router does not store output, so it cannot be replayed.`, { provider: id });
|
|
168
225
|
}
|
|
226
|
+
const calls = result.output.tool_calls ?? [];
|
|
227
|
+
const parts = [
|
|
228
|
+
...result.output.content || !calls.length ? [{ type: "text", text: result.output.content }] : [],
|
|
229
|
+
...calls.map((call) => {
|
|
230
|
+
const { value, repaired } = repairToolArguments(call.arguments);
|
|
231
|
+
return { type: "tool-call", callId: call.id, name: call.name, input: value, status: "pending", ...repaired ? { repaired } : {} };
|
|
232
|
+
})
|
|
233
|
+
];
|
|
169
234
|
return {
|
|
170
|
-
parts
|
|
171
|
-
finishReason: failed ? "error" :
|
|
235
|
+
parts,
|
|
236
|
+
finishReason: failed ? "error" : finishOf(result.finish_reason, calls.length > 0),
|
|
172
237
|
usage: toUsage(result.usage.meters),
|
|
173
238
|
responseId: result.id,
|
|
174
239
|
modelId: req.model,
|
|
@@ -181,17 +246,36 @@ function createSuperRouterProvider(config) {
|
|
|
181
246
|
async *stream(req, opts) {
|
|
182
247
|
const { request } = build(req);
|
|
183
248
|
let started = false;
|
|
249
|
+
const open = /* @__PURE__ */ new Map();
|
|
250
|
+
let completed = 0;
|
|
184
251
|
try {
|
|
185
|
-
for await (const
|
|
252
|
+
for await (const raw of config.gateway.stream(request, newKey(), opts?.signal)) {
|
|
253
|
+
const event = raw;
|
|
186
254
|
if (!started) {
|
|
187
255
|
started = true;
|
|
188
256
|
yield { type: "start", responseId: event.request_id, modelId: req.model };
|
|
189
257
|
}
|
|
190
258
|
if (event.type === "output.delta") yield { type: "text-delta", delta: event.text };
|
|
191
|
-
else if (event.type === "
|
|
259
|
+
else if (event.type === "output.tool_call.delta") {
|
|
260
|
+
let call = open.get(event.index);
|
|
261
|
+
if (!call) {
|
|
262
|
+
if (!event.id || !event.name) throw new AgentError("unknown", "Super Router sent a tool call without an id or name.", { provider: id });
|
|
263
|
+
call = { id: event.id, name: event.name };
|
|
264
|
+
open.set(event.index, call);
|
|
265
|
+
yield { type: "tool-call-start", callId: call.id, name: call.name };
|
|
266
|
+
}
|
|
267
|
+
if (event.arguments_delta) yield { type: "tool-call-delta", callId: call.id, argsDelta: event.arguments_delta };
|
|
268
|
+
} else if (event.type === "output.tool_call.completed") {
|
|
269
|
+
if (!open.has(event.index)) yield { type: "tool-call-start", callId: event.id, name: event.name };
|
|
270
|
+
const { value, repaired } = repairToolArguments(event.arguments);
|
|
271
|
+
completed += 1;
|
|
272
|
+
yield { type: "tool-call-end", callId: event.id, name: event.name, input: value, repaired };
|
|
273
|
+
} else if (event.type === "request.completed" || event.type === "request.failed") {
|
|
274
|
+
const usage = event.usage?.meters ? toUsage(event.usage.meters) : void 0;
|
|
275
|
+
if (usage) yield { type: "usage", usage };
|
|
192
276
|
const ok = event.type === "request.completed" && event.execution_status === "succeeded";
|
|
193
|
-
const finishReason = ok ? "
|
|
194
|
-
yield { type: "finish", finishReason, responseId: event.request_id };
|
|
277
|
+
const finishReason = ok ? finishOf(event.finish_reason, completed > 0) : event.finish_reason === "length" ? "length" : event.execution_status === "cancelled" ? "cancelled" : "error";
|
|
278
|
+
yield { type: "finish", finishReason, responseId: event.request_id, ...usage ? { usage } : {} };
|
|
195
279
|
} else if (event.type === "request.replayed") {
|
|
196
280
|
throw new AgentError("invalid-request", `This idempotency key was already used (request ${event.request_id}).`, { provider: id });
|
|
197
281
|
}
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/gateway.ts","../src/provider.ts"],"sourcesContent":["import {\n GatewayError,\n parseSSE,\n type InferenceGateway,\n type InferenceRequest,\n type InferenceResult,\n type StreamEvent,\n} from \"@supersolutions/super-protocol\";\n\nexport type SuperRouterGatewayConfig = {\n /** Origin of the Super Router server, e.g. \"https://router.example.com\". */\n baseUrl: string;\n /** A Super Router API key. Keep it server-side; the browser should use a proxy. */\n apiKey: string;\n fetch?: typeof fetch;\n};\n\nconst body = (request: InferenceRequest, stream: boolean) =>\n JSON.stringify({\n service: request.service,\n ...(request.service_version ? { service_version: request.service_version } : {}),\n customer_id: request.customer_id,\n input: { messages: request.messages },\n limits: {\n max_output_tokens: request.max_output_tokens ?? 1024,\n ...(request.timeout_ms ? { timeout_ms: request.timeout_ms } : {}),\n },\n stream,\n });\n\n/** An `InferenceGateway` over the Super Router HTTP API (`POST /v1/inferences`). */\nexport function createSuperRouterGateway(config: SuperRouterGatewayConfig): InferenceGateway {\n const base = config.baseUrl.replace(/\\/+$/, \"\");\n const doFetch = config.fetch ?? fetch;\n\n async function send(path: string, init: RequestInit, idempotencyKey?: string): Promise<Response> {\n let response: Response;\n try {\n response = await doFetch(base + path, {\n ...init,\n redirect: \"manual\",\n headers: {\n Authorization: `Bearer ${config.apiKey}`,\n \"Content-Type\": \"application/json\",\n ...(idempotencyKey ? { \"Idempotency-Key\": idempotencyKey } : {}),\n },\n });\n } catch (error) {\n if ((error as { name?: string })?.name === \"AbortError\") throw error;\n throw new GatewayError(\"network_error\");\n }\n // A repeated idempotency key answers 303 with the original request's location.\n if (response.status === 303 || (response.status >= 300 && response.status < 400)) return response;\n if (!response.ok) {\n let code = \"http_error\";\n let requestId: string | undefined;\n try {\n const parsed = (await response.json()) as { error?: { code?: string; request_id?: string } };\n code = parsed.error?.code ?? code;\n requestId = parsed.error?.request_id;\n } catch {\n /* non-JSON error body */\n }\n throw new GatewayError(code, response.status, requestId);\n }\n return response;\n }\n\n const requestIdFrom = (response: Response) => (response.headers.get(\"location\") ?? \"\").split(\"/\").pop() ?? \"\";\n\n return {\n async infer(request, idempotencyKey) {\n const response = await send(\"/v1/inferences\", { method: \"POST\", body: body(request, false) }, idempotencyKey);\n if (response.status >= 300 && response.status < 400) {\n const id = requestIdFrom(response);\n if (!id) throw new GatewayError(\"bad_redirect\", response.status);\n return (await (await send(\"/v1/requests/\" + encodeURIComponent(id), { method: \"GET\" })).json()) as InferenceResult;\n }\n return (await response.json()) as InferenceResult;\n },\n\n async *stream(request, idempotencyKey, signal) {\n const response = await send(\"/v1/inferences\", { method: \"POST\", body: body(request, true), ...(signal ? { signal } : {}) }, idempotencyKey);\n if (response.status >= 300 && response.status < 400) {\n yield { type: \"request.replayed\", request_id: requestIdFrom(response), sequence: 0 } satisfies StreamEvent;\n return;\n }\n if (!response.body) throw new GatewayError(\"empty_stream\");\n for await (const frame of parseSSE(response.body)) {\n yield { type: frame.event, ...(JSON.parse(frame.data) as object) } as StreamEvent;\n }\n },\n };\n}\n","import {\n AgentError,\n type CallOptions,\n type ContentPart,\n type FinishReason,\n type GenerateResult,\n type Message,\n type NormalizedRequest,\n type Provider,\n type StreamEvent,\n type Transport,\n type Usage,\n} from \"@supersolutions/super-chat-core\";\nimport { GatewayError, type InferenceGateway, type InferenceMessage, type InferenceRequest, type Usage as RouterUsage } from \"@supersolutions/super-protocol\";\n\nexport type SuperRouterProviderConfig = {\n gateway: InferenceGateway;\n /** The customer the usage is billed to. */\n customerId: string;\n id?: string;\n label?: string;\n /** Used when the request sets no `maxOutputTokens`. Super Router allows 1..8192. */\n defaultMaxOutputTokens?: number;\n /** One key per logical call; reuse it when retrying so the call never bills twice. */\n idempotencyKey?: () => string;\n};\n\n// A gateway provider has no HTTP of its own: the gateway holds the credential and the wire.\nconst noTransport: Transport = {\n kind: \"custom\",\n credentialSafe: true,\n async fetch() {\n throw new AgentError(\"not-supported\", \"The Super Router provider does not use a Transport.\");\n },\n} as Transport;\n\nfunction textOf(parts: ContentPart[]): { text: string; dropped: number } {\n let dropped = 0;\n const text = parts\n .map((p) => {\n if (p.type === \"text\") return p.text;\n if (p.type !== \"reasoning\") dropped += 1;\n return \"\";\n })\n .filter(Boolean)\n .join(\"\\n\");\n return { text, dropped };\n}\n\nfunction toMessages(req: NormalizedRequest): { messages: InferenceMessage[]; warnings: string[] } {\n const warnings: string[] = [];\n const messages: InferenceMessage[] = [];\n if (req.system) messages.push({ role: \"system\", content: req.system });\n let dropped = 0;\n for (const m of req.messages as Message[]) {\n if (m.role === \"tool\") {\n dropped += m.parts.length;\n continue;\n }\n const t = textOf(m.parts);\n dropped += t.dropped;\n if (t.text) messages.push({ role: m.role, content: t.text });\n }\n if (dropped) warnings.push(`${dropped} non-text part(s) were dropped: Super Router services take text messages only.`);\n if (req.tools?.length) warnings.push(\"Tools were ignored: Super Router services do not call tools yet.\");\n if (!messages.some((m) => m.role !== \"system\")) throw new AgentError(\"invalid-request\", \"Super Router needs at least one user or assistant text message.\");\n return { messages, warnings };\n}\n\nfunction toUsage(u?: RouterUsage): Usage {\n if (!u) return {};\n const inputTokens = u.input + u.cached + u.cache_write;\n return { inputTokens, outputTokens: u.output, totalTokens: inputTokens + u.output, ...(u.cached ? { cachedInputTokens: u.cached } : {}) };\n}\n\nfunction toError(error: unknown, provider: string): AgentError {\n if (error instanceof AgentError) return error;\n if ((error as { name?: string })?.name === \"AbortError\") return new AgentError(\"cancelled\", \"Cancelled.\", { provider, cause: error });\n if (error instanceof GatewayError) {\n const status = error.status;\n const kind = error.code === \"network_error\" ? \"network\"\n : status === 401 || status === 403 ? \"auth\"\n : status === 402 ? \"invalid-request\"\n : status === 429 ? \"rate-limit\"\n : status !== undefined && status >= 500 ? \"overloaded\"\n : status !== undefined && status >= 400 ? \"invalid-request\"\n : \"unknown\";\n return new AgentError(kind, error.requestId ? `${error.code} (request ${error.requestId})` : error.code, { ...(status ? { status } : {}), provider, cause: error });\n }\n return new AgentError(\"unknown\", error instanceof Error ? error.message : String(error), { provider, cause: error });\n}\n\n/**\n * A text-only `Provider` that sends every call through an `InferenceGateway`.\n * `NormalizedRequest.model` is the Super Router **service** id, not a raw model name.\n */\nexport function createSuperRouterProvider(config: SuperRouterProviderConfig): Provider {\n const id = config.id ?? \"super-router\";\n const newKey = config.idempotencyKey ?? (() => globalThis.crypto.randomUUID());\n const build = (req: NormalizedRequest) => {\n const { messages, warnings } = toMessages(req);\n const request: InferenceRequest = {\n service: req.model,\n customer_id: config.customerId,\n messages,\n max_output_tokens: Math.min(8192, Math.max(1, req.maxOutputTokens ?? config.defaultMaxOutputTokens ?? 1024)),\n };\n return { request, warnings };\n };\n\n return {\n id,\n label: config.label ?? \"Super Router\",\n capabilities: {\n streaming: true, backgroundJobs: false, resumableStreams: false, tools: false, parallelToolCalls: false,\n images: false, files: false, audio: false, reasoning: false, strictJsonSchema: false, serverSideHistory: false, fileUpload: false,\n },\n transport: noTransport,\n\n async generate(req: NormalizedRequest, _opts?: CallOptions): Promise<GenerateResult> {\n const { request, warnings } = build(req);\n try {\n const result = await config.gateway.infer(request, newKey());\n const failed = result.execution_status !== \"succeeded\";\n if (!result.output) {\n // A repeated idempotency key reads the stored request back, and completions are never stored.\n throw new AgentError(\"invalid-request\", `This idempotency key was already used (request ${result.id}); the router does not store output, so it cannot be replayed.`, { provider: id });\n }\n return {\n parts: [{ type: \"text\", text: result.output.content }],\n finishReason: failed ? \"error\" : \"stop\",\n usage: toUsage(result.usage.meters),\n responseId: result.id,\n modelId: req.model,\n ...(warnings.length ? { warnings } : {}),\n };\n } catch (error) {\n throw toError(error, id);\n }\n },\n\n async *stream(req: NormalizedRequest, opts?: CallOptions): AsyncIterable<StreamEvent> {\n const { request } = build(req);\n let started = false;\n try {\n for await (const event of config.gateway.stream(request, newKey(), opts?.signal)) {\n if (!started) {\n started = true;\n yield { type: \"start\", responseId: event.request_id, modelId: req.model };\n }\n if (event.type === \"output.delta\") yield { type: \"text-delta\", delta: event.text };\n else if (event.type === \"request.completed\" || event.type === \"request.failed\") {\n const ok = event.type === \"request.completed\" && event.execution_status === \"succeeded\";\n const finishReason: FinishReason = ok ? \"stop\" : event.execution_status === \"cancelled\" ? \"cancelled\" : \"error\";\n yield { type: \"finish\", finishReason, responseId: event.request_id };\n } else if (event.type === \"request.replayed\") {\n // The original call already ran; its result is read with the request id, never re-billed.\n throw new AgentError(\"invalid-request\", `This idempotency key was already used (request ${event.request_id}).`, { provider: id });\n }\n }\n } catch (error) {\n yield { type: \"error\", error: (() => { try { throw toError(error, id); } catch (e) { return e; } })() };\n }\n },\n };\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,EACA;AAAA,OAKK;AAUP,IAAM,OAAO,CAAC,SAA2B,WACvC,KAAK,UAAU;AAAA,EACb,SAAS,QAAQ;AAAA,EACjB,GAAI,QAAQ,kBAAkB,EAAE,iBAAiB,QAAQ,gBAAgB,IAAI,CAAC;AAAA,EAC9E,aAAa,QAAQ;AAAA,EACrB,OAAO,EAAE,UAAU,QAAQ,SAAS;AAAA,EACpC,QAAQ;AAAA,IACN,mBAAmB,QAAQ,qBAAqB;AAAA,IAChD,GAAI,QAAQ,aAAa,EAAE,YAAY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W,mBAAmB,kDAAkD,MAAM,UAAU,MAAM,EAAE,UAAU,GAAG,CAAC;AAAA,UAClI;AAAA,QACF;AAAA,MACF,SAAS,OAAO;AACd,cAAM,EAAE,MAAM,SAAS,QAAQ,MAAM;AAAE,cAAI;AAAE,kBAAM,QAAQ,OAAO,EAAE;AAAA,UAAG,SAAS,GAAG;AAAE,mBAAO;AAAA,UAAG;AAAA,QAAE,GAAG,EAAE;AAAA,MACxG;AAAA,IACF;AAAA,EACF;AACF;","names":["GatewayError"]}
|
|
1
|
+
{"version":3,"sources":["../src/gateway.ts","../src/provider.ts"],"sourcesContent":["import {\n GatewayError,\n parseSSE,\n type InferenceGateway,\n type InferenceRequest,\n type InferenceResult,\n type StreamEvent,\n} from \"@supersolutions/super-protocol\";\n\nexport type SuperRouterGatewayConfig = {\n /** Origin of the Super Router server, e.g. \"https://router.example.com\". */\n baseUrl: string;\n /** A Super Router API key. Keep it server-side; the browser should use a proxy. */\n apiKey: string;\n fetch?: typeof fetch;\n};\n\nconst body = (request: InferenceRequest, stream: boolean) => {\n return JSON.stringify({\n service: request.service,\n ...(request.service_version ? { service_version: request.service_version } : {}),\n customer_id: request.customer_id,\n input: {\n messages: request.messages,\n ...(request.tools?.length ? { tools: request.tools } : {}),\n ...(request.tools?.length && request.tool_choice !== undefined ? { tool_choice: request.tool_choice } : {}),\n },\n limits: {\n max_output_tokens: request.max_output_tokens ?? 1024,\n ...(request.timeout_ms ? { timeout_ms: request.timeout_ms } : {}),\n },\n stream,\n });\n};\n\n/** An `InferenceGateway` over the Super Router HTTP API (`POST /v1/inferences`). */\nexport function createSuperRouterGateway(config: SuperRouterGatewayConfig): InferenceGateway {\n const base = config.baseUrl.replace(/\\/+$/, \"\");\n const doFetch = config.fetch ?? fetch;\n\n async function send(path: string, init: RequestInit, idempotencyKey?: string): Promise<Response> {\n let response: Response;\n try {\n response = await doFetch(base + path, {\n ...init,\n redirect: \"manual\",\n headers: {\n Authorization: `Bearer ${config.apiKey}`,\n \"Content-Type\": \"application/json\",\n ...(idempotencyKey ? { \"Idempotency-Key\": idempotencyKey } : {}),\n },\n });\n } catch (error) {\n if ((error as { name?: string })?.name === \"AbortError\") throw error;\n throw new GatewayError(\"network_error\");\n }\n // A repeated idempotency key answers 303 with the original request's location.\n if (response.status === 303 || (response.status >= 300 && response.status < 400)) return response;\n if (!response.ok) {\n let code = \"http_error\";\n let requestId: string | undefined;\n try {\n const parsed = (await response.json()) as { error?: { code?: string; request_id?: string } };\n code = parsed.error?.code ?? code;\n requestId = parsed.error?.request_id;\n } catch {\n /* non-JSON error body */\n }\n throw new GatewayError(code, response.status, requestId);\n }\n return response;\n }\n\n const requestIdFrom = (response: Response) => (response.headers.get(\"location\") ?? \"\").split(\"/\").pop() ?? \"\";\n\n return {\n async infer(request, idempotencyKey) {\n const response = await send(\"/v1/inferences\", { method: \"POST\", body: body(request, false) }, idempotencyKey);\n if (response.status >= 300 && response.status < 400) {\n const id = requestIdFrom(response);\n if (!id) throw new GatewayError(\"bad_redirect\", response.status);\n return (await (await send(\"/v1/requests/\" + encodeURIComponent(id), { method: \"GET\" })).json()) as InferenceResult;\n }\n return (await response.json()) as InferenceResult;\n },\n\n async *stream(request, idempotencyKey, signal) {\n const response = await send(\"/v1/inferences\", { method: \"POST\", body: body(request, true), ...(signal ? { signal } : {}) }, idempotencyKey);\n if (response.status >= 300 && response.status < 400) {\n yield { type: \"request.replayed\", request_id: requestIdFrom(response), sequence: 0 } satisfies StreamEvent;\n return;\n }\n if (!response.body) throw new GatewayError(\"empty_stream\");\n for await (const frame of parseSSE(response.body)) {\n yield { type: frame.event, ...(JSON.parse(frame.data) as object) } as StreamEvent;\n }\n },\n };\n}\n","import {\n AgentError,\n type CallOptions,\n type ContentPart,\n type FinishReason,\n type GenerateResult,\n type Message,\n type NormalizedRequest,\n type Provider,\n repairToolArguments,\n type StreamEvent,\n type Transport,\n type Usage,\n} from \"@supersolutions/super-chat-core\";\nimport {\n GatewayError,\n type InferenceContentPart,\n type InferenceFinishReason,\n type InferenceGateway,\n type InferenceMessage,\n type InferenceRequest,\n type InferenceTool,\n type InferenceToolCall,\n type InferenceToolChoice,\n type StreamEvent as RouterStreamEvent,\n type Usage as RouterUsage,\n} from \"@supersolutions/super-protocol\";\n\nexport type SuperRouterProviderConfig = {\n gateway: InferenceGateway;\n /** The customer the usage is billed to. */\n customerId: string;\n id?: string;\n label?: string;\n /** Used when the request sets no `maxOutputTokens`. Super Router allows 1..8192. */\n defaultMaxOutputTokens?: number;\n /** One key per logical call; reuse it when retrying so the call never bills twice. */\n idempotencyKey?: () => string;\n /**\n * Send tools and images to the router. Default true. Turn it off for a server\n * that predates tool calling: tools are then left out with a warning.\n */\n toolCalling?: boolean;\n};\n\n// A gateway provider has no HTTP of its own: the gateway holds the credential and the wire.\nconst noTransport: Transport = {\n kind: \"custom\",\n credentialSafe: true,\n async fetch() {\n throw new AgentError(\"not-supported\", \"The Super Router provider does not use a Transport.\");\n },\n} as Transport;\n\nconst MAX_TOOL_RESULT_CHARS = 256_000;\nconst MAX_TOOL_DESCRIPTION_CHARS = 4096;\nconst IMAGE_MEDIA = /^image\\/(png|jpeg|gif|webp)$/;\n\n// Super Router accepts these characters in a call id; a thread may hold ids minted by another provider.\nconst wireCallId = (id: string) => id.replace(/[^a-zA-Z0-9_-]/g, \"_\").slice(0, 128) || \"call\";\n\nconst asText = (output: unknown) => (typeof output === \"string\" ? output : (JSON.stringify(output) ?? \"null\"));\n\nfunction resultText(output: unknown): string {\n const text = asText(output);\n const marker = \"…[truncated]\";\n return text.length > MAX_TOOL_RESULT_CHARS ? text.slice(0, MAX_TOOL_RESULT_CHARS - marker.length) + marker : text;\n}\n\n// The wire requires a JSON object; a repaired call can hold any JSON value.\nfunction argumentsText(input: unknown): string {\n const object = typeof input === \"object\" && input !== null && !Array.isArray(input);\n return JSON.stringify(object ? input : input === undefined || input === null ? {} : { input });\n}\n\nfunction imageUrl(part: Extract<ContentPart, { type: \"image\" }>): string | undefined {\n const { source, mediaType } = part;\n if (source.kind === \"url\") return source.url.startsWith(\"https://\") || /^data:image\\/(png|jpeg|gif|webp);base64,/.test(source.url) ? source.url : undefined;\n if (source.kind === \"base64\" && mediaType && IMAGE_MEDIA.test(mediaType)) return `data:${mediaType};base64,${source.data}`;\n return undefined;\n}\n\nfunction toMessages(req: NormalizedRequest, toolCalling: boolean): { messages: InferenceMessage[]; warnings: string[] } {\n const warnings: string[] = [];\n const messages: InferenceMessage[] = [];\n if (req.system) messages.push({ role: \"system\", content: req.system });\n const history = req.messages as Message[];\n // A call without a result, or a result without a call, is refused by the router: both happen in interrupted threads.\n const called = new Set(history.flatMap((m) => m.parts.flatMap((p) => (p.type === \"tool-call\" ? [p.callId] : []))));\n const answered = new Set(history.flatMap((m) => m.parts.flatMap((p) => (p.type === \"tool-result\" ? [p.callId] : []))));\n let dropped = 0;\n for (const m of history) {\n const texts: string[] = [];\n const images: InferenceContentPart[] = [];\n const calls: InferenceToolCall[] = [];\n const results: InferenceMessage[] = [];\n for (const p of m.parts) {\n if (p.type === \"text\") {\n if (p.text) texts.push(p.text);\n } else if (p.type === \"image\" && toolCalling) {\n const url = imageUrl(p);\n if (url) images.push({ type: \"image\", url, ...(p.detail ? { detail: p.detail } : {}) });\n else dropped += 1;\n } else if (p.type === \"tool-call\" && toolCalling) {\n if (answered.has(p.callId)) calls.push({ id: wireCallId(p.callId), name: p.name, arguments: argumentsText(p.input) });\n } else if (p.type === \"tool-result\" && toolCalling) {\n if (called.has(p.callId)) results.push({ role: \"tool\", tool_call_id: wireCallId(p.callId), content: resultText(p.output), ...(p.failure ? { is_error: true } : {}) });\n } else if (p.type !== \"reasoning\" && p.type !== \"artifact\") {\n dropped += 1;\n }\n }\n const text = texts.join(\"\\n\");\n if (m.role === \"tool\") messages.push(...results);\n else if (m.role === \"assistant\" && calls.length) messages.push({ role: \"assistant\", ...(text ? { content: text } : {}), tool_calls: calls });\n else if (m.role === \"user\" && images.length) messages.push({ role: \"user\", content: [...(text ? [{ type: \"text\" as const, text }] : []), ...images] });\n else if (text) messages.push({ role: m.role, content: text });\n if (m.role !== \"tool\") messages.push(...results);\n }\n if (dropped) warnings.push(`${dropped} part(s) were dropped: Super Router takes text, tool calls and https or base64 PNG, JPEG, GIF and WebP images.`);\n if (!toolCalling && req.tools?.length) warnings.push(\"Tools were ignored: tool calling is turned off for this provider.\");\n if (!messages.some((m) => m.role !== \"system\")) throw new AgentError(\"invalid-request\", \"Super Router needs at least one user or assistant message.\");\n return { messages, warnings };\n}\n\nfunction toTools(req: NormalizedRequest): { tools?: InferenceTool[]; tool_choice?: InferenceToolChoice } {\n const active = req.activeTools ? new Set(req.activeTools) : undefined;\n const tools = (req.tools ?? [])\n .filter((t) => !active || active.has(t.name))\n .map((t): InferenceTool => ({\n name: t.name,\n ...(t.description ? { description: t.description.slice(0, MAX_TOOL_DESCRIPTION_CHARS) } : {}),\n input_schema: { ...t.parameters, type: \"object\" },\n }));\n if (!tools.length) return {};\n const choice = req.toolChoice;\n if (!choice) return { tools };\n if (choice.type !== \"tool\") return { tools, tool_choice: choice.type };\n // Naming a tool that is not on offer this step would be refused; let the model choose instead.\n return tools.some((t) => t.name === choice.name) ? { tools, tool_choice: { name: choice.name } } : { tools };\n}\n\nconst finishOf = (reason: InferenceFinishReason | undefined, hasCalls: boolean): FinishReason =>\n reason === \"length\" ? \"length\" : reason === \"tool_calls\" || hasCalls ? \"tool-calls\" : \"stop\";\n\nfunction toUsage(u?: RouterUsage): Usage {\n if (!u) return {};\n const inputTokens = u.input + u.cached + u.cache_write;\n return { inputTokens, outputTokens: u.output, totalTokens: inputTokens + u.output, ...(u.cached ? { cachedInputTokens: u.cached } : {}) };\n}\n\nfunction toError(error: unknown, provider: string): AgentError {\n if (error instanceof AgentError) return error;\n if ((error as { name?: string })?.name === \"AbortError\") return new AgentError(\"cancelled\", \"Cancelled.\", { provider, cause: error });\n if (error instanceof GatewayError) {\n const status = error.status;\n const kind = error.code === \"network_error\" ? \"network\"\n : status === 401 || status === 403 ? \"auth\"\n : status === 402 ? \"invalid-request\"\n : status === 429 ? \"rate-limit\"\n : status !== undefined && status >= 500 ? \"overloaded\"\n : status !== undefined && status >= 400 ? \"invalid-request\"\n : \"unknown\";\n return new AgentError(kind, error.requestId ? `${error.code} (request ${error.requestId})` : error.code, { ...(status ? { status } : {}), provider, cause: error });\n }\n return new AgentError(\"unknown\", error instanceof Error ? error.message : String(error), { provider, cause: error });\n}\n\n/**\n * A `Provider` that sends every call through an `InferenceGateway`, with tool calling and images.\n * `NormalizedRequest.model` is the Super Router **service** id, not a raw model name.\n */\nexport function createSuperRouterProvider(config: SuperRouterProviderConfig): Provider {\n const id = config.id ?? \"super-router\";\n const newKey = config.idempotencyKey ?? (() => globalThis.crypto.randomUUID());\n const toolCalling = config.toolCalling !== false;\n const build = (req: NormalizedRequest) => {\n const { messages, warnings } = toMessages(req, toolCalling);\n const request: InferenceRequest = {\n service: req.model,\n customer_id: config.customerId,\n messages,\n ...(toolCalling ? toTools(req) : {}),\n max_output_tokens: Math.min(8192, Math.max(1, req.maxOutputTokens ?? config.defaultMaxOutputTokens ?? 1024)),\n };\n return { request, warnings };\n };\n\n return {\n id,\n label: config.label ?? \"Super Router\",\n capabilities: {\n streaming: true, backgroundJobs: false, resumableStreams: false, tools: toolCalling, parallelToolCalls: toolCalling,\n images: toolCalling, files: false, audio: false, reasoning: false, strictJsonSchema: false, serverSideHistory: false, fileUpload: false,\n },\n transport: noTransport,\n\n async generate(req: NormalizedRequest, _opts?: CallOptions): Promise<GenerateResult> {\n const { request, warnings } = build(req);\n try {\n const result = await config.gateway.infer(request, newKey());\n const failed = result.execution_status !== \"succeeded\";\n if (!result.output) {\n // A repeated idempotency key reads the stored request back, and completions are never stored.\n throw new AgentError(\"invalid-request\", `This idempotency key was already used (request ${result.id}); the router does not store output, so it cannot be replayed.`, { provider: id });\n }\n const calls = result.output.tool_calls ?? [];\n const parts: ContentPart[] = [\n ...(result.output.content || !calls.length ? [{ type: \"text\" as const, text: result.output.content }] : []),\n ...calls.map((call): ContentPart => {\n const { value, repaired } = repairToolArguments(call.arguments);\n return { type: \"tool-call\", callId: call.id, name: call.name, input: value, status: \"pending\", ...(repaired ? { repaired } : {}) };\n }),\n ];\n return {\n parts,\n finishReason: failed ? \"error\" : finishOf(result.finish_reason, calls.length > 0),\n usage: toUsage(result.usage.meters),\n responseId: result.id,\n modelId: req.model,\n ...(warnings.length ? { warnings } : {}),\n };\n } catch (error) {\n throw toError(error, id);\n }\n },\n\n async *stream(req: NormalizedRequest, opts?: CallOptions): AsyncIterable<StreamEvent> {\n const { request } = build(req);\n let started = false;\n // Calls that have begun, by the router's index. Only `completed` makes one callable.\n const open = new Map<number, { id: string; name: string }>();\n let completed = 0;\n try {\n for await (const raw of config.gateway.stream(request, newKey(), opts?.signal)) {\n // A failed request can also say why the model stopped, which the protocol does not name yet.\n const event = raw as RouterStreamEvent & { finish_reason?: InferenceFinishReason };\n if (!started) {\n started = true;\n yield { type: \"start\", responseId: event.request_id, modelId: req.model };\n }\n if (event.type === \"output.delta\") yield { type: \"text-delta\", delta: event.text };\n else if (event.type === \"output.tool_call.delta\") {\n let call = open.get(event.index);\n if (!call) {\n if (!event.id || !event.name) throw new AgentError(\"unknown\", \"Super Router sent a tool call without an id or name.\", { provider: id });\n call = { id: event.id, name: event.name };\n open.set(event.index, call);\n yield { type: \"tool-call-start\", callId: call.id, name: call.name };\n }\n if (event.arguments_delta) yield { type: \"tool-call-delta\", callId: call.id, argsDelta: event.arguments_delta };\n } else if (event.type === \"output.tool_call.completed\") {\n if (!open.has(event.index)) yield { type: \"tool-call-start\", callId: event.id, name: event.name };\n const { value, repaired } = repairToolArguments(event.arguments);\n completed += 1;\n yield { type: \"tool-call-end\", callId: event.id, name: event.name, input: value, repaired };\n } else if (event.type === \"request.completed\" || event.type === \"request.failed\") {\n const usage = event.usage?.meters ? toUsage(event.usage.meters) : undefined;\n if (usage) yield { type: \"usage\", usage };\n const ok = event.type === \"request.completed\" && event.execution_status === \"succeeded\";\n const finishReason: FinishReason = ok\n ? finishOf(event.finish_reason, completed > 0)\n : event.finish_reason === \"length\"\n ? \"length\"\n : event.execution_status === \"cancelled\"\n ? \"cancelled\"\n : \"error\";\n yield { type: \"finish\", finishReason, responseId: event.request_id, ...(usage ? { usage } : {}) };\n } else if (event.type === \"request.replayed\") {\n // The original call already ran; its result is read with the request id, never re-billed.\n throw new AgentError(\"invalid-request\", `This idempotency key was already used (request ${event.request_id}).`, { provider: id });\n }\n }\n } catch (error) {\n yield { type: \"error\", error: (() => { try { throw toError(error, id); } catch (e) { return e; } })() };\n }\n },\n };\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,EACA;AAAA,OAKK;AAUP,IAAM,OAAO,CAAC,SAA2B,WAAoB;AAC3D,SAAO,KAAK,UAAU;AAAA,IACpB,SAAS,QAAQ;AAAA,IACjB,GAAI,QAAQ,kBAAkB,EAAE,iBAAiB,QAAQ,gBAAgB,IAAI,CAAC;AAAA,IAC9E,aAAa,QAAQ;AAAA,IACrB,OAAO;AAAA,MACL,UAAU,QAAQ;AAAA,MAClB,GAAI,QAAQ,OAAO,SAAS,EAAE,OAAO,QAAQ,MAAM,IAAI,CAAC;AAAA,MACxD,GAAI,QAAQ,OAAO,UAAU,QAAQ,gBAAgB,SAAY,EAAE,aAAa,QAAQ,YAAY,IAAI,CAAC;AAAA,IAC3G;AAAA,IACA,QAAQ;AAAA,MACN,mBAAmB,QAAQ,qBAAqB;AAAA,MAChD,GAAI,QAAQ,aAAa,EAAE,YAAY,QAAQ,WAAW,IAAI,CAAC;AAAA,IACjE;AAAA,IACA;AAAA,EACF,CAAC;AACH;AAGO,SAAS,yBAAyB,QAAoD;AAC3F,QAAM,OAAO,OAAO,QAAQ,QAAQ,QAAQ,EAAE;AAC9C,QAAM,UAAU,OAAO,SAAS;AAEhC,iBAAe,KAAK,MAAc,MAAmB,gBAA4C;AAC/F,QAAI;AACJ,QAAI;AACF,iBAAW,MAAM,QAAQ,OAAO,MAAM;AAAA,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AAI,MAAM,MAAM,KAAK;AAChG,kBAAM,EAAE,OAAO,SAAS,IAAI,oBAAoB,MAAM,SAAS;AAC/D,yBAAa;AACb,kBAAM,EAAE,MAAM,iBAAiB,QAAQ,MAAM,IAAI,MAAM,MAAM,MAAM,OAAO,OAAO,SAAS;AAAA,UAC5F,WAAW,MAAM,SAAS,uBAAuB,MAAM,SAAS,kBAAkB;AAChF,kBAAM,QAAQ,MAAM,OAAO,SAAS,QAAQ,MAAM,MAAM,MAAM,IAAI;AAClE,gBAAI,MAAO,OAAM,EAAE,MAAM,SAAS,MAAM;AACxC,kBAAM,KAAK,MAAM,SAAS,uBAAuB,MAAM,qBAAqB;AAC5E,kBAAM,eAA6B,KAC/B,SAAS,MAAM,eAAe,YAAY,CAAC,IAC3C,MAAM,kBAAkB,WACtB,WACA,MAAM,qBAAqB,cACzB,cACA;AACR,kBAAM,EAAE,MAAM,UAAU,cAAc,YAAY,MAAM,YAAY,GAAI,QAAQ,EAAE,MAAM,IAAI,CAAC,EAAG;AAAA,UAClG,WAAW,MAAM,SAAS,oBAAoB;AAE5C,kBAAM,IAAI,WAAW,mBAAmB,kDAAkD,MAAM,UAAU,MAAM,EAAE,UAAU,GAAG,CAAC;AAAA,UAClI;AAAA,QACF;AAAA,MACF,SAAS,OAAO;AACd,cAAM,EAAE,MAAM,SAAS,QAAQ,MAAM;AAAE,cAAI;AAAE,kBAAM,QAAQ,OAAO,EAAE;AAAA,UAAG,SAAS,GAAG;AAAE,mBAAO;AAAA,UAAG;AAAA,QAAE,GAAG,EAAE;AAAA,MACxG;AAAA,IACF;AAAA,EACF;AACF;","names":["GatewayError"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@supersolutions/super-chat-router",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Super Router binding for super-chat: an HTTP InferenceGateway and a text Provider that routes through any InferenceGateway.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "SUPER SOLUTION LABS INC",
|
|
@@ -41,8 +41,8 @@
|
|
|
41
41
|
"access": "public"
|
|
42
42
|
},
|
|
43
43
|
"dependencies": {
|
|
44
|
-
"@supersolutions/super-protocol": "0.
|
|
45
|
-
"@supersolutions/super-chat-core": "0.
|
|
44
|
+
"@supersolutions/super-protocol": "0.2.0",
|
|
45
|
+
"@supersolutions/super-chat-core": "0.2.0"
|
|
46
46
|
},
|
|
47
47
|
"devDependencies": {
|
|
48
48
|
"tsup": "^8.3.5",
|