agent402-model-provider 0.0.0-stage → 0.7.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 +21 -0
- package/README.md +175 -2
- package/cli.js +224 -0
- package/index.d.ts +93 -0
- package/index.js +209 -0
- package/known-assets.js +358 -0
- package/models.d.ts +41 -0
- package/models.js +122 -0
- package/openclaw.plugin.json +64 -0
- package/package.json +92 -4
- package/provider.js +45 -0
- package/proxy.d.ts +48 -0
- package/proxy.js +311 -0
package/proxy.js
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
// Local proxy: OpenClaw (or any client) talks to http://127.0.0.1:<port>, the
|
|
2
|
+
// proxy pays Agent402 and forwards. Two wires:
|
|
3
|
+
// OpenAI POST /v1/chat/completions -> the tier the model id names
|
|
4
|
+
// Anthropic POST /v1/messages -> the gateway's metered Messages
|
|
5
|
+
// route (/v1/metered/messages), so Claude Code and the Anthropic
|
|
6
|
+
// SDK pay from a wallet too (ANTHROPIC_BASE_URL=http://127.0.0.1:<port>).
|
|
7
|
+
//
|
|
8
|
+
// Two ways to pay, chosen at start:
|
|
9
|
+
// creditsKey - a prepaid credits key (a402_...) sent as a Bearer; the
|
|
10
|
+
// gateway authorizes against the balance before the handler and
|
|
11
|
+
// debits only on a final 200. No wallet, no chain.
|
|
12
|
+
// payFetch - an x402-paying fetch (e.g. @x402/fetch wrapped around a
|
|
13
|
+
// wallet signer) used for the upstream call; the gateway's 402
|
|
14
|
+
// is settled per call in USDC. The proxy never sees a key.
|
|
15
|
+
// With neither, paid calls answer a 402-shaped JSON that says how to set up.
|
|
16
|
+
//
|
|
17
|
+
// Routing: the model id decides the upstream tier endpoint, read from the
|
|
18
|
+
// gateway's own GET /v1/models at start (never a hand-typed table). "auto"
|
|
19
|
+
// goes to the routed tier with the model field omitted.
|
|
20
|
+
//
|
|
21
|
+
// Idempotency: a client-supplied Idempotency-Key is passed through so an
|
|
22
|
+
// x402 retry with the same key replays the paid answer server-side; without
|
|
23
|
+
// one each forwarded call gets a fresh key (a safety for the fetch layer's
|
|
24
|
+
// own 402->pay retry), which does NOT make two client calls one payment.
|
|
25
|
+
// Streams pass through byte for byte.
|
|
26
|
+
//
|
|
27
|
+
// Refusals: a refused paid call's 402 from an x402 v2 seller carries the whole
|
|
28
|
+
// payment offer in its JSON body (Agent402 mirrors its PAYMENT-REQUIRED header
|
|
29
|
+
// there) beside the refusal's own reason, hint and retry. OpenClaw's model
|
|
30
|
+
// client builds its error message from `error.message`, else from the whole
|
|
31
|
+
// body, so relaying that body put kilobytes of accepts and schemas into the
|
|
32
|
+
// agent's error text in place of the one sentence that says what to fix. Such
|
|
33
|
+
// a body is answered in the OpenAI error shape instead (refusalAsOpenAIError);
|
|
34
|
+
// every other upstream body passes through byte for byte.
|
|
35
|
+
//
|
|
36
|
+
// Loopback only, and browser-hostile on purpose: any web page can POST to
|
|
37
|
+
// 127.0.0.1 with a "simple" no-cors request, and this proxy spends the
|
|
38
|
+
// user's key, so a request carrying an Origin header (browsers always send
|
|
39
|
+
// one on cross-origin POSTs; native clients send none) or a Host that is
|
|
40
|
+
// not loopback is refused before anything is forwarded.
|
|
41
|
+
import { createServer } from "node:http";
|
|
42
|
+
import { readFileSync } from "node:fs";
|
|
43
|
+
import { randomUUID } from "node:crypto";
|
|
44
|
+
import { AUTO_ID, routesFromCatalog, stripTrailingSlashes } from "./models.js";
|
|
45
|
+
|
|
46
|
+
export const DEFAULT_UPSTREAM = "https://agent402.tools";
|
|
47
|
+
export const PKG_VERSION = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8")).version;
|
|
48
|
+
// The User-Agent product token that names this package on every request.
|
|
49
|
+
const USER_AGENT = `agent402-model-provider/${PKG_VERSION}`;
|
|
50
|
+
const MAX_BODY = 2 * 1024 * 1024;
|
|
51
|
+
|
|
52
|
+
// The model catalog read (GET /v1/models) settles nothing, so a 503 the
|
|
53
|
+
// server sheds under load is safe to repeat. It is retried only when it names
|
|
54
|
+
// its own delay (a Retry-After header or a retryAfterSeconds body field), at
|
|
55
|
+
// most DISCOVERY_ATTEMPTS tries in all, each wait capped at
|
|
56
|
+
// DISCOVERY_MAX_WAIT_MS. A paid call never goes through here: a repeat of
|
|
57
|
+
// one could settle twice.
|
|
58
|
+
const DISCOVERY_ATTEMPTS = 3;
|
|
59
|
+
const DISCOVERY_MAX_WAIT_MS = 5000;
|
|
60
|
+
|
|
61
|
+
async function shedRetryWaitMs(r) {
|
|
62
|
+
if (!r || r.status !== 503) return null;
|
|
63
|
+
const header = r.headers && typeof r.headers.get === "function" ? r.headers.get("retry-after") : null;
|
|
64
|
+
let seconds = header != null && String(header).trim() !== "" ? Number(header) : NaN;
|
|
65
|
+
if (!Number.isFinite(seconds)) {
|
|
66
|
+
try {
|
|
67
|
+
const body = await (typeof r.clone === "function" ? r.clone() : r).json();
|
|
68
|
+
seconds = Number(body && body.retryAfterSeconds);
|
|
69
|
+
} catch { seconds = NaN; }
|
|
70
|
+
}
|
|
71
|
+
if (!Number.isFinite(seconds) || seconds < 0) return null;
|
|
72
|
+
return Math.min(seconds * 1000, DISCOVERY_MAX_WAIT_MS);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// Resolves with the 2xx response, or throws `${label}: HTTP <status>` (plus
|
|
76
|
+
// "after N attempts" when it retried, and the server's `error` text) with
|
|
77
|
+
// `.status`, `.body` and `.attempts` set.
|
|
78
|
+
// `init` may be a function, so each attempt gets its own timeout signal.
|
|
79
|
+
async function discoveryFetch(fetchImpl, label, url, init) {
|
|
80
|
+
let r;
|
|
81
|
+
let attempts = 0;
|
|
82
|
+
for (;;) {
|
|
83
|
+
attempts++;
|
|
84
|
+
const i = (typeof init === "function" ? init() : init) || {};
|
|
85
|
+
r = await fetchImpl(url, { ...i, headers: { "User-Agent": USER_AGENT, ...(i.headers || {}) } });
|
|
86
|
+
if (r.ok) return r;
|
|
87
|
+
if (attempts >= DISCOVERY_ATTEMPTS) break;
|
|
88
|
+
const wait = await shedRetryWaitMs(r);
|
|
89
|
+
if (wait == null) break;
|
|
90
|
+
await new Promise((resolve) => setTimeout(resolve, wait));
|
|
91
|
+
}
|
|
92
|
+
const err = await responseError(`${label}: HTTP ${r.status}${attempts > 1 ? ` after ${attempts} attempts` : ""}`, r);
|
|
93
|
+
err.attempts = attempts;
|
|
94
|
+
throw err;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// The server's own answer to a failed request, on the thrown error: its
|
|
98
|
+
// `error` text joins the message, and `.status` and `.body` (the parsed JSON,
|
|
99
|
+
// else the text, at most ERROR_BODY_MAX characters) are set, so a caller sees
|
|
100
|
+
// why the call failed (a refusal, a limit, a missing parameter).
|
|
101
|
+
const ERROR_BODY_MAX = 4000;
|
|
102
|
+
async function responseError(message, r) {
|
|
103
|
+
let text = "";
|
|
104
|
+
try { text = typeof r?.text === "function" ? String(await r.text()) : ""; } catch { text = ""; }
|
|
105
|
+
text = text.slice(0, ERROR_BODY_MAX);
|
|
106
|
+
let body = null;
|
|
107
|
+
try { body = text ? JSON.parse(text) : null; } catch { body = null; }
|
|
108
|
+
const said = body && typeof body === "object" && typeof body.error === "string" ? body.error.slice(0, 500) : (!body ? text.trim().slice(0, 300) : "");
|
|
109
|
+
const err = new Error(said ? `${message}: ${said}` : message);
|
|
110
|
+
err.status = r?.status;
|
|
111
|
+
err.body = body ?? (text || null);
|
|
112
|
+
return err;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export async function loadRoutes(upstream, fetchImpl = fetch, { pricing = "metered" } = {}) {
|
|
116
|
+
const r = await discoveryFetch(fetchImpl, "GET /v1/models", `${upstream}/v1/models`, () => ({ headers: { accept: "application/json" }, signal: AbortSignal.timeout(15_000) }));
|
|
117
|
+
return routesFromCatalog(await r.json(), { pricing });
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function readBody(req, limit = MAX_BODY) {
|
|
121
|
+
return new Promise((resolve, reject) => {
|
|
122
|
+
const chunks = []; let n = 0;
|
|
123
|
+
req.on("data", (c) => { n += c.length; if (n > limit) { reject(new Error("body too large")); req.destroy(); return; } chunks.push(c); });
|
|
124
|
+
req.on("end", () => resolve(Buffer.concat(chunks)));
|
|
125
|
+
req.on("error", reject);
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// The x402 offer keys a refusal body may carry beside its own fields.
|
|
130
|
+
const OFFER_KEYS = ["x402Version", "resource", "accepts", "extensions"];
|
|
131
|
+
const text = (v) => (typeof v === "string" && v.trim() ? v : null);
|
|
132
|
+
|
|
133
|
+
/** An upstream error body that carries an x402 offer (a numeric x402Version),
|
|
134
|
+
* as an OpenAI-shaped error: the explanation (a problem's detail, else the
|
|
135
|
+
* hint, else the error sentence) as error.message, the retry class or reason as
|
|
136
|
+
* error.code, the refusal's own fields beside it, and no offer. Null for any
|
|
137
|
+
* other body, which the caller relays unchanged. */
|
|
138
|
+
export function refusalAsOpenAIError(status, doc) {
|
|
139
|
+
if (!doc || typeof doc !== "object" || Array.isArray(doc) || typeof doc.x402Version !== "number") return null;
|
|
140
|
+
const ours = { ...doc };
|
|
141
|
+
for (const k of OFFER_KEYS) delete ours[k];
|
|
142
|
+
const { error, ...fields } = ours;
|
|
143
|
+
const message = text(fields.detail) || text(fields.hint) || text(error) || text(fields.title) || `Agent402 answered HTTP ${status}`;
|
|
144
|
+
return {
|
|
145
|
+
error: { message, type: status === 402 ? "payment_required" : "upstream_error", code: text(fields.retry) || text(fields.reason) || null },
|
|
146
|
+
...fields,
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** The same refusal in the Anthropic error shape ({type:"error", error:{type,
|
|
151
|
+
* message}}), which Anthropic clients read their error text from. Null for any
|
|
152
|
+
* other body, which the caller relays unchanged. */
|
|
153
|
+
export function refusalAsAnthropicError(status, doc) {
|
|
154
|
+
const o = refusalAsOpenAIError(status, doc);
|
|
155
|
+
if (!o) return null;
|
|
156
|
+
const { error, ...fields } = o;
|
|
157
|
+
return { type: "error", error: { type: status === 402 ? "payment_required" : "api_error", message: error.message }, ...fields };
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// The gateway's metered Anthropic Messages route: quoted per request from the
|
|
161
|
+
// body, any model id the gateway lists (dated Claude ids resolve to the live one).
|
|
162
|
+
export const MESSAGES_UPSTREAM_PATH = "/v1/metered/messages";
|
|
163
|
+
|
|
164
|
+
// Each client wire's own error shapes: mapRefusal turns an upstream refusal
|
|
165
|
+
// that carries an offer into the wire's error; error(type, message) is an
|
|
166
|
+
// error the proxy makes itself (a refused redirect, an unreachable upstream).
|
|
167
|
+
const OPENAI_WIRE = { mapRefusal: refusalAsOpenAIError, error: (type, message) => ({ error: { message, type } }) };
|
|
168
|
+
const ANTHROPIC_WIRE = { mapRefusal: refusalAsAnthropicError, error: (type, message) => ({ type: "error", error: { type, message } }) };
|
|
169
|
+
|
|
170
|
+
const json = (res, status, obj, headers = {}) => {
|
|
171
|
+
res.writeHead(status, { "content-type": "application/json; charset=utf-8", ...headers });
|
|
172
|
+
res.end(JSON.stringify(obj));
|
|
173
|
+
};
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* @param {object} o
|
|
177
|
+
* @param {string} [o.upstream] gateway origin (default https://agent402.tools)
|
|
178
|
+
* @param {string} [o.creditsKey] prepaid credits key (a402_...)
|
|
179
|
+
* @param {Function} [o.payFetch] x402-paying fetch for wallet payment
|
|
180
|
+
* @param {Function} [o.fetch] plain fetch (tests inject one)
|
|
181
|
+
* @param {number} [o.port] 0 = ephemeral
|
|
182
|
+
* @param {string} [o.host] default 127.0.0.1 (loopback only: anyone who can reach the port spends your key)
|
|
183
|
+
* @param {Map} [o.routes] pre-loaded routes (tests); else loaded from upstream
|
|
184
|
+
* @param {"metered"|"flat"} [o.pricing] metered (default): explicit models pay per-request quotes; flat: home tiers
|
|
185
|
+
* @param {(msg:string)=>void} [o.log]
|
|
186
|
+
*/
|
|
187
|
+
export async function startProxy({ upstream = DEFAULT_UPSTREAM, creditsKey = null, payFetch = null, fetch: fetchImpl = fetch, port = 0, host = "127.0.0.1", routes = null, pricing = "metered", log = () => {} } = {}) {
|
|
188
|
+
upstream = stripTrailingSlashes(upstream);
|
|
189
|
+
pricing = pricing === "flat" ? "flat" : "metered";
|
|
190
|
+
const key = typeof creditsKey === "string" && /^a402_[A-Za-z0-9_-]{16,80}$/.test(creditsKey) ? creditsKey : null;
|
|
191
|
+
const paid = key ? fetchImpl : payFetch;
|
|
192
|
+
const mode = key ? "credits" : payFetch ? "x402" : "unpaid";
|
|
193
|
+
let table = routes || await loadRoutes(upstream, fetchImpl, { pricing });
|
|
194
|
+
const stats = { requests: 0, forwarded: 0, errors: 0, startedAt: new Date().toISOString() };
|
|
195
|
+
|
|
196
|
+
// Pays and forwards one call. Streams pass through byte for byte; a refused
|
|
197
|
+
// paid call's offer-carrying JSON body is answered in the client wire's own
|
|
198
|
+
// error shape (wire.mapRefusal); every other upstream body is relayed as sent.
|
|
199
|
+
async function forward(req, res, endpoint, outbound, extraHeaders, wire) {
|
|
200
|
+
const clientIdem = typeof req.headers["idempotency-key"] === "string" && /^[\w.:-]{8,128}$/.test(req.headers["idempotency-key"]) ? req.headers["idempotency-key"] : null;
|
|
201
|
+
const headers = { "content-type": "application/json", accept: req.headers.accept || "application/json", "idempotency-key": clientIdem || randomUUID(), "user-agent": USER_AGENT, ...extraHeaders };
|
|
202
|
+
if (key) headers.authorization = `Bearer ${key}`;
|
|
203
|
+
// A paid request never follows a redirect: followed, it would pay another
|
|
204
|
+
// origin's 402 or carry a signature (or the credits key) to another host.
|
|
205
|
+
const up = await paid(`${upstream}${endpoint}`, { method: "POST", headers, body: JSON.stringify(outbound), redirect: "manual", signal: AbortSignal.timeout(300_000) });
|
|
206
|
+
if (up.type === "opaqueredirect" || (up.status >= 300 && up.status < 400)) {
|
|
207
|
+
stats.errors++;
|
|
208
|
+
const loc = up.headers.get("location");
|
|
209
|
+
const to = loc ? new URL(loc, `${upstream}${endpoint}`).href : null;
|
|
210
|
+
return json(res, 502, wire.error("upstream_redirect_refused", `refused to follow a redirect on a paid call: ${upstream}${endpoint} answered HTTP ${up.status || "redirect"}${to ? ` pointing to ${to}` : ""}. Paid requests never follow redirects${to ? `; if that is the address you meant, set the upstream to ${new URL(to).origin}` : ""}.`));
|
|
211
|
+
}
|
|
212
|
+
stats.forwarded++;
|
|
213
|
+
const passthrough = {};
|
|
214
|
+
// payment-response / x-payment-response carry the x402 settlement receipt
|
|
215
|
+
// (v2 / v1); payment-receipt is MPP's. The client sees what it paid.
|
|
216
|
+
for (const h of ["content-type", "x-credits-balance", "payment-response", "x-payment-response", "payment-receipt", "x-cache", "cache-control"]) { const v = up.headers.get(h); if (v) passthrough[h] = v; }
|
|
217
|
+
if (!up.ok && /json/i.test(passthrough["content-type"] || "")) {
|
|
218
|
+
const raw = await up.text();
|
|
219
|
+
let doc = null;
|
|
220
|
+
try { doc = JSON.parse(raw); } catch { /* not JSON after all: relayed as sent */ }
|
|
221
|
+
const mapped = wire.mapRefusal(up.status, doc);
|
|
222
|
+
if (mapped) {
|
|
223
|
+
const { "content-type": _ct, ...rest } = passthrough;
|
|
224
|
+
return json(res, up.status, mapped, rest);
|
|
225
|
+
}
|
|
226
|
+
res.writeHead(up.status, passthrough);
|
|
227
|
+
return res.end(raw);
|
|
228
|
+
}
|
|
229
|
+
res.writeHead(up.status, passthrough);
|
|
230
|
+
if (!up.body) return res.end();
|
|
231
|
+
const reader = up.body.getReader();
|
|
232
|
+
req.on("close", () => { reader.cancel().catch(() => {}); });
|
|
233
|
+
for (;;) { const { done, value } = await reader.read(); if (done) break; res.write(Buffer.from(value)); }
|
|
234
|
+
return res.end();
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// forward() is awaited inside the try below, so a payment fetch that throws
|
|
238
|
+
// (an unreachable upstream, a refused signature) answers a 502 in the wire's
|
|
239
|
+
// own shape instead of escaping as an unhandled rejection.
|
|
240
|
+
const server = createServer(async (req, res) => {
|
|
241
|
+
stats.requests++;
|
|
242
|
+
const url = new URL(req.url, "http://localhost");
|
|
243
|
+
try {
|
|
244
|
+
if (req.headers.origin !== undefined) {
|
|
245
|
+
return json(res, 403, { error: { message: "Browser-origin requests are refused: this proxy spends a payment key and answers native clients only.", type: "forbidden" } });
|
|
246
|
+
}
|
|
247
|
+
const hostName = String(req.headers.host || "").replace(/:\d+$/, "").replace(/^\[|\]$/g, "");
|
|
248
|
+
if (hostName && !["127.0.0.1", "localhost", "::1"].includes(hostName)) {
|
|
249
|
+
return json(res, 403, { error: { message: `Host "${hostName.slice(0, 64)}" is not loopback; refused.`, type: "forbidden" } });
|
|
250
|
+
}
|
|
251
|
+
if (req.method === "GET" && url.pathname === "/health") {
|
|
252
|
+
return json(res, 200, { ok: true, upstream, mode, pricing, models: table.size, stats });
|
|
253
|
+
}
|
|
254
|
+
if (req.method === "GET" && url.pathname === "/v1/models") {
|
|
255
|
+
return json(res, 200, { object: "list", data: [...table.values()].filter((r) => !r.stealth).map((r) => ({ id: r.id, object: "model", owned_by: "agent402", agent402: { endpoint: r.endpoint, priceUsd: r.priceUsd, tier: r.tier, metered: !!r.metered } })) });
|
|
256
|
+
}
|
|
257
|
+
if (req.method === "POST" && url.pathname === "/v1/chat/completions") {
|
|
258
|
+
const raw = await readBody(req);
|
|
259
|
+
let body;
|
|
260
|
+
try { body = JSON.parse(raw.toString("utf8") || "{}"); } catch { return json(res, 400, { error: { message: "Request body must be JSON", type: "invalid_request_error" } }); }
|
|
261
|
+
const requested = typeof body.model === "string" && body.model.trim() ? body.model.trim().replace(/^agent402\//, "") : AUTO_ID;
|
|
262
|
+
const route = table.get(requested);
|
|
263
|
+
if (!route) {
|
|
264
|
+
return json(res, 400, { error: { message: `Unknown model "${requested}". Use "auto" or an id from GET /v1/models (${table.size} available).`, type: "invalid_request_error", code: "model_not_found" } });
|
|
265
|
+
}
|
|
266
|
+
if (!paid) {
|
|
267
|
+
return json(res, 402, { error: { message: "No payment method configured. Run `agent402-model-provider setup` to generate an x402 wallet, set AGENT402_WALLET_KEY, or set AGENT402_CREDITS_KEY to a prepaid credits key.", type: "payment_required", code: "agent402_unconfigured" }, topup: `${upstream}/credits`, priceUsd: route.priceUsd });
|
|
268
|
+
}
|
|
269
|
+
const outbound = { ...body };
|
|
270
|
+
if (requested === AUTO_ID) delete outbound.model; else outbound.model = route.id;
|
|
271
|
+
return await forward(req, res, route.endpoint, outbound, {}, OPENAI_WIRE);
|
|
272
|
+
}
|
|
273
|
+
if (req.method === "POST" && url.pathname === "/v1/messages") {
|
|
274
|
+
const raw = await readBody(req);
|
|
275
|
+
let body;
|
|
276
|
+
try { body = JSON.parse(raw.toString("utf8") || "{}"); } catch { return json(res, 400, { type: "error", error: { type: "invalid_request_error", message: "Request body must be JSON" } }); }
|
|
277
|
+
if (typeof body.model !== "string" || !body.model.trim()) {
|
|
278
|
+
return json(res, 400, { type: "error", error: { type: "invalid_request_error", message: "\"model\" is required (any id from GET /v1/models, or a Claude id such as claude-sonnet-5)" } });
|
|
279
|
+
}
|
|
280
|
+
if (!paid) {
|
|
281
|
+
return json(res, 402, { type: "error", error: { type: "payment_required", message: "No payment method configured. Set AGENT402_WALLET_KEY to an EVM key holding USDC on Base (or run `agent402-model-provider setup`), or set AGENT402_CREDITS_KEY to a prepaid credits key." } });
|
|
282
|
+
}
|
|
283
|
+
const outbound = { ...body, model: body.model.trim().replace(/^agent402\//, "") };
|
|
284
|
+
const extra = {};
|
|
285
|
+
for (const h of ["anthropic-version", "anthropic-beta"]) { const v = req.headers[h]; if (typeof v === "string" && v.length <= 512) extra[h] = v; }
|
|
286
|
+
return await forward(req, res, MESSAGES_UPSTREAM_PATH, outbound, extra, ANTHROPIC_WIRE);
|
|
287
|
+
}
|
|
288
|
+
return json(res, 404, { error: { message: `No route for ${req.method} ${url.pathname}`, type: "invalid_request_error" } });
|
|
289
|
+
} catch (e) {
|
|
290
|
+
stats.errors++;
|
|
291
|
+
// A thrown message is the payment fetch's or the network's own text,
|
|
292
|
+
// so the credits key is cut out of it before it is logged or answered.
|
|
293
|
+
const msg = key ? String(e?.message || e).split(key).join("[redacted]") : String(e?.message || e);
|
|
294
|
+
log(`[agent402-model-provider] ${req.method} ${url.pathname}: ${msg}`);
|
|
295
|
+
const wire = url.pathname === "/v1/messages" ? ANTHROPIC_WIRE : OPENAI_WIRE;
|
|
296
|
+
if (!res.headersSent) return json(res, 502, wire.error("upstream_error", `Upstream error: ${msg.slice(0, 200)}`));
|
|
297
|
+
try { res.end(); } catch { /* ignore */ }
|
|
298
|
+
}
|
|
299
|
+
});
|
|
300
|
+
|
|
301
|
+
await new Promise((resolve, reject) => { server.once("error", reject); server.listen(port, host, resolve); });
|
|
302
|
+
const actualPort = server.address().port;
|
|
303
|
+
const baseUrl = `http://${host}:${actualPort}`;
|
|
304
|
+
log(`[agent402-model-provider] proxy on ${baseUrl}/v1 -> ${upstream} (${mode}, ${pricing} pricing, ${table.size} models)`);
|
|
305
|
+
return {
|
|
306
|
+
baseUrl, port: actualPort, mode, upstream, pricing,
|
|
307
|
+
stats: () => ({ ...stats }),
|
|
308
|
+
refreshModels: async () => { table = await loadRoutes(upstream, fetchImpl, { pricing }); return table.size; },
|
|
309
|
+
close: () => new Promise((resolve) => server.close(() => resolve())),
|
|
310
|
+
};
|
|
311
|
+
}
|