@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,579 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Config-driven Anthropic-compatible provider endpoints (#5419).
|
|
3
|
+
*
|
|
4
|
+
* Anything that speaks the Anthropic Messages API — Z.ai GLM, Moonshot
|
|
5
|
+
* Kimi, MiniMax, LM Studio 0.4.1+, llama.cpp server, vLLM, OpenRouter,
|
|
6
|
+
* any custom proxy — can be declared in config.json under
|
|
7
|
+
* `providers.anthropicCompatible` and registered as a first-class
|
|
8
|
+
* provider at startup, without writing a per-service session class.
|
|
9
|
+
*
|
|
10
|
+
* One generic factory, `createAnthropicCompatibleSessionClass(entry)`,
|
|
11
|
+
* stamps out a ClaudeByokSession subclass per entry by parameterizing
|
|
12
|
+
* the four seams (`_defaultModel`, `_resolveCredentials`, `_buildClient`,
|
|
13
|
+
* `_getPricing`) plus the static-side metadata — exactly what
|
|
14
|
+
* deepseek-session.js and ollama-session.js do by hand. Subclass, not
|
|
15
|
+
* fork: every byok-session fix (history rollback, parallel tools,
|
|
16
|
+
* MAX_TOOL_ROUNDS, MCP teardown) flows to every configured endpoint.
|
|
17
|
+
*
|
|
18
|
+
* Entry conventions (validated in anthropic-compatible-config.js):
|
|
19
|
+
* - `models` present → static allowlist (`getAllowedModels()` returns
|
|
20
|
+
* the array; settings-handlers' tri-state takes the array path).
|
|
21
|
+
* - `models` absent → unrestricted (`getAllowedModels()` returns null
|
|
22
|
+
* → PROVIDER_MODELS_UNRESTRICTED symbol path, the #5418 ollama rule).
|
|
23
|
+
* - `pricing` absent → zero pricing (a real frozen all-zero entry, not
|
|
24
|
+
* null, so byok-session's "no pricing entry" warn never fires and
|
|
25
|
+
* cost is an honest $0 — the ollama convention for local endpoints).
|
|
26
|
+
* - `contextWindow` absent → null. Never fabricate a window: clients
|
|
27
|
+
* already handle a null/omitted window (#5444) by hiding the chip.
|
|
28
|
+
* - Neither `apiKeyEnv` nor `credentialsKey` → keyless local endpoint
|
|
29
|
+
* (LM Studio, llama.cpp, vLLM); the SDK refuses an empty apiKey so a
|
|
30
|
+
* placeholder is sent, same as ollama's dummy key.
|
|
31
|
+
*
|
|
32
|
+
* Credentials never touch config.json: `apiKeyEnv` names an env var,
|
|
33
|
+
* `credentialsKey` names a field in ~/.chroxy/credentials.json (which
|
|
34
|
+
* must be mode 0600 — same enforcement as deepseek-credentials.js). Env
|
|
35
|
+
* wins over file. Keys are never logged; byok-session masks at the use
|
|
36
|
+
* site.
|
|
37
|
+
*/
|
|
38
|
+
|
|
39
|
+
import { readCredentialJsonField } from './credentials-file.js'
|
|
40
|
+
import { join } from 'path'
|
|
41
|
+
import { homedir } from 'os'
|
|
42
|
+
import Anthropic from '@anthropic-ai/sdk'
|
|
43
|
+
import { ClaudeByokSession } from './byok-session.js'
|
|
44
|
+
import { validateAnthropicCompatibleProviders } from './anthropic-compatible-config.js'
|
|
45
|
+
import { registerProvider, getRegisteredProviderNames } from './providers.js'
|
|
46
|
+
import { getRegistryForProvider } from './models.js'
|
|
47
|
+
import { refreshDiscoveredModels } from './model-discovery.js'
|
|
48
|
+
import { cachedResolveCredentialFile } from './auth-probes.js'
|
|
49
|
+
import { createLogger } from './logger.js'
|
|
50
|
+
import { BILLING_CLASSES } from './billing-class.js'
|
|
51
|
+
|
|
52
|
+
const log = createLogger('anthropic-compatible')
|
|
53
|
+
|
|
54
|
+
// Sent when an entry configures no credential source (local endpoints):
|
|
55
|
+
// the wire requires an api key field but the server ignores it, and the
|
|
56
|
+
// Anthropic SDK refuses an empty apiKey — same story as ollama's dummy.
|
|
57
|
+
const COMPAT_PLACEHOLDER_API_KEY = 'anthropic-compatible'
|
|
58
|
+
|
|
59
|
+
// Zero-rate pricing for entries without a `pricing` block. A real
|
|
60
|
+
// (frozen) entry rather than null so byok-session's once-per-model "no
|
|
61
|
+
// pricing entry" warn never fires for an endpoint where missing pricing
|
|
62
|
+
// is the configuration, not a bug.
|
|
63
|
+
const ZERO_PRICING = Object.freeze({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0 })
|
|
64
|
+
|
|
65
|
+
// Lazy-resolved per call so tests that mutate process.env.HOME between
|
|
66
|
+
// cases pick up the new home (same rationale as deepseek-credentials.js).
|
|
67
|
+
function credentialsFilePath() {
|
|
68
|
+
return join(homedir(), '.chroxy', 'credentials.json')
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Read one field out of ~/.chroxy/credentials.json with 0600 enforcement.
|
|
73
|
+
* Thin wrapper over the shared reader (P2-9); its reason strings match this
|
|
74
|
+
* caller's prior format 1:1 (no env-var ENOENT prefix here), so the `code` is
|
|
75
|
+
* not consulted.
|
|
76
|
+
*
|
|
77
|
+
* @param {string} field - Field name (e.g. 'zaiApiKey')
|
|
78
|
+
* @returns {{ key: string } | { key: null, reason: string }}
|
|
79
|
+
*/
|
|
80
|
+
function readCredentialsField(field) {
|
|
81
|
+
const { key, reason } = readCredentialJsonField(credentialsFilePath(), field)
|
|
82
|
+
return key !== null ? { key } : { key: null, reason }
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Resolve the API key for a config-driven Anthropic-compatible entry.
|
|
87
|
+
*
|
|
88
|
+
* Priority order:
|
|
89
|
+
* 1. process.env[entry.apiKeyEnv] (when apiKeyEnv is set)
|
|
90
|
+
* 2. ~/.chroxy/credentials.json[entry.credentialsKey], file mode 0600
|
|
91
|
+
* (when credentialsKey is set)
|
|
92
|
+
* 3. Neither source configured → the keyless placeholder (local endpoints)
|
|
93
|
+
*
|
|
94
|
+
* Never logged.
|
|
95
|
+
*
|
|
96
|
+
* `resolveAuth` calls this once per configured entry on every dashboard
|
|
97
|
+
* `list_providers` round-trip, so entries with a `credentialsKey` route the
|
|
98
|
+
* credentials.json stat+read+parse through the shared
|
|
99
|
+
* `cachedResolveCredentialFile` cache (#5461) — the same mtime+size+mode /
|
|
100
|
+
* env-value invalidation contract the built-in byok/deepseek/discord slots
|
|
101
|
+
* use, with one dynamic slot per (apiKeyEnv, credentialsKey) pair. Keying by
|
|
102
|
+
* the resolver's actual inputs (rather than entry.id) means two entries that
|
|
103
|
+
* share a credential spec share the cached result, and an id-less raw entry
|
|
104
|
+
* can never poison a sibling's slot.
|
|
105
|
+
*
|
|
106
|
+
* @param {{ apiKeyEnv: string|null, credentialsKey: string|null }} entry
|
|
107
|
+
* @returns {{ key: string, source: 'env' | 'file' } | { key: null, source: 'none', reason: string }}
|
|
108
|
+
*/
|
|
109
|
+
export function resolveAnthropicCompatibleApiKey(entry) {
|
|
110
|
+
const { apiKeyEnv, credentialsKey } = entry
|
|
111
|
+
if (!credentialsKey) {
|
|
112
|
+
// Keyless placeholder or env-only entry — no credentials.json I/O to
|
|
113
|
+
// cache; the uncached resolver never touches the file on these paths.
|
|
114
|
+
return resolveAnthropicCompatibleApiKeyUncached(entry)
|
|
115
|
+
}
|
|
116
|
+
return cachedResolveCredentialFile(
|
|
117
|
+
// #5486: encode the (apiKeyEnv, credentialsKey) pair with JSON so the slot key
|
|
118
|
+
// is collision-proof for ANY input charset. The plain `compat:<env>:<key>`
|
|
119
|
+
// form is unambiguous only for config-validated entries (ENV_VAR_NAME_RE /
|
|
120
|
+
// CREDENTIALS_KEY_RE both exclude `:` — #5458). But createAnthropicCompatibleSessionClass
|
|
121
|
+
// is exported for embedders/tests and its defensive normalization only checks
|
|
122
|
+
// "non-empty string", so a `:`-bearing value (apiKeyEnv 'A:B' + key 'C' vs
|
|
123
|
+
// 'A' + 'B:C') would mint the same `compat:A:B:C` slot and cross-serve cached
|
|
124
|
+
// credentials between two different specs. JSON.stringify quotes/escapes the
|
|
125
|
+
// delimiter, so distinct specs get distinct slots; an identical spec still
|
|
126
|
+
// produces an identical key (the intentional sharing from #5461 is preserved).
|
|
127
|
+
`compat:${JSON.stringify([apiKeyEnv || '', credentialsKey])}`,
|
|
128
|
+
apiKeyEnv ? process.env[apiKeyEnv] : undefined,
|
|
129
|
+
() => resolveAnthropicCompatibleApiKeyUncached(entry),
|
|
130
|
+
apiKeyEnv || null,
|
|
131
|
+
)
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* The uncached resolver body — does the actual env lookup and (0600-enforced)
|
|
136
|
+
* credentials.json read. Exercised through the cache wrapper above.
|
|
137
|
+
*
|
|
138
|
+
* @param {{ apiKeyEnv: string|null, credentialsKey: string|null }} entry
|
|
139
|
+
* @returns {{ key: string, source: 'env' | 'file' } | { key: null, source: 'none', reason: string }}
|
|
140
|
+
*/
|
|
141
|
+
function resolveAnthropicCompatibleApiKeyUncached(entry) {
|
|
142
|
+
const { apiKeyEnv, credentialsKey } = entry
|
|
143
|
+
|
|
144
|
+
if (!apiKeyEnv && !credentialsKey) {
|
|
145
|
+
// Keyless local endpoint. 'env' keeps byok-session's key-source log
|
|
146
|
+
// line truthful enough without growing a new source enum value —
|
|
147
|
+
// mirrors ollama's dummy-key convention.
|
|
148
|
+
return { key: COMPAT_PLACEHOLDER_API_KEY, source: 'env' }
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
if (apiKeyEnv) {
|
|
152
|
+
const envKey = process.env[apiKeyEnv]
|
|
153
|
+
if (typeof envKey === 'string' && envKey.length > 0) {
|
|
154
|
+
return { key: envKey, source: 'env' }
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
if (credentialsKey) {
|
|
159
|
+
const fromFile = readCredentialsField(credentialsKey)
|
|
160
|
+
if (fromFile.key) {
|
|
161
|
+
return { key: fromFile.key, source: 'file' }
|
|
162
|
+
}
|
|
163
|
+
const envPart = apiKeyEnv ? `${apiKeyEnv} not set and ` : ''
|
|
164
|
+
return { key: null, source: 'none', reason: `${envPart}${fromFile.reason}` }
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
return { key: null, source: 'none', reason: `${apiKeyEnv} not set` }
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Build the credential hint shown by preflight / resolveAuth for a
|
|
172
|
+
* not-ready entry.
|
|
173
|
+
*/
|
|
174
|
+
function credentialHint(entry) {
|
|
175
|
+
const parts = []
|
|
176
|
+
if (entry.apiKeyEnv) parts.push(`set ${entry.apiKeyEnv}`)
|
|
177
|
+
if (entry.credentialsKey) parts.push(`save it as "${entry.credentialsKey}" in ~/.chroxy/credentials.json (mode 0600)`)
|
|
178
|
+
return parts.join(' or ')
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Create a ClaudeByokSession subclass for one validated config entry.
|
|
183
|
+
*
|
|
184
|
+
* The entry should be the NORMALIZED shape produced by
|
|
185
|
+
* `validateAnthropicCompatibleProviders` (anthropic-compatible-config.js);
|
|
186
|
+
* the factory still applies the same defaults defensively so tests and
|
|
187
|
+
* embedders can pass a minimal raw entry.
|
|
188
|
+
*
|
|
189
|
+
* @param {object} rawEntry - Normalized config entry
|
|
190
|
+
* @param {object} [options] - Factory options
|
|
191
|
+
* @param {string} [options.blockLabel='anthropicCompatible'] - The config block
|
|
192
|
+
* name that construction-error messages should reference. The OpenAI-compatible
|
|
193
|
+
* factory delegates here and passes 'openaiCompatible' so a malformed
|
|
194
|
+
* `providers.openaiCompatible` entry names its own block rather than this one
|
|
195
|
+
* (#6253). Defaults to 'anthropicCompatible' so the Anthropic path's wording is
|
|
196
|
+
* byte-for-byte unchanged.
|
|
197
|
+
* @returns {typeof ClaudeByokSession} Provider session class for the registry
|
|
198
|
+
*/
|
|
199
|
+
export function createAnthropicCompatibleSessionClass(rawEntry, { blockLabel = 'anthropicCompatible' } = {}) {
|
|
200
|
+
if (typeof rawEntry !== 'object' || rawEntry === null || typeof rawEntry.id !== 'string' || rawEntry.id.length === 0) {
|
|
201
|
+
// The Anthropic block keeps its original (function-named) wording so its
|
|
202
|
+
// tests are unchanged; a delegated block (e.g. openaiCompatible) names
|
|
203
|
+
// itself, since there is no id to embed in the message here (#6253).
|
|
204
|
+
throw new Error(
|
|
205
|
+
blockLabel === 'anthropicCompatible'
|
|
206
|
+
? 'createAnthropicCompatibleSessionClass requires an entry with a non-empty id'
|
|
207
|
+
: `${blockLabel} entry requires a non-empty id`,
|
|
208
|
+
)
|
|
209
|
+
}
|
|
210
|
+
if (typeof rawEntry.baseUrl !== 'string' || rawEntry.baseUrl.length === 0) {
|
|
211
|
+
throw new Error(`${blockLabel} entry '${rawEntry.id}' requires a baseUrl`)
|
|
212
|
+
}
|
|
213
|
+
if (typeof rawEntry.defaultModel !== 'string' || rawEntry.defaultModel.length === 0) {
|
|
214
|
+
throw new Error(`${blockLabel} entry '${rawEntry.id}' requires a defaultModel`)
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// Defensive normalization (no-op for validator output).
|
|
218
|
+
const entry = Object.freeze({
|
|
219
|
+
id: rawEntry.id,
|
|
220
|
+
label: typeof rawEntry.label === 'string' && rawEntry.label.length > 0 ? rawEntry.label : rawEntry.id,
|
|
221
|
+
baseUrl: rawEntry.baseUrl,
|
|
222
|
+
apiKeyEnv: typeof rawEntry.apiKeyEnv === 'string' && rawEntry.apiKeyEnv.length > 0 ? rawEntry.apiKeyEnv : null,
|
|
223
|
+
credentialsKey: typeof rawEntry.credentialsKey === 'string' && rawEntry.credentialsKey.length > 0 ? rawEntry.credentialsKey : null,
|
|
224
|
+
defaultModel: rawEntry.defaultModel,
|
|
225
|
+
models: Array.isArray(rawEntry.models) && rawEntry.models.length > 0 ? Object.freeze([...rawEntry.models]) : null,
|
|
226
|
+
pricing: rawEntry.pricing ? Object.freeze({ ...ZERO_PRICING, ...rawEntry.pricing }) : null,
|
|
227
|
+
contextWindow: Number.isInteger(rawEntry.contextWindow) && rawEntry.contextWindow > 0 ? rawEntry.contextWindow : null,
|
|
228
|
+
modelDiscovery: (rawEntry.modelDiscovery
|
|
229
|
+
&& typeof rawEntry.modelDiscovery === 'object'
|
|
230
|
+
&& typeof rawEntry.modelDiscovery.url === 'string'
|
|
231
|
+
&& typeof rawEntry.modelDiscovery.format === 'string')
|
|
232
|
+
? Object.freeze({ url: rawEntry.modelDiscovery.url, format: rawEntry.modelDiscovery.format })
|
|
233
|
+
: null,
|
|
234
|
+
})
|
|
235
|
+
|
|
236
|
+
const keyless = !entry.apiKeyEnv && !entry.credentialsKey
|
|
237
|
+
const flatPricing = entry.pricing || ZERO_PRICING
|
|
238
|
+
|
|
239
|
+
// Per-class mutable catalog state (#5548). Populated by model discovery
|
|
240
|
+
// (refreshModels → applyCatalog) when `modelDiscovery` is configured;
|
|
241
|
+
// otherwise stays null and every model-shaped static falls back to the
|
|
242
|
+
// static `models`/defaultModel seed. Held in a closure shared by the class
|
|
243
|
+
// statics — one catalog per registered provider id, exactly like the
|
|
244
|
+
// module-scoped registry the registry hooks below resolve.
|
|
245
|
+
// - catalogIds: Set of discovered model ids (authoritative allowlist)
|
|
246
|
+
// - catalogMeta: Map id → { label, contextWindow }
|
|
247
|
+
// - catalogPricing: Map id → { input, output, cacheRead, cacheWrite }
|
|
248
|
+
let catalogIds = null
|
|
249
|
+
let catalogMeta = null
|
|
250
|
+
let catalogPricing = null
|
|
251
|
+
|
|
252
|
+
function applyCatalog(catalog) {
|
|
253
|
+
const models = Array.isArray(catalog?.models) ? catalog.models : []
|
|
254
|
+
if (models.length === 0) return
|
|
255
|
+
const ids = new Set()
|
|
256
|
+
const meta = new Map()
|
|
257
|
+
for (const m of models) {
|
|
258
|
+
if (typeof m?.id !== 'string' || m.id.length === 0) continue
|
|
259
|
+
ids.add(m.id)
|
|
260
|
+
meta.set(m.id, {
|
|
261
|
+
label: typeof m.label === 'string' && m.label.length > 0 ? m.label : m.id,
|
|
262
|
+
contextWindow: Number.isInteger(m.contextWindow) && m.contextWindow > 0 ? m.contextWindow : null,
|
|
263
|
+
})
|
|
264
|
+
}
|
|
265
|
+
const pricingTable = catalog?.pricing && typeof catalog.pricing === 'object' ? catalog.pricing : {}
|
|
266
|
+
const pricingMap = new Map()
|
|
267
|
+
for (const id of Object.keys(pricingTable)) {
|
|
268
|
+
const p = pricingTable[id]
|
|
269
|
+
if (p && typeof p === 'object') {
|
|
270
|
+
pricingMap.set(id, Object.freeze({ ...ZERO_PRICING, ...p }))
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
catalogIds = ids
|
|
274
|
+
catalogMeta = meta
|
|
275
|
+
catalogPricing = pricingMap
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// Picker seed: the allowlist when one is declared, otherwise just the
|
|
279
|
+
// default model (the operator can type any id — unrestricted). Discovery,
|
|
280
|
+
// once it runs, supersedes this in getFallbackModels via catalogMeta.
|
|
281
|
+
const fallbackModels = Object.freeze(
|
|
282
|
+
(entry.models || [entry.defaultModel]).map((id) =>
|
|
283
|
+
Object.freeze({ id, label: id, fullId: id, contextWindow: entry.contextWindow })),
|
|
284
|
+
)
|
|
285
|
+
|
|
286
|
+
class AnthropicCompatibleSession extends ClaudeByokSession {
|
|
287
|
+
// #5858: NOT Claude-family — config-driven Anthropic-compatible endpoints
|
|
288
|
+
// ride ClaudeByokSession's agent loop but have their own model allowlists,
|
|
289
|
+
// so override the inherited flag to false (validate strictly, never
|
|
290
|
+
// soft-fall-back to claude).
|
|
291
|
+
static claudeFamily = false
|
|
292
|
+
|
|
293
|
+
/** The validated config entry this class was built from (introspection/tests). */
|
|
294
|
+
static get compatEntry() {
|
|
295
|
+
return entry
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
static get displayLabel() {
|
|
299
|
+
return entry.label
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
static get dataDir() {
|
|
303
|
+
// No `~/.claude` dependency — pure HTTP(S) to the configured
|
|
304
|
+
// endpoint. getProviderDataDirs() skips providers that return
|
|
305
|
+
// null (#2965).
|
|
306
|
+
return null
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
static get preflight() {
|
|
310
|
+
return {
|
|
311
|
+
label: entry.label,
|
|
312
|
+
credentials: {
|
|
313
|
+
// Empty envVars (keyless / credentials.json-only entries) →
|
|
314
|
+
// the preflight credential gate is skipped (utils/preflight.js
|
|
315
|
+
// requires envVars.length > 0); a missing file-sourced key
|
|
316
|
+
// still surfaces through start()'s credentials-not-found path.
|
|
317
|
+
envVars: entry.apiKeyEnv ? [entry.apiKeyEnv] : [],
|
|
318
|
+
hint: keyless
|
|
319
|
+
? `no API key required — Anthropic-compatible endpoint at ${entry.baseUrl}`
|
|
320
|
+
: credentialHint(entry),
|
|
321
|
+
optional: keyless,
|
|
322
|
+
},
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* Runtime auth state for the dashboard (#4769). Keyless entries are
|
|
328
|
+
* always ready (local endpoints); keyed entries mirror the DeepSeek
|
|
329
|
+
* flow — env var OR credentials.json, both surfacing as ready with a
|
|
330
|
+
* `detail` that disambiguates the source. The key value itself never
|
|
331
|
+
* appears in the result.
|
|
332
|
+
*
|
|
333
|
+
* @param {NodeJS.ProcessEnv} env
|
|
334
|
+
* @returns {{ready:boolean, source:string, envVar:string|null, envVars:string[], hint:string, detail:string}}
|
|
335
|
+
*/
|
|
336
|
+
static resolveAuth(env) {
|
|
337
|
+
const envVars = entry.apiKeyEnv ? [entry.apiKeyEnv] : []
|
|
338
|
+
if (keyless) {
|
|
339
|
+
return {
|
|
340
|
+
ready: true,
|
|
341
|
+
source: 'env',
|
|
342
|
+
envVar: null,
|
|
343
|
+
envVars,
|
|
344
|
+
hint: '',
|
|
345
|
+
detail: `${entry.label} at ${entry.baseUrl} (no API key configured — config-driven Anthropic-compatible endpoint)`,
|
|
346
|
+
billingClass: BILLING_CLASSES.API_KEY,
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
const envKey = entry.apiKeyEnv ? env[entry.apiKeyEnv] : undefined
|
|
350
|
+
const resolved = typeof envKey === 'string' && envKey.length > 0
|
|
351
|
+
? { key: envKey, source: 'env' }
|
|
352
|
+
: resolveAnthropicCompatibleApiKey(entry)
|
|
353
|
+
if (resolved.key && resolved.key !== COMPAT_PLACEHOLDER_API_KEY) {
|
|
354
|
+
return {
|
|
355
|
+
ready: true,
|
|
356
|
+
source: 'env',
|
|
357
|
+
envVar: resolved.source === 'env' ? entry.apiKeyEnv : null,
|
|
358
|
+
envVars,
|
|
359
|
+
hint: '',
|
|
360
|
+
detail: `${entry.label} at ${entry.baseUrl} (${resolved.source === 'env' ? `${entry.apiKeyEnv} set` : '~/.chroxy/credentials.json'})`,
|
|
361
|
+
billingClass: BILLING_CLASSES.API_KEY,
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
return {
|
|
365
|
+
ready: false,
|
|
366
|
+
source: 'none',
|
|
367
|
+
envVar: null,
|
|
368
|
+
envVars,
|
|
369
|
+
hint: credentialHint(entry),
|
|
370
|
+
detail: `${entry.label} at ${entry.baseUrl} (${resolved.reason})`,
|
|
371
|
+
// Config-driven endpoint billed against your own key — api-key,
|
|
372
|
+
// era-independent.
|
|
373
|
+
billingClass: BILLING_CLASSES.API_KEY,
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
static getFallbackModels() {
|
|
378
|
+
// Once a catalog has been discovered, seed the picker from it (hundreds
|
|
379
|
+
// of models with labels + windows) instead of the static default-only
|
|
380
|
+
// seed. Pre-discovery (cold boot) the static seed keeps the picker
|
|
381
|
+
// useful until the first refresh resolves.
|
|
382
|
+
if (catalogMeta && catalogMeta.size > 0) {
|
|
383
|
+
return Object.freeze(
|
|
384
|
+
[...catalogMeta.entries()].map(([id, m]) =>
|
|
385
|
+
Object.freeze({ id, label: m.label, fullId: id, contextWindow: m.contextWindow })),
|
|
386
|
+
)
|
|
387
|
+
}
|
|
388
|
+
return fallbackModels
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/** The validated modelDiscovery seam for this class (null when absent). */
|
|
392
|
+
static get modelDiscovery() {
|
|
393
|
+
return entry.modelDiscovery
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/**
|
|
397
|
+
* Tri-state model validation source (settings-handlers, #2946/#5418):
|
|
398
|
+
* - discovered catalog present → the discovered ids are the
|
|
399
|
+
* authoritative allowlist (replaces PROVIDER_MODELS_UNRESTRICTED for
|
|
400
|
+
* this entry — the issue's tri-state interplay).
|
|
401
|
+
* - `models` declared (no/empty catalog) → the static array is the
|
|
402
|
+
* authoritative allowlist.
|
|
403
|
+
* - neither → null = unrestricted; any non-empty model id passes
|
|
404
|
+
* through verbatim and an unknown id surfaces as the endpoint's own
|
|
405
|
+
* error (the ollama rule).
|
|
406
|
+
*/
|
|
407
|
+
static getAllowedModels() {
|
|
408
|
+
if (catalogIds && catalogIds.size > 0) return [...catalogIds]
|
|
409
|
+
return entry.models ? [...entry.models] : null
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
static getModelMetadata(modelId) {
|
|
413
|
+
if (typeof modelId !== 'string' || modelId.length === 0) return null
|
|
414
|
+
// Discovered catalog wins: it carries real labels + context windows.
|
|
415
|
+
if (catalogMeta && catalogMeta.size > 0) {
|
|
416
|
+
const hit = catalogMeta.get(modelId)
|
|
417
|
+
if (hit) return { id: modelId, label: hit.label, fullId: modelId, contextWindow: hit.contextWindow }
|
|
418
|
+
// Catalog present but this id isn't in it — unknown model. The picker
|
|
419
|
+
// is now restricted to the catalog (getAllowedModels), so return null
|
|
420
|
+
// the same way a declared-allowlist miss does.
|
|
421
|
+
return null
|
|
422
|
+
}
|
|
423
|
+
if (entry.models) {
|
|
424
|
+
if (!entry.models.includes(modelId)) return null
|
|
425
|
+
return { id: modelId, label: modelId, fullId: modelId, contextWindow: entry.contextWindow }
|
|
426
|
+
}
|
|
427
|
+
// Unrestricted endpoint: any non-empty id is valid metadata. The
|
|
428
|
+
// explicit contextWindow key (possibly null) is load-bearing —
|
|
429
|
+
// models.js preserves an explicit null instead of substituting
|
|
430
|
+
// DEFAULT_CONTEXT_WINDOW, so the dashboard omits the chip rather
|
|
431
|
+
// than showing a fabricated window (#5418 / #5444).
|
|
432
|
+
return { id: modelId, label: modelId, fullId: modelId, contextWindow: entry.contextWindow }
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/**
|
|
436
|
+
* Dynamic model-catalog discovery hook (#5548) — ws-history's generic
|
|
437
|
+
* `scheduleProviderModelsRefresh` calls this (fire-and-forget) whenever it
|
|
438
|
+
* sends `available_models` for this provider, and pushes a refreshed list
|
|
439
|
+
* if discovery changed the registry. No-op (resolves null) when the entry
|
|
440
|
+
* declares no `modelDiscovery`. Never throws, never blocks validation.
|
|
441
|
+
*
|
|
442
|
+
* `deps` is a test seam (fetchFn / now / ttlMs / registry / apiKey).
|
|
443
|
+
*/
|
|
444
|
+
static refreshModels(deps = {}) {
|
|
445
|
+
if (!entry.modelDiscovery) return Promise.resolve(null)
|
|
446
|
+
const apiKey = deps.apiKey !== undefined ? deps.apiKey : resolveDiscoveryApiKey(entry)
|
|
447
|
+
return refreshDiscoveredModels({
|
|
448
|
+
id: entry.id,
|
|
449
|
+
url: entry.modelDiscovery.url,
|
|
450
|
+
format: entry.modelDiscovery.format,
|
|
451
|
+
apiKey,
|
|
452
|
+
registry: deps.registry || getRegistryForProvider(entry.id),
|
|
453
|
+
applyCatalog,
|
|
454
|
+
...deps,
|
|
455
|
+
})
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
/** Test/introspection hook: the discovered per-model pricing snapshot. */
|
|
459
|
+
static get discoveredPricing() {
|
|
460
|
+
return catalogPricing
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
constructor(opts = {}) {
|
|
464
|
+
// Force the registry name so the provider id on this session is
|
|
465
|
+
// always the config entry's id — independent of whatever the
|
|
466
|
+
// embedder passed (mirrors DeepSeekSession / OllamaSession).
|
|
467
|
+
super({ ...opts, provider: entry.id })
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/**
|
|
471
|
+
* #5548: kick off catalog discovery on session start when the entry opts
|
|
472
|
+
* in via `modelDiscovery` — the moment we know the user cares about this
|
|
473
|
+
* endpoint, exactly like OllamaSession.start() probes /api/tags. Fire-and-
|
|
474
|
+
* forget: discovery must never delay or fail session start (byok's start()
|
|
475
|
+
* already emitted 'ready' by the time the probe resolves). On a changed
|
|
476
|
+
* list, emit `models_updated` so the picker refreshes without a restart.
|
|
477
|
+
*/
|
|
478
|
+
async start() {
|
|
479
|
+
await super.start()
|
|
480
|
+
if (!entry.modelDiscovery) return
|
|
481
|
+
AnthropicCompatibleSession.refreshModels()
|
|
482
|
+
.then((models) => {
|
|
483
|
+
if (Array.isArray(models) && models.length > 0) {
|
|
484
|
+
this.emit('models_updated', { models })
|
|
485
|
+
}
|
|
486
|
+
})
|
|
487
|
+
.catch(() => {})
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
// --- Seam overrides (see byok-session.js for the contract) ---
|
|
491
|
+
|
|
492
|
+
get _defaultModel() {
|
|
493
|
+
return entry.defaultModel
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
_resolveCredentials() {
|
|
497
|
+
return resolveAnthropicCompatibleApiKey(entry)
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
_buildClient(apiKey) {
|
|
501
|
+
return new Anthropic({
|
|
502
|
+
apiKey,
|
|
503
|
+
baseURL: entry.baseUrl,
|
|
504
|
+
})
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/**
|
|
508
|
+
* Per-model pricing (#5548). When discovery has populated a per-model
|
|
509
|
+
* table, the model's discovered rates win so OpenRouter sessions report
|
|
510
|
+
* real cost; otherwise fall back to the flat `pricing` block (or honest
|
|
511
|
+
* all-zero for local endpoints). byok-session calls this with the active
|
|
512
|
+
* model id, so cost reflects the specific model in use, not a single flat
|
|
513
|
+
* rate across a catalog of hundreds.
|
|
514
|
+
*/
|
|
515
|
+
_getPricing(model) {
|
|
516
|
+
if (catalogPricing && typeof model === 'string') {
|
|
517
|
+
const hit = catalogPricing.get(model)
|
|
518
|
+
if (hit) return hit
|
|
519
|
+
}
|
|
520
|
+
return flatPricing
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
return AnthropicCompatibleSession
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
/**
|
|
528
|
+
* Resolve the API key to pass on the discovery probe (#5548). OpenRouter's
|
|
529
|
+
* /api/v1/models needs no key, but passing the entry's key is harmless and
|
|
530
|
+
* future-proofs gated aggregators. Returns null (no Authorization header) when
|
|
531
|
+
* unresolved or for the keyless placeholder. Never logged.
|
|
532
|
+
*
|
|
533
|
+
* @param {object} entry - normalized config entry
|
|
534
|
+
* @returns {string|null}
|
|
535
|
+
*/
|
|
536
|
+
function resolveDiscoveryApiKey(entry) {
|
|
537
|
+
if (!entry.apiKeyEnv && !entry.credentialsKey) return null
|
|
538
|
+
const resolved = resolveAnthropicCompatibleApiKey(entry)
|
|
539
|
+
if (resolved.key && resolved.key !== COMPAT_PLACEHOLDER_API_KEY) return resolved.key
|
|
540
|
+
return null
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
/**
|
|
544
|
+
* Register every valid `providers.anthropicCompatible` entry from the
|
|
545
|
+
* merged config as a first-class provider (#5419). Called once at server
|
|
546
|
+
* startup (server-cli.js), before the default-provider resolution so
|
|
547
|
+
* `--provider <id>` can select a config-driven endpoint.
|
|
548
|
+
*
|
|
549
|
+
* Invalid entries are logged and skipped; valid siblings still register.
|
|
550
|
+
* Collisions are checked against both the static RESERVED_PROVIDER_IDS
|
|
551
|
+
* and the LIVE registry at call time.
|
|
552
|
+
*
|
|
553
|
+
* @param {object | null | undefined} config - Merged server config
|
|
554
|
+
* @returns {string[]} The provider ids that were registered
|
|
555
|
+
*/
|
|
556
|
+
export function registerAnthropicCompatibleProviders(config) {
|
|
557
|
+
const block = config?.providers
|
|
558
|
+
// Legacy form: `providers` as an array of provider-id strings
|
|
559
|
+
// (informational, written by `chroxy init`) — nothing to register.
|
|
560
|
+
if (typeof block !== 'object' || block === null || Array.isArray(block)) return []
|
|
561
|
+
if (!Object.prototype.hasOwnProperty.call(block, 'anthropicCompatible')) return []
|
|
562
|
+
|
|
563
|
+
const { entries, warnings } = validateAnthropicCompatibleProviders(block.anthropicCompatible, {
|
|
564
|
+
reservedIds: getRegisteredProviderNames(),
|
|
565
|
+
})
|
|
566
|
+
for (const warning of warnings) {
|
|
567
|
+
log.warn(warning)
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
const registered = []
|
|
571
|
+
for (const entry of entries) {
|
|
572
|
+
registerProvider(entry.id, createAnthropicCompatibleSessionClass(entry))
|
|
573
|
+
registered.push(entry.id)
|
|
574
|
+
log.info(
|
|
575
|
+
`Anthropic-compatible provider registered: ${entry.id} → ${entry.baseUrl} (default model: ${entry.defaultModel}, models: ${entry.models ? entry.models.join(', ') : 'unrestricted'}, key: ${entry.apiKeyEnv || entry.credentialsKey || 'none'})`,
|
|
576
|
+
)
|
|
577
|
+
}
|
|
578
|
+
return registered
|
|
579
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Network glue for the OpenAI-compatible provider (#5420).
|
|
3
|
+
*
|
|
4
|
+
* `ClaudeByokSession` drives `@anthropic-ai/sdk`'s `client.messages.stream(...)`:
|
|
5
|
+
* it passes an Anthropic Messages request, consumes an async iterable of raw SDK
|
|
6
|
+
* events (message_start / content_block_* / message_delta / message_stop), then
|
|
7
|
+
* reads `stream.finalMessage()`. To reach OpenAI-compatible servers (LM Studio,
|
|
8
|
+
* vLLM, llama.cpp, OpenRouter, …) without forking that loop, this shim reproduces
|
|
9
|
+
* that surface but speaks OpenAI chat-completions underneath.
|
|
10
|
+
*
|
|
11
|
+
* The pure translation (request shape + the streaming-chunk fold into Anthropic
|
|
12
|
+
* SDK events + the final Message) lives in anthropic-openai-translate.js (#6127).
|
|
13
|
+
* This module is the thin I/O layer: it imports `openai`, awaits the SSE
|
|
14
|
+
* iterator, feeds each chunk through `createStreamTranslator()`, and exposes the
|
|
15
|
+
* async-iterable + `.finalMessage()` the byok loop expects. Keeping it this thin
|
|
16
|
+
* means the translation stays fixture-testable with no live endpoint, and this
|
|
17
|
+
* file is exercised with a MOCKED `openai` package (no network).
|
|
18
|
+
*
|
|
19
|
+
* The emitted event objects match the RAW Anthropic SDK shapes that
|
|
20
|
+
* byok-event-translator.js switches on — that file is the contract.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import OpenAI from 'openai'
|
|
24
|
+
import { anthropicRequestToOpenAi, createStreamTranslator } from './anthropic-openai-translate.js'
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Build a minimal Anthropic-SDK-shaped client backed by an OpenAI-compatible
|
|
28
|
+
* chat-completions endpoint.
|
|
29
|
+
*
|
|
30
|
+
* Returns `{ messages: { stream(params, opts) } }` where `stream` mirrors
|
|
31
|
+
* `@anthropic-ai/sdk`'s `messages.stream`: it returns an object that is
|
|
32
|
+
* async-iterable over the translated Anthropic SDK events AND exposes
|
|
33
|
+
* `finalMessage()` resolving to the assembled final Message
|
|
34
|
+
* (`{ id, type, role, model, content, stop_reason, stop_sequence, usage }`).
|
|
35
|
+
*
|
|
36
|
+
* @param {{ baseURL: string, apiKey: string }} cfg
|
|
37
|
+
* @returns {{ messages: { stream: (params: object, opts?: { signal?: AbortSignal }) => object } }}
|
|
38
|
+
*/
|
|
39
|
+
export function createAnthropicShimClient({ baseURL, apiKey }) {
|
|
40
|
+
const client = new OpenAI({ baseURL, apiKey })
|
|
41
|
+
|
|
42
|
+
return {
|
|
43
|
+
messages: {
|
|
44
|
+
stream(params = {}, opts = {}) {
|
|
45
|
+
return createShimStream(client, params, opts)
|
|
46
|
+
},
|
|
47
|
+
},
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* The async-iterable + finalMessage object returned by `messages.stream`.
|
|
53
|
+
*
|
|
54
|
+
* Iteration is single-pass: it opens the OpenAI stream lazily on the first
|
|
55
|
+
* iteration, folds each chunk through the translator (yielding Anthropic events),
|
|
56
|
+
* then flushes the translator's trailing events on stream end. The assembled
|
|
57
|
+
* final Message is captured during iteration so `finalMessage()` resolves once
|
|
58
|
+
* iteration completes (the byok loop always fully iterates before awaiting it).
|
|
59
|
+
*
|
|
60
|
+
* @param {object} client - the OpenAI client
|
|
61
|
+
* @param {object} params - Anthropic Messages params
|
|
62
|
+
* @param {{ signal?: AbortSignal }} opts
|
|
63
|
+
*/
|
|
64
|
+
function createShimStream(client, params, opts) {
|
|
65
|
+
const signal = opts?.signal
|
|
66
|
+
const translator = createStreamTranslator()
|
|
67
|
+
let finalMessage = null
|
|
68
|
+
|
|
69
|
+
async function* iterate() {
|
|
70
|
+
const request = {
|
|
71
|
+
...anthropicRequestToOpenAi(params),
|
|
72
|
+
stream: true,
|
|
73
|
+
// Ask for usage on the final chunk where the server supports it
|
|
74
|
+
// (OpenAI / vLLM / many proxies); mapUsage defaults to zero otherwise.
|
|
75
|
+
stream_options: { include_usage: true },
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const openaiStream = await client.chat.completions.create(request, { signal })
|
|
79
|
+
|
|
80
|
+
for await (const chunk of openaiStream) {
|
|
81
|
+
for (const event of translator.push(chunk)) yield event
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const { events, finalMessage: assembled } = translator.finish()
|
|
85
|
+
finalMessage = assembled
|
|
86
|
+
for (const event of events) yield event
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const iterable = iterate()
|
|
90
|
+
|
|
91
|
+
return {
|
|
92
|
+
[Symbol.asyncIterator]() {
|
|
93
|
+
return iterable
|
|
94
|
+
},
|
|
95
|
+
async finalMessage() {
|
|
96
|
+
// The byok loop fully drains the iterator before calling this, so the
|
|
97
|
+
// translator has already been finished and `finalMessage` is populated.
|
|
98
|
+
// Guard defensively: if a caller asks early, drain the remaining events
|
|
99
|
+
// (discarding them) so `finish()` runs and the message is assembled.
|
|
100
|
+
if (finalMessage === null) {
|
|
101
|
+
// Drain remaining events so the generator runs finish() and assembles
|
|
102
|
+
// the message (the events themselves are discarded on this path).
|
|
103
|
+
// eslint-disable-next-line no-unused-vars
|
|
104
|
+
for await (const _event of iterable) { /* drain */ }
|
|
105
|
+
}
|
|
106
|
+
return finalMessage
|
|
107
|
+
},
|
|
108
|
+
}
|
|
109
|
+
}
|