@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.
- package/esm/node/command-sandbox.d.ts +6 -2
- package/esm/node/command-sandbox.js +26 -4
- package/esm/node/docker-engine.d.ts +50 -0
- package/esm/node/docker-engine.js +98 -11
- package/esm/node/docker-sandbox.d.ts +6 -1
- package/esm/node/docker-sandbox.js +23 -3
- package/esm/node/environments.d.ts +36 -2
- package/esm/node/environments.js +192 -14
- package/esm/node/gateway-audit.d.ts +12 -0
- package/esm/node/gateway-audit.js +47 -0
- package/esm/node/gateway-cli.d.ts +2 -0
- package/esm/node/gateway-cli.js +1 -0
- package/esm/node/gateway-exec.d.ts +19 -0
- package/esm/node/gateway-exec.js +65 -0
- package/esm/node/gateway-policy.d.ts +47 -0
- package/esm/node/gateway-policy.js +152 -0
- package/esm/node/gateway-quotas.d.ts +40 -0
- package/esm/node/gateway-quotas.js +135 -0
- package/esm/node/gateway-server.d.ts +28 -2
- package/esm/node/gateway-server.js +112 -9
- package/esm/node/gateway-service.d.ts +99 -16
- package/esm/node/gateway-service.js +385 -45
- package/esm/node/gateway-socket.d.ts +7 -1
- package/esm/node/gateway-socket.js +40 -1
- package/esm/node/gateway-usage.d.ts +37 -0
- package/esm/node/gateway-usage.js +137 -0
- package/esm/node/local-sandbox.d.ts +13 -0
- package/esm/node/local-sandbox.js +38 -2
- package/esm/node/model-proxy.d.ts +105 -0
- package/esm/node/model-proxy.js +435 -0
- package/esm/node/sandbox-provider.d.ts +17 -0
- package/esm/node/tenant-store.d.ts +19 -1
- package/esm/node/tenant-store.js +10 -0
- package/lib/node/command-sandbox.d.ts +6 -2
- package/lib/node/command-sandbox.js +26 -4
- package/lib/node/docker-engine.d.ts +50 -0
- package/lib/node/docker-engine.js +98 -11
- package/lib/node/docker-sandbox.d.ts +6 -1
- package/lib/node/docker-sandbox.js +23 -3
- package/lib/node/environments.d.ts +36 -2
- package/lib/node/environments.js +191 -13
- package/lib/node/gateway-audit.d.ts +13 -0
- package/lib/node/gateway-audit.js +51 -0
- package/lib/node/gateway-cli.d.ts +2 -0
- package/lib/node/gateway-cli.js +1 -0
- package/lib/node/gateway-exec.d.ts +20 -0
- package/lib/node/gateway-exec.js +69 -0
- package/lib/node/gateway-policy.d.ts +48 -0
- package/lib/node/gateway-policy.js +157 -0
- package/lib/node/gateway-quotas.d.ts +41 -0
- package/lib/node/gateway-quotas.js +139 -0
- package/lib/node/gateway-server.d.ts +28 -2
- package/lib/node/gateway-server.js +112 -9
- package/lib/node/gateway-service.d.ts +99 -16
- package/lib/node/gateway-service.js +384 -44
- package/lib/node/gateway-socket.d.ts +7 -1
- package/lib/node/gateway-socket.js +40 -1
- package/lib/node/gateway-usage.d.ts +38 -0
- package/lib/node/gateway-usage.js +141 -0
- package/lib/node/local-sandbox.d.ts +13 -0
- package/lib/node/local-sandbox.js +40 -3
- package/lib/node/model-proxy.d.ts +106 -0
- package/lib/node/model-proxy.js +440 -0
- package/lib/node/sandbox-provider.d.ts +17 -0
- package/lib/node/tenant-store.d.ts +19 -1
- package/lib/node/tenant-store.js +10 -0
- package/package.json +4 -4
|
@@ -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>;
|
package/lib/node/gateway-cli.js
CHANGED
|
@@ -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,20 @@
|
|
|
1
|
+
import type { WebSocketConnection } from '@celljs/rpc/lib/node/websocket/websocket-connection';
|
|
2
|
+
import type { SandboxEndpoint } from './sandbox-provider';
|
|
3
|
+
/**
|
|
4
|
+
* A connection of another Ta to the exec server of its account's sandbox (`/api/exec`): what it sends goes to the
|
|
5
|
+
* sandbox once it answers, and back, unread. The account's own token is checked by the gateway; the sandbox's by it.
|
|
6
|
+
*/
|
|
7
|
+
export declare class GatewayExecProxy {
|
|
8
|
+
protected readonly outer: WebSocketConnection;
|
|
9
|
+
protected readonly release: () => void;
|
|
10
|
+
protected inner?: WebSocket;
|
|
11
|
+
protected readonly queued: string[];
|
|
12
|
+
protected queuedBytes: number;
|
|
13
|
+
protected closed: boolean;
|
|
14
|
+
constructor(outer: WebSocketConnection, endpoint: Promise<SandboxEndpoint>, release: () => void);
|
|
15
|
+
protected open(endpoint: SandboxEndpoint): void;
|
|
16
|
+
protected send(text: string): void;
|
|
17
|
+
close(code: number, reason: string): void;
|
|
18
|
+
protected dispose(): void;
|
|
19
|
+
}
|
|
20
|
+
//# sourceMappingURL=gateway-exec.d.ts.map
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.GatewayExecProxy = void 0;
|
|
4
|
+
/** What waits for the sandbox at most, as GatewaySocket. */
|
|
5
|
+
const MAX_QUEUED_BYTES = 16 * 1024 * 1024;
|
|
6
|
+
/**
|
|
7
|
+
* A connection of another Ta to the exec server of its account's sandbox (`/api/exec`): what it sends goes to the
|
|
8
|
+
* sandbox once it answers, and back, unread. The account's own token is checked by the gateway; the sandbox's by it.
|
|
9
|
+
*/
|
|
10
|
+
class GatewayExecProxy {
|
|
11
|
+
constructor(outer, endpoint, release) {
|
|
12
|
+
this.outer = outer;
|
|
13
|
+
this.release = release;
|
|
14
|
+
this.queued = [];
|
|
15
|
+
this.queuedBytes = 0;
|
|
16
|
+
this.closed = false;
|
|
17
|
+
outer.onMessage(text => this.send(text));
|
|
18
|
+
outer.onClose(() => this.dispose());
|
|
19
|
+
endpoint.then(found => this.open(found), (error) => this.close(1011, `Your environment did not start: ${error.message}`.slice(0, 120)));
|
|
20
|
+
}
|
|
21
|
+
open(endpoint) {
|
|
22
|
+
if (this.closed) {
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
const url = new URL(`${endpoint.url.replace(/^http/, 'ws')}/api/exec`);
|
|
26
|
+
url.searchParams.set('token', endpoint.token);
|
|
27
|
+
const inner = new WebSocket(url);
|
|
28
|
+
this.inner = inner;
|
|
29
|
+
inner.onopen = () => {
|
|
30
|
+
for (const text of this.queued.splice(0)) {
|
|
31
|
+
inner.send(text);
|
|
32
|
+
}
|
|
33
|
+
this.queuedBytes = 0;
|
|
34
|
+
};
|
|
35
|
+
inner.onmessage = message => this.outer.open && this.outer.send(String(message.data));
|
|
36
|
+
inner.onclose = event => this.close(event.code === 1000 || event.code === 1001 ? 1001 : 1011, 'The sandbox closed the connection.');
|
|
37
|
+
inner.onerror = () => undefined;
|
|
38
|
+
}
|
|
39
|
+
send(text) {
|
|
40
|
+
var _a;
|
|
41
|
+
if (((_a = this.inner) === null || _a === void 0 ? void 0 : _a.readyState) === WebSocket.OPEN) {
|
|
42
|
+
this.inner.send(text);
|
|
43
|
+
}
|
|
44
|
+
else if (this.queuedBytes + text.length <= MAX_QUEUED_BYTES) {
|
|
45
|
+
this.queued.push(text);
|
|
46
|
+
this.queuedBytes += text.length;
|
|
47
|
+
}
|
|
48
|
+
else {
|
|
49
|
+
this.close(1013, 'The environment is still starting.');
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
close(code, reason) {
|
|
53
|
+
if (this.outer.open) {
|
|
54
|
+
this.outer.close(code, reason);
|
|
55
|
+
}
|
|
56
|
+
this.dispose();
|
|
57
|
+
}
|
|
58
|
+
dispose() {
|
|
59
|
+
var _a;
|
|
60
|
+
if (this.closed) {
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
this.closed = true;
|
|
64
|
+
this.release();
|
|
65
|
+
(_a = this.inner) === null || _a === void 0 ? void 0 : _a.close();
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
exports.GatewayExecProxy = GatewayExecProxy;
|
|
69
|
+
//# sourceMappingURL=gateway-exec.js.map
|
|
@@ -0,0 +1,48 @@
|
|
|
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
|
+
monthlyTokens?: number;
|
|
11
|
+
promptsPerMinute?: number;
|
|
12
|
+
connections?: number;
|
|
13
|
+
providers?: string[];
|
|
14
|
+
own: boolean;
|
|
15
|
+
}
|
|
16
|
+
export declare class PolicyError extends Error {
|
|
17
|
+
}
|
|
18
|
+
export declare namespace GatewayPolicyUtil {
|
|
19
|
+
function rank(role: TaGatewayRole): number;
|
|
20
|
+
/**
|
|
21
|
+
* Limits as a page sent them, checked: whole numbers of 0 and more, a list of providers of those there are, a
|
|
22
|
+
* boolean. `nullable`: those of an account, where null drops a limit; in the defaults null is none, left out.
|
|
23
|
+
*/
|
|
24
|
+
function limits(value: unknown, providers: readonly string[], nullable: boolean): TaGatewayLimits;
|
|
25
|
+
/** An account's own over the defaults: a value of its own wins, null in it is none. */
|
|
26
|
+
function resolve(defaults: TaGatewayLimits, own: TaGatewayLimits | undefined, ownAllowed: boolean): ResolvedLimits;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Who manages the gateway and what members may use: owners are those of TA_GATEWAY_ADMINS, where the gateway runs,
|
|
30
|
+
* which the console cannot change; admins and the default limits are those of `policy.json`, which owners change
|
|
31
|
+
* in the console.
|
|
32
|
+
*/
|
|
33
|
+
export declare class GatewayPolicy {
|
|
34
|
+
protected readonly owners: readonly string[];
|
|
35
|
+
protected readonly file: string;
|
|
36
|
+
protected stored: StoredPolicy;
|
|
37
|
+
constructor(dir: string, owners: readonly string[]);
|
|
38
|
+
role(account: string): TaGatewayRole;
|
|
39
|
+
/** Whether the account is let in by its role, whatever the list of access says. */
|
|
40
|
+
lets(account: string): boolean;
|
|
41
|
+
get defaults(): TaGatewayLimits;
|
|
42
|
+
setDefaults(limits: TaGatewayLimits): void;
|
|
43
|
+
setRole(account: string, role: 'admin' | 'member'): void;
|
|
44
|
+
view(idleMinutes: number): TaGatewayPolicy;
|
|
45
|
+
protected read(): StoredPolicy;
|
|
46
|
+
}
|
|
47
|
+
export {};
|
|
48
|
+
//# sourceMappingURL=gateway-policy.d.ts.map
|
|
@@ -0,0 +1,157 @@
|
|
|
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', 'monthlyTokens', '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
|
+
monthlyTokens: number('monthlyTokens'),
|
|
91
|
+
promptsPerMinute: number('promptsPerMinute'),
|
|
92
|
+
connections: number('connections'),
|
|
93
|
+
providers: Array.isArray(providers) ? providers : undefined,
|
|
94
|
+
own: ownAllowed && own_ !== false,
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
GatewayPolicyUtil.resolve = resolve;
|
|
98
|
+
})(GatewayPolicyUtil || (exports.GatewayPolicyUtil = GatewayPolicyUtil = {}));
|
|
99
|
+
/**
|
|
100
|
+
* Who manages the gateway and what members may use: owners are those of TA_GATEWAY_ADMINS, where the gateway runs,
|
|
101
|
+
* which the console cannot change; admins and the default limits are those of `policy.json`, which owners change
|
|
102
|
+
* in the console.
|
|
103
|
+
*/
|
|
104
|
+
class GatewayPolicy {
|
|
105
|
+
constructor(dir, owners) {
|
|
106
|
+
this.owners = owners;
|
|
107
|
+
this.file = (0, node_path_1.join)(dir, 'policy.json');
|
|
108
|
+
this.stored = this.read();
|
|
109
|
+
}
|
|
110
|
+
role(account) {
|
|
111
|
+
var _a;
|
|
112
|
+
if (this.owners.some(pattern => access_store_1.AccessUtil.matches(pattern, account))) {
|
|
113
|
+
return 'owner';
|
|
114
|
+
}
|
|
115
|
+
return ((_a = this.stored.admins) === null || _a === void 0 ? void 0 : _a.includes(account)) ? 'admin' : 'member';
|
|
116
|
+
}
|
|
117
|
+
/** Whether the account is let in by its role, whatever the list of access says. */
|
|
118
|
+
lets(account) {
|
|
119
|
+
return this.role(account) !== 'member';
|
|
120
|
+
}
|
|
121
|
+
get defaults() {
|
|
122
|
+
var _a;
|
|
123
|
+
return (_a = this.stored.defaults) !== null && _a !== void 0 ? _a : {};
|
|
124
|
+
}
|
|
125
|
+
setDefaults(limits) {
|
|
126
|
+
this.stored = { ...this.stored, defaults: limits };
|
|
127
|
+
(0, tenant_store_1.writePrivate)(this.file, this.stored);
|
|
128
|
+
}
|
|
129
|
+
setRole(account, role) {
|
|
130
|
+
var _a;
|
|
131
|
+
const admins = ((_a = this.stored.admins) !== null && _a !== void 0 ? _a : []).filter(other => other !== account);
|
|
132
|
+
this.stored = { ...this.stored, admins: role === 'admin' ? [...admins, account] : admins };
|
|
133
|
+
(0, tenant_store_1.writePrivate)(this.file, this.stored);
|
|
134
|
+
}
|
|
135
|
+
view(idleMinutes) {
|
|
136
|
+
var _a;
|
|
137
|
+
return {
|
|
138
|
+
defaults: this.defaults,
|
|
139
|
+
admins: [
|
|
140
|
+
...this.owners.map(account => ({ account, role: 'owner' })),
|
|
141
|
+
...((_a = this.stored.admins) !== null && _a !== void 0 ? _a : []).filter(account => this.role(account) === 'admin').map(account => ({ account, role: 'admin' })),
|
|
142
|
+
],
|
|
143
|
+
idleMinutes,
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
read() {
|
|
147
|
+
try {
|
|
148
|
+
const value = JSON.parse((0, node_fs_1.readFileSync)(this.file, 'utf8'));
|
|
149
|
+
return value && typeof value === 'object' ? value : {};
|
|
150
|
+
}
|
|
151
|
+
catch (_a) {
|
|
152
|
+
return {};
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
exports.GatewayPolicy = GatewayPolicy;
|
|
157
|
+
//# sourceMappingURL=gateway-policy.js.map
|
|
@@ -0,0 +1,41 @@
|
|
|
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
|
+
/** Whether the gateway gives its sandboxes models: then it counts their tokens, and holds them to the limit. */
|
|
15
|
+
protected readonly metered: () => boolean;
|
|
16
|
+
protected lastTick: number;
|
|
17
|
+
/** By tenant: the times of its messages within the last minute. */
|
|
18
|
+
protected readonly prompts: Map<string, number[]>;
|
|
19
|
+
constructor(policy: GatewayPolicy, tenants: TenantStore, usage: GatewayUsage, ownAllowed: () => boolean,
|
|
20
|
+
/** Whether the gateway gives its sandboxes models: then it counts their tokens, and holds them to the limit. */
|
|
21
|
+
metered?: () => boolean);
|
|
22
|
+
role(tenant: Tenant): TaGatewayRole;
|
|
23
|
+
limits(tenant: Tenant): ResolvedLimits;
|
|
24
|
+
/** That of this month: a meter of a month before starts again. */
|
|
25
|
+
meter(tenant: Tenant, now?: number): TenantMeter;
|
|
26
|
+
blocked(tenant: Tenant, now?: number): TaQuotaBlock | undefined;
|
|
27
|
+
state(tenant: Tenant, now?: number): TaQuotaState;
|
|
28
|
+
/** Why a call of a model of the gateway is refused now; owners have no limit. */
|
|
29
|
+
refuseModels(tenant: Tenant, now?: number): string | undefined;
|
|
30
|
+
/** What a call of a model took, to the month of the tenant. */
|
|
31
|
+
addTokens(tenantId: string, tokens: number, cost: number, now?: number): void;
|
|
32
|
+
/** What a message of the tenant to its agents needs: false when it sent as many this minute as it may. */
|
|
33
|
+
takePrompt(tenant: Tenant, now?: number): boolean;
|
|
34
|
+
/** When the next message may go: the oldest of the minute leaves it. */
|
|
35
|
+
retryAfter(tenant: Tenant, now?: number): number;
|
|
36
|
+
/** The time since the last tick, to each tenant whose sandbox ran meanwhile; those now blocked. */
|
|
37
|
+
tick(running: readonly string[], now?: number): Tenant[];
|
|
38
|
+
/** Free minutes on top of the limit, this month; never fewer than none. */
|
|
39
|
+
grant(tenant: Tenant, minutes: number, now?: number): Tenant;
|
|
40
|
+
}
|
|
41
|
+
//# sourceMappingURL=gateway-quotas.d.ts.map
|
|
@@ -0,0 +1,139 @@
|
|
|
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
|
+
/** Whether the gateway gives its sandboxes models: then it counts their tokens, and holds them to the limit. */
|
|
16
|
+
metered = () => false) {
|
|
17
|
+
this.policy = policy;
|
|
18
|
+
this.tenants = tenants;
|
|
19
|
+
this.usage = usage;
|
|
20
|
+
this.ownAllowed = ownAllowed;
|
|
21
|
+
this.metered = metered;
|
|
22
|
+
this.lastTick = Date.now();
|
|
23
|
+
/** By tenant: the times of its messages within the last minute. */
|
|
24
|
+
this.prompts = new Map();
|
|
25
|
+
}
|
|
26
|
+
role(tenant) {
|
|
27
|
+
return this.policy.role(tenant.account);
|
|
28
|
+
}
|
|
29
|
+
limits(tenant) {
|
|
30
|
+
if (this.role(tenant) === 'owner') {
|
|
31
|
+
return { own: this.ownAllowed() };
|
|
32
|
+
}
|
|
33
|
+
return gateway_policy_1.GatewayPolicyUtil.resolve(this.policy.defaults, tenant.limits, this.ownAllowed());
|
|
34
|
+
}
|
|
35
|
+
/** That of this month: a meter of a month before starts again. */
|
|
36
|
+
meter(tenant, now = Date.now()) {
|
|
37
|
+
var _a;
|
|
38
|
+
const { key } = gateway_usage_1.GatewayUsageUtil.month(now);
|
|
39
|
+
return ((_a = tenant.meter) === null || _a === void 0 ? void 0 : _a.month) === key ? tenant.meter : { month: key, runMs: 0, bonusMinutes: 0 };
|
|
40
|
+
}
|
|
41
|
+
blocked(tenant, now = Date.now()) {
|
|
42
|
+
if (tenant.suspended && this.role(tenant) !== 'owner') {
|
|
43
|
+
return 'suspended';
|
|
44
|
+
}
|
|
45
|
+
const { freeMinutes } = this.limits(tenant);
|
|
46
|
+
const meter = this.meter(tenant, now);
|
|
47
|
+
return freeMinutes !== undefined && meter.runMs >= (freeMinutes + meter.bonusMinutes) * MINUTE ? 'minutes' : undefined;
|
|
48
|
+
}
|
|
49
|
+
state(tenant, now = Date.now()) {
|
|
50
|
+
var _a, _b;
|
|
51
|
+
const { key, next } = gateway_usage_1.GatewayUsageUtil.month(now);
|
|
52
|
+
const meter = this.meter(tenant, now);
|
|
53
|
+
const limits = this.limits(tenant);
|
|
54
|
+
const metered = this.metered();
|
|
55
|
+
const month = metered ? { tokens: (_a = meter.tokens) !== null && _a !== void 0 ? _a : 0, cost: (_b = meter.cost) !== null && _b !== void 0 ? _b : 0 } : this.usage.month(tenant.id, now);
|
|
56
|
+
return {
|
|
57
|
+
month: key,
|
|
58
|
+
resetsAt: next,
|
|
59
|
+
minutes: { used: Math.floor(meter.runMs / MINUTE), limit: limits.freeMinutes, bonus: meter.bonusMinutes },
|
|
60
|
+
tokens: { used: month.tokens, cost: month.cost, limit: metered ? limits.monthlyTokens : undefined, metered },
|
|
61
|
+
promptsPerMinute: limits.promptsPerMinute,
|
|
62
|
+
connections: limits.connections,
|
|
63
|
+
blocked: this.blocked(tenant, now),
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
/** Why a call of a model of the gateway is refused now; owners have no limit. */
|
|
67
|
+
refuseModels(tenant, now = Date.now()) {
|
|
68
|
+
var _a;
|
|
69
|
+
if (this.role(tenant) === 'owner') {
|
|
70
|
+
return undefined;
|
|
71
|
+
}
|
|
72
|
+
if (tenant.suspended) {
|
|
73
|
+
return 'Your account is suspended by an administrator of the gateway.';
|
|
74
|
+
}
|
|
75
|
+
const limit = this.limits(tenant).monthlyTokens;
|
|
76
|
+
const used = (_a = this.meter(tenant, now).tokens) !== null && _a !== void 0 ? _a : 0;
|
|
77
|
+
// The words pi does not retry on: the month is over, not a moment of load.
|
|
78
|
+
return limit !== undefined && used >= limit
|
|
79
|
+
? `Monthly usage limit reached: ${used} of ${limit} tokens this month; it starts again next month, or ask an administrator.`
|
|
80
|
+
: undefined;
|
|
81
|
+
}
|
|
82
|
+
/** What a call of a model took, to the month of the tenant. */
|
|
83
|
+
addTokens(tenantId, tokens, cost, now = Date.now()) {
|
|
84
|
+
var _a, _b;
|
|
85
|
+
const tenant = this.tenants.get(tenantId);
|
|
86
|
+
if (!tenant) {
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
const meter = this.meter(tenant, now);
|
|
90
|
+
this.tenants.update(tenantId, { meter: { ...meter, tokens: ((_a = meter.tokens) !== null && _a !== void 0 ? _a : 0) + tokens, cost: ((_b = meter.cost) !== null && _b !== void 0 ? _b : 0) + cost } });
|
|
91
|
+
}
|
|
92
|
+
/** What a message of the tenant to its agents needs: false when it sent as many this minute as it may. */
|
|
93
|
+
takePrompt(tenant, now = Date.now()) {
|
|
94
|
+
var _a;
|
|
95
|
+
const limit = this.limits(tenant).promptsPerMinute;
|
|
96
|
+
if (limit === undefined) {
|
|
97
|
+
return true;
|
|
98
|
+
}
|
|
99
|
+
const times = ((_a = this.prompts.get(tenant.id)) !== null && _a !== void 0 ? _a : []).filter(time => now - time < MINUTE);
|
|
100
|
+
if (times.length >= limit) {
|
|
101
|
+
this.prompts.set(tenant.id, times);
|
|
102
|
+
return false;
|
|
103
|
+
}
|
|
104
|
+
times.push(now);
|
|
105
|
+
this.prompts.set(tenant.id, times);
|
|
106
|
+
return true;
|
|
107
|
+
}
|
|
108
|
+
/** When the next message may go: the oldest of the minute leaves it. */
|
|
109
|
+
retryAfter(tenant, now = Date.now()) {
|
|
110
|
+
var _a;
|
|
111
|
+
const oldest = (_a = this.prompts.get(tenant.id)) === null || _a === void 0 ? void 0 : _a[0];
|
|
112
|
+
return oldest === undefined ? 0 : Math.max(0, MINUTE - (now - oldest));
|
|
113
|
+
}
|
|
114
|
+
/** The time since the last tick, to each tenant whose sandbox ran meanwhile; those now blocked. */
|
|
115
|
+
tick(running, now = Date.now()) {
|
|
116
|
+
const elapsed = Math.min(Math.max(0, now - this.lastTick), MAX_TICK_MS);
|
|
117
|
+
this.lastTick = now;
|
|
118
|
+
const blocked = [];
|
|
119
|
+
for (const id of running) {
|
|
120
|
+
const tenant = this.tenants.get(id);
|
|
121
|
+
if (!tenant) {
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
const meter = this.meter(tenant, now);
|
|
125
|
+
const next = this.tenants.update(id, { meter: { ...meter, runMs: meter.runMs + elapsed } });
|
|
126
|
+
if (this.blocked(next, now)) {
|
|
127
|
+
blocked.push(next);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return blocked;
|
|
131
|
+
}
|
|
132
|
+
/** Free minutes on top of the limit, this month; never fewer than none. */
|
|
133
|
+
grant(tenant, minutes, now = Date.now()) {
|
|
134
|
+
const meter = this.meter(tenant, now);
|
|
135
|
+
return this.tenants.update(tenant.id, { meter: { ...meter, bonusMinutes: Math.max(0, meter.bonusMinutes + minutes) } });
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
exports.GatewayQuotas = GatewayQuotas;
|
|
139
|
+
//# sourceMappingURL=gateway-quotas.js.map
|
|
@@ -2,9 +2,15 @@ import { type IncomingMessage, type Server, type ServerResponse } from 'node:htt
|
|
|
2
2
|
import { type Duplex } from 'node:stream';
|
|
3
3
|
import { SignInFlow } from '@celljs/ta-host/lib/node/sign-in/sign-in-flow';
|
|
4
4
|
import { type SignInAccount } from '@celljs/ta-host/lib/node/sign-in/sign-in-provider';
|
|
5
|
+
import { type TaQuotaBlock } from '@celljs/ta-protocol';
|
|
5
6
|
import { Environments } from './environments';
|
|
7
|
+
import { GatewayAudit } from './gateway-audit';
|
|
8
|
+
import { GatewayPolicy } from './gateway-policy';
|
|
9
|
+
import { GatewayQuotas } from './gateway-quotas';
|
|
6
10
|
import { type GatewayCaller, GatewayService } from './gateway-service';
|
|
7
11
|
import { GatewaySocket } from './gateway-socket';
|
|
12
|
+
import { GatewayUsage } from './gateway-usage';
|
|
13
|
+
import { type GatewayModelsConfig, ModelProxy } from './model-proxy';
|
|
8
14
|
import { type SandboxProviderFactory, SandboxProviders } from './sandbox-provider';
|
|
9
15
|
import { SignInLinks } from './sign-in-links';
|
|
10
16
|
import { TenantStore } from './tenant-store';
|
|
@@ -19,8 +25,19 @@ export interface GatewayServerOptions {
|
|
|
19
25
|
publicDir: string;
|
|
20
26
|
taCommand: string[];
|
|
21
27
|
env?: Record<string, string | undefined>;
|
|
28
|
+
/** Of Ta, for the console. */
|
|
29
|
+
version?: string;
|
|
22
30
|
}
|
|
23
31
|
export declare namespace GatewayServerUtil {
|
|
32
|
+
/**
|
|
33
|
+
* Where a sandbox reaches the gateway, by the type of its provider: a container the host (host.docker.internal,
|
|
34
|
+
* mapped on Linux too), a process of this machine 127.0.0.1, another the public address.
|
|
35
|
+
*/
|
|
36
|
+
function reach(type: string, port: number, publicUrl: string | undefined): string;
|
|
37
|
+
/** Where another Ta reaches the exec server of its account's sandbox. */
|
|
38
|
+
const EXEC_PATH = "/api/exec";
|
|
39
|
+
/** What a page is told when its Ta does not start for its account's limits; TaGatewayInfo.quota says it in the page's words. */
|
|
40
|
+
function blockedReason(block: TaQuotaBlock | undefined): string | undefined;
|
|
24
41
|
/** A file of `root` for a path of the page, never outside it; the page for what is not a file. */
|
|
25
42
|
function file(root: string, urlPath: string): string;
|
|
26
43
|
/**
|
|
@@ -50,11 +67,20 @@ export declare class GatewayServer {
|
|
|
50
67
|
readonly links: SignInLinks;
|
|
51
68
|
protected readonly service: GatewayService;
|
|
52
69
|
protected readonly sockets: Set<GatewaySocket>;
|
|
53
|
-
|
|
70
|
+
readonly policy: GatewayPolicy;
|
|
71
|
+
readonly quotas: GatewayQuotas;
|
|
72
|
+
readonly usage: GatewayUsage;
|
|
73
|
+
readonly audit: GatewayAudit;
|
|
74
|
+
readonly models: ModelProxy;
|
|
75
|
+
/** The port it listens on, once it does. */
|
|
76
|
+
protected port?: number;
|
|
54
77
|
protected server?: Server;
|
|
78
|
+
protected ticker?: ReturnType<typeof setInterval>;
|
|
55
79
|
static create(options: GatewayServerOptions): Promise<GatewayServer>;
|
|
56
|
-
protected constructor(options: GatewayServerOptions, providers: Awaited<ReturnType<typeof SandboxProviders.create>>, config: ReturnType<typeof SandboxProviders.read
|
|
80
|
+
protected constructor(options: GatewayServerOptions, providers: Awaited<ReturnType<typeof SandboxProviders.create>>, config: ReturnType<typeof SandboxProviders.read>, models?: GatewayModelsConfig);
|
|
57
81
|
isAdmin(account: string): boolean;
|
|
82
|
+
/** The minutes of the sandboxes that ran since the last time; those out of them, or suspended, stop. */
|
|
83
|
+
tick(now?: number): Promise<void>;
|
|
58
84
|
listen(): Promise<string>;
|
|
59
85
|
close(): Promise<void>;
|
|
60
86
|
/** The browsers whose sign-in no longer works are cut off. */
|