@celljs/ta-gateway 4.15.2 → 4.17.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 (81) hide show
  1. package/README.en.md +5 -2
  2. package/README.md +5 -2
  3. package/esm/node/command-sandbox.d.ts +1 -0
  4. package/esm/node/command-sandbox.js +10 -1
  5. package/esm/node/docker-engine.d.ts +10 -1
  6. package/esm/node/docker-engine.js +18 -1
  7. package/esm/node/docker-sandbox.d.ts +13 -1
  8. package/esm/node/docker-sandbox.js +35 -2
  9. package/esm/node/egress-proxy.d.ts +98 -0
  10. package/esm/node/egress-proxy.js +428 -0
  11. package/esm/node/environments.d.ts +5 -0
  12. package/esm/node/environments.js +7 -3
  13. package/esm/node/gateway-cli.js +12 -5
  14. package/esm/node/gateway-exec.d.ts +19 -0
  15. package/esm/node/gateway-exec.js +65 -0
  16. package/esm/node/gateway-policy.d.ts +7 -1
  17. package/esm/node/gateway-policy.js +12 -2
  18. package/esm/node/gateway-quotas.d.ts +15 -2
  19. package/esm/node/gateway-quotas.js +51 -3
  20. package/esm/node/gateway-server.d.ts +43 -1
  21. package/esm/node/gateway-server.js +179 -10
  22. package/esm/node/gateway-service-util.d.ts +41 -0
  23. package/esm/node/gateway-service-util.js +178 -0
  24. package/esm/node/gateway-service.d.ts +13 -41
  25. package/esm/node/gateway-service.js +41 -176
  26. package/esm/node/gateway-socket.d.ts +1 -1
  27. package/esm/node/gateway-socket.js +1 -1
  28. package/esm/node/index.d.ts +4 -0
  29. package/esm/node/index.js +4 -0
  30. package/esm/node/kubernetes-api.d.ts +35 -0
  31. package/esm/node/kubernetes-api.js +115 -0
  32. package/esm/node/kubernetes-sandbox.d.ts +198 -0
  33. package/esm/node/kubernetes-sandbox.js +279 -0
  34. package/esm/node/local-sandbox.d.ts +1 -0
  35. package/esm/node/local-sandbox.js +2 -1
  36. package/esm/node/model-proxy.d.ts +105 -0
  37. package/esm/node/model-proxy.js +435 -0
  38. package/esm/node/sandbox-provider.d.ts +17 -0
  39. package/esm/node/sandbox-provider.js +2 -1
  40. package/esm/node/tenant-store.d.ts +22 -0
  41. package/esm/node/tenant-store.js +25 -0
  42. package/lib/node/command-sandbox.d.ts +1 -0
  43. package/lib/node/command-sandbox.js +10 -1
  44. package/lib/node/docker-engine.d.ts +10 -1
  45. package/lib/node/docker-engine.js +18 -1
  46. package/lib/node/docker-sandbox.d.ts +13 -1
  47. package/lib/node/docker-sandbox.js +35 -2
  48. package/lib/node/egress-proxy.d.ts +99 -0
  49. package/lib/node/egress-proxy.js +433 -0
  50. package/lib/node/environments.d.ts +5 -0
  51. package/lib/node/environments.js +7 -3
  52. package/lib/node/gateway-cli.js +12 -5
  53. package/lib/node/gateway-exec.d.ts +20 -0
  54. package/lib/node/gateway-exec.js +69 -0
  55. package/lib/node/gateway-policy.d.ts +7 -1
  56. package/lib/node/gateway-policy.js +12 -2
  57. package/lib/node/gateway-quotas.d.ts +15 -2
  58. package/lib/node/gateway-quotas.js +51 -3
  59. package/lib/node/gateway-server.d.ts +43 -1
  60. package/lib/node/gateway-server.js +177 -8
  61. package/lib/node/gateway-service-util.d.ts +42 -0
  62. package/lib/node/gateway-service-util.js +182 -0
  63. package/lib/node/gateway-service.d.ts +13 -41
  64. package/lib/node/gateway-service.js +63 -199
  65. package/lib/node/gateway-socket.d.ts +1 -1
  66. package/lib/node/gateway-socket.js +10 -10
  67. package/lib/node/index.d.ts +4 -0
  68. package/lib/node/index.js +4 -0
  69. package/lib/node/kubernetes-api.d.ts +36 -0
  70. package/lib/node/kubernetes-api.js +120 -0
  71. package/lib/node/kubernetes-sandbox.d.ts +199 -0
  72. package/lib/node/kubernetes-sandbox.js +283 -0
  73. package/lib/node/local-sandbox.d.ts +1 -0
  74. package/lib/node/local-sandbox.js +2 -1
  75. package/lib/node/model-proxy.d.ts +106 -0
  76. package/lib/node/model-proxy.js +440 -0
  77. package/lib/node/sandbox-provider.d.ts +17 -0
  78. package/lib/node/sandbox-provider.js +2 -1
  79. package/lib/node/tenant-store.d.ts +22 -0
  80. package/lib/node/tenant-store.js +25 -0
  81. package/package.json +4 -4
@@ -0,0 +1,120 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.KubernetesUtil = exports.KubernetesApi = exports.KubernetesError = void 0;
4
+ const node_fs_1 = require("node:fs");
5
+ const node_http_1 = require("node:http");
6
+ const node_https_1 = require("node:https");
7
+ /** Where a pod finds the API of its cluster: its service account's token, CA and namespace. */
8
+ const ACCOUNT = '/var/run/secrets/kubernetes.io/serviceaccount';
9
+ class KubernetesError extends Error {
10
+ constructor(status, message) {
11
+ super(message);
12
+ this.status = status;
13
+ }
14
+ }
15
+ exports.KubernetesError = KubernetesError;
16
+ /**
17
+ * The API of a cluster over HTTPS, without a client library: what a provider of sandboxes needs is a few
18
+ * resources by their paths.
19
+ */
20
+ class KubernetesApi {
21
+ /** In a pod of the cluster: its service account, and the namespace it runs in. */
22
+ static inCluster(env = process.env, read = (path) => (0, node_fs_1.readFileSync)(path, 'utf8')) {
23
+ var _a;
24
+ const host = env.KUBERNETES_SERVICE_HOST;
25
+ if (!host) {
26
+ throw new Error('Not in a pod of Kubernetes (no KUBERNETES_SERVICE_HOST): give "server" and "token" of the cluster.');
27
+ }
28
+ const port = (_a = env.KUBERNETES_SERVICE_PORT) !== null && _a !== void 0 ? _a : '443';
29
+ return {
30
+ server: `https://${host.includes(':') ? `[${host}]` : host}:${port}`,
31
+ token: read(`${ACCOUNT}/token`).trim(),
32
+ ca: read(`${ACCOUNT}/ca.crt`),
33
+ namespace: read(`${ACCOUNT}/namespace`).trim(),
34
+ };
35
+ }
36
+ constructor(options) {
37
+ this.options = options;
38
+ }
39
+ async call(method, path, body, type = 'application/json') {
40
+ const text = await this.send(method, path, body === undefined ? undefined : JSON.stringify(body), type);
41
+ return (text ? JSON.parse(text) : undefined);
42
+ }
43
+ text(path) {
44
+ return this.send('GET', path);
45
+ }
46
+ send(method, path, body, type) {
47
+ const url = new URL(path, this.options.server);
48
+ const options = {
49
+ method,
50
+ headers: {
51
+ accept: 'application/json, */*',
52
+ ...(this.options.token ? { authorization: `Bearer ${this.options.token}` } : {}),
53
+ ...(body !== undefined ? { 'content-type': type !== null && type !== void 0 ? type : 'application/json', 'content-length': Buffer.byteLength(body) } : {}),
54
+ },
55
+ ...(this.options.ca ? { ca: this.options.ca } : {}),
56
+ timeout: 30000,
57
+ };
58
+ const send = url.protocol === 'https:' ? node_https_1.request : node_http_1.request;
59
+ return new Promise((resolve, reject) => {
60
+ const request = send(url, options, response => {
61
+ const chunks = [];
62
+ response.on('data', chunk => chunks.push(chunk));
63
+ response.on('end', () => {
64
+ var _a, _b;
65
+ const text = Buffer.concat(chunks).toString('utf8');
66
+ const status = (_a = response.statusCode) !== null && _a !== void 0 ? _a : 0;
67
+ if (status >= 200 && status < 300) {
68
+ resolve(text);
69
+ return;
70
+ }
71
+ let message = text.slice(0, 300);
72
+ try {
73
+ message = (_b = JSON.parse(text).message) !== null && _b !== void 0 ? _b : message;
74
+ }
75
+ catch (_c) {
76
+ // Not JSON.
77
+ }
78
+ reject(new KubernetesError(status, `${method} ${url.pathname}: ${status} ${message}`));
79
+ });
80
+ response.on('error', reject);
81
+ });
82
+ request.on('timeout', () => request.destroy(new Error(`${method} ${url.pathname}: no answer in time`)));
83
+ request.on('error', reject);
84
+ request.end(body);
85
+ });
86
+ }
87
+ }
88
+ exports.KubernetesApi = KubernetesApi;
89
+ var KubernetesUtil;
90
+ (function (KubernetesUtil) {
91
+ /** A quantity of Kubernetes (`4Gi`, `500M`, `250m`, `123456n`) as a number of its unit (bytes, CPUs). */
92
+ function quantity(value) {
93
+ if (typeof value === 'number') {
94
+ return value;
95
+ }
96
+ const match = /^([0-9.]+)([a-zA-Z]*)$/.exec(String(value !== null && value !== void 0 ? value : '').trim());
97
+ if (!match) {
98
+ return undefined;
99
+ }
100
+ const scale = {
101
+ '': 1,
102
+ n: 1e-9,
103
+ u: 1e-6,
104
+ m: 1e-3,
105
+ k: 1e3,
106
+ K: 1e3,
107
+ M: 1e6,
108
+ G: 1e9,
109
+ T: 1e12,
110
+ Ki: 2 ** 10,
111
+ Mi: 2 ** 20,
112
+ Gi: 2 ** 30,
113
+ Ti: 2 ** 40,
114
+ };
115
+ const factor = scale[match[2]];
116
+ return factor === undefined ? undefined : Number(match[1]) * factor;
117
+ }
118
+ KubernetesUtil.quantity = quantity;
119
+ })(KubernetesUtil || (exports.KubernetesUtil = KubernetesUtil = {}));
120
+ //# sourceMappingURL=kubernetes-api.js.map
@@ -0,0 +1,199 @@
1
+ import { KubernetesApi, type KubernetesCalls } from './kubernetes-api';
2
+ import { type SandboxEndpoint, type SandboxProvider, type SandboxProviderConfig, type SandboxState, type SandboxTenant, type SandboxUsage } from './sandbox-provider';
3
+ export interface KubernetesSandboxOptions {
4
+ image: string;
5
+ imagePullPolicy?: string;
6
+ namespace: string;
7
+ /** Each sandbox at most: a quantity of memory (`4Gi`), CPUs. */
8
+ memory: string;
9
+ cpus: number;
10
+ /** The volume of its home: its size, and the class of storage (the cluster's default without one). */
11
+ storage: string;
12
+ storageClass?: string;
13
+ /** gVisor, Kata: the isolation of the cluster's choice, a RuntimeClass. */
14
+ runtimeClass?: string;
15
+ /** Names of the Sandbox and its Secret: `<prefix><tenant>`. */
16
+ prefix: string;
17
+ /** More of the environment of every sandbox. */
18
+ env: Record<string, string>;
19
+ nodeSelector?: Record<string, string>;
20
+ imagePullSecrets?: string[];
21
+ /** The domain of the cluster's services, for the address of a sandbox. */
22
+ clusterDomain: string;
23
+ }
24
+ /** What the API answers of a Sandbox, as far as the provider reads it. */
25
+ interface SandboxObject {
26
+ metadata: {
27
+ name: string;
28
+ uid?: string;
29
+ annotations?: Record<string, string>;
30
+ };
31
+ spec: {
32
+ operatingMode?: 'Running' | 'Suspended';
33
+ };
34
+ status?: {
35
+ serviceFQDN?: string;
36
+ conditions?: {
37
+ type: string;
38
+ status: string;
39
+ reason?: string;
40
+ message?: string;
41
+ }[];
42
+ };
43
+ }
44
+ export declare namespace KubernetesSandboxUtil {
45
+ /** The annotation of a Sandbox and its pod that tells the environment the gateway gave it (as `cell.ta.env` of docker). */
46
+ const ENV_ANNOTATION = "cell.ta/env";
47
+ const COMPONENT = "ta-sandbox";
48
+ function options(config: SandboxProviderConfig, inCluster?: () => {
49
+ namespace: string;
50
+ }): KubernetesSandboxOptions;
51
+ /** The API: `server` and `token` (`$NAME`: of the gateway's environment) of the configuration, else the pod's own. */
52
+ function api(config: SandboxProviderConfig, env?: Record<string, string | undefined>): KubernetesApi;
53
+ function ready(sandbox: SandboxObject | undefined): boolean;
54
+ }
55
+ /**
56
+ * `kubernetes`: a Sandbox of kubernetes-sigs/agent-sandbox per tenant (docs/design/ta-deploy.md 6): a pod of ta serve,
57
+ * its home in a volume of its own that stays while it is suspended, a headless Service for a stable address. Stopping
58
+ * suspends it (the pod goes, the volume stays); its token and the environment of the gateway are in a Secret of its
59
+ * own, not in the Sandbox, which more people may read.
60
+ */
61
+ export declare class KubernetesSandbox implements SandboxProvider {
62
+ readonly id: string;
63
+ protected readonly options: KubernetesSandboxOptions;
64
+ readonly type = "kubernetes";
65
+ readonly name: string;
66
+ readonly gatewayUrl?: string;
67
+ /** A first pull of the image and a volume to bind take longer than a container. */
68
+ readonly readyTimeoutMs: number;
69
+ protected readonly api: KubernetesCalls;
70
+ constructor(id: string, config: SandboxProviderConfig, api?: KubernetesCalls, options?: KubernetesSandboxOptions);
71
+ start(tenant: SandboxTenant): Promise<SandboxEndpoint>;
72
+ stop(tenant: SandboxTenant): Promise<void>;
73
+ state(tenant: SandboxTenant): Promise<SandboxState>;
74
+ /** From metrics.k8s.io, when the cluster has metrics-server. */
75
+ usage(tenant: SandboxTenant): Promise<SandboxUsage | undefined>;
76
+ logs(tenant: SandboxTenant, lines: number): Promise<string>;
77
+ /** The Sandbox of a tenant, as the API is given it. */
78
+ manifest(tenant: SandboxTenant): {
79
+ apiVersion: string;
80
+ kind: string;
81
+ metadata: {
82
+ name: string;
83
+ labels: {
84
+ 'app.kubernetes.io/name': string;
85
+ 'app.kubernetes.io/component': string;
86
+ 'cell.ta/tenant': string;
87
+ };
88
+ annotations: {
89
+ "cell.ta/env": string;
90
+ 'cell.ta/account': string;
91
+ };
92
+ };
93
+ spec: {
94
+ operatingMode: string;
95
+ service: boolean;
96
+ failedPodPolicy: string;
97
+ podTemplate: {
98
+ metadata: {
99
+ labels: {
100
+ 'app.kubernetes.io/name': string;
101
+ 'app.kubernetes.io/component': string;
102
+ 'cell.ta/tenant': string;
103
+ };
104
+ annotations: {
105
+ "cell.ta/env": string;
106
+ };
107
+ };
108
+ spec: {
109
+ automountServiceAccountToken: boolean;
110
+ enableServiceLinks: boolean;
111
+ hostname: string;
112
+ securityContext: {
113
+ runAsUser: number;
114
+ runAsGroup: number;
115
+ fsGroup: number;
116
+ seccompProfile: {
117
+ type: string;
118
+ };
119
+ };
120
+ runtimeClassName?: string | undefined;
121
+ nodeSelector?: Record<string, string> | undefined;
122
+ imagePullSecrets?: {
123
+ name: string;
124
+ }[] | undefined;
125
+ containers: {
126
+ name: string;
127
+ image: string;
128
+ imagePullPolicy?: string | undefined;
129
+ workingDir: string;
130
+ command: string[];
131
+ envFrom: {
132
+ secretRef: {
133
+ name: string;
134
+ };
135
+ }[];
136
+ ports: {
137
+ name: string;
138
+ containerPort: number;
139
+ }[];
140
+ resources: {
141
+ limits: {
142
+ memory: string;
143
+ cpu: string;
144
+ };
145
+ requests: {
146
+ memory: string;
147
+ cpu: string;
148
+ };
149
+ };
150
+ securityContext: {
151
+ capabilities: {
152
+ drop: string[];
153
+ };
154
+ };
155
+ readinessProbe: {
156
+ httpGet: {
157
+ path: string;
158
+ port: number;
159
+ };
160
+ periodSeconds: number;
161
+ failureThreshold: number;
162
+ };
163
+ volumeMounts: {
164
+ name: string;
165
+ mountPath: string;
166
+ }[];
167
+ }[];
168
+ };
169
+ };
170
+ volumeClaimTemplates: {
171
+ metadata: {
172
+ name: string;
173
+ labels: {
174
+ 'app.kubernetes.io/name': string;
175
+ 'app.kubernetes.io/component': string;
176
+ 'cell.ta/tenant': string;
177
+ };
178
+ };
179
+ spec: {
180
+ accessModes: string[];
181
+ resources: {
182
+ requests: {
183
+ storage: string;
184
+ };
185
+ };
186
+ storageClassName?: string | undefined;
187
+ };
188
+ }[];
189
+ };
190
+ };
191
+ /** Its token and the environment of the gateway, owned by its Sandbox, which takes it along when it goes. */
192
+ protected putSecret(tenant: SandboxTenant, sandbox: SandboxObject): Promise<void>;
193
+ protected deletePod(name: string): Promise<void>;
194
+ protected read(name: string): Promise<SandboxObject | undefined>;
195
+ protected path(name?: string): string;
196
+ protected resourceName(tenant: SandboxTenant): string;
197
+ }
198
+ export {};
199
+ //# sourceMappingURL=kubernetes-sandbox.d.ts.map
@@ -0,0 +1,283 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.KubernetesSandbox = exports.KubernetesSandboxUtil = void 0;
4
+ const node_fs_1 = require("node:fs");
5
+ const docker_sandbox_1 = require("./docker-sandbox");
6
+ const kubernetes_api_1 = require("./kubernetes-api");
7
+ const sandbox_provider_1 = require("./sandbox-provider");
8
+ /** The resources of kubernetes-sigs/agent-sandbox the provider makes. */
9
+ const GROUP = '/apis/agents.x-k8s.io/v1beta1';
10
+ /** The port of ta serve in the image (its Dockerfile). */
11
+ const PORT = 4100;
12
+ var KubernetesSandboxUtil;
13
+ (function (KubernetesSandboxUtil) {
14
+ /** The annotation of a Sandbox and its pod that tells the environment the gateway gave it (as `cell.ta.env` of docker). */
15
+ KubernetesSandboxUtil.ENV_ANNOTATION = 'cell.ta/env';
16
+ KubernetesSandboxUtil.COMPONENT = 'ta-sandbox';
17
+ function options(config, inCluster) {
18
+ var _a, _b, _c, _d, _e;
19
+ const text = (key, fallback) => sandbox_provider_1.SandboxProviders.string(config, key, fallback);
20
+ const cpus = (_a = config.cpus) !== null && _a !== void 0 ? _a : 2;
21
+ if (typeof cpus !== 'number' || cpus <= 0) {
22
+ throw new sandbox_provider_1.SandboxConfigError('"cpus" of a provider of the type kubernetes is a number above 0.');
23
+ }
24
+ const memory = String((_b = config.memory) !== null && _b !== void 0 ? _b : '4Gi');
25
+ const storage = String((_c = config.storage) !== null && _c !== void 0 ? _c : '10Gi');
26
+ for (const [key, value] of [
27
+ ['memory', memory],
28
+ ['storage', storage],
29
+ ]) {
30
+ if (!kubernetes_api_1.KubernetesUtil.quantity(value)) {
31
+ throw new sandbox_provider_1.SandboxConfigError(`"${key}" of a provider of the type kubernetes is a quantity such as 4Gi.`);
32
+ }
33
+ }
34
+ const strings = (key) => {
35
+ const value = config[key];
36
+ if (value !== undefined && (!Array.isArray(value) || value.some(item => typeof item !== 'string'))) {
37
+ throw new sandbox_provider_1.SandboxConfigError(`"${key}" of a provider of the type kubernetes is a list of strings.`);
38
+ }
39
+ return value;
40
+ };
41
+ const selector = config.nodeSelector;
42
+ if (selector !== undefined &&
43
+ (typeof selector !== 'object' || Array.isArray(selector) || Object.values(selector).some(item => typeof item !== 'string'))) {
44
+ throw new sandbox_provider_1.SandboxConfigError('"nodeSelector" of a provider of the type kubernetes is an object of strings.');
45
+ }
46
+ const prefix = text('prefix', 'ta-');
47
+ if (!/^[a-z][a-z0-9-]{0,20}$/.test(prefix)) {
48
+ throw new sandbox_provider_1.SandboxConfigError('"prefix" of a provider of the type kubernetes starts with a letter: lower-case letters, digits and -.');
49
+ }
50
+ return {
51
+ image: text('image', 'ta:latest'),
52
+ imagePullPolicy: text('imagePullPolicy'),
53
+ namespace: (_e = (_d = text('namespace')) !== null && _d !== void 0 ? _d : inCluster === null || inCluster === void 0 ? void 0 : inCluster().namespace) !== null && _e !== void 0 ? _e : 'default',
54
+ memory,
55
+ cpus,
56
+ storage,
57
+ storageClass: text('storageClass'),
58
+ runtimeClass: text('runtimeClass'),
59
+ prefix,
60
+ env: sandbox_provider_1.SandboxProviders.env(config),
61
+ nodeSelector: selector,
62
+ imagePullSecrets: strings('imagePullSecrets'),
63
+ clusterDomain: text('clusterDomain', 'cluster.local'),
64
+ };
65
+ }
66
+ KubernetesSandboxUtil.options = options;
67
+ /** The API: `server` and `token` (`$NAME`: of the gateway's environment) of the configuration, else the pod's own. */
68
+ function api(config, env = process.env) {
69
+ const server = sandbox_provider_1.SandboxProviders.string(config, 'server');
70
+ if (!server) {
71
+ return new kubernetes_api_1.KubernetesApi(kubernetes_api_1.KubernetesApi.inCluster(env));
72
+ }
73
+ const given = sandbox_provider_1.SandboxProviders.string(config, 'token');
74
+ const token = (given === null || given === void 0 ? void 0 : given.startsWith('$')) ? env[given.slice(1).replace(/^\{|\}$/g, '')] : given;
75
+ const caFile = sandbox_provider_1.SandboxProviders.string(config, 'caFile');
76
+ return new kubernetes_api_1.KubernetesApi({ server, token, ...(caFile ? { ca: (0, node_fs_1.readFileSync)(caFile, 'utf8') } : {}) });
77
+ }
78
+ KubernetesSandboxUtil.api = api;
79
+ function ready(sandbox) {
80
+ var _a, _b;
81
+ var _c;
82
+ return (_c = (_b = (_a = sandbox === null || sandbox === void 0 ? void 0 : sandbox.status) === null || _a === void 0 ? void 0 : _a.conditions) === null || _b === void 0 ? void 0 : _b.some(condition => condition.type === 'Ready' && condition.status === 'True')) !== null && _c !== void 0 ? _c : false;
83
+ }
84
+ KubernetesSandboxUtil.ready = ready;
85
+ })(KubernetesSandboxUtil || (exports.KubernetesSandboxUtil = KubernetesSandboxUtil = {}));
86
+ /**
87
+ * `kubernetes`: a Sandbox of kubernetes-sigs/agent-sandbox per tenant (docs/design/ta-deploy.md 6): a pod of ta serve,
88
+ * its home in a volume of its own that stays while it is suspended, a headless Service for a stable address. Stopping
89
+ * suspends it (the pod goes, the volume stays); its token and the environment of the gateway are in a Secret of its
90
+ * own, not in the Sandbox, which more people may read.
91
+ */
92
+ class KubernetesSandbox {
93
+ constructor(id, config, api, options = KubernetesSandboxUtil.options(config, () => kubernetes_api_1.KubernetesApi.inCluster())) {
94
+ this.id = id;
95
+ this.options = options;
96
+ this.type = 'kubernetes';
97
+ /** A first pull of the image and a volume to bind take longer than a container. */
98
+ this.readyTimeoutMs = 5 * 60 * 1000;
99
+ this.name = sandbox_provider_1.SandboxProviders.string(config, 'name', 'Kubernetes');
100
+ this.gatewayUrl = sandbox_provider_1.SandboxProviders.string(config, 'gatewayUrl');
101
+ this.api = api !== null && api !== void 0 ? api : KubernetesSandboxUtil.api(config);
102
+ }
103
+ async start(tenant) {
104
+ var _a;
105
+ const name = this.resourceName(tenant);
106
+ const hash = docker_sandbox_1.DockerSandboxUtil.envHash(tenant.env);
107
+ let sandbox = await this.read(name);
108
+ if (!sandbox) {
109
+ sandbox = await this.api.call('POST', this.path(), this.manifest(tenant));
110
+ await this.putSecret(tenant, sandbox);
111
+ }
112
+ else {
113
+ await this.putSecret(tenant, sandbox);
114
+ const changed = ((_a = sandbox.metadata.annotations) === null || _a === void 0 ? void 0 : _a[KubernetesSandboxUtil.ENV_ANNOTATION]) !== hash;
115
+ if (changed || sandbox.spec.operatingMode === 'Suspended') {
116
+ // Its pod is made from the template when it starts: the one with another environment goes, the volume stays.
117
+ const { metadata, spec } = this.manifest(tenant);
118
+ await this.api.call('PATCH', this.path(name), { metadata: { annotations: metadata.annotations }, spec }, 'application/merge-patch+json');
119
+ if (changed && sandbox.spec.operatingMode !== 'Suspended') {
120
+ await this.deletePod(name);
121
+ }
122
+ }
123
+ }
124
+ return { url: `http://${name}.${this.options.namespace}.svc.${this.options.clusterDomain}:${PORT}`, token: tenant.token };
125
+ }
126
+ async stop(tenant) {
127
+ const name = this.resourceName(tenant);
128
+ if (await this.read(name)) {
129
+ await this.api.call('PATCH', this.path(name), { spec: { operatingMode: 'Suspended' } }, 'application/merge-patch+json');
130
+ }
131
+ }
132
+ async state(tenant) {
133
+ const sandbox = await this.read(this.resourceName(tenant));
134
+ return !sandbox ? 'missing' : sandbox.spec.operatingMode === 'Suspended' ? 'stopped' : 'running';
135
+ }
136
+ /** From metrics.k8s.io, when the cluster has metrics-server. */
137
+ async usage(tenant) {
138
+ var _a, _b;
139
+ const name = this.resourceName(tenant);
140
+ const metrics = await this.api
141
+ .call('GET', `/apis/metrics.k8s.io/v1beta1/namespaces/${this.options.namespace}/pods/${name}`)
142
+ .catch(() => undefined);
143
+ const usage = (_b = (_a = metrics === null || metrics === void 0 ? void 0 : metrics.containers) === null || _a === void 0 ? void 0 : _a.find(container => container.name === 'ta')) === null || _b === void 0 ? void 0 : _b.usage;
144
+ if (!usage) {
145
+ return undefined;
146
+ }
147
+ const cpu = kubernetes_api_1.KubernetesUtil.quantity(usage.cpu);
148
+ return {
149
+ cpu: cpu === undefined ? undefined : Math.round(cpu * 1000) / 10,
150
+ memory: kubernetes_api_1.KubernetesUtil.quantity(usage.memory),
151
+ memoryLimit: kubernetes_api_1.KubernetesUtil.quantity(this.options.memory),
152
+ };
153
+ }
154
+ logs(tenant, lines) {
155
+ const name = this.resourceName(tenant);
156
+ return this.api
157
+ .text(`/api/v1/namespaces/${this.options.namespace}/pods/${name}/log?container=ta&tailLines=${Math.max(1, Math.floor(lines))}`)
158
+ .catch(error => (error instanceof kubernetes_api_1.KubernetesError && error.status === 404 ? '' : Promise.reject(error)));
159
+ }
160
+ /** The Sandbox of a tenant, as the API is given it. */
161
+ manifest(tenant) {
162
+ var _a;
163
+ const name = this.resourceName(tenant);
164
+ const hash = docker_sandbox_1.DockerSandboxUtil.envHash(tenant.env);
165
+ const labels = { 'app.kubernetes.io/name': 'ta', 'app.kubernetes.io/component': KubernetesSandboxUtil.COMPONENT, 'cell.ta/tenant': tenant.id };
166
+ const options = this.options;
167
+ return {
168
+ apiVersion: 'agents.x-k8s.io/v1beta1',
169
+ kind: 'Sandbox',
170
+ metadata: { name, labels, annotations: { [KubernetesSandboxUtil.ENV_ANNOTATION]: hash, 'cell.ta/account': tenant.account } },
171
+ spec: {
172
+ operatingMode: 'Running',
173
+ service: true,
174
+ failedPodPolicy: 'Recreate',
175
+ podTemplate: {
176
+ metadata: { labels, annotations: { [KubernetesSandboxUtil.ENV_ANNOTATION]: hash } },
177
+ spec: {
178
+ // Nothing of the cluster's API in a sandbox, nor the addresses of its services.
179
+ automountServiceAccountToken: false,
180
+ enableServiceLinks: false,
181
+ // What the Ta of the tenant tells its clients its machine is.
182
+ hostname: docker_sandbox_1.DockerSandboxUtil.hostname(tenant.account),
183
+ securityContext: { runAsUser: 1000, runAsGroup: 1000, fsGroup: 1000, seccompProfile: { type: 'RuntimeDefault' } },
184
+ ...(options.runtimeClass ? { runtimeClassName: options.runtimeClass } : {}),
185
+ ...(options.nodeSelector ? { nodeSelector: options.nodeSelector } : {}),
186
+ ...(((_a = options.imagePullSecrets) === null || _a === void 0 ? void 0 : _a.length) ? { imagePullSecrets: options.imagePullSecrets.map(secret => ({ name: secret })) } : {}),
187
+ containers: [
188
+ {
189
+ name: 'ta',
190
+ image: options.image,
191
+ ...(options.imagePullPolicy ? { imagePullPolicy: options.imagePullPolicy } : {}),
192
+ // A new volume is empty: the workspace the image has is made in it, by its user (the
193
+ // runtime would make the image's WORKDIR in the volume as root).
194
+ workingDir: '/home/ta',
195
+ command: [
196
+ 'tini',
197
+ '--',
198
+ 'sh',
199
+ '-c',
200
+ `mkdir -p /home/ta/workspace && cd /home/ta/workspace && exec ta serve --host 0.0.0.0 --port ${PORT}`,
201
+ ],
202
+ envFrom: [{ secretRef: { name } }],
203
+ ports: [{ name: 'ta', containerPort: PORT }],
204
+ resources: {
205
+ limits: { memory: options.memory, cpu: String(options.cpus) },
206
+ requests: { memory: '256Mi', cpu: '100m' },
207
+ },
208
+ // A tenant is root in its sandbox (sudo), as in docker: without raw sockets it cannot forge packets.
209
+ securityContext: { capabilities: { drop: ['NET_RAW'] } },
210
+ readinessProbe: { httpGet: { path: '/', port: PORT }, periodSeconds: 5, failureThreshold: 3 },
211
+ volumeMounts: [{ name: 'home', mountPath: '/home/ta' }],
212
+ },
213
+ ],
214
+ },
215
+ },
216
+ volumeClaimTemplates: [
217
+ {
218
+ metadata: { name: 'home', labels },
219
+ spec: {
220
+ accessModes: ['ReadWriteOnce'],
221
+ resources: { requests: { storage: options.storage } },
222
+ ...(options.storageClass ? { storageClassName: options.storageClass } : {}),
223
+ },
224
+ },
225
+ ],
226
+ },
227
+ };
228
+ }
229
+ /** Its token and the environment of the gateway, owned by its Sandbox, which takes it along when it goes. */
230
+ async putSecret(tenant, sandbox) {
231
+ const name = this.resourceName(tenant);
232
+ const env = { ...this.options.env, ...tenant.env, TA_SERVE_TOKEN: tenant.token };
233
+ const secret = {
234
+ apiVersion: 'v1',
235
+ kind: 'Secret',
236
+ metadata: {
237
+ name,
238
+ labels: { 'app.kubernetes.io/name': 'ta', 'app.kubernetes.io/component': KubernetesSandboxUtil.COMPONENT, 'cell.ta/tenant': tenant.id },
239
+ ...(sandbox.metadata.uid
240
+ ? { ownerReferences: [{ apiVersion: 'agents.x-k8s.io/v1beta1', kind: 'Sandbox', name, uid: sandbox.metadata.uid }] }
241
+ : {}),
242
+ },
243
+ type: 'Opaque',
244
+ stringData: env,
245
+ };
246
+ const path = `/api/v1/namespaces/${this.options.namespace}/secrets`;
247
+ try {
248
+ await this.api.call('PUT', `${path}/${name}`, secret);
249
+ }
250
+ catch (error) {
251
+ if (!(error instanceof kubernetes_api_1.KubernetesError && error.status === 404)) {
252
+ throw error;
253
+ }
254
+ await this.api.call('POST', path, secret);
255
+ }
256
+ }
257
+ async deletePod(name) {
258
+ await this.api.call('DELETE', `/api/v1/namespaces/${this.options.namespace}/pods/${name}`).catch(error => {
259
+ if (!(error instanceof kubernetes_api_1.KubernetesError && error.status === 404)) {
260
+ throw error;
261
+ }
262
+ });
263
+ }
264
+ async read(name) {
265
+ try {
266
+ return await this.api.call('GET', this.path(name));
267
+ }
268
+ catch (error) {
269
+ if (error instanceof kubernetes_api_1.KubernetesError && error.status === 404) {
270
+ return undefined;
271
+ }
272
+ throw error;
273
+ }
274
+ }
275
+ path(name) {
276
+ return `${GROUP}/namespaces/${this.options.namespace}/sandboxes${name ? `/${name}` : ''}`;
277
+ }
278
+ resourceName(tenant) {
279
+ return `${this.options.prefix}${tenant.id}`;
280
+ }
281
+ }
282
+ exports.KubernetesSandbox = KubernetesSandbox;
283
+ //# sourceMappingURL=kubernetes-sandbox.js.map
@@ -19,6 +19,7 @@ export declare class LocalSandbox implements SandboxProvider {
19
19
  protected readonly context: SandboxContext;
20
20
  readonly type = "local";
21
21
  readonly name: string;
22
+ readonly gatewayUrl?: string;
22
23
  protected readonly running: Map<string, {
23
24
  child: ChildProcess;
24
25
  url: string;
@@ -46,6 +46,7 @@ class LocalSandbox {
46
46
  /** Kept past a stop, so that the console shows why one ended. */
47
47
  this.output = new Map();
48
48
  this.name = sandbox_provider_1.SandboxProviders.string(config, 'name', 'Local');
49
+ this.gatewayUrl = sandbox_provider_1.SandboxProviders.string(config, 'gatewayUrl');
49
50
  }
50
51
  async start(tenant) {
51
52
  var _a, _b;
@@ -62,7 +63,7 @@ class LocalSandbox {
62
63
  const [command, ...args] = this.context.taCommand;
63
64
  const child = (0, node_child_process_1.spawn)(command, [...args, 'serve', '--port', String(port)], {
64
65
  cwd,
65
- env: { ...process.env, TA_CODING_AGENT_DIR: agentDir, TA_SERVE_TOKEN: tenant.token, CELL_SERVER__HOST: '127.0.0.1' },
66
+ env: { ...process.env, ...tenant.env, TA_CODING_AGENT_DIR: agentDir, TA_SERVE_TOKEN: tenant.token, CELL_SERVER__HOST: '127.0.0.1' },
66
67
  stdio: ['ignore', 'pipe', 'pipe'],
67
68
  });
68
69
  const tail = new LineTail();