@celljs/ta-gateway 4.15.0 → 4.15.2

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 (57) hide show
  1. package/esm/node/command-sandbox.d.ts +5 -2
  2. package/esm/node/command-sandbox.js +17 -4
  3. package/esm/node/docker-engine.d.ts +45 -0
  4. package/esm/node/docker-engine.js +87 -11
  5. package/esm/node/docker-sandbox.d.ts +3 -1
  6. package/esm/node/docker-sandbox.js +6 -0
  7. package/esm/node/environments.d.ts +34 -2
  8. package/esm/node/environments.js +187 -11
  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-policy.d.ts +46 -0
  14. package/esm/node/gateway-policy.js +151 -0
  15. package/esm/node/gateway-quotas.d.ts +32 -0
  16. package/esm/node/gateway-quotas.js +104 -0
  17. package/esm/node/gateway-server.d.ts +16 -1
  18. package/esm/node/gateway-server.js +58 -6
  19. package/esm/node/gateway-service.d.ts +91 -16
  20. package/esm/node/gateway-service.js +366 -45
  21. package/esm/node/gateway-socket.d.ts +7 -1
  22. package/esm/node/gateway-socket.js +40 -1
  23. package/esm/node/gateway-usage.d.ts +37 -0
  24. package/esm/node/gateway-usage.js +137 -0
  25. package/esm/node/local-sandbox.d.ts +12 -0
  26. package/esm/node/local-sandbox.js +36 -1
  27. package/esm/node/sandbox-provider.d.ts +10 -0
  28. package/esm/node/tenant-store.d.ts +12 -1
  29. package/lib/node/command-sandbox.d.ts +5 -2
  30. package/lib/node/command-sandbox.js +17 -4
  31. package/lib/node/docker-engine.d.ts +45 -0
  32. package/lib/node/docker-engine.js +87 -11
  33. package/lib/node/docker-sandbox.d.ts +3 -1
  34. package/lib/node/docker-sandbox.js +6 -0
  35. package/lib/node/environments.d.ts +34 -2
  36. package/lib/node/environments.js +186 -10
  37. package/lib/node/gateway-audit.d.ts +13 -0
  38. package/lib/node/gateway-audit.js +51 -0
  39. package/lib/node/gateway-cli.d.ts +2 -0
  40. package/lib/node/gateway-cli.js +1 -0
  41. package/lib/node/gateway-policy.d.ts +47 -0
  42. package/lib/node/gateway-policy.js +156 -0
  43. package/lib/node/gateway-quotas.d.ts +33 -0
  44. package/lib/node/gateway-quotas.js +108 -0
  45. package/lib/node/gateway-server.d.ts +16 -1
  46. package/lib/node/gateway-server.js +58 -6
  47. package/lib/node/gateway-service.d.ts +91 -16
  48. package/lib/node/gateway-service.js +365 -44
  49. package/lib/node/gateway-socket.d.ts +7 -1
  50. package/lib/node/gateway-socket.js +40 -1
  51. package/lib/node/gateway-usage.d.ts +38 -0
  52. package/lib/node/gateway-usage.js +141 -0
  53. package/lib/node/local-sandbox.d.ts +12 -0
  54. package/lib/node/local-sandbox.js +38 -2
  55. package/lib/node/sandbox-provider.d.ts +10 -0
  56. package/lib/node/tenant-store.d.ts +12 -1
  57. package/package.json +4 -4
@@ -0,0 +1,38 @@
1
+ import type { TaUsageBucket, TaUsageTrend } from '@celljs/ta-protocol';
2
+ interface Kept {
3
+ readAt: number;
4
+ buckets: TaUsageBucket[];
5
+ }
6
+ export declare namespace GatewayUsageUtil {
7
+ const KEEP_MS: number;
8
+ /** The start of the month of UTC of `now`, and of the next. */
9
+ function month(now: number): {
10
+ key: string;
11
+ start: number;
12
+ next: number;
13
+ };
14
+ function tokens(bucket: TaUsageBucket): number;
15
+ /** The buckets of tenants since `since`: by hour, by model and by tenant. */
16
+ function trend(byTenant: Map<string, TaUsageBucket[]>, since: number, stale: string[], now: number): TaUsageTrend;
17
+ }
18
+ /**
19
+ * What the agents of each tenant took, by hour, as its Ta said last (TaUsageServer): asked of a running sandbox
20
+ * at most once a minute, kept in `usage/<tenant>.json` so that one stopped still counts.
21
+ */
22
+ export declare class GatewayUsage {
23
+ protected readonly dir: string;
24
+ protected readonly kept: Map<string, Kept>;
25
+ protected readonly reading: Map<string, Promise<void>>;
26
+ constructor(root: string);
27
+ /** What is kept of the tenant. */
28
+ get(tenantId: string): Kept | undefined;
29
+ /** Asks the tenant's Ta again, unless it was asked within `maxAge` (a minute); `read` undefined: it does not run. */
30
+ refresh(tenantId: string, read: ((since: number) => Promise<TaUsageBucket[]>) | undefined, now?: number, maxAge?: number): Promise<boolean>;
31
+ /** Tokens and dollars of the month of `now`. */
32
+ month(tenantId: string, now?: number): {
33
+ tokens: number;
34
+ cost: number;
35
+ };
36
+ }
37
+ export {};
38
+ //# sourceMappingURL=gateway-usage.d.ts.map
@@ -0,0 +1,141 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GatewayUsage = exports.GatewayUsageUtil = void 0;
4
+ const node_fs_1 = require("node:fs");
5
+ const node_path_1 = require("node:path");
6
+ const tenant_store_1 = require("./tenant-store");
7
+ const HOUR = 3600000;
8
+ const DAY = 24 * HOUR;
9
+ /** Kept of each tenant: a month, whatever day of it. */
10
+ const KEPT_DAYS = 32;
11
+ /** A tenant's usage is asked again at most this often. */
12
+ const FRESH_MS = 60000;
13
+ var GatewayUsageUtil;
14
+ (function (GatewayUsageUtil) {
15
+ GatewayUsageUtil.KEEP_MS = KEPT_DAYS * DAY;
16
+ /** The start of the month of UTC of `now`, and of the next. */
17
+ function month(now) {
18
+ const date = new Date(now);
19
+ const start = Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), 1);
20
+ const next = Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + 1, 1);
21
+ return { key: new Date(start).toISOString().slice(0, 7), start, next };
22
+ }
23
+ GatewayUsageUtil.month = month;
24
+ function tokens(bucket) {
25
+ return bucket.input + bucket.output + bucket.cacheRead + bucket.cacheWrite;
26
+ }
27
+ GatewayUsageUtil.tokens = tokens;
28
+ /** The buckets of tenants since `since`: by hour, by model and by tenant. */
29
+ function trend(byTenant, since, stale, now) {
30
+ var _a, _b;
31
+ const hours = new Map();
32
+ const models = new Map();
33
+ const tenants = [];
34
+ for (const [tenantId, buckets] of byTenant) {
35
+ const share = { tenantId, tokens: 0, cost: 0, turns: 0 };
36
+ for (const bucket of buckets) {
37
+ if (bucket.at + HOUR <= since) {
38
+ continue;
39
+ }
40
+ const count = tokens(bucket);
41
+ const hour = (_a = hours.get(bucket.at)) !== null && _a !== void 0 ? _a : { at: bucket.at, input: 0, output: 0, tokens: 0, cost: 0, turns: 0 };
42
+ hour.input += bucket.input;
43
+ hour.output += bucket.output;
44
+ hour.tokens += count;
45
+ hour.cost += bucket.cost;
46
+ hour.turns += bucket.turns;
47
+ hours.set(bucket.at, hour);
48
+ const model = (_b = models.get(bucket.model)) !== null && _b !== void 0 ? _b : { model: bucket.model, tokens: 0, cost: 0, turns: 0 };
49
+ model.tokens += count;
50
+ model.cost += bucket.cost;
51
+ model.turns += bucket.turns;
52
+ models.set(bucket.model, model);
53
+ share.tokens += count;
54
+ share.cost += bucket.cost;
55
+ share.turns += bucket.turns;
56
+ }
57
+ if (share.turns > 0) {
58
+ tenants.push(share);
59
+ }
60
+ }
61
+ return {
62
+ since,
63
+ hours: [...hours.values()].sort((a, b) => a.at - b.at),
64
+ byModel: [...models.values()].sort((a, b) => b.cost - a.cost || b.tokens - a.tokens),
65
+ byTenant: tenants.sort((a, b) => b.cost - a.cost || b.tokens - a.tokens),
66
+ stale,
67
+ readAt: now,
68
+ };
69
+ }
70
+ GatewayUsageUtil.trend = trend;
71
+ })(GatewayUsageUtil || (exports.GatewayUsageUtil = GatewayUsageUtil = {}));
72
+ /**
73
+ * What the agents of each tenant took, by hour, as its Ta said last (TaUsageServer): asked of a running sandbox
74
+ * at most once a minute, kept in `usage/<tenant>.json` so that one stopped still counts.
75
+ */
76
+ class GatewayUsage {
77
+ constructor(root) {
78
+ this.kept = new Map();
79
+ this.reading = new Map();
80
+ this.dir = (0, node_path_1.join)(root, 'usage');
81
+ (0, node_fs_1.mkdirSync)(this.dir, { recursive: true, mode: 0o700 });
82
+ }
83
+ /** What is kept of the tenant. */
84
+ get(tenantId) {
85
+ let kept = this.kept.get(tenantId);
86
+ if (!kept && /^[0-9a-f]{16}$/.test(tenantId)) {
87
+ try {
88
+ kept = JSON.parse((0, node_fs_1.readFileSync)((0, node_path_1.join)(this.dir, `${tenantId}.json`), 'utf8'));
89
+ this.kept.set(tenantId, kept);
90
+ }
91
+ catch (_a) {
92
+ return undefined;
93
+ }
94
+ }
95
+ return kept;
96
+ }
97
+ /** Asks the tenant's Ta again, unless it was asked within `maxAge` (a minute); `read` undefined: it does not run. */
98
+ async refresh(tenantId, read, now = Date.now(), maxAge = FRESH_MS) {
99
+ const kept = this.get(tenantId);
100
+ if (!read) {
101
+ return false;
102
+ }
103
+ if (kept && now - kept.readAt < maxAge) {
104
+ return true;
105
+ }
106
+ let reading = this.reading.get(tenantId);
107
+ if (!reading) {
108
+ reading = read(now - GatewayUsageUtil.KEEP_MS).then(buckets => {
109
+ const next = { readAt: now, buckets };
110
+ this.kept.set(tenantId, next);
111
+ (0, tenant_store_1.writePrivate)((0, node_path_1.join)(this.dir, `${tenantId}.json`), next);
112
+ });
113
+ this.reading.set(tenantId, reading);
114
+ void reading.finally(() => this.reading.delete(tenantId)).catch(() => undefined);
115
+ }
116
+ try {
117
+ await reading;
118
+ return true;
119
+ }
120
+ catch (_a) {
121
+ return false;
122
+ }
123
+ }
124
+ /** Tokens and dollars of the month of `now`. */
125
+ month(tenantId, now = Date.now()) {
126
+ var _a;
127
+ var _b;
128
+ const { start } = GatewayUsageUtil.month(now);
129
+ let tokens = 0;
130
+ let cost = 0;
131
+ for (const bucket of (_b = (_a = this.get(tenantId)) === null || _a === void 0 ? void 0 : _a.buckets) !== null && _b !== void 0 ? _b : []) {
132
+ if (bucket.at >= start) {
133
+ tokens += GatewayUsageUtil.tokens(bucket);
134
+ cost += bucket.cost;
135
+ }
136
+ }
137
+ return { tokens, cost };
138
+ }
139
+ }
140
+ exports.GatewayUsage = GatewayUsage;
141
+ //# sourceMappingURL=gateway-usage.js.map
@@ -1,5 +1,14 @@
1
1
  import { type ChildProcess } from 'node:child_process';
2
2
  import type { SandboxContext, SandboxEndpoint, SandboxProvider, SandboxProviderConfig, SandboxState, SandboxTenant } from './sandbox-provider';
3
+ /** The last lines written to it, whole lines only but the one being written. */
4
+ export declare class LineTail {
5
+ protected readonly max: number;
6
+ protected readonly lines: string[];
7
+ protected partial: string;
8
+ constructor(max?: number);
9
+ write(chunk: string): void;
10
+ last(count: number): string;
11
+ }
3
12
  /**
4
13
  * `local`: a `ta serve` process per tenant on the machine of the gateway, its agent directory and workspace
5
14
  * under `<gateway>/local/<tenant>`. Not a sandbox: every tenant runs as the user of the gateway and can read
@@ -14,10 +23,13 @@ export declare class LocalSandbox implements SandboxProvider {
14
23
  child: ChildProcess;
15
24
  url: string;
16
25
  }>;
26
+ /** Kept past a stop, so that the console shows why one ended. */
27
+ protected readonly output: Map<string, LineTail>;
17
28
  constructor(id: string, config: SandboxProviderConfig, context: SandboxContext);
18
29
  start(tenant: SandboxTenant): Promise<SandboxEndpoint>;
19
30
  stop(tenant: SandboxTenant): Promise<void>;
20
31
  state(tenant: SandboxTenant): Promise<SandboxState>;
32
+ logs(tenant: SandboxTenant, lines: number): Promise<string>;
21
33
  dispose(): Promise<void>;
22
34
  static freePort(): Promise<number>;
23
35
  }
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.LocalSandbox = void 0;
3
+ exports.LocalSandbox = exports.LineTail = void 0;
4
4
  const node_child_process_1 = require("node:child_process");
5
5
  const node_fs_1 = require("node:fs");
6
6
  const node_net_1 = require("node:net");
@@ -8,6 +8,30 @@ const node_path_1 = require("node:path");
8
8
  const sandbox_provider_1 = require("./sandbox-provider");
9
9
  /** How long a ta serve has to end on SIGTERM before it is killed. */
10
10
  const STOP_TIMEOUT_MS = 10000;
11
+ /** The lines of output of each tenant's ta serve kept for the console. */
12
+ const KEPT_LINES = 2000;
13
+ /** The last lines written to it, whole lines only but the one being written. */
14
+ class LineTail {
15
+ constructor(max = KEPT_LINES) {
16
+ this.max = max;
17
+ this.lines = [];
18
+ this.partial = '';
19
+ }
20
+ write(chunk) {
21
+ var _a;
22
+ const parts = (this.partial + chunk).split('\n');
23
+ this.partial = (_a = parts.pop()) !== null && _a !== void 0 ? _a : '';
24
+ this.lines.push(...parts);
25
+ if (this.lines.length > this.max) {
26
+ this.lines.splice(0, this.lines.length - this.max);
27
+ }
28
+ }
29
+ last(count) {
30
+ const lines = this.partial ? [...this.lines, this.partial] : this.lines;
31
+ return lines.slice(-count).join('\n');
32
+ }
33
+ }
34
+ exports.LineTail = LineTail;
11
35
  /**
12
36
  * `local`: a `ta serve` process per tenant on the machine of the gateway, its agent directory and workspace
13
37
  * under `<gateway>/local/<tenant>`. Not a sandbox: every tenant runs as the user of the gateway and can read
@@ -19,9 +43,12 @@ class LocalSandbox {
19
43
  this.context = context;
20
44
  this.type = 'local';
21
45
  this.running = new Map();
46
+ /** Kept past a stop, so that the console shows why one ended. */
47
+ this.output = new Map();
22
48
  this.name = sandbox_provider_1.SandboxProviders.string(config, 'name', 'Local');
23
49
  }
24
50
  async start(tenant) {
51
+ var _a, _b;
25
52
  const running = this.running.get(tenant.id);
26
53
  if (running && running.child.exitCode === null) {
27
54
  return { url: running.url, token: tenant.token };
@@ -36,8 +63,12 @@ class LocalSandbox {
36
63
  const child = (0, node_child_process_1.spawn)(command, [...args, 'serve', '--port', String(port)], {
37
64
  cwd,
38
65
  env: { ...process.env, TA_CODING_AGENT_DIR: agentDir, TA_SERVE_TOKEN: tenant.token, CELL_SERVER__HOST: '127.0.0.1' },
39
- stdio: 'ignore',
66
+ stdio: ['ignore', 'pipe', 'pipe'],
40
67
  });
68
+ const tail = new LineTail();
69
+ this.output.set(tenant.id, tail);
70
+ (_a = child.stdout) === null || _a === void 0 ? void 0 : _a.setEncoding('utf8').on('data', (data) => tail.write(data));
71
+ (_b = child.stderr) === null || _b === void 0 ? void 0 : _b.setEncoding('utf8').on('data', (data) => tail.write(data));
41
72
  const url = `http://127.0.0.1:${port}`;
42
73
  // A command that cannot start fails this tenant's start (nothing answers), not the gateway.
43
74
  const gone = () => {
@@ -72,6 +103,11 @@ class LocalSandbox {
72
103
  async state(tenant) {
73
104
  return this.running.has(tenant.id) ? 'running' : 'stopped';
74
105
  }
106
+ async logs(tenant, lines) {
107
+ var _a;
108
+ var _b;
109
+ return (_b = (_a = this.output.get(tenant.id)) === null || _a === void 0 ? void 0 : _a.last(lines)) !== null && _b !== void 0 ? _b : '';
110
+ }
75
111
  async dispose() {
76
112
  await Promise.all([...this.running.keys()].map(id => this.stop({ id, account: '', token: '' })));
77
113
  }
@@ -10,6 +10,12 @@ export interface SandboxEndpoint {
10
10
  token: string;
11
11
  }
12
12
  export type SandboxState = 'running' | 'stopped' | 'missing';
13
+ /** What a running sandbox takes: CPU in percent of one CPU, memory in bytes. */
14
+ export interface SandboxUsage {
15
+ cpu?: number;
16
+ memory?: number;
17
+ memoryLimit?: number;
18
+ }
13
19
  /**
14
20
  * Makes and runs the sandboxes of tenants, one each: a container, a process, a machine of a cloud. As a model
15
21
  * provider of pi is to models, built in (`docker`, `command`, `local`, `ta`) or a module of the operator's
@@ -30,6 +36,10 @@ export interface SandboxProvider {
30
36
  /** Stops it, keeping what it holds, to start again later. */
31
37
  stop(tenant: SandboxTenant): Promise<void>;
32
38
  state(tenant: SandboxTenant): Promise<SandboxState>;
39
+ /** What its sandbox takes now, for the console; undefined when it does not run. */
40
+ usage?(tenant: SandboxTenant): Promise<SandboxUsage | undefined>;
41
+ /** The last `lines` its sandbox wrote (its Ta service's output), for the console. */
42
+ logs?(tenant: SandboxTenant, lines: number): Promise<string>;
33
43
  /** The gateway stops: what runs in this process ends (`local`). */
34
44
  dispose?(): Promise<void>;
35
45
  }
@@ -1,4 +1,11 @@
1
- import type { TaEnvironmentChoice } from '@celljs/ta-protocol';
1
+ import type { TaEnvironmentChoice, TaGatewayLimits } from '@celljs/ta-protocol';
2
+ /** The minutes a tenant's sandbox ran in a month (of UTC), and those given on top of its limit. */
3
+ export interface TenantMeter {
4
+ /** `YYYY-MM`. */
5
+ month: string;
6
+ runMs: number;
7
+ bonusMinutes: number;
8
+ }
2
9
  /** A tenant: an account and its Ta, wherever it runs. */
3
10
  export interface Tenant {
4
11
  id: string;
@@ -11,6 +18,10 @@ export interface Tenant {
11
18
  environment?: TaEnvironmentChoice;
12
19
  createdAt: number;
13
20
  lastActiveAt?: number;
21
+ /** Its own limits over the gateway's defaults. */
22
+ limits?: TaGatewayLimits;
23
+ suspended?: boolean;
24
+ meter?: TenantMeter;
14
25
  }
15
26
  /** Files written whole or not at all, readable by this user only. */
16
27
  export declare function writePrivate(file: string, data: unknown): void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@celljs/ta-gateway",
3
- "version": "4.15.0",
3
+ "version": "4.15.2",
4
4
  "description": "ta gateway: one Ta per account, each in a sandbox of its own, behind one sign-in",
5
5
  "homepage": "https://github.com/cellbang/ta",
6
6
  "bugs": {
@@ -29,9 +29,9 @@
29
29
  "watch": "tsc -b -w --preserveWatchOutput"
30
30
  },
31
31
  "dependencies": {
32
- "@celljs/rpc": "4.15.0",
33
- "@celljs/ta-host": "4.15.0",
34
- "@celljs/ta-protocol": "4.15.0"
32
+ "@celljs/rpc": "4.15.2",
33
+ "@celljs/ta-host": "4.15.2",
34
+ "@celljs/ta-protocol": "4.15.2"
35
35
  },
36
36
  "publishConfig": {
37
37
  "access": "public"