@celljs/ta-gateway 4.15.2 → 4.16.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/esm/node/command-sandbox.d.ts +1 -0
- package/esm/node/command-sandbox.js +10 -1
- package/esm/node/docker-engine.d.ts +5 -0
- package/esm/node/docker-engine.js +11 -0
- package/esm/node/docker-sandbox.d.ts +3 -0
- package/esm/node/docker-sandbox.js +17 -3
- package/esm/node/environments.d.ts +2 -0
- package/esm/node/environments.js +5 -3
- package/esm/node/gateway-exec.d.ts +19 -0
- package/esm/node/gateway-exec.js +65 -0
- package/esm/node/gateway-policy.d.ts +1 -0
- package/esm/node/gateway-policy.js +2 -1
- package/esm/node/gateway-quotas.d.ts +9 -1
- package/esm/node/gateway-quotas.js +34 -3
- package/esm/node/gateway-server.d.ts +12 -1
- package/esm/node/gateway-server.js +55 -4
- package/esm/node/gateway-service.d.ts +8 -0
- package/esm/node/gateway-service.js +23 -4
- package/esm/node/local-sandbox.d.ts +1 -0
- package/esm/node/local-sandbox.js +2 -1
- package/esm/node/model-proxy.d.ts +105 -0
- package/esm/node/model-proxy.js +435 -0
- package/esm/node/sandbox-provider.d.ts +7 -0
- package/esm/node/tenant-store.d.ts +7 -0
- package/esm/node/tenant-store.js +10 -0
- package/lib/node/command-sandbox.d.ts +1 -0
- package/lib/node/command-sandbox.js +10 -1
- package/lib/node/docker-engine.d.ts +5 -0
- package/lib/node/docker-engine.js +11 -0
- package/lib/node/docker-sandbox.d.ts +3 -0
- package/lib/node/docker-sandbox.js +17 -3
- package/lib/node/environments.d.ts +2 -0
- package/lib/node/environments.js +5 -3
- package/lib/node/gateway-exec.d.ts +20 -0
- package/lib/node/gateway-exec.js +69 -0
- package/lib/node/gateway-policy.d.ts +1 -0
- package/lib/node/gateway-policy.js +2 -1
- package/lib/node/gateway-quotas.d.ts +9 -1
- package/lib/node/gateway-quotas.js +34 -3
- package/lib/node/gateway-server.d.ts +12 -1
- package/lib/node/gateway-server.js +55 -4
- package/lib/node/gateway-service.d.ts +8 -0
- package/lib/node/gateway-service.js +23 -4
- package/lib/node/local-sandbox.d.ts +1 -0
- package/lib/node/local-sandbox.js +2 -1
- package/lib/node/model-proxy.d.ts +106 -0
- package/lib/node/model-proxy.js +440 -0
- package/lib/node/sandbox-provider.d.ts +7 -0
- package/lib/node/tenant-store.d.ts +7 -0
- package/lib/node/tenant-store.js +10 -0
- package/package.json +4 -4
|
@@ -3,6 +3,7 @@ import { TA_RPC_ERROR_CODE, TaErrorCode, } from '@celljs/ta-protocol';
|
|
|
3
3
|
import { Redactor } from '@celljs/ta-protocol/lib/common/redactor';
|
|
4
4
|
import { GatewayPolicyUtil, PolicyError } from './gateway-policy.js';
|
|
5
5
|
import { GatewayUsageUtil } from './gateway-usage.js';
|
|
6
|
+
import { ModelProxyUtil } from './model-proxy.js';
|
|
6
7
|
import { TaSandboxUtil } from './ta-sandbox.js';
|
|
7
8
|
export class GatewayCallError extends Error {
|
|
8
9
|
constructor(message, code, hint) {
|
|
@@ -43,6 +44,7 @@ export var GatewayServiceUtil;
|
|
|
43
44
|
setSuspended: 'admin',
|
|
44
45
|
setDefaultLimits: 'owner',
|
|
45
46
|
setRole: 'owner',
|
|
47
|
+
createAccessToken: 'anyone',
|
|
46
48
|
},
|
|
47
49
|
TaAccessServer: {
|
|
48
50
|
getAccess: 'anyone',
|
|
@@ -181,6 +183,7 @@ export var GatewayServiceUtil;
|
|
|
181
183
|
*/
|
|
182
184
|
export class GatewayService {
|
|
183
185
|
constructor(parts) {
|
|
186
|
+
this.models = parts.models;
|
|
184
187
|
this.flow = parts.flow;
|
|
185
188
|
this.tenants = parts.tenants;
|
|
186
189
|
this.environments = parts.environments;
|
|
@@ -232,6 +235,7 @@ export class GatewayService {
|
|
|
232
235
|
setSuspended: () => this.setSuspended(caller, first, second),
|
|
233
236
|
setDefaultLimits: () => this.setDefaultLimits(first),
|
|
234
237
|
setRole: () => this.setRole(caller, first, second),
|
|
238
|
+
createAccessToken: () => this.accessToken(caller, first),
|
|
235
239
|
}
|
|
236
240
|
: {
|
|
237
241
|
getAccess: () => this.access(caller),
|
|
@@ -306,8 +310,8 @@ export class GatewayService {
|
|
|
306
310
|
}
|
|
307
311
|
/** The tenants with what their sandboxes take and their agents do, read together: a slow one holds the console a second, not a second each. */
|
|
308
312
|
async console(caller) {
|
|
309
|
-
var _a;
|
|
310
|
-
var
|
|
313
|
+
var _a, _b;
|
|
314
|
+
var _c, _d, _e;
|
|
311
315
|
const tenants = this.tenants.list();
|
|
312
316
|
const [usages, agents] = await Promise.all([
|
|
313
317
|
Promise.all(tenants.map(tenant => this.environments.usage(tenant).catch(() => undefined))),
|
|
@@ -316,9 +320,9 @@ export class GatewayService {
|
|
|
316
320
|
const counts = new Map();
|
|
317
321
|
for (const tenant of tenants) {
|
|
318
322
|
const { provider } = this.environments.info(tenant);
|
|
319
|
-
counts.set(provider, ((
|
|
323
|
+
counts.set(provider, ((_c = counts.get(provider)) !== null && _c !== void 0 ? _c : 0) + 1);
|
|
320
324
|
}
|
|
321
|
-
const fallback = (
|
|
325
|
+
const fallback = (_d = this.environments.settings.default) !== null && _d !== void 0 ? _d : (_a = this.environments.providers[0]) === null || _a === void 0 ? void 0 : _a.id;
|
|
322
326
|
return {
|
|
323
327
|
version: this.meta.version,
|
|
324
328
|
startedAt: this.meta.startedAt,
|
|
@@ -339,6 +343,12 @@ export class GatewayService {
|
|
|
339
343
|
requests: this.flow.store.info(caller.token).requests.length,
|
|
340
344
|
role: caller.role,
|
|
341
345
|
policy: this.policyView(),
|
|
346
|
+
models: ModelProxyUtil.catalog((_e = (_b = this.models) === null || _b === void 0 ? void 0 : _b.config) !== null && _e !== void 0 ? _e : {}).providers.map(provider => ({
|
|
347
|
+
id: provider.id,
|
|
348
|
+
name: provider.name,
|
|
349
|
+
api: provider.api,
|
|
350
|
+
models: provider.models.length,
|
|
351
|
+
})),
|
|
342
352
|
};
|
|
343
353
|
}
|
|
344
354
|
policyView() {
|
|
@@ -448,6 +458,15 @@ export class GatewayService {
|
|
|
448
458
|
this.policy.setRole(id, role);
|
|
449
459
|
return this.policyView();
|
|
450
460
|
}
|
|
461
|
+
/** A sign-in of the caller's own account, named for where it is used. */
|
|
462
|
+
accessToken(caller, label) {
|
|
463
|
+
var _a;
|
|
464
|
+
const tenant = (_a = this.tenants.get(caller.tenant.id)) !== null && _a !== void 0 ? _a : caller.tenant;
|
|
465
|
+
const device = typeof label === 'string' && label.trim() ? label.trim().slice(0, 60) : 'Another Ta';
|
|
466
|
+
const token = this.flow.store.signIn({ id: caller.account, name: tenant.name, avatar: tenant.avatar }, device);
|
|
467
|
+
console.log(`ta gateway: ${caller.account} made a token for ${device}`);
|
|
468
|
+
return { token, url: this.meta.publicUrl };
|
|
469
|
+
}
|
|
451
470
|
access(caller) {
|
|
452
471
|
const providers = this.flow.providers.map(({ id, name }) => ({ id, name }));
|
|
453
472
|
const info = this.flow.store.info(caller.token);
|
|
@@ -19,6 +19,7 @@ export declare class LocalSandbox implements SandboxProvider {
|
|
|
19
19
|
protected readonly context: SandboxContext;
|
|
20
20
|
readonly type = "local";
|
|
21
21
|
readonly name: string;
|
|
22
|
+
readonly gatewayUrl?: string;
|
|
22
23
|
protected readonly running: Map<string, {
|
|
23
24
|
child: ChildProcess;
|
|
24
25
|
url: string;
|
|
@@ -42,6 +42,7 @@ export class LocalSandbox {
|
|
|
42
42
|
/** Kept past a stop, so that the console shows why one ended. */
|
|
43
43
|
this.output = new Map();
|
|
44
44
|
this.name = SandboxProviders.string(config, 'name', 'Local');
|
|
45
|
+
this.gatewayUrl = SandboxProviders.string(config, 'gatewayUrl');
|
|
45
46
|
}
|
|
46
47
|
async start(tenant) {
|
|
47
48
|
var _a, _b;
|
|
@@ -58,7 +59,7 @@ export class LocalSandbox {
|
|
|
58
59
|
const [command, ...args] = this.context.taCommand;
|
|
59
60
|
const child = spawn(command, [...args, 'serve', '--port', String(port)], {
|
|
60
61
|
cwd,
|
|
61
|
-
env: { ...process.env, TA_CODING_AGENT_DIR: agentDir, TA_SERVE_TOKEN: tenant.token, CELL_SERVER__HOST: '127.0.0.1' },
|
|
62
|
+
env: { ...process.env, ...tenant.env, TA_CODING_AGENT_DIR: agentDir, TA_SERVE_TOKEN: tenant.token, CELL_SERVER__HOST: '127.0.0.1' },
|
|
62
63
|
stdio: ['ignore', 'pipe', 'pipe'],
|
|
63
64
|
});
|
|
64
65
|
const tail = new LineTail();
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
+
/** What a model costs, in dollars per million tokens, as pi's models.json says it. */
|
|
3
|
+
export interface ModelCost {
|
|
4
|
+
input?: number;
|
|
5
|
+
output?: number;
|
|
6
|
+
cacheRead?: number;
|
|
7
|
+
cacheWrite?: number;
|
|
8
|
+
}
|
|
9
|
+
/** A provider of models of the gateway: an entry of pi's models.json, its key kept by the gateway alone. */
|
|
10
|
+
export interface GatewayModelProvider {
|
|
11
|
+
name?: string;
|
|
12
|
+
baseUrl: string;
|
|
13
|
+
/** pi's `api`: openai-completions, openai-responses, anthropic-messages, google-generative-ai, … */
|
|
14
|
+
api: string;
|
|
15
|
+
/** The key, or the name of a variable of the environment of the gateway that holds it. */
|
|
16
|
+
apiKey?: string;
|
|
17
|
+
/** Headers sent upstream, never to sandboxes. */
|
|
18
|
+
headers?: Record<string, string>;
|
|
19
|
+
models: ({
|
|
20
|
+
id: string;
|
|
21
|
+
cost?: ModelCost;
|
|
22
|
+
} & Record<string, unknown>)[];
|
|
23
|
+
}
|
|
24
|
+
/** `models.json` of the directory of the gateway. */
|
|
25
|
+
export interface GatewayModelsConfig {
|
|
26
|
+
providers?: Record<string, GatewayModelProvider>;
|
|
27
|
+
}
|
|
28
|
+
/** Tokens of one call, as the gateway counts them. */
|
|
29
|
+
export interface ModelUsage {
|
|
30
|
+
input: number;
|
|
31
|
+
output: number;
|
|
32
|
+
cacheRead: number;
|
|
33
|
+
cacheWrite: number;
|
|
34
|
+
}
|
|
35
|
+
/** What sandboxes are told of the providers: everything but where they are and their keys. */
|
|
36
|
+
export interface ModelCatalog {
|
|
37
|
+
providers: {
|
|
38
|
+
id: string;
|
|
39
|
+
name?: string;
|
|
40
|
+
api: string;
|
|
41
|
+
models: Record<string, unknown>[];
|
|
42
|
+
}[];
|
|
43
|
+
}
|
|
44
|
+
/** Who a model key is, whether they may call now, and what a call took. */
|
|
45
|
+
export interface ModelProxyHooks {
|
|
46
|
+
tenantOfKey(key: string): {
|
|
47
|
+
id: string;
|
|
48
|
+
account: string;
|
|
49
|
+
} | undefined;
|
|
50
|
+
/** Why the tenant may not call a model now (out of tokens, suspended), as the message a model would give. */
|
|
51
|
+
refuse(tenantId: string): string | undefined;
|
|
52
|
+
record(tenantId: string, usage: ModelUsage, cost: number): void;
|
|
53
|
+
}
|
|
54
|
+
export declare class ModelConfigError extends Error {
|
|
55
|
+
}
|
|
56
|
+
export declare namespace ModelProxyUtil {
|
|
57
|
+
const PATH = "/api/models";
|
|
58
|
+
function read(dir: string): GatewayModelsConfig;
|
|
59
|
+
/** The key: the variable of the environment it names, else itself. */
|
|
60
|
+
function key(value: string | undefined, env?: Record<string, string | undefined>): string | undefined;
|
|
61
|
+
function catalog(config: GatewayModelsConfig): ModelCatalog;
|
|
62
|
+
/** The key a sandbox sent, however its API sends one. */
|
|
63
|
+
function presented(request: IncomingMessage): string | undefined;
|
|
64
|
+
/** How the provider takes its key. */
|
|
65
|
+
function authHeaders(api: string, key: string | undefined): Record<string, string>;
|
|
66
|
+
/** Where a call goes: the rest of its path on the provider's base, its query without a key. */
|
|
67
|
+
function target(baseUrl: string, rest: string, query: URLSearchParams): string;
|
|
68
|
+
/**
|
|
69
|
+
* The tokens an object of an answer tells (OpenAI chat or responses, Anthropic, Google), cached input apart;
|
|
70
|
+
* undefined for one that tells none.
|
|
71
|
+
*/
|
|
72
|
+
function usageOf(value: unknown): ModelUsage | undefined;
|
|
73
|
+
/** Events of a stream tell them as they go, each so far: the most of each. */
|
|
74
|
+
function merge(into: ModelUsage | undefined, next: ModelUsage | undefined): ModelUsage | undefined;
|
|
75
|
+
function total(usage: ModelUsage): number;
|
|
76
|
+
function cost(usage: ModelUsage, price: ModelCost | undefined): number;
|
|
77
|
+
/**
|
|
78
|
+
* The body of an OpenAI chat stream asking for its usage too: without stream_options.include_usage the stream
|
|
79
|
+
* tells none, and a call would go uncounted past every limit. Other bodies are sent as they came.
|
|
80
|
+
*/
|
|
81
|
+
function metered(api: string, body: Buffer): Buffer;
|
|
82
|
+
/** The model a call names: in its path (Google), else in its body. */
|
|
83
|
+
function modelOf(body: Buffer, rest: string): string | undefined;
|
|
84
|
+
/** An error as a model service gives one, so that the clients of every API read its message. */
|
|
85
|
+
function error(response: ServerResponse, status: number, message: string, type?: string): void;
|
|
86
|
+
function sameKey(given: string, known: string): boolean;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* The models of the gateway, for its sandboxes: a call of a sandbox with the model key of its tenant goes to the
|
|
90
|
+
* provider with the gateway's key, which no sandbox has, and what it took is counted for the tenant, from the usage
|
|
91
|
+
* of the answer (a stream's too). A tenant out of its tokens of the month gets an error instead of a call.
|
|
92
|
+
*/
|
|
93
|
+
export declare class ModelProxy {
|
|
94
|
+
readonly config: GatewayModelsConfig;
|
|
95
|
+
protected readonly hooks: ModelProxyHooks;
|
|
96
|
+
protected readonly env: Record<string, string | undefined>;
|
|
97
|
+
constructor(config: GatewayModelsConfig, hooks: ModelProxyHooks, env?: Record<string, string | undefined>);
|
|
98
|
+
get enabled(): boolean;
|
|
99
|
+
protected provider(id: string): GatewayModelProvider | undefined;
|
|
100
|
+
handle(request: IncomingMessage, response: ServerResponse): Promise<void>;
|
|
101
|
+
/** Whether the response drained, false once it closed instead (its drain never comes then). */
|
|
102
|
+
protected drained(response: ServerResponse): Promise<boolean>;
|
|
103
|
+
protected event(line: string): ModelUsage | undefined;
|
|
104
|
+
protected body(request: IncomingMessage): Promise<Buffer | undefined>;
|
|
105
|
+
}
|
|
@@ -0,0 +1,435 @@
|
|
|
1
|
+
import { createHash, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
export class ModelConfigError extends Error {
|
|
5
|
+
}
|
|
6
|
+
const MAX_BODY = 32 * 1024 * 1024;
|
|
7
|
+
/** Of an answer that is not a stream, at most this is read for its usage. */
|
|
8
|
+
const MAX_READ = 8 * 1024 * 1024;
|
|
9
|
+
const DROPPED_REQUEST = new Set([
|
|
10
|
+
'host',
|
|
11
|
+
'authorization',
|
|
12
|
+
'x-api-key',
|
|
13
|
+
'x-goog-api-key',
|
|
14
|
+
'api-key',
|
|
15
|
+
'cookie',
|
|
16
|
+
'connection',
|
|
17
|
+
'content-length',
|
|
18
|
+
'accept-encoding',
|
|
19
|
+
'transfer-encoding',
|
|
20
|
+
'keep-alive',
|
|
21
|
+
'upgrade',
|
|
22
|
+
'proxy-authorization',
|
|
23
|
+
'x-forwarded-for',
|
|
24
|
+
'x-forwarded-proto',
|
|
25
|
+
'x-forwarded-host',
|
|
26
|
+
]);
|
|
27
|
+
const DROPPED_RESPONSE = new Set(['content-encoding', 'content-length', 'transfer-encoding', 'connection', 'keep-alive', 'set-cookie']);
|
|
28
|
+
export var ModelProxyUtil;
|
|
29
|
+
(function (ModelProxyUtil) {
|
|
30
|
+
ModelProxyUtil.PATH = '/api/models';
|
|
31
|
+
const ID = /^[a-z0-9][a-z0-9._-]{0,63}$/i;
|
|
32
|
+
function read(dir) {
|
|
33
|
+
var _a;
|
|
34
|
+
const file = join(dir, 'models.json');
|
|
35
|
+
if (!existsSync(file)) {
|
|
36
|
+
return {};
|
|
37
|
+
}
|
|
38
|
+
let config;
|
|
39
|
+
try {
|
|
40
|
+
config = JSON.parse(readFileSync(file, 'utf8'));
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
throw new ModelConfigError(`${file} is not JSON: ${error.message}`);
|
|
44
|
+
}
|
|
45
|
+
for (const [id, provider] of Object.entries((_a = config.providers) !== null && _a !== void 0 ? _a : {})) {
|
|
46
|
+
if (!ID.test(id)) {
|
|
47
|
+
throw new ModelConfigError(`"${id}" cannot name a provider of models: letters, digits, . _ and -.`);
|
|
48
|
+
}
|
|
49
|
+
if (typeof (provider === null || provider === void 0 ? void 0 : provider.baseUrl) !== 'string' ||
|
|
50
|
+
!/^https?:\/\//.test(provider.baseUrl) ||
|
|
51
|
+
typeof provider.api !== 'string' ||
|
|
52
|
+
!Array.isArray(provider.models)) {
|
|
53
|
+
throw new ModelConfigError(`The provider of models "${id}" needs baseUrl (http or https), api and models, as pi's models.json.`);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return config;
|
|
57
|
+
}
|
|
58
|
+
ModelProxyUtil.read = read;
|
|
59
|
+
/** The key: the variable of the environment it names, else itself. */
|
|
60
|
+
function key(value, env = process.env) {
|
|
61
|
+
if (!value) {
|
|
62
|
+
return undefined;
|
|
63
|
+
}
|
|
64
|
+
const name = value.startsWith('$') ? value.slice(1) : value;
|
|
65
|
+
if (/^[A-Z][A-Z0-9_]*$/.test(name) && env[name]) {
|
|
66
|
+
return env[name];
|
|
67
|
+
}
|
|
68
|
+
return value.startsWith('$') ? undefined : value;
|
|
69
|
+
}
|
|
70
|
+
ModelProxyUtil.key = key;
|
|
71
|
+
function catalog(config) {
|
|
72
|
+
var _a;
|
|
73
|
+
return {
|
|
74
|
+
providers: Object.entries((_a = config.providers) !== null && _a !== void 0 ? _a : {}).map(([id, provider]) => ({
|
|
75
|
+
id,
|
|
76
|
+
name: provider.name,
|
|
77
|
+
api: provider.api,
|
|
78
|
+
models: provider.models.map(model => ({ ...model })),
|
|
79
|
+
})),
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
ModelProxyUtil.catalog = catalog;
|
|
83
|
+
/** The key a sandbox sent, however its API sends one. */
|
|
84
|
+
function presented(request) {
|
|
85
|
+
var _a, _b;
|
|
86
|
+
const bearer = request.headers.authorization;
|
|
87
|
+
if (bearer === null || bearer === void 0 ? void 0 : bearer.startsWith('Bearer ')) {
|
|
88
|
+
return bearer.slice('Bearer '.length).trim();
|
|
89
|
+
}
|
|
90
|
+
for (const name of ['x-api-key', 'x-goog-api-key', 'api-key']) {
|
|
91
|
+
const value = request.headers[name];
|
|
92
|
+
if (typeof value === 'string' && value) {
|
|
93
|
+
return value.trim();
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return (_b = new URL((_a = request.url) !== null && _a !== void 0 ? _a : '/', 'http://gateway').searchParams.get('key')) !== null && _b !== void 0 ? _b : undefined;
|
|
97
|
+
}
|
|
98
|
+
ModelProxyUtil.presented = presented;
|
|
99
|
+
/** How the provider takes its key. */
|
|
100
|
+
function authHeaders(api, key) {
|
|
101
|
+
if (!key) {
|
|
102
|
+
return {};
|
|
103
|
+
}
|
|
104
|
+
if (api.startsWith('anthropic')) {
|
|
105
|
+
return { 'x-api-key': key };
|
|
106
|
+
}
|
|
107
|
+
if (api.startsWith('google')) {
|
|
108
|
+
return { 'x-goog-api-key': key };
|
|
109
|
+
}
|
|
110
|
+
if (api.includes('azure')) {
|
|
111
|
+
return { 'api-key': key };
|
|
112
|
+
}
|
|
113
|
+
return { authorization: `Bearer ${key}` };
|
|
114
|
+
}
|
|
115
|
+
ModelProxyUtil.authHeaders = authHeaders;
|
|
116
|
+
/** Where a call goes: the rest of its path on the provider's base, its query without a key. */
|
|
117
|
+
function target(baseUrl, rest, query) {
|
|
118
|
+
const params = new URLSearchParams(query);
|
|
119
|
+
params.delete('key');
|
|
120
|
+
const search = params.toString();
|
|
121
|
+
return `${baseUrl.replace(/\/+$/, '')}${rest}${search ? `?${search}` : ''}`;
|
|
122
|
+
}
|
|
123
|
+
ModelProxyUtil.target = target;
|
|
124
|
+
function number(value) {
|
|
125
|
+
return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0;
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* The tokens an object of an answer tells (OpenAI chat or responses, Anthropic, Google), cached input apart;
|
|
129
|
+
* undefined for one that tells none.
|
|
130
|
+
*/
|
|
131
|
+
function usageOf(value) {
|
|
132
|
+
var _a, _b, _c, _d;
|
|
133
|
+
var _e, _f, _g;
|
|
134
|
+
if (!value || typeof value !== 'object') {
|
|
135
|
+
return undefined;
|
|
136
|
+
}
|
|
137
|
+
const object = value;
|
|
138
|
+
const usage = (_g = (_f = (_e = object.usage) !== null && _e !== void 0 ? _e : (_a = object.message) === null || _a === void 0 ? void 0 : _a.usage) !== null && _f !== void 0 ? _f : (_b = object.response) === null || _b === void 0 ? void 0 : _b.usage) !== null && _g !== void 0 ? _g : object.usageMetadata;
|
|
139
|
+
if (!usage || typeof usage !== 'object') {
|
|
140
|
+
return undefined;
|
|
141
|
+
}
|
|
142
|
+
if ('promptTokenCount' in usage || 'candidatesTokenCount' in usage) {
|
|
143
|
+
const cached = number(usage.cachedContentTokenCount);
|
|
144
|
+
return {
|
|
145
|
+
input: Math.max(0, number(usage.promptTokenCount) - cached),
|
|
146
|
+
output: number(usage.candidatesTokenCount) + number(usage.thoughtsTokenCount),
|
|
147
|
+
cacheRead: cached,
|
|
148
|
+
cacheWrite: 0,
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
if ('prompt_tokens' in usage || 'completion_tokens' in usage) {
|
|
152
|
+
const cached = number((_c = usage.prompt_tokens_details) === null || _c === void 0 ? void 0 : _c.cached_tokens);
|
|
153
|
+
return { input: Math.max(0, number(usage.prompt_tokens) - cached), output: number(usage.completion_tokens), cacheRead: cached, cacheWrite: 0 };
|
|
154
|
+
}
|
|
155
|
+
if ('input_tokens' in usage || 'output_tokens' in usage) {
|
|
156
|
+
// The responses API counts cached input in input_tokens; Anthropic apart, in cache_read_input_tokens.
|
|
157
|
+
const cached = number((_d = usage.input_tokens_details) === null || _d === void 0 ? void 0 : _d.cached_tokens);
|
|
158
|
+
return {
|
|
159
|
+
input: Math.max(0, number(usage.input_tokens) - cached),
|
|
160
|
+
output: number(usage.output_tokens),
|
|
161
|
+
cacheRead: cached + number(usage.cache_read_input_tokens),
|
|
162
|
+
cacheWrite: number(usage.cache_creation_input_tokens),
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
return undefined;
|
|
166
|
+
}
|
|
167
|
+
ModelProxyUtil.usageOf = usageOf;
|
|
168
|
+
/** Events of a stream tell them as they go, each so far: the most of each. */
|
|
169
|
+
function merge(into, next) {
|
|
170
|
+
if (!next) {
|
|
171
|
+
return into;
|
|
172
|
+
}
|
|
173
|
+
if (!into) {
|
|
174
|
+
return { ...next };
|
|
175
|
+
}
|
|
176
|
+
return {
|
|
177
|
+
input: Math.max(into.input, next.input),
|
|
178
|
+
output: Math.max(into.output, next.output),
|
|
179
|
+
cacheRead: Math.max(into.cacheRead, next.cacheRead),
|
|
180
|
+
cacheWrite: Math.max(into.cacheWrite, next.cacheWrite),
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
ModelProxyUtil.merge = merge;
|
|
184
|
+
function total(usage) {
|
|
185
|
+
return usage.input + usage.output + usage.cacheRead + usage.cacheWrite;
|
|
186
|
+
}
|
|
187
|
+
ModelProxyUtil.total = total;
|
|
188
|
+
function cost(usage, price) {
|
|
189
|
+
var _a, _b, _c, _d;
|
|
190
|
+
if (!price) {
|
|
191
|
+
return 0;
|
|
192
|
+
}
|
|
193
|
+
return ((usage.input * ((_a = price.input) !== null && _a !== void 0 ? _a : 0) +
|
|
194
|
+
usage.output * ((_b = price.output) !== null && _b !== void 0 ? _b : 0) +
|
|
195
|
+
usage.cacheRead * ((_c = price.cacheRead) !== null && _c !== void 0 ? _c : 0) +
|
|
196
|
+
usage.cacheWrite * ((_d = price.cacheWrite) !== null && _d !== void 0 ? _d : 0)) /
|
|
197
|
+
1e6);
|
|
198
|
+
}
|
|
199
|
+
ModelProxyUtil.cost = cost;
|
|
200
|
+
/**
|
|
201
|
+
* The body of an OpenAI chat stream asking for its usage too: without stream_options.include_usage the stream
|
|
202
|
+
* tells none, and a call would go uncounted past every limit. Other bodies are sent as they came.
|
|
203
|
+
*/
|
|
204
|
+
function metered(api, body) {
|
|
205
|
+
if (api !== 'openai-completions') {
|
|
206
|
+
return body;
|
|
207
|
+
}
|
|
208
|
+
let parsed;
|
|
209
|
+
try {
|
|
210
|
+
parsed = JSON.parse(body.toString('utf8'));
|
|
211
|
+
}
|
|
212
|
+
catch (_a) {
|
|
213
|
+
return body;
|
|
214
|
+
}
|
|
215
|
+
if (!parsed || typeof parsed !== 'object' || parsed.stream !== true) {
|
|
216
|
+
return body;
|
|
217
|
+
}
|
|
218
|
+
const options = parsed.stream_options && typeof parsed.stream_options === 'object' ? parsed.stream_options : {};
|
|
219
|
+
return Buffer.from(JSON.stringify({ ...parsed, stream_options: { ...options, include_usage: true } }));
|
|
220
|
+
}
|
|
221
|
+
ModelProxyUtil.metered = metered;
|
|
222
|
+
/** The model a call names: in its path (Google), else in its body. */
|
|
223
|
+
function modelOf(body, rest) {
|
|
224
|
+
var _a;
|
|
225
|
+
const named = (_a = /\/models\/([^/:]+)/.exec(rest)) === null || _a === void 0 ? void 0 : _a[1];
|
|
226
|
+
if (named) {
|
|
227
|
+
return decodeURIComponent(named);
|
|
228
|
+
}
|
|
229
|
+
try {
|
|
230
|
+
const model = JSON.parse(body.toString('utf8')).model;
|
|
231
|
+
return typeof model === 'string' ? model : undefined;
|
|
232
|
+
}
|
|
233
|
+
catch (_b) {
|
|
234
|
+
return undefined;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
ModelProxyUtil.modelOf = modelOf;
|
|
238
|
+
/** An error as a model service gives one, so that the clients of every API read its message. */
|
|
239
|
+
function error(response, status, message, type = 'insufficient_quota') {
|
|
240
|
+
if (response.headersSent) {
|
|
241
|
+
response.destroy();
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
response.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
|
|
245
|
+
response.end(JSON.stringify({ type: 'error', error: { type, code: type, message } }));
|
|
246
|
+
}
|
|
247
|
+
ModelProxyUtil.error = error;
|
|
248
|
+
function sameKey(given, known) {
|
|
249
|
+
return timingSafeEqual(createHash('sha256').update(given).digest(), createHash('sha256').update(known).digest());
|
|
250
|
+
}
|
|
251
|
+
ModelProxyUtil.sameKey = sameKey;
|
|
252
|
+
})(ModelProxyUtil || (ModelProxyUtil = {}));
|
|
253
|
+
/**
|
|
254
|
+
* The models of the gateway, for its sandboxes: a call of a sandbox with the model key of its tenant goes to the
|
|
255
|
+
* provider with the gateway's key, which no sandbox has, and what it took is counted for the tenant, from the usage
|
|
256
|
+
* of the answer (a stream's too). A tenant out of its tokens of the month gets an error instead of a call.
|
|
257
|
+
*/
|
|
258
|
+
export class ModelProxy {
|
|
259
|
+
constructor(config, hooks, env = process.env) {
|
|
260
|
+
this.config = config;
|
|
261
|
+
this.hooks = hooks;
|
|
262
|
+
this.env = env;
|
|
263
|
+
}
|
|
264
|
+
get enabled() {
|
|
265
|
+
var _a;
|
|
266
|
+
return Object.keys((_a = this.config.providers) !== null && _a !== void 0 ? _a : {}).length > 0;
|
|
267
|
+
}
|
|
268
|
+
provider(id) {
|
|
269
|
+
var _a;
|
|
270
|
+
return new Map(Object.entries((_a = this.config.providers) !== null && _a !== void 0 ? _a : {})).get(id);
|
|
271
|
+
}
|
|
272
|
+
async handle(request, response) {
|
|
273
|
+
var _a, _b;
|
|
274
|
+
var _c, _d, _e, _f;
|
|
275
|
+
response.setHeader('Cache-Control', 'no-store');
|
|
276
|
+
const url = new URL((_c = request.url) !== null && _c !== void 0 ? _c : '/', 'http://gateway');
|
|
277
|
+
const given = ModelProxyUtil.presented(request);
|
|
278
|
+
const tenant = given ? this.hooks.tenantOfKey(given) : undefined;
|
|
279
|
+
if (!tenant) {
|
|
280
|
+
ModelProxyUtil.error(response, 401, 'This model key is not one of the gateway.', 'authentication_error');
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
const rest = url.pathname.slice(ModelProxyUtil.PATH.length);
|
|
284
|
+
if (rest === '' || rest === '/') {
|
|
285
|
+
if (request.method !== 'GET') {
|
|
286
|
+
ModelProxyUtil.error(response, 405, 'Read the catalog with GET.', 'invalid_request_error');
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
response.writeHead(200, { 'Content-Type': 'application/json' });
|
|
290
|
+
response.end(JSON.stringify(ModelProxyUtil.catalog(this.config)));
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
const id = rest.slice(1).split('/')[0];
|
|
294
|
+
const provider = this.provider(id);
|
|
295
|
+
if (!provider) {
|
|
296
|
+
ModelProxyUtil.error(response, 404, `The gateway has no provider of models ${id}.`, 'not_found_error');
|
|
297
|
+
return;
|
|
298
|
+
}
|
|
299
|
+
const refused = this.hooks.refuse(tenant.id);
|
|
300
|
+
if (refused) {
|
|
301
|
+
ModelProxyUtil.error(response, 429, refused);
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
304
|
+
const received = await this.body(request);
|
|
305
|
+
if (!received) {
|
|
306
|
+
ModelProxyUtil.error(response, 413, 'The request is too large.', 'invalid_request_error');
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
const body = ModelProxyUtil.metered(provider.api, received);
|
|
310
|
+
const path = rest.slice(1 + id.length);
|
|
311
|
+
const model = ModelProxyUtil.modelOf(body, path);
|
|
312
|
+
const headers = {};
|
|
313
|
+
for (const [name, value] of Object.entries(request.headers)) {
|
|
314
|
+
if (typeof value === 'string' && !DROPPED_REQUEST.has(name)) {
|
|
315
|
+
headers[name] = value;
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
Object.assign(headers, (_d = provider.headers) !== null && _d !== void 0 ? _d : {}, ModelProxyUtil.authHeaders(provider.api, ModelProxyUtil.key(provider.apiKey, this.env)));
|
|
319
|
+
const abort = new AbortController();
|
|
320
|
+
response.once('close', () => abort.abort());
|
|
321
|
+
let upstream;
|
|
322
|
+
try {
|
|
323
|
+
upstream = await fetch(ModelProxyUtil.target(provider.baseUrl, path, url.searchParams), {
|
|
324
|
+
method: request.method,
|
|
325
|
+
headers,
|
|
326
|
+
body: request.method === 'GET' || request.method === 'HEAD' ? undefined : new Uint8Array(body),
|
|
327
|
+
signal: abort.signal,
|
|
328
|
+
});
|
|
329
|
+
}
|
|
330
|
+
catch (error) {
|
|
331
|
+
ModelProxyUtil.error(response, 502, `The provider of models ${id} is not reachable: ${error.message}`, 'api_error');
|
|
332
|
+
return;
|
|
333
|
+
}
|
|
334
|
+
const out = {};
|
|
335
|
+
upstream.headers.forEach((value, name) => {
|
|
336
|
+
if (!DROPPED_RESPONSE.has(name)) {
|
|
337
|
+
out[name] = value;
|
|
338
|
+
}
|
|
339
|
+
});
|
|
340
|
+
response.writeHead(upstream.status, out);
|
|
341
|
+
const stream = ((_e = upstream.headers.get('content-type')) !== null && _e !== void 0 ? _e : '').includes('event-stream');
|
|
342
|
+
let usage;
|
|
343
|
+
let text = '';
|
|
344
|
+
const decoder = new TextDecoder();
|
|
345
|
+
const reader = (_a = upstream.body) === null || _a === void 0 ? void 0 : _a.getReader();
|
|
346
|
+
try {
|
|
347
|
+
while (reader) {
|
|
348
|
+
const { done, value } = await reader.read();
|
|
349
|
+
if (done) {
|
|
350
|
+
break;
|
|
351
|
+
}
|
|
352
|
+
if (!response.write(value) && !(await this.drained(response))) {
|
|
353
|
+
// The sandbox went away while the answer waited for it: what was seen counts.
|
|
354
|
+
break;
|
|
355
|
+
}
|
|
356
|
+
const chunk = decoder.decode(value, { stream: true });
|
|
357
|
+
if (stream) {
|
|
358
|
+
text += chunk;
|
|
359
|
+
const lines = text.split('\n');
|
|
360
|
+
text = (_f = lines.pop()) !== null && _f !== void 0 ? _f : '';
|
|
361
|
+
for (const line of lines) {
|
|
362
|
+
usage = ModelProxyUtil.merge(usage, this.event(line));
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
else if (text.length < MAX_READ) {
|
|
366
|
+
text += chunk;
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
if (stream) {
|
|
370
|
+
usage = ModelProxyUtil.merge(usage, this.event(text));
|
|
371
|
+
}
|
|
372
|
+
else if (upstream.ok) {
|
|
373
|
+
try {
|
|
374
|
+
usage = ModelProxyUtil.usageOf(JSON.parse(text));
|
|
375
|
+
}
|
|
376
|
+
catch (_g) {
|
|
377
|
+
// Not JSON: nothing to count.
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
response.end();
|
|
381
|
+
}
|
|
382
|
+
catch (_h) {
|
|
383
|
+
// The sandbox went away, or the provider did: what was seen counts.
|
|
384
|
+
response.destroy();
|
|
385
|
+
}
|
|
386
|
+
finally {
|
|
387
|
+
if (usage && ModelProxyUtil.total(usage) > 0) {
|
|
388
|
+
const price = (_b = provider.models.find(each => each.id === model)) === null || _b === void 0 ? void 0 : _b.cost;
|
|
389
|
+
this.hooks.record(tenant.id, usage, ModelProxyUtil.cost(usage, price));
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
/** Whether the response drained, false once it closed instead (its drain never comes then). */
|
|
394
|
+
drained(response) {
|
|
395
|
+
if (response.destroyed) {
|
|
396
|
+
return Promise.resolve(false);
|
|
397
|
+
}
|
|
398
|
+
return new Promise(resolve => {
|
|
399
|
+
const done = (drained) => {
|
|
400
|
+
response.off('drain', onDrain);
|
|
401
|
+
response.off('close', onClose);
|
|
402
|
+
resolve(drained);
|
|
403
|
+
};
|
|
404
|
+
const onDrain = () => done(true);
|
|
405
|
+
const onClose = () => done(false);
|
|
406
|
+
response.on('drain', onDrain);
|
|
407
|
+
response.on('close', onClose);
|
|
408
|
+
});
|
|
409
|
+
}
|
|
410
|
+
event(line) {
|
|
411
|
+
const trimmed = line.trim();
|
|
412
|
+
if (!trimmed.startsWith('data:')) {
|
|
413
|
+
return undefined;
|
|
414
|
+
}
|
|
415
|
+
try {
|
|
416
|
+
return ModelProxyUtil.usageOf(JSON.parse(trimmed.slice(5)));
|
|
417
|
+
}
|
|
418
|
+
catch (_a) {
|
|
419
|
+
return undefined;
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
async body(request) {
|
|
423
|
+
const chunks = [];
|
|
424
|
+
let size = 0;
|
|
425
|
+
for await (const chunk of request) {
|
|
426
|
+
size += chunk.length;
|
|
427
|
+
if (size > MAX_BODY) {
|
|
428
|
+
return undefined;
|
|
429
|
+
}
|
|
430
|
+
chunks.push(chunk);
|
|
431
|
+
}
|
|
432
|
+
return Buffer.concat(chunks);
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
//# sourceMappingURL=model-proxy.js.map
|
|
@@ -3,6 +3,11 @@ export interface SandboxTenant {
|
|
|
3
3
|
id: string;
|
|
4
4
|
account: string;
|
|
5
5
|
token: string;
|
|
6
|
+
/**
|
|
7
|
+
* More of the environment of its Ta service: TA_MODEL_PROXY_URL and TA_MODEL_PROXY_KEY, by which it takes the
|
|
8
|
+
* models of the gateway (ta-host GatewayModels). A provider that makes a sandbox once remakes it when they change.
|
|
9
|
+
*/
|
|
10
|
+
env?: Record<string, string>;
|
|
6
11
|
}
|
|
7
12
|
/** Where the Ta service of a tenant answers: `url` is its http(s) address, the gateway connects to `/api/ws` there. */
|
|
8
13
|
export interface SandboxEndpoint {
|
|
@@ -25,6 +30,8 @@ export interface SandboxProvider {
|
|
|
25
30
|
readonly id: string;
|
|
26
31
|
readonly name: string;
|
|
27
32
|
readonly type: string;
|
|
33
|
+
/** Where its sandboxes reach the gateway, for its models (`gatewayUrl` of sandboxes.json); else as the gateway reckons for its type. */
|
|
34
|
+
readonly gatewayUrl?: string;
|
|
28
35
|
/** How long its Ta service has to answer once started; default two minutes, for a first pull of an image. */
|
|
29
36
|
readonly readyTimeoutMs?: number;
|
|
30
37
|
/**
|