@celljs/ta-gateway 4.15.0 → 4.15.2

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 (57) hide show
  1. package/esm/node/command-sandbox.d.ts +5 -2
  2. package/esm/node/command-sandbox.js +17 -4
  3. package/esm/node/docker-engine.d.ts +45 -0
  4. package/esm/node/docker-engine.js +87 -11
  5. package/esm/node/docker-sandbox.d.ts +3 -1
  6. package/esm/node/docker-sandbox.js +6 -0
  7. package/esm/node/environments.d.ts +34 -2
  8. package/esm/node/environments.js +187 -11
  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-policy.d.ts +46 -0
  14. package/esm/node/gateway-policy.js +151 -0
  15. package/esm/node/gateway-quotas.d.ts +32 -0
  16. package/esm/node/gateway-quotas.js +104 -0
  17. package/esm/node/gateway-server.d.ts +16 -1
  18. package/esm/node/gateway-server.js +58 -6
  19. package/esm/node/gateway-service.d.ts +91 -16
  20. package/esm/node/gateway-service.js +366 -45
  21. package/esm/node/gateway-socket.d.ts +7 -1
  22. package/esm/node/gateway-socket.js +40 -1
  23. package/esm/node/gateway-usage.d.ts +37 -0
  24. package/esm/node/gateway-usage.js +137 -0
  25. package/esm/node/local-sandbox.d.ts +12 -0
  26. package/esm/node/local-sandbox.js +36 -1
  27. package/esm/node/sandbox-provider.d.ts +10 -0
  28. package/esm/node/tenant-store.d.ts +12 -1
  29. package/lib/node/command-sandbox.d.ts +5 -2
  30. package/lib/node/command-sandbox.js +17 -4
  31. package/lib/node/docker-engine.d.ts +45 -0
  32. package/lib/node/docker-engine.js +87 -11
  33. package/lib/node/docker-sandbox.d.ts +3 -1
  34. package/lib/node/docker-sandbox.js +6 -0
  35. package/lib/node/environments.d.ts +34 -2
  36. package/lib/node/environments.js +186 -10
  37. package/lib/node/gateway-audit.d.ts +13 -0
  38. package/lib/node/gateway-audit.js +51 -0
  39. package/lib/node/gateway-cli.d.ts +2 -0
  40. package/lib/node/gateway-cli.js +1 -0
  41. package/lib/node/gateway-policy.d.ts +47 -0
  42. package/lib/node/gateway-policy.js +156 -0
  43. package/lib/node/gateway-quotas.d.ts +33 -0
  44. package/lib/node/gateway-quotas.js +108 -0
  45. package/lib/node/gateway-server.d.ts +16 -1
  46. package/lib/node/gateway-server.js +58 -6
  47. package/lib/node/gateway-service.d.ts +91 -16
  48. package/lib/node/gateway-service.js +365 -44
  49. package/lib/node/gateway-socket.d.ts +7 -1
  50. package/lib/node/gateway-socket.js +40 -1
  51. package/lib/node/gateway-usage.d.ts +38 -0
  52. package/lib/node/gateway-usage.js +141 -0
  53. package/lib/node/local-sandbox.d.ts +12 -0
  54. package/lib/node/local-sandbox.js +38 -2
  55. package/lib/node/sandbox-provider.d.ts +10 -0
  56. package/lib/node/tenant-store.d.ts +12 -1
  57. package/package.json +4 -4
@@ -30,37 +30,127 @@ var EnvironmentsUtil;
30
30
  }
31
31
  EnvironmentsUtil.waitReady = waitReady;
32
32
  /** One call of the Ta service at `endpoint` over a WebSocket of its own: the gateway's, not a browser's. */
33
- function call(endpoint, method, params = [], timeoutMs = 10000) {
33
+ async function call(endpoint, method, params = [], timeoutMs = 10000) {
34
+ const [result] = await calls(endpoint, [[method, params]], timeoutMs);
35
+ return result;
36
+ }
37
+ EnvironmentsUtil.call = call;
38
+ /**
39
+ * Calls of the Ta service at `endpoint` over one WebSocket of the gateway's, in their order: the answers, or
40
+ * the error of each that failed. Throws when the service is not reached, or all took too long.
41
+ */
42
+ function calls(endpoint, list, timeoutMs = 10000) {
34
43
  return new Promise((resolve, reject) => {
35
44
  const url = new URL(`${endpoint.url.replace(/^http/, 'ws')}${ta_protocol_1.TA_WEBSOCKET_PATH}`);
36
45
  url.searchParams.set('token', endpoint.token);
37
46
  const socket = new WebSocket(url);
38
- const timer = setTimeout(() => finish(new EnvironmentError(`${method} took too long`)), timeoutMs);
39
- const finish = (error, result) => {
47
+ const results = new Array(list.length);
48
+ let left = list.length;
49
+ let done = false;
50
+ const timer = setTimeout(() => { var _a; var _b; return finish(new EnvironmentError(`${(_b = (_a = list[0]) === null || _a === void 0 ? void 0 : _a[0]) !== null && _b !== void 0 ? _b : 'A call'} took too long`)); }, timeoutMs);
51
+ const finish = (error) => {
52
+ if (done) {
53
+ return;
54
+ }
55
+ done = true;
40
56
  clearTimeout(timer);
41
57
  socket.close();
42
58
  if (error) {
43
59
  reject(error);
44
60
  }
45
61
  else {
46
- resolve(result);
62
+ resolve(results);
63
+ }
64
+ };
65
+ if (left === 0) {
66
+ queueMicrotask(() => finish());
67
+ }
68
+ socket.onopen = () => {
69
+ for (const [index, [method, params]] of list.entries()) {
70
+ socket.send(JSON.stringify({ jsonrpc: '2.0', id: index + 1, method, params }));
47
71
  }
48
72
  };
49
- socket.onopen = () => socket.send(JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }));
50
73
  socket.onerror = () => finish(new EnvironmentError(`Cannot reach ${endpoint.url}`));
51
74
  socket.onmessage = message => {
75
+ var _a;
52
76
  const answer = JSON.parse(String(message.data));
53
- if (answer.id === 1) {
54
- finish(answer.error ? new EnvironmentError(answer.error.message) : undefined, answer.result);
55
- }
56
- else if (answer.method !== undefined && answer.id !== undefined) {
77
+ if (answer.method !== undefined && answer.id !== undefined) {
57
78
  // A push of the server (TaClient): answered, so that it does not wait.
58
79
  socket.send(JSON.stringify({ jsonrpc: '2.0', id: answer.id, result: null }));
80
+ return;
81
+ }
82
+ const index = typeof answer.id === 'number' ? answer.id - 1 : -1;
83
+ if (index < 0 || index >= list.length || results[index] !== undefined) {
84
+ return;
85
+ }
86
+ if (list.length === 1 && answer.error) {
87
+ finish(new EnvironmentError(answer.error.message));
88
+ return;
89
+ }
90
+ results[index] = answer.error ? new EnvironmentError(answer.error.message) : ((_a = answer.result) !== null && _a !== void 0 ? _a : null);
91
+ if (--left === 0) {
92
+ finish();
59
93
  }
60
94
  };
61
95
  });
62
96
  }
63
- EnvironmentsUtil.call = call;
97
+ EnvironmentsUtil.calls = calls;
98
+ /** What the console says an agent does: a dialog waiting for the user first, then a turn, then a question left. */
99
+ function status(session) {
100
+ return session.waiting ? 'waiting' : session.isStreaming ? 'working' : session.asking ? 'asking' : 'idle';
101
+ }
102
+ EnvironmentsUtil.status = status;
103
+ function summary(sessions) {
104
+ const statuses = sessions.map(status);
105
+ return {
106
+ sessions: sessions.length,
107
+ working: statuses.filter(each => each === 'working').length,
108
+ waiting: statuses.filter(each => each === 'waiting' || each === 'asking').length,
109
+ };
110
+ }
111
+ EnvironmentsUtil.summary = summary;
112
+ /** Of pi's statistics of a session, what the console shows; undefined for what is not them (an error). */
113
+ function stats(value) {
114
+ var _a;
115
+ var _b, _c, _d, _e, _f, _g, _h, _j;
116
+ const given = value;
117
+ if (!given || typeof given !== 'object' || !given.tokens || typeof given.cost !== 'number') {
118
+ return undefined;
119
+ }
120
+ const percent = (_a = given.contextUsage) === null || _a === void 0 ? void 0 : _a.percent;
121
+ return {
122
+ userMessages: (_b = given.userMessages) !== null && _b !== void 0 ? _b : 0,
123
+ assistantMessages: (_c = given.assistantMessages) !== null && _c !== void 0 ? _c : 0,
124
+ toolCalls: (_d = given.toolCalls) !== null && _d !== void 0 ? _d : 0,
125
+ tokens: {
126
+ input: (_e = given.tokens.input) !== null && _e !== void 0 ? _e : 0,
127
+ output: (_f = given.tokens.output) !== null && _f !== void 0 ? _f : 0,
128
+ cacheRead: (_g = given.tokens.cacheRead) !== null && _g !== void 0 ? _g : 0,
129
+ cacheWrite: (_h = given.tokens.cacheWrite) !== null && _h !== void 0 ? _h : 0,
130
+ total: (_j = given.tokens.total) !== null && _j !== void 0 ? _j : 0,
131
+ },
132
+ cost: given.cost,
133
+ context: typeof percent === 'number' ? Math.round(percent) : undefined,
134
+ };
135
+ }
136
+ EnvironmentsUtil.stats = stats;
137
+ /** A session as an administrator sees it: never what was said in it. */
138
+ function agentSession(session, stats) {
139
+ return {
140
+ sessionId: session.sessionId,
141
+ name: session.sessionName || undefined,
142
+ cwd: session.cwd,
143
+ model: session.model,
144
+ status: status(session),
145
+ messageCount: session.messageCount,
146
+ attached: session.attached,
147
+ createdAt: session.createdAt,
148
+ updatedAt: session.updatedAt,
149
+ group: session.group,
150
+ stats,
151
+ };
152
+ }
153
+ EnvironmentsUtil.agentSession = agentSession;
64
154
  function sandboxTenant(tenant) {
65
155
  return { id: tenant.id, account: tenant.account, token: tenant.token };
66
156
  }
@@ -118,6 +208,86 @@ class Environments {
118
208
  url: own && provider instanceof ta_sandbox_1.TaSandbox ? provider.url : undefined,
119
209
  };
120
210
  }
211
+ /** What the sandbox of a running tenant takes, when its provider tells; a provider that fails to tell leaves it out. */
212
+ async usage(tenant) {
213
+ var _a;
214
+ if (((_a = this.running.get(tenant.id)) === null || _a === void 0 ? void 0 : _a.status) !== 'running') {
215
+ return undefined;
216
+ }
217
+ const { provider, own } = this.provider(tenant);
218
+ if (own || !provider.usage) {
219
+ return undefined;
220
+ }
221
+ return provider.usage(EnvironmentsUtil.sandboxTenant(tenant)).catch(() => undefined);
222
+ }
223
+ /** The last lines its sandbox wrote; a Ta service of the user's, or a provider without logs, has none for the gateway. */
224
+ async logs(tenant, lines) {
225
+ const { provider, own } = this.provider(tenant);
226
+ if (own || !provider.logs) {
227
+ throw new EnvironmentError(`The sandboxes of ${own ? 'a Ta service of the user' : provider.name} keep no logs for the gateway.`);
228
+ }
229
+ return provider.logs(EnvironmentsUtil.sandboxTenant(tenant), lines);
230
+ }
231
+ /** Where the Ta of a tenant answers, while it runs in a sandbox of the gateway's; a Ta service of the user's is theirs to watch. */
232
+ watched(tenant) {
233
+ const running = this.running.get(tenant.id);
234
+ return (running === null || running === void 0 ? void 0 : running.status) === 'running' && running.endpoint && !this.provider(tenant).own ? running.endpoint : undefined;
235
+ }
236
+ /** The tenants whose sandbox of the gateway's runs now: those whose minutes count. */
237
+ runningIds() {
238
+ return [...this.running.entries()]
239
+ .filter(([id, running]) => {
240
+ const tenant = running.status === 'running' ? this.tenants.get(id) : undefined;
241
+ return tenant !== undefined && !this.provider(tenant).own;
242
+ })
243
+ .map(([id]) => id);
244
+ }
245
+ /** How the gateway asks its Ta what its agents took; undefined while it does not run. */
246
+ usageReader(tenant) {
247
+ const endpoint = this.watched(tenant);
248
+ return endpoint && (since => EnvironmentsUtil.call(endpoint, 'TaUsageServer/getUsage', [since], 20000));
249
+ }
250
+ /** The latest of what an agent of its Ta did. */
251
+ async activity(tenant, sessionId) {
252
+ const endpoint = this.watched(tenant);
253
+ if (!endpoint) {
254
+ throw new EnvironmentError('Its sandbox does not run: start it to see what its agents did.');
255
+ }
256
+ return EnvironmentsUtil.call(endpoint, 'TaUsageServer/getActivity', [sessionId, 50]);
257
+ }
258
+ /** How many conversations its Ta has open and how many work or wait; undefined when it does not run, or does not answer soon. */
259
+ async agentSummary(tenant, timeoutMs = 3000) {
260
+ const endpoint = this.watched(tenant);
261
+ if (!endpoint) {
262
+ return undefined;
263
+ }
264
+ const sessions = await EnvironmentsUtil.call(endpoint, 'TaServer/listSessions', [], timeoutMs).catch(() => undefined);
265
+ return sessions && EnvironmentsUtil.summary(sessions);
266
+ }
267
+ /** The conversations open in its Ta, each with pi's statistics of it, over one connection. */
268
+ async agents(tenant, now = Date.now()) {
269
+ const endpoint = this.watched(tenant);
270
+ if (!endpoint) {
271
+ throw new EnvironmentError(this.provider(tenant).own
272
+ ? 'The Ta service of the user is theirs: the gateway does not watch it.'
273
+ : 'Its sandbox does not run: start it to see its agents.');
274
+ }
275
+ const [sessions] = await EnvironmentsUtil.calls(endpoint, [['TaServer/listSessions', []]]);
276
+ const stats = await EnvironmentsUtil.calls(endpoint, sessions.map(session => ['TaServer/getSessionStats', [session.sessionId]])).catch(() => sessions.map(() => undefined));
277
+ const list = sessions
278
+ .map((session, index) => EnvironmentsUtil.agentSession(session, EnvironmentsUtil.stats(stats[index])))
279
+ .sort((a, b) => b.updatedAt - a.updatedAt);
280
+ return {
281
+ sessions: list,
282
+ totals: {
283
+ ...EnvironmentsUtil.summary(sessions),
284
+ toolCalls: list.reduce((sum, each) => { var _a; var _b; return sum + ((_b = (_a = each.stats) === null || _a === void 0 ? void 0 : _a.toolCalls) !== null && _b !== void 0 ? _b : 0); }, 0),
285
+ tokens: list.reduce((sum, each) => { var _a; var _b; return sum + ((_b = (_a = each.stats) === null || _a === void 0 ? void 0 : _a.tokens.total) !== null && _b !== void 0 ? _b : 0); }, 0),
286
+ cost: list.reduce((sum, each) => { var _a; var _b; return sum + ((_b = (_a = each.stats) === null || _a === void 0 ? void 0 : _a.cost) !== null && _b !== void 0 ? _b : 0); }, 0),
287
+ },
288
+ readAt: now,
289
+ };
290
+ }
121
291
  connections(tenantId) {
122
292
  var _a;
123
293
  var _b;
@@ -125,6 +295,7 @@ class Environments {
125
295
  }
126
296
  /** Where the Ta of the tenant answers, started when it does not run. */
127
297
  ensure(tenant) {
298
+ var _a;
128
299
  const running = this.state(tenant.id);
129
300
  if (running.status === 'running' && running.endpoint) {
130
301
  return Promise.resolve(running.endpoint);
@@ -132,6 +303,11 @@ class Environments {
132
303
  if (running.starting) {
133
304
  return running.starting;
134
305
  }
306
+ const blocked = (_a = this.guard) === null || _a === void 0 ? void 0 : _a.call(this, tenant);
307
+ if (blocked) {
308
+ Object.assign(running, { status: 'failed', error: blocked });
309
+ return Promise.reject(new EnvironmentError(blocked));
310
+ }
135
311
  running.status = 'starting';
136
312
  running.error = undefined;
137
313
  const starting = (async () => {
@@ -0,0 +1,13 @@
1
+ import type { TaGatewayAuditEntry } from '@celljs/ta-protocol';
2
+ /**
3
+ * What administrators did, one JSON line each (`audit.jsonl`, readable by the gateway's user only): what changed
4
+ * and what of others was looked at (logs, what an agent did), with who and when.
5
+ */
6
+ export declare class GatewayAudit {
7
+ protected readonly file: string;
8
+ constructor(dir: string);
9
+ add(entry: Omit<TaGatewayAuditEntry, 'at'>, now?: number): void;
10
+ /** The latest first. */
11
+ list(limit: number): TaGatewayAuditEntry[];
12
+ }
13
+ //# sourceMappingURL=gateway-audit.d.ts.map
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GatewayAudit = void 0;
4
+ const node_fs_1 = require("node:fs");
5
+ const node_path_1 = require("node:path");
6
+ /** What is kept of the audit when read: the end of the file, as many bytes at most. */
7
+ const TAIL_BYTES = 2 * 1024 * 1024;
8
+ /**
9
+ * What administrators did, one JSON line each (`audit.jsonl`, readable by the gateway's user only): what changed
10
+ * and what of others was looked at (logs, what an agent did), with who and when.
11
+ */
12
+ class GatewayAudit {
13
+ constructor(dir) {
14
+ this.file = (0, node_path_1.join)(dir, 'audit.jsonl');
15
+ }
16
+ add(entry, now = Date.now()) {
17
+ const fresh = !(0, node_fs_1.existsSync)(this.file);
18
+ (0, node_fs_1.appendFileSync)(this.file, `${JSON.stringify({ at: now, ...entry })}\n`, { mode: 0o600 });
19
+ if (fresh) {
20
+ (0, node_fs_1.chmodSync)(this.file, 0o600);
21
+ }
22
+ }
23
+ /** The latest first. */
24
+ list(limit) {
25
+ let text;
26
+ try {
27
+ text = (0, node_fs_1.readFileSync)(this.file, 'utf8');
28
+ }
29
+ catch (_a) {
30
+ return [];
31
+ }
32
+ if (text.length > TAIL_BYTES) {
33
+ text = text.slice(text.indexOf('\n', text.length - TAIL_BYTES) + 1);
34
+ }
35
+ const entries = [];
36
+ const lines = text.split('\n');
37
+ for (let index = lines.length - 1; index >= 0 && entries.length < limit; index--) {
38
+ try {
39
+ if (lines[index]) {
40
+ entries.push(JSON.parse(lines[index]));
41
+ }
42
+ }
43
+ catch (_b) {
44
+ // A line cut short when the gateway stopped.
45
+ }
46
+ }
47
+ return entries;
48
+ }
49
+ }
50
+ exports.GatewayAudit = GatewayAudit;
51
+ //# sourceMappingURL=gateway-audit.js.map
@@ -3,6 +3,8 @@ export interface GatewayCliOptions {
3
3
  publicDir: string;
4
4
  /** How to run `ta` (the local sandboxes). */
5
5
  taCommand: string[];
6
+ /** Of Ta, which the console shows. */
7
+ version?: string;
6
8
  }
7
9
  export declare namespace GatewayCli {
8
10
  function run(argv: string[], options: GatewayCliOptions): Promise<void>;
@@ -66,6 +66,7 @@ var GatewayCli;
66
66
  port: Number((_d = (_c = values.port) !== null && _c !== void 0 ? _c : process.env.PORT) !== null && _d !== void 0 ? _d : 4100),
67
67
  publicDir: options.publicDir,
68
68
  taCommand: options.taCommand,
69
+ version: options.version,
69
70
  });
70
71
  }
71
72
  catch (error) {
@@ -0,0 +1,47 @@
1
+ import type { TaGatewayLimits, TaGatewayPolicy, TaGatewayRole } from '@celljs/ta-protocol';
2
+ interface StoredPolicy {
3
+ defaults?: TaGatewayLimits;
4
+ /** Accounts made admins in the console. */
5
+ admins?: string[];
6
+ }
7
+ /** The limits of a member once the defaults and their own are taken together: none where a value is missing. */
8
+ export interface ResolvedLimits {
9
+ freeMinutes?: number;
10
+ promptsPerMinute?: number;
11
+ connections?: number;
12
+ providers?: string[];
13
+ own: boolean;
14
+ }
15
+ export declare class PolicyError extends Error {
16
+ }
17
+ export declare namespace GatewayPolicyUtil {
18
+ function rank(role: TaGatewayRole): number;
19
+ /**
20
+ * Limits as a page sent them, checked: whole numbers of 0 and more, a list of providers of those there are, a
21
+ * boolean. `nullable`: those of an account, where null drops a limit; in the defaults null is none, left out.
22
+ */
23
+ function limits(value: unknown, providers: readonly string[], nullable: boolean): TaGatewayLimits;
24
+ /** An account's own over the defaults: a value of its own wins, null in it is none. */
25
+ function resolve(defaults: TaGatewayLimits, own: TaGatewayLimits | undefined, ownAllowed: boolean): ResolvedLimits;
26
+ }
27
+ /**
28
+ * Who manages the gateway and what members may use: owners are those of TA_GATEWAY_ADMINS, where the gateway runs,
29
+ * which the console cannot change; admins and the default limits are those of `policy.json`, which owners change
30
+ * in the console.
31
+ */
32
+ export declare class GatewayPolicy {
33
+ protected readonly owners: readonly string[];
34
+ protected readonly file: string;
35
+ protected stored: StoredPolicy;
36
+ constructor(dir: string, owners: readonly string[]);
37
+ role(account: string): TaGatewayRole;
38
+ /** Whether the account is let in by its role, whatever the list of access says. */
39
+ lets(account: string): boolean;
40
+ get defaults(): TaGatewayLimits;
41
+ setDefaults(limits: TaGatewayLimits): void;
42
+ setRole(account: string, role: 'admin' | 'member'): void;
43
+ view(idleMinutes: number): TaGatewayPolicy;
44
+ protected read(): StoredPolicy;
45
+ }
46
+ export {};
47
+ //# sourceMappingURL=gateway-policy.d.ts.map
@@ -0,0 +1,156 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GatewayPolicy = exports.GatewayPolicyUtil = exports.PolicyError = void 0;
4
+ const node_fs_1 = require("node:fs");
5
+ const node_path_1 = require("node:path");
6
+ const access_store_1 = require("@celljs/ta-host/lib/node/sign-in/access-store");
7
+ const tenant_store_1 = require("./tenant-store");
8
+ class PolicyError extends Error {
9
+ }
10
+ exports.PolicyError = PolicyError;
11
+ var GatewayPolicyUtil;
12
+ (function (GatewayPolicyUtil) {
13
+ const NUMBERS = ['freeMinutes', 'promptsPerMinute', 'connections'];
14
+ const RANK = { member: 0, admin: 1, owner: 2 };
15
+ function rank(role) {
16
+ return RANK[role];
17
+ }
18
+ GatewayPolicyUtil.rank = rank;
19
+ /**
20
+ * Limits as a page sent them, checked: whole numbers of 0 and more, a list of providers of those there are, a
21
+ * boolean. `nullable`: those of an account, where null drops a limit; in the defaults null is none, left out.
22
+ */
23
+ function limits(value, providers, nullable) {
24
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
25
+ throw new PolicyError('Limits are an object, such as { "freeMinutes": 600 }.');
26
+ }
27
+ const given = value;
28
+ const out = {};
29
+ for (const key of Object.keys(given)) {
30
+ if (![...NUMBERS, 'providers', 'own'].includes(key)) {
31
+ throw new PolicyError(`"${key}" is no limit: those there are are ${[...NUMBERS, 'providers', 'own'].join(', ')}.`);
32
+ }
33
+ }
34
+ for (const key of NUMBERS) {
35
+ const item = given[key];
36
+ if (item === undefined) {
37
+ continue;
38
+ }
39
+ if (item === null) {
40
+ if (nullable) {
41
+ out[key] = null;
42
+ }
43
+ continue;
44
+ }
45
+ if (typeof item !== 'number' || !Number.isInteger(item) || item < 0 || item > 10000000) {
46
+ throw new PolicyError(`"${key}" is a whole number from 0, or null for none.`);
47
+ }
48
+ out[key] = item;
49
+ }
50
+ if (given.providers !== undefined) {
51
+ if (given.providers === null) {
52
+ if (nullable) {
53
+ out.providers = null;
54
+ }
55
+ }
56
+ else if (!Array.isArray(given.providers) || given.providers.some(id => typeof id !== 'string' || !providers.includes(id))) {
57
+ throw new PolicyError(`"providers" lists providers of the gateway: ${providers.join(', ')}.`);
58
+ }
59
+ else {
60
+ out.providers = [...new Set(given.providers)];
61
+ }
62
+ }
63
+ if (given.own !== undefined) {
64
+ if (given.own === null) {
65
+ if (nullable) {
66
+ out.own = null;
67
+ }
68
+ }
69
+ else if (typeof given.own !== 'boolean') {
70
+ throw new PolicyError('"own" is true or false.');
71
+ }
72
+ else {
73
+ out.own = given.own;
74
+ }
75
+ }
76
+ return out;
77
+ }
78
+ GatewayPolicyUtil.limits = limits;
79
+ /** An account's own over the defaults: a value of its own wins, null in it is none. */
80
+ function resolve(defaults, own, ownAllowed) {
81
+ const pick = (key) => (own && own[key] !== undefined ? own[key] : defaults[key]);
82
+ const number = (key) => {
83
+ const value = pick(key);
84
+ return typeof value === 'number' ? value : undefined;
85
+ };
86
+ const providers = pick('providers');
87
+ const own_ = pick('own');
88
+ return {
89
+ freeMinutes: number('freeMinutes'),
90
+ promptsPerMinute: number('promptsPerMinute'),
91
+ connections: number('connections'),
92
+ providers: Array.isArray(providers) ? providers : undefined,
93
+ own: ownAllowed && own_ !== false,
94
+ };
95
+ }
96
+ GatewayPolicyUtil.resolve = resolve;
97
+ })(GatewayPolicyUtil || (exports.GatewayPolicyUtil = GatewayPolicyUtil = {}));
98
+ /**
99
+ * Who manages the gateway and what members may use: owners are those of TA_GATEWAY_ADMINS, where the gateway runs,
100
+ * which the console cannot change; admins and the default limits are those of `policy.json`, which owners change
101
+ * in the console.
102
+ */
103
+ class GatewayPolicy {
104
+ constructor(dir, owners) {
105
+ this.owners = owners;
106
+ this.file = (0, node_path_1.join)(dir, 'policy.json');
107
+ this.stored = this.read();
108
+ }
109
+ role(account) {
110
+ var _a;
111
+ if (this.owners.some(pattern => access_store_1.AccessUtil.matches(pattern, account))) {
112
+ return 'owner';
113
+ }
114
+ return ((_a = this.stored.admins) === null || _a === void 0 ? void 0 : _a.includes(account)) ? 'admin' : 'member';
115
+ }
116
+ /** Whether the account is let in by its role, whatever the list of access says. */
117
+ lets(account) {
118
+ return this.role(account) !== 'member';
119
+ }
120
+ get defaults() {
121
+ var _a;
122
+ return (_a = this.stored.defaults) !== null && _a !== void 0 ? _a : {};
123
+ }
124
+ setDefaults(limits) {
125
+ this.stored = { ...this.stored, defaults: limits };
126
+ (0, tenant_store_1.writePrivate)(this.file, this.stored);
127
+ }
128
+ setRole(account, role) {
129
+ var _a;
130
+ const admins = ((_a = this.stored.admins) !== null && _a !== void 0 ? _a : []).filter(other => other !== account);
131
+ this.stored = { ...this.stored, admins: role === 'admin' ? [...admins, account] : admins };
132
+ (0, tenant_store_1.writePrivate)(this.file, this.stored);
133
+ }
134
+ view(idleMinutes) {
135
+ var _a;
136
+ return {
137
+ defaults: this.defaults,
138
+ admins: [
139
+ ...this.owners.map(account => ({ account, role: 'owner' })),
140
+ ...((_a = this.stored.admins) !== null && _a !== void 0 ? _a : []).filter(account => this.role(account) === 'admin').map(account => ({ account, role: 'admin' })),
141
+ ],
142
+ idleMinutes,
143
+ };
144
+ }
145
+ read() {
146
+ try {
147
+ const value = JSON.parse((0, node_fs_1.readFileSync)(this.file, 'utf8'));
148
+ return value && typeof value === 'object' ? value : {};
149
+ }
150
+ catch (_a) {
151
+ return {};
152
+ }
153
+ }
154
+ }
155
+ exports.GatewayPolicy = GatewayPolicy;
156
+ //# sourceMappingURL=gateway-policy.js.map
@@ -0,0 +1,33 @@
1
+ import type { TaGatewayRole, TaQuotaBlock, TaQuotaState } from '@celljs/ta-protocol';
2
+ import { type GatewayPolicy, type ResolvedLimits } from './gateway-policy';
3
+ import { type GatewayUsage } from './gateway-usage';
4
+ import type { Tenant, TenantMeter, TenantStore } from './tenant-store';
5
+ /**
6
+ * What members may use and what they used: the minutes their sandboxes ran this month (of UTC), counted by the
7
+ * gateway as it sees them run, and the messages a minute they send their agents. Owners have no limits.
8
+ */
9
+ export declare class GatewayQuotas {
10
+ protected readonly policy: GatewayPolicy;
11
+ protected readonly tenants: TenantStore;
12
+ protected readonly usage: GatewayUsage;
13
+ protected readonly ownAllowed: () => boolean;
14
+ protected lastTick: number;
15
+ /** By tenant: the times of its messages within the last minute. */
16
+ protected readonly prompts: Map<string, number[]>;
17
+ constructor(policy: GatewayPolicy, tenants: TenantStore, usage: GatewayUsage, ownAllowed: () => boolean);
18
+ role(tenant: Tenant): TaGatewayRole;
19
+ limits(tenant: Tenant): ResolvedLimits;
20
+ /** That of this month: a meter of a month before starts again. */
21
+ meter(tenant: Tenant, now?: number): TenantMeter;
22
+ blocked(tenant: Tenant, now?: number): TaQuotaBlock | undefined;
23
+ state(tenant: Tenant, now?: number): TaQuotaState;
24
+ /** What a message of the tenant to its agents needs: false when it sent as many this minute as it may. */
25
+ takePrompt(tenant: Tenant, now?: number): boolean;
26
+ /** When the next message may go: the oldest of the minute leaves it. */
27
+ retryAfter(tenant: Tenant, now?: number): number;
28
+ /** The time since the last tick, to each tenant whose sandbox ran meanwhile; those now blocked. */
29
+ tick(running: readonly string[], now?: number): Tenant[];
30
+ /** Free minutes on top of the limit, this month; never fewer than none. */
31
+ grant(tenant: Tenant, minutes: number, now?: number): Tenant;
32
+ }
33
+ //# sourceMappingURL=gateway-quotas.d.ts.map
@@ -0,0 +1,108 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GatewayQuotas = void 0;
4
+ const gateway_policy_1 = require("./gateway-policy");
5
+ const gateway_usage_1 = require("./gateway-usage");
6
+ const MINUTE = 60000;
7
+ /** Of the time between two ticks, at most this counts: a gateway asleep or stopped did not see its sandboxes run. */
8
+ const MAX_TICK_MS = 2 * MINUTE;
9
+ /**
10
+ * What members may use and what they used: the minutes their sandboxes ran this month (of UTC), counted by the
11
+ * gateway as it sees them run, and the messages a minute they send their agents. Owners have no limits.
12
+ */
13
+ class GatewayQuotas {
14
+ constructor(policy, tenants, usage, ownAllowed) {
15
+ this.policy = policy;
16
+ this.tenants = tenants;
17
+ this.usage = usage;
18
+ this.ownAllowed = ownAllowed;
19
+ this.lastTick = Date.now();
20
+ /** By tenant: the times of its messages within the last minute. */
21
+ this.prompts = new Map();
22
+ }
23
+ role(tenant) {
24
+ return this.policy.role(tenant.account);
25
+ }
26
+ limits(tenant) {
27
+ if (this.role(tenant) === 'owner') {
28
+ return { own: this.ownAllowed() };
29
+ }
30
+ return gateway_policy_1.GatewayPolicyUtil.resolve(this.policy.defaults, tenant.limits, this.ownAllowed());
31
+ }
32
+ /** That of this month: a meter of a month before starts again. */
33
+ meter(tenant, now = Date.now()) {
34
+ var _a;
35
+ const { key } = gateway_usage_1.GatewayUsageUtil.month(now);
36
+ return ((_a = tenant.meter) === null || _a === void 0 ? void 0 : _a.month) === key ? tenant.meter : { month: key, runMs: 0, bonusMinutes: 0 };
37
+ }
38
+ blocked(tenant, now = Date.now()) {
39
+ if (tenant.suspended && this.role(tenant) !== 'owner') {
40
+ return 'suspended';
41
+ }
42
+ const { freeMinutes } = this.limits(tenant);
43
+ const meter = this.meter(tenant, now);
44
+ return freeMinutes !== undefined && meter.runMs >= (freeMinutes + meter.bonusMinutes) * MINUTE ? 'minutes' : undefined;
45
+ }
46
+ state(tenant, now = Date.now()) {
47
+ const { key, next } = gateway_usage_1.GatewayUsageUtil.month(now);
48
+ const meter = this.meter(tenant, now);
49
+ const limits = this.limits(tenant);
50
+ const month = this.usage.month(tenant.id, now);
51
+ return {
52
+ month: key,
53
+ resetsAt: next,
54
+ minutes: { used: Math.floor(meter.runMs / MINUTE), limit: limits.freeMinutes, bonus: meter.bonusMinutes },
55
+ tokens: { used: month.tokens, cost: month.cost },
56
+ promptsPerMinute: limits.promptsPerMinute,
57
+ connections: limits.connections,
58
+ blocked: this.blocked(tenant, now),
59
+ };
60
+ }
61
+ /** What a message of the tenant to its agents needs: false when it sent as many this minute as it may. */
62
+ takePrompt(tenant, now = Date.now()) {
63
+ var _a;
64
+ const limit = this.limits(tenant).promptsPerMinute;
65
+ if (limit === undefined) {
66
+ return true;
67
+ }
68
+ const times = ((_a = this.prompts.get(tenant.id)) !== null && _a !== void 0 ? _a : []).filter(time => now - time < MINUTE);
69
+ if (times.length >= limit) {
70
+ this.prompts.set(tenant.id, times);
71
+ return false;
72
+ }
73
+ times.push(now);
74
+ this.prompts.set(tenant.id, times);
75
+ return true;
76
+ }
77
+ /** When the next message may go: the oldest of the minute leaves it. */
78
+ retryAfter(tenant, now = Date.now()) {
79
+ var _a;
80
+ const oldest = (_a = this.prompts.get(tenant.id)) === null || _a === void 0 ? void 0 : _a[0];
81
+ return oldest === undefined ? 0 : Math.max(0, MINUTE - (now - oldest));
82
+ }
83
+ /** The time since the last tick, to each tenant whose sandbox ran meanwhile; those now blocked. */
84
+ tick(running, now = Date.now()) {
85
+ const elapsed = Math.min(Math.max(0, now - this.lastTick), MAX_TICK_MS);
86
+ this.lastTick = now;
87
+ const blocked = [];
88
+ for (const id of running) {
89
+ const tenant = this.tenants.get(id);
90
+ if (!tenant) {
91
+ continue;
92
+ }
93
+ const meter = this.meter(tenant, now);
94
+ const next = this.tenants.update(id, { meter: { ...meter, runMs: meter.runMs + elapsed } });
95
+ if (this.blocked(next, now)) {
96
+ blocked.push(next);
97
+ }
98
+ }
99
+ return blocked;
100
+ }
101
+ /** Free minutes on top of the limit, this month; never fewer than none. */
102
+ grant(tenant, minutes, now = Date.now()) {
103
+ const meter = this.meter(tenant, now);
104
+ return this.tenants.update(tenant.id, { meter: { ...meter, bonusMinutes: Math.max(0, meter.bonusMinutes + minutes) } });
105
+ }
106
+ }
107
+ exports.GatewayQuotas = GatewayQuotas;
108
+ //# sourceMappingURL=gateway-quotas.js.map