@celljs/ta-gateway 4.15.2 → 4.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/esm/node/command-sandbox.d.ts +1 -0
- package/esm/node/command-sandbox.js +10 -1
- package/esm/node/docker-engine.d.ts +5 -0
- package/esm/node/docker-engine.js +11 -0
- package/esm/node/docker-sandbox.d.ts +3 -0
- package/esm/node/docker-sandbox.js +17 -3
- package/esm/node/environments.d.ts +2 -0
- package/esm/node/environments.js +5 -3
- package/esm/node/gateway-exec.d.ts +19 -0
- package/esm/node/gateway-exec.js +65 -0
- package/esm/node/gateway-policy.d.ts +1 -0
- package/esm/node/gateway-policy.js +2 -1
- package/esm/node/gateway-quotas.d.ts +9 -1
- package/esm/node/gateway-quotas.js +34 -3
- package/esm/node/gateway-server.d.ts +12 -1
- package/esm/node/gateway-server.js +55 -4
- package/esm/node/gateway-service.d.ts +8 -0
- package/esm/node/gateway-service.js +23 -4
- package/esm/node/local-sandbox.d.ts +1 -0
- package/esm/node/local-sandbox.js +2 -1
- package/esm/node/model-proxy.d.ts +105 -0
- package/esm/node/model-proxy.js +435 -0
- package/esm/node/sandbox-provider.d.ts +7 -0
- package/esm/node/tenant-store.d.ts +7 -0
- package/esm/node/tenant-store.js +10 -0
- package/lib/node/command-sandbox.d.ts +1 -0
- package/lib/node/command-sandbox.js +10 -1
- package/lib/node/docker-engine.d.ts +5 -0
- package/lib/node/docker-engine.js +11 -0
- package/lib/node/docker-sandbox.d.ts +3 -0
- package/lib/node/docker-sandbox.js +17 -3
- package/lib/node/environments.d.ts +2 -0
- package/lib/node/environments.js +5 -3
- package/lib/node/gateway-exec.d.ts +20 -0
- package/lib/node/gateway-exec.js +69 -0
- package/lib/node/gateway-policy.d.ts +1 -0
- package/lib/node/gateway-policy.js +2 -1
- package/lib/node/gateway-quotas.d.ts +9 -1
- package/lib/node/gateway-quotas.js +34 -3
- package/lib/node/gateway-server.d.ts +12 -1
- package/lib/node/gateway-server.js +55 -4
- package/lib/node/gateway-service.d.ts +8 -0
- package/lib/node/gateway-service.js +23 -4
- package/lib/node/local-sandbox.d.ts +1 -0
- package/lib/node/local-sandbox.js +2 -1
- package/lib/node/model-proxy.d.ts +106 -0
- package/lib/node/model-proxy.js +440 -0
- package/lib/node/sandbox-provider.d.ts +7 -0
- package/lib/node/tenant-store.d.ts +7 -0
- package/lib/node/tenant-store.js +10 -0
- package/package.json +4 -4
|
@@ -27,6 +27,7 @@ export class CommandSandbox {
|
|
|
27
27
|
this.id = id;
|
|
28
28
|
this.type = 'command';
|
|
29
29
|
this.name = SandboxProviders.string(config, 'name', id);
|
|
30
|
+
this.gatewayUrl = SandboxProviders.string(config, 'gatewayUrl');
|
|
30
31
|
const start = SandboxProviders.string(config, 'start');
|
|
31
32
|
if (!start) {
|
|
32
33
|
throw new Error(`The provider "${id}" of the type command needs "start", a command that prints the address of the Ta service.`);
|
|
@@ -69,7 +70,15 @@ export class CommandSandbox {
|
|
|
69
70
|
run(command, tenant, extra = {}) {
|
|
70
71
|
return new Promise((resolve, reject) => {
|
|
71
72
|
const child = spawn('sh', ['-c', command], {
|
|
72
|
-
env: {
|
|
73
|
+
env: {
|
|
74
|
+
...process.env,
|
|
75
|
+
...this.env,
|
|
76
|
+
...tenant.env,
|
|
77
|
+
TA_TENANT_ID: tenant.id,
|
|
78
|
+
TA_TENANT_ACCOUNT: tenant.account,
|
|
79
|
+
TA_SERVE_TOKEN: tenant.token,
|
|
80
|
+
...extra,
|
|
81
|
+
},
|
|
73
82
|
stdio: ['ignore', 'pipe', 'pipe'],
|
|
74
83
|
});
|
|
75
84
|
let stdout = '';
|
|
@@ -43,6 +43,8 @@ export declare class DockerEngine {
|
|
|
43
43
|
} | undefined>;
|
|
44
44
|
/** The last `lines` of what a container wrote, its output and errors in their order; empty for one that is not there. */
|
|
45
45
|
logs(name: string, lines: number): Promise<string>;
|
|
46
|
+
/** Removed, its volumes kept; nothing when it is not there. */
|
|
47
|
+
remove(name: string): Promise<void>;
|
|
46
48
|
/** A bridge network, made when missing; `isolated`: its containers cannot reach each other. */
|
|
47
49
|
ensureNetwork(name: string, isolated: boolean): Promise<void>;
|
|
48
50
|
/** Pulled when it is not here; one built here (ta:latest) is. */
|
|
@@ -50,6 +52,9 @@ export declare class DockerEngine {
|
|
|
50
52
|
}
|
|
51
53
|
export interface DockerContainer {
|
|
52
54
|
Id: string;
|
|
55
|
+
Config?: {
|
|
56
|
+
Env?: string[];
|
|
57
|
+
};
|
|
53
58
|
State: {
|
|
54
59
|
Running: boolean;
|
|
55
60
|
Status: string;
|
|
@@ -132,6 +132,17 @@ export class DockerEngine {
|
|
|
132
132
|
throw error;
|
|
133
133
|
}
|
|
134
134
|
}
|
|
135
|
+
/** Removed, its volumes kept; nothing when it is not there. */
|
|
136
|
+
async remove(name) {
|
|
137
|
+
try {
|
|
138
|
+
await this.call('DELETE', `/containers/${encodeURIComponent(name)}?force=true`);
|
|
139
|
+
}
|
|
140
|
+
catch (error) {
|
|
141
|
+
if (!(error instanceof DockerError && error.status === 404)) {
|
|
142
|
+
throw error;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
135
146
|
/** A bridge network, made when missing; `isolated`: its containers cannot reach each other. */
|
|
136
147
|
async ensureNetwork(name, isolated) {
|
|
137
148
|
try {
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { DockerEngine } from './docker-engine.js';
|
|
2
2
|
import { type SandboxEndpoint, type SandboxProvider, type SandboxProviderConfig, type SandboxState, type SandboxTenant, type SandboxUsage } from './sandbox-provider.js';
|
|
3
3
|
export declare namespace DockerSandboxUtil {
|
|
4
|
+
/** Whether a container has each variable of `env` as it is. */
|
|
5
|
+
function hasEnv(have: string[] | undefined, want: Record<string, string> | undefined): boolean;
|
|
4
6
|
/** `github:Octo.Cat` → `octo-cat`: a name of a host from the account, `ta` when nothing is left. */
|
|
5
7
|
function hostname(account: string): string;
|
|
6
8
|
}
|
|
@@ -33,6 +35,7 @@ export declare class DockerSandbox implements SandboxProvider {
|
|
|
33
35
|
protected readonly options: DockerSandboxOptions;
|
|
34
36
|
readonly type = "docker";
|
|
35
37
|
readonly name: string;
|
|
38
|
+
readonly gatewayUrl?: string;
|
|
36
39
|
protected readonly engine: DockerEngine;
|
|
37
40
|
static options(config: SandboxProviderConfig): DockerSandboxOptions;
|
|
38
41
|
constructor(id: string, config: SandboxProviderConfig, options?: DockerSandboxOptions, engine?: DockerEngine);
|
|
@@ -2,6 +2,12 @@ import { DockerEngine, DockerEngineUtil } from './docker-engine.js';
|
|
|
2
2
|
import { SandboxProviders, } from './sandbox-provider.js';
|
|
3
3
|
export var DockerSandboxUtil;
|
|
4
4
|
(function (DockerSandboxUtil) {
|
|
5
|
+
/** Whether a container has each variable of `env` as it is. */
|
|
6
|
+
function hasEnv(have, want) {
|
|
7
|
+
const set = new Set(have !== null && have !== void 0 ? have : []);
|
|
8
|
+
return Object.entries(want !== null && want !== void 0 ? want : {}).every(([key, value]) => set.has(`${key}=${value}`));
|
|
9
|
+
}
|
|
10
|
+
DockerSandboxUtil.hasEnv = hasEnv;
|
|
5
11
|
/** `github:Octo.Cat` → `octo-cat`: a name of a host from the account, `ta` when nothing is left. */
|
|
6
12
|
function hostname(account) {
|
|
7
13
|
const name = account
|
|
@@ -52,12 +58,18 @@ export class DockerSandbox {
|
|
|
52
58
|
this.options = options;
|
|
53
59
|
this.type = 'docker';
|
|
54
60
|
this.name = SandboxProviders.string(config, 'name', 'Docker');
|
|
61
|
+
this.gatewayUrl = SandboxProviders.string(config, 'gatewayUrl');
|
|
55
62
|
this.engine = engine !== null && engine !== void 0 ? engine : new DockerEngine({ host: options.host });
|
|
56
63
|
}
|
|
57
64
|
async start(tenant) {
|
|
58
|
-
var _a, _b, _c;
|
|
65
|
+
var _a, _b, _c, _d;
|
|
59
66
|
const name = this.containerName(tenant);
|
|
60
67
|
let container = await this.engine.inspect(name);
|
|
68
|
+
if (container && !DockerSandboxUtil.hasEnv((_a = container.Config) === null || _a === void 0 ? void 0 : _a.Env, tenant.env)) {
|
|
69
|
+
// Made before the gateway gave it this environment (the models of the gateway): made again, its volume kept.
|
|
70
|
+
await this.engine.remove(name);
|
|
71
|
+
container = undefined;
|
|
72
|
+
}
|
|
61
73
|
if (!container) {
|
|
62
74
|
await this.engine.ensureImage(this.options.image);
|
|
63
75
|
await this.engine.ensureNetwork(this.options.network, true);
|
|
@@ -68,7 +80,7 @@ export class DockerSandbox {
|
|
|
68
80
|
await this.engine.start(name);
|
|
69
81
|
container = await this.engine.inspect(name);
|
|
70
82
|
}
|
|
71
|
-
const port = (
|
|
83
|
+
const port = (_d = (_c = (_b = container === null || container === void 0 ? void 0 : container.NetworkSettings.Ports) === null || _b === void 0 ? void 0 : _b[PORT]) === null || _c === void 0 ? void 0 : _c[0]) === null || _d === void 0 ? void 0 : _d.HostPort;
|
|
72
84
|
if (!port) {
|
|
73
85
|
throw new Error(`The container ${name} publishes no port for ${PORT}.`);
|
|
74
86
|
}
|
|
@@ -94,11 +106,13 @@ export class DockerSandbox {
|
|
|
94
106
|
Image: this.options.image,
|
|
95
107
|
// What the Ta of the tenant tells its clients its machine is, as the list of computers of the phone shows it.
|
|
96
108
|
Hostname: DockerSandboxUtil.hostname(tenant.account),
|
|
97
|
-
Env: [`TA_SERVE_TOKEN=${tenant.token}`, ...Object.entries(this.options.env).map(([key, value]) => `${key}=${value}`)],
|
|
109
|
+
Env: [`TA_SERVE_TOKEN=${tenant.token}`, ...Object.entries({ ...this.options.env, ...tenant.env }).map(([key, value]) => `${key}=${value}`)],
|
|
98
110
|
Labels: { 'cell.ta.tenant': tenant.id, 'cell.ta.account': tenant.account },
|
|
99
111
|
ExposedPorts: { [PORT]: {} },
|
|
100
112
|
HostConfig: {
|
|
101
113
|
PortBindings: { [PORT]: [{ HostIp: this.options.bind, HostPort: '' }] },
|
|
114
|
+
// The gateway, for the models it gives (TA_MODEL_PROXY_URL): the host, on Linux too.
|
|
115
|
+
ExtraHosts: ['host.docker.internal:host-gateway'],
|
|
102
116
|
Mounts: [{ Type: 'volume', Source: name, Target: '/home/ta' }],
|
|
103
117
|
NetworkMode: this.options.network,
|
|
104
118
|
Memory: this.options.memory,
|
|
@@ -48,6 +48,8 @@ export declare class Environments {
|
|
|
48
48
|
protected readonly running: Map<string, Running>;
|
|
49
49
|
/** Why the tenant's Ta may not start now (suspended, its free minutes used), checked before each start. */
|
|
50
50
|
guard?: (tenant: Tenant) => string | undefined;
|
|
51
|
+
/** More of the environment of a sandbox the gateway starts: what reaches the models of the gateway. */
|
|
52
|
+
envOf?: (tenant: Tenant, provider: SandboxProvider) => Record<string, string> | undefined;
|
|
51
53
|
constructor(providers: SandboxProvider[], tenants: TenantStore, settings: {
|
|
52
54
|
default?: string;
|
|
53
55
|
own: boolean;
|
package/esm/node/environments.js
CHANGED
|
@@ -308,9 +308,11 @@ export class Environments {
|
|
|
308
308
|
running.error = undefined;
|
|
309
309
|
const starting = (async () => {
|
|
310
310
|
var _a;
|
|
311
|
-
|
|
312
|
-
const
|
|
313
|
-
|
|
311
|
+
var _b;
|
|
312
|
+
const { provider, own } = this.provider(tenant);
|
|
313
|
+
const env = own ? undefined : (_a = this.envOf) === null || _a === void 0 ? void 0 : _a.call(this, tenant, provider);
|
|
314
|
+
const endpoint = await provider.start({ ...EnvironmentsUtil.sandboxTenant(tenant), ...(env ? { env } : {}) });
|
|
315
|
+
await EnvironmentsUtil.waitReady(endpoint.url, (_b = this.settings.readyTimeoutMs) !== null && _b !== void 0 ? _b : provider.readyTimeoutMs);
|
|
314
316
|
return endpoint;
|
|
315
317
|
})();
|
|
316
318
|
running.starting = starting;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { WebSocketConnection } from '@celljs/rpc/lib/node/websocket/websocket-connection';
|
|
2
|
+
import type { SandboxEndpoint } from './sandbox-provider.js';
|
|
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
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/** What waits for the sandbox at most, as GatewaySocket. */
|
|
2
|
+
const MAX_QUEUED_BYTES = 16 * 1024 * 1024;
|
|
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 class GatewayExecProxy {
|
|
8
|
+
constructor(outer, endpoint, release) {
|
|
9
|
+
this.outer = outer;
|
|
10
|
+
this.release = release;
|
|
11
|
+
this.queued = [];
|
|
12
|
+
this.queuedBytes = 0;
|
|
13
|
+
this.closed = false;
|
|
14
|
+
outer.onMessage(text => this.send(text));
|
|
15
|
+
outer.onClose(() => this.dispose());
|
|
16
|
+
endpoint.then(found => this.open(found), (error) => this.close(1011, `Your environment did not start: ${error.message}`.slice(0, 120)));
|
|
17
|
+
}
|
|
18
|
+
open(endpoint) {
|
|
19
|
+
if (this.closed) {
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
const url = new URL(`${endpoint.url.replace(/^http/, 'ws')}/api/exec`);
|
|
23
|
+
url.searchParams.set('token', endpoint.token);
|
|
24
|
+
const inner = new WebSocket(url);
|
|
25
|
+
this.inner = inner;
|
|
26
|
+
inner.onopen = () => {
|
|
27
|
+
for (const text of this.queued.splice(0)) {
|
|
28
|
+
inner.send(text);
|
|
29
|
+
}
|
|
30
|
+
this.queuedBytes = 0;
|
|
31
|
+
};
|
|
32
|
+
inner.onmessage = message => this.outer.open && this.outer.send(String(message.data));
|
|
33
|
+
inner.onclose = event => this.close(event.code === 1000 || event.code === 1001 ? 1001 : 1011, 'The sandbox closed the connection.');
|
|
34
|
+
inner.onerror = () => undefined;
|
|
35
|
+
}
|
|
36
|
+
send(text) {
|
|
37
|
+
var _a;
|
|
38
|
+
if (((_a = this.inner) === null || _a === void 0 ? void 0 : _a.readyState) === WebSocket.OPEN) {
|
|
39
|
+
this.inner.send(text);
|
|
40
|
+
}
|
|
41
|
+
else if (this.queuedBytes + text.length <= MAX_QUEUED_BYTES) {
|
|
42
|
+
this.queued.push(text);
|
|
43
|
+
this.queuedBytes += text.length;
|
|
44
|
+
}
|
|
45
|
+
else {
|
|
46
|
+
this.close(1013, 'The environment is still starting.');
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
close(code, reason) {
|
|
50
|
+
if (this.outer.open) {
|
|
51
|
+
this.outer.close(code, reason);
|
|
52
|
+
}
|
|
53
|
+
this.dispose();
|
|
54
|
+
}
|
|
55
|
+
dispose() {
|
|
56
|
+
var _a;
|
|
57
|
+
if (this.closed) {
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
this.closed = true;
|
|
61
|
+
this.release();
|
|
62
|
+
(_a = this.inner) === null || _a === void 0 ? void 0 : _a.close();
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
//# sourceMappingURL=gateway-exec.js.map
|
|
@@ -7,6 +7,7 @@ interface StoredPolicy {
|
|
|
7
7
|
/** The limits of a member once the defaults and their own are taken together: none where a value is missing. */
|
|
8
8
|
export interface ResolvedLimits {
|
|
9
9
|
freeMinutes?: number;
|
|
10
|
+
monthlyTokens?: number;
|
|
10
11
|
promptsPerMinute?: number;
|
|
11
12
|
connections?: number;
|
|
12
13
|
providers?: string[];
|
|
@@ -6,7 +6,7 @@ export class PolicyError extends Error {
|
|
|
6
6
|
}
|
|
7
7
|
export var GatewayPolicyUtil;
|
|
8
8
|
(function (GatewayPolicyUtil) {
|
|
9
|
-
const NUMBERS = ['freeMinutes', 'promptsPerMinute', 'connections'];
|
|
9
|
+
const NUMBERS = ['freeMinutes', 'monthlyTokens', 'promptsPerMinute', 'connections'];
|
|
10
10
|
const RANK = { member: 0, admin: 1, owner: 2 };
|
|
11
11
|
function rank(role) {
|
|
12
12
|
return RANK[role];
|
|
@@ -83,6 +83,7 @@ export var GatewayPolicyUtil;
|
|
|
83
83
|
const own_ = pick('own');
|
|
84
84
|
return {
|
|
85
85
|
freeMinutes: number('freeMinutes'),
|
|
86
|
+
monthlyTokens: number('monthlyTokens'),
|
|
86
87
|
promptsPerMinute: number('promptsPerMinute'),
|
|
87
88
|
connections: number('connections'),
|
|
88
89
|
providers: Array.isArray(providers) ? providers : undefined,
|
|
@@ -11,16 +11,24 @@ export declare class GatewayQuotas {
|
|
|
11
11
|
protected readonly tenants: TenantStore;
|
|
12
12
|
protected readonly usage: GatewayUsage;
|
|
13
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;
|
|
14
16
|
protected lastTick: number;
|
|
15
17
|
/** By tenant: the times of its messages within the last minute. */
|
|
16
18
|
protected readonly prompts: Map<string, number[]>;
|
|
17
|
-
constructor(policy: GatewayPolicy, tenants: TenantStore, usage: GatewayUsage, ownAllowed: () => boolean
|
|
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);
|
|
18
22
|
role(tenant: Tenant): TaGatewayRole;
|
|
19
23
|
limits(tenant: Tenant): ResolvedLimits;
|
|
20
24
|
/** That of this month: a meter of a month before starts again. */
|
|
21
25
|
meter(tenant: Tenant, now?: number): TenantMeter;
|
|
22
26
|
blocked(tenant: Tenant, now?: number): TaQuotaBlock | undefined;
|
|
23
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;
|
|
24
32
|
/** What a message of the tenant to its agents needs: false when it sent as many this minute as it may. */
|
|
25
33
|
takePrompt(tenant: Tenant, now?: number): boolean;
|
|
26
34
|
/** When the next message may go: the oldest of the minute leaves it. */
|
|
@@ -8,11 +8,14 @@ const MAX_TICK_MS = 2 * MINUTE;
|
|
|
8
8
|
* gateway as it sees them run, and the messages a minute they send their agents. Owners have no limits.
|
|
9
9
|
*/
|
|
10
10
|
export class GatewayQuotas {
|
|
11
|
-
constructor(policy, tenants, usage, ownAllowed
|
|
11
|
+
constructor(policy, tenants, usage, ownAllowed,
|
|
12
|
+
/** Whether the gateway gives its sandboxes models: then it counts their tokens, and holds them to the limit. */
|
|
13
|
+
metered = () => false) {
|
|
12
14
|
this.policy = policy;
|
|
13
15
|
this.tenants = tenants;
|
|
14
16
|
this.usage = usage;
|
|
15
17
|
this.ownAllowed = ownAllowed;
|
|
18
|
+
this.metered = metered;
|
|
16
19
|
this.lastTick = Date.now();
|
|
17
20
|
/** By tenant: the times of its messages within the last minute. */
|
|
18
21
|
this.prompts = new Map();
|
|
@@ -41,20 +44,48 @@ export class GatewayQuotas {
|
|
|
41
44
|
return freeMinutes !== undefined && meter.runMs >= (freeMinutes + meter.bonusMinutes) * MINUTE ? 'minutes' : undefined;
|
|
42
45
|
}
|
|
43
46
|
state(tenant, now = Date.now()) {
|
|
47
|
+
var _a, _b;
|
|
44
48
|
const { key, next } = GatewayUsageUtil.month(now);
|
|
45
49
|
const meter = this.meter(tenant, now);
|
|
46
50
|
const limits = this.limits(tenant);
|
|
47
|
-
const
|
|
51
|
+
const metered = this.metered();
|
|
52
|
+
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);
|
|
48
53
|
return {
|
|
49
54
|
month: key,
|
|
50
55
|
resetsAt: next,
|
|
51
56
|
minutes: { used: Math.floor(meter.runMs / MINUTE), limit: limits.freeMinutes, bonus: meter.bonusMinutes },
|
|
52
|
-
tokens: { used: month.tokens, cost: month.cost },
|
|
57
|
+
tokens: { used: month.tokens, cost: month.cost, limit: metered ? limits.monthlyTokens : undefined, metered },
|
|
53
58
|
promptsPerMinute: limits.promptsPerMinute,
|
|
54
59
|
connections: limits.connections,
|
|
55
60
|
blocked: this.blocked(tenant, now),
|
|
56
61
|
};
|
|
57
62
|
}
|
|
63
|
+
/** Why a call of a model of the gateway is refused now; owners have no limit. */
|
|
64
|
+
refuseModels(tenant, now = Date.now()) {
|
|
65
|
+
var _a;
|
|
66
|
+
if (this.role(tenant) === 'owner') {
|
|
67
|
+
return undefined;
|
|
68
|
+
}
|
|
69
|
+
if (tenant.suspended) {
|
|
70
|
+
return 'Your account is suspended by an administrator of the gateway.';
|
|
71
|
+
}
|
|
72
|
+
const limit = this.limits(tenant).monthlyTokens;
|
|
73
|
+
const used = (_a = this.meter(tenant, now).tokens) !== null && _a !== void 0 ? _a : 0;
|
|
74
|
+
// The words pi does not retry on: the month is over, not a moment of load.
|
|
75
|
+
return limit !== undefined && used >= limit
|
|
76
|
+
? `Monthly usage limit reached: ${used} of ${limit} tokens this month; it starts again next month, or ask an administrator.`
|
|
77
|
+
: undefined;
|
|
78
|
+
}
|
|
79
|
+
/** What a call of a model took, to the month of the tenant. */
|
|
80
|
+
addTokens(tenantId, tokens, cost, now = Date.now()) {
|
|
81
|
+
var _a, _b;
|
|
82
|
+
const tenant = this.tenants.get(tenantId);
|
|
83
|
+
if (!tenant) {
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
const meter = this.meter(tenant, now);
|
|
87
|
+
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 } });
|
|
88
|
+
}
|
|
58
89
|
/** What a message of the tenant to its agents needs: false when it sent as many this minute as it may. */
|
|
59
90
|
takePrompt(tenant, now = Date.now()) {
|
|
60
91
|
var _a;
|
|
@@ -10,6 +10,7 @@ import { GatewayQuotas } from './gateway-quotas.js';
|
|
|
10
10
|
import { type GatewayCaller, GatewayService } from './gateway-service.js';
|
|
11
11
|
import { GatewaySocket } from './gateway-socket.js';
|
|
12
12
|
import { GatewayUsage } from './gateway-usage.js';
|
|
13
|
+
import { type GatewayModelsConfig, ModelProxy } from './model-proxy.js';
|
|
13
14
|
import { type SandboxProviderFactory, SandboxProviders } from './sandbox-provider.js';
|
|
14
15
|
import { SignInLinks } from './sign-in-links.js';
|
|
15
16
|
import { TenantStore } from './tenant-store.js';
|
|
@@ -28,6 +29,13 @@ export interface GatewayServerOptions {
|
|
|
28
29
|
version?: string;
|
|
29
30
|
}
|
|
30
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";
|
|
31
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. */
|
|
32
40
|
function blockedReason(block: TaQuotaBlock | undefined): string | undefined;
|
|
33
41
|
/** A file of `root` for a path of the page, never outside it; the page for what is not a file. */
|
|
@@ -63,10 +71,13 @@ export declare class GatewayServer {
|
|
|
63
71
|
readonly quotas: GatewayQuotas;
|
|
64
72
|
readonly usage: GatewayUsage;
|
|
65
73
|
readonly audit: GatewayAudit;
|
|
74
|
+
readonly models: ModelProxy;
|
|
75
|
+
/** The port it listens on, once it does. */
|
|
76
|
+
protected port?: number;
|
|
66
77
|
protected server?: Server;
|
|
67
78
|
protected ticker?: ReturnType<typeof setInterval>;
|
|
68
79
|
static create(options: GatewayServerOptions): Promise<GatewayServer>;
|
|
69
|
-
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);
|
|
70
81
|
isAdmin(account: string): boolean;
|
|
71
82
|
/** The minutes of the sandboxes that ran since the last time; those out of them, or suspended, stop. */
|
|
72
83
|
tick(now?: number): Promise<void>;
|
|
@@ -13,12 +13,14 @@ import { CommandSandbox } from './command-sandbox.js';
|
|
|
13
13
|
import { DockerSandbox } from './docker-sandbox.js';
|
|
14
14
|
import { Environments } from './environments.js';
|
|
15
15
|
import { GatewayAudit } from './gateway-audit.js';
|
|
16
|
+
import { GatewayExecProxy } from './gateway-exec.js';
|
|
16
17
|
import { GatewayPolicy } from './gateway-policy.js';
|
|
17
18
|
import { GatewayQuotas } from './gateway-quotas.js';
|
|
18
19
|
import { GatewayService } from './gateway-service.js';
|
|
19
20
|
import { GatewaySocket } from './gateway-socket.js';
|
|
20
21
|
import { GatewayUsage } from './gateway-usage.js';
|
|
21
22
|
import { LocalSandbox } from './local-sandbox.js';
|
|
23
|
+
import { ModelProxy, ModelProxyUtil } from './model-proxy.js';
|
|
22
24
|
import { SandboxProviders } from './sandbox-provider.js';
|
|
23
25
|
import { SIGN_IN_LINK_PATH, SignInLinks } from './sign-in-links.js';
|
|
24
26
|
import { TaSandbox } from './ta-sandbox.js';
|
|
@@ -50,6 +52,22 @@ export const SANDBOX_TYPES = {
|
|
|
50
52
|
};
|
|
51
53
|
export var GatewayServerUtil;
|
|
52
54
|
(function (GatewayServerUtil) {
|
|
55
|
+
/**
|
|
56
|
+
* Where a sandbox reaches the gateway, by the type of its provider: a container the host (host.docker.internal,
|
|
57
|
+
* mapped on Linux too), a process of this machine 127.0.0.1, another the public address.
|
|
58
|
+
*/
|
|
59
|
+
function reach(type, port, publicUrl) {
|
|
60
|
+
if (type === 'docker') {
|
|
61
|
+
return `http://host.docker.internal:${port}`;
|
|
62
|
+
}
|
|
63
|
+
if (type === 'local' || !publicUrl) {
|
|
64
|
+
return `http://127.0.0.1:${port}`;
|
|
65
|
+
}
|
|
66
|
+
return publicUrl;
|
|
67
|
+
}
|
|
68
|
+
GatewayServerUtil.reach = reach;
|
|
69
|
+
/** Where another Ta reaches the exec server of its account's sandbox. */
|
|
70
|
+
GatewayServerUtil.EXEC_PATH = '/api/exec';
|
|
53
71
|
/** 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. */
|
|
54
72
|
function blockedReason(block) {
|
|
55
73
|
switch (block) {
|
|
@@ -107,13 +125,14 @@ export var GatewayServerUtil;
|
|
|
107
125
|
*/
|
|
108
126
|
export class GatewayServer {
|
|
109
127
|
static async create(options) {
|
|
128
|
+
const models = ModelProxyUtil.read(options.dir);
|
|
110
129
|
mkdirSync(options.dir, { recursive: true, mode: 0o700 });
|
|
111
130
|
const config = SandboxProviders.read(options.dir);
|
|
112
131
|
const context = { dir: options.dir, taCommand: options.taCommand };
|
|
113
132
|
const providers = await SandboxProviders.create(config, context, SANDBOX_TYPES);
|
|
114
|
-
return new GatewayServer(options, providers, config);
|
|
133
|
+
return new GatewayServer(options, providers, config, models);
|
|
115
134
|
}
|
|
116
|
-
constructor(options, providers, config) {
|
|
135
|
+
constructor(options, providers, config, models = {}) {
|
|
117
136
|
var _a, _b;
|
|
118
137
|
this.options = options;
|
|
119
138
|
this.sockets = new Set();
|
|
@@ -131,8 +150,24 @@ export class GatewayServer {
|
|
|
131
150
|
});
|
|
132
151
|
this.usage = new GatewayUsage(options.dir);
|
|
133
152
|
this.audit = new GatewayAudit(options.dir);
|
|
134
|
-
this.quotas = new GatewayQuotas(this.policy, this.tenants, this.usage, () => this.environments.settings.own);
|
|
153
|
+
this.quotas = new GatewayQuotas(this.policy, this.tenants, this.usage, () => this.environments.settings.own, () => this.models.enabled);
|
|
135
154
|
this.environments.guard = tenant => GatewayServerUtil.blockedReason(this.quotas.blocked(tenant));
|
|
155
|
+
this.models = new ModelProxy(models, {
|
|
156
|
+
tenantOfKey: key => this.tenants.list().find(tenant => tenant.modelKey && ModelProxyUtil.sameKey(key, tenant.modelKey)),
|
|
157
|
+
refuse: id => {
|
|
158
|
+
const tenant = this.tenants.get(id);
|
|
159
|
+
return tenant ? this.quotas.refuseModels(tenant) : 'No such account.';
|
|
160
|
+
},
|
|
161
|
+
record: (id, usage, cost) => this.quotas.addTokens(id, ModelProxyUtil.total(usage), cost),
|
|
162
|
+
}, env);
|
|
163
|
+
this.environments.envOf = (tenant, provider) => {
|
|
164
|
+
var _a, _b, _c;
|
|
165
|
+
if (!this.models.enabled) {
|
|
166
|
+
return undefined;
|
|
167
|
+
}
|
|
168
|
+
const url = (_a = provider.gatewayUrl) !== null && _a !== void 0 ? _a : GatewayServerUtil.reach(provider.type, (_c = (_b = this.port) !== null && _b !== void 0 ? _b : options.port) !== null && _c !== void 0 ? _c : 4100, SandboxProviders.publicBase(env));
|
|
169
|
+
return { TA_MODEL_PROXY_URL: url.replace(/\/+$/, ''), TA_MODEL_PROXY_KEY: this.tenants.modelKey(tenant.id) };
|
|
170
|
+
};
|
|
136
171
|
this.service = new GatewayService({
|
|
137
172
|
flow: this.flow,
|
|
138
173
|
tenants: this.tenants,
|
|
@@ -142,6 +177,7 @@ export class GatewayServer {
|
|
|
142
177
|
usage: this.usage,
|
|
143
178
|
audit: this.audit,
|
|
144
179
|
hooks: { cutOff: () => this.cutOff(), reset: id => this.reset(id) },
|
|
180
|
+
models: this.models,
|
|
145
181
|
meta: { links: this.links, startedAt: Date.now(), version: options.version, publicUrl: SandboxProviders.publicBase(env) },
|
|
146
182
|
});
|
|
147
183
|
}
|
|
@@ -168,6 +204,7 @@ export class GatewayServer {
|
|
|
168
204
|
server.once('error', reject);
|
|
169
205
|
server.listen((_a = this.options.port) !== null && _a !== void 0 ? _a : 4100, (_b = this.options.host) !== null && _b !== void 0 ? _b : '127.0.0.1', () => {
|
|
170
206
|
const { address, port } = server.address();
|
|
207
|
+
this.port = port;
|
|
171
208
|
resolve(`http://${address.includes(':') ? `[${address}]` : address}:${port}`);
|
|
172
209
|
});
|
|
173
210
|
});
|
|
@@ -224,6 +261,9 @@ export class GatewayServer {
|
|
|
224
261
|
onSignedIn: (res, token, account, origin) => this.signedIn(res, token, account, origin),
|
|
225
262
|
});
|
|
226
263
|
}
|
|
264
|
+
else if (path === ModelProxyUtil.PATH || path.startsWith(`${ModelProxyUtil.PATH}/`)) {
|
|
265
|
+
await this.models.handle(request, response);
|
|
266
|
+
}
|
|
227
267
|
else if (path.startsWith(`${TA_FILES_PATH}/`)) {
|
|
228
268
|
await this.files(request, response);
|
|
229
269
|
}
|
|
@@ -337,7 +377,7 @@ export class GatewayServer {
|
|
|
337
377
|
upgrade(request, socket, head) {
|
|
338
378
|
var _a, _b;
|
|
339
379
|
const url = new URL((_a = request.url) !== null && _a !== void 0 ? _a : '/', 'http://gateway');
|
|
340
|
-
if (url.pathname !== TA_WEBSOCKET_PATH) {
|
|
380
|
+
if (url.pathname !== TA_WEBSOCKET_PATH && url.pathname !== GatewayServerUtil.EXEC_PATH) {
|
|
341
381
|
socket.destroy();
|
|
342
382
|
return;
|
|
343
383
|
}
|
|
@@ -359,6 +399,17 @@ export class GatewayServer {
|
|
|
359
399
|
return;
|
|
360
400
|
}
|
|
361
401
|
this.tenants.update(caller.tenant.id, { lastActiveAt: Date.now() });
|
|
402
|
+
if (url.pathname === GatewayServerUtil.EXEC_PATH) {
|
|
403
|
+
// Another Ta works in this account's sandbox: it counts as a page connected, and keeps the sandbox running.
|
|
404
|
+
const blocked = GatewayServerUtil.blockedReason(this.quotas.blocked(caller.tenant));
|
|
405
|
+
if (blocked) {
|
|
406
|
+
WebSocketConnection.refuse(socket, 403, blocked);
|
|
407
|
+
return;
|
|
408
|
+
}
|
|
409
|
+
const exec = WebSocketConnection.open(socket, checked.key, head, { maxPayload: 64 * 1024 * 1024, heartbeat: 30000 });
|
|
410
|
+
new GatewayExecProxy(exec, this.environments.ensure(caller.tenant), this.environments.connect(caller.tenant.id));
|
|
411
|
+
return;
|
|
412
|
+
}
|
|
362
413
|
const connection = WebSocketConnection.open(socket, checked.key, head, { maxPayload: 32 * 1024 * 1024, heartbeat: 30000, deflate: checked.deflate });
|
|
363
414
|
const gatewaySocket = new GatewaySocket(connection, caller, this.environments, this.service, this.quotas);
|
|
364
415
|
this.sockets.add(gatewaySocket);
|
|
@@ -5,6 +5,7 @@ import type { GatewayAudit } from './gateway-audit.js';
|
|
|
5
5
|
import { type GatewayPolicy } from './gateway-policy.js';
|
|
6
6
|
import type { GatewayQuotas } from './gateway-quotas.js';
|
|
7
7
|
import { type GatewayUsage } from './gateway-usage.js';
|
|
8
|
+
import { type ModelProxy } from './model-proxy.js';
|
|
8
9
|
import type { SignInLinks } from './sign-in-links.js';
|
|
9
10
|
import type { Tenant, TenantStore } from './tenant-store.js';
|
|
10
11
|
/** Who calls: the browser signed in as `account`, with the token `token`, and what that account is on the gateway. */
|
|
@@ -42,6 +43,7 @@ export interface GatewayParts {
|
|
|
42
43
|
reset(tenantId: string): void;
|
|
43
44
|
};
|
|
44
45
|
meta: GatewayMeta;
|
|
46
|
+
models?: ModelProxy;
|
|
45
47
|
}
|
|
46
48
|
type Need = TaGatewayRole | 'anyone';
|
|
47
49
|
export declare namespace GatewayServiceUtil {
|
|
@@ -92,6 +94,7 @@ export declare class GatewayService {
|
|
|
92
94
|
protected readonly audit: GatewayAudit;
|
|
93
95
|
protected readonly hooks: GatewayParts['hooks'];
|
|
94
96
|
protected readonly meta: GatewayMeta;
|
|
97
|
+
protected readonly models?: ModelProxy;
|
|
95
98
|
constructor(parts: GatewayParts);
|
|
96
99
|
call(caller: GatewayCaller, method: string, params: unknown[]): Promise<unknown>;
|
|
97
100
|
protected handle(caller: GatewayCaller, service: string, name: string, params: unknown[]): Promise<unknown>;
|
|
@@ -119,6 +122,11 @@ export declare class GatewayService {
|
|
|
119
122
|
protected setSuspended(caller: GatewayCaller, id: unknown, suspended: unknown): Promise<void>;
|
|
120
123
|
protected setDefaultLimits(value: unknown): TaGatewayPolicy;
|
|
121
124
|
protected setRole(caller: GatewayCaller, account: unknown, role: unknown): TaGatewayPolicy;
|
|
125
|
+
/** A sign-in of the caller's own account, named for where it is used. */
|
|
126
|
+
protected accessToken(caller: GatewayCaller, label: unknown): {
|
|
127
|
+
token: string;
|
|
128
|
+
url?: string;
|
|
129
|
+
};
|
|
122
130
|
protected access(caller: GatewayCaller): TaAccessInfo;
|
|
123
131
|
protected allow(account: unknown, name: unknown): void;
|
|
124
132
|
/** The browsers of the account are cut off, and what reaches its Ta otherwise (paired phones) goes with its sandbox. */
|