@chroxy/server 0.11.0 → 0.11.10
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 +204 -18
- package/README.md +2 -2
- package/hooks/claude-native-route-check.mjs +17 -0
- package/hooks/permission-hook.sh +166 -11
- package/package.json +16 -12
- package/sidecar/Dockerfile +1 -1
- package/sidecar/PROTOCOL.md +9 -1
- package/sidecar/agent.js +102 -10
- package/sidecar/package-lock.json +3 -3
- package/src/acp-config.js +206 -0
- package/src/acp-session.js +954 -0
- package/src/activity-registry.js +110 -5
- package/src/agent-connections.js +293 -0
- package/src/agent-control/client.js +1616 -0
- package/src/agent-control/events.js +547 -0
- package/src/agent-control/local-connection.js +275 -0
- package/src/agent-control/mcp-server.js +545 -0
- package/src/anthropic-compatible-config.js +29 -4
- package/src/anthropic-compatible-session.js +15 -6
- package/src/anthropic-openai-shim.js +0 -1
- package/src/archive-continuation.js +164 -0
- package/src/assistant-response.js +24 -0
- package/src/auth-probes.js +120 -13
- package/src/background-shell-tracker.js +27 -0
- package/src/base-session.js +1203 -36
- package/src/bearer-recheck.js +49 -0
- package/src/billing-budget.js +19 -0
- package/src/billing-class.js +40 -7
- package/src/binary-provenance-trust.js +11 -5
- package/src/bound-client-policy.js +279 -0
- package/src/built-in-tools/bash-exec.js +46 -7
- package/src/built-in-tools/file-ops.js +69 -5
- package/src/built-in-tools/tool-transforms.js +1113 -13
- package/src/byok-compose-state.js +6 -9
- package/src/byok-credentials.js +2 -3
- package/src/byok-mcp-client.js +92 -7
- package/src/byok-mcp-config.js +628 -121
- package/src/byok-mcp-fleet.js +49 -7
- package/src/byok-mcp-oauth-store.js +18 -16
- package/src/byok-mcp-trust.js +3 -3
- package/src/byok-session.js +650 -175
- package/src/byok-tool-executor.js +2662 -26
- package/src/byok-tools.js +9 -2
- package/src/channels/chroxy-channel-server.js +2 -3
- package/src/checkpoint-manager.js +64 -46
- package/src/claude-channel-session.js +16 -10
- package/src/claude-model-catalog.js +131 -16
- package/src/claude-model-refresh.js +385 -0
- package/src/claude-model-request.js +103 -0
- package/src/claude-stream-parser.js +53 -3
- package/src/claude-tui/diagnostic-tail.js +83 -0
- package/src/claude-tui/form-driver.js +44 -7
- package/src/claude-tui/model-error.js +41 -0
- package/src/claude-tui/pty-driver.js +211 -88
- package/src/claude-tui/sanitize-question-payload.js +109 -0
- package/src/claude-tui/usage-limit.js +239 -0
- package/src/claude-tui-session.js +3513 -287
- package/src/claude-tui-tool-response.js +300 -0
- package/src/cli/agent-control-cmd.js +65 -0
- package/src/cli/config-cmd.js +4 -4
- package/src/cli/config-dir-cmd.js +234 -0
- package/src/cli/deploy-cmd.js +45 -10
- package/src/cli/doctor-cmd.js +7 -3
- package/src/cli/init-cmd.js +15 -16
- package/src/cli/providers-cmd.js +3 -3
- package/src/cli/schedule-cmd.js +68 -39
- package/src/cli/server-cmd.js +48 -1
- package/src/cli/service-cmd.js +33 -10
- package/src/cli/session-cmd.js +227 -74
- package/src/cli/shared.js +162 -11
- package/src/cli/tokens-cmd.js +4 -5
- package/src/cli/tunnel-cmd.js +255 -24
- package/src/cli/worktree-gc-cmd.js +2 -2
- package/src/cli-session.js +1066 -121
- package/src/cli.js +4 -0
- package/src/codex-app-server-client.js +36 -3
- package/src/codex-app-server-session.js +1454 -79
- package/src/codex-bundled-client.js +66 -0
- package/src/codex-model-catalog.js +548 -0
- package/src/codex-model-rejections.js +87 -0
- package/src/codex-native-resume.js +104 -0
- package/src/codex-protocol-capabilities.js +188 -0
- package/src/codex-session.js +450 -27
- package/src/config-dir-migration.js +444 -0
- package/src/config-dir.js +108 -0
- package/src/config.js +286 -26
- package/src/connection-authority.js +48 -0
- package/src/connection-info.js +5 -9
- package/src/connection-locality.js +60 -0
- package/src/container-liveness-monitor.js +189 -0
- package/src/continuation-metadata-worker.js +17 -0
- package/src/continuations.js +114 -0
- package/src/control-room/host-prune.js +5 -0
- package/src/control-room/integrations.js +7 -20
- package/src/control-room/skills-inventory.js +2 -2
- package/src/conversation-scanner.js +40 -18
- package/src/conversation-scope.js +59 -39
- package/src/conversation-search.js +24 -22
- package/src/credential-store.js +23 -19
- package/src/daemon-commit.js +92 -0
- package/src/daemon-idle-state.js +171 -0
- package/src/daemon-update-status.js +314 -0
- package/src/dashboard-build.js +70 -0
- package/src/declared-status.js +90 -0
- package/src/deepseek-credentials.js +2 -3
- package/src/dev-preview.js +169 -182
- package/src/device-preferences.js +2 -2
- package/src/diff-parser.js +87 -0
- package/src/discord-credentials.js +2 -3
- package/src/docker-byok-pool.js +3 -1
- package/src/docker-byok-session.js +678 -78
- package/src/docker-image-allowlist.js +23 -1
- package/src/docker-sdk-session.js +172 -3
- package/src/docker-session.js +284 -10
- package/src/doctor.js +767 -61
- package/src/edited-input.js +264 -0
- package/src/environment-manager.js +175 -36
- package/src/environments/authority.js +95 -0
- package/src/environments/backends/container-claude-spawn.js +94 -0
- package/src/environments/backends/docker.js +31 -10
- package/src/environments/backends/k8s.js +49 -24
- package/src/environments/destroy-with-sessions.js +142 -0
- package/src/event-ingest.js +118 -13
- package/src/event-normalizer.js +151 -233
- package/src/gemini-session.js +81 -5
- package/src/handler-utils.js +535 -68
- package/src/handlers/checkpoint-handlers.js +39 -4
- package/src/handlers/control-room-handlers.js +51 -11
- package/src/handlers/conversation-handlers.js +469 -56
- package/src/handlers/daemon-update-handlers.js +81 -0
- package/src/handlers/evaluator-handlers.js +14 -1
- package/src/handlers/feature-handlers.js +186 -69
- package/src/handlers/file-handlers.js +57 -13
- package/src/handlers/input-handlers.js +685 -48
- package/src/handlers/orchestration-handlers.js +3 -3
- package/src/handlers/scheduler-handlers.js +88 -14
- package/src/handlers/session-handlers.js +542 -20
- package/src/handlers/session-pr-status-handlers.js +283 -0
- package/src/handlers/session-pr-threads-handlers.js +247 -0
- package/src/handlers/settings-handlers.js +330 -42
- package/src/handlers/skills-handlers.js +13 -4
- package/src/handlers/summarize-handlers.js +32 -1
- package/src/handlers/survey-throttle.js +380 -0
- package/src/health-proof.js +40 -0
- package/src/history-page.js +104 -0
- package/src/http-routes.js +127 -8
- package/src/ide/search.js +24 -6
- package/src/ide/symbols.js +20 -6
- package/src/input-context.js +117 -0
- package/src/instruction-policy-compiler.js +229 -0
- package/src/instruction-policy.js +250 -0
- package/src/jsonl-reader.js +289 -82
- package/src/jsonl-subprocess-session.js +92 -8
- package/src/keychain.js +1 -1
- package/src/logger.js +63 -17
- package/src/mailbox-route.js +11 -22
- package/src/message-wire.js +386 -0
- package/src/model-discovery.js +43 -3
- package/src/models.js +1276 -174
- package/src/notification-prefs.js +12 -4
- package/src/notifications/discord-billing-sink.js +22 -5
- package/src/notifications/discord-ci-sink.js +243 -0
- package/src/notifications/discord-webhook-client.js +71 -0
- package/src/notifications/discord-webhook-sink.js +64 -23
- package/src/notifications/expo-push-sink.js +85 -6
- package/src/notifications/ready-body.js +16 -5
- package/src/ollama-session.js +34 -2
- package/src/orchestration/build-manager.js +9 -2
- package/src/orchestration/git-ops.js +41 -7
- package/src/orchestration/orchestration-manager.js +80 -33
- package/src/orchestration/permission-gate.js +13 -1
- package/src/orchestration/run-model.js +2 -1
- package/src/orchestration/turn-driver.js +44 -20
- package/src/orphan-reaper.js +413 -0
- package/src/outgoing-policy.js +183 -0
- package/src/pairing.js +92 -13
- package/src/path-hash-trust-ledger.js +642 -25
- package/src/permission-deadlines.js +82 -0
- package/src/permission-floor.js +1357 -42
- package/src/permission-hook.js +180 -69
- package/src/permission-manager.js +712 -83
- package/src/permission-mode-support.js +35 -0
- package/src/permission-resolver.js +122 -8
- package/src/permission-scope.js +43 -0
- package/src/platform.js +159 -43
- package/src/preview-ingress.js +54 -0
- package/src/preview-target.js +213 -0
- package/src/prompt-evaluator.js +34 -4
- package/src/provider-customization.js +180 -0
- package/src/providers.js +207 -4
- package/src/push.js +30 -4
- package/src/question-route-map.js +130 -0
- package/src/redaction.js +360 -8
- package/src/roster-broadcast.js +186 -0
- package/src/scheduled-task-store.js +318 -26
- package/src/scheduler.js +73 -3
- package/src/sdk-session.js +2060 -187
- package/src/server-cli/preview-shutdown.js +22 -0
- package/src/server-cli/push-notification-handler.js +11 -2
- package/src/server-cli/server-orchestrator.js +28 -5
- package/src/server-cli-child.js +33 -18
- package/src/server-cli.js +524 -38
- package/src/server-identity.js +15 -11
- package/src/service.js +396 -25
- package/src/session-archive-limits.js +15 -0
- package/src/session-archive.js +1029 -0
- package/src/session-busy-state.js +72 -0
- package/src/session-ci-watcher.js +926 -0
- package/src/session-context.js +7 -2
- package/src/session-manager.js +3491 -312
- package/src/session-message-history.js +722 -16
- package/src/session-pr-status.js +654 -0
- package/src/session-pr-threads.js +271 -0
- package/src/session-preset-trust.js +3 -3
- package/src/session-preset.js +10 -5
- package/src/session-state-persistence.js +94 -17
- package/src/session-timeout-manager.js +20 -0
- package/src/session-token-store.js +17 -8
- package/src/session-wake.js +240 -0
- package/src/shell-approval-info.js +2 -2
- package/src/shell-approval-store.js +3 -1
- package/src/skills-loader.js +7 -4
- package/src/skills-manager.js +2 -2
- package/src/skills-trust.js +95 -13
- package/src/skills-usage.js +2 -3
- package/src/snapshots-store.js +2 -3
- package/src/statusline.js +23 -11
- package/src/summarize-session.js +51 -4
- package/src/supervisor.js +22 -11
- package/src/sweep-stale-provider-dirs.js +95 -0
- package/src/thinking-level-wire.js +39 -0
- package/src/thinking-stream.js +179 -0
- package/src/tool-result.js +61 -0
- package/src/transcript-sources.js +109 -0
- package/src/transcript-tasks.js +372 -25
- package/src/trusted-file-read.js +302 -0
- package/src/tunnel/base.js +0 -8
- package/src/tunnel/cloudflare.js +34 -31
- package/src/tunnel/index.js +9 -0
- package/src/tunnel/preview.js +64 -0
- package/src/turn-outcome.js +137 -0
- package/src/usage-normalize.js +9 -5
- package/src/user-shell-session.js +59 -5
- package/src/utils/agent-sdk-version.js +107 -0
- package/src/utils/argv-safety.js +741 -0
- package/src/utils/auth-cause.js +60 -0
- package/src/utils/binary-package-manifest.js +597 -0
- package/src/utils/binary-version.js +224 -0
- package/src/utils/bounded-regex-worker.js +25 -0
- package/src/utils/bounded-regex.js +153 -0
- package/src/utils/claude-binary.js +43 -0
- package/src/utils/claude-config-dir.js +245 -0
- package/src/utils/claude-login-command.js +16 -0
- package/src/utils/claude-native-route.js +81 -0
- package/src/utils/componentwise-resolver.js +133 -37
- package/src/utils/deploy-control-files.js +87 -0
- package/src/utils/exec-failure-reason.js +21 -0
- package/src/utils/git-repo.js +42 -0
- package/src/utils/is-entry-point.js +137 -0
- package/src/utils/node-pty-probe.js +95 -0
- package/src/utils/node-pty-support.js +118 -0
- package/src/utils/opened-file-path.js +167 -0
- package/src/utils/path-containment.js +165 -0
- package/src/utils/permission-mode-sidecar.js +51 -0
- package/src/utils/preflight.js +360 -16
- package/src/utils/read-limiter.js +217 -0
- package/src/utils/regular-file.js +375 -0
- package/src/utils/safe-regex.js +113 -0
- package/src/utils/small-file.js +129 -0
- package/src/utils/spawn-env.js +189 -4
- package/src/utils/stale-session-dirs.js +182 -0
- package/src/utils/stat-identity.js +43 -0
- package/src/utils/verify-provenance.js +406 -13
- package/src/web-task-manager.js +256 -16
- package/src/worktree-gc.js +7 -2
- package/src/ws-auth.js +69 -21
- package/src/ws-broadcaster.js +14 -2
- package/src/ws-client-manager.js +16 -1
- package/src/ws-client-sender.js +7 -0
- package/src/ws-file-ops/browser.js +331 -58
- package/src/ws-file-ops/common.js +320 -14
- package/src/ws-file-ops/git.js +395 -42
- package/src/ws-file-ops/index.js +2 -0
- package/src/ws-file-ops/memory.js +137 -35
- package/src/ws-file-ops/open-nofollow.js +354 -0
- package/src/ws-file-ops/reader.js +571 -113
- package/src/ws-forwarding.js +329 -39
- package/src/ws-handler-context.js +70 -2
- package/src/ws-history.js +940 -172
- package/src/ws-message-handlers.js +17 -1
- package/src/ws-permissions.js +307 -37
- package/src/ws-schemas.js +5 -0
- package/src/ws-server.js +643 -96
- package/sidecar/node_modules/.package-lock.json +0 -29
- package/sidecar/node_modules/ws/LICENSE +0 -20
- package/sidecar/node_modules/ws/README.md +0 -548
- package/sidecar/node_modules/ws/browser.js +0 -8
- package/sidecar/node_modules/ws/index.js +0 -22
- package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
- package/sidecar/node_modules/ws/lib/constants.js +0 -19
- package/sidecar/node_modules/ws/lib/event-target.js +0 -292
- package/sidecar/node_modules/ws/lib/extension.js +0 -203
- package/sidecar/node_modules/ws/lib/limiter.js +0 -55
- package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
- package/sidecar/node_modules/ws/lib/receiver.js +0 -706
- package/sidecar/node_modules/ws/lib/sender.js +0 -602
- package/sidecar/node_modules/ws/lib/stream.js +0 -161
- package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
- package/sidecar/node_modules/ws/lib/validation.js +0 -152
- package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
- package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
- package/sidecar/node_modules/ws/package.json +0 -70
- package/sidecar/node_modules/ws/wrapper.mjs +0 -21
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
- package/src/dashboard-next/dist/index.html +0 -13
- package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* #7596 — environment-surface authority for pairing-bound (share-a-session)
|
|
3
|
+
* clients.
|
|
4
|
+
*
|
|
5
|
+
* The container-environment surface is host-level: an environment outlives any
|
|
6
|
+
* one session and its descriptor carries host metadata (the `sessions` roster
|
|
7
|
+
* wired #7552, plus `cwd` = an absolute host path, `image`, `containerId`,
|
|
8
|
+
* `containerUser`, `containerCliPath`). docs/security/bearer-token-authority.md's
|
|
9
|
+
* rule is that a bound token learns NOTHING host-level: every Control Room host
|
|
10
|
+
* survey (containers, repo-runtime, byok-pool, …) and `destroy_environment`
|
|
11
|
+
* (#7571) already REFUSE bound clients rather than hand them a partial view.
|
|
12
|
+
*
|
|
13
|
+
* #7576 briefly redacted just the `sessions` roster for bound clients on the
|
|
14
|
+
* theory they might need the env ids for a picker; #7596 retired that — a bound
|
|
15
|
+
* client cannot `create_session` (that handler refuses bound tokens), so it has
|
|
16
|
+
* no picker, and the sessions-only redaction still leaked the host metadata
|
|
17
|
+
* above. So bound clients are REFUSED `list_environments` / `get_environment`
|
|
18
|
+
* and are excluded from the `environment_list` broadcasts entirely, matching the
|
|
19
|
+
* rest of the host surface.
|
|
20
|
+
*
|
|
21
|
+
* WHO IS "BOUND" — fail SAFE. A client is treated as bound unless it is
|
|
22
|
+
* DEFINITELY an unbound host client: a real client object whose `boundSessionId`
|
|
23
|
+
* is null/undefined. This matches the server's canonical `boundSessionId == null`
|
|
24
|
+
* bound-check (ws-server.js, #4787), which deliberately treats the unlikely
|
|
25
|
+
* empty-string id as bound — a truthy `client.boundSessionId` check would
|
|
26
|
+
* misclassify `''` as unbound and leak the surface (Copilot, #7595 review). It
|
|
27
|
+
* also fails CLOSED on a nullish client, the safe direction for a security check,
|
|
28
|
+
* even though WS dispatch guarantees an authenticated client here.
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Fail-safe bound check: everything that is not provably an unbound host client
|
|
33
|
+
* is treated as bound. `boundSessionId == null` is true only for null/undefined,
|
|
34
|
+
* so `''` and any real id are bound; a nullish client is bound too.
|
|
35
|
+
*/
|
|
36
|
+
export function isBoundClient(client) {
|
|
37
|
+
return !client || client.boundSessionId != null
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* True when `client` is session-bound (fail-safe, see `isBoundClient`) to a
|
|
42
|
+
* session other than `sessionId`: such a client receives no data for
|
|
43
|
+
* `sessionId` — no frame tagged with it and no subscription to it. This is the
|
|
44
|
+
* ONE predicate behind the broadcaster's delivery paths and the client
|
|
45
|
+
* manager's subscription index; a client bound to `sessionId` itself, and an
|
|
46
|
+
* unbound client, are never "bound to another session".
|
|
47
|
+
*/
|
|
48
|
+
export function isBoundToOtherSession(client, sessionId) {
|
|
49
|
+
return client.boundSessionId != null && client.boundSessionId !== sessionId
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* May `recipient` be told that `peer` is connected? An unscoped recipient may
|
|
54
|
+
* hear about every peer. A session-scoped one only about peers on its OWN
|
|
55
|
+
* session (the same binding): the other connections' names and platforms are not
|
|
56
|
+
* part of its session. Fail-safe like `isBoundClient`: an empty or non-string
|
|
57
|
+
* binding on the recipient is a binding, and matches no unscoped peer.
|
|
58
|
+
*/
|
|
59
|
+
export function canSeePeer(recipient, peer) {
|
|
60
|
+
if (!isBoundClient(recipient)) return true
|
|
61
|
+
const own = recipient?.boundSessionId
|
|
62
|
+
return typeof own === 'string' && own.length > 0 && peer?.boundSessionId === own
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Fan an `environment_list` out to UNBOUND (host-authority) clients only. The
|
|
67
|
+
* `environment_list` payload carries the whole descriptor (host metadata + the
|
|
68
|
+
* #7552 sessions roster), so a bound client must not receive it — not on a pull
|
|
69
|
+
* (list/get refuse) and not on a push. The #7552 sessions-changed re-broadcast
|
|
70
|
+
* fires on every session open/close, so a plain broadcast would stream the
|
|
71
|
+
* surface to every bound listener continuously.
|
|
72
|
+
*
|
|
73
|
+
* @param {(msg: object, filter: (client: object) => boolean) => void} broadcast
|
|
74
|
+
* a FILTERED broadcast fn (`ctx.transport.broadcast` / `WsServer._broadcast`).
|
|
75
|
+
* @param {object[]} environments full descriptors (EnvironmentManager.list()).
|
|
76
|
+
*/
|
|
77
|
+
export function broadcastEnvironmentList(broadcast, environments) {
|
|
78
|
+
broadcast({ type: 'environment_list', environments }, (client) => !isBoundClient(client))
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* A transcript replay frame names a CONVERSATION in its `sessionId` field (there
|
|
83
|
+
* is no live session behind a closed conversation), so the "tagged with another
|
|
84
|
+
* session" delivery rule must not read it as a session id. The handler that
|
|
85
|
+
* produced it, after authorising the conversation, marks the frame with this
|
|
86
|
+
* symbol (not serialised, not settable from the wire) and the delivery check
|
|
87
|
+
* skips the tag test for it.
|
|
88
|
+
*/
|
|
89
|
+
export const CONVERSATION_FRAME = Symbol('conversation-frame')
|
|
90
|
+
|
|
91
|
+
/** @template T @param {T} frame @returns {T} */
|
|
92
|
+
export function markConversationFrame(frame) {
|
|
93
|
+
Object.defineProperty(frame, CONVERSATION_FRAME, { value: true, enumerable: false })
|
|
94
|
+
return frame
|
|
95
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { normalize } from 'path'
|
|
2
|
+
|
|
3
|
+
const JS_CLI_RE = /\.(?:c|m)?js$/i
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Is `p` the path of a claude executable (native binary), judged by its
|
|
7
|
+
* basename on either path flavour? The SDK's own platform binary is named
|
|
8
|
+
* `claude` (`claude.exe` on Windows), and so is the `claude` we pin through
|
|
9
|
+
* `pathToClaudeCodeExecutable` (#7986).
|
|
10
|
+
*/
|
|
11
|
+
function isNativeClaudeCommand(p) {
|
|
12
|
+
if (typeof p !== 'string' || p.length === 0) return false
|
|
13
|
+
const base = p.split(/[\\/]/).pop()
|
|
14
|
+
return base === 'claude' || base === 'claude.exe'
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const CLAUDE_CLI_JS_SUFFIX = '@anthropic-ai/claude-code/cli.js'
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Is `p` the claude-code cli.js? Separators are normalised first so a Windows
|
|
21
|
+
* host path matches, and the path must END with the package's cli.js (a mere
|
|
22
|
+
* substring elsewhere in an argument does not count), or equal the pinned path.
|
|
23
|
+
*/
|
|
24
|
+
function isClaudeJsScript(p, pinned) {
|
|
25
|
+
if (typeof p !== 'string' || p.length === 0) return false
|
|
26
|
+
if (isPinnedPath(p, pinned)) return true
|
|
27
|
+
const norm = p.replace(/\\/g, '/')
|
|
28
|
+
return norm === CLAUDE_CLI_JS_SUFFIX || norm.endsWith('/' + CLAUDE_CLI_JS_SUFFIX)
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function isPinnedPath(cmd, pinned) {
|
|
32
|
+
if (typeof cmd !== 'string' || cmd.length === 0) return false
|
|
33
|
+
if (typeof pinned !== 'string' || pinned.length === 0) return false
|
|
34
|
+
return normalize(cmd) === normalize(pinned)
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Map the SDK's spawn request for the claude CLI onto what the container can
|
|
39
|
+
* exec (#8027). The SDK hands `spawnClaudeCodeProcess({ command, args })` HOST
|
|
40
|
+
* paths, in one of two shapes:
|
|
41
|
+
*
|
|
42
|
+
* - JS cli (old): `command` = `node`, `args[0]` = `<host>/@anthropic-ai/claude-code/cli.js`
|
|
43
|
+
* - native: `command` = absolute host path to a `claude` binary (a darwin
|
|
44
|
+
* Mach-O on a Mac, which a Linux container cannot exec), `args[0]` = a flag
|
|
45
|
+
*
|
|
46
|
+
* Both must run the container's own claude (`containerCliPath`), keeping every
|
|
47
|
+
* other arg. The claude spawn is identified positively (the native shape by the
|
|
48
|
+
* basename of `command`; the JS shape by `args[0]` naming the claude-code
|
|
49
|
+
* cli.js), so any other command passes through untouched. The result does not
|
|
50
|
+
* depend on how the host path is shaped, which is the point.
|
|
51
|
+
*
|
|
52
|
+
* A `containerCliPath` ending in .js/.mjs/.cjs is the npm-installed cli.js and
|
|
53
|
+
* is run via `node`; any other path is itself the container's claude executable.
|
|
54
|
+
*
|
|
55
|
+
* `hostClaudePath` is the pinned host executable the caller gave the SDK as
|
|
56
|
+
* `pathToClaudeCodeExecutable`; a `cmd` equal to it (after normalisation) is the
|
|
57
|
+
* claude spawn whatever its basename (`claude.cmd`, a versioned file, ...).
|
|
58
|
+
*
|
|
59
|
+
* @param {{ cmd: string, args?: string[], containerCliPath: string, hostClaudePath?: string }} spec
|
|
60
|
+
* @returns {{ cmd: string, args: string[], remapped: boolean }}
|
|
61
|
+
*/
|
|
62
|
+
export function remapClaudeSpawn({ cmd, args = [], containerCliPath, hostClaudePath }) {
|
|
63
|
+
const viaNode = JS_CLI_RE.test(containerCliPath)
|
|
64
|
+
|
|
65
|
+
if (isNativeClaudeCommand(cmd) || isPinnedPath(cmd, hostClaudePath)) {
|
|
66
|
+
return viaNode
|
|
67
|
+
? { cmd: 'node', args: [containerCliPath, ...args], remapped: true }
|
|
68
|
+
: { cmd: containerCliPath, args: [...args], remapped: true }
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
if (isClaudeJsScript(args[0], hostClaudePath)) {
|
|
72
|
+
// JS shape (`node|bun <host cli.js> ...`): drop the host runtime and script
|
|
73
|
+
// and run the container's claude, via node when it is a JS file.
|
|
74
|
+
return viaNode
|
|
75
|
+
? { cmd: 'node', args: [containerCliPath, ...args.slice(1)], remapped: true }
|
|
76
|
+
: { cmd: containerCliPath, args: args.slice(1), remapped: true }
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
return { cmd, args: [...args], remapped: false }
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Claude resolves its config directory from `CLAUDE_CONFIG_DIR` when the container
|
|
84
|
+
* image or pod defines it, which can put it somewhere the permission floor does not
|
|
85
|
+
* recognise. A claude spawn in a container therefore runs with the variable unset,
|
|
86
|
+
* so claude uses its own `<HOME>/.claude` (recognised by name) and its credentials
|
|
87
|
+
* and global config stay where they are. One definition for every container path.
|
|
88
|
+
*/
|
|
89
|
+
export const CONTAINER_UNSET_ENV = Object.freeze(['CLAUDE_CONFIG_DIR'])
|
|
90
|
+
|
|
91
|
+
/** The argv prefix that runs a command with {@link CONTAINER_UNSET_ENV} unset (`env -u VAR ...`). */
|
|
92
|
+
export function containerUnsetEnvPrefix() {
|
|
93
|
+
return ['env', ...CONTAINER_UNSET_ENV.flatMap((name) => ['-u', name])]
|
|
94
|
+
}
|
|
@@ -2,6 +2,8 @@ import { execFile, spawn } from 'child_process'
|
|
|
2
2
|
import { createLogger } from '../../logger.js'
|
|
3
3
|
import { VALID_USERNAME_RE } from '../../utils/validation-patterns.js'
|
|
4
4
|
import { getChroxyHostEnv } from '../../chroxy-host-metadata.js'
|
|
5
|
+
import { remapClaudeSpawn } from './container-claude-spawn.js'
|
|
6
|
+
import { containerUnsetEnvPrefix } from './container-claude-spawn.js'
|
|
5
7
|
|
|
6
8
|
const log = createLogger('docker-backend')
|
|
7
9
|
|
|
@@ -485,6 +487,7 @@ export class DockerBackend {
|
|
|
485
487
|
* @param {string} [opts.containerUser] - Non-root user inside the container (default: 'chroxy')
|
|
486
488
|
* @param {string} [opts.containerCliPath] - Container path to claude-code CLI (default fallback)
|
|
487
489
|
* @param {string} [opts.hostCwd] - Host CWD mount root (default: opts.cwd)
|
|
490
|
+
* @param {string} [opts.hostClaudePath] - Pinned host claude executable handed to the SDK; a `cmd` equal to it is the claude spawn
|
|
488
491
|
* @returns {import('child_process').ChildProcess}
|
|
489
492
|
*/
|
|
490
493
|
streamCliInEnvironment(containerId, opts = {}) {
|
|
@@ -493,6 +496,7 @@ export class DockerBackend {
|
|
|
493
496
|
containerUser = 'chroxy',
|
|
494
497
|
containerCliPath = DEFAULT_CONTAINER_CLI_PATH,
|
|
495
498
|
hostCwd,
|
|
499
|
+
hostClaudePath,
|
|
496
500
|
} = opts
|
|
497
501
|
|
|
498
502
|
const dockerArgs = ['exec', '-i', '-u', containerUser]
|
|
@@ -528,18 +532,19 @@ export class DockerBackend {
|
|
|
528
532
|
dockerArgs.push('--env', `HOME=/home/${containerUser}`)
|
|
529
533
|
dockerArgs.push('--env', 'PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin')
|
|
530
534
|
|
|
531
|
-
// Remap
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
containerArgs[0]
|
|
535
|
+
// Remap the SDK's host-path claude spawn (JS cli.js or native binary) to the
|
|
536
|
+
// container's claude (#8027).
|
|
537
|
+
const remap = remapClaudeSpawn({ cmd, args, containerCliPath, hostClaudePath })
|
|
538
|
+
const containerCmd = remap.cmd
|
|
539
|
+
const containerArgs = remap.args
|
|
540
|
+
if (remap.remapped) {
|
|
541
|
+
log.info(`Remapped claude spawn: ${cmd} ${args[0] ?? ''} -> ${containerCmd} ${containerArgs[0] ?? ''}`)
|
|
538
542
|
}
|
|
539
543
|
|
|
540
|
-
|
|
544
|
+
// A claude spawn runs with CLAUDE_CONFIG_DIR unset (see container-claude-spawn.js).
|
|
545
|
+
dockerArgs.push(containerId, ...(remap.remapped ? containerUnsetEnvPrefix() : []), containerCmd, ...containerArgs)
|
|
541
546
|
|
|
542
|
-
log.info(`docker exec stream: ${containerId.slice(0, 12)} ${
|
|
547
|
+
log.info(`docker exec stream: ${containerId.slice(0, 12)} ${containerCmd} ${containerArgs.slice(0, 2).join(' ')}`)
|
|
543
548
|
|
|
544
549
|
const child = (this._spawn || spawn)('docker', dockerArgs, {
|
|
545
550
|
stdio: ['pipe', 'pipe', 'pipe'],
|
|
@@ -665,7 +670,23 @@ export class DockerBackend {
|
|
|
665
670
|
runArgs.push('--add-host', 'host.docker.internal:host-gateway')
|
|
666
671
|
}
|
|
667
672
|
|
|
668
|
-
|
|
673
|
+
// #7296 — `image` reaches here from the wire (`create_environment`), and
|
|
674
|
+
// a bare positional is option-parsed by `docker run`. The allowlist
|
|
675
|
+
// refuses a dash-leading reference; this terminates option parsing so
|
|
676
|
+
// the refusal is not the only thing standing between a flag and the
|
|
677
|
+
// daemon. Measured on Docker 29.7.2: `docker run -- --help sleep
|
|
678
|
+
// infinity` does NOT print help (the `--` is consumed and `--help`
|
|
679
|
+
// becomes the image), while the same argv without `--` does.
|
|
680
|
+
//
|
|
681
|
+
// What the separator needs from the argv above it is narrow and worth
|
|
682
|
+
// stating exactly: every FLAG NAME there is a chroxy literal, so no
|
|
683
|
+
// earlier token is a bare `--` that would terminate option parsing
|
|
684
|
+
// ahead of this one. The flag VALUES are not all chroxy's own
|
|
685
|
+
// (memoryLimit/cpuLimit arrive from the wire; containerEnv, mounts and
|
|
686
|
+
// forwardPorts from devcontainer.json) — but each sits in a slot pflag
|
|
687
|
+
// consumes as the preceding flag's argument, so it is a bad-value error
|
|
688
|
+
// there, never a new option.
|
|
689
|
+
runArgs.push('--', image, 'sleep', 'infinity')
|
|
669
690
|
|
|
670
691
|
this._execFile('docker', runArgs, { encoding: 'utf-8', timeout: 120_000 }, (err, stdout, stderr) => {
|
|
671
692
|
if (err) {
|
|
@@ -5,6 +5,8 @@ import { KubeConfig, CoreV1Api, PortForward } from '@kubernetes/client-node'
|
|
|
5
5
|
import WebSocket from 'ws'
|
|
6
6
|
import { createLogger } from '../../logger.js'
|
|
7
7
|
import { getChroxyHostEnv } from '../../chroxy-host-metadata.js'
|
|
8
|
+
import { assertSafeArgvValue } from '../../utils/argv-safety.js'
|
|
9
|
+
import { remapClaudeSpawn, CONTAINER_UNSET_ENV, containerUnsetEnvPrefix } from './container-claude-spawn.js'
|
|
8
10
|
|
|
9
11
|
const log = createLogger('k8s-backend')
|
|
10
12
|
|
|
@@ -305,26 +307,35 @@ const DEFAULT_WORKSPACE_MOUNT_PATH = '/workspace'
|
|
|
305
307
|
|
|
306
308
|
/**
|
|
307
309
|
* Reject argv values that git would interpret as an option rather than a
|
|
308
|
-
* positional argument (argument-injection hardening, #3193)
|
|
310
|
+
* positional argument (argument-injection hardening, #3193) — routed through
|
|
311
|
+
* the shared guard in `utils/argv-safety.js` (#7869).
|
|
312
|
+
*
|
|
313
|
+
* This was previously a locally-scoped spelling — `typeof value === 'string'
|
|
314
|
+
* && value.startsWith('-')` — that git-ops.js's own comment named as "a THIRD
|
|
315
|
+
* … still live and NOT folded in" after #7290 folded a second, equally weak
|
|
316
|
+
* copy out of ws-file-ops/reader.js. It was strictly weaker than the shared
|
|
317
|
+
* guard: it fell through (accepted) on a non-string, an empty string, and a
|
|
318
|
+
* value carrying an embedded NUL/CR/LF, all of which `assertSafeArgvValue`
|
|
319
|
+
* rejects. A newline in particular matters because several CLIs (including
|
|
320
|
+
* git's own `--stdin` modes) treat one as a record separator, letting an
|
|
321
|
+
* embedded newline smuggle a second argument into a single slot.
|
|
309
322
|
*
|
|
310
323
|
* git-clone argv is NOT passed through a shell — the init container runs
|
|
311
324
|
* `command: ['git']` with an explicit `args` array — so classic shell
|
|
312
325
|
* metacharacter injection (`;`, `|`, `$()`, backticks) is structurally
|
|
313
|
-
* impossible. The residual risk is *argument* injection
|
|
314
|
-
*
|
|
315
|
-
*
|
|
316
|
-
* uses `--` to terminate option parsing as belt-and-braces.
|
|
326
|
+
* impossible. The residual risk is *argument* injection, which
|
|
327
|
+
* `assertSafeArgvValue` covers in full; the clone argv also uses `--` to
|
|
328
|
+
* terminate option parsing as belt-and-braces.
|
|
317
329
|
*
|
|
318
330
|
* @param {string} value
|
|
319
331
|
* @param {string} field - Field name for the error message
|
|
320
|
-
* @throws {Error} If the value
|
|
332
|
+
* @throws {Error} If the value is unsafe to place in the git clone argv.
|
|
321
333
|
*/
|
|
322
|
-
function
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
)
|
|
334
|
+
function assertGitRepoFieldSafe(value, field) {
|
|
335
|
+
try {
|
|
336
|
+
assertSafeArgvValue(value, `opts.gitRepo.${field}`)
|
|
337
|
+
} catch (err) {
|
|
338
|
+
throw new Error(`createEnvironment: ${err.message} (rejected to prevent git argument injection)`)
|
|
328
339
|
}
|
|
329
340
|
}
|
|
330
341
|
|
|
@@ -378,20 +389,20 @@ function validateGitRepo(gitRepo, cwd, workspacePVC) {
|
|
|
378
389
|
'createEnvironment: opts.gitRepo.url must be a non-empty string',
|
|
379
390
|
)
|
|
380
391
|
}
|
|
381
|
-
|
|
392
|
+
assertGitRepoFieldSafe(spec.url, 'url')
|
|
382
393
|
|
|
383
394
|
if (spec.branch != null) {
|
|
384
395
|
if (typeof spec.branch !== 'string' || spec.branch.length === 0) {
|
|
385
396
|
throw new Error('createEnvironment: opts.gitRepo.branch must be a non-empty string')
|
|
386
397
|
}
|
|
387
|
-
|
|
398
|
+
assertGitRepoFieldSafe(spec.branch, 'branch')
|
|
388
399
|
}
|
|
389
400
|
|
|
390
401
|
if (spec.commit != null) {
|
|
391
402
|
if (typeof spec.commit !== 'string' || spec.commit.length === 0) {
|
|
392
403
|
throw new Error('createEnvironment: opts.gitRepo.commit must be a non-empty string')
|
|
393
404
|
}
|
|
394
|
-
|
|
405
|
+
assertGitRepoFieldSafe(spec.commit, 'commit')
|
|
395
406
|
}
|
|
396
407
|
|
|
397
408
|
let depth = null
|
|
@@ -1637,6 +1648,7 @@ export class K8sBackend {
|
|
|
1637
1648
|
cmd, args = [], env, cwd, signal,
|
|
1638
1649
|
containerCliPath = DEFAULT_CONTAINER_CLI_PATH,
|
|
1639
1650
|
hostCwd,
|
|
1651
|
+
hostClaudePath,
|
|
1640
1652
|
} = opts
|
|
1641
1653
|
const ns = this._namespaceForCall(opts, 'streamCliInEnvironment')
|
|
1642
1654
|
|
|
@@ -1648,15 +1660,27 @@ export class K8sBackend {
|
|
|
1648
1660
|
|| this._agentTokens.get(podName)
|
|
1649
1661
|
|| this._readAgentToken(podName, ns)
|
|
1650
1662
|
|
|
1651
|
-
// Remap host cli.js
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
containerArgs[0]
|
|
1663
|
+
// Remap the SDK's host-path claude spawn (JS cli.js or native binary) to the
|
|
1664
|
+
// Pod's claude, mirroring DockerBackend (#8027).
|
|
1665
|
+
const remap = remapClaudeSpawn({ cmd, args, containerCliPath, hostClaudePath })
|
|
1666
|
+
const containerCmd = remap.cmd
|
|
1667
|
+
const containerArgs = remap.args
|
|
1668
|
+
if (remap.remapped) {
|
|
1669
|
+
log.info(`Remapped claude spawn: ${cmd} ${args[0] ?? ''} -> ${containerCmd} ${containerArgs[0] ?? ''}`)
|
|
1658
1670
|
}
|
|
1659
1671
|
|
|
1672
|
+
// A claude spawn runs with CLAUDE_CONFIG_DIR unset, so claude uses its own
|
|
1673
|
+
// `<HOME>/.claude`. Two layers: the command is wrapped in `env -u ...` (holds with
|
|
1674
|
+
// any sidecar image version) and the frame asks the sidecar to remove it from the
|
|
1675
|
+
// merged env (`unsetEnv`; an older sidecar ignores it). See container-claude-spawn.js.
|
|
1676
|
+
const unsetEnv = remap.remapped ? [...CONTAINER_UNSET_ENV] : undefined
|
|
1677
|
+
const spawnEnv = env && unsetEnv
|
|
1678
|
+
? Object.fromEntries(Object.entries(env).filter(([key]) => !unsetEnv.includes(key)))
|
|
1679
|
+
: env
|
|
1680
|
+
|
|
1681
|
+
const spawnCmd = unsetEnv ? containerUnsetEnvPrefix()[0] : containerCmd
|
|
1682
|
+
const spawnArgs = unsetEnv ? [...containerUnsetEnvPrefix().slice(1), containerCmd, ...containerArgs] : containerArgs
|
|
1683
|
+
|
|
1660
1684
|
// Remap host cwd to /workspace inside the Pod when provided.
|
|
1661
1685
|
let containerCwd = cwd
|
|
1662
1686
|
if (cwd && hostCwd) {
|
|
@@ -1719,7 +1743,7 @@ export class K8sBackend {
|
|
|
1719
1743
|
}
|
|
1720
1744
|
|
|
1721
1745
|
_wireWsToProc(ws, proc, {
|
|
1722
|
-
cmd, args:
|
|
1746
|
+
cmd: spawnCmd, args: spawnArgs, env: spawnEnv, unsetEnv, cwd: containerCwd, signal, cleanup,
|
|
1723
1747
|
})
|
|
1724
1748
|
}).catch((err) => {
|
|
1725
1749
|
log.warn(`streamCliInEnvironment dial failed for ${podName}: ${err.message}`)
|
|
@@ -2303,7 +2327,7 @@ class SidecarProcess extends EventEmitter {
|
|
|
2303
2327
|
* @param {AbortSignal} [spawnOpts.signal]
|
|
2304
2328
|
* @param {Function} [spawnOpts.cleanup] - Optional teardown for portforward bridge
|
|
2305
2329
|
*/
|
|
2306
|
-
function _wireWsToProc(ws, proc, { cmd, args = [], env, cwd, signal, cleanup } = {}) {
|
|
2330
|
+
function _wireWsToProc(ws, proc, { cmd, args = [], env, unsetEnv, cwd, signal, cleanup } = {}) {
|
|
2307
2331
|
// Distinguish initial wiring (spawn) from a reconnect (resume).
|
|
2308
2332
|
const isReconnect = Boolean(proc._sessionId)
|
|
2309
2333
|
|
|
@@ -2402,6 +2426,7 @@ function _wireWsToProc(ws, proc, { cmd, args = [], env, cwd, signal, cleanup } =
|
|
|
2402
2426
|
// sidecar protocol default introduced by #3329.
|
|
2403
2427
|
frame = { type: 'spawn', cmd, args, stdin: 'pipe' }
|
|
2404
2428
|
if (env && Object.keys(env).length > 0) frame.env = env
|
|
2429
|
+
if (unsetEnv && unsetEnv.length > 0) frame.unsetEnv = unsetEnv
|
|
2405
2430
|
if (cwd) frame.cwd = cwd
|
|
2406
2431
|
log.info(`Sent spawn frame: ${cmd} ${args.slice(0, 2).join(' ')}`)
|
|
2407
2432
|
}
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* #7562 — the ONE funnel for "destroy this environment", shared by both wire
|
|
3
|
+
* paths (`destroy_environment` in feature-handlers.js and `containers_action`
|
|
4
|
+
* with `action: 'destroy'` in control-room-handlers.js).
|
|
5
|
+
*
|
|
6
|
+
* POLICY (adjudicated 2026-08-30, recorded in
|
|
7
|
+
* docs/decisions/2026-08-destroy-environment-live-sessions.md):
|
|
8
|
+
*
|
|
9
|
+
* REFUSE when the environment has live sessions; `force: true` escapes, and
|
|
10
|
+
* force means CASCADE — destroy those sessions CLEANLY first, then the
|
|
11
|
+
* environment.
|
|
12
|
+
*
|
|
13
|
+
* Why cascade rather than detach: destroying an environment runs `docker rm -f`
|
|
14
|
+
* on its container, which kills every process inside it. The attached sessions
|
|
15
|
+
* die either way — the only question is whether they die cleanly (provider
|
|
16
|
+
* teardown, synthetic `stream_end` for in-flight streams, `session_destroyed`
|
|
17
|
+
* broadcast so clients drop the tab, state flushed, the environment tag
|
|
18
|
+
* removed) or are left sitting in `SessionManager._sessions` pointing at a
|
|
19
|
+
* container that no longer exists. "Detach and keep running" is not available:
|
|
20
|
+
* a `docker-sdk` session whose container is gone cannot run, and one that
|
|
21
|
+
* silently fell back to a fresh container would be #7561's containment escape.
|
|
22
|
+
*
|
|
23
|
+
* Why the refusal lives in `EnvironmentManager.destroy()` and not here: that is
|
|
24
|
+
* the single chokepoint every caller reaches, including any future one. A check
|
|
25
|
+
* duplicated per handler is the "guard wired to only some of its callers" shape
|
|
26
|
+
* catalogued in docs/false-safety-guards.md — which is how `containers_action`
|
|
27
|
+
* ended up with no guard at all while the dashboard had one.
|
|
28
|
+
*/
|
|
29
|
+
import { createLogger } from '../logger.js'
|
|
30
|
+
import { assertAuthorized } from '../connection-authority.js'
|
|
31
|
+
|
|
32
|
+
const log = createLogger('destroy-environment')
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* `err.code` on the refusal thrown by `EnvironmentManager.destroy()` when the
|
|
36
|
+
* environment still has sessions attached and `force` was not set. Also the
|
|
37
|
+
* `code` echoed on the `environment_error` wire reply.
|
|
38
|
+
*/
|
|
39
|
+
export const ENVIRONMENT_HAS_LIVE_SESSIONS = 'ENVIRONMENT_HAS_LIVE_SESSIONS'
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* How many times the cascade re-reads `env.sessions` before giving up on
|
|
43
|
+
* draining it. A session can attach between the read and the destroy (nothing
|
|
44
|
+
* holds the environment lock across `createSession`), so one snapshot is not
|
|
45
|
+
* enough; an unbounded loop would let a client that creates sessions in a loop
|
|
46
|
+
* wedge an operator's force-destroy. Bounded, then the destroy proceeds — the
|
|
47
|
+
* operator asked for `force`, and a straggler is a session the container
|
|
48
|
+
* teardown was going to kill anyway.
|
|
49
|
+
*/
|
|
50
|
+
export const MAX_CASCADE_PASSES = 5
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Build the structured refusal. Exported so `EnvironmentManager.destroy()` and
|
|
54
|
+
* this module cannot drift on the shape the handlers destructure.
|
|
55
|
+
* @param {{id: string, name?: string, sessions: string[]}} env
|
|
56
|
+
* @returns {Error & {code: string, environmentId: string, sessions: string[]}}
|
|
57
|
+
*/
|
|
58
|
+
export function liveSessionsError(env) {
|
|
59
|
+
const sessions = [...env.sessions]
|
|
60
|
+
const err = new Error(
|
|
61
|
+
`Environment "${env.name || env.id}" has ${sessions.length} live session(s) running in it ` +
|
|
62
|
+
`(${sessions.join(', ')}). Destroying the container would kill them. ` +
|
|
63
|
+
`Close the sessions first, or resend with force to destroy them and the environment together.`,
|
|
64
|
+
)
|
|
65
|
+
err.code = ENVIRONMENT_HAS_LIVE_SESSIONS
|
|
66
|
+
err.environmentId = env.id
|
|
67
|
+
err.sessions = sessions
|
|
68
|
+
return err
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Destroy an environment, honouring the live-session policy.
|
|
73
|
+
*
|
|
74
|
+
* @param {object} args
|
|
75
|
+
* @param {object} args.environmentManager - the live EnvironmentManager
|
|
76
|
+
* @param {object|null} [args.sessionManager] - the live SessionManager; only needed for the cascade
|
|
77
|
+
* @param {string} args.environmentId
|
|
78
|
+
* @param {boolean} [args.force=false] - destroy the attached sessions first, then the environment
|
|
79
|
+
* @returns {Promise<{destroyedSessions: string[]}>}
|
|
80
|
+
* @throws the structured `ENVIRONMENT_HAS_LIVE_SESSIONS` refusal (unforced, sessions attached),
|
|
81
|
+
* or whatever `EnvironmentManager.destroy()` throws (unknown id, backend failure).
|
|
82
|
+
*/
|
|
83
|
+
export async function destroyEnvironmentWithSessions({
|
|
84
|
+
environmentManager,
|
|
85
|
+
sessionManager = null,
|
|
86
|
+
environmentId,
|
|
87
|
+
force = false,
|
|
88
|
+
isAuthorized,
|
|
89
|
+
}) {
|
|
90
|
+
const destroyedSessions = []
|
|
91
|
+
assertAuthorized(isAuthorized)
|
|
92
|
+
|
|
93
|
+
if (force) {
|
|
94
|
+
// Drain first, so every session gets a real teardown while its container is
|
|
95
|
+
// still alive. Re-read between passes: `env.sessions` is mutated by
|
|
96
|
+
// `_cleanupSessionMaps` as each destroy lands, and a session can attach
|
|
97
|
+
// mid-cascade.
|
|
98
|
+
if (sessionManager && typeof sessionManager.destroySession === 'function') {
|
|
99
|
+
for (let pass = 0; pass < MAX_CASCADE_PASSES; pass++) {
|
|
100
|
+
const live = [...(environmentManager.get?.(environmentId)?.sessions || [])]
|
|
101
|
+
const pending = live.filter((id) => !destroyedSessions.includes(id))
|
|
102
|
+
if (pending.length === 0) break
|
|
103
|
+
for (const sessionId of pending) {
|
|
104
|
+
// Push BEFORE the destroy, deliberately (#7571 review S2). This list
|
|
105
|
+
// is two things at once: the caller's report, and — via the `pending`
|
|
106
|
+
// filter above — the loop's own record of what it has already
|
|
107
|
+
// attempted. Pushing after a successful destroy would make a session
|
|
108
|
+
// whose `destroySession` throws deterministically re-enter `pending`
|
|
109
|
+
// on every pass, so ONE broken session could consume all
|
|
110
|
+
// MAX_CASCADE_PASSES and starve the sessions behind it of a clean
|
|
111
|
+
// teardown — the exact outcome the cascade exists to prevent.
|
|
112
|
+
//
|
|
113
|
+
// The cost is that `destroyedSessions` can name a session whose
|
|
114
|
+
// teardown threw, so it is "attempted", not "confirmed". That
|
|
115
|
+
// misreport is confined to the handlers' `log.warn` summary; nothing
|
|
116
|
+
// branches on the list, and the environment goes away regardless.
|
|
117
|
+
// Attempted-once-each is the right trade against
|
|
118
|
+
// starve-the-rest-for-one-bad-session.
|
|
119
|
+
destroyedSessions.push(sessionId)
|
|
120
|
+
try {
|
|
121
|
+
sessionManager.destroySession(sessionId)
|
|
122
|
+
} catch (err) {
|
|
123
|
+
// A session that fails to tear down must not block the destroy the
|
|
124
|
+
// operator explicitly forced — the container teardown below ends it
|
|
125
|
+
// regardless. Log loudly; never rethrow.
|
|
126
|
+
log.error(`force-destroy: failed to destroy session ${sessionId} in ${environmentId}: ${err?.stack || err}`)
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
} else if ((environmentManager.get?.(environmentId)?.sessions || []).length > 0) {
|
|
131
|
+
log.warn(`force-destroy: ${environmentId} has attached sessions but no SessionManager is wired — they cannot be torn down cleanly`)
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// Always route through the manager, and always pass `force` through: after a
|
|
136
|
+
// successful drain the refusal would not fire anyway, but a session that
|
|
137
|
+
// attached after the last pass must not turn an explicit force into a
|
|
138
|
+
// failure.
|
|
139
|
+
assertAuthorized(isAuthorized)
|
|
140
|
+
await environmentManager.destroy(environmentId, { force, isAuthorized })
|
|
141
|
+
return { destroyedSessions }
|
|
142
|
+
}
|