Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : SP Wallet8 * File : services/research-runner/src/gateway.ts9 * Module : services10 * Repository : https://git.spboucher.ai/sp-wallet11 * Project Website : https://wallet.spboucher.ai12 * Created : 2026-11-1113 * Last Modified : 2026-11-1114 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: support@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243// Model gateway of ONE research job: the only network door of the sandboxed agent.44//45// The sandbox profile lets the agent connect to one loopback port — this server — and nowhere else. The gateway:46// - accepts only the model API's message endpoints (POST /v1/messages and /v1/messages/count_tokens); every other path is 404;47// - requires the per-job placeholder key the runner put in the agent's environment (another local process cannot use it);48// - REPLACES the credentials: the agent's headers are dropped and the runner's real model credential is added here, so the49// agent process never holds it (its environment contains no secret at all);50// - refuses requests that ask the model API for server-side tools that reach the web or run code elsewhere (web search,51// web fetch, code execution, remote MCP servers): a job has no web access, whatever the agent's own tool list says;52// - counts the tokens of every answer (usage in the JSON body or in the event stream) and refuses further requests once53// the job's token budget is spent — the runner then kills the job. The agent cannot reset or bypass this counter.54// The upstream is one fixed origin (https://api.anthropic.com unless configured); the gateway never follows redirects and55// never connects anywhere the request names.56import { createServer, request as httpRequest, type IncomingMessage, type Server, type ServerResponse } from 'node:http';57import { request as httpsRequest } from 'node:https';58import type { AddressInfo } from 'node:net';59import { timingSafeEqual } from 'node:crypto';6061export interface GatewayOptions {62 /** origin of the model API, e.g. https://api.anthropic.com (tests: a local fake) */63 upstream: string;64 /** header carrying the runner's real credential, e.g. ['x-api-key', '...'] or ['authorization', 'Bearer ...']; null = none (fake upstream) */65 credential: [name: string, value: string] | null;66 /** placeholder the agent must present (given to it as ANTHROPIC_API_KEY) */67 jobKey: string;68 maxTokens: number;69 onLog?: (line: string) => void;70}71export interface GatewayUsage { requests: number; refused: number; inputTokens: number; outputTokens: number; cacheTokens: number; total: number; exhausted: boolean }7273const ALLOWED = new Set(['/v1/messages', '/v1/messages/count_tokens']);74const MAX_BODY = 32 * 1024 * 1024;75/** tool types executed by the model provider, outside the sandbox */76const SERVER_TOOL = /^(web_search|web_fetch|code_execution|mcp|computer|bash_code_execution|text_editor_code_execution)/;77const DROP_REQ = new Set(['host', 'connection', 'content-length', 'transfer-encoding', 'x-api-key', 'authorization', 'proxy-authorization', 'cookie', 'accept-encoding', 'expect', 'keep-alive', 'upgrade']);78const DROP_RES = new Set(['connection', 'transfer-encoding', 'keep-alive', 'set-cookie', 'content-length']);7980const same = (a: string, b: string): boolean => { const x = Buffer.from(a), y = Buffer.from(b); return x.length === y.length && timingSafeEqual(x, y); };8182export class ModelGateway {83 private server: Server | null = null;84 private readonly o: GatewayOptions;85 private readonly up: URL;86 readonly usage: GatewayUsage = { requests: 0, refused: 0, inputTokens: 0, outputTokens: 0, cacheTokens: 0, total: 0, exhausted: false };87 port = 0;8889 constructor(o: GatewayOptions) {90 this.o = o; this.up = new URL(o.upstream);91 if (this.up.protocol !== 'https:' && !['127.0.0.1', 'localhost'].includes(this.up.hostname)) throw new Error('gateway: the upstream must be https (plain http is accepted for a loopback fake only)');92 }9394 async start(): Promise<number> {95 this.server = createServer((req, res) => { this.handle(req, res).catch((e: Error) => { this.fail(res, 502, 'api_error', `gateway: ${e.message.slice(0, 120)}`); }); });96 await new Promise<void>((resolve, reject) => { this.server!.once('error', reject); this.server!.listen(0, '127.0.0.1', resolve); });97 this.port = (this.server.address() as AddressInfo).port;98 return this.port;99 }100 async stop(): Promise<void> {101 const s = this.server; this.server = null;102 if (!s) return;103 s.closeAllConnections();104 await new Promise<void>((r) => s.close(() => r()));105 }106107 private fail(res: ServerResponse, status: number, type: string, message: string): void {108 if (res.headersSent) { res.end(); return; }109 res.writeHead(status, { 'content-type': 'application/json' });110 res.end(JSON.stringify({ type: 'error', error: { type, message } }));111 }112 private count(u: unknown): void {113 if (!u || typeof u !== 'object') return;114 const n = (k: string): number => { const v = (u as Record<string, unknown>)[k]; return typeof v === 'number' && Number.isFinite(v) && v > 0 ? Math.floor(v) : 0; };115 this.usage.inputTokens += n('input_tokens'); this.usage.outputTokens += n('output_tokens');116 this.usage.cacheTokens += n('cache_creation_input_tokens') + n('cache_read_input_tokens');117 this.usage.total = this.usage.inputTokens + this.usage.outputTokens + this.usage.cacheTokens;118 if (this.usage.total >= this.o.maxTokens) this.usage.exhausted = true;119 }120121 private async handle(req: IncomingMessage, res: ServerResponse): Promise<void> {122 const path = (req.url ?? '').split('?')[0]!;123 const refuse = (status: number, type: string, message: string): void => { this.usage.refused += 1; this.o.onLog?.(`gateway refused ${req.method} ${path.slice(0, 80)}: ${message}`); req.resume(); this.fail(res, status, type, message); };124 if (req.method !== 'POST' || !ALLOWED.has(path)) return refuse(404, 'not_found_error', 'this gateway only serves the model message endpoints');125 const presented = String(req.headers['x-api-key'] ?? '') || String(req.headers.authorization ?? '').replace(/^Bearer\s+/i, '');126 if (!same(presented, this.o.jobKey)) return refuse(401, 'authentication_error', 'unknown job key');127 if (this.usage.exhausted) return refuse(429, 'rate_limit_error', 'the token budget of this research job is spent');128 const chunks: Buffer[] = []; let size = 0;129 for await (const c of req) { size += (c as Buffer).length; if (size > MAX_BODY) return refuse(413, 'request_too_large', 'request body too large'); chunks.push(c as Buffer); }130 const body = Buffer.concat(chunks);131 let parsed: { tools?: unknown; mcp_servers?: unknown; stream?: unknown };132 try { parsed = JSON.parse(body.toString('utf8')) as typeof parsed; } catch { return refuse(400, 'invalid_request_error', 'the body is not JSON'); }133 if (parsed.mcp_servers !== undefined) return refuse(403, 'permission_error', 'remote MCP servers are not available to a research job');134 if (Array.isArray(parsed.tools)) for (const t of parsed.tools) { const type = (t as { type?: unknown } | null)?.type;135 if (typeof type === 'string' && SERVER_TOOL.test(type)) return refuse(403, 'permission_error', `the server-side tool "${type.slice(0, 40)}" is not available to a research job (no web access)`); }136 this.usage.requests += 1;137138 const headers: Record<string, string | string[]> = {};139 for (const [k, v] of Object.entries(req.headers)) if (v !== undefined && !DROP_REQ.has(k)) headers[k] = v;140 headers.host = this.up.host; headers['content-length'] = String(body.length); headers['accept-encoding'] = 'identity';141 if (this.o.credential) headers[this.o.credential[0]] = this.o.credential[1];142 const send = this.up.protocol === 'https:' ? httpsRequest : httpRequest;143 await new Promise<void>((resolve) => {144 const up = send({ protocol: this.up.protocol, hostname: this.up.hostname, port: this.up.port || undefined, method: 'POST', path: path + (req.url!.includes('?') ? req.url!.slice(req.url!.indexOf('?')) : ''), headers }, (ur) => {145 const out: Record<string, string | string[]> = {};146 for (const [k, v] of Object.entries(ur.headers)) if (v !== undefined && !DROP_RES.has(k)) out[k] = v;147 res.writeHead(ur.statusCode ?? 502, out);148 const sse = String(ur.headers['content-type'] ?? '').includes('text/event-stream');149 let text = '';150 ur.on('data', (c: Buffer) => {151 res.write(c);152 if (path !== '/v1/messages') return; // count_tokens answers are not usage153 text += c.toString('utf8');154 if (!sse) { if (text.length > 8_000_000) text = text.slice(-8_000_000); return; }155 let i: number;156 while ((i = text.indexOf('\n')) >= 0) { const line = text.slice(0, i).trim(); text = text.slice(i + 1);157 if (!line.startsWith('data:')) continue;158 try { const ev = JSON.parse(line.slice(5)) as { type?: string; message?: { usage?: unknown }; usage?: unknown };159 if (ev.type === 'message_start') this.count(ev.message?.usage);160 else if (ev.type === 'message_delta') this.count({ output_tokens: (ev.usage as { output_tokens?: number } | undefined)?.output_tokens }); } catch { /* not an event we count */ } }161 });162 ur.on('end', () => { if (!sse && path === '/v1/messages') { try { this.count((JSON.parse(text) as { usage?: unknown }).usage); } catch { /* an error body */ } } res.end(); resolve(); });163 ur.on('error', () => { res.end(); resolve(); });164 });165 up.on('error', (e) => { this.fail(res, 502, 'api_error', `the model API could not be reached: ${e.message.slice(0, 100)}`); resolve(); });166 up.setTimeout(10 * 60_000, () => up.destroy(new Error('timeout')));167 res.on('close', () => up.destroy());168 up.end(body);169 });170 }171}172