@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
@@ -8,21 +8,25 @@ export declare namespace CommandSandboxUtil {
8
8
  * by shell commands, as pi's models.json takes an endpoint it has no provider for. Each runs with
9
9
  * TA_TENANT_ID, TA_TENANT_ACCOUNT and TA_SERVE_TOKEN in its environment: `start` makes or starts the sandbox
10
10
  * of the tenant, whose Ta service takes TA_SERVE_TOKEN, and prints its address last; `stop` stops it;
11
- * `state` prints running, stopped or missing.
11
+ * `state` prints running, stopped or missing; `logs`, when there is one, prints the last TA_LOG_LINES lines
12
+ * the sandbox wrote, for the console.
12
13
  */
13
14
  export declare class CommandSandbox implements SandboxProvider {
14
15
  readonly id: string;
15
16
  readonly type = "command";
16
17
  readonly name: string;
18
+ readonly gatewayUrl?: string;
17
19
  protected readonly commands: {
18
20
  start: string;
19
21
  stop?: string;
20
22
  state?: string;
23
+ logs?: string;
21
24
  };
22
25
  protected readonly env: Record<string, string>;
23
26
  constructor(id: string, config: SandboxProviderConfig);
27
+ logs?(tenant: SandboxTenant, lines: number): Promise<string>;
24
28
  start(tenant: SandboxTenant): Promise<SandboxEndpoint>;
25
29
  stop(tenant: SandboxTenant): Promise<void>;
26
30
  state(tenant: SandboxTenant): Promise<SandboxState>;
27
- protected run(command: string, tenant: SandboxTenant): Promise<string>;
31
+ protected run(command: string, tenant: SandboxTenant, extra?: Record<string, string>): Promise<string>;
28
32
  }
@@ -19,19 +19,33 @@ export var CommandSandboxUtil;
19
19
  * by shell commands, as pi's models.json takes an endpoint it has no provider for. Each runs with
20
20
  * TA_TENANT_ID, TA_TENANT_ACCOUNT and TA_SERVE_TOKEN in its environment: `start` makes or starts the sandbox
21
21
  * of the tenant, whose Ta service takes TA_SERVE_TOKEN, and prints its address last; `stop` stops it;
22
- * `state` prints running, stopped or missing.
22
+ * `state` prints running, stopped or missing; `logs`, when there is one, prints the last TA_LOG_LINES lines
23
+ * the sandbox wrote, for the console.
23
24
  */
24
25
  export class CommandSandbox {
25
26
  constructor(id, config) {
26
27
  this.id = id;
27
28
  this.type = 'command';
28
29
  this.name = SandboxProviders.string(config, 'name', id);
30
+ this.gatewayUrl = SandboxProviders.string(config, 'gatewayUrl');
29
31
  const start = SandboxProviders.string(config, 'start');
30
32
  if (!start) {
31
33
  throw new Error(`The provider "${id}" of the type command needs "start", a command that prints the address of the Ta service.`);
32
34
  }
33
- this.commands = { start, stop: SandboxProviders.string(config, 'stop'), state: SandboxProviders.string(config, 'state') };
35
+ this.commands = {
36
+ start,
37
+ stop: SandboxProviders.string(config, 'stop'),
38
+ state: SandboxProviders.string(config, 'state'),
39
+ logs: SandboxProviders.string(config, 'logs'),
40
+ };
34
41
  this.env = SandboxProviders.env(config);
42
+ if (!this.commands.logs) {
43
+ // The console asks a provider whether it has logs by the method.
44
+ this.logs = undefined;
45
+ }
46
+ }
47
+ logs(tenant, lines) {
48
+ return this.run(this.commands.logs, tenant, { TA_LOG_LINES: String(lines) });
35
49
  }
36
50
  async start(tenant) {
37
51
  const stdout = await this.run(this.commands.start, tenant);
@@ -53,10 +67,18 @@ export class CommandSandbox {
53
67
  const word = (await this.run(this.commands.state, tenant)).trim().split(/\s+/).pop();
54
68
  return word === 'running' || word === 'stopped' ? word : 'missing';
55
69
  }
56
- run(command, tenant) {
70
+ run(command, tenant, extra = {}) {
57
71
  return new Promise((resolve, reject) => {
58
72
  const child = spawn('sh', ['-c', command], {
59
- env: { ...process.env, ...this.env, TA_TENANT_ID: tenant.id, TA_TENANT_ACCOUNT: tenant.account, TA_SERVE_TOKEN: tenant.token },
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
+ },
60
82
  stdio: ['ignore', 'pipe', 'pipe'],
61
83
  });
62
84
  let stdout = '';
@@ -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`. */
@@ -24,7 +24,20 @@ export class DockerEngine {
24
24
  }
25
25
  }
26
26
  /** The answer of the Engine, parsed when it is JSON; a status of 400 and above throws. */
27
- call(method, path, body, timeoutMs = 120000) {
27
+ async call(method, path, body, timeoutMs = 120000) {
28
+ const answer = await this.raw(method, path, body, timeoutMs);
29
+ const text = answer.body.toString('utf8');
30
+ let parsed = text;
31
+ try {
32
+ parsed = text ? JSON.parse(text) : undefined;
33
+ }
34
+ catch (_a) {
35
+ // Streams of progress (a pull) are lines of JSON: kept as text.
36
+ }
37
+ return { status: answer.status, body: parsed };
38
+ }
39
+ /** The answer of the Engine as it came, for the streams of logs, which are not text; a status of 400 and above throws. */
40
+ raw(method, path, body, timeoutMs = 120000) {
28
41
  return new Promise((resolve, reject) => {
29
42
  const payload = body === undefined ? undefined : JSON.stringify(body);
30
43
  const req = request({
@@ -38,21 +51,21 @@ export class DockerEngine {
38
51
  res.on('data', chunk => chunks.push(chunk));
39
52
  res.on('end', () => {
40
53
  var _a, _b;
41
- const text = Buffer.concat(chunks).toString('utf8');
42
- let parsed = text;
43
- try {
44
- parsed = text ? JSON.parse(text) : undefined;
45
- }
46
- catch (_c) {
47
- // Streams of progress (a pull) are lines of JSON: kept as text.
48
- }
54
+ const buffer = Buffer.concat(chunks);
49
55
  const status = (_a = res.statusCode) !== null && _a !== void 0 ? _a : 0;
50
56
  if (status >= 400) {
51
- const message = (_b = parsed === null || parsed === void 0 ? void 0 : parsed.message) !== null && _b !== void 0 ? _b : text;
57
+ const text = buffer.toString('utf8');
58
+ let message = text;
59
+ try {
60
+ message = (_b = JSON.parse(text).message) !== null && _b !== void 0 ? _b : text;
61
+ }
62
+ catch (_c) {
63
+ // Not JSON: the text as it is.
64
+ }
52
65
  reject(new DockerError(`Docker: ${method} ${path.split('?')[0]} answered ${status}: ${message}`, status));
53
66
  }
54
67
  else {
55
- resolve({ status, body: parsed });
68
+ resolve({ status, body: buffer });
56
69
  }
57
70
  });
58
71
  });
@@ -93,6 +106,43 @@ export class DockerEngine {
93
106
  }
94
107
  }
95
108
  }
109
+ /** 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. */
110
+ async stats(name) {
111
+ try {
112
+ const { body } = await this.call('GET', `/containers/${encodeURIComponent(name)}/stats?stream=false`, undefined, 15000);
113
+ return DockerEngineUtil.usage(body);
114
+ }
115
+ catch (error) {
116
+ if (error instanceof DockerError && (error.status === 404 || error.status === 409)) {
117
+ return undefined;
118
+ }
119
+ throw error;
120
+ }
121
+ }
122
+ /** The last `lines` of what a container wrote, its output and errors in their order; empty for one that is not there. */
123
+ async logs(name, lines) {
124
+ try {
125
+ const { body } = await this.raw('GET', `/containers/${encodeURIComponent(name)}/logs?stdout=1&stderr=1&tail=${lines}`, undefined, 15000);
126
+ return DockerEngineUtil.demux(body);
127
+ }
128
+ catch (error) {
129
+ if (error instanceof DockerError && error.status === 404) {
130
+ return '';
131
+ }
132
+ throw error;
133
+ }
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
+ }
96
146
  /** A bridge network, made when missing; `isolated`: its containers cannot reach each other. */
97
147
  async ensureNetwork(name, isolated) {
98
148
  try {
@@ -124,6 +174,43 @@ export class DockerEngine {
124
174
  }
125
175
  export var DockerEngineUtil;
126
176
  (function (DockerEngineUtil) {
177
+ /** As `docker stats` reckons: CPU in percent of one CPU, memory without the page cache. */
178
+ function usage(stats) {
179
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
180
+ var _r, _s, _t, _u, _v, _w;
181
+ 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)) {
182
+ // A container that does not run answers with zeroes.
183
+ return undefined;
184
+ }
185
+ 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);
186
+ 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);
187
+ const cpus = ((_j = stats.cpu_stats) === null || _j === void 0 ? void 0 : _j.online_cpus) || 1;
188
+ const cpu = systemDelta > 0 && cpuDelta >= 0 ? Math.round((cpuDelta / systemDelta) * cpus * 1000) / 10 : undefined;
189
+ const memory = (_k = stats.memory_stats) === null || _k === void 0 ? void 0 : _k.usage;
190
+ // cgroup v2 says inactive_file, v1 cache: what `docker stats` takes away.
191
+ 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;
192
+ return { cpu, memory: memory === undefined ? undefined : Math.max(0, memory - cache), memoryLimit: (_q = stats.memory_stats) === null || _q === void 0 ? void 0 : _q.limit };
193
+ }
194
+ DockerEngineUtil.usage = usage;
195
+ /**
196
+ * The text of the logs of a container without a terminal: frames of a header of 8 bytes (the stream, three
197
+ * zeroes, the length) and their bytes. One with a terminal sends its text as it is.
198
+ */
199
+ function demux(buffer) {
200
+ const parts = [];
201
+ let offset = 0;
202
+ while (offset + 8 <= buffer.length) {
203
+ const stream = buffer[offset];
204
+ const size = buffer.readUInt32BE(offset + 4);
205
+ if (stream > 2 || buffer[offset + 1] !== 0 || buffer[offset + 2] !== 0 || buffer[offset + 3] !== 0 || offset + 8 + size > buffer.length) {
206
+ return buffer.toString('utf8');
207
+ }
208
+ parts.push(buffer.subarray(offset + 8, offset + 8 + size));
209
+ offset += 8 + size;
210
+ }
211
+ return offset === buffer.length ? Buffer.concat(parts).toString('utf8') : buffer.toString('utf8');
212
+ }
213
+ DockerEngineUtil.demux = demux;
127
214
  /** `ghcr.io:443/me/ta:1.0` → `ghcr.io:443/me/ta`, `1.0`: the tag after the last `:` that is past the last `/`. */
128
215
  function splitImage(image) {
129
216
  const slash = image.lastIndexOf('/');
@@ -1,6 +1,8 @@
1
1
  import { DockerEngine } from './docker-engine.js';
2
- import { type SandboxEndpoint, type SandboxProvider, type SandboxProviderConfig, type SandboxState, type SandboxTenant } from './sandbox-provider.js';
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,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;
@@ -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 = (_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;
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
  }
@@ -81,6 +93,12 @@ export class DockerSandbox {
81
93
  const container = await this.engine.inspect(this.containerName(tenant));
82
94
  return !container ? 'missing' : container.State.Running ? 'running' : 'stopped';
83
95
  }
96
+ usage(tenant) {
97
+ return this.engine.stats(this.containerName(tenant));
98
+ }
99
+ logs(tenant, lines) {
100
+ return this.engine.logs(this.containerName(tenant), lines);
101
+ }
84
102
  /** What `docker run` would be given. */
85
103
  spec(tenant) {
86
104
  const name = this.containerName(tenant);
@@ -88,11 +106,13 @@ export class DockerSandbox {
88
106
  Image: this.options.image,
89
107
  // What the Ta of the tenant tells its clients its machine is, as the list of computers of the phone shows it.
90
108
  Hostname: DockerSandboxUtil.hostname(tenant.account),
91
- 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}`)],
92
110
  Labels: { 'cell.ta.tenant': tenant.id, 'cell.ta.account': tenant.account },
93
111
  ExposedPorts: { [PORT]: {} },
94
112
  HostConfig: {
95
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'],
96
116
  Mounts: [{ Type: 'volume', Source: name, Target: '/home/ta' }],
97
117
  NetworkMode: this.options.network,
98
118
  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.js';
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.js';
3
3
  import type { Tenant, TenantStore } from './tenant-store.js';
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>;