@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,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Message transform pipeline for pre-processing user prompts.
|
|
3
|
+
*
|
|
4
|
+
* Transforms are pure synchronous functions: (message, context) => message.
|
|
5
|
+
* The pipeline is opt-in — if no transforms are configured, messages pass
|
|
6
|
+
* through unchanged (zero behavior change for existing users).
|
|
7
|
+
*/
|
|
8
|
+
import { createLogger } from './logger.js'
|
|
9
|
+
|
|
10
|
+
const log = createLogger('message-transform')
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Built-in transforms registry.
|
|
14
|
+
* Each transform takes (message, context) and returns the transformed message.
|
|
15
|
+
* Context: { cwd, model, isVoiceInput, sessionName, platform, gitBranch }
|
|
16
|
+
*/
|
|
17
|
+
const BUILT_IN_TRANSFORMS = {
|
|
18
|
+
/**
|
|
19
|
+
* Prepend a brief context annotation so Claude knows the environment.
|
|
20
|
+
* Uses a system-note style prefix that Claude treats as ambient context.
|
|
21
|
+
*/
|
|
22
|
+
contextAnnotation: (message, ctx) => {
|
|
23
|
+
// Skip annotation for very short messages (plan approvals, yes/no, etc.)
|
|
24
|
+
if (message.length < 10) return message
|
|
25
|
+
const parts = []
|
|
26
|
+
if (ctx.cwd) parts.push(`cwd: ${ctx.cwd}`)
|
|
27
|
+
if (ctx.model) parts.push(`model: ${ctx.model}`)
|
|
28
|
+
if (ctx.gitBranch) parts.push(`branch: ${ctx.gitBranch}`)
|
|
29
|
+
if (ctx.platform) parts.push(`platform: ${ctx.platform}`)
|
|
30
|
+
if (parts.length === 0) return message
|
|
31
|
+
return `[${parts.join(', ')}]\n\n${message}`
|
|
32
|
+
},
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Clean up common voice-to-text artifacts: filler words, missing
|
|
36
|
+
* punctuation, and normalization for cleaner prompts.
|
|
37
|
+
*/
|
|
38
|
+
voiceCleanup: (message, ctx) => {
|
|
39
|
+
if (!ctx.isVoiceInput) return message
|
|
40
|
+
let cleaned = message
|
|
41
|
+
// Remove common filler words at start of message
|
|
42
|
+
cleaned = cleaned.replace(/^(um|uh|like|so|okay|well|basically),?\s*/i, '')
|
|
43
|
+
// Remove mid-sentence fillers (comma-delimited or standalone)
|
|
44
|
+
// Careful: "like" and "so" have legitimate uses, only strip after comma
|
|
45
|
+
cleaned = cleaned.replace(/,\s*(um|uh),?\s*/gi, ', ')
|
|
46
|
+
cleaned = cleaned.replace(/\s+(um|uh),?\s+/gi, ' ')
|
|
47
|
+
// Remove trailing filler words (e.g. "fix the bug um" → "fix the bug")
|
|
48
|
+
cleaned = cleaned.replace(/\s+(um|uh)$/gi, '')
|
|
49
|
+
// Clean up double spaces from removals
|
|
50
|
+
cleaned = cleaned.replace(/ +/g, ' ').trim()
|
|
51
|
+
// Remove trailing comma left by filler removal (e.g. "fix the bug, um" → "fix the bug")
|
|
52
|
+
cleaned = cleaned.replace(/,\s*$/, '')
|
|
53
|
+
// Ensure sentence ends with punctuation
|
|
54
|
+
if (cleaned.length > 0 && !/[.!?]$/.test(cleaned)) {
|
|
55
|
+
cleaned += '.'
|
|
56
|
+
}
|
|
57
|
+
return cleaned
|
|
58
|
+
},
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export class MessageTransformPipeline {
|
|
62
|
+
/**
|
|
63
|
+
* @param {string[]} transformNames - Ordered list of transform names to apply
|
|
64
|
+
*/
|
|
65
|
+
constructor(transformNames = []) {
|
|
66
|
+
this._transforms = []
|
|
67
|
+
for (const name of transformNames) {
|
|
68
|
+
const fn = BUILT_IN_TRANSFORMS[name]
|
|
69
|
+
if (fn) {
|
|
70
|
+
this._transforms.push({ name, fn })
|
|
71
|
+
} else {
|
|
72
|
+
log.warn(`Unknown transform: "${name}", skipping`)
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
if (this._transforms.length > 0) {
|
|
76
|
+
log.info(`Pipeline: ${this._transforms.map(t => t.name).join(' → ')}`)
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Apply all configured transforms to a message.
|
|
82
|
+
* @param {string} message - The user's raw prompt
|
|
83
|
+
* @param {object} context - Transform context
|
|
84
|
+
* @returns {string} Transformed message
|
|
85
|
+
*/
|
|
86
|
+
apply(message, context = {}) {
|
|
87
|
+
if (this._transforms.length === 0) return message
|
|
88
|
+
let result = message
|
|
89
|
+
for (const { fn } of this._transforms) {
|
|
90
|
+
result = fn(result, context)
|
|
91
|
+
}
|
|
92
|
+
return result
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** @returns {boolean} True if pipeline has any transforms configured */
|
|
96
|
+
get hasTransforms() {
|
|
97
|
+
return this._transforms.length > 0
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Exported for testing */
|
|
102
|
+
export const transforms = BUILT_IN_TRANSFORMS
|
package/src/metrics.js
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lightweight in-process event counter store.
|
|
3
|
+
*
|
|
4
|
+
* Added in the 2026-04-11 production readiness audit (Phase 2 —
|
|
5
|
+
* observability). The existing /metrics endpoint only exposes
|
|
6
|
+
* instantaneous gauges (active sessions, memory). Without persistent
|
|
7
|
+
* event counters, debugging production incidents requires reading
|
|
8
|
+
* source code. This module closes that gap.
|
|
9
|
+
*
|
|
10
|
+
* Usage:
|
|
11
|
+
* import { metrics } from './metrics.js'
|
|
12
|
+
* metrics.inc('push.failures')
|
|
13
|
+
* metrics.inc('ws.messages.received', 5)
|
|
14
|
+
* const snapshot = metrics.snapshot()
|
|
15
|
+
*
|
|
16
|
+
* Counters reset to zero on process restart — they measure the
|
|
17
|
+
* current server lifetime, not cumulative history.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
class MetricsStore {
|
|
21
|
+
constructor() {
|
|
22
|
+
this._counters = new Map()
|
|
23
|
+
this._startedAt = Date.now()
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Increment a named counter by `n` (default 1).
|
|
28
|
+
* Counter is auto-created on first use.
|
|
29
|
+
*/
|
|
30
|
+
inc(name, n = 1) {
|
|
31
|
+
this._counters.set(name, (this._counters.get(name) || 0) + n)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Read the current value of a counter (0 if never incremented).
|
|
36
|
+
*/
|
|
37
|
+
get(name) {
|
|
38
|
+
return this._counters.get(name) || 0
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Return a plain object snapshot of all counters, suitable for
|
|
43
|
+
* JSON serialization. Includes a `_uptimeSeconds` meta-field.
|
|
44
|
+
*/
|
|
45
|
+
snapshot() {
|
|
46
|
+
const obj = {}
|
|
47
|
+
for (const [k, v] of this._counters) {
|
|
48
|
+
obj[k] = v
|
|
49
|
+
}
|
|
50
|
+
obj._uptimeSeconds = Math.round((Date.now() - this._startedAt) / 1000)
|
|
51
|
+
return obj
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Reset all counters to zero. Primarily for testing.
|
|
56
|
+
*/
|
|
57
|
+
reset() {
|
|
58
|
+
this._counters.clear()
|
|
59
|
+
this._startedAt = Date.now()
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Singleton instance. All server components import and use this
|
|
65
|
+
* directly — no DI plumbing needed.
|
|
66
|
+
*/
|
|
67
|
+
export const metrics = new MetricsStore()
|
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generic model-catalog discovery for `providers.anthropicCompatible` entries
|
|
3
|
+
* (#5548) — a capability declared via `modelDiscovery: { url, format }`, NOT
|
|
4
|
+
* OpenRouter-specific code.
|
|
5
|
+
*
|
|
6
|
+
* Many aggregators and local servers expose an OpenAI-ish `/v1/models` listing
|
|
7
|
+
* (OpenRouter carries per-token pricing alongside; LM Studio / vLLM list ids
|
|
8
|
+
* only). This module probes that endpoint, normalizes the response per-format
|
|
9
|
+
* into `{ models, pricing }`, and feeds the result into the provider's models
|
|
10
|
+
* registry + per-model cost table — exactly the role Ollama's /api/tags probe
|
|
11
|
+
* (ollama-tags.js, #5421) plays for the local daemon. The cache/refresh shape
|
|
12
|
+
* is deliberately the same:
|
|
13
|
+
*
|
|
14
|
+
* - ADVISORY for the picker, AUTHORITATIVE for validation. A discovered
|
|
15
|
+
* catalog replaces the static `models` allowlist for that entry (the
|
|
16
|
+
* issue's tri-state interplay with #5418): the session class reports the
|
|
17
|
+
* discovered ids from getAllowedModels() once a catalog is in hand.
|
|
18
|
+
* - GRACEFUL FAILURE. Endpoint down / slow / garbage must never delay or
|
|
19
|
+
* break session start: bounded timeout, debug-level logging, and the
|
|
20
|
+
* picker keeps whatever it already had (the static seed on cold boot).
|
|
21
|
+
* - NO RETRY STORM. Results — success AND failure — are cached per entry for
|
|
22
|
+
* a TTL, and concurrent callers share one in-flight request. A reconnect
|
|
23
|
+
* loop can't hammer the aggregator.
|
|
24
|
+
*
|
|
25
|
+
* Unlike Ollama's single global daemon, anthropicCompatible entries are
|
|
26
|
+
* many-and-configurable, so the cache here is keyed per entry id (a Map of
|
|
27
|
+
* per-entry slots) rather than module-level scalars.
|
|
28
|
+
*
|
|
29
|
+
* Pricing: OpenRouter reports USD-per-TOKEN rates as strings (e.g.
|
|
30
|
+
* `"0.0000004"` = $0.40/MTok). We convert to chroxy's internal USD-per-MTok
|
|
31
|
+
* convention so the discovered table drops straight into byok-session's cost
|
|
32
|
+
* math (the same units `pricing` blocks already use).
|
|
33
|
+
*/
|
|
34
|
+
|
|
35
|
+
import { createLogger } from './logger.js'
|
|
36
|
+
|
|
37
|
+
const log = createLogger('model-discovery')
|
|
38
|
+
|
|
39
|
+
// Bounded probe. A catalog endpoint is a remote HTTP service (OpenRouter) or a
|
|
40
|
+
// local one (LM Studio) — 4s is generous for the former and instant for the
|
|
41
|
+
// latter, while still capping a wedged endpoint's drag on a session that opted
|
|
42
|
+
// in. Discovery is fire-and-forget, so this never blocks the user.
|
|
43
|
+
export const MODEL_DISCOVERY_TIMEOUT_MS = 4000
|
|
44
|
+
|
|
45
|
+
// Cache window for discovery results (success AND failure). A catalog of
|
|
46
|
+
// hundreds of models changes slowly; 5 min keeps a reconnecting dashboard /
|
|
47
|
+
// multi-client handshake burst down to at most one HTTP probe per window while
|
|
48
|
+
// still picking up new models within the session.
|
|
49
|
+
export const MODEL_DISCOVERY_CACHE_TTL_MS = 5 * 60_000
|
|
50
|
+
|
|
51
|
+
// USD per token → USD per MTok. OpenRouter prices are per-token strings.
|
|
52
|
+
const TOKENS_PER_MTOK = 1_000_000
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Coerce an OpenRouter per-token price (string or number) to USD-per-MTok.
|
|
56
|
+
* Missing / unparseable / negative → 0 (an honest $0 rather than a fabricated
|
|
57
|
+
* rate — the ollama/local convention).
|
|
58
|
+
*
|
|
59
|
+
* @param {*} perToken
|
|
60
|
+
* @returns {number}
|
|
61
|
+
*/
|
|
62
|
+
function perTokenToMTok(perToken) {
|
|
63
|
+
const n = typeof perToken === 'string' ? Number(perToken) : perToken
|
|
64
|
+
if (typeof n !== 'number' || !Number.isFinite(n) || n < 0) return 0
|
|
65
|
+
return n * TOKENS_PER_MTOK
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Normalize an OpenRouter /api/v1/models response into chroxy's shape.
|
|
70
|
+
*
|
|
71
|
+
* OpenRouter entry (relevant fields):
|
|
72
|
+
* { id, name, context_length,
|
|
73
|
+
* pricing: { prompt, completion, input_cache_read, input_cache_write } }
|
|
74
|
+
*
|
|
75
|
+
* @param {*} body - parsed JSON
|
|
76
|
+
* @returns {{ models: Array<{id,label,contextWindow}>, pricing: Object }|null}
|
|
77
|
+
*/
|
|
78
|
+
function parseOpenRouter(body) {
|
|
79
|
+
const list = Array.isArray(body?.data) ? body.data : null
|
|
80
|
+
if (!list) return null
|
|
81
|
+
const models = []
|
|
82
|
+
const pricing = {}
|
|
83
|
+
const seen = new Set()
|
|
84
|
+
for (const m of list) {
|
|
85
|
+
const id = typeof m?.id === 'string' ? m.id.trim() : ''
|
|
86
|
+
if (!id || seen.has(id)) continue
|
|
87
|
+
seen.add(id)
|
|
88
|
+
const label = typeof m?.name === 'string' && m.name.trim().length > 0 ? m.name.trim() : id
|
|
89
|
+
const ctx = Number.isInteger(m?.context_length) && m.context_length > 0 ? m.context_length : null
|
|
90
|
+
models.push({ id, label, contextWindow: ctx })
|
|
91
|
+
const p = m?.pricing
|
|
92
|
+
if (p && typeof p === 'object') {
|
|
93
|
+
pricing[id] = Object.freeze({
|
|
94
|
+
input: perTokenToMTok(p.prompt),
|
|
95
|
+
output: perTokenToMTok(p.completion),
|
|
96
|
+
cacheRead: perTokenToMTok(p.input_cache_read),
|
|
97
|
+
cacheWrite: perTokenToMTok(p.input_cache_write),
|
|
98
|
+
})
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
if (models.length === 0) return null
|
|
102
|
+
return { models, pricing }
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Normalize a bare OpenAI /v1/models response (ids only, no pricing). Covers
|
|
107
|
+
* LM Studio, vLLM, and any OpenAI-format server. Designed to slot in alongside
|
|
108
|
+
* the openrouter adapter — same return shape, empty pricing table.
|
|
109
|
+
*
|
|
110
|
+
* OpenAI entry: { id, object: 'model', ... } under a top-level `data` array.
|
|
111
|
+
*
|
|
112
|
+
* @param {*} body
|
|
113
|
+
* @returns {{ models: Array<{id,label,contextWindow}>, pricing: Object }|null}
|
|
114
|
+
*/
|
|
115
|
+
function parseOpenAi(body) {
|
|
116
|
+
const list = Array.isArray(body?.data) ? body.data : null
|
|
117
|
+
if (!list) return null
|
|
118
|
+
const models = []
|
|
119
|
+
const seen = new Set()
|
|
120
|
+
for (const m of list) {
|
|
121
|
+
const id = typeof m?.id === 'string' ? m.id.trim() : ''
|
|
122
|
+
if (!id || seen.has(id)) continue
|
|
123
|
+
seen.add(id)
|
|
124
|
+
// No name/context in the bare OpenAI list — id doubles as label, window
|
|
125
|
+
// unknown (null, never fabricated — the #5444 rule).
|
|
126
|
+
models.push({ id, label: id, contextWindow: null })
|
|
127
|
+
}
|
|
128
|
+
if (models.length === 0) return null
|
|
129
|
+
return { models, pricing: {} }
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const FORMAT_PARSERS = Object.freeze({
|
|
133
|
+
openrouter: parseOpenRouter,
|
|
134
|
+
openai: parseOpenAi,
|
|
135
|
+
})
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Fetch + normalize a model catalog. Returns `{ models, pricing }` on success
|
|
139
|
+
* or null on ANY failure (endpoint down, non-2xx, malformed JSON, unexpected
|
|
140
|
+
* shape, timeout, unknown format). Failures log at debug level only.
|
|
141
|
+
*
|
|
142
|
+
* Authorization: discovery endpoints often gate the list behind the same key
|
|
143
|
+
* as the chat endpoint (OpenRouter requires no key for /api/v1/models, but
|
|
144
|
+
* passing one is harmless and future-proofs gated aggregators). When `apiKey`
|
|
145
|
+
* is supplied and non-empty it rides as `Authorization: Bearer`. Never logged.
|
|
146
|
+
*
|
|
147
|
+
* @param {Object} opts
|
|
148
|
+
* @param {string} opts.url
|
|
149
|
+
* @param {string} opts.format - one of MODEL_DISCOVERY_FORMATS
|
|
150
|
+
* @param {string|null} [opts.apiKey]
|
|
151
|
+
* @param {typeof fetch} [opts.fetchFn] - injectable fetch for tests
|
|
152
|
+
* @param {number} [opts.timeoutMs]
|
|
153
|
+
* @returns {Promise<{models:Array,pricing:Object}|null>}
|
|
154
|
+
*/
|
|
155
|
+
export async function fetchModelCatalog({ url, format, apiKey = null, fetchFn = fetch, timeoutMs = MODEL_DISCOVERY_TIMEOUT_MS } = {}) {
|
|
156
|
+
const parse = FORMAT_PARSERS[format]
|
|
157
|
+
if (typeof parse !== 'function') {
|
|
158
|
+
log.debug(`discovery: unknown format '${format}' for ${url}`)
|
|
159
|
+
return null
|
|
160
|
+
}
|
|
161
|
+
const controller = new AbortController()
|
|
162
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs)
|
|
163
|
+
try {
|
|
164
|
+
const headers = { accept: 'application/json' }
|
|
165
|
+
if (typeof apiKey === 'string' && apiKey.length > 0) {
|
|
166
|
+
headers.authorization = `Bearer ${apiKey}`
|
|
167
|
+
}
|
|
168
|
+
const res = await fetchFn(url, { signal: controller.signal, headers })
|
|
169
|
+
if (!res?.ok) {
|
|
170
|
+
log.debug(`discovery: ${url} answered ${res?.status ?? 'no response'}`)
|
|
171
|
+
return null
|
|
172
|
+
}
|
|
173
|
+
const body = await res.json()
|
|
174
|
+
const parsed = parse(body)
|
|
175
|
+
if (!parsed) {
|
|
176
|
+
log.debug(`discovery: ${url} returned an unexpected shape for format '${format}'`)
|
|
177
|
+
return null
|
|
178
|
+
}
|
|
179
|
+
return parsed
|
|
180
|
+
} catch (err) {
|
|
181
|
+
log.debug(`discovery: ${url} failed (${err?.name === 'AbortError' ? `timeout after ${timeoutMs}ms` : err?.message || err})`)
|
|
182
|
+
return null
|
|
183
|
+
} finally {
|
|
184
|
+
clearTimeout(timer)
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// --- Per-entry TTL cache for refreshDiscoveredModels ---
|
|
189
|
+
// Keyed by entry id (anthropicCompatible entries are many; Ollama is one
|
|
190
|
+
// global daemon and uses module scalars). Each slot tracks last-probe time,
|
|
191
|
+
// the in-flight promise, and the last-applied key for change detection.
|
|
192
|
+
const _slots = new Map()
|
|
193
|
+
|
|
194
|
+
function slotFor(id) {
|
|
195
|
+
let slot = _slots.get(id)
|
|
196
|
+
if (!slot) {
|
|
197
|
+
slot = { lastProbeAt: -Infinity, inflight: null, lastAppliedKey: null }
|
|
198
|
+
_slots.set(id, slot)
|
|
199
|
+
}
|
|
200
|
+
return slot
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** Test hook: drop all per-entry cache + change-detection state. */
|
|
204
|
+
export function _resetModelDiscoveryStateForTests() {
|
|
205
|
+
_slots.clear()
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Discover the catalog for one anthropicCompatible entry and feed it into the
|
|
210
|
+
* provider's models registry. Resolves to the refreshed registry model list
|
|
211
|
+
* when the picker CHANGED, or null when there is nothing new to broadcast
|
|
212
|
+
* (probe failed, no models, same set as last time, or served from the TTL
|
|
213
|
+
* cache) — the exact contract of refreshOllamaModels so the generic
|
|
214
|
+
* `scheduleProviderModelsRefresh` hook in ws-history treats both alike.
|
|
215
|
+
*
|
|
216
|
+
* Side effect: when discovery succeeds, the full catalog (`{ models, pricing }`)
|
|
217
|
+
* is published via `applyCatalog(catalog)` BEFORE the registry feed, so the
|
|
218
|
+
* session class's getModelMetadata/getAllowedModels/_getPricing read from the
|
|
219
|
+
* discovered ids + context windows + per-model pricing (real cost, not $0) by
|
|
220
|
+
* the time the registry's updateModels() consults them.
|
|
221
|
+
*
|
|
222
|
+
* @param {Object} opts
|
|
223
|
+
* @param {string} opts.id - provider/entry id (cache key + log label)
|
|
224
|
+
* @param {string} opts.url
|
|
225
|
+
* @param {string} opts.format
|
|
226
|
+
* @param {string|null} [opts.apiKey]
|
|
227
|
+
* @param {Object} opts.registry - provider models registry (updateModels/getModels)
|
|
228
|
+
* @param {(catalog: {models:Array,pricing:Object}) => void} [opts.applyCatalog] - catalog sink
|
|
229
|
+
* @param {typeof fetch} [opts.fetchFn]
|
|
230
|
+
* @param {number} [opts.timeoutMs]
|
|
231
|
+
* @param {number} [opts.ttlMs]
|
|
232
|
+
* @param {() => number} [opts.now] - injectable clock for tests
|
|
233
|
+
* @returns {Promise<Array<Object>|null>}
|
|
234
|
+
*/
|
|
235
|
+
export async function refreshDiscoveredModels(opts = {}) {
|
|
236
|
+
const { id } = opts
|
|
237
|
+
if (typeof id !== 'string' || id.length === 0) return null
|
|
238
|
+
const now = typeof opts.now === 'function' ? opts.now : Date.now
|
|
239
|
+
const ttlMs = typeof opts.ttlMs === 'number' ? opts.ttlMs : MODEL_DISCOVERY_CACHE_TTL_MS
|
|
240
|
+
const slot = slotFor(id)
|
|
241
|
+
if (slot.inflight) return slot.inflight
|
|
242
|
+
if (now() - slot.lastProbeAt < ttlMs) return null
|
|
243
|
+
slot.inflight = (async () => {
|
|
244
|
+
try {
|
|
245
|
+
const catalog = await fetchModelCatalog(opts)
|
|
246
|
+
slot.lastProbeAt = now()
|
|
247
|
+
if (!catalog || !Array.isArray(catalog.models) || catalog.models.length === 0) return null
|
|
248
|
+
// Publish the catalog to the session class FIRST (cheap, idempotent) so
|
|
249
|
+
// its getModelMetadata/getAllowedModels/_getPricing reflect the discovered
|
|
250
|
+
// ids + context windows + per-model pricing before updateModels() (which
|
|
251
|
+
// consults getModelMetadata for labels/windows) runs below. Done on every
|
|
252
|
+
// successful probe so a re-probe with the same model SET but updated rates
|
|
253
|
+
// still refreshes cost reporting.
|
|
254
|
+
if (typeof opts.applyCatalog === 'function') {
|
|
255
|
+
try {
|
|
256
|
+
opts.applyCatalog(catalog)
|
|
257
|
+
} catch (err) {
|
|
258
|
+
log.debug(`discovery: applyCatalog for ${id} threw: ${err?.message || err}`)
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
// Change-detection key: order-insensitive (a reorder of the same set
|
|
262
|
+
// isn't a change) and metadata-aware (a label / context-window update on
|
|
263
|
+
// an existing id IS a change the registry must pick up — updateModels()
|
|
264
|
+
// feeds those into the picker). Sort so upstream ordering can't trigger a
|
|
265
|
+
// spurious rebroadcast; include label + window so a metadata-only update
|
|
266
|
+
// still re-pushes. (Pricing already refreshes unconditionally via the
|
|
267
|
+
// applyCatalog call above, so it stays out of the key.)
|
|
268
|
+
const key = JSON.stringify(
|
|
269
|
+
catalog.models
|
|
270
|
+
.map((m) => [m.id, m.label ?? '', m.contextWindow ?? null])
|
|
271
|
+
.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)),
|
|
272
|
+
)
|
|
273
|
+
if (key === slot.lastAppliedKey) return null
|
|
274
|
+
const registry = opts.registry
|
|
275
|
+
if (!registry || typeof registry.updateModels !== 'function') return null
|
|
276
|
+
const converted = registry.updateModels(
|
|
277
|
+
catalog.models.map((m) => ({ value: m.id, displayName: m.label, contextWindow: m.contextWindow })),
|
|
278
|
+
)
|
|
279
|
+
if (!Array.isArray(converted) || converted.length === 0) return null
|
|
280
|
+
slot.lastAppliedKey = key
|
|
281
|
+
log.info(`discovered ${catalog.models.length} models for '${id}' via ${opts.format} catalog`)
|
|
282
|
+
return typeof registry.getModels === 'function' ? registry.getModels() : converted
|
|
283
|
+
} finally {
|
|
284
|
+
slot.inflight = null
|
|
285
|
+
}
|
|
286
|
+
})()
|
|
287
|
+
return slot.inflight
|
|
288
|
+
}
|