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