@chroxy/server 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONFIG.md +695 -0
- package/README.md +105 -0
- package/hooks/permission-hook.sh +285 -0
- package/package.json +69 -0
- package/scripts/fix-node-pty-helper.js +44 -0
- package/sidecar/Dockerfile +40 -0
- package/sidecar/PROTOCOL.md +691 -0
- package/sidecar/agent.js +1290 -0
- package/sidecar/package-lock.json +43 -0
- package/sidecar/package.json +17 -0
- package/src/activity-registry.js +491 -0
- package/src/anthropic-compatible-config.js +534 -0
- package/src/anthropic-compatible-session.js +579 -0
- package/src/anthropic-openai-shim.js +109 -0
- package/src/anthropic-openai-translate.js +377 -0
- package/src/auth-probes.js +296 -0
- package/src/background-shell-tracker.js +320 -0
- package/src/background-shells.js +125 -0
- package/src/base-session.js +1518 -0
- package/src/billing-budget.js +191 -0
- package/src/billing-canary-monitor.js +203 -0
- package/src/billing-class.js +149 -0
- package/src/bind-host.js +82 -0
- package/src/built-in-tools/bash-exec.js +167 -0
- package/src/built-in-tools/file-ops.js +198 -0
- package/src/built-in-tools/tool-transforms.js +179 -0
- package/src/builtin-commands.js +107 -0
- package/src/byok-compose-state-shared.js +31 -0
- package/src/byok-compose-state.js +234 -0
- package/src/byok-credentials.js +127 -0
- package/src/byok-event-translator.js +136 -0
- package/src/byok-mcp-client.js +404 -0
- package/src/byok-mcp-config.js +159 -0
- package/src/byok-mcp-fleet.js +214 -0
- package/src/byok-mcp-trust.js +175 -0
- package/src/byok-session.js +2019 -0
- package/src/byok-subagent-profiles.js +101 -0
- package/src/byok-tool-executor.js +813 -0
- package/src/byok-tools.js +271 -0
- package/src/channels/PACKAGING.md +181 -0
- package/src/channels/README.md +99 -0
- package/src/channels/chroxy-channel-server.js +248 -0
- package/src/checkpoint-manager.js +515 -0
- package/src/child-stream-guard.js +38 -0
- package/src/claude-channel-session.js +185 -0
- package/src/claude-model-catalog.js +266 -0
- package/src/claude-stream-parser.js +106 -0
- package/src/claude-tui/form-driver.js +874 -0
- package/src/claude-tui/pty-driver.js +520 -0
- package/src/claude-tui/tested-cli-version.js +22 -0
- package/src/claude-tui-attachments.js +342 -0
- package/src/claude-tui-session.js +4029 -0
- package/src/cli/config-cmd.js +34 -0
- package/src/cli/credentials-cmd.js +59 -0
- package/src/cli/deploy-cmd.js +167 -0
- package/src/cli/doctor-cmd.js +52 -0
- package/src/cli/identity-cmd.js +82 -0
- package/src/cli/init-cmd.js +209 -0
- package/src/cli/pages-cmd.js +167 -0
- package/src/cli/pair-code-cmd.js +108 -0
- package/src/cli/pair-discord-cmd.js +100 -0
- package/src/cli/providers-cmd.js +168 -0
- package/src/cli/server-cmd.js +94 -0
- package/src/cli/service-cmd.js +237 -0
- package/src/cli/session-cmd.js +143 -0
- package/src/cli/shared.js +194 -0
- package/src/cli/shell-cmd.js +130 -0
- package/src/cli/status-cmd.js +204 -0
- package/src/cli/tunnel-cmd.js +101 -0
- package/src/cli/update-cmd.js +45 -0
- package/src/cli/worktree-gc-cmd.js +195 -0
- package/src/cli-session.js +1820 -0
- package/src/cli.js +60 -0
- package/src/codex-app-server-client.js +156 -0
- package/src/codex-app-server-session.js +572 -0
- package/src/codex-session.js +604 -0
- package/src/config.js +1757 -0
- package/src/connection-info.js +42 -0
- package/src/connection-locality.js +55 -0
- package/src/content-blocks.js +42 -0
- package/src/control-room/byok-pool.js +130 -0
- package/src/control-room/constants.js +26 -0
- package/src/control-room/containers.js +258 -0
- package/src/control-room/emulators.js +279 -0
- package/src/control-room/handler-factory.js +142 -0
- package/src/control-room/host-prune.js +387 -0
- package/src/control-room/integrations.js +929 -0
- package/src/control-room/repo-runtime-config.js +239 -0
- package/src/control-room/repo-set.js +162 -0
- package/src/control-room/runners.js +479 -0
- package/src/control-room/simulators.js +223 -0
- package/src/control-room/skills-inventory.js +303 -0
- package/src/control-room/survey.js +685 -0
- package/src/control-room/wsl.js +182 -0
- package/src/conversation-scanner.js +270 -0
- package/src/conversation-scope.js +52 -0
- package/src/conversation-search.js +216 -0
- package/src/cost-budget-manager.js +190 -0
- package/src/credential-cipher.js +179 -0
- package/src/credential-store.js +786 -0
- package/src/credential-test.js +145 -0
- package/src/credentials-file.js +58 -0
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +111 -0
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +1 -0
- package/src/dashboard-next/dist/index.html +13 -0
- package/src/deepseek-credentials.js +58 -0
- package/src/deepseek-session.js +192 -0
- package/src/detect-thinking-keyword.js +67 -0
- package/src/dev-preview.js +227 -0
- package/src/devcontainer-config.js +269 -0
- package/src/device-preferences.js +267 -0
- package/src/diagnostics.js +187 -0
- package/src/diff-parser.js +157 -0
- package/src/discord-credentials.js +188 -0
- package/src/discord-pair-delivery.js +113 -0
- package/src/docker-byok-pool-stats.js +221 -0
- package/src/docker-byok-pool.js +841 -0
- package/src/docker-byok-session.js +2172 -0
- package/src/docker-image-allowlist.js +99 -0
- package/src/docker-sdk-session.js +396 -0
- package/src/docker-session.js +382 -0
- package/src/doctor-billing.js +179 -0
- package/src/doctor.js +667 -0
- package/src/duration.js +77 -0
- package/src/environment-manager.js +753 -0
- package/src/environment-statuses.js +20 -0
- package/src/environments/backends/docker.js +931 -0
- package/src/environments/backends/k8s.js +3030 -0
- package/src/environments/backends/rancher.js +326 -0
- package/src/environments/backends/types.js +332 -0
- package/src/event-ingest.js +546 -0
- package/src/event-normalizer.js +1083 -0
- package/src/external-session-registry.js +0 -0
- package/src/file-store.js +52 -0
- package/src/gemini-session.js +498 -0
- package/src/get-public-ip.js +52 -0
- package/src/git.js +15 -0
- package/src/github-webhook.js +256 -0
- package/src/handler-utils.js +663 -0
- package/src/handlers/checkpoint-handlers.js +202 -0
- package/src/handlers/control-room-handlers.js +1945 -0
- package/src/handlers/conversation-handlers.js +201 -0
- package/src/handlers/credential-handlers.js +247 -0
- package/src/handlers/evaluator-handlers.js +94 -0
- package/src/handlers/feature-handlers.js +332 -0
- package/src/handlers/file-handlers.js +142 -0
- package/src/handlers/ide-handlers.js +238 -0
- package/src/handlers/input-handlers.js +1048 -0
- package/src/handlers/pairing-handlers.js +94 -0
- package/src/handlers/repo-handlers.js +295 -0
- package/src/handlers/session-handlers.js +660 -0
- package/src/handlers/settings-handlers.js +818 -0
- package/src/handlers/skills-handlers.js +682 -0
- package/src/handlers/summarize-handlers.js +172 -0
- package/src/handlers/token-handlers.js +57 -0
- package/src/http-oversize.js +51 -0
- package/src/http-routes.js +1158 -0
- package/src/ide/search.js +268 -0
- package/src/ide/symbols.js +423 -0
- package/src/ip-utils.js +85 -0
- package/src/json-state-file.js +169 -0
- package/src/jsonl-reader.js +187 -0
- package/src/jsonl-subprocess-session.js +441 -0
- package/src/keychain.js +458 -0
- package/src/lan-ip.js +38 -0
- package/src/logger.js +388 -0
- package/src/mailbox-route.js +252 -0
- package/src/mcp-tools.js +46 -0
- package/src/message-transform.js +102 -0
- package/src/metrics.js +67 -0
- package/src/model-discovery.js +288 -0
- package/src/models.js +1426 -0
- package/src/notification-prefs.js +544 -0
- package/src/notifications/discord-billing-sink.js +323 -0
- package/src/notifications/discord-webhook-client.js +187 -0
- package/src/notifications/discord-webhook-sink.js +768 -0
- package/src/notifications/expo-push-sink.js +414 -0
- package/src/notifications/ready-body.js +177 -0
- package/src/notifications/sink-registry.js +98 -0
- package/src/notifications/sink.js +82 -0
- package/src/ollama-session.js +221 -0
- package/src/ollama-tags.js +238 -0
- package/src/openai-compatible-session.js +118 -0
- package/src/pages-store.js +255 -0
- package/src/pairing.js +836 -0
- package/src/path-hash-trust-ledger.js +311 -0
- package/src/per-session-settings.js +366 -0
- package/src/permission-audit.js +120 -0
- package/src/permission-hook.js +257 -0
- package/src/permission-manager.js +829 -0
- package/src/permission-resolver.js +144 -0
- package/src/platform.js +139 -0
- package/src/prompt-evaluator.js +386 -0
- package/src/providers.js +436 -0
- package/src/push.js +565 -0
- package/src/rate-limiter.js +433 -0
- package/src/redaction.js +206 -0
- package/src/sdk-session.js +1773 -0
- package/src/semver.js +92 -0
- package/src/server-cli/push-notification-handler.js +240 -0
- package/src/server-cli/server-orchestrator.js +168 -0
- package/src/server-cli/startup-display.js +146 -0
- package/src/server-cli/tunnel-lifecycle-handler.js +219 -0
- package/src/server-cli-child.js +207 -0
- package/src/server-cli.js +1223 -0
- package/src/server-identity.js +383 -0
- package/src/service.js +835 -0
- package/src/session-context.js +49 -0
- package/src/session-lock.js +60 -0
- package/src/session-manager.js +3257 -0
- package/src/session-message-history.js +511 -0
- package/src/session-preset-trust.js +78 -0
- package/src/session-preset.js +458 -0
- package/src/session-state-persistence.js +307 -0
- package/src/session-timeout-manager.js +166 -0
- package/src/session-token-store.js +83 -0
- package/src/shell-approval-info.js +45 -0
- package/src/shell-approval-store.js +163 -0
- package/src/shell-audit.js +63 -0
- package/src/skills-budget.js +181 -0
- package/src/skills-content-validator.js +106 -0
- package/src/skills-frontmatter.js +422 -0
- package/src/skills-loader.js +1893 -0
- package/src/skills-manager.js +256 -0
- package/src/skills-trust.js +532 -0
- package/src/skills-usage.js +335 -0
- package/src/snapshots-store.js +345 -0
- package/src/ssrf-guard.js +130 -0
- package/src/subagent-counter.js +149 -0
- package/src/summarize-session.js +268 -0
- package/src/supervisor.js +929 -0
- package/src/test-client.js +131 -0
- package/src/token-compare.js +28 -0
- package/src/token-manager.js +220 -0
- package/src/tool-result.js +87 -0
- package/src/transcript-tasks.js +334 -0
- package/src/tunnel/base.js +294 -0
- package/src/tunnel/cloudflare.js +281 -0
- package/src/tunnel/index.js +54 -0
- package/src/tunnel-check.js +84 -0
- package/src/turn-tracker.js +0 -0
- package/src/user-shell-registry.js +218 -0
- package/src/user-shell-session.js +411 -0
- package/src/utils/check-dependencies.js +70 -0
- package/src/utils/concurrency.js +24 -0
- package/src/utils/context-window-learn.js +148 -0
- package/src/utils/error-message.js +25 -0
- package/src/utils/format-bytes.js +35 -0
- package/src/utils/preflight.js +143 -0
- package/src/utils/resolve-binary.js +91 -0
- package/src/utils/respawn-rate-limiter.js +59 -0
- package/src/utils/sleep.js +58 -0
- package/src/utils/spawn-env.js +193 -0
- package/src/utils/validation-patterns.js +23 -0
- package/src/utils/win-spawn.js +98 -0
- package/src/version-check.js +16 -0
- package/src/web-task-manager.js +383 -0
- package/src/worktree-gc.js +418 -0
- package/src/worktree-reaper.js +168 -0
- package/src/ws-auth.js +645 -0
- package/src/ws-broadcaster.js +385 -0
- package/src/ws-client-manager.js +476 -0
- package/src/ws-client-sender.js +115 -0
- package/src/ws-file-ops/browser.js +594 -0
- package/src/ws-file-ops/common.js +163 -0
- package/src/ws-file-ops/git.js +298 -0
- package/src/ws-file-ops/index.js +52 -0
- package/src/ws-file-ops/reader.js +595 -0
- package/src/ws-forwarding.js +543 -0
- package/src/ws-handler-context.js +196 -0
- package/src/ws-history.js +1251 -0
- package/src/ws-message-handlers.js +165 -0
- package/src/ws-permissions.js +676 -0
- package/src/ws-schemas.js +119 -0
- package/src/ws-server.js +2866 -0
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
import { KubeConfig, CoreV1Api } from '@kubernetes/client-node'
|
|
2
|
+
import { K8sBackend } from './k8s.js'
|
|
3
|
+
import { createLogger } from '../../logger.js'
|
|
4
|
+
|
|
5
|
+
const log = createLogger('rancher-backend')
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Rancher cluster-ID format: `c-<short>` (legacy RKE) or `c-m-<random>` (Rancher
|
|
9
|
+
* v2 provisioned). We accept both by requiring a `c-` prefix followed by
|
|
10
|
+
* lowercase alphanumerics and hyphens. Validating up-front keeps a typo'd
|
|
11
|
+
* clusterId from being silently spliced into the proxy URL where it would
|
|
12
|
+
* surface as an opaque 404 from the Rancher server.
|
|
13
|
+
*/
|
|
14
|
+
const RANCHER_CLUSTER_ID = /^c-[a-z0-9-]+$/
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Rancher project-ID format: `p-<random>`. Used only when annotating a
|
|
18
|
+
* project-scoped namespace; never spliced into a URL.
|
|
19
|
+
*/
|
|
20
|
+
const RANCHER_PROJECT_ID = /^p-[a-z0-9-]+$/
|
|
21
|
+
|
|
22
|
+
/** Annotation Rancher reads to bind a namespace to a project. */
|
|
23
|
+
const PROJECT_ID_ANNOTATION = 'field.cattle.io/projectId'
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Builds the Rancher kube-API proxy path for a cluster.
|
|
27
|
+
*
|
|
28
|
+
* Rancher fronts each downstream cluster's Kubernetes API under
|
|
29
|
+
* `<rancherUrl>/k8s/clusters/<clusterId>`, authenticated with a Rancher bearer
|
|
30
|
+
* token. Pointing a standard `@kubernetes/client-node` client at this URL lets
|
|
31
|
+
* the entire K8sBackend operate unchanged — Rancher is purely an auth/proxy
|
|
32
|
+
* layer in front of the kube API.
|
|
33
|
+
*
|
|
34
|
+
* @param {string} rancherUrl - Rancher server base URL (trailing slash tolerated)
|
|
35
|
+
* @param {string} clusterId - Rancher downstream cluster ID (e.g. `c-m-abc123`)
|
|
36
|
+
* @returns {string} Fully-qualified proxy URL
|
|
37
|
+
*/
|
|
38
|
+
function buildProxyUrl(rancherUrl, clusterId) {
|
|
39
|
+
const base = rancherUrl.replace(/\/+$/, '')
|
|
40
|
+
return `${base}/k8s/clusters/${clusterId}`
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Validates the Rancher-specific connection options and normalises them.
|
|
45
|
+
*
|
|
46
|
+
* Enforced (all required unless noted):
|
|
47
|
+
* - rancherUrl: non-empty http(s):// URL
|
|
48
|
+
* - clusterId : matches the Rancher cluster-ID format
|
|
49
|
+
* - token : non-empty string (bearer token; never logged)
|
|
50
|
+
* - caData : optional, base64-encoded PEM bundle (string)
|
|
51
|
+
* - skipTLSVerify: optional boolean (default false)
|
|
52
|
+
*
|
|
53
|
+
* @param {Object} opts
|
|
54
|
+
* @returns {{ rancherUrl: string, clusterId: string, token: string, caData?: string, skipTLSVerify: boolean }}
|
|
55
|
+
* @throws {Error} on any malformed option
|
|
56
|
+
*/
|
|
57
|
+
function validateRancherOptions({ rancherUrl, clusterId, token, caData, skipTLSVerify } = {}) {
|
|
58
|
+
if (typeof rancherUrl !== 'string' || rancherUrl.length === 0) {
|
|
59
|
+
throw new Error('RancherBackend: rancherUrl must be a non-empty string')
|
|
60
|
+
}
|
|
61
|
+
let parsed
|
|
62
|
+
try {
|
|
63
|
+
parsed = new URL(rancherUrl)
|
|
64
|
+
} catch {
|
|
65
|
+
throw new Error(`RancherBackend: rancherUrl is not a valid URL: ${rancherUrl}`)
|
|
66
|
+
}
|
|
67
|
+
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
|
68
|
+
throw new Error(`RancherBackend: rancherUrl must use http:// or https://, got ${parsed.protocol}`)
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
if (typeof clusterId !== 'string' || !RANCHER_CLUSTER_ID.test(clusterId)) {
|
|
72
|
+
throw new Error(`RancherBackend: clusterId must match the Rancher cluster-ID format (c-...), got "${clusterId}"`)
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
if (typeof token !== 'string' || token.length === 0) {
|
|
76
|
+
throw new Error('RancherBackend: token must be a non-empty bearer token string')
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
if (caData != null && (typeof caData !== 'string' || caData.length === 0)) {
|
|
80
|
+
throw new Error('RancherBackend: caData, when provided, must be a non-empty base64-encoded PEM string')
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
if (skipTLSVerify != null && typeof skipTLSVerify !== 'boolean') {
|
|
84
|
+
throw new Error(`RancherBackend: skipTLSVerify must be a boolean, got ${typeof skipTLSVerify}`)
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
return {
|
|
88
|
+
rancherUrl,
|
|
89
|
+
clusterId,
|
|
90
|
+
token,
|
|
91
|
+
caData: caData ?? undefined,
|
|
92
|
+
skipTLSVerify: skipTLSVerify ?? false,
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Builds a CoreV1Api client pointed at the Rancher kube-API proxy.
|
|
98
|
+
*
|
|
99
|
+
* Uses `KubeConfig.loadFromClusterAndUser` so no kubeconfig file is needed:
|
|
100
|
+
* the cluster's server URL is the Rancher proxy endpoint and the user carries
|
|
101
|
+
* the Rancher bearer token. TLS verification is on by default; operators can
|
|
102
|
+
* supply a CA bundle (`caData`) for self-signed Rancher servers or, as a last
|
|
103
|
+
* resort, disable verification (`skipTLSVerify`).
|
|
104
|
+
*
|
|
105
|
+
* @param {{ rancherUrl: string, clusterId: string, token: string, caData?: string, skipTLSVerify: boolean }} cfg
|
|
106
|
+
* @returns {import('@kubernetes/client-node').CoreV1Api}
|
|
107
|
+
*/
|
|
108
|
+
function buildRancherApi(cfg) {
|
|
109
|
+
const kc = new KubeConfig()
|
|
110
|
+
const cluster = {
|
|
111
|
+
name: `rancher-${cfg.clusterId}`,
|
|
112
|
+
server: buildProxyUrl(cfg.rancherUrl, cfg.clusterId),
|
|
113
|
+
skipTLSVerify: cfg.skipTLSVerify,
|
|
114
|
+
}
|
|
115
|
+
if (cfg.caData) cluster.caData = cfg.caData
|
|
116
|
+
kc.loadFromClusterAndUser(cluster, {
|
|
117
|
+
name: `rancher-${cfg.clusterId}-user`,
|
|
118
|
+
token: cfg.token,
|
|
119
|
+
})
|
|
120
|
+
return kc.makeApiClient(CoreV1Api)
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Returns true when the supplied options carry a complete Rancher connection
|
|
125
|
+
* config (URL + clusterId + token). EnvironmentManager / config wiring uses
|
|
126
|
+
* this to decide whether to instantiate a RancherBackend at all — when Rancher
|
|
127
|
+
* is not configured, the plain K8sBackend (in-cluster / kubeconfig) path is the
|
|
128
|
+
* default and nothing about Rancher is touched.
|
|
129
|
+
*
|
|
130
|
+
* Does NOT validate shape (that is `validateRancherOptions`'s job at construct
|
|
131
|
+
* time); it only checks presence so the default path stays untouched.
|
|
132
|
+
*
|
|
133
|
+
* @param {Object} [opts]
|
|
134
|
+
* @returns {boolean}
|
|
135
|
+
*/
|
|
136
|
+
export function isRancherConfigured(opts = {}) {
|
|
137
|
+
return Boolean(opts && opts.rancherUrl && opts.clusterId && opts.token)
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Determine whether an API error means "already exists" (HTTP 409 Conflict).
|
|
142
|
+
* Mirrors `_isNotFound` in k8s.js but for the create-idempotency case.
|
|
143
|
+
*/
|
|
144
|
+
function isAlreadyExists(err) {
|
|
145
|
+
return err?.code === 409 ||
|
|
146
|
+
err?.statusCode === 409 ||
|
|
147
|
+
err?.response?.statusCode === 409 ||
|
|
148
|
+
err?.body?.code === 409 ||
|
|
149
|
+
err?.body?.reason === 'AlreadyExists'
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* RancherBackend — optional adapter that runs the full K8sBackend against a
|
|
154
|
+
* Rancher-managed cluster (#3196).
|
|
155
|
+
*
|
|
156
|
+
* Rancher is an auth/proxy layer in front of the Kubernetes API: it exposes
|
|
157
|
+
* every downstream cluster's kube API under `/k8s/clusters/<clusterId>` and
|
|
158
|
+
* authenticates with a Rancher bearer token. RancherBackend therefore reuses
|
|
159
|
+
* 100% of the K8sBackend pod/secret/exec logic and only changes how the kube
|
|
160
|
+
* client is constructed (Rancher proxy URL + bearer token + optional CA).
|
|
161
|
+
*
|
|
162
|
+
* It additionally layers Rancher's org model on top: `ensureProjectNamespace`
|
|
163
|
+
* creates a namespace bound to a Rancher Project via the
|
|
164
|
+
* `field.cattle.io/projectId` annotation, so quotas / RBAC defined at the
|
|
165
|
+
* project level apply to Chroxy's environments.
|
|
166
|
+
*
|
|
167
|
+
* Opt-in: this class is only instantiated when a Rancher connection is
|
|
168
|
+
* configured (`isRancherConfigured`). The default in-cluster / kubeconfig
|
|
169
|
+
* K8sBackend path is unchanged when Rancher is not configured.
|
|
170
|
+
*/
|
|
171
|
+
export class RancherBackend extends K8sBackend {
|
|
172
|
+
/**
|
|
173
|
+
* @param {Object} opts - All K8sBackend opts PLUS the Rancher connection block:
|
|
174
|
+
* @param {string} opts.rancherUrl - Rancher server base URL
|
|
175
|
+
* @param {string} opts.clusterId - Rancher downstream cluster ID (c-...)
|
|
176
|
+
* @param {string} opts.token - Rancher bearer token (never logged)
|
|
177
|
+
* @param {string} [opts.caData] - base64-encoded PEM CA bundle for the Rancher server
|
|
178
|
+
* @param {boolean} [opts.skipTLSVerify] - Disable TLS verification (default false; discouraged)
|
|
179
|
+
* @param {string} [opts.defaultProjectId] - Default Rancher project (p-...) for ensureProjectNamespace
|
|
180
|
+
* @param {object} [opts._coreV1Api] - Injected CoreV1Api for testing (bypasses Rancher kube-client build)
|
|
181
|
+
*/
|
|
182
|
+
constructor(opts = {}) {
|
|
183
|
+
const {
|
|
184
|
+
rancherUrl, clusterId, token, caData, skipTLSVerify, defaultProjectId,
|
|
185
|
+
_coreV1Api,
|
|
186
|
+
...k8sOpts
|
|
187
|
+
} = opts
|
|
188
|
+
|
|
189
|
+
if (_coreV1Api) {
|
|
190
|
+
// Test / pre-built-client seam: skip Rancher kube-client construction and
|
|
191
|
+
// hand the injected api straight to K8sBackend. The Rancher identity
|
|
192
|
+
// fields are optional here (so unit tests can exercise inherited pod logic
|
|
193
|
+
// without a full Rancher config), but when present they are validated to
|
|
194
|
+
// the same format rules as the live path — a malformed clusterId /
|
|
195
|
+
// defaultProjectId would otherwise be spliced verbatim into the
|
|
196
|
+
// `field.cattle.io/projectId` annotation.
|
|
197
|
+
if (clusterId != null && !RANCHER_CLUSTER_ID.test(clusterId)) {
|
|
198
|
+
throw new Error(`RancherBackend: clusterId must match the Rancher cluster-ID format (c-...), got "${clusterId}"`)
|
|
199
|
+
}
|
|
200
|
+
if (defaultProjectId != null && !RANCHER_PROJECT_ID.test(defaultProjectId)) {
|
|
201
|
+
throw new Error(`RancherBackend: defaultProjectId must match the Rancher project-ID format (p-...), got "${defaultProjectId}"`)
|
|
202
|
+
}
|
|
203
|
+
super({ ...k8sOpts, _coreV1Api })
|
|
204
|
+
this._rancher = {
|
|
205
|
+
rancherUrl,
|
|
206
|
+
clusterId,
|
|
207
|
+
defaultProjectId,
|
|
208
|
+
}
|
|
209
|
+
} else {
|
|
210
|
+
const cfg = validateRancherOptions({ rancherUrl, clusterId, token, caData, skipTLSVerify })
|
|
211
|
+
if (defaultProjectId != null && !RANCHER_PROJECT_ID.test(defaultProjectId)) {
|
|
212
|
+
throw new Error(`RancherBackend: defaultProjectId must match the Rancher project-ID format (p-...), got "${defaultProjectId}"`)
|
|
213
|
+
}
|
|
214
|
+
const api = buildRancherApi(cfg)
|
|
215
|
+
// Hand the Rancher-pointed client to K8sBackend via its injection seam so
|
|
216
|
+
// K8sBackend never constructs its own (in-cluster/kubeconfig) client.
|
|
217
|
+
super({ ...k8sOpts, _coreV1Api: api })
|
|
218
|
+
// Store only non-secret identity fields. The bearer token lives inside
|
|
219
|
+
// the kube client's auth provider and is never copied onto `this`.
|
|
220
|
+
this._rancher = {
|
|
221
|
+
rancherUrl: cfg.rancherUrl,
|
|
222
|
+
clusterId: cfg.clusterId,
|
|
223
|
+
defaultProjectId: defaultProjectId ?? undefined,
|
|
224
|
+
}
|
|
225
|
+
log.info(`RancherBackend connected to cluster ${cfg.clusterId} via ${cfg.rancherUrl} (proxy: /k8s/clusters/${cfg.clusterId})`)
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Rancher cluster ID this backend is bound to (for diagnostics / annotation).
|
|
231
|
+
* @returns {string|undefined}
|
|
232
|
+
*/
|
|
233
|
+
get clusterId() {
|
|
234
|
+
return this._rancher?.clusterId
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* Create (idempotently) a Kubernetes namespace bound to a Rancher Project.
|
|
239
|
+
*
|
|
240
|
+
* Rancher's project model is expressed on standard K8s Namespaces via the
|
|
241
|
+
* `field.cattle.io/projectId: <clusterId>:<projectId>` annotation — Rancher's
|
|
242
|
+
* controllers then apply the project's RBAC and resource quotas to the
|
|
243
|
+
* namespace. Creating the namespace through the proxied kube API (the same
|
|
244
|
+
* `_api` client every K8sBackend method uses) is all that is required; there
|
|
245
|
+
* is no separate Rancher REST call.
|
|
246
|
+
*
|
|
247
|
+
* Idempotent: a 409 Conflict (namespace already exists) is treated as success.
|
|
248
|
+
* Because the namespace already existed, we did NOT apply the project
|
|
249
|
+
* annotation in this call, so the returned `projectId` is `null` even when a
|
|
250
|
+
* binding was requested — the caller must not assume the pre-existing
|
|
251
|
+
* namespace carries the requested Rancher Project binding (it may have a
|
|
252
|
+
* different binding, or none). Verifying/patching the annotation on an
|
|
253
|
+
* existing namespace is intentionally out of scope here (see #5144).
|
|
254
|
+
*
|
|
255
|
+
* Fallback: if Rancher is not configured with a usable clusterId (e.g. the
|
|
256
|
+
* test/injected-client path) the annotation is omitted and a plain namespace
|
|
257
|
+
* is created — this is the "falls back to plain K8s" behaviour from the AC.
|
|
258
|
+
*
|
|
259
|
+
* @param {string} namespace - RFC 1123 namespace name to create
|
|
260
|
+
* @param {Object} [opts]
|
|
261
|
+
* @param {string} [opts.projectId] - Rancher project ID (p-...); defaults to defaultProjectId
|
|
262
|
+
* @returns {Promise<{ namespace: string, projectId: string|null, created: boolean }>}
|
|
263
|
+
* `projectId` reflects the binding this call actually applied: the requested
|
|
264
|
+
* project when the namespace was freshly created with the annotation, or
|
|
265
|
+
* `null` when the namespace already existed (binding unverified) or no
|
|
266
|
+
* project was requested.
|
|
267
|
+
*/
|
|
268
|
+
async ensureProjectNamespace(namespace, opts = {}) {
|
|
269
|
+
const ns = this._validateNamespace(this._resolveNamespace(namespace), 'ensureProjectNamespace')
|
|
270
|
+
const projectId = opts.projectId ?? this._rancher?.defaultProjectId ?? null
|
|
271
|
+
const clusterId = this._rancher?.clusterId
|
|
272
|
+
|
|
273
|
+
const metadata = { name: ns }
|
|
274
|
+
|
|
275
|
+
if (projectId != null) {
|
|
276
|
+
if (!RANCHER_PROJECT_ID.test(projectId)) {
|
|
277
|
+
throw new Error(`RancherBackend.ensureProjectNamespace: projectId must match the Rancher project-ID format (p-...), got "${projectId}"`)
|
|
278
|
+
}
|
|
279
|
+
if (!clusterId) {
|
|
280
|
+
// Project requested but we have no cluster ID to form the binding.
|
|
281
|
+
// Fall back to a plain namespace rather than creating a malformed
|
|
282
|
+
// annotation, and surface the degradation in the logs.
|
|
283
|
+
log.warn(`ensureProjectNamespace: projectId ${projectId} requested but no clusterId configured — creating plain namespace ${ns} without project binding`)
|
|
284
|
+
} else {
|
|
285
|
+
metadata.annotations = {
|
|
286
|
+
[PROJECT_ID_ANNOTATION]: `${clusterId}:${projectId}`,
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
const boundProjectId = metadata.annotations ? projectId : null
|
|
292
|
+
const body = { apiVersion: 'v1', kind: 'Namespace', metadata }
|
|
293
|
+
|
|
294
|
+
log.info(`Ensuring namespace ${ns}${boundProjectId ? ` bound to project ${boundProjectId}` : ''}`)
|
|
295
|
+
try {
|
|
296
|
+
await this._api.createNamespace({ body })
|
|
297
|
+
return { namespace: ns, projectId: boundProjectId, created: true }
|
|
298
|
+
} catch (err) {
|
|
299
|
+
if (isAlreadyExists(err)) {
|
|
300
|
+
// The namespace pre-existed, so this call did not apply the annotation.
|
|
301
|
+
// Report projectId:null so callers don't assume a binding we didn't make
|
|
302
|
+
// (the existing namespace may carry a different binding, or none).
|
|
303
|
+
if (boundProjectId) {
|
|
304
|
+
log.warn(`Namespace ${ns} already exists — project binding ${boundProjectId} NOT applied (pre-existing namespace; binding unverified)`)
|
|
305
|
+
} else {
|
|
306
|
+
log.info(`Namespace ${ns} already exists — treating as success`)
|
|
307
|
+
}
|
|
308
|
+
return { namespace: ns, projectId: null, created: false }
|
|
309
|
+
}
|
|
310
|
+
// Do not include err details that could echo the request body / token.
|
|
311
|
+
log.warn(`Failed to create namespace ${ns}: ${err.message}`)
|
|
312
|
+
throw err
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
// Internal helpers exported for unit testing only.
|
|
318
|
+
export const __test__ = {
|
|
319
|
+
buildProxyUrl,
|
|
320
|
+
validateRancherOptions,
|
|
321
|
+
buildRancherApi,
|
|
322
|
+
isAlreadyExists,
|
|
323
|
+
RANCHER_CLUSTER_ID,
|
|
324
|
+
RANCHER_PROJECT_ID,
|
|
325
|
+
PROJECT_ID_ANNOTATION,
|
|
326
|
+
}
|
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module environments/backends/types
|
|
3
|
+
*
|
|
4
|
+
* Defines the pluggable Backend interface for container environments.
|
|
5
|
+
*
|
|
6
|
+
* The EnvironmentManager owns lifecycle state — the in-memory map, persistence,
|
|
7
|
+
* per-environment mutexes, naming, input validation, and event emission. The
|
|
8
|
+
* Backend owns the underlying execution mechanism — Docker shellout today,
|
|
9
|
+
* Kubernetes API tomorrow (#3191+).
|
|
10
|
+
*
|
|
11
|
+
* Backends MUST NOT hold environment state of their own. Every method receives
|
|
12
|
+
* all the information it needs on each call via its arguments. State ownership
|
|
13
|
+
* stays with EnvironmentManager.
|
|
14
|
+
*
|
|
15
|
+
* "Handle" is an opaque identifier that maps to the underlying resource. For
|
|
16
|
+
* DockerBackend it is the container ID string returned by `docker run`. For
|
|
17
|
+
* compose environments it is the compose project name. The manager stores the
|
|
18
|
+
* handle inside the environment record and passes it back on every subsequent
|
|
19
|
+
* call.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* @interface Backend
|
|
24
|
+
*
|
|
25
|
+
* Contract that every backend implementation MUST satisfy. Implementations
|
|
26
|
+
* live in sibling files (e.g. docker.js) and are injected into EnvironmentManager
|
|
27
|
+
* via the `backend` constructor parameter.
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
// ─── Method contracts ──────────────────────────────────────────────────────
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Start a new standalone (non-compose) container and prepare it for use.
|
|
34
|
+
*
|
|
35
|
+
* Responsibilities:
|
|
36
|
+
* - Launch the container with the requested resource limits and mounts
|
|
37
|
+
* - Create the non-root user inside the container
|
|
38
|
+
* - Install Claude Code CLI globally
|
|
39
|
+
* - Determine the installed CLI path
|
|
40
|
+
* - Run postCreateCommand if provided
|
|
41
|
+
* - On any failure after the container starts, stop and remove the container
|
|
42
|
+
* before re-throwing so the manager never sees a partially-initialised handle
|
|
43
|
+
*
|
|
44
|
+
* @function createEnvironment
|
|
45
|
+
* @memberof Backend
|
|
46
|
+
* @param {Object} opts
|
|
47
|
+
* @param {string} opts.envId - Unique environment ID (used to name the container `chroxy-env-{envId}`)
|
|
48
|
+
* @param {string} opts.cwd - Host working directory; mounted as /workspace inside the container
|
|
49
|
+
* @param {string} opts.image - Docker image tag (already resolved to a default before this call)
|
|
50
|
+
* @param {string} opts.memoryLimit - Docker memory limit string (e.g. "2g")
|
|
51
|
+
* @param {string} opts.cpuLimit - Docker CPU limit string (e.g. "2")
|
|
52
|
+
* @param {Object} [opts.resources] - Structured K8s resource requests/limits (#3195):
|
|
53
|
+
* `{ cpu, memory, cpuLimit, memoryLimit }` (all optional K8s quantity strings; `cpu`/`memory`
|
|
54
|
+
* map to `requests`, `cpuLimit`/`memoryLimit` to `limits`). Honoured only by K8sBackend —
|
|
55
|
+
* Docker and other backends silently ignore this field. When unset, K8sBackend falls back to
|
|
56
|
+
* the legacy `opts.cpuLimit`/`opts.memoryLimit`, then to its configured defaults.
|
|
57
|
+
* @param {string} opts.containerUser - Non-root username to create inside the container
|
|
58
|
+
* @param {Object.<string,string>} [opts.containerEnv] - Extra environment variables to inject (already sanitized)
|
|
59
|
+
* @param {number[]|string[]} [opts.forwardPorts] - Ports to expose from the container
|
|
60
|
+
* @param {string[]} [opts.mounts] - Additional volume mounts (already validated)
|
|
61
|
+
* @param {string} [opts.postCreateCommand] - Shell command to run after setup completes
|
|
62
|
+
* @param {'Always'|'IfNotPresent'|'Never'} [opts.imagePullPolicy] - Container image pull policy.
|
|
63
|
+
* Honoured only by K8sBackend — Docker and other backends silently ignore this field.
|
|
64
|
+
* When absent, K8sBackend omits the field from the Pod spec and the K8s cluster default applies
|
|
65
|
+
* (typically `IfNotPresent` for tagged images, `Always` for `latest`).
|
|
66
|
+
* @param {Object} [opts.workspacePVC] - PersistentVolumeClaim-based workspace strategy for
|
|
67
|
+
* multi-node K8s clusters where `hostPath` cannot reach the operator's source tree (#3385).
|
|
68
|
+
* Honoured only by K8sBackend — Docker and other backends silently ignore this field.
|
|
69
|
+
* Mutually exclusive with `opts.cwd` on K8sBackend (passing both throws so the operator picks
|
|
70
|
+
* exactly one strategy — see `K8sBackend.validateWorkspacePVC`).
|
|
71
|
+
* @param {string} opts.workspacePVC.claimName - Name of a pre-provisioned PVC in the
|
|
72
|
+
* target namespace. Required when `workspacePVC` is set; must be a non-empty string.
|
|
73
|
+
* @param {string} [opts.workspacePVC.mountPath] - Pod-side mount path (default: `/workspace`).
|
|
74
|
+
* @param {boolean} [opts.workspacePVC.readOnly] - Mount the PVC read-only (default: false).
|
|
75
|
+
* @param {string|Object} [opts.gitRepo] - git-clone workspace strategy (#3193). Honoured only by
|
|
76
|
+
* K8sBackend — Docker and other backends silently ignore this field. A bare URL string is shorthand
|
|
77
|
+
* for `{ url }`. K8sBackend provisions an `emptyDir` workspace populated by a `git clone` init
|
|
78
|
+
* container. Mutually exclusive with `opts.cwd` and `opts.workspacePVC` (passing more than one
|
|
79
|
+
* throws — see the `validateGitRepo` helper in k8s.js). `emptyDir` is ephemeral; PVC-backed
|
|
80
|
+
* persistence for the git-clone strategy is the follow-up (#3385).
|
|
81
|
+
* @param {string} opts.gitRepo.url - Repo URL to clone (required; must not start with "-").
|
|
82
|
+
* @param {string} [opts.gitRepo.branch] - Branch/tag checked out at clone time.
|
|
83
|
+
* @param {string} [opts.gitRepo.commit] - Exact commit SHA pinned via a follow-up checkout step.
|
|
84
|
+
* @param {number} [opts.gitRepo.depth] - Positive integer for a shallow clone.
|
|
85
|
+
* @param {string} [opts.gitRepo.mountPath] - Pod-side workspace mount path (default: `/workspace`).
|
|
86
|
+
* @returns {Promise<{ containerId: string, containerCliPath: string }>}
|
|
87
|
+
* containerId — the full container ID string returned by the runtime
|
|
88
|
+
* containerCliPath — absolute path inside the container where the CLI binary was installed
|
|
89
|
+
* @throws {Error} If any step fails; the container is cleaned up before throwing
|
|
90
|
+
*/
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Start a Docker Compose stack and prepare the primary service container.
|
|
94
|
+
*
|
|
95
|
+
* Responsibilities:
|
|
96
|
+
* - Run `docker compose up -d` for the given compose file
|
|
97
|
+
* - Identify the primary container (by service name or first service)
|
|
98
|
+
* - Set up the non-root user and install Claude Code inside the primary container
|
|
99
|
+
* - Return the full list of services in the project
|
|
100
|
+
* - On any failure, run `docker compose down` before re-throwing
|
|
101
|
+
*
|
|
102
|
+
* @function createComposeEnvironment
|
|
103
|
+
* @memberof Backend
|
|
104
|
+
* @param {Object} opts
|
|
105
|
+
* @param {string} opts.envId - Unique environment ID
|
|
106
|
+
* @param {string} opts.cwd - Working directory (passed to docker compose as its cwd)
|
|
107
|
+
* @param {string} opts.composeFile - Absolute path to the docker-compose.yml file
|
|
108
|
+
* @param {string} opts.composeProject - Compose project name (e.g. "chroxy-env-{envId}")
|
|
109
|
+
* @param {string} opts.containerUser - Non-root username to create inside the primary container
|
|
110
|
+
* @param {string} [opts.primaryService] - Service name to target as the primary; uses first service if omitted
|
|
111
|
+
* @returns {Promise<{ containerId: string, containerCliPath: string, services: Array<{name: string, status: string, primary: boolean}> }>}
|
|
112
|
+
* containerId — container ID of the primary service
|
|
113
|
+
* containerCliPath — absolute path to the CLI inside the primary container
|
|
114
|
+
* services — metadata for all services in the compose project
|
|
115
|
+
* @throws {Error} If up, identification, or setup fails; compose stack is torn down before throwing
|
|
116
|
+
*/
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Destroy a standalone container environment.
|
|
120
|
+
*
|
|
121
|
+
* @function destroyEnvironment
|
|
122
|
+
* @memberof Backend
|
|
123
|
+
* @param {string} containerId - Container ID to force-remove (`docker rm -f`)
|
|
124
|
+
* @returns {Promise<void>} Resolves when the container is removed (or was already gone).
|
|
125
|
+
* Never rejects — removal failures are logged and swallowed.
|
|
126
|
+
*/
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Tear down a Docker Compose stack.
|
|
130
|
+
*
|
|
131
|
+
* @function destroyComposeEnvironment
|
|
132
|
+
* @memberof Backend
|
|
133
|
+
* @param {Object} opts
|
|
134
|
+
* @param {string} opts.composeFile - Absolute path to the docker-compose.yml
|
|
135
|
+
* @param {string} opts.composeProject - Compose project name
|
|
136
|
+
* @param {string} opts.cwd - Working directory for docker compose
|
|
137
|
+
* @returns {Promise<void>} Resolves after `docker compose down --remove-orphans`.
|
|
138
|
+
* Never rejects — failures are logged and swallowed.
|
|
139
|
+
*/
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Remove a local Docker image (e.g. a snapshot image created by commitEnvironment).
|
|
143
|
+
*
|
|
144
|
+
* @function removeImage
|
|
145
|
+
* @memberof Backend
|
|
146
|
+
* @param {string} imageTag - Image tag to remove
|
|
147
|
+
* @returns {Promise<void>} Resolves when the image is removed (or was already gone).
|
|
148
|
+
* Never rejects — removal failures are logged and swallowed.
|
|
149
|
+
*/
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Execute a shell command inside a running container.
|
|
153
|
+
*
|
|
154
|
+
* Used by EnvironmentManager for any in-container operation that goes beyond
|
|
155
|
+
* setup/install (e.g. running a one-off tool command initiated by a session).
|
|
156
|
+
* The DockerBackend implements this as `docker exec`.
|
|
157
|
+
*
|
|
158
|
+
* @function execInEnvironment
|
|
159
|
+
* @memberof Backend
|
|
160
|
+
* @param {string} containerId - Container ID
|
|
161
|
+
* @param {Object} opts
|
|
162
|
+
* @param {string} opts.cmd - Shell command to run (passed as `bash -c <cmd>`)
|
|
163
|
+
* @param {Object.<string,string>} [opts.env] - Extra environment variables for the exec process; null/undefined values are skipped
|
|
164
|
+
* @param {string} [opts.cwd] - Working directory inside the container
|
|
165
|
+
* @param {number} [opts.timeout] - Timeout in ms (default 30 000)
|
|
166
|
+
* @returns {Promise<{ stdout: string, stderr: string }>}
|
|
167
|
+
* @throws {Error} If the command exits non-zero
|
|
168
|
+
*/
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Inspect a container and return whether it is currently running.
|
|
172
|
+
*
|
|
173
|
+
* Used by reconnect() to check container health after server restart, and by
|
|
174
|
+
* restore() to validate a newly-started container before removing the old one.
|
|
175
|
+
*
|
|
176
|
+
* @function getEnvironmentStatus
|
|
177
|
+
* @memberof Backend
|
|
178
|
+
* @param {string} containerId - Container ID to inspect
|
|
179
|
+
* @returns {Promise<boolean>} true if the container exists and is in the Running state
|
|
180
|
+
* @throws {Error} If the container does not exist (lets the caller distinguish
|
|
181
|
+
* "not found" from "stopped")
|
|
182
|
+
*/
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* List all running containers whose names match the `chroxy-env-*` pattern.
|
|
186
|
+
*
|
|
187
|
+
* Used by reconcile() to detect orphaned containers that are not tracked in
|
|
188
|
+
* the environment registry.
|
|
189
|
+
*
|
|
190
|
+
* @function listEnvironments
|
|
191
|
+
* @memberof Backend
|
|
192
|
+
* @returns {Promise<string[]>} Array of short container IDs
|
|
193
|
+
* @throws {Error} If the Docker daemon is unreachable (caller must handle)
|
|
194
|
+
*/
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Commit a running container to a new local image (snapshot).
|
|
198
|
+
*
|
|
199
|
+
* This maps to `docker commit`. It does not fit neatly into the
|
|
200
|
+
* create/destroy/exec/status/list quintet because it produces a named artifact
|
|
201
|
+
* (the image tag) that lives outside the container lifecycle. It is therefore
|
|
202
|
+
* a 6th method on the interface rather than being squeezed into an existing one.
|
|
203
|
+
*
|
|
204
|
+
* @function commitEnvironment
|
|
205
|
+
* @memberof Backend
|
|
206
|
+
* @param {string} containerId - Running container to commit
|
|
207
|
+
* @param {string} imageTag - Local image tag to create (e.g. "chroxy-env:{envId}-{timestamp}")
|
|
208
|
+
* @returns {Promise<string>} The image SHA returned by `docker commit`
|
|
209
|
+
* @throws {Error} If the commit fails
|
|
210
|
+
*/
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Rename a container (used during atomic restore to free the chroxy-env-{envId} name).
|
|
214
|
+
*
|
|
215
|
+
* This is an 8th method beyond the standard 5. It is needed by the atomic
|
|
216
|
+
* restore flow: before starting the new container under the canonical name, the
|
|
217
|
+
* old container must be renamed so the name is free. It does not fit into any
|
|
218
|
+
* of the other 5 methods and is too low-level to be a composite operation.
|
|
219
|
+
* Failures are swallowed (logged only) because the rename is best-effort and
|
|
220
|
+
* the restore can proceed without it.
|
|
221
|
+
*
|
|
222
|
+
* **Docker-only concept — non-Docker backends MUST implement this as a no-op.**
|
|
223
|
+
*
|
|
224
|
+
* Docker containers have mutable, reusable names: the canonical
|
|
225
|
+
* `chroxy-env-{envId}` name must be freed before the replacement container can
|
|
226
|
+
* claim it. K8s pods are immutable and have unique names by design — there is
|
|
227
|
+
* no canonical name slot to free — so K8sBackend (and any future backend that
|
|
228
|
+
* does not rely on mutable container names) MUST resolve the returned Promise
|
|
229
|
+
* immediately without performing any I/O. The restore flow in
|
|
230
|
+
* EnvironmentManager tolerates a no-op here because the old resource is
|
|
231
|
+
* destroyed after the new container passes its health check, regardless of
|
|
232
|
+
* whether a rename occurred.
|
|
233
|
+
*
|
|
234
|
+
* Implementation guidance per backend:
|
|
235
|
+
* - **DockerBackend** — calls `docker rename <containerId> <newName>`; failures
|
|
236
|
+
* are logged and swallowed (best-effort).
|
|
237
|
+
* - **K8sBackend** — no-op; `return Promise.resolve()`. Do NOT throw
|
|
238
|
+
* `NotImplementedError` — the restore flow calls this unconditionally and a
|
|
239
|
+
* rejection will abort the restore.
|
|
240
|
+
*
|
|
241
|
+
* @function renameEnvironment
|
|
242
|
+
* @memberof Backend
|
|
243
|
+
* @param {string} containerId - Container to rename (Docker) or ignored (K8s / no-op backends)
|
|
244
|
+
* @param {string} newName - New name (Docker) or ignored (K8s / no-op backends)
|
|
245
|
+
* @returns {Promise<void>} Resolves regardless of success — rename failures are logged only;
|
|
246
|
+
* non-Docker backends resolve immediately without any I/O
|
|
247
|
+
*/
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* Start a container from a pre-configured image WITHOUT running user setup or
|
|
251
|
+
* CLI install. Used exclusively by the restore flow, where the snapshot image
|
|
252
|
+
* already has the user, CLI, and workspace baked in.
|
|
253
|
+
*
|
|
254
|
+
* This is distinct from createEnvironment (which runs full setup) because
|
|
255
|
+
* re-running setup on a pre-configured snapshot image would fail or corrupt
|
|
256
|
+
* the environment. Backends that do not support snapshotting (e.g. K8sBackend
|
|
257
|
+
* before snapshots are implemented, #3191) should throw a descriptive error.
|
|
258
|
+
*
|
|
259
|
+
* @function restoreEnvironment
|
|
260
|
+
* @memberof Backend
|
|
261
|
+
* @param {Object} opts
|
|
262
|
+
* @param {string} opts.envId - Environment ID (used to name the container `chroxy-env-{envId}`)
|
|
263
|
+
* @param {string} opts.cwd - Host working directory to mount as /workspace
|
|
264
|
+
* @param {string} opts.image - Snapshot image tag to run
|
|
265
|
+
* @param {string} opts.memoryLimit - Docker memory limit string (e.g. "2g")
|
|
266
|
+
* @param {string} opts.cpuLimit - Docker CPU limit string (e.g. "2")
|
|
267
|
+
* @returns {Promise<string>} The full container ID of the newly-started container
|
|
268
|
+
* @throws {Error} If the container fails to start
|
|
269
|
+
*/
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* Re-populate the backend's in-memory credential cache for a single environment
|
|
273
|
+
* after a server restart. This method is OPTIONAL — the Backend interface does
|
|
274
|
+
* not require it. EnvironmentManager.reconnect() checks for it via duck-typing:
|
|
275
|
+
*
|
|
276
|
+
* ```js
|
|
277
|
+
* if (typeof this._backend.reconnectAgentToken === 'function') {
|
|
278
|
+
* await this._backend.reconnectAgentToken(env.containerId)
|
|
279
|
+
* }
|
|
280
|
+
* ```
|
|
281
|
+
*
|
|
282
|
+
* Backends that hold per-environment credentials in memory (e.g. K8sBackend
|
|
283
|
+
* stores agent tokens fetched from a K8s Secret) SHOULD implement this method
|
|
284
|
+
* so that streamCliInEnvironment() continues to work after the server process
|
|
285
|
+
* restarts. Backends whose credentials are stateless or persisted to disk
|
|
286
|
+
* (e.g. DockerBackend) need not implement it.
|
|
287
|
+
*
|
|
288
|
+
* @function reconnectAgentToken
|
|
289
|
+
* @memberof Backend
|
|
290
|
+
* @param {string} handle - Opaque environment handle (container ID for Docker, Pod name for K8s)
|
|
291
|
+
* @param {Object} [opts] - Backend-specific options (e.g. {namespace} for K8sBackend)
|
|
292
|
+
* @returns {Promise<boolean>}
|
|
293
|
+
* `true` — credential was found and is now cached; the environment is usable
|
|
294
|
+
* `false` — credential source is gone (e.g. the Pod/Secret was garbage-collected);
|
|
295
|
+
* the caller should treat the environment as unreachable
|
|
296
|
+
* @throws {Error} On unexpected I/O errors (not on 404 / resource-not-found — return false instead)
|
|
297
|
+
*/
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* Spawn a long-lived CLI process inside a running environment and return a
|
|
301
|
+
* ChildProcess-shaped handle for streaming I/O.
|
|
302
|
+
*
|
|
303
|
+
* Used by session layers (e.g. DockerSdkSession, K8sSdkSession) as the
|
|
304
|
+
* `spawnClaudeCodeProcess` callback passed to the Agent SDK's `query()`.
|
|
305
|
+
* The return value must satisfy the SpawnedProcess interface that the SDK
|
|
306
|
+
* expects: readable `stdout` and `stderr` streams, a writable `stdin` stream,
|
|
307
|
+
* and an `'exit'` event emitted with `(code)` when the process terminates.
|
|
308
|
+
*
|
|
309
|
+
* Node's `ChildProcess` (returned by `child_process.spawn`) satisfies this
|
|
310
|
+
* contract natively for DockerBackend. K8sBackend returns a thin EventEmitter
|
|
311
|
+
* wrapper that bridges the sidecar WebSocket protocol to the same surface.
|
|
312
|
+
*
|
|
313
|
+
* Unlike `execInEnvironment` (which buffers output and resolves on exit),
|
|
314
|
+
* `streamCliInEnvironment` is intended for long-running interactive processes
|
|
315
|
+
* whose stdout is consumed incrementally by the SDK.
|
|
316
|
+
*
|
|
317
|
+
* @function streamCliInEnvironment
|
|
318
|
+
* @memberof Backend
|
|
319
|
+
* @param {string} handle - Environment handle (container ID for Docker, Pod name for K8s)
|
|
320
|
+
* @param {Object} opts
|
|
321
|
+
* @param {string} opts.cmd - Binary to execute (e.g. 'node')
|
|
322
|
+
* @param {string[]} [opts.args] - Argument list (default [])
|
|
323
|
+
* @param {Object.<string,string>} [opts.env] - Extra environment variables (merged on top of container env)
|
|
324
|
+
* @param {string} [opts.cwd] - Working directory inside the environment
|
|
325
|
+
* @param {AbortSignal} [opts.signal] - Abort signal; triggers SIGTERM on the child when fired
|
|
326
|
+
* @returns {object} SpawnedProcess-like handle with:
|
|
327
|
+
* - `stdout` {stream.Readable} — child process stdout
|
|
328
|
+
* - `stderr` {stream.Readable} — child process stderr
|
|
329
|
+
* - `stdin` {stream.Writable} — child process stdin
|
|
330
|
+
* - `'exit'` event `(code: number|null)` — emitted when the child exits
|
|
331
|
+
* @throws {Error} If the environment is not reachable or the spawn fails synchronously
|
|
332
|
+
*/
|