@pipeworx/mcp-ai-model-experiments 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/src/index.ts ADDED
@@ -0,0 +1,1140 @@
1
+ interface McpToolDefinition {
2
+ name: string;
3
+ description: string;
4
+ inputSchema: {
5
+ type: 'object';
6
+ properties: Record<string, unknown>;
7
+ required?: string[];
8
+ anyOf?: Array<{ required: string[] }>;
9
+ oneOf?: Array<{ required: string[] }>;
10
+ allOf?: Array<{ required: string[] }>;
11
+ };
12
+ outputSchema?: Record<string, unknown>;
13
+ }
14
+
15
+ interface McpToolExport {
16
+ tools: McpToolDefinition[];
17
+ callTool: (name: string, args: Record<string, unknown>) => Promise<unknown>;
18
+ meter?: { credits: number };
19
+ cost?: Record<string, unknown>;
20
+ provider?: string;
21
+ }
22
+
23
+ /**
24
+ * One place to turn a failed `fetch` into an error a caller can act on.
25
+ *
26
+ * Nearly every pack was written the same way:
27
+ *
28
+ * if (!res.ok) throw new Error(`Unsplash: ${res.status}`);
29
+ *
30
+ * which discards the response body — and the body is usually where the upstream
31
+ * says what was actually wrong ("**symbol** not found: GBP", "parameter `year`
32
+ * out of range", "unknown taxonomy id"). The caller gets a number, cannot
33
+ * self-correct, and retries the same broken call. A 2026-07-31 sweep found this
34
+ * shape in 481 of 1,400 packs, 47 of them PLATFORM-keyed.
35
+ *
36
+ * It also hides bugs one level down. Two of the first three packs audited had a
37
+ * second defect that only existed because of this line: unsplash's rate-limit
38
+ * branch sat BELOW a catch-all and was unreachable, and bea-gov parsed
39
+ * `BEAAPI.Error.APIErrorDescription` below a `!res.ok` throw that made the
40
+ * parsing dead code for every non-200.
41
+ *
42
+ * DELIBERATELY NOT A CLASSIFIER. It does not add `user_error:` /
43
+ * `upstream_down:` prefixes. Those decide which tier a failure lands in, and the
44
+ * `error` tier is what the daily problem-tools list is built from — it means
45
+ * "Pipeworx has a defect". A 400 is genuinely ambiguous: often a caller's bad
46
+ * argument, but sometimes a query WE built wrong (ted-eu comma-joined its CPV
47
+ * values into something TED rejected, and that bug was found only because it sat
48
+ * in `error`). Blanket-classifying 400s as caller mistakes would have hidden it.
49
+ * A pack that KNOWS which it is should keep saying so explicitly; this helper is
50
+ * for the 481 that say nothing at all.
51
+ */
52
+
53
+ /** Longest upstream explanation we'll pass through. Enough for a real message,
54
+ * short enough that an HTML page or a stack trace can't swamp the error. */
55
+
56
+ const MAX_DETAIL = 300;
57
+
58
+ /**
59
+ * Default bound for `fetchWithTimeout` when a pack doesn't state its own.
60
+ *
61
+ * 25s mirrors the number `epo-ops` landed on after measuring the real failure:
62
+ * a degraded upstream that doesn't error, it just never answers, and a Worker
63
+ * sits in `await fetch()` until ITS OWN execution budget kills the request —
64
+ * which can take minutes, not seconds (epo_ops_search_patents measured 4-8
65
+ * MINUTE hangs before this existed). 25s is short enough that a caller gets a
66
+ * fast, actionable error instead of holding the connection, and long enough
67
+ * that it doesn't false-trip on a merely-slow-but-alive upstream.
68
+ */
69
+ const DEFAULT_FETCH_TIMEOUT_MS = 25_000;
70
+
71
+ /**
72
+ * Read the body of a failed response and fold it into a throwable Error.
73
+ *
74
+ * Usage — note the `await`, which is the one thing that makes this a mechanical
75
+ * change rather than a drop-in:
76
+ *
77
+ * if (!res.ok) throw await httpError(res, 'Unsplash');
78
+ *
79
+ * Safe to call on any non-ok response: a body that is missing, empty, unreadable
80
+ * or HTML degrades to exactly the old `Name: 404` string rather than throwing
81
+ * something new from inside the error path.
82
+ */
83
+ async function httpError(res: Response, name: string): Promise<Error> {
84
+ return new Error(await httpErrorMessage(res, name));
85
+ }
86
+
87
+ /** The message text without constructing an Error — for packs that need to wrap
88
+ * it in their own envelope or add an explicit classification prefix. */
89
+ async function httpErrorMessage(res: Response, name: string): Promise<string> {
90
+ // The one place a 5xx from a host WE run gets stamped as ours. `res.url` is
91
+ // the URL the fetch actually resolved to (after redirects), so this is a fact
92
+ // about the call rather than a guess from the `name` the pack passed in —
93
+ // reword that label freely, the class does not move. See
94
+ // internal-host-class.ts; no-op for every third-party upstream, which is why
95
+ // this touches 481 packs' error text and changes none of it.
96
+ return markInternalOrigin(
97
+ `${name}: ${res.status}${detailSuffix(await readDetail(res))}`,
98
+ res.url,
99
+ res.status,
100
+ );
101
+ }
102
+
103
+ /**
104
+ * Just the upstream's own explanation — no name, no status.
105
+ *
106
+ * For a pack that has already said both in its own sentence. epo-ops reads
107
+ * `EPO rejected this search as too large (HTTP 413) — ${httpErrorMessage(…)}`,
108
+ * which rendered as `… (HTTP 413) — EPO: 413.` once the XML detail was being
109
+ * dropped: the upstream named twice, the status twice, and the one thing EPO
110
+ * actually said ("Not enough characters before truncation character") nowhere
111
+ * (fleet #712). Returns '' when the body carries nothing readable, so a caller
112
+ * can fall back to its own wording.
113
+ */
114
+ async function upstreamDetail(res: Response): Promise<string> {
115
+ return readDetail(res);
116
+ }
117
+
118
+ /**
119
+ * Read a SUCCESSFUL response as JSON, failing loudly when it isn't JSON.
120
+ *
121
+ * `httpError` above only ever runs on `!res.ok`, which leaves the nastier half
122
+ * of the problem unhandled: an upstream that answers **HTTP 200 with an HTML
123
+ * page**. A bot wall, a login redirect, a maintenance interstitial and a CDN
124
+ * error page are all 200s, so `res.ok` is true, and `res.json()` then throws
125
+ * `Unexpected token '<', "<!DOCTYPE "... is not valid JSON`.
126
+ *
127
+ * That string is the problem. It names no upstream, carries no status, and
128
+ * reads like a parser bug in Pipeworx — so it lands in the `error` tier, which
129
+ * means "we have a defect", and the caller is told nothing they can act on.
130
+ * data.govt.nz sat dead behind an Imperva challenge this way and every
131
+ * status-code health check we own reported it green (7889a845). A zero-length
132
+ * body has the same shape: `Unexpected end of JSON input`, seen this week on
133
+ * uk-gazette (83% of external calls) and census.
134
+ *
135
+ * UNLIKE `httpError`, this one DOES classify, and the asymmetry is deliberate.
136
+ * A 400 is genuinely ambiguous — often the caller's bad argument, sometimes a
137
+ * query we built wrong — so blanket-classifying it would hide our own bugs.
138
+ * There is no such ambiguity here: **no argument a caller can pass makes a JSON
139
+ * API return an HTML page.** It is always the upstream, so `upstream_down:` is
140
+ * a statement of fact rather than a guess, and it keeps these out of the
141
+ * problem-tools list where they crowd out real defects.
142
+ *
143
+ * const data = await parseJson<Feed>(res, 'UK Gazette');
144
+ *
145
+ * Call it only after the `!res.ok` check — on a failed response you want
146
+ * `httpError`, which mines the body for the upstream's own explanation.
147
+ */
148
+ async function parseJson<T>(res: Response, name: string): Promise<T> {
149
+ let raw: string;
150
+ try {
151
+ raw = await res.text();
152
+ } catch {
153
+ throw new Error(
154
+ `upstream_down: ${name} returned a body that could not be read (HTTP ${res.status}). ` +
155
+ 'The connection most likely dropped mid-response; retrying is reasonable.',
156
+ );
157
+ }
158
+
159
+ const type = res.headers.get('content-type') ?? 'no content-type';
160
+
161
+ if (!raw.trim()) {
162
+ throw new Error(
163
+ `upstream_down: ${name} answered HTTP ${res.status} with an EMPTY body where JSON was expected (${type}). ` +
164
+ 'Nothing about the request can cause this — it is an upstream fault, and the same call may well work on retry.',
165
+ );
166
+ }
167
+
168
+ // Checked before parsing rather than in the catch, because knowing it is
169
+ // markup is what turns "we failed to parse something" into "they served a
170
+ // web page" — the second is diagnosable, the first is not.
171
+ const head = raw.slice(0, 200).trimStart().toLowerCase();
172
+ if (head.startsWith('<!doctype') || head.startsWith('<html') || head.startsWith('<?xml')) {
173
+ const kind = head.startsWith('<?xml') ? 'an XML document' : 'an HTML page';
174
+ // The summary, not the source. Pasting the first 120 characters of a web
175
+ // page handed the agent `<!DOCTYPE html><html lang="en"…` — the same leak
176
+ // this branch exists to describe (fleet #712).
177
+ throw new Error(
178
+ `upstream_down: ${name} answered HTTP ${res.status} with ${kind} instead of JSON (${type}). ` +
179
+ 'That is typically a bot wall, a login redirect or a maintenance page — it is returned as a SUCCESS, ' +
180
+ `so status-code health checks read it as fine. No argument change will get past it. ` +
181
+ `The page says: ${summarizeErrorBody(raw) || 'nothing readable'}`,
182
+ );
183
+ }
184
+
185
+ try {
186
+ return JSON.parse(raw) as T;
187
+ } catch {
188
+ throw new Error(
189
+ `upstream_down: ${name} answered HTTP ${res.status} with a body that is not valid JSON (${type}). ` +
190
+ `It begins: ${stripMarkup(raw).slice(0, 120) || '(unreadable)'}`,
191
+ );
192
+ }
193
+ }
194
+
195
+ /**
196
+ * `fetch`, but bounded — the fix for a systemic gap found 2026-08-30: a grep
197
+ * audit of every pack's `mcps/*\/src/index.ts` found 1,339 of ~1,500 call
198
+ * `fetch()` with NO timeout guard anywhere in the file. Two of those
199
+ * (epo-ops, statcan) were confirmed live-hanging for 4-8 minutes before this
200
+ * existed — every unguarded call carries the same risk, just unconfirmed.
201
+ *
202
+ * Mirrors the `epoFetch` wrapper `mcps/epo-ops/src/index.ts` shipped first:
203
+ * bound the request with `AbortSignal.timeout`, and on a timeout/abort throw
204
+ * an `upstream_down:` error that names the upstream and the bound rather than
205
+ * letting the raw `TimeoutError`/`AbortError` (which names neither) propagate.
206
+ * `upstream_down:` is deliberate, same reasoning as `parseJson` above — no
207
+ * argument a caller passes can make an upstream hang, so it is always the
208
+ * upstream's fault, and marking it that way keeps a slow API off the
209
+ * problem-tools list where it would crowd out our own defects.
210
+ *
211
+ * Usage — a mechanical swap for a bare `fetch(url, init)`:
212
+ *
213
+ * const res = await fetchWithTimeout(url, init, 'Some API');
214
+ *
215
+ * Pass `timeoutMs` as a fourth argument to override the default for a pack
216
+ * with a known-slower upstream; the label should be the same short name you'd
217
+ * pass to `httpError`/`httpErrorMessage` for that call.
218
+ */
219
+ async function fetchWithTimeout(
220
+ url: string | URL,
221
+ init: RequestInit = {},
222
+ name: string,
223
+ timeoutMs: number = DEFAULT_FETCH_TIMEOUT_MS,
224
+ ): Promise<Response> {
225
+ try {
226
+ return await fetch(url, { ...init, signal: AbortSignal.timeout(timeoutMs) });
227
+ } catch (err) {
228
+ if (err instanceof Error && (err.name === 'TimeoutError' || err.name === 'AbortError')) {
229
+ // States the OBSERVATION (no response in N seconds), not a diagnosis.
230
+ // "appears to be degraded" is an inference about the vendor that we have
231
+ // not checked, and it is wrong in a way that misdirects whoever reads it:
232
+ // a timeout from a Worker can equally mean OUR egress is blocked.
233
+ //
234
+ // Measured today (2026-09-01, fleet #1047): every call to
235
+ // mainnet.base.org failed from the x402 facilitator while the identical
236
+ // request from a laptop returned 200. Base was entirely healthy; the
237
+ // public RPC refuses Cloudflare Worker egress. Had this message fired
238
+ // there it would have blamed Base by name, and the next person would have
239
+ // waited for a vendor outage to clear that did not exist.
240
+ // A timeout has no status to test — there is no response at all — so
241
+ // `markInternalOrigin` is called without one: an origin we run that never
242
+ // answered is an availability failure by definition. This is the half of
243
+ // fleet #1096 with neither a SQLSTATE nor a status code to key on.
244
+ throw new Error(
245
+ markInternalOrigin(
246
+ `upstream_down: ${name} did not respond within ${timeoutMs / 1000}s. ` +
247
+ `That can be ${name} being slow or down, or this environment being unable to reach it ` +
248
+ `(some hosts refuse datacenter/Worker egress) — retry shortly, and check reachability ` +
249
+ `from elsewhere before concluding ${name} is down.`,
250
+ url,
251
+ ),
252
+ );
253
+ }
254
+ throw err;
255
+ }
256
+ }
257
+
258
+ function detailSuffix(detail: string): string {
259
+ return detail ? ` — ${detail}` : '';
260
+ }
261
+
262
+ async function readDetail(res: Response): Promise<string> {
263
+ let raw: string;
264
+ try {
265
+ raw = await res.text();
266
+ } catch {
267
+ // Body already consumed, or the connection died mid-read. The status alone
268
+ // is still worth throwing — never let the error path throw its own error.
269
+ return '';
270
+ }
271
+ return summarizeErrorBody(raw);
272
+ }
273
+
274
+ /**
275
+ * Turn ANY error body — JSON, HTML, XML or plain text — into one short phrase
276
+ * that never contains markup.
277
+ *
278
+ * This used to just drop an HTML or XML body on the floor, on the reasoning
279
+ * that markup crowds out the status. That was half right. Dropping it loses the
280
+ * one sentence a caller could have acted on: an `Access Denied` title, an SDMX
281
+ * `<message:Error>` text, an OPS fault string. A 2026-08-30 support sweep
282
+ * measured 13 of 291 caller-facing error rows carrying a raw page or document
283
+ * verbatim, across 11 packs, and in every one of them the useful content —
284
+ * "Access Denied", "Invalid country code", "SCRAPE_TIMEOUT" — was in there,
285
+ * buried in markup the agent had to parse out of a string (fleet #712).
286
+ *
287
+ * So: extract the meaning, discard the markup. The output is passed through
288
+ * `stripMarkup` unconditionally, which is what lets `check:error-body-leak`
289
+ * assert mechanically that no caller-facing message can contain `<?xml`,
290
+ * `<!DOCTYPE` or `<html`.
291
+ */
292
+ function summarizeErrorBody(raw: string): string {
293
+ if (!raw || !raw.trim()) return '';
294
+
295
+ const head = raw.slice(0, 400).trimStart().toLowerCase();
296
+
297
+ // An HTML error page (Cloudflare interstitial, nginx default, a login
298
+ // redirect) says what it is in its <title>, and almost nowhere else.
299
+ if (head.startsWith('<!doctype') || head.startsWith('<html')) {
300
+ const title = htmlTitle(raw);
301
+ return title
302
+ ? `${title} (upstream returned an HTML error page, not an API response)`
303
+ : 'upstream returned an HTML error page, not an API response';
304
+ }
305
+
306
+ // XML fault documents — EPO OPS, SDMX (`<message:Error>`), SOAP faults. The
307
+ // human sentence sits in a child element whose tag name says what it is.
308
+ if (head.startsWith('<?xml') || head.startsWith('<')) {
309
+ const fault = xmlFaultText(raw);
310
+ return fault
311
+ ? `${stripMarkup(fault).slice(0, MAX_DETAIL)} (from the upstream's XML error document)`
312
+ : 'upstream returned an XML error document with no readable message';
313
+ }
314
+
315
+ // Most JSON error bodies bury one human sentence among ids and echoed request
316
+ // params. Prefer that sentence; fall back to the whole body when the shape is
317
+ // unfamiliar, since an unfamiliar shape is exactly when we can least afford to
318
+ // guess wrong and show nothing.
319
+ const fromJson = messageFromJson(raw);
320
+ return stripMarkup(fromJson ?? raw).slice(0, MAX_DETAIL);
321
+ }
322
+
323
+ /** The `<title>` of an HTML error page, or its first `<h1>` — the two places a
324
+ * bot wall, a 502 and an "Access Denied" all state what happened. */
325
+ function htmlTitle(raw: string): string | null {
326
+ const head = raw.slice(0, 4000);
327
+ for (const re of [/<title[^>]*>([\s\S]*?)<\/title>/i, /<h1[^>]*>([\s\S]*?)<\/h1>/i]) {
328
+ const m = re.exec(head);
329
+ const text = m ? stripMarkup(m[1]) : '';
330
+ if (text) return text.slice(0, 160);
331
+ }
332
+ return null;
333
+ }
334
+
335
+ /** Tag names that carry the explanation in an XML fault document, namespace
336
+ * prefix optional (`<message:Error>`, `<com:Text>`, `<faultstring>`). */
337
+ const XML_FAULT_TAG_RE =
338
+ /<(?:[A-Za-z0-9_.-]+:)?(?:text|message|description|faultstring|reason|detail|title|errormessage|error)\b[^>]*>([^<]{2,400})</i;
339
+
340
+ function xmlFaultText(raw: string): string | null {
341
+ const head = raw.slice(0, 8000);
342
+ const tagged = XML_FAULT_TAG_RE.exec(head);
343
+ if (tagged && tagged[1].trim()) return tagged[1];
344
+
345
+ // Nothing conventionally named — take the longest text node instead. A fault
346
+ // document with one sentence in an oddly named element is still readable;
347
+ // returning nothing at all is not.
348
+ let best = '';
349
+ for (const m of head.matchAll(/>([^<>]{8,400})</g)) {
350
+ const text = m[1].trim();
351
+ if (text.length > best.length) best = text;
352
+ }
353
+ return best || null;
354
+ }
355
+
356
+ /**
357
+ * Remove every tag and stray angle bracket, then collapse whitespace.
358
+ *
359
+ * Applied to everything on the way out, including the JSON and plain-text
360
+ * paths, because an upstream is free to embed markup in a JSON string field —
361
+ * and a leak is a leak regardless of which branch produced it.
362
+ */
363
+ function stripMarkup(s: string): string {
364
+ return collapse(decodeEntities(s.replace(/<[^>]*>/g, ' ')).replace(/[<>]/g, ' '));
365
+ }
366
+
367
+ /** The handful of entities that show up in error-page titles. Decoded AFTER
368
+ * tags are stripped and BEFORE the angle-bracket sweep, so `&lt;script&gt;`
369
+ * in a title cannot decode into markup that survives — EMBL-EBI's ChEMBL 500
370
+ * page renders as `500 Internal Server Error &lt; EMBL-EBI` otherwise. */
371
+ function decodeEntities(s: string): string {
372
+ return s
373
+ .replace(/&(?:amp|#0*38);/gi, '&')
374
+ .replace(/&(?:lt|#0*60);/gi, '<')
375
+ .replace(/&(?:gt|#0*62);/gi, '>')
376
+ .replace(/&(?:quot|#0*34);/gi, '"')
377
+ .replace(/&(?:#0*39|apos|#x0*27);/gi, "'")
378
+ .replace(/&nbsp;/gi, ' ');
379
+ }
380
+
381
+ /** The conventional "what went wrong" field, under any of the names upstreams
382
+ * actually use. Checked in order; first non-empty string wins. */
383
+ const MESSAGE_KEYS = [
384
+ 'message', 'error_message', 'errorMessage', 'detail', 'details',
385
+ 'description', 'error_description', 'reason', 'title', 'fault',
386
+ ];
387
+
388
+ function messageFromJson(raw: string): string | null {
389
+ let parsed: unknown;
390
+ try {
391
+ parsed = JSON.parse(raw);
392
+ } catch {
393
+ return null;
394
+ }
395
+ return pickMessage(parsed, 0);
396
+ }
397
+
398
+ function pickMessage(node: unknown, depth: number): string | null {
399
+ // Two levels covers `{error: {message}}` and `{errors: [{detail}]}`, the two
400
+ // shapes that account for nearly all of them, without walking a large payload.
401
+ if (depth > 2 || node == null) return null;
402
+
403
+ if (typeof node === 'string') return node.trim() || null;
404
+
405
+ if (Array.isArray(node)) {
406
+ for (const item of node) {
407
+ const found = pickMessage(item, depth + 1);
408
+ if (found) return found;
409
+ }
410
+ return null;
411
+ }
412
+
413
+ if (typeof node !== 'object') return null;
414
+ const obj = node as Record<string, unknown>;
415
+
416
+ for (const key of MESSAGE_KEYS) {
417
+ const v = obj[key];
418
+ if (typeof v === 'string' && v.trim()) return v.trim();
419
+ }
420
+ // `{error: …}` where error is itself an object or a string — the single most
421
+ // common wrapper, so it is worth descending into by name rather than scanning
422
+ // every key and risking picking up an echoed request parameter.
423
+ for (const key of ['error', 'errors', 'fault', 'Error', 'data']) {
424
+ if (key in obj) {
425
+ const found = pickMessage(obj[key], depth + 1);
426
+ if (found) return found;
427
+ }
428
+ }
429
+ return null;
430
+ }
431
+
432
+ /** Errors are read in a single line of log output; newlines and runs of
433
+ * whitespace make a multi-line body unreadable there. */
434
+ function collapse(s: string): string {
435
+ return s.replace(/\s+/g, ' ').trim();
436
+ }
437
+
438
+ /**
439
+ * Was this failure OUR OWN web service? — the other half of `internal-db-class.ts`.
440
+ *
441
+ * fleet #1089 pulled failures from our own Postgres out of `upstream_down` by
442
+ * keying on the SQLSTATE inside PostgREST's four-key error envelope. That
443
+ * covered the majority and structurally could not cover the rest: the rest
444
+ * never reach Postgres, so they carry no SQLSTATE. What was left, measured over
445
+ * the 24h to 2026-09-02T15:00Z (fleet #1096):
446
+ *
447
+ * 5 pipeworx-catalog get_pack_tools Pipeworx catalog error: 522 — error code: 522
448
+ * 3 fleet fleet_list_open … upstream_down: Fleet task queue did not respond within 25s
449
+ *
450
+ * 521/522/523/526 are Cloudflare saying its edge could not reach an ORIGIN, and
451
+ * in both of those rows the origin is ours — `gateway.pipeworx.io` for the
452
+ * catalog pack (it self-fetches when the gateway hasn't injected a manifest),
453
+ * our own Supabase for fleet. There is no third party anywhere in either call.
454
+ * Same defect as #1089: our own outage filed under `upstream_down`, the one
455
+ * class that means "the source is unreachable and there is nothing for us to
456
+ * fix", which is why the problem-tools triage skips it.
457
+ *
458
+ * WHY NOT A WORDING RULE. The obvious fix is to match `fleet db error:` and
459
+ * `Pipeworx catalog error:` in classifyToolError. Each is emitted from exactly
460
+ * one site today, so it would work today. It would also rot the first time
461
+ * somebody rewords a label — silently, and in the direction of hiding our own
462
+ * outage, which is worse than the bug being fixed. Every prose rule in
463
+ * error-class.ts has needed widening as packs invented new wording (#409/#450/
464
+ * #584); that history is most of that file's comment budget.
465
+ *
466
+ * WHAT THIS KEYS ON INSTEAD: **the host the call actually reached.** A URL's
467
+ * hostname is a fact about the call, not a guess about its prose. Two
468
+ * consequences that a pack-level flag could not give us, and the reason the
469
+ * flag was rejected:
470
+ *
471
+ * - It describes the CALL, not the pack. `govcon-intel` fans out to our own
472
+ * Supabase AND to genuine third parties; `court-listener` holds our cache
473
+ * in Supabase and fetches courtlistener.com. An `internallyHosted: true` on
474
+ * either pack would relabel a real third-party outage as ours — inventing
475
+ * work, which is the same class of error in the opposite direction.
476
+ * - It covers every future internal pack for free, instead of one declared
477
+ * slug at a time.
478
+ *
479
+ * WHY IT SURVIVES A REWORD. The marker below is not matched as a literal by two
480
+ * separate files. `markInternalOrigin()` writes it and `internalHostMetricsClass()`
481
+ * reads it, both from the single exported `INTERNAL_ORIGIN_MARKER` constant in
482
+ * this module — so changing the wording changes both sides in the same edit and
483
+ * cannot desynchronise them. The pack's own label (`fleet db error:`,
484
+ * `Pipeworx catalog error:`) is not read at all: reword it freely, the class is
485
+ * unaffected. That is the property `stripClassPrefix` lacked when it drifted
486
+ * from its own classifier three times and needed a CI gate to hold them
487
+ * together.
488
+ *
489
+ * WHERE THE 5xx TEST LIVES. `markInternalOrigin` is called from the places that
490
+ * hold the real `Response` — `httpError`/`httpErrorMessage` and the timeout
491
+ * branch of `fetchWithTimeout` in `shared/src/http.ts` — so "is this an
492
+ * availability failure" is decided from the actual status code, never re-derived
493
+ * by scraping a number out of a sentence. A 404 from our own registry for a slug
494
+ * that does not exist is a caller's bad argument and is deliberately NOT marked.
495
+ */
496
+
497
+ /**
498
+ * OUR OWN web service was unreachable — not an upstream, and never `upstream_down`.
499
+ *
500
+ * ONE value, not three, unlike `internal_db_*`. That split existed because a
501
+ * slow query, an exhausted pool and an unknown SQLSTATE have different owners
502
+ * and different fixes. Here there is only one story to tell — an origin we run
503
+ * did not answer the edge — and one owner. A bucket with no distinct owner per
504
+ * value is decoration; #724 is what happens when a class holds several
505
+ * situations, and inventing sub-values ahead of a reason to act on them
506
+ * differently is the same mistake with the sign flipped.
507
+ *
508
+ * METRICS ONLY, exactly like PLATFORM_KEY_ERROR_CLASS and the internal_db
509
+ * values. `classifyToolError` still answers `upstream_down` for the retry and
510
+ * hint paths, which only care whether retrying or a sibling tool might work —
511
+ * and it might. Nothing a caller sees or is charged changes here.
512
+ *
513
+ * READ SIDE: this value is in BROKEN_TOOL_CLASSES, FAULT_CLASSES and
514
+ * ALL_ERROR_CLASSES in `workers/registry-api/src/index.ts`. All three, or it
515
+ * lands on no dashboard — fleet #721 is the warning, where the #719 split
516
+ * worked on the write side and was invisible for weeks.
517
+ */
518
+ const INTERNAL_SERVICE_UNREACHABLE_CLASS = 'internal_service_unreachable';
519
+
520
+ /**
521
+ * The token that carries "this origin is ours" from the call site to the
522
+ * classifier.
523
+ *
524
+ * Appended to the error message rather than attached to the Error object,
525
+ * because the object does not survive the trip: 275 packs return `{ error:
526
+ * string }` instead of throwing, the gateway reads `observedError` as a string,
527
+ * and the fleet pack rebuilds its error from a captured status + body across a
528
+ * retry loop. A property on an Error would be dropped by every one of those
529
+ * paths and the class would work in tests and vanish in production.
530
+ *
531
+ * Written as a sentence rather than a sigil because it is going to be read by
532
+ * whoever gets the error, and "our own service, not a third party" is the
533
+ * single most useful thing to tell them — fetchWithTimeout's own comment
534
+ * (fleet #1047) is about exactly this ambiguity, where blaming a healthy vendor
535
+ * by name sent the next person waiting for an outage that did not exist.
536
+ */
537
+ const INTERNAL_ORIGIN_MARKER = ' [pipeworx-hosted origin — our own service, not a third party]';
538
+
539
+ /**
540
+ * Supabase's data plane for a project is `<ref>.supabase.co`, where the ref is
541
+ * exactly twenty lowercase letters (ours is `pqauisounztsgdgfkhke`).
542
+ *
543
+ * Matching the shape rather than listing the ref keeps this correct when we add
544
+ * a project — `supabaseEnv` on a pack entry already points some packs at a
545
+ * second one — while still excluding `status.supabase.co`, which is Supabase's
546
+ * own status page and emphatically not our database. Verified 2026-09-02 by
547
+ * `grep -rhoE '[a-z0-9-]+\.supabase\.(co|in)' mcps shared workers scripts`: the
548
+ * only real project ref anywhere in the tree is ours, the rest are doc
549
+ * placeholders (`abc`, `xyz`, `example`) which this pattern also excludes. Same
550
+ * finding internal-db-class.ts relies on for the PostgREST envelope being ours
551
+ * by construction.
552
+ */
553
+ const SUPABASE_PROJECT_HOST = /^[a-z]{20}\.supabase\.(co|in)$/;
554
+
555
+ /**
556
+ * Is this a host WE run?
557
+ *
558
+ * Deliberately NOT including `*.workers.dev`: plenty of third-party APIs are
559
+ * hosted on workers.dev, so the suffix says where something runs and not who
560
+ * owns it. Every internal call we actually make goes to a `pipeworx.io`
561
+ * hostname or to our Supabase project, both of which are ownership facts.
562
+ *
563
+ * Returns false on anything unparseable rather than throwing — this runs inside
564
+ * an error path, and an error path that can itself throw turns a diagnosable
565
+ * failure into a mystery.
566
+ */
567
+ function isPipeworxOrigin(url: string | URL | undefined | null): boolean {
568
+ if (!url) return false;
569
+ let host: string;
570
+ try {
571
+ host = new URL(url instanceof URL ? url.href : url).hostname.toLowerCase();
572
+ } catch {
573
+ return false;
574
+ }
575
+ if (host === 'pipeworx.io' || host.endsWith('.pipeworx.io')) return true;
576
+ return SUPABASE_PROJECT_HOST.test(host);
577
+ }
578
+
579
+ /**
580
+ * Append the marker when this failure was OUR origin failing to answer.
581
+ *
582
+ * `status` is the HTTP status when there is one, and omitted for a timeout —
583
+ * where there is no response at all, and "the origin did not answer" is the
584
+ * whole observation. Statuses below 500 are left alone: a 404 from our own
585
+ * registry for a slug that does not exist is the caller's argument, not our
586
+ * outage, and marking it would put ordinary 404s on the incident dashboard.
587
+ *
588
+ * Idempotent, so a message that is wrapped and re-marked on the way up (the
589
+ * fleet pack's retry loop re-throws through two layers) carries the marker once.
590
+ */
591
+ function markInternalOrigin(
592
+ message: string,
593
+ url: string | URL | undefined | null,
594
+ status?: number,
595
+ ): string {
596
+ if (status !== undefined && status < 500) return message;
597
+ if (!isPipeworxOrigin(url)) return message;
598
+ if (message.includes(INTERNAL_ORIGIN_MARKER)) return message;
599
+ return message + INTERNAL_ORIGIN_MARKER;
600
+ }
601
+
602
+ /**
603
+ * Which blob4 value a failure from our own web services books as, or undefined
604
+ * if this is not one.
605
+ *
606
+ * Ordered AFTER `internalDbMetricsClass` at the call site: a PostgREST envelope
607
+ * from our own Supabase is a strictly more specific statement about the same
608
+ * row (which of our services, and why), and the two cannot disagree about
609
+ * whether the failure is ours.
610
+ */
611
+ function internalHostMetricsClass(error: string): string | undefined {
612
+ return error.includes(INTERNAL_ORIGIN_MARKER) ? INTERNAL_SERVICE_UNREACHABLE_CLASS : undefined;
613
+ }
614
+
615
+
616
+ /**
617
+ * AI Model Experiments MCP ("Model Lab") — run the same prompts across many
618
+ * AI models simultaneously and compare outputs, latency, and cost.
619
+ *
620
+ * PREPAID ONLY: every run costs real provider money (OpenRouter inference,
621
+ * billed at 1.5× provider cost from the caller's Pipeworx credit balance).
622
+ * Callers top up via x402 USDC (POST /credits/topup on the gateway) — see
623
+ * experiment_topup for exact instructions.
624
+ *
625
+ * Async by design: experiment_create returns immediately with an id; the
626
+ * experiment-runner worker executes cells within ~1 minute (cron). Agents
627
+ * poll experiment_status, then read experiment_results. An optional
628
+ * Fable-written summary compares the models' outputs when the run completes.
629
+ *
630
+ * State lives in Supabase (lab_experiments / lab_cells, migration 053);
631
+ * the gateway injects _supabaseUrl/_supabaseKey (injectSupabase) plus
632
+ * _accountId/_creditBalance/_internal for the prepaid gate.
633
+ */
634
+
635
+
636
+ // Bound every fetch() in this pack to a fixed timeout — an upstream that
637
+ // degrades without erroring would otherwise hold the Worker in `await fetch()`
638
+ // until its own execution budget kills the request (minutes, not seconds).
639
+ // Mirrors the epoFetch / usaspending retryFetch pattern (fleet #685).
640
+ async function pwFetch(url: string | URL, init?: RequestInit): Promise<Response> {
641
+ return fetchWithTimeout(url, init ?? {}, 'AI Model Experiments');
642
+ }
643
+
644
+ const OPENROUTER_MODELS_URL = 'https://openrouter.ai/api/v1/models';
645
+ const MARKUP = 1.5;
646
+ const FLOOR_USD = 0.1; // minimum charge per experiment
647
+ const CAPS = { prompts: 20, models: 12, reps: 5, cells: 240, maxSpendUsd: 100 };
648
+ const CREDIT_USD = 0.0001; // 1 credit = $0.0001 (shared/src/overage.ts)
649
+
650
+ const tools: McpToolExport['tools'] = [
651
+ {
652
+ name: 'experiment_models',
653
+ description:
654
+ 'List AI models available for experiments (about 300 across Anthropic, OpenAI, Google, Meta, Mistral, DeepSeek, Qwen and more), with context window and OUR per-token prices (provider cost × 1.5 — what experiments actually bill). Filter by name/vendor search, minimum context, or max price. Use the returned model ids in experiment_create. Example: experiment_models({ search: "claude", min_context: 100000 })',
655
+ inputSchema: {
656
+ type: 'object' as const,
657
+ properties: {
658
+ search: { type: 'string', description: 'Substring match on model id or name, e.g. "claude", "gpt", "llama"' },
659
+ min_context: { type: 'number', description: 'Minimum context window in tokens' },
660
+ max_price_per_mtok: { type: 'number', description: 'Max billed OUTPUT price in USD per million tokens' },
661
+ limit: { type: 'number', description: 'Max models to return (default 30)' },
662
+ },
663
+ required: [],
664
+ },
665
+ },
666
+ {
667
+ name: 'experiment_estimate',
668
+ description:
669
+ 'Dry-run cost estimate for an experiment BEFORE creating it — cell count and estimated billed cost range (at our 1.5× pricing) for prompts × models × reps. Free to call, no side effects, does not need credit balance. Same spec shape as experiment_create. Example: experiment_estimate({ prompts: ["Summarize: ..."], models: ["anthropic/claude-sonnet-4.5", "openai/gpt-5"], reps: 2 })',
670
+ inputSchema: {
671
+ type: 'object' as const,
672
+ properties: {
673
+ prompts: { type: 'array', items: { type: 'string' }, description: 'Prompts to test (max 20)' },
674
+ models: { type: 'array', items: { type: 'string' }, description: 'Model ids from experiment_models (max 12)' },
675
+ reps: { type: 'number', description: 'Repetitions per prompt×model, 1-5 (default 1)' },
676
+ params: { type: 'object', description: 'Optional {system, temperature, max_tokens}' },
677
+ summary: { type: 'boolean', description: 'Include the AI-written comparison summary stage (default true)' },
678
+ },
679
+ required: ['prompts', 'models'],
680
+ },
681
+ },
682
+ {
683
+ name: 'experiment_create',
684
+ description:
685
+ 'Model Lab: run one prompt across many AI models at once and compare their outputs, cost, and latency side by side. Create and start an experiment: run each prompt against each model (× reps), collecting output, tokens, latency, and billed cost per cell. PREPAID: requires Pipeworx credit balance ≥ max_spend_usd (top up via experiment_topup); bills actual provider cost × 1.5 with a $0.10 minimum per experiment. ASYNC: returns experiment_id immediately — execution starts within ~1 minute; poll experiment_status until complete, then call experiment_results. Do NOT wait synchronously. Set summary:false to skip the AI-written model-comparison summary. Example: experiment_create({ name: "tone test", prompts: ["Rewrite formally: ..."], models: ["anthropic/claude-haiku-4.5", "openai/gpt-5-mini"], reps: 2, max_spend_usd: 2 })',
686
+ inputSchema: {
687
+ type: 'object' as const,
688
+ properties: {
689
+ name: { type: 'string', description: 'Short experiment name' },
690
+ prompts: { type: 'array', items: { type: 'string' }, description: 'Prompts to test (max 20)' },
691
+ models: { type: 'array', items: { type: 'string' }, description: 'Model ids from experiment_models (max 12)' },
692
+ reps: { type: 'number', description: 'Repetitions per prompt×model for variance, 1-5 (default 1)' },
693
+ params: { type: 'object', description: 'Optional {system, temperature, max_tokens (default 512)}' },
694
+ summary: { type: 'boolean', description: 'AI-written comparison of the models\' outputs when the run completes (default true)' },
695
+ max_spend_usd: { type: 'number', description: 'REQUIRED hard spend cap in USD for this experiment (max 100). Execution stops when reached.' },
696
+ },
697
+ required: ['prompts', 'models', 'max_spend_usd'],
698
+ },
699
+ },
700
+ {
701
+ name: 'experiment_status',
702
+ description:
703
+ 'Progress of an experiment: cell counts by state (pending/running/ok/error/skipped), spend so far vs cap, and whether it is complete. Poll this after experiment_create (every few seconds). Example: experiment_status({ experiment_id: "..." })',
704
+ inputSchema: {
705
+ type: 'object' as const,
706
+ properties: { experiment_id: { type: 'string', description: 'From experiment_create' } },
707
+ required: ['experiment_id'],
708
+ },
709
+ },
710
+ {
711
+ name: 'experiment_results',
712
+ description:
713
+ 'Results of an experiment: per-model aggregates (mean latency, tokens, total billed cost, error rate), per-cell outputs, and the AI-written summary comparing how the models differed (if enabled). Use include_outputs:false for aggregates only. Example: experiment_results({ experiment_id: "..." })',
714
+ inputSchema: {
715
+ type: 'object' as const,
716
+ properties: {
717
+ experiment_id: { type: 'string', description: 'From experiment_create' },
718
+ include_outputs: { type: 'boolean', description: 'Include full model outputs per cell (default true)' },
719
+ },
720
+ required: ['experiment_id'],
721
+ },
722
+ },
723
+ {
724
+ name: 'experiment_list',
725
+ description: 'List your experiments, newest first, with status and spend. Example: experiment_list({ limit: 10 })',
726
+ inputSchema: {
727
+ type: 'object' as const,
728
+ properties: { limit: { type: 'number', description: 'Max experiments (default 20)' } },
729
+ required: [],
730
+ },
731
+ },
732
+ {
733
+ name: 'experiment_cancel',
734
+ description:
735
+ 'Cancel a running experiment: pending cells are skipped (not billed); in-flight cells finish and bill. Example: experiment_cancel({ experiment_id: "..." })',
736
+ inputSchema: {
737
+ type: 'object' as const,
738
+ properties: { experiment_id: { type: 'string', description: 'From experiment_create' } },
739
+ required: ['experiment_id'],
740
+ },
741
+ },
742
+ {
743
+ name: 'experiment_topup',
744
+ description:
745
+ 'How to add prepaid credits for experiments (and your current balance). Payment is x402 — USDC on Base, paid in-band by any wallet-equipped agent: POST https://gateway.pipeworx.io/credits/topup?amount_usd=10 responds HTTP 402 with payment requirements; retry with PAYMENT-SIGNATURE to settle and the credits land instantly. Example: experiment_topup({})',
746
+ inputSchema: {
747
+ type: 'object' as const,
748
+ properties: { amount_usd: { type: 'number', description: 'Intended top-up amount in USD (1-500) — echoed into the instructions' } },
749
+ required: [],
750
+ },
751
+ },
752
+ ];
753
+
754
+ // ---------------------------------------------------------------------------
755
+
756
+ interface Ctx {
757
+ url: string;
758
+ key: string;
759
+ accountId: string;
760
+ balanceCredits: number; // -1 = unknown (Redis fail-open)
761
+ internal: boolean;
762
+ }
763
+
764
+ async function pg(ctx: Ctx, path: string, init?: RequestInit & { prefer?: string }): Promise<Response> {
765
+ const res = await pwFetch(`${ctx.url}/rest/v1/${path}`, {
766
+ ...init,
767
+ headers: {
768
+ apikey: ctx.key,
769
+ Authorization: `Bearer ${ctx.key}`,
770
+ 'Content-Type': 'application/json',
771
+ ...(init?.prefer ? { Prefer: init.prefer } : {}),
772
+ ...(init?.headers ?? {}),
773
+ },
774
+ });
775
+ if (!res.ok) {
776
+ const body = await res.text().catch(() => '');
777
+ throw new Error(`Model Lab storage error (HTTP ${res.status}): ${body.slice(0, 200)}`);
778
+ }
779
+ return res;
780
+ }
781
+
782
+ // ---------------------------------------------------------------------------
783
+ // Model catalog (OpenRouter public /models, keyless) with 1.5× pricing.
784
+
785
+ interface ORModel {
786
+ id: string;
787
+ name?: string;
788
+ context_length?: number;
789
+ pricing?: { prompt?: string; completion?: string; request?: string };
790
+ }
791
+
792
+ let MODEL_CACHE: { at: number; models: ORModel[] } | null = null;
793
+
794
+ async function fetchModels(): Promise<ORModel[]> {
795
+ if (MODEL_CACHE && Date.now() - MODEL_CACHE.at < 3_600_000) return MODEL_CACHE.models;
796
+ const res = await pwFetch(OPENROUTER_MODELS_URL, { headers: { Accept: 'application/json' } });
797
+ if (!res.ok) throw new Error(`Model catalog unavailable (OpenRouter HTTP ${res.status}) — retry shortly.`);
798
+ const data = (await res.json()) as { data?: ORModel[] };
799
+ MODEL_CACHE = { at: Date.now(), models: data.data ?? [] };
800
+ return MODEL_CACHE.models;
801
+ }
802
+
803
+ function billedPerMtok(perTok: string | undefined): number {
804
+ return Math.round((Number(perTok ?? 0) || 0) * 1_000_000 * MARKUP * 100) / 100;
805
+ }
806
+
807
+ async function listModels(args: Record<string, unknown>) {
808
+ const models = await fetchModels();
809
+ const q = String(args.search ?? '').toLowerCase();
810
+ const minCtx = Number(args.min_context) || 0;
811
+ const maxPrice = args.max_price_per_mtok != null ? Number(args.max_price_per_mtok) : Infinity;
812
+ const limit = Math.min(Math.max(Number(args.limit) || 30, 1), 100);
813
+ const out = models
814
+ .filter(
815
+ (m) =>
816
+ (!q || m.id.toLowerCase().includes(q) || (m.name ?? '').toLowerCase().includes(q)) &&
817
+ (m.context_length ?? 0) >= minCtx &&
818
+ billedPerMtok(m.pricing?.completion) <= maxPrice,
819
+ )
820
+ .slice(0, limit)
821
+ .map((m) => ({
822
+ id: m.id,
823
+ name: m.name,
824
+ context: m.context_length,
825
+ billed_input_per_mtok_usd: billedPerMtok(m.pricing?.prompt),
826
+ billed_output_per_mtok_usd: billedPerMtok(m.pricing?.completion),
827
+ }));
828
+ return {
829
+ count: out.length,
830
+ pricing_note: 'Prices are what experiments bill: provider cost × 1.5, USD per million tokens. $0.10 minimum per experiment.',
831
+ models: out,
832
+ };
833
+ }
834
+
835
+ // ---------------------------------------------------------------------------
836
+ // Spec validation + estimation (shared by estimate and create).
837
+
838
+ interface Spec {
839
+ prompts: string[];
840
+ models: string[];
841
+ reps: number;
842
+ params: { system?: string; temperature?: number; max_tokens?: number };
843
+ summary: boolean;
844
+ }
845
+
846
+ function parseSpec(args: Record<string, unknown>): Spec {
847
+ const prompts = (Array.isArray(args.prompts) ? args.prompts : []).map(String).filter((p) => p.trim());
848
+ const models = (Array.isArray(args.models) ? args.models : []).map(String).filter(Boolean);
849
+ const reps = Math.min(Math.max(Math.round(Number(args.reps) || 1), 1), CAPS.reps);
850
+ if (prompts.length === 0) throw new Error('At least one non-empty prompt is required.');
851
+ if (models.length === 0) throw new Error('At least one model id is required — pick from experiment_models.');
852
+ if (prompts.length > CAPS.prompts) throw new Error(`Too many prompts (${prompts.length} > ${CAPS.prompts}).`);
853
+ if (models.length > CAPS.models) throw new Error(`Too many models (${models.length} > ${CAPS.models}).`);
854
+ const cells = prompts.length * models.length * reps;
855
+ if (cells > CAPS.cells) {
856
+ throw new Error(`${cells} cells exceeds the ${CAPS.cells}-cell cap — reduce prompts, models, or reps.`);
857
+ }
858
+ const p = (args.params ?? {}) as Record<string, unknown>;
859
+ return {
860
+ prompts,
861
+ models,
862
+ reps,
863
+ params: {
864
+ system: p.system != null ? String(p.system) : undefined,
865
+ temperature: p.temperature != null ? Number(p.temperature) : undefined,
866
+ max_tokens: Math.min(Math.max(Number(p.max_tokens) || 512, 16), 8192),
867
+ },
868
+ summary: args.summary !== false,
869
+ };
870
+ }
871
+
872
+ async function estimateSpec(spec: Spec) {
873
+ const models = await fetchModels();
874
+ const byId = new Map(models.map((m) => [m.id, m]));
875
+ const unknown = spec.models.filter((id) => !byId.has(id));
876
+ if (unknown.length > 0) {
877
+ throw new Error(`Unknown model id(s): ${unknown.join(', ')}. Use ids exactly as returned by experiment_models.`);
878
+ }
879
+ const cells = spec.prompts.length * spec.models.length * spec.reps;
880
+ const estInTok = spec.prompts.reduce((s, p) => s + Math.ceil((p.length + (spec.params.system?.length ?? 0)) / 4), 0) / spec.prompts.length;
881
+ let estUsd = 0;
882
+ for (const id of spec.models) {
883
+ const m = byId.get(id)!;
884
+ const inCost = (Number(m.pricing?.prompt ?? 0) || 0) * estInTok;
885
+ const outCost = (Number(m.pricing?.completion ?? 0) || 0) * (spec.params.max_tokens ?? 512);
886
+ estUsd += (inCost + outCost) * spec.prompts.length * spec.reps;
887
+ }
888
+ estUsd *= MARKUP;
889
+ // 4-decimal precision: cheap-model runs cost fractions of a cent and a
890
+ // rounded "$0" estimate reads as free when it isn't.
891
+ const r4 = (n: number) => Math.round(n * 10000) / 10000;
892
+ return {
893
+ cells,
894
+ estimated_billed_usd: r4(estUsd),
895
+ // Output length is the wild card — models rarely use the full max_tokens.
896
+ estimated_range_usd: [r4(estUsd * 0.25), r4(estUsd)],
897
+ minimum_charge_usd: FLOOR_USD,
898
+ note: 'Upper bound assumes every response hits max_tokens; typical spend lands well below it. Actual billing is measured provider cost × 1.5.',
899
+ };
900
+ }
901
+
902
+ // ---------------------------------------------------------------------------
903
+
904
+ async function createExperiment(ctx: Ctx, args: Record<string, unknown>) {
905
+ const spec = parseSpec(args);
906
+ const maxSpendUsd = Number(args.max_spend_usd);
907
+ if (!Number.isFinite(maxSpendUsd) || maxSpendUsd <= 0) {
908
+ throw new Error('max_spend_usd is required — a hard USD spend cap for this experiment (e.g. 2).');
909
+ }
910
+ if (maxSpendUsd > CAPS.maxSpendUsd) throw new Error(`max_spend_usd exceeds the $${CAPS.maxSpendUsd} per-experiment cap.`);
911
+ if (maxSpendUsd < FLOOR_USD) throw new Error(`max_spend_usd must be at least the $${FLOOR_USD} minimum charge.`);
912
+
913
+ const est = await estimateSpec(spec);
914
+
915
+ // Prepaid gate: balance must cover the cap. -1 = Redis unknown (fail-open
916
+ // for internal only; paying callers must have a readable balance).
917
+ const needCredits = Math.ceil(maxSpendUsd / CREDIT_USD);
918
+ if (!ctx.internal) {
919
+ if (ctx.balanceCredits < 0) {
920
+ throw new Error('Credit balance is temporarily unreadable — retry in a few seconds.');
921
+ }
922
+ if (ctx.balanceCredits < needCredits) {
923
+ const haveUsd = (ctx.balanceCredits * CREDIT_USD).toFixed(2);
924
+ throw new Error(
925
+ `Insufficient prepaid balance: experiments require balance ≥ max_spend_usd. You have $${haveUsd}, this experiment caps at $${maxSpendUsd.toFixed(2)}. Top up via x402: POST https://gateway.pipeworx.io/credits/topup?amount_usd=${Math.ceil(maxSpendUsd)} (see experiment_topup for the flow).`,
926
+ );
927
+ }
928
+ }
929
+
930
+ const insert = await pg(ctx, 'lab_experiments', {
931
+ method: 'POST',
932
+ prefer: 'return=representation',
933
+ body: JSON.stringify({
934
+ account_id: ctx.accountId,
935
+ name: args.name != null ? String(args.name).slice(0, 120) : null,
936
+ spec,
937
+ max_spend_cents: Math.round(maxSpendUsd * 100),
938
+ is_internal: ctx.internal,
939
+ }),
940
+ });
941
+ const [exp] = (await insert.json()) as Array<{ id: string }>;
942
+
943
+ const cells: Array<Record<string, unknown>> = [];
944
+ for (let pi = 0; pi < spec.prompts.length; pi++) {
945
+ for (const model of spec.models) {
946
+ for (let rep = 0; rep < spec.reps; rep++) {
947
+ cells.push({ experiment_id: exp.id, prompt_idx: pi, model, rep, kind: 'run' });
948
+ }
949
+ }
950
+ }
951
+ // ≤240 rows — safely inside PostgREST statement-timeout bounds in one insert.
952
+ await pg(ctx, 'lab_cells', { method: 'POST', body: JSON.stringify(cells) });
953
+
954
+ return {
955
+ experiment_id: exp.id,
956
+ status: 'running',
957
+ cells: cells.length,
958
+ estimate: est,
959
+ max_spend_usd: maxSpendUsd,
960
+ next: 'Execution starts within ~1 minute. Poll experiment_status({experiment_id}) until status is complete, then call experiment_results. Do not block waiting.',
961
+ };
962
+ }
963
+
964
+ async function getExperiment(ctx: Ctx, id: string) {
965
+ const res = await pg(ctx, `lab_experiments?id=eq.${encodeURIComponent(id)}&select=*`);
966
+ const rows = (await res.json()) as Array<Record<string, unknown>>;
967
+ const exp = rows[0];
968
+ if (!exp) throw new Error(`No experiment ${id}.`);
969
+ if (!ctx.internal && exp.account_id !== ctx.accountId) throw new Error(`No experiment ${id} on your account.`);
970
+ return exp;
971
+ }
972
+
973
+ async function statusTool(ctx: Ctx, args: Record<string, unknown>) {
974
+ const id = String(args.experiment_id ?? '');
975
+ const exp = await getExperiment(ctx, id);
976
+ const res = await pg(ctx, `lab_cells?experiment_id=eq.${encodeURIComponent(id)}&select=status,kind`);
977
+ const cells = (await res.json()) as Array<{ status: string; kind: string }>;
978
+ const by: Record<string, number> = {};
979
+ for (const c of cells) by[c.status] = (by[c.status] ?? 0) + 1;
980
+ const done = (by.ok ?? 0) + (by.error ?? 0) + (by.skipped ?? 0);
981
+ return {
982
+ experiment_id: id,
983
+ status: exp.status,
984
+ cells_total: cells.length,
985
+ cells_by_state: by,
986
+ progress: cells.length > 0 ? Math.round((done / cells.length) * 100) / 100 : 0,
987
+ spent_usd: Math.round(Number(exp.spent_cents ?? 0)) / 100,
988
+ max_spend_usd: Number(exp.max_spend_cents) / 100,
989
+ summary_pending: exp.status === 'running' && (exp.spec as Spec | null)?.summary !== false,
990
+ complete: exp.status !== 'running',
991
+ };
992
+ }
993
+
994
+ async function resultsTool(ctx: Ctx, args: Record<string, unknown>) {
995
+ const id = String(args.experiment_id ?? '');
996
+ const includeOutputs = args.include_outputs !== false;
997
+ const exp = await getExperiment(ctx, id);
998
+ const spec = exp.spec as Spec;
999
+ const res = await pg(
1000
+ ctx,
1001
+ `lab_cells?experiment_id=eq.${encodeURIComponent(id)}&kind=eq.run&select=prompt_idx,model,rep,status,output,error,tokens_in,tokens_out,latency_ms,billed_cents&order=prompt_idx,model,rep`,
1002
+ );
1003
+ const cells = (await res.json()) as Array<Record<string, unknown>>;
1004
+
1005
+ const agg = new Map<string, { n: number; ok: number; latency: number; tokensOut: number; billed: number }>();
1006
+ for (const c of cells) {
1007
+ const a = agg.get(String(c.model)) ?? { n: 0, ok: 0, latency: 0, tokensOut: 0, billed: 0 };
1008
+ a.n++;
1009
+ if (c.status === 'ok') {
1010
+ a.ok++;
1011
+ a.latency += Number(c.latency_ms ?? 0);
1012
+ a.tokensOut += Number(c.tokens_out ?? 0);
1013
+ }
1014
+ a.billed += Number(c.billed_cents ?? 0);
1015
+ agg.set(String(c.model), a);
1016
+ }
1017
+
1018
+ return {
1019
+ experiment_id: id,
1020
+ name: exp.name,
1021
+ status: exp.status,
1022
+ spent_usd: Math.round(Number(exp.spent_cents ?? 0)) / 100,
1023
+ summary: exp.summary ?? (exp.status === 'running' ? '(pending — run still in progress)' : undefined),
1024
+ summary_model: exp.summary_model ?? undefined,
1025
+ per_model: [...agg.entries()].map(([model, a]) => ({
1026
+ model,
1027
+ cells: a.n,
1028
+ ok: a.ok,
1029
+ error_rate: a.n > 0 ? Math.round(((a.n - a.ok) / a.n) * 100) / 100 : 0,
1030
+ mean_latency_ms: a.ok > 0 ? Math.round(a.latency / a.ok) : null,
1031
+ mean_output_tokens: a.ok > 0 ? Math.round(a.tokensOut / a.ok) : null,
1032
+ billed_usd: Math.round(a.billed) / 100,
1033
+ })),
1034
+ prompts: spec.prompts,
1035
+ cells: includeOutputs
1036
+ ? cells.map((c) => ({
1037
+ prompt_idx: c.prompt_idx,
1038
+ model: c.model,
1039
+ rep: c.rep,
1040
+ status: c.status,
1041
+ output: c.output,
1042
+ error: c.error ?? undefined,
1043
+ tokens_in: c.tokens_in,
1044
+ tokens_out: c.tokens_out,
1045
+ latency_ms: c.latency_ms,
1046
+ billed_usd: c.billed_cents != null ? Math.round(Number(c.billed_cents)) / 100 : null,
1047
+ }))
1048
+ : undefined,
1049
+ };
1050
+ }
1051
+
1052
+ async function listTool(ctx: Ctx, args: Record<string, unknown>) {
1053
+ const limit = Math.min(Math.max(Number(args.limit) || 20, 1), 100);
1054
+ const res = await pg(
1055
+ ctx,
1056
+ `lab_experiments?account_id=eq.${encodeURIComponent(ctx.accountId)}&select=id,name,status,spent_cents,max_spend_cents,created_at,completed_at&order=created_at.desc&limit=${limit}`,
1057
+ );
1058
+ const rows = (await res.json()) as Array<Record<string, unknown>>;
1059
+ return {
1060
+ count: rows.length,
1061
+ experiments: rows.map((r) => ({
1062
+ experiment_id: r.id,
1063
+ name: r.name,
1064
+ status: r.status,
1065
+ spent_usd: Math.round(Number(r.spent_cents ?? 0)) / 100,
1066
+ max_spend_usd: Number(r.max_spend_cents) / 100,
1067
+ created_at: r.created_at,
1068
+ completed_at: r.completed_at,
1069
+ })),
1070
+ };
1071
+ }
1072
+
1073
+ async function cancelTool(ctx: Ctx, args: Record<string, unknown>) {
1074
+ const id = String(args.experiment_id ?? '');
1075
+ await getExperiment(ctx, id);
1076
+ await pg(ctx, `lab_cells?experiment_id=eq.${encodeURIComponent(id)}&status=eq.pending`, {
1077
+ method: 'PATCH',
1078
+ body: JSON.stringify({ status: 'skipped' }),
1079
+ });
1080
+ await pg(ctx, `lab_experiments?id=eq.${encodeURIComponent(id)}&status=eq.running`, {
1081
+ method: 'PATCH',
1082
+ body: JSON.stringify({ status: 'cancelled', completed_at: new Date().toISOString() }),
1083
+ });
1084
+ return {
1085
+ experiment_id: id,
1086
+ status: 'cancelled',
1087
+ note: 'Pending cells skipped (not billed). Cells already in flight finish and bill. Results so far remain readable via experiment_results.',
1088
+ };
1089
+ }
1090
+
1091
+ function topupTool(ctx: Ctx, args: Record<string, unknown>) {
1092
+ const amount = Math.min(Math.max(Number(args.amount_usd) || 10, 1), 500);
1093
+ return {
1094
+ balance_usd: ctx.balanceCredits >= 0 ? Math.round(ctx.balanceCredits * CREDIT_USD * 100) / 100 : null,
1095
+ how_to_topup: {
1096
+ protocol: 'x402 (USDC on Base, in-band HTTP 402 payment)',
1097
+ step1: `POST https://gateway.pipeworx.io/credits/topup?amount_usd=${amount} — the response is HTTP 402 with a PAYMENT-REQUIRED header (base64 payment requirements).`,
1098
+ step2: 'Sign the USDC transfer with your wallet and retry the same request with a PAYMENT-SIGNATURE header.',
1099
+ step3: 'On settlement the credits land on your account instantly (1 credit = $0.0001) and the response confirms your new balance.',
1100
+ note: 'Send your usual Authorization bearer token so credits attach to your Pipeworx account; without one they attach to your paying wallet address.',
1101
+ },
1102
+ pricing: 'Experiments bill actual provider cost × 1.5, $0.10 minimum per experiment. Balance must cover max_spend_usd at create time.',
1103
+ };
1104
+ }
1105
+
1106
+ async function callTool(name: string, args: Record<string, unknown>): Promise<unknown> {
1107
+ const url = (args._supabaseUrl as string | undefined)?.trim();
1108
+ const key = (args._supabaseKey as string | undefined)?.trim();
1109
+ if (!url || !key) throw new Error('ai-model-experiments is not configured on this deployment — an operator must enable its data credentials. This is a setup problem, not your arguments.');
1110
+ const ctx: Ctx = {
1111
+ url,
1112
+ key,
1113
+ accountId: String(args._accountId ?? '').trim() || 'anonymous',
1114
+ balanceCredits: typeof args._creditBalance === 'number' ? args._creditBalance : -1,
1115
+ internal: args._internal === true,
1116
+ };
1117
+
1118
+ switch (name) {
1119
+ case 'experiment_models':
1120
+ return listModels(args);
1121
+ case 'experiment_estimate':
1122
+ return estimateSpec(parseSpec(args));
1123
+ case 'experiment_create':
1124
+ return createExperiment(ctx, args);
1125
+ case 'experiment_status':
1126
+ return statusTool(ctx, args);
1127
+ case 'experiment_results':
1128
+ return resultsTool(ctx, args);
1129
+ case 'experiment_list':
1130
+ return listTool(ctx, args);
1131
+ case 'experiment_cancel':
1132
+ return cancelTool(ctx, args);
1133
+ case 'experiment_topup':
1134
+ return topupTool(ctx, args);
1135
+ default:
1136
+ throw new Error(`Unknown tool: ${name}`);
1137
+ }
1138
+ }
1139
+
1140
+ export default { tools, callTool, meter: { credits: 1 } } satisfies McpToolExport;