@celljs/ta-gateway 4.15.1 → 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.
Files changed (67) hide show
  1. package/esm/node/command-sandbox.d.ts +6 -2
  2. package/esm/node/command-sandbox.js +26 -4
  3. package/esm/node/docker-engine.d.ts +50 -0
  4. package/esm/node/docker-engine.js +98 -11
  5. package/esm/node/docker-sandbox.d.ts +6 -1
  6. package/esm/node/docker-sandbox.js +23 -3
  7. package/esm/node/environments.d.ts +36 -2
  8. package/esm/node/environments.js +192 -14
  9. package/esm/node/gateway-audit.d.ts +12 -0
  10. package/esm/node/gateway-audit.js +47 -0
  11. package/esm/node/gateway-cli.d.ts +2 -0
  12. package/esm/node/gateway-cli.js +1 -0
  13. package/esm/node/gateway-exec.d.ts +19 -0
  14. package/esm/node/gateway-exec.js +65 -0
  15. package/esm/node/gateway-policy.d.ts +47 -0
  16. package/esm/node/gateway-policy.js +152 -0
  17. package/esm/node/gateway-quotas.d.ts +40 -0
  18. package/esm/node/gateway-quotas.js +135 -0
  19. package/esm/node/gateway-server.d.ts +28 -2
  20. package/esm/node/gateway-server.js +112 -9
  21. package/esm/node/gateway-service.d.ts +99 -16
  22. package/esm/node/gateway-service.js +385 -45
  23. package/esm/node/gateway-socket.d.ts +7 -1
  24. package/esm/node/gateway-socket.js +40 -1
  25. package/esm/node/gateway-usage.d.ts +37 -0
  26. package/esm/node/gateway-usage.js +137 -0
  27. package/esm/node/local-sandbox.d.ts +13 -0
  28. package/esm/node/local-sandbox.js +38 -2
  29. package/esm/node/model-proxy.d.ts +105 -0
  30. package/esm/node/model-proxy.js +435 -0
  31. package/esm/node/sandbox-provider.d.ts +17 -0
  32. package/esm/node/tenant-store.d.ts +19 -1
  33. package/esm/node/tenant-store.js +10 -0
  34. package/lib/node/command-sandbox.d.ts +6 -2
  35. package/lib/node/command-sandbox.js +26 -4
  36. package/lib/node/docker-engine.d.ts +50 -0
  37. package/lib/node/docker-engine.js +98 -11
  38. package/lib/node/docker-sandbox.d.ts +6 -1
  39. package/lib/node/docker-sandbox.js +23 -3
  40. package/lib/node/environments.d.ts +36 -2
  41. package/lib/node/environments.js +191 -13
  42. package/lib/node/gateway-audit.d.ts +13 -0
  43. package/lib/node/gateway-audit.js +51 -0
  44. package/lib/node/gateway-cli.d.ts +2 -0
  45. package/lib/node/gateway-cli.js +1 -0
  46. package/lib/node/gateway-exec.d.ts +20 -0
  47. package/lib/node/gateway-exec.js +69 -0
  48. package/lib/node/gateway-policy.d.ts +48 -0
  49. package/lib/node/gateway-policy.js +157 -0
  50. package/lib/node/gateway-quotas.d.ts +41 -0
  51. package/lib/node/gateway-quotas.js +139 -0
  52. package/lib/node/gateway-server.d.ts +28 -2
  53. package/lib/node/gateway-server.js +112 -9
  54. package/lib/node/gateway-service.d.ts +99 -16
  55. package/lib/node/gateway-service.js +384 -44
  56. package/lib/node/gateway-socket.d.ts +7 -1
  57. package/lib/node/gateway-socket.js +40 -1
  58. package/lib/node/gateway-usage.d.ts +38 -0
  59. package/lib/node/gateway-usage.js +141 -0
  60. package/lib/node/local-sandbox.d.ts +13 -0
  61. package/lib/node/local-sandbox.js +40 -3
  62. package/lib/node/model-proxy.d.ts +106 -0
  63. package/lib/node/model-proxy.js +440 -0
  64. package/lib/node/sandbox-provider.d.ts +17 -0
  65. package/lib/node/tenant-store.d.ts +19 -1
  66. package/lib/node/tenant-store.js +10 -0
  67. package/package.json +4 -4
@@ -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 {
@@ -10,6 +15,12 @@ export interface SandboxEndpoint {
10
15
  token: string;
11
16
  }
12
17
  export type SandboxState = 'running' | 'stopped' | 'missing';
18
+ /** What a running sandbox takes: CPU in percent of one CPU, memory in bytes. */
19
+ export interface SandboxUsage {
20
+ cpu?: number;
21
+ memory?: number;
22
+ memoryLimit?: number;
23
+ }
13
24
  /**
14
25
  * Makes and runs the sandboxes of tenants, one each: a container, a process, a machine of a cloud. As a model
15
26
  * provider of pi is to models, built in (`docker`, `command`, `local`, `ta`) or a module of the operator's
@@ -19,6 +30,8 @@ export interface SandboxProvider {
19
30
  readonly id: string;
20
31
  readonly name: string;
21
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;
22
35
  /** How long its Ta service has to answer once started; default two minutes, for a first pull of an image. */
23
36
  readonly readyTimeoutMs?: number;
24
37
  /**
@@ -30,6 +43,10 @@ export interface SandboxProvider {
30
43
  /** Stops it, keeping what it holds, to start again later. */
31
44
  stop(tenant: SandboxTenant): Promise<void>;
32
45
  state(tenant: SandboxTenant): Promise<SandboxState>;
46
+ /** What its sandbox takes now, for the console; undefined when it does not run. */
47
+ usage?(tenant: SandboxTenant): Promise<SandboxUsage | undefined>;
48
+ /** The last `lines` its sandbox wrote (its Ta service's output), for the console. */
49
+ logs?(tenant: SandboxTenant, lines: number): Promise<string>;
33
50
  /** The gateway stops: what runs in this process ends (`local`). */
34
51
  dispose?(): Promise<void>;
35
52
  }
@@ -1,4 +1,14 @@
1
- import type { TaEnvironmentChoice } from '@celljs/ta-protocol';
1
+ import type { TaEnvironmentChoice, TaGatewayLimits } from '@celljs/ta-protocol';
2
+ /** The minutes a tenant's sandbox ran in a month (of UTC), and those given on top of its limit. */
3
+ export interface TenantMeter {
4
+ /** `YYYY-MM`. */
5
+ month: string;
6
+ runMs: number;
7
+ bonusMinutes: number;
8
+ /** Tokens and dollars of calls of models through the gateway. */
9
+ tokens?: number;
10
+ cost?: number;
11
+ }
2
12
  /** A tenant: an account and its Ta, wherever it runs. */
3
13
  export interface Tenant {
4
14
  id: string;
@@ -11,6 +21,12 @@ export interface Tenant {
11
21
  environment?: TaEnvironmentChoice;
12
22
  createdAt: number;
13
23
  lastActiveAt?: number;
24
+ /** Its own limits over the gateway's defaults. */
25
+ limits?: TaGatewayLimits;
26
+ suspended?: boolean;
27
+ meter?: TenantMeter;
28
+ /** What its sandbox calls the models of the gateway with: it reaches no key of a provider. */
29
+ modelKey?: string;
14
30
  }
15
31
  /** Files written whole or not at all, readable by this user only. */
16
32
  export declare function writePrivate(file: string, data: unknown): void;
@@ -31,6 +47,8 @@ export declare class TenantStore {
31
47
  avatar?: string;
32
48
  }, now?: number): Tenant;
33
49
  update(id: string, change: Partial<Omit<Tenant, 'id' | 'account' | 'token'>>): Tenant;
50
+ /** Its model key, made for a tenant of before. */
51
+ modelKey(id: string): string;
34
52
  list(): Tenant[];
35
53
  protected save(tenant: Tenant): void;
36
54
  }
@@ -55,6 +55,7 @@ export class TenantStore {
55
55
  name: account.name,
56
56
  avatar: account.avatar,
57
57
  token: randomBytes(32).toString('base64url'),
58
+ modelKey: `tam-${randomBytes(24).toString('base64url')}`,
58
59
  createdAt: now,
59
60
  };
60
61
  this.save(tenant);
@@ -69,6 +70,15 @@ export class TenantStore {
69
70
  this.save(next);
70
71
  return next;
71
72
  }
73
+ /** Its model key, made for a tenant of before. */
74
+ modelKey(id) {
75
+ var _a;
76
+ const tenant = this.get(id);
77
+ if (!tenant) {
78
+ throw new Error(`No tenant ${id}`);
79
+ }
80
+ return (_a = tenant.modelKey) !== null && _a !== void 0 ? _a : this.update(id, { modelKey: `tam-${randomBytes(24).toString('base64url')}` }).modelKey;
81
+ }
72
82
  list() {
73
83
  return readdirSync(this.dir)
74
84
  .filter(name => /^[0-9a-f]{16}\.json$/.test(name))
@@ -8,22 +8,26 @@ export declare namespace CommandSandboxUtil {
8
8
  * by shell commands, as pi's models.json takes an endpoint it has no provider for. Each runs with
9
9
  * TA_TENANT_ID, TA_TENANT_ACCOUNT and TA_SERVE_TOKEN in its environment: `start` makes or starts the sandbox
10
10
  * of the tenant, whose Ta service takes TA_SERVE_TOKEN, and prints its address last; `stop` stops it;
11
- * `state` prints running, stopped or missing.
11
+ * `state` prints running, stopped or missing; `logs`, when there is one, prints the last TA_LOG_LINES lines
12
+ * the sandbox wrote, for the console.
12
13
  */
13
14
  export declare class CommandSandbox implements SandboxProvider {
14
15
  readonly id: string;
15
16
  readonly type = "command";
16
17
  readonly name: string;
18
+ readonly gatewayUrl?: string;
17
19
  protected readonly commands: {
18
20
  start: string;
19
21
  stop?: string;
20
22
  state?: string;
23
+ logs?: string;
21
24
  };
22
25
  protected readonly env: Record<string, string>;
23
26
  constructor(id: string, config: SandboxProviderConfig);
27
+ logs?(tenant: SandboxTenant, lines: number): Promise<string>;
24
28
  start(tenant: SandboxTenant): Promise<SandboxEndpoint>;
25
29
  stop(tenant: SandboxTenant): Promise<void>;
26
30
  state(tenant: SandboxTenant): Promise<SandboxState>;
27
- protected run(command: string, tenant: SandboxTenant): Promise<string>;
31
+ protected run(command: string, tenant: SandboxTenant, extra?: Record<string, string>): Promise<string>;
28
32
  }
29
33
  //# sourceMappingURL=command-sandbox.d.ts.map
@@ -22,19 +22,33 @@ var CommandSandboxUtil;
22
22
  * by shell commands, as pi's models.json takes an endpoint it has no provider for. Each runs with
23
23
  * TA_TENANT_ID, TA_TENANT_ACCOUNT and TA_SERVE_TOKEN in its environment: `start` makes or starts the sandbox
24
24
  * of the tenant, whose Ta service takes TA_SERVE_TOKEN, and prints its address last; `stop` stops it;
25
- * `state` prints running, stopped or missing.
25
+ * `state` prints running, stopped or missing; `logs`, when there is one, prints the last TA_LOG_LINES lines
26
+ * the sandbox wrote, for the console.
26
27
  */
27
28
  class CommandSandbox {
28
29
  constructor(id, config) {
29
30
  this.id = id;
30
31
  this.type = 'command';
31
32
  this.name = sandbox_provider_1.SandboxProviders.string(config, 'name', id);
33
+ this.gatewayUrl = sandbox_provider_1.SandboxProviders.string(config, 'gatewayUrl');
32
34
  const start = sandbox_provider_1.SandboxProviders.string(config, 'start');
33
35
  if (!start) {
34
36
  throw new Error(`The provider "${id}" of the type command needs "start", a command that prints the address of the Ta service.`);
35
37
  }
36
- this.commands = { start, stop: sandbox_provider_1.SandboxProviders.string(config, 'stop'), state: sandbox_provider_1.SandboxProviders.string(config, 'state') };
38
+ this.commands = {
39
+ start,
40
+ stop: sandbox_provider_1.SandboxProviders.string(config, 'stop'),
41
+ state: sandbox_provider_1.SandboxProviders.string(config, 'state'),
42
+ logs: sandbox_provider_1.SandboxProviders.string(config, 'logs'),
43
+ };
37
44
  this.env = sandbox_provider_1.SandboxProviders.env(config);
45
+ if (!this.commands.logs) {
46
+ // The console asks a provider whether it has logs by the method.
47
+ this.logs = undefined;
48
+ }
49
+ }
50
+ logs(tenant, lines) {
51
+ return this.run(this.commands.logs, tenant, { TA_LOG_LINES: String(lines) });
38
52
  }
39
53
  async start(tenant) {
40
54
  const stdout = await this.run(this.commands.start, tenant);
@@ -56,10 +70,18 @@ class CommandSandbox {
56
70
  const word = (await this.run(this.commands.state, tenant)).trim().split(/\s+/).pop();
57
71
  return word === 'running' || word === 'stopped' ? word : 'missing';
58
72
  }
59
- run(command, tenant) {
73
+ run(command, tenant, extra = {}) {
60
74
  return new Promise((resolve, reject) => {
61
75
  const child = (0, node_child_process_1.spawn)('sh', ['-c', command], {
62
- env: { ...process.env, ...this.env, TA_TENANT_ID: tenant.id, TA_TENANT_ACCOUNT: tenant.account, TA_SERVE_TOKEN: tenant.token },
76
+ env: {
77
+ ...process.env,
78
+ ...this.env,
79
+ ...tenant.env,
80
+ TA_TENANT_ID: tenant.id,
81
+ TA_TENANT_ACCOUNT: tenant.account,
82
+ TA_SERVE_TOKEN: tenant.token,
83
+ ...extra,
84
+ },
63
85
  stdio: ['ignore', 'pipe', 'pipe'],
64
86
  });
65
87
  let stdout = '';