@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,382 @@
|
|
|
1
|
+
import { spawn, execFile } from 'child_process'
|
|
2
|
+
import { createInterface } from 'readline'
|
|
3
|
+
import { CliSession } from './cli-session.js'
|
|
4
|
+
import { createLogger } from './logger.js'
|
|
5
|
+
import { BILLING_CLASSES } from './billing-class.js'
|
|
6
|
+
|
|
7
|
+
const log = createLogger('docker-session')
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Classify a Docker error into a structured error with a specific code.
|
|
11
|
+
*
|
|
12
|
+
* Returns an object with `code` and `message` fields so callers can surface
|
|
13
|
+
* actionable errors to clients instead of raw spawn/exec messages.
|
|
14
|
+
*
|
|
15
|
+
* @param {Error} err - The error from execFile or spawn
|
|
16
|
+
* @param {string} [stderrText] - Optional stderr output to include in classification
|
|
17
|
+
* @returns {{ code: string, message: string }}
|
|
18
|
+
*/
|
|
19
|
+
export function classifyDockerError(err, stderrText = '') {
|
|
20
|
+
const msg = (err.message || '').toLowerCase()
|
|
21
|
+
const stderr = (stderrText || err.stderr || '').toLowerCase()
|
|
22
|
+
const combined = msg + ' ' + stderr
|
|
23
|
+
|
|
24
|
+
if (
|
|
25
|
+
combined.includes('cannot connect to the docker daemon') ||
|
|
26
|
+
combined.includes('is the docker daemon running') ||
|
|
27
|
+
(combined.includes('connection refused') && combined.includes('docker'))
|
|
28
|
+
) {
|
|
29
|
+
return { code: 'docker_not_running', message: 'Docker is not running. Start Docker Desktop and try again.' }
|
|
30
|
+
}
|
|
31
|
+
if (
|
|
32
|
+
combined.includes('no such image') ||
|
|
33
|
+
combined.includes('manifest unknown') ||
|
|
34
|
+
combined.includes('pull access denied') ||
|
|
35
|
+
combined.includes('repository does not exist') ||
|
|
36
|
+
(combined.includes('not found') && combined.includes('image'))
|
|
37
|
+
) {
|
|
38
|
+
const imageMatch = combined.match(/(?:no such image:\s*|pull access denied for\s+)['"]?([a-z0-9][a-z0-9._\/-]*(?::[a-z0-9._-]+)?)/)
|
|
39
|
+
const imageName = imageMatch ? imageMatch[1] : null
|
|
40
|
+
const message = imageName
|
|
41
|
+
? `Docker image '${imageName}' not found. Run: docker pull ${imageName}`
|
|
42
|
+
: 'Docker image not found. Run: docker pull <image>'
|
|
43
|
+
return { code: 'docker_image_not_found', message }
|
|
44
|
+
}
|
|
45
|
+
if (
|
|
46
|
+
combined.includes('permission denied') ||
|
|
47
|
+
combined.includes('access denied')
|
|
48
|
+
) {
|
|
49
|
+
return { code: 'docker_permission_denied', message: 'Permission denied connecting to Docker. Check your Docker group membership.' }
|
|
50
|
+
}
|
|
51
|
+
return { code: 'docker_error', message: err.message }
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Env vars explicitly forwarded into the Docker container.
|
|
56
|
+
* Only vars needed for Claude Code operation — never forward the full host env.
|
|
57
|
+
*
|
|
58
|
+
* This list is broader than DockerSdkSession's allowlist because CliSession
|
|
59
|
+
* uses an external permission hook (HTTP callback to the host), which requires
|
|
60
|
+
* CHROXY_PORT, CHROXY_HOOK_SECRET, and CHROXY_PERMISSION_MODE. The CLI process
|
|
61
|
+
* also needs CLAUDE_HEADLESS and CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING
|
|
62
|
+
* for headless stream-json mode.
|
|
63
|
+
*
|
|
64
|
+
* See also: FORWARDED_ENV_KEYS in docker-sdk-session.js
|
|
65
|
+
*/
|
|
66
|
+
const FORWARDED_ENV_KEYS = [
|
|
67
|
+
'ANTHROPIC_API_KEY',
|
|
68
|
+
'CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING',
|
|
69
|
+
'CHROXY_PORT',
|
|
70
|
+
'CHROXY_HOOK_SECRET',
|
|
71
|
+
'CHROXY_PERMISSION_MODE',
|
|
72
|
+
'CLAUDE_HEADLESS',
|
|
73
|
+
'HOME',
|
|
74
|
+
'PATH',
|
|
75
|
+
]
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* DockerSession runs Claude Code inside an isolated Docker container.
|
|
79
|
+
*
|
|
80
|
+
* Extends CliSession and overrides only `_spawnPersistentProcess()` so that
|
|
81
|
+
* the child process is `docker exec -i <container> claude ...` instead of a
|
|
82
|
+
* bare `claude ...` subprocess. All upstream event handling, respawn logic,
|
|
83
|
+
* stdin/stdout piping, and lifecycle management from CliSession apply
|
|
84
|
+
* unchanged — only the spawn mechanism differs.
|
|
85
|
+
*
|
|
86
|
+
* Container lifecycle:
|
|
87
|
+
* start() → _startContainer() → long-lived `docker run … sleep infinity`
|
|
88
|
+
* spawn → `docker exec -i <id> claude …` (one per respawn)
|
|
89
|
+
* destroy() → `docker rm -f <id>`
|
|
90
|
+
*
|
|
91
|
+
* Permission hook routing:
|
|
92
|
+
* The container process must reach the host's HTTP server. On macOS/Windows
|
|
93
|
+
* `host.docker.internal` resolves automatically; on Linux we add
|
|
94
|
+
* `--add-host host.docker.internal:host-gateway` to the run args.
|
|
95
|
+
*/
|
|
96
|
+
export class DockerSession extends CliSession {
|
|
97
|
+
static get capabilities() {
|
|
98
|
+
return { ...CliSession.capabilities, containerized: true }
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Preflight credentials block — overrides CliSession's host-side spec (#4780).
|
|
103
|
+
*
|
|
104
|
+
* Inside a container `claude login` cannot work: there is no ~/.claude OAuth
|
|
105
|
+
* state and the host Keychain is invisible. The only valid path is the
|
|
106
|
+
* `ANTHROPIC_API_KEY` env var, which `_startContainer` forwards via
|
|
107
|
+
* `docker run --env`. CLAUDE_CODE_OAUTH_TOKEN is intentionally NOT in
|
|
108
|
+
* `envVars` — _startContainer does not forward it, so claiming the OAuth
|
|
109
|
+
* token satisfies auth would mislead the dashboard into reporting ready
|
|
110
|
+
* for a container that would still fail to authenticate.
|
|
111
|
+
*/
|
|
112
|
+
static get preflight() {
|
|
113
|
+
const parent = CliSession.preflight
|
|
114
|
+
return {
|
|
115
|
+
...parent,
|
|
116
|
+
credentials: {
|
|
117
|
+
envVars: ['ANTHROPIC_API_KEY'],
|
|
118
|
+
hint: 'set ANTHROPIC_API_KEY on the host so it is forwarded into the container (no OAuth fallback inside the container — the container has no ~/.claude state)',
|
|
119
|
+
optional: true,
|
|
120
|
+
},
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Resolve runtime auth state for the dashboard (#4769, #4780).
|
|
126
|
+
*
|
|
127
|
+
* Docker container providers forward process.env.ANTHROPIC_API_KEY to
|
|
128
|
+
* the container at `docker run` time (see _startContainer). Inside the
|
|
129
|
+
* container there is no ~/.claude OAuth state, so the env var is the
|
|
130
|
+
* only auth path — no OAuth fallback even though the host-side preflight
|
|
131
|
+
* marks credentials as optional. Overrides CliSession's "subscription
|
|
132
|
+
* always" branch — container providers do not bill the host's subscription.
|
|
133
|
+
*
|
|
134
|
+
* @param {NodeJS.ProcessEnv} env
|
|
135
|
+
* @returns {{ready:boolean, source:string, envVar:string|null, envVars:string[], hint:string, detail:string, billingClass:string}}
|
|
136
|
+
*/
|
|
137
|
+
static resolveAuth(env) {
|
|
138
|
+
const credSpec = this.preflight.credentials
|
|
139
|
+
const envVars = credSpec.envVars
|
|
140
|
+
const hint = credSpec.hint
|
|
141
|
+
|
|
142
|
+
// docker-cli forwards the host's ANTHROPIC_API_KEY into the container and
|
|
143
|
+
// has NO OAuth fallback (the container has no ~/.claude state), so it
|
|
144
|
+
// always bills the raw API account — api-key, era-independent. The host's
|
|
145
|
+
// subscription/programmatic-credit pool never applies inside the container.
|
|
146
|
+
const billingClass = BILLING_CLASSES.API_KEY
|
|
147
|
+
const matched = envVars.find(v => env[v])
|
|
148
|
+
if (matched) {
|
|
149
|
+
return {
|
|
150
|
+
ready: true,
|
|
151
|
+
source: 'env',
|
|
152
|
+
envVar: matched,
|
|
153
|
+
envVars,
|
|
154
|
+
hint: '',
|
|
155
|
+
detail: `Anthropic API (forwarded to container) (${matched} set)`,
|
|
156
|
+
billingClass,
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return {
|
|
160
|
+
ready: false,
|
|
161
|
+
source: 'none',
|
|
162
|
+
envVar: null,
|
|
163
|
+
envVars,
|
|
164
|
+
hint,
|
|
165
|
+
detail: 'Not configured — set ANTHROPIC_API_KEY on the host (forwarded into the container at run time). No OAuth fallback inside the container — the container has no ~/.claude state.',
|
|
166
|
+
billingClass,
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
constructor(opts = {}) {
|
|
171
|
+
super(opts)
|
|
172
|
+
this._containerId = null
|
|
173
|
+
this._image = opts.image || 'node:22-slim'
|
|
174
|
+
this._memoryLimit = opts.memoryLimit || '2g'
|
|
175
|
+
this._cpuLimit = opts.cpuLimit || '2'
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Start the container asynchronously, then call super.start() which invokes
|
|
180
|
+
* _spawnPersistentProcess() with the built Claude args.
|
|
181
|
+
*/
|
|
182
|
+
start() {
|
|
183
|
+
if (this._containerId) {
|
|
184
|
+
super.start()
|
|
185
|
+
return
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// Start container async to avoid blocking the event loop
|
|
189
|
+
this._startContainer((err) => {
|
|
190
|
+
if (err) {
|
|
191
|
+
this.emit('error', { code: err.code || 'docker_error', message: `Failed to start Docker container: ${err.message}` })
|
|
192
|
+
// Self-destruct so SessionManager doesn't keep a phantom entry
|
|
193
|
+
this.destroy()
|
|
194
|
+
return
|
|
195
|
+
}
|
|
196
|
+
super.start()
|
|
197
|
+
})
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Launch a long-lived container with security constraints.
|
|
202
|
+
* The container runs `sleep infinity` so it stays alive across
|
|
203
|
+
* multiple `docker exec` invocations (e.g. model switches / respawns).
|
|
204
|
+
*
|
|
205
|
+
* Uses async execFile to avoid blocking the event loop during image pull.
|
|
206
|
+
*/
|
|
207
|
+
_startContainer(callback) {
|
|
208
|
+
const args = [
|
|
209
|
+
'run', '-d', '--init', '--rm',
|
|
210
|
+
'--memory', this._memoryLimit,
|
|
211
|
+
'--cpus', this._cpuLimit,
|
|
212
|
+
'--pids-limit', '512',
|
|
213
|
+
'--cap-drop', 'ALL',
|
|
214
|
+
'--security-opt', 'no-new-privileges',
|
|
215
|
+
'-v', `${this.cwd || process.cwd()}:/workspace`,
|
|
216
|
+
'-w', '/workspace',
|
|
217
|
+
]
|
|
218
|
+
|
|
219
|
+
// Pass ANTHROPIC_API_KEY to the container so Claude can authenticate
|
|
220
|
+
const apiKey = process.env.ANTHROPIC_API_KEY
|
|
221
|
+
if (apiKey) {
|
|
222
|
+
args.push('--env', `ANTHROPIC_API_KEY=${apiKey}`)
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// On Linux, host.docker.internal is not available by default
|
|
226
|
+
if (process.platform === 'linux') {
|
|
227
|
+
args.push('--add-host', 'host.docker.internal:host-gateway')
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
args.push(this._image, 'sleep', 'infinity')
|
|
231
|
+
|
|
232
|
+
log.info(`Starting container (image: ${this._image}, memory: ${this._memoryLimit}, cpus: ${this._cpuLimit})`)
|
|
233
|
+
|
|
234
|
+
execFile('docker', args, { encoding: 'utf-8', timeout: 120_000 }, (err, stdout, stderr) => {
|
|
235
|
+
if (err) {
|
|
236
|
+
const classified = classifyDockerError(err, stderr)
|
|
237
|
+
log.warn(`Docker start failed [${classified.code}]: ${classified.message}`)
|
|
238
|
+
const error = new Error(classified.message)
|
|
239
|
+
error.code = classified.code
|
|
240
|
+
callback(error)
|
|
241
|
+
return
|
|
242
|
+
}
|
|
243
|
+
this._containerId = stdout.trim()
|
|
244
|
+
log.info(`Container started: ${this._containerId.slice(0, 12)}`)
|
|
245
|
+
callback(null)
|
|
246
|
+
})
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* Override CliSession._spawnPersistentProcess to use `docker exec -i`
|
|
251
|
+
* instead of spawning `claude` directly.
|
|
252
|
+
*
|
|
253
|
+
* The returned child process has the same stdio interface as a bare spawn
|
|
254
|
+
* so all CliSession readline/event wiring works unchanged — we just swap
|
|
255
|
+
* the underlying process handle.
|
|
256
|
+
*/
|
|
257
|
+
_spawnPersistentProcess(claudeArgs) {
|
|
258
|
+
this._cleanupReadlines()
|
|
259
|
+
this._processReady = false
|
|
260
|
+
|
|
261
|
+
if (!this._containerId) {
|
|
262
|
+
this.emit('error', { message: 'Docker container not started — cannot exec' })
|
|
263
|
+
return
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
const env = this._buildChildEnv()
|
|
267
|
+
|
|
268
|
+
// Route permission hook to host.docker.internal so the container process
|
|
269
|
+
// can reach the HTTP endpoint running on the host.
|
|
270
|
+
if (env.CHROXY_PORT) {
|
|
271
|
+
env.CHROXY_HOST = 'host.docker.internal'
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
const dockerArgs = ['exec', '-i', '--workdir', '/workspace']
|
|
275
|
+
|
|
276
|
+
// Forward only allowed env vars — never leak host secrets
|
|
277
|
+
for (const key of FORWARDED_ENV_KEYS) {
|
|
278
|
+
const val = env[key]
|
|
279
|
+
if (val !== undefined) {
|
|
280
|
+
dockerArgs.push('--env', `${key}=${val}`)
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
// Always forward CHROXY_HOST if set
|
|
284
|
+
if (env.CHROXY_HOST) {
|
|
285
|
+
dockerArgs.push('--env', `CHROXY_HOST=${env.CHROXY_HOST}`)
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
dockerArgs.push(this._containerId, 'claude', ...claudeArgs)
|
|
289
|
+
|
|
290
|
+
log.info(`Exec into container ${this._containerId.slice(0, 12)} (model: ${this.model || 'default'})`)
|
|
291
|
+
|
|
292
|
+
const child = spawn('docker', dockerArgs, {
|
|
293
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
294
|
+
})
|
|
295
|
+
|
|
296
|
+
this._child = child
|
|
297
|
+
|
|
298
|
+
// Absorb EPIPE errors on stdin
|
|
299
|
+
child.stdin.on('error', (err) => {
|
|
300
|
+
log.warn(`stdin error (ignored): ${err.message}`)
|
|
301
|
+
})
|
|
302
|
+
|
|
303
|
+
// Read stdout line by line — each line is a JSON object
|
|
304
|
+
const rl = createInterface({ input: child.stdout })
|
|
305
|
+
this._rl = rl
|
|
306
|
+
|
|
307
|
+
rl.on('line', (line) => {
|
|
308
|
+
if (!line.trim()) return
|
|
309
|
+
let data
|
|
310
|
+
try {
|
|
311
|
+
data = JSON.parse(line)
|
|
312
|
+
} catch {
|
|
313
|
+
return
|
|
314
|
+
}
|
|
315
|
+
this._handleEvent(data)
|
|
316
|
+
})
|
|
317
|
+
|
|
318
|
+
// Log stderr for debugging
|
|
319
|
+
const stderrRL = createInterface({ input: child.stderr })
|
|
320
|
+
this._stderrRL = stderrRL
|
|
321
|
+
stderrRL.on('line', (line) => {
|
|
322
|
+
if (line.trim()) {
|
|
323
|
+
log.info(`stderr: ${line}`)
|
|
324
|
+
}
|
|
325
|
+
})
|
|
326
|
+
|
|
327
|
+
child.on('error', (err) => {
|
|
328
|
+
this._cleanupReadlines()
|
|
329
|
+
this._processReady = false
|
|
330
|
+
this._child = null
|
|
331
|
+
const classified = classifyDockerError(err)
|
|
332
|
+
log.warn(`Docker exec failed [${classified.code}]: ${classified.message}`)
|
|
333
|
+
this.emit('error', { code: classified.code, message: classified.message })
|
|
334
|
+
this._scheduleRespawn()
|
|
335
|
+
})
|
|
336
|
+
|
|
337
|
+
child.on('close', (code) => this._handleChildClose(code))
|
|
338
|
+
|
|
339
|
+
this._processReady = true
|
|
340
|
+
log.info('Container exec started, ready for messages')
|
|
341
|
+
this.emit('ready', { sessionId: null, model: this.model, tools: [] })
|
|
342
|
+
|
|
343
|
+
// Dequeue the next pending message if not already busy.
|
|
344
|
+
// sendMessage() sets _isBusy, so the loop sends at most one message.
|
|
345
|
+
// Remaining items stay in the queue and are drained one-by-one via
|
|
346
|
+
// _clearMessageState() after each result.
|
|
347
|
+
while (this._pendingQueue.length > 0 && !this._isBusy) {
|
|
348
|
+
const pending = this._pendingQueue.shift()
|
|
349
|
+
log.info(`Dequeuing pending message (${this._pendingQueue.length} remaining)`)
|
|
350
|
+
this.sendMessage(pending.prompt, pending.attachments, pending.options || {})
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
// #4473: log the container-specific exit line under the docker-session
|
|
355
|
+
// namespace before delegating to the inherited handler (#4469). The
|
|
356
|
+
// inherited code emits its own "Process exited" line; this override
|
|
357
|
+
// lands first so `docker logs <ctr>` correlation by operators stays easy.
|
|
358
|
+
_handleChildClose(code) {
|
|
359
|
+
if (!this._destroying && !this._respawning) {
|
|
360
|
+
log.info(`Container exec exited (code ${code}), scheduling respawn`)
|
|
361
|
+
}
|
|
362
|
+
super._handleChildClose(code)
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/**
|
|
366
|
+
* Destroy the session: stop the exec process, remove the container,
|
|
367
|
+
* then call super.destroy() to clean up CliSession state.
|
|
368
|
+
*/
|
|
369
|
+
destroy() {
|
|
370
|
+
const containerId = this._containerId
|
|
371
|
+
this._containerId = null
|
|
372
|
+
|
|
373
|
+
super.destroy()
|
|
374
|
+
|
|
375
|
+
if (containerId) {
|
|
376
|
+
log.info(`Removing container ${containerId.slice(0, 12)}`)
|
|
377
|
+
execFile('docker', ['rm', '-f', containerId], { stdio: 'ignore' }, (err) => {
|
|
378
|
+
if (err) log.warn(`Failed to remove container ${containerId.slice(0, 12)}: ${err.message}`)
|
|
379
|
+
})
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
}
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
// doctor-billing.js — billing canary for the 2026-06-15 programmatic-credit cutover.
|
|
2
|
+
//
|
|
3
|
+
// rec #4 of docs/audit/june15-billing-strategy-2026-06-14.md. Early-warning that the
|
|
4
|
+
// `claude-tui` subscription-billing bet may have stopped holding, plus a
|
|
5
|
+
// datacenter-egress ban-signal warning. Every check here is PURE and injectable (pass
|
|
6
|
+
// `now`, the session list, the egress ip) so they unit-test without timers or network.
|
|
7
|
+
//
|
|
8
|
+
// Wiring status:
|
|
9
|
+
// - detectSilentMeteredDefault — WIRED into `chroxy doctor` (doctor.js "Billing"
|
|
10
|
+
// check). It needs only the resolved default provider + the clock, both available
|
|
11
|
+
// in the standalone preflight.
|
|
12
|
+
// - detectBillingReclassification — exported for the DAEMON / dashboard to call: it
|
|
13
|
+
// needs live per-session `totalCostUsd`, which a standalone `chroxy doctor` (no
|
|
14
|
+
// running daemon) does not have. Not wired into the CLI for that reason.
|
|
15
|
+
// - classifyEgressIp — exported; needs the daemon's resolved public egress IP (a
|
|
16
|
+
// network lookup), so it is consumed by the daemon/dashboard, not standalone doctor.
|
|
17
|
+
import {
|
|
18
|
+
BILLING_CLASSES,
|
|
19
|
+
PROGRAMMATIC_CREDIT_ERA_START,
|
|
20
|
+
billingClassForProvider,
|
|
21
|
+
isProgrammaticCreditEra,
|
|
22
|
+
} from './billing-class.js'
|
|
23
|
+
import { expandIpv6, normalizeIpv6Prefix } from './ip-utils.js'
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Loophole-closed canary. A `claude-tui` session is nominally subscription-billed
|
|
27
|
+
* (interactive allowance), so it should report no programmatic cost. If one reports
|
|
28
|
+
* a non-zero cost on/after the cutover, the bet may have been reclassified to metered
|
|
29
|
+
* credits — the single most important signal to surface.
|
|
30
|
+
*
|
|
31
|
+
* @param {Array<{id:string, provider:string, totalCostUsd?:number, apiKeyAuth?:boolean}>} sessions
|
|
32
|
+
* @param {number} [now]
|
|
33
|
+
* @returns {Array<{code:string, sessionId:string, costUsd:number, message:string}>}
|
|
34
|
+
*/
|
|
35
|
+
export function detectBillingReclassification(sessions = [], now = Date.now()) {
|
|
36
|
+
const warnings = []
|
|
37
|
+
// Only meaningful on/after the cutover: before it, claude-tui and the host
|
|
38
|
+
// programmatic providers all bill as flat subscription, so a cost reading is
|
|
39
|
+
// not a reclassification signal. Gating here keeps the behaviour matching the
|
|
40
|
+
// docstring (no surprising pre-cutover warnings).
|
|
41
|
+
if (!isProgrammaticCreditEra(now)) return warnings
|
|
42
|
+
for (const s of sessions || []) {
|
|
43
|
+
if (!s || s.provider !== 'claude-tui') continue
|
|
44
|
+
// claude-tui is always SUBSCRIPTION per billing-class; guard anyway so this
|
|
45
|
+
// stays correct if that ever changes.
|
|
46
|
+
if (billingClassForProvider('claude-tui', now) !== BILLING_CLASSES.SUBSCRIPTION) continue
|
|
47
|
+
const cost = Number(s.totalCostUsd)
|
|
48
|
+
if (Number.isFinite(cost) && cost > 0) {
|
|
49
|
+
warnings.push({
|
|
50
|
+
code: 'TUI_REPORTED_PROGRAMMATIC_COST',
|
|
51
|
+
sessionId: s.id,
|
|
52
|
+
costUsd: cost,
|
|
53
|
+
message:
|
|
54
|
+
`claude-tui session ${s.id} reported $${cost.toFixed(4)} of programmatic cost, but it ` +
|
|
55
|
+
`should bill against your subscription's interactive allowance. The cutover may have ` +
|
|
56
|
+
`reclassified it — verify in your Anthropic billing dashboard and consider BYOK (ANTHROPIC_API_KEY).`,
|
|
57
|
+
})
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return warnings
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Silent-metered-default canary. On/after the era boundary, a daemon whose default
|
|
65
|
+
* provider is a programmatic one meters credits with no prompt. (#5819.)
|
|
66
|
+
*
|
|
67
|
+
* @param {string} defaultProvider - the resolved default provider id
|
|
68
|
+
* @param {number} [now]
|
|
69
|
+
* @param {{ apiKeyAuth?: boolean }} [opts] - `apiKeyAuth: true` forwards billing-class's
|
|
70
|
+
* refinement: claude-sdk/claude-cli authed with an explicit ANTHROPIC_API_KEY bill the
|
|
71
|
+
* raw API account (api-key), NOT the credit pool — so a BYOK default must NOT trip this
|
|
72
|
+
* warning. The caller decides this (e.g. claude-sdk + ANTHROPIC_API_KEY set).
|
|
73
|
+
* @returns {Array<{code:string, provider:string, message:string}>}
|
|
74
|
+
*/
|
|
75
|
+
export function detectSilentMeteredDefault(defaultProvider, now = Date.now(), { apiKeyAuth = false } = {}) {
|
|
76
|
+
if (!isProgrammaticCreditEra(now)) return []
|
|
77
|
+
if (billingClassForProvider(defaultProvider, now, { apiKeyAuth }) !== BILLING_CLASSES.PROGRAMMATIC_CREDIT) return []
|
|
78
|
+
// Derive the boundary date from the shared constant so a moved cutover can't
|
|
79
|
+
// leave a stale string here.
|
|
80
|
+
const cutover = new Date(PROGRAMMATIC_CREDIT_ERA_START).toISOString().slice(0, 10)
|
|
81
|
+
return [{
|
|
82
|
+
code: 'SILENT_METERED_DEFAULT',
|
|
83
|
+
provider: defaultProvider,
|
|
84
|
+
message:
|
|
85
|
+
`The default provider '${defaultProvider}' bills against the metered programmatic-credit pool ` +
|
|
86
|
+
`since ${cutover}. New default sessions draw credits silently — switch with --provider claude-tui ` +
|
|
87
|
+
`(subscription, best-effort) or set ANTHROPIC_API_KEY (BYOK).`,
|
|
88
|
+
}]
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// Datacenter-egress ban-signal. Cloud-hosted daemons behind a tunnel are a documented
|
|
92
|
+
// flag (the audit cites ~20-minute bans on Hetzner ranges). This is a pure classifier
|
|
93
|
+
// over known-prefix lists (IPv4 and IPv6); the caller supplies the public egress ip.
|
|
94
|
+
//
|
|
95
|
+
// CONSERVATIVE BY DESIGN: only specific, documented datacenter ranges are listed.
|
|
96
|
+
// Coarse blocks (e.g. AWS/GCP /8s `13.`, `34.`, `52.`) were deliberately REMOVED —
|
|
97
|
+
// they span large amounts of residential/ISP space too and would fire false positives,
|
|
98
|
+
// training users to ignore the warning. A comprehensive classifier needs a maintained
|
|
99
|
+
// cloud-IP dataset (e.g. the published AWS/GCP/Azure range JSON); until that is plumbed
|
|
100
|
+
// in, a precise-but-narrow list that never cries wolf beats a broad-but-noisy one. A
|
|
101
|
+
// missed datacenter IP is a silent non-warning; a false hit erodes trust.
|
|
102
|
+
const DATACENTER_IPV4_PREFIXES = [
|
|
103
|
+
// Hetzner (cited in claude-code#21678) — specific allocated /16s.
|
|
104
|
+
'5.9.', '88.99.', '95.216.', '116.202.', '135.181.', '167.235.', '168.119.',
|
|
105
|
+
]
|
|
106
|
+
|
|
107
|
+
// #5831: IPv6 datacenter ranges, matched against the CANONICAL expanded form
|
|
108
|
+
// (8 zero-padded groups) so a compressed `2a01:4f8::1` and a padded
|
|
109
|
+
// `2a01:04f8:...` compare equal. Same conservative stance as the IPv4 list —
|
|
110
|
+
// only documented Hetzner blocks. Matching the leading two groups is NARROWER
|
|
111
|
+
// than the announced /29s on purpose: a missed datacenter IP is a silent
|
|
112
|
+
// non-warning, a false hit erodes trust. Listed pre-normalised (lowercase,
|
|
113
|
+
// zero-padded) so they prefix-match expandIpv6 output directly.
|
|
114
|
+
const DATACENTER_IPV6_PREFIXES = [
|
|
115
|
+
'2a01:04f8:', // Hetzner Online (dedicated)
|
|
116
|
+
'2a01:04f9:', // Hetzner Online
|
|
117
|
+
'2a01:04ff:', // Hetzner Cloud
|
|
118
|
+
]
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* @param {string} ip - public egress IP (IPv4 or IPv6)
|
|
122
|
+
* @param {string[]} [extraPrefixes] - operator-supplied extra prefixes
|
|
123
|
+
* (config.billing.datacenterPrefixes), merged with the built-in lists. A
|
|
124
|
+
* prefix containing `:` is treated as IPv6, otherwise IPv4. Lets a user on a
|
|
125
|
+
* known cloud add their provider's ranges without a code change.
|
|
126
|
+
* @returns {{datacenter:boolean, code?:string, message?:string}}
|
|
127
|
+
*/
|
|
128
|
+
export function classifyEgressIp(ip, extraPrefixes = []) {
|
|
129
|
+
if (!ip || typeof ip !== 'string') return { datacenter: false }
|
|
130
|
+
// Trim operator prefixes — a copy/pasted `" 2a02:1370: "` passes config
|
|
131
|
+
// validation (non-empty string) but would otherwise never match.
|
|
132
|
+
const extra = Array.isArray(extraPrefixes)
|
|
133
|
+
? extraPrefixes.filter((p) => typeof p === 'string').map((p) => p.trim()).filter((p) => p.length > 0)
|
|
134
|
+
: []
|
|
135
|
+
|
|
136
|
+
let hit = false
|
|
137
|
+
if (ip.includes(':')) {
|
|
138
|
+
// IPv6: compare canonical expanded forms so spelling doesn't matter.
|
|
139
|
+
const expanded = expandIpv6(ip)
|
|
140
|
+
if (expanded) {
|
|
141
|
+
const v6 = [...DATACENTER_IPV6_PREFIXES, ...extra.filter((p) => p.includes(':')).map(normalizeIpv6Prefix)]
|
|
142
|
+
hit = v6.some((p) => expanded.startsWith(p))
|
|
143
|
+
}
|
|
144
|
+
} else {
|
|
145
|
+
const v4 = [...DATACENTER_IPV4_PREFIXES, ...extra.filter((p) => !p.includes(':'))]
|
|
146
|
+
hit = v4.some((p) => ip.startsWith(p))
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
if (!hit) return { datacenter: false }
|
|
150
|
+
return {
|
|
151
|
+
datacenter: true,
|
|
152
|
+
code: 'DATACENTER_EGRESS',
|
|
153
|
+
message:
|
|
154
|
+
`This daemon's public egress IP (${ip}) looks like a datacenter/cloud range. Driving a Claude ` +
|
|
155
|
+
`subscription login from a cloud host is a documented ban signal — prefer a residential network ` +
|
|
156
|
+
`for claude-tui, or use BYOK on cloud hosts.`,
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Aggregate the canary. Returns a flat warnings array (empty = all clear).
|
|
162
|
+
*
|
|
163
|
+
* @param {{sessions?:Array, defaultProvider?:string, egressIp?:string, now?:number, apiKeyAuth?:boolean, datacenterPrefixes?:string[]}} input
|
|
164
|
+
* `apiKeyAuth: true` forwards billing-class's refinement to the silent-metered
|
|
165
|
+
* check so a BYOK (claude-sdk + ANTHROPIC_API_KEY) default isn't flagged.
|
|
166
|
+
* `datacenterPrefixes` extends the built-in egress prefix list (#5828).
|
|
167
|
+
*/
|
|
168
|
+
export function runBillingCanary({ sessions = [], defaultProvider, egressIp, now = Date.now(), apiKeyAuth = false, datacenterPrefixes = [] } = {}) {
|
|
169
|
+
const warnings = []
|
|
170
|
+
warnings.push(...detectSilentMeteredDefault(defaultProvider, now, { apiKeyAuth }))
|
|
171
|
+
warnings.push(...detectBillingReclassification(sessions, now))
|
|
172
|
+
const egress = classifyEgressIp(egressIp, datacenterPrefixes)
|
|
173
|
+
if (egress.datacenter) warnings.push({ code: egress.code, message: egress.message })
|
|
174
|
+
return {
|
|
175
|
+
eraStarted: isProgrammaticCreditEra(now),
|
|
176
|
+
eraStart: PROGRAMMATIC_CREDIT_ERA_START,
|
|
177
|
+
warnings,
|
|
178
|
+
}
|
|
179
|
+
}
|