@celljs/ta-gateway 4.15.2 → 4.17.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.
Files changed (81) hide show
  1. package/README.en.md +5 -2
  2. package/README.md +5 -2
  3. package/esm/node/command-sandbox.d.ts +1 -0
  4. package/esm/node/command-sandbox.js +10 -1
  5. package/esm/node/docker-engine.d.ts +10 -1
  6. package/esm/node/docker-engine.js +18 -1
  7. package/esm/node/docker-sandbox.d.ts +13 -1
  8. package/esm/node/docker-sandbox.js +35 -2
  9. package/esm/node/egress-proxy.d.ts +98 -0
  10. package/esm/node/egress-proxy.js +428 -0
  11. package/esm/node/environments.d.ts +5 -0
  12. package/esm/node/environments.js +7 -3
  13. package/esm/node/gateway-cli.js +12 -5
  14. package/esm/node/gateway-exec.d.ts +19 -0
  15. package/esm/node/gateway-exec.js +65 -0
  16. package/esm/node/gateway-policy.d.ts +7 -1
  17. package/esm/node/gateway-policy.js +12 -2
  18. package/esm/node/gateway-quotas.d.ts +15 -2
  19. package/esm/node/gateway-quotas.js +51 -3
  20. package/esm/node/gateway-server.d.ts +43 -1
  21. package/esm/node/gateway-server.js +179 -10
  22. package/esm/node/gateway-service-util.d.ts +41 -0
  23. package/esm/node/gateway-service-util.js +178 -0
  24. package/esm/node/gateway-service.d.ts +13 -41
  25. package/esm/node/gateway-service.js +41 -176
  26. package/esm/node/gateway-socket.d.ts +1 -1
  27. package/esm/node/gateway-socket.js +1 -1
  28. package/esm/node/index.d.ts +4 -0
  29. package/esm/node/index.js +4 -0
  30. package/esm/node/kubernetes-api.d.ts +35 -0
  31. package/esm/node/kubernetes-api.js +115 -0
  32. package/esm/node/kubernetes-sandbox.d.ts +198 -0
  33. package/esm/node/kubernetes-sandbox.js +279 -0
  34. package/esm/node/local-sandbox.d.ts +1 -0
  35. package/esm/node/local-sandbox.js +2 -1
  36. package/esm/node/model-proxy.d.ts +105 -0
  37. package/esm/node/model-proxy.js +435 -0
  38. package/esm/node/sandbox-provider.d.ts +17 -0
  39. package/esm/node/sandbox-provider.js +2 -1
  40. package/esm/node/tenant-store.d.ts +22 -0
  41. package/esm/node/tenant-store.js +25 -0
  42. package/lib/node/command-sandbox.d.ts +1 -0
  43. package/lib/node/command-sandbox.js +10 -1
  44. package/lib/node/docker-engine.d.ts +10 -1
  45. package/lib/node/docker-engine.js +18 -1
  46. package/lib/node/docker-sandbox.d.ts +13 -1
  47. package/lib/node/docker-sandbox.js +35 -2
  48. package/lib/node/egress-proxy.d.ts +99 -0
  49. package/lib/node/egress-proxy.js +433 -0
  50. package/lib/node/environments.d.ts +5 -0
  51. package/lib/node/environments.js +7 -3
  52. package/lib/node/gateway-cli.js +12 -5
  53. package/lib/node/gateway-exec.d.ts +20 -0
  54. package/lib/node/gateway-exec.js +69 -0
  55. package/lib/node/gateway-policy.d.ts +7 -1
  56. package/lib/node/gateway-policy.js +12 -2
  57. package/lib/node/gateway-quotas.d.ts +15 -2
  58. package/lib/node/gateway-quotas.js +51 -3
  59. package/lib/node/gateway-server.d.ts +43 -1
  60. package/lib/node/gateway-server.js +177 -8
  61. package/lib/node/gateway-service-util.d.ts +42 -0
  62. package/lib/node/gateway-service-util.js +182 -0
  63. package/lib/node/gateway-service.d.ts +13 -41
  64. package/lib/node/gateway-service.js +63 -199
  65. package/lib/node/gateway-socket.d.ts +1 -1
  66. package/lib/node/gateway-socket.js +10 -10
  67. package/lib/node/index.d.ts +4 -0
  68. package/lib/node/index.js +4 -0
  69. package/lib/node/kubernetes-api.d.ts +36 -0
  70. package/lib/node/kubernetes-api.js +120 -0
  71. package/lib/node/kubernetes-sandbox.d.ts +199 -0
  72. package/lib/node/kubernetes-sandbox.js +283 -0
  73. package/lib/node/local-sandbox.d.ts +1 -0
  74. package/lib/node/local-sandbox.js +2 -1
  75. package/lib/node/model-proxy.d.ts +106 -0
  76. package/lib/node/model-proxy.js +440 -0
  77. package/lib/node/sandbox-provider.d.ts +17 -0
  78. package/lib/node/sandbox-provider.js +2 -1
  79. package/lib/node/tenant-store.d.ts +22 -0
  80. package/lib/node/tenant-store.js +25 -0
  81. package/package.json +4 -4
@@ -0,0 +1,106 @@
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
+ }
106
+ //# sourceMappingURL=model-proxy.d.ts.map
@@ -0,0 +1,440 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ModelProxy = exports.ModelProxyUtil = exports.ModelConfigError = void 0;
4
+ const node_crypto_1 = require("node:crypto");
5
+ const node_fs_1 = require("node:fs");
6
+ const node_path_1 = require("node:path");
7
+ class ModelConfigError extends Error {
8
+ }
9
+ exports.ModelConfigError = ModelConfigError;
10
+ const MAX_BODY = 32 * 1024 * 1024;
11
+ /** Of an answer that is not a stream, at most this is read for its usage. */
12
+ const MAX_READ = 8 * 1024 * 1024;
13
+ const DROPPED_REQUEST = new Set([
14
+ 'host',
15
+ 'authorization',
16
+ 'x-api-key',
17
+ 'x-goog-api-key',
18
+ 'api-key',
19
+ 'cookie',
20
+ 'connection',
21
+ 'content-length',
22
+ 'accept-encoding',
23
+ 'transfer-encoding',
24
+ 'keep-alive',
25
+ 'upgrade',
26
+ 'proxy-authorization',
27
+ 'x-forwarded-for',
28
+ 'x-forwarded-proto',
29
+ 'x-forwarded-host',
30
+ ]);
31
+ const DROPPED_RESPONSE = new Set(['content-encoding', 'content-length', 'transfer-encoding', 'connection', 'keep-alive', 'set-cookie']);
32
+ var ModelProxyUtil;
33
+ (function (ModelProxyUtil) {
34
+ ModelProxyUtil.PATH = '/api/models';
35
+ const ID = /^[a-z0-9][a-z0-9._-]{0,63}$/i;
36
+ function read(dir) {
37
+ var _a;
38
+ const file = (0, node_path_1.join)(dir, 'models.json');
39
+ if (!(0, node_fs_1.existsSync)(file)) {
40
+ return {};
41
+ }
42
+ let config;
43
+ try {
44
+ config = JSON.parse((0, node_fs_1.readFileSync)(file, 'utf8'));
45
+ }
46
+ catch (error) {
47
+ throw new ModelConfigError(`${file} is not JSON: ${error.message}`);
48
+ }
49
+ for (const [id, provider] of Object.entries((_a = config.providers) !== null && _a !== void 0 ? _a : {})) {
50
+ if (!ID.test(id)) {
51
+ throw new ModelConfigError(`"${id}" cannot name a provider of models: letters, digits, . _ and -.`);
52
+ }
53
+ if (typeof (provider === null || provider === void 0 ? void 0 : provider.baseUrl) !== 'string' ||
54
+ !/^https?:\/\//.test(provider.baseUrl) ||
55
+ typeof provider.api !== 'string' ||
56
+ !Array.isArray(provider.models)) {
57
+ throw new ModelConfigError(`The provider of models "${id}" needs baseUrl (http or https), api and models, as pi's models.json.`);
58
+ }
59
+ }
60
+ return config;
61
+ }
62
+ ModelProxyUtil.read = read;
63
+ /** The key: the variable of the environment it names, else itself. */
64
+ function key(value, env = process.env) {
65
+ if (!value) {
66
+ return undefined;
67
+ }
68
+ const name = value.startsWith('$') ? value.slice(1) : value;
69
+ if (/^[A-Z][A-Z0-9_]*$/.test(name) && env[name]) {
70
+ return env[name];
71
+ }
72
+ return value.startsWith('$') ? undefined : value;
73
+ }
74
+ ModelProxyUtil.key = key;
75
+ function catalog(config) {
76
+ var _a;
77
+ return {
78
+ providers: Object.entries((_a = config.providers) !== null && _a !== void 0 ? _a : {}).map(([id, provider]) => ({
79
+ id,
80
+ name: provider.name,
81
+ api: provider.api,
82
+ models: provider.models.map(model => ({ ...model })),
83
+ })),
84
+ };
85
+ }
86
+ ModelProxyUtil.catalog = catalog;
87
+ /** The key a sandbox sent, however its API sends one. */
88
+ function presented(request) {
89
+ var _a, _b;
90
+ const bearer = request.headers.authorization;
91
+ if (bearer === null || bearer === void 0 ? void 0 : bearer.startsWith('Bearer ')) {
92
+ return bearer.slice('Bearer '.length).trim();
93
+ }
94
+ for (const name of ['x-api-key', 'x-goog-api-key', 'api-key']) {
95
+ const value = request.headers[name];
96
+ if (typeof value === 'string' && value) {
97
+ return value.trim();
98
+ }
99
+ }
100
+ return (_b = new URL((_a = request.url) !== null && _a !== void 0 ? _a : '/', 'http://gateway').searchParams.get('key')) !== null && _b !== void 0 ? _b : undefined;
101
+ }
102
+ ModelProxyUtil.presented = presented;
103
+ /** How the provider takes its key. */
104
+ function authHeaders(api, key) {
105
+ if (!key) {
106
+ return {};
107
+ }
108
+ if (api.startsWith('anthropic')) {
109
+ return { 'x-api-key': key };
110
+ }
111
+ if (api.startsWith('google')) {
112
+ return { 'x-goog-api-key': key };
113
+ }
114
+ if (api.includes('azure')) {
115
+ return { 'api-key': key };
116
+ }
117
+ return { authorization: `Bearer ${key}` };
118
+ }
119
+ ModelProxyUtil.authHeaders = authHeaders;
120
+ /** Where a call goes: the rest of its path on the provider's base, its query without a key. */
121
+ function target(baseUrl, rest, query) {
122
+ const params = new URLSearchParams(query);
123
+ params.delete('key');
124
+ const search = params.toString();
125
+ return `${baseUrl.replace(/\/+$/, '')}${rest}${search ? `?${search}` : ''}`;
126
+ }
127
+ ModelProxyUtil.target = target;
128
+ function number(value) {
129
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0;
130
+ }
131
+ /**
132
+ * The tokens an object of an answer tells (OpenAI chat or responses, Anthropic, Google), cached input apart;
133
+ * undefined for one that tells none.
134
+ */
135
+ function usageOf(value) {
136
+ var _a, _b, _c, _d;
137
+ var _e, _f, _g;
138
+ if (!value || typeof value !== 'object') {
139
+ return undefined;
140
+ }
141
+ const object = value;
142
+ 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;
143
+ if (!usage || typeof usage !== 'object') {
144
+ return undefined;
145
+ }
146
+ if ('promptTokenCount' in usage || 'candidatesTokenCount' in usage) {
147
+ const cached = number(usage.cachedContentTokenCount);
148
+ return {
149
+ input: Math.max(0, number(usage.promptTokenCount) - cached),
150
+ output: number(usage.candidatesTokenCount) + number(usage.thoughtsTokenCount),
151
+ cacheRead: cached,
152
+ cacheWrite: 0,
153
+ };
154
+ }
155
+ if ('prompt_tokens' in usage || 'completion_tokens' in usage) {
156
+ const cached = number((_c = usage.prompt_tokens_details) === null || _c === void 0 ? void 0 : _c.cached_tokens);
157
+ return { input: Math.max(0, number(usage.prompt_tokens) - cached), output: number(usage.completion_tokens), cacheRead: cached, cacheWrite: 0 };
158
+ }
159
+ if ('input_tokens' in usage || 'output_tokens' in usage) {
160
+ // The responses API counts cached input in input_tokens; Anthropic apart, in cache_read_input_tokens.
161
+ const cached = number((_d = usage.input_tokens_details) === null || _d === void 0 ? void 0 : _d.cached_tokens);
162
+ return {
163
+ input: Math.max(0, number(usage.input_tokens) - cached),
164
+ output: number(usage.output_tokens),
165
+ cacheRead: cached + number(usage.cache_read_input_tokens),
166
+ cacheWrite: number(usage.cache_creation_input_tokens),
167
+ };
168
+ }
169
+ return undefined;
170
+ }
171
+ ModelProxyUtil.usageOf = usageOf;
172
+ /** Events of a stream tell them as they go, each so far: the most of each. */
173
+ function merge(into, next) {
174
+ if (!next) {
175
+ return into;
176
+ }
177
+ if (!into) {
178
+ return { ...next };
179
+ }
180
+ return {
181
+ input: Math.max(into.input, next.input),
182
+ output: Math.max(into.output, next.output),
183
+ cacheRead: Math.max(into.cacheRead, next.cacheRead),
184
+ cacheWrite: Math.max(into.cacheWrite, next.cacheWrite),
185
+ };
186
+ }
187
+ ModelProxyUtil.merge = merge;
188
+ function total(usage) {
189
+ return usage.input + usage.output + usage.cacheRead + usage.cacheWrite;
190
+ }
191
+ ModelProxyUtil.total = total;
192
+ function cost(usage, price) {
193
+ var _a, _b, _c, _d;
194
+ if (!price) {
195
+ return 0;
196
+ }
197
+ return ((usage.input * ((_a = price.input) !== null && _a !== void 0 ? _a : 0) +
198
+ usage.output * ((_b = price.output) !== null && _b !== void 0 ? _b : 0) +
199
+ usage.cacheRead * ((_c = price.cacheRead) !== null && _c !== void 0 ? _c : 0) +
200
+ usage.cacheWrite * ((_d = price.cacheWrite) !== null && _d !== void 0 ? _d : 0)) /
201
+ 1e6);
202
+ }
203
+ ModelProxyUtil.cost = cost;
204
+ /**
205
+ * The body of an OpenAI chat stream asking for its usage too: without stream_options.include_usage the stream
206
+ * tells none, and a call would go uncounted past every limit. Other bodies are sent as they came.
207
+ */
208
+ function metered(api, body) {
209
+ if (api !== 'openai-completions') {
210
+ return body;
211
+ }
212
+ let parsed;
213
+ try {
214
+ parsed = JSON.parse(body.toString('utf8'));
215
+ }
216
+ catch (_a) {
217
+ return body;
218
+ }
219
+ if (!parsed || typeof parsed !== 'object' || parsed.stream !== true) {
220
+ return body;
221
+ }
222
+ const options = parsed.stream_options && typeof parsed.stream_options === 'object' ? parsed.stream_options : {};
223
+ return Buffer.from(JSON.stringify({ ...parsed, stream_options: { ...options, include_usage: true } }));
224
+ }
225
+ ModelProxyUtil.metered = metered;
226
+ /** The model a call names: in its path (Google), else in its body. */
227
+ function modelOf(body, rest) {
228
+ var _a;
229
+ const named = (_a = /\/models\/([^/:]+)/.exec(rest)) === null || _a === void 0 ? void 0 : _a[1];
230
+ if (named) {
231
+ return decodeURIComponent(named);
232
+ }
233
+ try {
234
+ const model = JSON.parse(body.toString('utf8')).model;
235
+ return typeof model === 'string' ? model : undefined;
236
+ }
237
+ catch (_b) {
238
+ return undefined;
239
+ }
240
+ }
241
+ ModelProxyUtil.modelOf = modelOf;
242
+ /** An error as a model service gives one, so that the clients of every API read its message. */
243
+ function error(response, status, message, type = 'insufficient_quota') {
244
+ if (response.headersSent) {
245
+ response.destroy();
246
+ return;
247
+ }
248
+ response.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
249
+ response.end(JSON.stringify({ type: 'error', error: { type, code: type, message } }));
250
+ }
251
+ ModelProxyUtil.error = error;
252
+ function sameKey(given, known) {
253
+ return (0, node_crypto_1.timingSafeEqual)((0, node_crypto_1.createHash)('sha256').update(given).digest(), (0, node_crypto_1.createHash)('sha256').update(known).digest());
254
+ }
255
+ ModelProxyUtil.sameKey = sameKey;
256
+ })(ModelProxyUtil || (exports.ModelProxyUtil = ModelProxyUtil = {}));
257
+ /**
258
+ * The models of the gateway, for its sandboxes: a call of a sandbox with the model key of its tenant goes to the
259
+ * provider with the gateway's key, which no sandbox has, and what it took is counted for the tenant, from the usage
260
+ * of the answer (a stream's too). A tenant out of its tokens of the month gets an error instead of a call.
261
+ */
262
+ class ModelProxy {
263
+ constructor(config, hooks, env = process.env) {
264
+ this.config = config;
265
+ this.hooks = hooks;
266
+ this.env = env;
267
+ }
268
+ get enabled() {
269
+ var _a;
270
+ return Object.keys((_a = this.config.providers) !== null && _a !== void 0 ? _a : {}).length > 0;
271
+ }
272
+ provider(id) {
273
+ var _a;
274
+ return new Map(Object.entries((_a = this.config.providers) !== null && _a !== void 0 ? _a : {})).get(id);
275
+ }
276
+ async handle(request, response) {
277
+ var _a, _b;
278
+ var _c, _d, _e, _f;
279
+ response.setHeader('Cache-Control', 'no-store');
280
+ const url = new URL((_c = request.url) !== null && _c !== void 0 ? _c : '/', 'http://gateway');
281
+ const given = ModelProxyUtil.presented(request);
282
+ const tenant = given ? this.hooks.tenantOfKey(given) : undefined;
283
+ if (!tenant) {
284
+ ModelProxyUtil.error(response, 401, 'This model key is not one of the gateway.', 'authentication_error');
285
+ return;
286
+ }
287
+ const rest = url.pathname.slice(ModelProxyUtil.PATH.length);
288
+ if (rest === '' || rest === '/') {
289
+ if (request.method !== 'GET') {
290
+ ModelProxyUtil.error(response, 405, 'Read the catalog with GET.', 'invalid_request_error');
291
+ return;
292
+ }
293
+ response.writeHead(200, { 'Content-Type': 'application/json' });
294
+ response.end(JSON.stringify(ModelProxyUtil.catalog(this.config)));
295
+ return;
296
+ }
297
+ const id = rest.slice(1).split('/')[0];
298
+ const provider = this.provider(id);
299
+ if (!provider) {
300
+ ModelProxyUtil.error(response, 404, `The gateway has no provider of models ${id}.`, 'not_found_error');
301
+ return;
302
+ }
303
+ const refused = this.hooks.refuse(tenant.id);
304
+ if (refused) {
305
+ ModelProxyUtil.error(response, 429, refused);
306
+ return;
307
+ }
308
+ const received = await this.body(request);
309
+ if (!received) {
310
+ ModelProxyUtil.error(response, 413, 'The request is too large.', 'invalid_request_error');
311
+ return;
312
+ }
313
+ const body = ModelProxyUtil.metered(provider.api, received);
314
+ const path = rest.slice(1 + id.length);
315
+ const model = ModelProxyUtil.modelOf(body, path);
316
+ const headers = {};
317
+ for (const [name, value] of Object.entries(request.headers)) {
318
+ if (typeof value === 'string' && !DROPPED_REQUEST.has(name)) {
319
+ headers[name] = value;
320
+ }
321
+ }
322
+ Object.assign(headers, (_d = provider.headers) !== null && _d !== void 0 ? _d : {}, ModelProxyUtil.authHeaders(provider.api, ModelProxyUtil.key(provider.apiKey, this.env)));
323
+ const abort = new AbortController();
324
+ response.once('close', () => abort.abort());
325
+ let upstream;
326
+ try {
327
+ upstream = await fetch(ModelProxyUtil.target(provider.baseUrl, path, url.searchParams), {
328
+ method: request.method,
329
+ headers,
330
+ body: request.method === 'GET' || request.method === 'HEAD' ? undefined : new Uint8Array(body),
331
+ signal: abort.signal,
332
+ });
333
+ }
334
+ catch (error) {
335
+ ModelProxyUtil.error(response, 502, `The provider of models ${id} is not reachable: ${error.message}`, 'api_error');
336
+ return;
337
+ }
338
+ const out = {};
339
+ upstream.headers.forEach((value, name) => {
340
+ if (!DROPPED_RESPONSE.has(name)) {
341
+ out[name] = value;
342
+ }
343
+ });
344
+ response.writeHead(upstream.status, out);
345
+ const stream = ((_e = upstream.headers.get('content-type')) !== null && _e !== void 0 ? _e : '').includes('event-stream');
346
+ let usage;
347
+ let text = '';
348
+ const decoder = new TextDecoder();
349
+ const reader = (_a = upstream.body) === null || _a === void 0 ? void 0 : _a.getReader();
350
+ try {
351
+ while (reader) {
352
+ const { done, value } = await reader.read();
353
+ if (done) {
354
+ break;
355
+ }
356
+ if (!response.write(value) && !(await this.drained(response))) {
357
+ // The sandbox went away while the answer waited for it: what was seen counts.
358
+ break;
359
+ }
360
+ const chunk = decoder.decode(value, { stream: true });
361
+ if (stream) {
362
+ text += chunk;
363
+ const lines = text.split('\n');
364
+ text = (_f = lines.pop()) !== null && _f !== void 0 ? _f : '';
365
+ for (const line of lines) {
366
+ usage = ModelProxyUtil.merge(usage, this.event(line));
367
+ }
368
+ }
369
+ else if (text.length < MAX_READ) {
370
+ text += chunk;
371
+ }
372
+ }
373
+ if (stream) {
374
+ usage = ModelProxyUtil.merge(usage, this.event(text));
375
+ }
376
+ else if (upstream.ok) {
377
+ try {
378
+ usage = ModelProxyUtil.usageOf(JSON.parse(text));
379
+ }
380
+ catch (_g) {
381
+ // Not JSON: nothing to count.
382
+ }
383
+ }
384
+ response.end();
385
+ }
386
+ catch (_h) {
387
+ // The sandbox went away, or the provider did: what was seen counts.
388
+ response.destroy();
389
+ }
390
+ finally {
391
+ if (usage && ModelProxyUtil.total(usage) > 0) {
392
+ const price = (_b = provider.models.find(each => each.id === model)) === null || _b === void 0 ? void 0 : _b.cost;
393
+ this.hooks.record(tenant.id, usage, ModelProxyUtil.cost(usage, price));
394
+ }
395
+ }
396
+ }
397
+ /** Whether the response drained, false once it closed instead (its drain never comes then). */
398
+ drained(response) {
399
+ if (response.destroyed) {
400
+ return Promise.resolve(false);
401
+ }
402
+ return new Promise(resolve => {
403
+ const done = (drained) => {
404
+ response.off('drain', onDrain);
405
+ response.off('close', onClose);
406
+ resolve(drained);
407
+ };
408
+ const onDrain = () => done(true);
409
+ const onClose = () => done(false);
410
+ response.on('drain', onDrain);
411
+ response.on('close', onClose);
412
+ });
413
+ }
414
+ event(line) {
415
+ const trimmed = line.trim();
416
+ if (!trimmed.startsWith('data:')) {
417
+ return undefined;
418
+ }
419
+ try {
420
+ return ModelProxyUtil.usageOf(JSON.parse(trimmed.slice(5)));
421
+ }
422
+ catch (_a) {
423
+ return undefined;
424
+ }
425
+ }
426
+ async body(request) {
427
+ const chunks = [];
428
+ let size = 0;
429
+ for await (const chunk of request) {
430
+ size += chunk.length;
431
+ if (size > MAX_BODY) {
432
+ return undefined;
433
+ }
434
+ chunks.push(chunk);
435
+ }
436
+ return Buffer.concat(chunks);
437
+ }
438
+ }
439
+ exports.ModelProxy = ModelProxy;
440
+ //# sourceMappingURL=model-proxy.js.map
@@ -1,8 +1,15 @@
1
+ import type { EgressConfig } from './egress-proxy';
1
2
  /** A tenant, as a provider of sandboxes sees it: `token` is the one its Ta service must take (TA_SERVE_TOKEN). */
2
3
  export interface SandboxTenant {
3
4
  id: string;
4
5
  account: string;
5
6
  token: string;
7
+ /**
8
+ * More of the environment of its Ta service: TA_MODEL_PROXY_URL and TA_MODEL_PROXY_KEY, by which it takes the
9
+ * models of the gateway (ta-host GatewayModels), and HTTPS_PROXY and the like, by which it goes out through the
10
+ * gateway. A provider that makes a sandbox once remakes it when they change.
11
+ */
12
+ env?: Record<string, string>;
6
13
  }
7
14
  /** Where the Ta service of a tenant answers: `url` is its http(s) address, the gateway connects to `/api/ws` there. */
8
15
  export interface SandboxEndpoint {
@@ -25,6 +32,8 @@ export interface SandboxProvider {
25
32
  readonly id: string;
26
33
  readonly name: string;
27
34
  readonly type: string;
35
+ /** Where its sandboxes reach the gateway, for its models (`gatewayUrl` of sandboxes.json); else as the gateway reckons for its type. */
36
+ readonly gatewayUrl?: string;
28
37
  /** How long its Ta service has to answer once started; default two minutes, for a first pull of an image. */
29
38
  readonly readyTimeoutMs?: number;
30
39
  /**
@@ -46,6 +55,8 @@ export interface SandboxProvider {
46
55
  export interface SandboxContext {
47
56
  /** The directory of the gateway: a module's path is relative to it, `local` keeps its tenants there. */
48
57
  dir: string;
58
+ /** Where sandboxes.json is, when not in `dir`: a module's path is relative to it then. */
59
+ config?: string;
49
60
  /** How to run `ta`: the Node.js executable and the entry of the command. */
50
61
  taCommand: string[];
51
62
  }
@@ -65,6 +76,12 @@ export interface SandboxesConfig {
65
76
  ownEnvironments?: boolean;
66
77
  /** Stops a sandbox nobody is connected to after this long; 0, the default, keeps it running (scheduled tasks, the double's work). */
67
78
  idleMinutes?: number;
79
+ /**
80
+ * Whether the sandboxes go out through the proxy of the gateway, with credentials of their epoch, and the private
81
+ * networks they may reach too: `true` or `{ "networks": ["10.0.0.0/8"] }`. The firewall of the machine is to let
82
+ * them out to the gateway only (docs/design/ta-cloud.md 3.5).
83
+ */
84
+ egress?: EgressConfig;
68
85
  }
69
86
  export declare class SandboxConfigError extends Error {
70
87
  }
@@ -53,10 +53,11 @@ var SandboxProviders;
53
53
  SandboxProviders.create = create;
54
54
  /** `{ "type": "module", "path": "./my-sandbox.mjs" }`: its default export is a SandboxProviderFactory. */
55
55
  async function loadModule(entry, context) {
56
+ var _a;
56
57
  if (typeof entry.path !== 'string' || !entry.path) {
57
58
  throw new SandboxConfigError('A provider of the type "module" names its file in "path".');
58
59
  }
59
- const path = (0, node_path_1.isAbsolute)(entry.path) ? entry.path : (0, node_path_1.join)(context.dir, entry.path);
60
+ const path = (0, node_path_1.isAbsolute)(entry.path) ? entry.path : (0, node_path_1.join)((_a = context.config) !== null && _a !== void 0 ? _a : context.dir, entry.path);
60
61
  const loaded = (await import((0, node_url_1.pathToFileURL)(path).href));
61
62
  if (typeof loaded.default !== 'function') {
62
63
  throw new SandboxConfigError(`${path} has no default export of a function (id, config, context) => SandboxProvider.`);
@@ -5,6 +5,11 @@ export interface TenantMeter {
5
5
  month: string;
6
6
  runMs: number;
7
7
  bonusMinutes: number;
8
+ /** Tokens and dollars of calls of models through the gateway. */
9
+ tokens?: number;
10
+ cost?: number;
11
+ /** Bytes its sandbox moved through the proxy of the gateway. */
12
+ egressBytes?: number;
8
13
  }
9
14
  /** A tenant: an account and its Ta, wherever it runs. */
10
15
  export interface Tenant {
@@ -22,6 +27,16 @@ export interface Tenant {
22
27
  limits?: TaGatewayLimits;
23
28
  suspended?: boolean;
24
29
  meter?: TenantMeter;
30
+ /** What its sandbox calls the models of the gateway with: it reaches no key of a provider. */
31
+ modelKey?: string;
32
+ /**
33
+ * What its sandbox goes out through the proxy of the gateway with: the epoch of the sandbox, one more each time
34
+ * the gateway makes it anew, and its secret. Those of an epoch before are refused.
35
+ */
36
+ egress?: {
37
+ epoch: number;
38
+ secret: string;
39
+ };
25
40
  }
26
41
  /** Files written whole or not at all, readable by this user only. */
27
42
  export declare function writePrivate(file: string, data: unknown): void;
@@ -42,6 +57,13 @@ export declare class TenantStore {
42
57
  avatar?: string;
43
58
  }, now?: number): Tenant;
44
59
  update(id: string, change: Partial<Omit<Tenant, 'id' | 'account' | 'token'>>): Tenant;
60
+ /** Its model key, made for a tenant of before. */
61
+ modelKey(id: string): string;
62
+ /** The credentials of its sandbox's way out: of a new epoch when `renew` (a sandbox made anew), or when it has none. */
63
+ egressKey(id: string, renew: boolean): {
64
+ epoch: number;
65
+ secret: string;
66
+ };
45
67
  list(): Tenant[];
46
68
  protected save(tenant: Tenant): void;
47
69
  }