@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,377 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure translation between the Anthropic Messages API shapes and the OpenAI
|
|
3
|
+
* Chat Completions API shapes (#5420, option 1 — the AnthropicShimClient core).
|
|
4
|
+
*
|
|
5
|
+
* `ClaudeByokSession` drives `@anthropic-ai/sdk`'s `client.messages.stream(...)`:
|
|
6
|
+
* it sends an Anthropic request and consumes an async iterable of raw SDK events
|
|
7
|
+
* (message_start / content_block_start / content_block_delta / content_block_stop
|
|
8
|
+
* / message_delta / message_stop), then reads `stream.finalMessage()`. To reach
|
|
9
|
+
* OpenAI-compatible servers (LM Studio, vLLM, llama.cpp, OpenRouter, …) without
|
|
10
|
+
* forking that loop, a shim reproduces the SDK surface but speaks chat-completions
|
|
11
|
+
* underneath. THIS module is the pure, side-effect-free heart of that shim:
|
|
12
|
+
*
|
|
13
|
+
* - `anthropicRequestToOpenAi(params)` — request shape translation.
|
|
14
|
+
* - `createStreamTranslator()` — fold OpenAI streaming chunks into the
|
|
15
|
+
* Anthropic SDK event sequence + a final
|
|
16
|
+
* Message (`{stop_reason, content, usage}`).
|
|
17
|
+
*
|
|
18
|
+
* Keeping it pure means the whole translation is fixture-testable against recorded
|
|
19
|
+
* OpenAI chunk sequences with no `openai` dependency and no live endpoint — the
|
|
20
|
+
* network glue (importing `openai`, awaiting the SSE iterator) is a thin separate
|
|
21
|
+
* layer. Live-endpoint fidelity (the #5420 spike: tool streaming, parallel tool
|
|
22
|
+
* calls, usage accounting against real servers) is verified separately.
|
|
23
|
+
*
|
|
24
|
+
* The emitted event objects match the RAW Anthropic SDK shapes that
|
|
25
|
+
* `byok-event-translator.js` switches on — that file is the contract this
|
|
26
|
+
* module's output must satisfy.
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
// ---------------------------------------------------------------------------
|
|
30
|
+
// Request: Anthropic Messages params → OpenAI Chat Completions params
|
|
31
|
+
// ---------------------------------------------------------------------------
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Map Anthropic content (string | block[]) to an OpenAI message `content` /
|
|
35
|
+
* `tool_calls`. Anthropic packs tool results and tool calls INTO the message
|
|
36
|
+
* content array; OpenAI splits them across roles, so a single Anthropic message
|
|
37
|
+
* can fan out into several OpenAI messages. This returns the pieces for one
|
|
38
|
+
* Anthropic message so the caller can flatten.
|
|
39
|
+
*/
|
|
40
|
+
function anthropicMessageToOpenAi(msg) {
|
|
41
|
+
const { role, content } = msg
|
|
42
|
+
// Plain string content → a single same-role message.
|
|
43
|
+
if (typeof content === 'string') {
|
|
44
|
+
return [{ role, content }]
|
|
45
|
+
}
|
|
46
|
+
if (!Array.isArray(content)) {
|
|
47
|
+
return [{ role, content: '' }]
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const textParts = content
|
|
51
|
+
.filter((b) => b?.type === 'text' && typeof b.text === 'string')
|
|
52
|
+
.map((b) => b.text)
|
|
53
|
+
|
|
54
|
+
// Tool RESULT blocks (carried on a 'user' message in Anthropic) become
|
|
55
|
+
// standalone OpenAI 'tool' messages keyed by tool_call_id. A user turn may
|
|
56
|
+
// ALSO carry sibling text blocks alongside the results — byok-session's
|
|
57
|
+
// MAX_TOOL_ROUNDS path builds exactly such a `[tool_result…, text]` turn (the
|
|
58
|
+
// "summarise, do not call tools" instruction). OpenAI has no text channel on a
|
|
59
|
+
// `tool` message, so append the text as a following `user` message rather than
|
|
60
|
+
// dropping it (#6128).
|
|
61
|
+
const toolResults = content.filter((b) => b?.type === 'tool_result')
|
|
62
|
+
if (toolResults.length > 0) {
|
|
63
|
+
const msgs = toolResults.map((b) => ({
|
|
64
|
+
role: 'tool',
|
|
65
|
+
tool_call_id: b.tool_use_id,
|
|
66
|
+
content: toolResultContentToString(b.content),
|
|
67
|
+
}))
|
|
68
|
+
if (textParts.length > 0) msgs.push({ role: 'user', content: textParts.join('') })
|
|
69
|
+
return msgs
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Assistant tool_use blocks → OpenAI assistant message with tool_calls.
|
|
73
|
+
const toolUses = content.filter((b) => b?.type === 'tool_use')
|
|
74
|
+
if (toolUses.length > 0) {
|
|
75
|
+
return [
|
|
76
|
+
{
|
|
77
|
+
role: 'assistant',
|
|
78
|
+
content: textParts.length > 0 ? textParts.join('') : null,
|
|
79
|
+
tool_calls: toolUses.map((b) => ({
|
|
80
|
+
id: b.id,
|
|
81
|
+
type: 'function',
|
|
82
|
+
function: { name: b.name, arguments: JSON.stringify(b.input ?? {}) },
|
|
83
|
+
})),
|
|
84
|
+
},
|
|
85
|
+
]
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Otherwise: concatenate text blocks into a single same-role message.
|
|
89
|
+
return [{ role, content: textParts.join('') }]
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Anthropic tool_result `content` is string | block[]; OpenAI wants a string. */
|
|
93
|
+
function toolResultContentToString(content) {
|
|
94
|
+
if (typeof content === 'string') return content
|
|
95
|
+
if (Array.isArray(content)) {
|
|
96
|
+
return content
|
|
97
|
+
.map((b) => (typeof b === 'string' ? b : typeof b?.text === 'string' ? b.text : ''))
|
|
98
|
+
.join('')
|
|
99
|
+
}
|
|
100
|
+
return ''
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Translate an Anthropic `messages.create/stream` params object to an OpenAI
|
|
105
|
+
* `chat.completions.create` params object. `stream`/`stream_options` are set by
|
|
106
|
+
* the caller (the shim always streams); everything else is shape translation.
|
|
107
|
+
*/
|
|
108
|
+
export function anthropicRequestToOpenAi(params = {}) {
|
|
109
|
+
const out = {
|
|
110
|
+
model: params.model,
|
|
111
|
+
// OpenAI uses max_tokens (deprecated) / max_completion_tokens; max_tokens is
|
|
112
|
+
// the broadly-compatible field across LM Studio / vLLM / llama.cpp / OpenRouter.
|
|
113
|
+
max_tokens: params.max_tokens,
|
|
114
|
+
messages: [],
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// Anthropic carries the system prompt as a top-level string; OpenAI wants a
|
|
118
|
+
// leading system-role message.
|
|
119
|
+
if (typeof params.system === 'string' && params.system.length > 0) {
|
|
120
|
+
out.messages.push({ role: 'system', content: params.system })
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
for (const msg of params.messages || []) {
|
|
124
|
+
for (const m of anthropicMessageToOpenAi(msg)) out.messages.push(m)
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
if (Array.isArray(params.tools) && params.tools.length > 0) {
|
|
128
|
+
out.tools = params.tools.map((t) => ({
|
|
129
|
+
type: 'function',
|
|
130
|
+
function: {
|
|
131
|
+
name: t.name,
|
|
132
|
+
description: t.description,
|
|
133
|
+
// Anthropic calls it input_schema; OpenAI calls it parameters.
|
|
134
|
+
parameters: t.input_schema ?? { type: 'object', properties: {} },
|
|
135
|
+
},
|
|
136
|
+
}))
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
if (params.tool_choice) out.tool_choice = mapToolChoice(params.tool_choice)
|
|
140
|
+
if (typeof params.temperature === 'number') out.temperature = params.temperature
|
|
141
|
+
return out
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Anthropic tool_choice → OpenAI tool_choice. */
|
|
145
|
+
function mapToolChoice(tc) {
|
|
146
|
+
if (!tc || typeof tc !== 'object') return undefined
|
|
147
|
+
if (tc.type === 'auto') return 'auto'
|
|
148
|
+
if (tc.type === 'any') return 'required'
|
|
149
|
+
if (tc.type === 'tool' && typeof tc.name === 'string') {
|
|
150
|
+
return { type: 'function', function: { name: tc.name } }
|
|
151
|
+
}
|
|
152
|
+
return undefined
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// ---------------------------------------------------------------------------
|
|
156
|
+
// Response: OpenAI streaming chunks → Anthropic SDK event sequence
|
|
157
|
+
// ---------------------------------------------------------------------------
|
|
158
|
+
|
|
159
|
+
/** OpenAI finish_reason → Anthropic stop_reason. */
|
|
160
|
+
export function mapFinishReason(reason) {
|
|
161
|
+
switch (reason) {
|
|
162
|
+
case 'stop':
|
|
163
|
+
return 'end_turn'
|
|
164
|
+
case 'tool_calls':
|
|
165
|
+
case 'function_call':
|
|
166
|
+
return 'tool_use'
|
|
167
|
+
case 'length':
|
|
168
|
+
return 'max_tokens'
|
|
169
|
+
case 'content_filter':
|
|
170
|
+
return 'stop_sequence'
|
|
171
|
+
default:
|
|
172
|
+
return reason ? 'end_turn' : null
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** OpenAI usage → Anthropic usage (no cache tokens in OpenAI; default 0). */
|
|
177
|
+
export function mapUsage(usage) {
|
|
178
|
+
if (!usage || typeof usage !== 'object') {
|
|
179
|
+
return { input_tokens: 0, output_tokens: 0, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 }
|
|
180
|
+
}
|
|
181
|
+
return {
|
|
182
|
+
input_tokens: Number(usage.prompt_tokens) || 0,
|
|
183
|
+
output_tokens: Number(usage.completion_tokens) || 0,
|
|
184
|
+
cache_read_input_tokens: Number(usage.prompt_tokens_details?.cached_tokens) || 0,
|
|
185
|
+
cache_creation_input_tokens: 0,
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Stateful (but I/O-free) fold of an OpenAI chat-completions STREAM into the
|
|
191
|
+
* Anthropic SDK event sequence the byok loop consumes, plus the final Message.
|
|
192
|
+
*
|
|
193
|
+
* OpenAI streams one `choices[0].delta` per chunk: `delta.content` (text) and/or
|
|
194
|
+
* `delta.tool_calls[]` (each with a stable `index`, an `id`+`function.name` on
|
|
195
|
+
* first appearance, and `function.arguments` fragments thereafter). Anthropic
|
|
196
|
+
* instead opens a content BLOCK (content_block_start) per text run / tool_use,
|
|
197
|
+
* streams deltas into it, and closes it (content_block_stop) — so this translator
|
|
198
|
+
* assigns Anthropic block indices and tracks which OpenAI tool_call index maps to
|
|
199
|
+
* which block.
|
|
200
|
+
*
|
|
201
|
+
* Usage:
|
|
202
|
+
* const tr = createStreamTranslator()
|
|
203
|
+
* for (const chunk of openaiChunks) emit(...tr.push(chunk)) // Anthropic events
|
|
204
|
+
* const { events, finalMessage } = tr.finish() // trailing events + final
|
|
205
|
+
*
|
|
206
|
+
* `push` returns the events to emit for that chunk (possibly empty); `finish`
|
|
207
|
+
* returns any trailing close events plus the assembled final Message.
|
|
208
|
+
*/
|
|
209
|
+
export function createStreamTranslator() {
|
|
210
|
+
let started = false
|
|
211
|
+
let nextBlockIndex = 0
|
|
212
|
+
// Text block: opened lazily on the first text delta, closed when a tool call
|
|
213
|
+
// starts or the stream ends.
|
|
214
|
+
let textBlock = null // { index, text }
|
|
215
|
+
// OpenAI tool_call index -> { blockIndex, id, name, args }
|
|
216
|
+
const toolCalls = new Map()
|
|
217
|
+
// Anthropic content-block order, for finalMessage.content assembly.
|
|
218
|
+
const order = [] // { type: 'text'|'tool_use', ref }
|
|
219
|
+
let stopReason = null
|
|
220
|
+
let usage = null
|
|
221
|
+
let model = null
|
|
222
|
+
let messageId = null
|
|
223
|
+
|
|
224
|
+
function ensureStarted(chunk) {
|
|
225
|
+
if (started) return []
|
|
226
|
+
started = true
|
|
227
|
+
model = chunk?.model ?? null
|
|
228
|
+
messageId = chunk?.id ?? null
|
|
229
|
+
return [{ type: 'message_start', message: { id: messageId, model, role: 'assistant', content: [], usage: mapUsage(null) } }]
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function closeTextBlock() {
|
|
233
|
+
if (!textBlock) return []
|
|
234
|
+
const ev = [{ type: 'content_block_stop', index: textBlock.index }]
|
|
235
|
+
textBlock = null
|
|
236
|
+
return ev
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function push(chunk) {
|
|
240
|
+
const events = []
|
|
241
|
+
if (!chunk || typeof chunk !== 'object') return events
|
|
242
|
+
events.push(...ensureStarted(chunk))
|
|
243
|
+
|
|
244
|
+
// Usage can ride on any chunk (final chunk when stream_options.include_usage),
|
|
245
|
+
// and some servers send a usage-only trailing chunk with empty choices.
|
|
246
|
+
if (chunk.usage) usage = chunk.usage
|
|
247
|
+
|
|
248
|
+
const choice = Array.isArray(chunk.choices) ? chunk.choices[0] : undefined
|
|
249
|
+
if (!choice) return events
|
|
250
|
+
const delta = choice.delta || {}
|
|
251
|
+
|
|
252
|
+
// Text delta → open a text block if needed, then stream into it.
|
|
253
|
+
if (typeof delta.content === 'string' && delta.content.length > 0) {
|
|
254
|
+
if (!textBlock) {
|
|
255
|
+
textBlock = { index: nextBlockIndex++, text: '' }
|
|
256
|
+
order.push({ type: 'text', ref: textBlock })
|
|
257
|
+
events.push({ type: 'content_block_start', index: textBlock.index, content_block: { type: 'text', text: '' } })
|
|
258
|
+
}
|
|
259
|
+
textBlock.text += delta.content
|
|
260
|
+
events.push({ type: 'content_block_delta', index: textBlock.index, delta: { type: 'text_delta', text: delta.content } })
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// Tool-call deltas. The block is NOT opened until BOTH id and name are
|
|
264
|
+
// known: a conformant OpenAI server sends them in the first tool_call delta,
|
|
265
|
+
// but a non-standard one (this module's whole point) may split them across
|
|
266
|
+
// chunks — emitting content_block_start eagerly would bake wrong/empty
|
|
267
|
+
// id/name into the streamed tool_start (dashboard label + any id-keyed
|
|
268
|
+
// correlation). So buffer args until we can start, then flush them. #6128.
|
|
269
|
+
if (Array.isArray(delta.tool_calls)) {
|
|
270
|
+
for (const tc of delta.tool_calls) {
|
|
271
|
+
const oaIndex = typeof tc.index === 'number' ? tc.index : 0
|
|
272
|
+
let entry = toolCalls.get(oaIndex)
|
|
273
|
+
if (!entry) {
|
|
274
|
+
entry = { blockIndex: null, id: tc.id || '', name: tc.function?.name || '', args: '', started: false, emittedLen: 0 }
|
|
275
|
+
toolCalls.set(oaIndex, entry)
|
|
276
|
+
order.push({ type: 'tool_use', ref: entry })
|
|
277
|
+
} else {
|
|
278
|
+
if (!entry.id && tc.id) entry.id = tc.id
|
|
279
|
+
if (!entry.name && tc.function?.name) entry.name = tc.function.name
|
|
280
|
+
}
|
|
281
|
+
const argFragment = tc.function?.arguments
|
|
282
|
+
if (typeof argFragment === 'string') entry.args += argFragment
|
|
283
|
+
events.push(...maybeStartToolBlock(entry))
|
|
284
|
+
events.push(...flushToolArgs(entry))
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
if (choice.finish_reason) stopReason = mapFinishReason(choice.finish_reason)
|
|
289
|
+
return events
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Open the tool_use block once id+name are known (close any open text block
|
|
294
|
+
* first — Anthropic blocks don't overlap). No-op until then, or once started.
|
|
295
|
+
*/
|
|
296
|
+
function maybeStartToolBlock(entry) {
|
|
297
|
+
if (entry.started || !entry.id || !entry.name) return []
|
|
298
|
+
const events = closeTextBlock()
|
|
299
|
+
entry.blockIndex = nextBlockIndex++
|
|
300
|
+
entry.started = true
|
|
301
|
+
events.push({
|
|
302
|
+
type: 'content_block_start',
|
|
303
|
+
index: entry.blockIndex,
|
|
304
|
+
content_block: { type: 'tool_use', id: entry.id, name: entry.name, input: {} },
|
|
305
|
+
})
|
|
306
|
+
return events
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** Emit any buffered tool-arg JSON not yet streamed (only once started). */
|
|
310
|
+
function flushToolArgs(entry) {
|
|
311
|
+
if (!entry.started || entry.args.length <= entry.emittedLen) return []
|
|
312
|
+
const pending = entry.args.slice(entry.emittedLen)
|
|
313
|
+
entry.emittedLen = entry.args.length
|
|
314
|
+
return [{ type: 'content_block_delta', index: entry.blockIndex, delta: { type: 'input_json_delta', partial_json: pending } }]
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
function finish() {
|
|
318
|
+
const events = []
|
|
319
|
+
// A tool_call that never received both id+name (non-conformant server) is
|
|
320
|
+
// force-started now so its block + accumulated args still surface.
|
|
321
|
+
for (const entry of toolCalls.values()) {
|
|
322
|
+
if (!entry.started) {
|
|
323
|
+
events.push(...closeTextBlock())
|
|
324
|
+
entry.blockIndex = nextBlockIndex++
|
|
325
|
+
entry.started = true
|
|
326
|
+
events.push({
|
|
327
|
+
type: 'content_block_start',
|
|
328
|
+
index: entry.blockIndex,
|
|
329
|
+
content_block: { type: 'tool_use', id: entry.id, name: entry.name, input: {} },
|
|
330
|
+
})
|
|
331
|
+
events.push(...flushToolArgs(entry))
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
// Close any still-open blocks (text, then each tool block in order).
|
|
335
|
+
events.push(...closeTextBlock())
|
|
336
|
+
for (const entry of toolCalls.values()) {
|
|
337
|
+
events.push({ type: 'content_block_stop', index: entry.blockIndex })
|
|
338
|
+
}
|
|
339
|
+
const finalUsage = mapUsage(usage)
|
|
340
|
+
// Resolve the stop_reason ONCE: if the server omitted finish_reason but the
|
|
341
|
+
// model emitted tool calls, infer tool_use so the byok loop runs the tools.
|
|
342
|
+
// Both message_delta and finalMessage carry this same value (no drift).
|
|
343
|
+
const effectiveStopReason = stopReason ?? (toolCalls.size > 0 ? 'tool_use' : 'end_turn')
|
|
344
|
+
events.push({ type: 'message_delta', delta: { stop_reason: effectiveStopReason }, usage: finalUsage })
|
|
345
|
+
events.push({ type: 'message_stop' })
|
|
346
|
+
|
|
347
|
+
const content = order.map((o) =>
|
|
348
|
+
o.type === 'text'
|
|
349
|
+
? { type: 'text', text: o.ref.text }
|
|
350
|
+
: { type: 'tool_use', id: o.ref.id, name: o.ref.name, input: safeParseJson(o.ref.args) },
|
|
351
|
+
)
|
|
352
|
+
const finalMessage = {
|
|
353
|
+
id: messageId,
|
|
354
|
+
type: 'message',
|
|
355
|
+
role: 'assistant',
|
|
356
|
+
model,
|
|
357
|
+
content,
|
|
358
|
+
stop_reason: effectiveStopReason,
|
|
359
|
+
stop_sequence: null,
|
|
360
|
+
usage: finalUsage,
|
|
361
|
+
}
|
|
362
|
+
return { events, finalMessage }
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
return { push, finish }
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/** Parse accumulated tool-arguments JSON; empty/invalid → {} (never throw). */
|
|
369
|
+
function safeParseJson(s) {
|
|
370
|
+
if (typeof s !== 'string' || s.trim() === '') return {}
|
|
371
|
+
try {
|
|
372
|
+
const v = JSON.parse(s)
|
|
373
|
+
return v && typeof v === 'object' ? v : {}
|
|
374
|
+
} catch {
|
|
375
|
+
return {}
|
|
376
|
+
}
|
|
377
|
+
}
|
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared on-disk credential probes and short-lived caching for the per-provider
|
|
3
|
+
* `static resolveAuth(env)` methods (#4769).
|
|
4
|
+
*
|
|
5
|
+
* Each provider class declares its own auth resolution strategy in
|
|
6
|
+
* `static resolveAuth(env, helpers)` so the dispatcher in providers.js no
|
|
7
|
+
* longer has to switch on a provider name string. The helpers below are the
|
|
8
|
+
* pieces that need to be shared:
|
|
9
|
+
*
|
|
10
|
+
* - `hasClaudeOAuthCreds()` / `hasCodexOAuthCreds()` / `hasGeminiOAuthCreds()`:
|
|
11
|
+
* 5s-TTL cached existence checks for the OAuth files written by the
|
|
12
|
+
* respective `claude login` / `codex login` / `gemini login` flows.
|
|
13
|
+
* - `cachedResolveCredentialFile(slot, envValue, resolve, envVarName)`:
|
|
14
|
+
* mtime+size+mode keyed cache around the BYOK / DeepSeek
|
|
15
|
+
* `~/.chroxy/credentials.json` resolvers — repeats reuse the parsed
|
|
16
|
+
* resolver result so the dashboard's list_providers poll doesn't re-read
|
|
17
|
+
* and re-JSON.parse the file on every call. Slots beyond the fixed
|
|
18
|
+
* byok/deepseek/discord trio are created lazily (#5461) so config-driven
|
|
19
|
+
* Anthropic-compatible entries can route their resolveAuth file reads
|
|
20
|
+
* through the same cache (one `compat:` slot per entry credential spec).
|
|
21
|
+
* - `resetCachesForTest()`: drops both caches so tests can isolate runs
|
|
22
|
+
* under temporary `CHROXY_*_HOME` overrides without flakiness.
|
|
23
|
+
*
|
|
24
|
+
* History: these helpers used to live as private (`_`-prefixed) functions
|
|
25
|
+
* inside providers.js. They are not changed semantically by this extraction —
|
|
26
|
+
* the cache keys, TTLs, and probe details are byte-for-byte identical to the
|
|
27
|
+
* pre-#4769 originals. See the prior comments in providers.js for the
|
|
28
|
+
* file-by-file rationale.
|
|
29
|
+
*/
|
|
30
|
+
import { existsSync, readFileSync, statSync } from 'fs'
|
|
31
|
+
import { join } from 'path'
|
|
32
|
+
import { homedir } from 'os'
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Best-effort probe for `claude login` OAuth state on disk (#3674).
|
|
36
|
+
*
|
|
37
|
+
* Different versions of the Claude Agent SDK and Claude Code CLI cache
|
|
38
|
+
* subscription credentials in different files; we cover the three known
|
|
39
|
+
* locations and return true if any of them looks plausibly populated:
|
|
40
|
+
*
|
|
41
|
+
* 1. `~/.claude/auth.json` — current SDK auth file
|
|
42
|
+
* 2. `~/.claude/.credentials.json` — older Claude Code CLI keystore
|
|
43
|
+
* 3. `~/.claude.json` — global config; contains a
|
|
44
|
+
* `claudeAiOauth` block when the
|
|
45
|
+
* user has logged in via subscription
|
|
46
|
+
*
|
|
47
|
+
* Override paths for tests / atypical installs:
|
|
48
|
+
* - `CHROXY_CLAUDE_HOME` — overrides the directory for the first two
|
|
49
|
+
* file checks AND the default location of
|
|
50
|
+
* `.claude.json` (one level up from this dir).
|
|
51
|
+
* - `CHROXY_CLAUDE_CONFIG` — overrides the global `.claude.json` path
|
|
52
|
+
* directly. Wins over the `CHROXY_CLAUDE_HOME`-
|
|
53
|
+
* derived default when both are set.
|
|
54
|
+
*/
|
|
55
|
+
function probeClaudeOAuthCreds() {
|
|
56
|
+
try {
|
|
57
|
+
const claudeHome = process.env.CHROXY_CLAUDE_HOME || join(homedir(), '.claude')
|
|
58
|
+
if (existsSync(join(claudeHome, 'auth.json'))) return true
|
|
59
|
+
if (existsSync(join(claudeHome, '.credentials.json'))) return true
|
|
60
|
+
const globalConfig = process.env.CHROXY_CLAUDE_CONFIG
|
|
61
|
+
|| (process.env.CHROXY_CLAUDE_HOME
|
|
62
|
+
? join(process.env.CHROXY_CLAUDE_HOME, '..', '.claude.json')
|
|
63
|
+
: join(homedir(), '.claude.json'))
|
|
64
|
+
if (existsSync(globalConfig)) {
|
|
65
|
+
try {
|
|
66
|
+
const parsed = JSON.parse(readFileSync(globalConfig, 'utf-8'))
|
|
67
|
+
if (parsed && typeof parsed === 'object' && parsed.claudeAiOauth) {
|
|
68
|
+
return true
|
|
69
|
+
}
|
|
70
|
+
} catch {
|
|
71
|
+
// Malformed JSON — treat as absent.
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
} catch {
|
|
75
|
+
// Any unexpected fs error → behave as if no creds.
|
|
76
|
+
}
|
|
77
|
+
return false
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Best-effort probe for `codex login` OAuth state on disk (#4301).
|
|
82
|
+
*
|
|
83
|
+
* Override path for tests / atypical installs:
|
|
84
|
+
* - `CHROXY_CODEX_HOME` — overrides the directory used to locate auth.json
|
|
85
|
+
*/
|
|
86
|
+
function probeCodexOAuthCreds() {
|
|
87
|
+
try {
|
|
88
|
+
const codexHome = process.env.CHROXY_CODEX_HOME || join(homedir(), '.codex')
|
|
89
|
+
const authPath = join(codexHome, 'auth.json')
|
|
90
|
+
if (!existsSync(authPath)) return false
|
|
91
|
+
try {
|
|
92
|
+
const parsed = JSON.parse(readFileSync(authPath, 'utf-8'))
|
|
93
|
+
if (!parsed || typeof parsed !== 'object') return false
|
|
94
|
+
if (parsed.tokens && typeof parsed.tokens === 'object') {
|
|
95
|
+
const t = parsed.tokens
|
|
96
|
+
if (typeof t.access_token === 'string' && t.access_token.length > 0) return true
|
|
97
|
+
if (typeof t.refresh_token === 'string' && t.refresh_token.length > 0) return true
|
|
98
|
+
if (typeof t.id_token === 'string' && t.id_token.length > 0) return true
|
|
99
|
+
}
|
|
100
|
+
if (typeof parsed.OPENAI_API_KEY === 'string' && parsed.OPENAI_API_KEY.length > 0) {
|
|
101
|
+
return true
|
|
102
|
+
}
|
|
103
|
+
} catch {
|
|
104
|
+
// Malformed JSON — treat as absent.
|
|
105
|
+
}
|
|
106
|
+
} catch {
|
|
107
|
+
// Any unexpected fs error → behave as if no creds.
|
|
108
|
+
}
|
|
109
|
+
return false
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Best-effort probe for `gemini login` OAuth state on disk (#4301).
|
|
114
|
+
*
|
|
115
|
+
* Override path for tests / atypical installs:
|
|
116
|
+
* - `CHROXY_GEMINI_HOME` — overrides the directory used for the lookups
|
|
117
|
+
*/
|
|
118
|
+
function probeGeminiOAuthCreds() {
|
|
119
|
+
try {
|
|
120
|
+
const geminiHome = process.env.CHROXY_GEMINI_HOME || join(homedir(), '.gemini')
|
|
121
|
+
if (existsSync(join(geminiHome, 'oauth_creds.json'))) return true
|
|
122
|
+
if (existsSync(join(geminiHome, 'google_accounts.json'))) return true
|
|
123
|
+
} catch {
|
|
124
|
+
// Any unexpected fs error → behave as if no creds.
|
|
125
|
+
}
|
|
126
|
+
return false
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* 5s TTL cache around the on-disk creds probes (#3678).
|
|
131
|
+
*
|
|
132
|
+
* `listProviders()` is called from `handleListProviders` on every dashboard
|
|
133
|
+
* `list_providers` WS request and once per `auth_ok` from `ws-history.js`.
|
|
134
|
+
* The cache is keyed on the override env vars so a test (or a runtime tweak)
|
|
135
|
+
* that changes any of the `CHROXY_*_HOME` variables naturally invalidates the
|
|
136
|
+
* previous result.
|
|
137
|
+
*/
|
|
138
|
+
let _credsCache = {
|
|
139
|
+
claude: { value: null, expiresAt: 0, key: null },
|
|
140
|
+
codex: { value: null, expiresAt: 0, key: null },
|
|
141
|
+
gemini: { value: null, expiresAt: 0, key: null },
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function _cachedProbe(slot, key, probe) {
|
|
145
|
+
const now = Date.now()
|
|
146
|
+
const entry = _credsCache[slot]
|
|
147
|
+
if (entry.key === key && entry.expiresAt > now) {
|
|
148
|
+
return entry.value
|
|
149
|
+
}
|
|
150
|
+
const value = probe()
|
|
151
|
+
_credsCache[slot] = { value, expiresAt: now + 5_000, key }
|
|
152
|
+
return value
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export function hasClaudeOAuthCreds() {
|
|
156
|
+
const key = `${process.env.CHROXY_CLAUDE_HOME ?? ''}|${process.env.CHROXY_CLAUDE_CONFIG ?? ''}`
|
|
157
|
+
return _cachedProbe('claude', key, probeClaudeOAuthCreds)
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export function hasCodexOAuthCreds() {
|
|
161
|
+
const key = `${process.env.CHROXY_CODEX_HOME ?? ''}`
|
|
162
|
+
return _cachedProbe('codex', key, probeCodexOAuthCreds)
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export function hasGeminiOAuthCreds() {
|
|
166
|
+
const key = `${process.env.CHROXY_GEMINI_HOME ?? ''}`
|
|
167
|
+
return _cachedProbe('gemini', key, probeGeminiOAuthCreds)
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* mtime+size+mode keyed cache for the BYOK + DeepSeek credential file reads
|
|
172
|
+
* (#4658, #4728). See providers.js' previous header for the long-form
|
|
173
|
+
* rationale — moved verbatim here without behavioural changes.
|
|
174
|
+
*/
|
|
175
|
+
let _credFileCache = {
|
|
176
|
+
byok: { envValue: null, path: null, mtimeMs: null, size: null, mode: null, result: null },
|
|
177
|
+
deepseek: { envValue: null, path: null, mtimeMs: null, size: null, mode: null, result: null },
|
|
178
|
+
// #5427: Discord webhook URL — same credentials.json, different key. The
|
|
179
|
+
// sink's isConfigured() is probed on every notification, so the resolver
|
|
180
|
+
// must not re-stat/re-parse the file per probe.
|
|
181
|
+
discord: { envValue: null, path: null, mtimeMs: null, size: null, mode: null, result: null },
|
|
182
|
+
// #5461: config-driven Anthropic-compatible entries add dynamic
|
|
183
|
+
// `compat:<JSON [apiKeyEnv, credentialsKey]>` slots lazily on first use
|
|
184
|
+
// (#5486: JSON-encoded so the key is collision-proof for any charset) —
|
|
185
|
+
// bounded by the configured entries, dropped by resetCachesForTest().
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// Empty template for a slot that has never resolved (also the lazy seed for
|
|
189
|
+
// dynamic slots). Frozen — every cache write replaces the whole slot object.
|
|
190
|
+
const _EMPTY_CRED_FILE_SLOT = Object.freeze({
|
|
191
|
+
envValue: null, path: null, mtimeMs: null, size: null, mode: null, result: null,
|
|
192
|
+
})
|
|
193
|
+
|
|
194
|
+
const _SLOT_ENV_VAR = {
|
|
195
|
+
byok: 'ANTHROPIC_API_KEY',
|
|
196
|
+
deepseek: 'DEEPSEEK_API_KEY',
|
|
197
|
+
discord: 'CHROXY_DISCORD_WEBHOOK_URL',
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Cache wrapper around a credential-file resolver. The resolver itself does
|
|
202
|
+
* the file read; this helper short-circuits to the cached resolver result when
|
|
203
|
+
* the env var is unchanged AND either (env-var path was taken last time) or
|
|
204
|
+
* (the file's stat-mtime+size+mode still matches what we cached).
|
|
205
|
+
*
|
|
206
|
+
* Fixed slots (byok/deepseek/discord) pre-exist; any other slot name is
|
|
207
|
+
* created lazily on first use (#5461 — dynamic `compat:` slots for the
|
|
208
|
+
* config-driven Anthropic-compatible entries). For dynamic slots the env var
|
|
209
|
+
* named in the synthesized ENOENT reason comes from `envVarName` (pass null
|
|
210
|
+
* for a file-only credential spec — the env clause is omitted); fixed slots
|
|
211
|
+
* keep their `_SLOT_ENV_VAR` mapping and don't pass it.
|
|
212
|
+
*
|
|
213
|
+
* @param {string} slot - 'byok' | 'deepseek' | 'discord' | dynamic (e.g. 'compat:["ZAI_API_KEY","zaiApiKey"]')
|
|
214
|
+
* @param {string | undefined} envValue - current value of the relevant env var
|
|
215
|
+
* @param {() => object} resolve - the underlying *-credentials resolver
|
|
216
|
+
* @param {string | null} [envVarName] - env var to name in the ENOENT reason (dynamic slots only)
|
|
217
|
+
* @returns {object} resolver result
|
|
218
|
+
*/
|
|
219
|
+
export function cachedResolveCredentialFile(slot, envValue, resolve, envVarName) {
|
|
220
|
+
const entry = _credFileCache[slot] || _EMPTY_CRED_FILE_SLOT
|
|
221
|
+
const credPath = join(homedir(), '.chroxy', 'credentials.json')
|
|
222
|
+
|
|
223
|
+
if (typeof envValue === 'string' && envValue.length > 0) {
|
|
224
|
+
if (entry.envValue === envValue && entry.path === null && entry.result) {
|
|
225
|
+
return entry.result
|
|
226
|
+
}
|
|
227
|
+
const result = resolve()
|
|
228
|
+
_credFileCache[slot] = { envValue, path: null, mtimeMs: null, size: null, mode: null, result }
|
|
229
|
+
return result
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
let stat
|
|
233
|
+
try {
|
|
234
|
+
stat = statSync(credPath)
|
|
235
|
+
} catch (err) {
|
|
236
|
+
_credFileCache[slot] = { envValue: null, path: null, mtimeMs: null, size: null, mode: null, result: null }
|
|
237
|
+
if (err.code === 'ENOENT') {
|
|
238
|
+
// The reason must match what the slot's own resolver would produce —
|
|
239
|
+
// dynamic slots name their entry's env var (or none, for file-only
|
|
240
|
+
// specs); fixed slots fall back to the static mapping.
|
|
241
|
+
const label = envVarName ?? _SLOT_ENV_VAR[slot]
|
|
242
|
+
return {
|
|
243
|
+
key: null,
|
|
244
|
+
source: 'none',
|
|
245
|
+
reason: label
|
|
246
|
+
? `${label} not set and ${credPath} does not exist`
|
|
247
|
+
: `${credPath} does not exist`,
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
return resolve()
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
const mode = stat.mode & 0o777
|
|
254
|
+
if (
|
|
255
|
+
entry.envValue === null
|
|
256
|
+
&& entry.path === credPath
|
|
257
|
+
&& entry.mtimeMs === stat.mtimeMs
|
|
258
|
+
&& entry.size === stat.size
|
|
259
|
+
&& entry.mode === mode
|
|
260
|
+
&& entry.result
|
|
261
|
+
) {
|
|
262
|
+
return entry.result
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
const result = resolve()
|
|
266
|
+
_credFileCache[slot] = {
|
|
267
|
+
envValue: null,
|
|
268
|
+
path: credPath,
|
|
269
|
+
mtimeMs: stat.mtimeMs,
|
|
270
|
+
size: stat.size,
|
|
271
|
+
mode,
|
|
272
|
+
result,
|
|
273
|
+
}
|
|
274
|
+
return result
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* Test-only hook: drop both cached probe results and the cached credential-
|
|
279
|
+
* file resolver entries so suites that mutate the `CHROXY_*_HOME` overrides or
|
|
280
|
+
* write/delete files under them start from a clean slate. Replacing the whole
|
|
281
|
+
* `_credFileCache` object also discards any dynamic `compat:` slots (#5461).
|
|
282
|
+
* Production code should never call this — the env-var-keyed invalidation +
|
|
283
|
+
* 5s TTL + mtime stat are what users see.
|
|
284
|
+
*/
|
|
285
|
+
export function resetCachesForTest() {
|
|
286
|
+
_credsCache = {
|
|
287
|
+
claude: { value: null, expiresAt: 0, key: null },
|
|
288
|
+
codex: { value: null, expiresAt: 0, key: null },
|
|
289
|
+
gemini: { value: null, expiresAt: 0, key: null },
|
|
290
|
+
}
|
|
291
|
+
_credFileCache = {
|
|
292
|
+
byok: { envValue: null, path: null, mtimeMs: null, size: null, mode: null, result: null },
|
|
293
|
+
deepseek: { envValue: null, path: null, mtimeMs: null, size: null, mode: null, result: null },
|
|
294
|
+
discord: { envValue: null, path: null, mtimeMs: null, size: null, mode: null, result: null },
|
|
295
|
+
}
|
|
296
|
+
}
|