@celljs/ta-gateway 4.15.1 → 4.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/esm/node/command-sandbox.d.ts +6 -2
  2. package/esm/node/command-sandbox.js +26 -4
  3. package/esm/node/docker-engine.d.ts +50 -0
  4. package/esm/node/docker-engine.js +98 -11
  5. package/esm/node/docker-sandbox.d.ts +6 -1
  6. package/esm/node/docker-sandbox.js +23 -3
  7. package/esm/node/environments.d.ts +36 -2
  8. package/esm/node/environments.js +192 -14
  9. package/esm/node/gateway-audit.d.ts +12 -0
  10. package/esm/node/gateway-audit.js +47 -0
  11. package/esm/node/gateway-cli.d.ts +2 -0
  12. package/esm/node/gateway-cli.js +1 -0
  13. package/esm/node/gateway-exec.d.ts +19 -0
  14. package/esm/node/gateway-exec.js +65 -0
  15. package/esm/node/gateway-policy.d.ts +47 -0
  16. package/esm/node/gateway-policy.js +152 -0
  17. package/esm/node/gateway-quotas.d.ts +40 -0
  18. package/esm/node/gateway-quotas.js +135 -0
  19. package/esm/node/gateway-server.d.ts +28 -2
  20. package/esm/node/gateway-server.js +112 -9
  21. package/esm/node/gateway-service.d.ts +99 -16
  22. package/esm/node/gateway-service.js +385 -45
  23. package/esm/node/gateway-socket.d.ts +7 -1
  24. package/esm/node/gateway-socket.js +40 -1
  25. package/esm/node/gateway-usage.d.ts +37 -0
  26. package/esm/node/gateway-usage.js +137 -0
  27. package/esm/node/local-sandbox.d.ts +13 -0
  28. package/esm/node/local-sandbox.js +38 -2
  29. package/esm/node/model-proxy.d.ts +105 -0
  30. package/esm/node/model-proxy.js +435 -0
  31. package/esm/node/sandbox-provider.d.ts +17 -0
  32. package/esm/node/tenant-store.d.ts +19 -1
  33. package/esm/node/tenant-store.js +10 -0
  34. package/lib/node/command-sandbox.d.ts +6 -2
  35. package/lib/node/command-sandbox.js +26 -4
  36. package/lib/node/docker-engine.d.ts +50 -0
  37. package/lib/node/docker-engine.js +98 -11
  38. package/lib/node/docker-sandbox.d.ts +6 -1
  39. package/lib/node/docker-sandbox.js +23 -3
  40. package/lib/node/environments.d.ts +36 -2
  41. package/lib/node/environments.js +191 -13
  42. package/lib/node/gateway-audit.d.ts +13 -0
  43. package/lib/node/gateway-audit.js +51 -0
  44. package/lib/node/gateway-cli.d.ts +2 -0
  45. package/lib/node/gateway-cli.js +1 -0
  46. package/lib/node/gateway-exec.d.ts +20 -0
  47. package/lib/node/gateway-exec.js +69 -0
  48. package/lib/node/gateway-policy.d.ts +48 -0
  49. package/lib/node/gateway-policy.js +157 -0
  50. package/lib/node/gateway-quotas.d.ts +41 -0
  51. package/lib/node/gateway-quotas.js +139 -0
  52. package/lib/node/gateway-server.d.ts +28 -2
  53. package/lib/node/gateway-server.js +112 -9
  54. package/lib/node/gateway-service.d.ts +99 -16
  55. package/lib/node/gateway-service.js +384 -44
  56. package/lib/node/gateway-socket.d.ts +7 -1
  57. package/lib/node/gateway-socket.js +40 -1
  58. package/lib/node/gateway-usage.d.ts +38 -0
  59. package/lib/node/gateway-usage.js +141 -0
  60. package/lib/node/local-sandbox.d.ts +13 -0
  61. package/lib/node/local-sandbox.js +40 -3
  62. package/lib/node/model-proxy.d.ts +106 -0
  63. package/lib/node/model-proxy.js +440 -0
  64. package/lib/node/sandbox-provider.d.ts +17 -0
  65. package/lib/node/tenant-store.d.ts +19 -1
  66. package/lib/node/tenant-store.js +10 -0
  67. package/package.json +4 -4
@@ -23,6 +23,11 @@ export declare class DockerEngine {
23
23
  status: number;
24
24
  body: T;
25
25
  }>;
26
+ /** The answer of the Engine as it came, for the streams of logs, which are not text; a status of 400 and above throws. */
27
+ raw(method: string, path: string, body?: unknown, timeoutMs?: number): Promise<{
28
+ status: number;
29
+ body: Buffer;
30
+ }>;
26
31
  /** undefined for a container that is not there. */
27
32
  inspect(name: string): Promise<DockerContainer | undefined>;
28
33
  create(name: string, spec: object): Promise<void>;
@@ -30,6 +35,16 @@ export declare class DockerEngine {
30
35
  start(name: string): Promise<void>;
31
36
  /** Stopped, already stopped (304) or not there (404). */
32
37
  stop(name: string, seconds?: number): Promise<void>;
38
+ /** What a running container takes: one sample of its CPU over a second or so, and its memory; undefined for one that does not run. */
39
+ stats(name: string): Promise<{
40
+ cpu?: number;
41
+ memory?: number;
42
+ memoryLimit?: number;
43
+ } | undefined>;
44
+ /** The last `lines` of what a container wrote, its output and errors in their order; empty for one that is not there. */
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>;
33
48
  /** A bridge network, made when missing; `isolated`: its containers cannot reach each other. */
34
49
  ensureNetwork(name: string, isolated: boolean): Promise<void>;
35
50
  /** Pulled when it is not here; one built here (ta:latest) is. */
@@ -37,6 +52,9 @@ export declare class DockerEngine {
37
52
  }
38
53
  export interface DockerContainer {
39
54
  Id: string;
55
+ Config?: {
56
+ Env?: string[];
57
+ };
40
58
  State: {
41
59
  Running: boolean;
42
60
  Status: string;
@@ -48,7 +66,39 @@ export interface DockerContainer {
48
66
  }[] | null>;
49
67
  };
50
68
  }
69
+ /** As far as the console reads `/containers/<name>/stats`. */
70
+ export interface DockerStats {
71
+ cpu_stats?: {
72
+ cpu_usage?: {
73
+ total_usage?: number;
74
+ };
75
+ system_cpu_usage?: number;
76
+ online_cpus?: number;
77
+ };
78
+ precpu_stats?: {
79
+ cpu_usage?: {
80
+ total_usage?: number;
81
+ };
82
+ system_cpu_usage?: number;
83
+ };
84
+ memory_stats?: {
85
+ usage?: number;
86
+ limit?: number;
87
+ stats?: Record<string, number>;
88
+ };
89
+ }
51
90
  export declare namespace DockerEngineUtil {
91
+ /** As `docker stats` reckons: CPU in percent of one CPU, memory without the page cache. */
92
+ function usage(stats: DockerStats | undefined): {
93
+ cpu?: number;
94
+ memory?: number;
95
+ memoryLimit?: number;
96
+ } | undefined;
97
+ /**
98
+ * The text of the logs of a container without a terminal: frames of a header of 8 bytes (the stream, three
99
+ * zeroes, the length) and their bytes. One with a terminal sends its text as it is.
100
+ */
101
+ function demux(buffer: Buffer): string;
52
102
  /** `ghcr.io:443/me/ta:1.0` → `ghcr.io:443/me/ta`, `1.0`: the tag after the last `:` that is past the last `/`. */
53
103
  function splitImage(image: string): [string, string?];
54
104
  /** `512m`, `4g`, a number of bytes: Docker's `--memory`. */
@@ -28,7 +28,20 @@ class DockerEngine {
28
28
  }
29
29
  }
30
30
  /** The answer of the Engine, parsed when it is JSON; a status of 400 and above throws. */
31
- call(method, path, body, timeoutMs = 120000) {
31
+ async call(method, path, body, timeoutMs = 120000) {
32
+ const answer = await this.raw(method, path, body, timeoutMs);
33
+ const text = answer.body.toString('utf8');
34
+ let parsed = text;
35
+ try {
36
+ parsed = text ? JSON.parse(text) : undefined;
37
+ }
38
+ catch (_a) {
39
+ // Streams of progress (a pull) are lines of JSON: kept as text.
40
+ }
41
+ return { status: answer.status, body: parsed };
42
+ }
43
+ /** The answer of the Engine as it came, for the streams of logs, which are not text; a status of 400 and above throws. */
44
+ raw(method, path, body, timeoutMs = 120000) {
32
45
  return new Promise((resolve, reject) => {
33
46
  const payload = body === undefined ? undefined : JSON.stringify(body);
34
47
  const req = (0, node_http_1.request)({
@@ -42,21 +55,21 @@ class DockerEngine {
42
55
  res.on('data', chunk => chunks.push(chunk));
43
56
  res.on('end', () => {
44
57
  var _a, _b;
45
- const text = Buffer.concat(chunks).toString('utf8');
46
- let parsed = text;
47
- try {
48
- parsed = text ? JSON.parse(text) : undefined;
49
- }
50
- catch (_c) {
51
- // Streams of progress (a pull) are lines of JSON: kept as text.
52
- }
58
+ const buffer = Buffer.concat(chunks);
53
59
  const status = (_a = res.statusCode) !== null && _a !== void 0 ? _a : 0;
54
60
  if (status >= 400) {
55
- const message = (_b = parsed === null || parsed === void 0 ? void 0 : parsed.message) !== null && _b !== void 0 ? _b : text;
61
+ const text = buffer.toString('utf8');
62
+ let message = text;
63
+ try {
64
+ message = (_b = JSON.parse(text).message) !== null && _b !== void 0 ? _b : text;
65
+ }
66
+ catch (_c) {
67
+ // Not JSON: the text as it is.
68
+ }
56
69
  reject(new DockerError(`Docker: ${method} ${path.split('?')[0]} answered ${status}: ${message}`, status));
57
70
  }
58
71
  else {
59
- resolve({ status, body: parsed });
72
+ resolve({ status, body: buffer });
60
73
  }
61
74
  });
62
75
  });
@@ -97,6 +110,43 @@ class DockerEngine {
97
110
  }
98
111
  }
99
112
  }
113
+ /** What a running container takes: one sample of its CPU over a second or so, and its memory; undefined for one that does not run. */
114
+ async stats(name) {
115
+ try {
116
+ const { body } = await this.call('GET', `/containers/${encodeURIComponent(name)}/stats?stream=false`, undefined, 15000);
117
+ return DockerEngineUtil.usage(body);
118
+ }
119
+ catch (error) {
120
+ if (error instanceof DockerError && (error.status === 404 || error.status === 409)) {
121
+ return undefined;
122
+ }
123
+ throw error;
124
+ }
125
+ }
126
+ /** The last `lines` of what a container wrote, its output and errors in their order; empty for one that is not there. */
127
+ async logs(name, lines) {
128
+ try {
129
+ const { body } = await this.raw('GET', `/containers/${encodeURIComponent(name)}/logs?stdout=1&stderr=1&tail=${lines}`, undefined, 15000);
130
+ return DockerEngineUtil.demux(body);
131
+ }
132
+ catch (error) {
133
+ if (error instanceof DockerError && error.status === 404) {
134
+ return '';
135
+ }
136
+ throw error;
137
+ }
138
+ }
139
+ /** Removed, its volumes kept; nothing when it is not there. */
140
+ async remove(name) {
141
+ try {
142
+ await this.call('DELETE', `/containers/${encodeURIComponent(name)}?force=true`);
143
+ }
144
+ catch (error) {
145
+ if (!(error instanceof DockerError && error.status === 404)) {
146
+ throw error;
147
+ }
148
+ }
149
+ }
100
150
  /** A bridge network, made when missing; `isolated`: its containers cannot reach each other. */
101
151
  async ensureNetwork(name, isolated) {
102
152
  try {
@@ -129,6 +179,43 @@ class DockerEngine {
129
179
  exports.DockerEngine = DockerEngine;
130
180
  var DockerEngineUtil;
131
181
  (function (DockerEngineUtil) {
182
+ /** As `docker stats` reckons: CPU in percent of one CPU, memory without the page cache. */
183
+ function usage(stats) {
184
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
185
+ var _r, _s, _t, _u, _v, _w;
186
+ if (!((_a = stats === null || stats === void 0 ? void 0 : stats.memory_stats) === null || _a === void 0 ? void 0 : _a.usage) && !((_b = stats === null || stats === void 0 ? void 0 : stats.cpu_stats) === null || _b === void 0 ? void 0 : _b.system_cpu_usage)) {
187
+ // A container that does not run answers with zeroes.
188
+ return undefined;
189
+ }
190
+ const cpuDelta = ((_r = (_d = (_c = stats.cpu_stats) === null || _c === void 0 ? void 0 : _c.cpu_usage) === null || _d === void 0 ? void 0 : _d.total_usage) !== null && _r !== void 0 ? _r : 0) - ((_s = (_f = (_e = stats.precpu_stats) === null || _e === void 0 ? void 0 : _e.cpu_usage) === null || _f === void 0 ? void 0 : _f.total_usage) !== null && _s !== void 0 ? _s : 0);
191
+ const systemDelta = ((_t = (_g = stats.cpu_stats) === null || _g === void 0 ? void 0 : _g.system_cpu_usage) !== null && _t !== void 0 ? _t : 0) - ((_u = (_h = stats.precpu_stats) === null || _h === void 0 ? void 0 : _h.system_cpu_usage) !== null && _u !== void 0 ? _u : 0);
192
+ const cpus = ((_j = stats.cpu_stats) === null || _j === void 0 ? void 0 : _j.online_cpus) || 1;
193
+ const cpu = systemDelta > 0 && cpuDelta >= 0 ? Math.round((cpuDelta / systemDelta) * cpus * 1000) / 10 : undefined;
194
+ const memory = (_k = stats.memory_stats) === null || _k === void 0 ? void 0 : _k.usage;
195
+ // cgroup v2 says inactive_file, v1 cache: what `docker stats` takes away.
196
+ const cache = (_w = (_v = (_m = (_l = stats.memory_stats) === null || _l === void 0 ? void 0 : _l.stats) === null || _m === void 0 ? void 0 : _m.inactive_file) !== null && _v !== void 0 ? _v : (_p = (_o = stats.memory_stats) === null || _o === void 0 ? void 0 : _o.stats) === null || _p === void 0 ? void 0 : _p.cache) !== null && _w !== void 0 ? _w : 0;
197
+ return { cpu, memory: memory === undefined ? undefined : Math.max(0, memory - cache), memoryLimit: (_q = stats.memory_stats) === null || _q === void 0 ? void 0 : _q.limit };
198
+ }
199
+ DockerEngineUtil.usage = usage;
200
+ /**
201
+ * The text of the logs of a container without a terminal: frames of a header of 8 bytes (the stream, three
202
+ * zeroes, the length) and their bytes. One with a terminal sends its text as it is.
203
+ */
204
+ function demux(buffer) {
205
+ const parts = [];
206
+ let offset = 0;
207
+ while (offset + 8 <= buffer.length) {
208
+ const stream = buffer[offset];
209
+ const size = buffer.readUInt32BE(offset + 4);
210
+ if (stream > 2 || buffer[offset + 1] !== 0 || buffer[offset + 2] !== 0 || buffer[offset + 3] !== 0 || offset + 8 + size > buffer.length) {
211
+ return buffer.toString('utf8');
212
+ }
213
+ parts.push(buffer.subarray(offset + 8, offset + 8 + size));
214
+ offset += 8 + size;
215
+ }
216
+ return offset === buffer.length ? Buffer.concat(parts).toString('utf8') : buffer.toString('utf8');
217
+ }
218
+ DockerEngineUtil.demux = demux;
132
219
  /** `ghcr.io:443/me/ta:1.0` → `ghcr.io:443/me/ta`, `1.0`: the tag after the last `:` that is past the last `/`. */
133
220
  function splitImage(image) {
134
221
  const slash = image.lastIndexOf('/');
@@ -1,6 +1,8 @@
1
1
  import { DockerEngine } from './docker-engine';
2
- import { type SandboxEndpoint, type SandboxProvider, type SandboxProviderConfig, type SandboxState, type SandboxTenant } from './sandbox-provider';
2
+ import { type SandboxEndpoint, type SandboxProvider, type SandboxProviderConfig, type SandboxState, type SandboxTenant, type SandboxUsage } from './sandbox-provider';
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,12 +35,15 @@ 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);
39
42
  start(tenant: SandboxTenant): Promise<SandboxEndpoint>;
40
43
  stop(tenant: SandboxTenant): Promise<void>;
41
44
  state(tenant: SandboxTenant): Promise<SandboxState>;
45
+ usage(tenant: SandboxTenant): Promise<SandboxUsage | undefined>;
46
+ logs(tenant: SandboxTenant, lines: number): Promise<string>;
42
47
  /** What `docker run` would be given. */
43
48
  spec(tenant: SandboxTenant): object;
44
49
  protected containerName(tenant: SandboxTenant): string;
@@ -5,6 +5,12 @@ const docker_engine_1 = require("./docker-engine");
5
5
  const sandbox_provider_1 = require("./sandbox-provider");
6
6
  var DockerSandboxUtil;
7
7
  (function (DockerSandboxUtil) {
8
+ /** Whether a container has each variable of `env` as it is. */
9
+ function hasEnv(have, want) {
10
+ const set = new Set(have !== null && have !== void 0 ? have : []);
11
+ return Object.entries(want !== null && want !== void 0 ? want : {}).every(([key, value]) => set.has(`${key}=${value}`));
12
+ }
13
+ DockerSandboxUtil.hasEnv = hasEnv;
8
14
  /** `github:Octo.Cat` → `octo-cat`: a name of a host from the account, `ta` when nothing is left. */
9
15
  function hostname(account) {
10
16
  const name = account
@@ -55,12 +61,18 @@ class DockerSandbox {
55
61
  this.options = options;
56
62
  this.type = 'docker';
57
63
  this.name = sandbox_provider_1.SandboxProviders.string(config, 'name', 'Docker');
64
+ this.gatewayUrl = sandbox_provider_1.SandboxProviders.string(config, 'gatewayUrl');
58
65
  this.engine = engine !== null && engine !== void 0 ? engine : new docker_engine_1.DockerEngine({ host: options.host });
59
66
  }
60
67
  async start(tenant) {
61
- var _a, _b, _c;
68
+ var _a, _b, _c, _d;
62
69
  const name = this.containerName(tenant);
63
70
  let container = await this.engine.inspect(name);
71
+ if (container && !DockerSandboxUtil.hasEnv((_a = container.Config) === null || _a === void 0 ? void 0 : _a.Env, tenant.env)) {
72
+ // Made before the gateway gave it this environment (the models of the gateway): made again, its volume kept.
73
+ await this.engine.remove(name);
74
+ container = undefined;
75
+ }
64
76
  if (!container) {
65
77
  await this.engine.ensureImage(this.options.image);
66
78
  await this.engine.ensureNetwork(this.options.network, true);
@@ -71,7 +83,7 @@ class DockerSandbox {
71
83
  await this.engine.start(name);
72
84
  container = await this.engine.inspect(name);
73
85
  }
74
- const port = (_c = (_b = (_a = container === null || container === void 0 ? void 0 : container.NetworkSettings.Ports) === null || _a === void 0 ? void 0 : _a[PORT]) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.HostPort;
86
+ 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;
75
87
  if (!port) {
76
88
  throw new Error(`The container ${name} publishes no port for ${PORT}.`);
77
89
  }
@@ -84,6 +96,12 @@ class DockerSandbox {
84
96
  const container = await this.engine.inspect(this.containerName(tenant));
85
97
  return !container ? 'missing' : container.State.Running ? 'running' : 'stopped';
86
98
  }
99
+ usage(tenant) {
100
+ return this.engine.stats(this.containerName(tenant));
101
+ }
102
+ logs(tenant, lines) {
103
+ return this.engine.logs(this.containerName(tenant), lines);
104
+ }
87
105
  /** What `docker run` would be given. */
88
106
  spec(tenant) {
89
107
  const name = this.containerName(tenant);
@@ -91,11 +109,13 @@ class DockerSandbox {
91
109
  Image: this.options.image,
92
110
  // What the Ta of the tenant tells its clients its machine is, as the list of computers of the phone shows it.
93
111
  Hostname: DockerSandboxUtil.hostname(tenant.account),
94
- Env: [`TA_SERVE_TOKEN=${tenant.token}`, ...Object.entries(this.options.env).map(([key, value]) => `${key}=${value}`)],
112
+ Env: [`TA_SERVE_TOKEN=${tenant.token}`, ...Object.entries({ ...this.options.env, ...tenant.env }).map(([key, value]) => `${key}=${value}`)],
95
113
  Labels: { 'cell.ta.tenant': tenant.id, 'cell.ta.account': tenant.account },
96
114
  ExposedPorts: { [PORT]: {} },
97
115
  HostConfig: {
98
116
  PortBindings: { [PORT]: [{ HostIp: this.options.bind, HostPort: '' }] },
117
+ // The gateway, for the models it gives (TA_MODEL_PROXY_URL): the host, on Linux too.
118
+ ExtraHosts: ['host.docker.internal:host-gateway'],
99
119
  Mounts: [{ Type: 'volume', Source: name, Target: '/home/ta' }],
100
120
  NetworkMode: this.options.network,
101
121
  Memory: this.options.memory,
@@ -1,5 +1,5 @@
1
- import { type TaEnvironmentChoice, type TaEnvironmentInfo, type TaEnvironmentOption, type TaEnvironmentStatus } from '@celljs/ta-protocol';
2
- import type { SandboxEndpoint, SandboxProvider, SandboxTenant } from './sandbox-provider';
1
+ import { type TaAgentActivity, type TaAgentCounts, type TaAgentSession, type TaAgentStats, type TaEnvironmentChoice, type TaEnvironmentInfo, type TaEnvironmentOption, type TaEnvironmentStatus, type TaSessionInfo, type TaTenantAgents, type TaUsageBucket } from '@celljs/ta-protocol';
2
+ import type { SandboxEndpoint, SandboxProvider, SandboxTenant, SandboxUsage } from './sandbox-provider';
3
3
  import type { Tenant, TenantStore } from './tenant-store';
4
4
  interface Running {
5
5
  status: TaEnvironmentStatus;
@@ -16,6 +16,20 @@ export declare namespace EnvironmentsUtil {
16
16
  function waitReady(url: string, timeoutMs?: number, fetcher?: typeof fetch): Promise<void>;
17
17
  /** One call of the Ta service at `endpoint` over a WebSocket of its own: the gateway's, not a browser's. */
18
18
  function call<T>(endpoint: SandboxEndpoint, method: string, params?: unknown[], timeoutMs?: number): Promise<T>;
19
+ /**
20
+ * Calls of the Ta service at `endpoint` over one WebSocket of the gateway's, in their order: the answers, or
21
+ * the error of each that failed. Throws when the service is not reached, or all took too long.
22
+ */
23
+ function calls<T extends unknown[]>(endpoint: SandboxEndpoint, list: [string, unknown[]][], timeoutMs?: number): Promise<{
24
+ [K in keyof T]: T[K];
25
+ }>;
26
+ /** What the console says an agent does: a dialog waiting for the user first, then a turn, then a question left. */
27
+ function status(session: TaSessionInfo): TaAgentSession['status'];
28
+ function summary(sessions: TaSessionInfo[]): TaAgentCounts;
29
+ /** Of pi's statistics of a session, what the console shows; undefined for what is not them (an error). */
30
+ function stats(value: unknown): TaAgentStats | undefined;
31
+ /** A session as an administrator sees it: never what was said in it. */
32
+ function agentSession(session: TaSessionInfo, stats?: TaAgentStats): TaAgentSession;
19
33
  function sandboxTenant(tenant: Tenant): SandboxTenant;
20
34
  }
21
35
  /**
@@ -32,6 +46,10 @@ export declare class Environments {
32
46
  readyTimeoutMs?: number;
33
47
  };
34
48
  protected readonly running: Map<string, Running>;
49
+ /** Why the tenant's Ta may not start now (suspended, its free minutes used), checked before each start. */
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;
35
53
  constructor(providers: SandboxProvider[], tenants: TenantStore, settings: {
36
54
  default?: string;
37
55
  own: boolean;
@@ -46,6 +64,22 @@ export declare class Environments {
46
64
  own: boolean;
47
65
  };
48
66
  info(tenant: Tenant): TaEnvironmentInfo;
67
+ /** What the sandbox of a running tenant takes, when its provider tells; a provider that fails to tell leaves it out. */
68
+ usage(tenant: Tenant): Promise<SandboxUsage | undefined>;
69
+ /** The last lines its sandbox wrote; a Ta service of the user's, or a provider without logs, has none for the gateway. */
70
+ logs(tenant: Tenant, lines: number): Promise<string>;
71
+ /** 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. */
72
+ protected watched(tenant: Tenant): SandboxEndpoint | undefined;
73
+ /** The tenants whose sandbox of the gateway's runs now: those whose minutes count. */
74
+ runningIds(): string[];
75
+ /** How the gateway asks its Ta what its agents took; undefined while it does not run. */
76
+ usageReader(tenant: Tenant): ((since: number) => Promise<TaUsageBucket[]>) | undefined;
77
+ /** The latest of what an agent of its Ta did. */
78
+ activity(tenant: Tenant, sessionId: string): Promise<TaAgentActivity[]>;
79
+ /** How many conversations its Ta has open and how many work or wait; undefined when it does not run, or does not answer soon. */
80
+ agentSummary(tenant: Tenant, timeoutMs?: number): Promise<TaAgentCounts | undefined>;
81
+ /** The conversations open in its Ta, each with pi's statistics of it, over one connection. */
82
+ agents(tenant: Tenant, now?: number): Promise<TaTenantAgents>;
49
83
  connections(tenantId: string): number;
50
84
  /** Where the Ta of the tenant answers, started when it does not run. */
51
85
  ensure(tenant: Tenant): Promise<SandboxEndpoint>;
@@ -30,37 +30,127 @@ var EnvironmentsUtil;
30
30
  }
31
31
  EnvironmentsUtil.waitReady = waitReady;
32
32
  /** One call of the Ta service at `endpoint` over a WebSocket of its own: the gateway's, not a browser's. */
33
- function call(endpoint, method, params = [], timeoutMs = 10000) {
33
+ async function call(endpoint, method, params = [], timeoutMs = 10000) {
34
+ const [result] = await calls(endpoint, [[method, params]], timeoutMs);
35
+ return result;
36
+ }
37
+ EnvironmentsUtil.call = call;
38
+ /**
39
+ * Calls of the Ta service at `endpoint` over one WebSocket of the gateway's, in their order: the answers, or
40
+ * the error of each that failed. Throws when the service is not reached, or all took too long.
41
+ */
42
+ function calls(endpoint, list, timeoutMs = 10000) {
34
43
  return new Promise((resolve, reject) => {
35
44
  const url = new URL(`${endpoint.url.replace(/^http/, 'ws')}${ta_protocol_1.TA_WEBSOCKET_PATH}`);
36
45
  url.searchParams.set('token', endpoint.token);
37
46
  const socket = new WebSocket(url);
38
- const timer = setTimeout(() => finish(new EnvironmentError(`${method} took too long`)), timeoutMs);
39
- const finish = (error, result) => {
47
+ const results = new Array(list.length);
48
+ let left = list.length;
49
+ let done = false;
50
+ const timer = setTimeout(() => { var _a; var _b; return finish(new EnvironmentError(`${(_b = (_a = list[0]) === null || _a === void 0 ? void 0 : _a[0]) !== null && _b !== void 0 ? _b : 'A call'} took too long`)); }, timeoutMs);
51
+ const finish = (error) => {
52
+ if (done) {
53
+ return;
54
+ }
55
+ done = true;
40
56
  clearTimeout(timer);
41
57
  socket.close();
42
58
  if (error) {
43
59
  reject(error);
44
60
  }
45
61
  else {
46
- resolve(result);
62
+ resolve(results);
63
+ }
64
+ };
65
+ if (left === 0) {
66
+ queueMicrotask(() => finish());
67
+ }
68
+ socket.onopen = () => {
69
+ for (const [index, [method, params]] of list.entries()) {
70
+ socket.send(JSON.stringify({ jsonrpc: '2.0', id: index + 1, method, params }));
47
71
  }
48
72
  };
49
- socket.onopen = () => socket.send(JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }));
50
73
  socket.onerror = () => finish(new EnvironmentError(`Cannot reach ${endpoint.url}`));
51
74
  socket.onmessage = message => {
75
+ var _a;
52
76
  const answer = JSON.parse(String(message.data));
53
- if (answer.id === 1) {
54
- finish(answer.error ? new EnvironmentError(answer.error.message) : undefined, answer.result);
55
- }
56
- else if (answer.method !== undefined && answer.id !== undefined) {
77
+ if (answer.method !== undefined && answer.id !== undefined) {
57
78
  // A push of the server (TaClient): answered, so that it does not wait.
58
79
  socket.send(JSON.stringify({ jsonrpc: '2.0', id: answer.id, result: null }));
80
+ return;
81
+ }
82
+ const index = typeof answer.id === 'number' ? answer.id - 1 : -1;
83
+ if (index < 0 || index >= list.length || results[index] !== undefined) {
84
+ return;
85
+ }
86
+ if (list.length === 1 && answer.error) {
87
+ finish(new EnvironmentError(answer.error.message));
88
+ return;
89
+ }
90
+ results[index] = answer.error ? new EnvironmentError(answer.error.message) : ((_a = answer.result) !== null && _a !== void 0 ? _a : null);
91
+ if (--left === 0) {
92
+ finish();
59
93
  }
60
94
  };
61
95
  });
62
96
  }
63
- EnvironmentsUtil.call = call;
97
+ EnvironmentsUtil.calls = calls;
98
+ /** What the console says an agent does: a dialog waiting for the user first, then a turn, then a question left. */
99
+ function status(session) {
100
+ return session.waiting ? 'waiting' : session.isStreaming ? 'working' : session.asking ? 'asking' : 'idle';
101
+ }
102
+ EnvironmentsUtil.status = status;
103
+ function summary(sessions) {
104
+ const statuses = sessions.map(status);
105
+ return {
106
+ sessions: sessions.length,
107
+ working: statuses.filter(each => each === 'working').length,
108
+ waiting: statuses.filter(each => each === 'waiting' || each === 'asking').length,
109
+ };
110
+ }
111
+ EnvironmentsUtil.summary = summary;
112
+ /** Of pi's statistics of a session, what the console shows; undefined for what is not them (an error). */
113
+ function stats(value) {
114
+ var _a;
115
+ var _b, _c, _d, _e, _f, _g, _h, _j;
116
+ const given = value;
117
+ if (!given || typeof given !== 'object' || !given.tokens || typeof given.cost !== 'number') {
118
+ return undefined;
119
+ }
120
+ const percent = (_a = given.contextUsage) === null || _a === void 0 ? void 0 : _a.percent;
121
+ return {
122
+ userMessages: (_b = given.userMessages) !== null && _b !== void 0 ? _b : 0,
123
+ assistantMessages: (_c = given.assistantMessages) !== null && _c !== void 0 ? _c : 0,
124
+ toolCalls: (_d = given.toolCalls) !== null && _d !== void 0 ? _d : 0,
125
+ tokens: {
126
+ input: (_e = given.tokens.input) !== null && _e !== void 0 ? _e : 0,
127
+ output: (_f = given.tokens.output) !== null && _f !== void 0 ? _f : 0,
128
+ cacheRead: (_g = given.tokens.cacheRead) !== null && _g !== void 0 ? _g : 0,
129
+ cacheWrite: (_h = given.tokens.cacheWrite) !== null && _h !== void 0 ? _h : 0,
130
+ total: (_j = given.tokens.total) !== null && _j !== void 0 ? _j : 0,
131
+ },
132
+ cost: given.cost,
133
+ context: typeof percent === 'number' ? Math.round(percent) : undefined,
134
+ };
135
+ }
136
+ EnvironmentsUtil.stats = stats;
137
+ /** A session as an administrator sees it: never what was said in it. */
138
+ function agentSession(session, stats) {
139
+ return {
140
+ sessionId: session.sessionId,
141
+ name: session.sessionName || undefined,
142
+ cwd: session.cwd,
143
+ model: session.model,
144
+ status: status(session),
145
+ messageCount: session.messageCount,
146
+ attached: session.attached,
147
+ createdAt: session.createdAt,
148
+ updatedAt: session.updatedAt,
149
+ group: session.group,
150
+ stats,
151
+ };
152
+ }
153
+ EnvironmentsUtil.agentSession = agentSession;
64
154
  function sandboxTenant(tenant) {
65
155
  return { id: tenant.id, account: tenant.account, token: tenant.token };
66
156
  }
@@ -118,6 +208,86 @@ class Environments {
118
208
  url: own && provider instanceof ta_sandbox_1.TaSandbox ? provider.url : undefined,
119
209
  };
120
210
  }
211
+ /** What the sandbox of a running tenant takes, when its provider tells; a provider that fails to tell leaves it out. */
212
+ async usage(tenant) {
213
+ var _a;
214
+ if (((_a = this.running.get(tenant.id)) === null || _a === void 0 ? void 0 : _a.status) !== 'running') {
215
+ return undefined;
216
+ }
217
+ const { provider, own } = this.provider(tenant);
218
+ if (own || !provider.usage) {
219
+ return undefined;
220
+ }
221
+ return provider.usage(EnvironmentsUtil.sandboxTenant(tenant)).catch(() => undefined);
222
+ }
223
+ /** The last lines its sandbox wrote; a Ta service of the user's, or a provider without logs, has none for the gateway. */
224
+ async logs(tenant, lines) {
225
+ const { provider, own } = this.provider(tenant);
226
+ if (own || !provider.logs) {
227
+ throw new EnvironmentError(`The sandboxes of ${own ? 'a Ta service of the user' : provider.name} keep no logs for the gateway.`);
228
+ }
229
+ return provider.logs(EnvironmentsUtil.sandboxTenant(tenant), lines);
230
+ }
231
+ /** Where the Ta of a tenant answers, while it runs in a sandbox of the gateway's; a Ta service of the user's is theirs to watch. */
232
+ watched(tenant) {
233
+ const running = this.running.get(tenant.id);
234
+ return (running === null || running === void 0 ? void 0 : running.status) === 'running' && running.endpoint && !this.provider(tenant).own ? running.endpoint : undefined;
235
+ }
236
+ /** The tenants whose sandbox of the gateway's runs now: those whose minutes count. */
237
+ runningIds() {
238
+ return [...this.running.entries()]
239
+ .filter(([id, running]) => {
240
+ const tenant = running.status === 'running' ? this.tenants.get(id) : undefined;
241
+ return tenant !== undefined && !this.provider(tenant).own;
242
+ })
243
+ .map(([id]) => id);
244
+ }
245
+ /** How the gateway asks its Ta what its agents took; undefined while it does not run. */
246
+ usageReader(tenant) {
247
+ const endpoint = this.watched(tenant);
248
+ return endpoint && (since => EnvironmentsUtil.call(endpoint, 'TaUsageServer/getUsage', [since], 20000));
249
+ }
250
+ /** The latest of what an agent of its Ta did. */
251
+ async activity(tenant, sessionId) {
252
+ const endpoint = this.watched(tenant);
253
+ if (!endpoint) {
254
+ throw new EnvironmentError('Its sandbox does not run: start it to see what its agents did.');
255
+ }
256
+ return EnvironmentsUtil.call(endpoint, 'TaUsageServer/getActivity', [sessionId, 50]);
257
+ }
258
+ /** How many conversations its Ta has open and how many work or wait; undefined when it does not run, or does not answer soon. */
259
+ async agentSummary(tenant, timeoutMs = 3000) {
260
+ const endpoint = this.watched(tenant);
261
+ if (!endpoint) {
262
+ return undefined;
263
+ }
264
+ const sessions = await EnvironmentsUtil.call(endpoint, 'TaServer/listSessions', [], timeoutMs).catch(() => undefined);
265
+ return sessions && EnvironmentsUtil.summary(sessions);
266
+ }
267
+ /** The conversations open in its Ta, each with pi's statistics of it, over one connection. */
268
+ async agents(tenant, now = Date.now()) {
269
+ const endpoint = this.watched(tenant);
270
+ if (!endpoint) {
271
+ throw new EnvironmentError(this.provider(tenant).own
272
+ ? 'The Ta service of the user is theirs: the gateway does not watch it.'
273
+ : 'Its sandbox does not run: start it to see its agents.');
274
+ }
275
+ const [sessions] = await EnvironmentsUtil.calls(endpoint, [['TaServer/listSessions', []]]);
276
+ const stats = await EnvironmentsUtil.calls(endpoint, sessions.map(session => ['TaServer/getSessionStats', [session.sessionId]])).catch(() => sessions.map(() => undefined));
277
+ const list = sessions
278
+ .map((session, index) => EnvironmentsUtil.agentSession(session, EnvironmentsUtil.stats(stats[index])))
279
+ .sort((a, b) => b.updatedAt - a.updatedAt);
280
+ return {
281
+ sessions: list,
282
+ totals: {
283
+ ...EnvironmentsUtil.summary(sessions),
284
+ toolCalls: list.reduce((sum, each) => { var _a; var _b; return sum + ((_b = (_a = each.stats) === null || _a === void 0 ? void 0 : _a.toolCalls) !== null && _b !== void 0 ? _b : 0); }, 0),
285
+ tokens: list.reduce((sum, each) => { var _a; var _b; return sum + ((_b = (_a = each.stats) === null || _a === void 0 ? void 0 : _a.tokens.total) !== null && _b !== void 0 ? _b : 0); }, 0),
286
+ cost: list.reduce((sum, each) => { var _a; var _b; return sum + ((_b = (_a = each.stats) === null || _a === void 0 ? void 0 : _a.cost) !== null && _b !== void 0 ? _b : 0); }, 0),
287
+ },
288
+ readAt: now,
289
+ };
290
+ }
121
291
  connections(tenantId) {
122
292
  var _a;
123
293
  var _b;
@@ -125,6 +295,7 @@ class Environments {
125
295
  }
126
296
  /** Where the Ta of the tenant answers, started when it does not run. */
127
297
  ensure(tenant) {
298
+ var _a;
128
299
  const running = this.state(tenant.id);
129
300
  if (running.status === 'running' && running.endpoint) {
130
301
  return Promise.resolve(running.endpoint);
@@ -132,13 +303,20 @@ class Environments {
132
303
  if (running.starting) {
133
304
  return running.starting;
134
305
  }
306
+ const blocked = (_a = this.guard) === null || _a === void 0 ? void 0 : _a.call(this, tenant);
307
+ if (blocked) {
308
+ Object.assign(running, { status: 'failed', error: blocked });
309
+ return Promise.reject(new EnvironmentError(blocked));
310
+ }
135
311
  running.status = 'starting';
136
312
  running.error = undefined;
137
313
  const starting = (async () => {
138
314
  var _a;
139
- const { provider } = this.provider(tenant);
140
- const endpoint = await provider.start(EnvironmentsUtil.sandboxTenant(tenant));
141
- await EnvironmentsUtil.waitReady(endpoint.url, (_a = this.settings.readyTimeoutMs) !== null && _a !== void 0 ? _a : provider.readyTimeoutMs);
315
+ var _b;
316
+ const { provider, own } = this.provider(tenant);
317
+ const env = own ? undefined : (_a = this.envOf) === null || _a === void 0 ? void 0 : _a.call(this, tenant, provider);
318
+ const endpoint = await provider.start({ ...EnvironmentsUtil.sandboxTenant(tenant), ...(env ? { env } : {}) });
319
+ await EnvironmentsUtil.waitReady(endpoint.url, (_b = this.settings.readyTimeoutMs) !== null && _b !== void 0 ? _b : provider.readyTimeoutMs);
142
320
  return endpoint;
143
321
  })();
144
322
  running.starting = starting;
@@ -0,0 +1,13 @@
1
+ import type { TaGatewayAuditEntry } from '@celljs/ta-protocol';
2
+ /**
3
+ * What administrators did, one JSON line each (`audit.jsonl`, readable by the gateway's user only): what changed
4
+ * and what of others was looked at (logs, what an agent did), with who and when.
5
+ */
6
+ export declare class GatewayAudit {
7
+ protected readonly file: string;
8
+ constructor(dir: string);
9
+ add(entry: Omit<TaGatewayAuditEntry, 'at'>, now?: number): void;
10
+ /** The latest first. */
11
+ list(limit: number): TaGatewayAuditEntry[];
12
+ }
13
+ //# sourceMappingURL=gateway-audit.d.ts.map