@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,144 @@
|
|
|
1
|
+
// permission-resolver.js (#5373) — the single source of truth for the DOMAIN
|
|
2
|
+
// decision of a permission response, extracted out of the duplicated HTTP
|
|
3
|
+
// (ws-permissions.js) and WS (settings-handlers.js) handlers.
|
|
4
|
+
//
|
|
5
|
+
// It owns ONLY the decision: the session-binding check (the bearer-token
|
|
6
|
+
// authorization boundary — bearer-token-authority.md §3-4; the
|
|
7
|
+
// #2806/#4788/#4794/#4820 chain), SDK-before-legacy dispatch, and audit. It
|
|
8
|
+
// returns a transport-agnostic descriptor (ResolveResult); each call site maps
|
|
9
|
+
// that to its own wire format (HTTP status codes vs WS messages).
|
|
10
|
+
//
|
|
11
|
+
// It deliberately does NOT own (these STAY at the call sites):
|
|
12
|
+
// - the HTTP body buffering / oversize-413 / parse-400 / crash-guard
|
|
13
|
+
// - the per-transport response shape (403 vs WS error, 200 vs ack, …)
|
|
14
|
+
// - the WS unbound-subscription guard (invariant G) — it has no HTTP analog
|
|
15
|
+
// by design (a primary token has full HTTP session authority), so it must
|
|
16
|
+
// not leak into the shared path and over-restrict HTTP
|
|
17
|
+
// - the per-transport `permission_resolved` broadcast
|
|
18
|
+
//
|
|
19
|
+
// ResolveResult (discriminated on `kind`):
|
|
20
|
+
// { kind: 'binding_mismatch', boundSessionId } -> HTTP 403 / WS error (map NOT consumed)
|
|
21
|
+
// { kind: 'resolved', via: 'sdk'|'legacy', sessionId } -> HTTP 200 / WS ack (map consumed)
|
|
22
|
+
// { kind: 'expired', sessionId } -> HTTP 410 / WS permission_expired
|
|
23
|
+
// { kind: 'not_found' } -> HTTP 404 / WS permission_expired
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* #6030: the single source of truth for the permission "dispatch origin"
|
|
27
|
+
* session id — the mapped session if the request was registered, else the
|
|
28
|
+
* WS-only legacy `client.activeSessionId` fallback (HTTP passes nothing).
|
|
29
|
+
*
|
|
30
|
+
* Both the WS handler (settings-handlers.js — for its unbound-subscription
|
|
31
|
+
* guard, invariant G) and the resolver below MUST compute this the SAME way, or
|
|
32
|
+
* the handler could authorize against one session while the resolver dispatches
|
|
33
|
+
* to another (issue #6030: the handler previously used `||` here while the
|
|
34
|
+
* resolver used `??`, so they disagreed on an empty-string / 0-ish mapped id).
|
|
35
|
+
* `??` is correct: a mapping is "present" iff it was actually registered
|
|
36
|
+
* (null/undefined absent), so an explicitly-mapped empty-string session id must
|
|
37
|
+
* be honoured, not silently coalesced to the active-session fallback.
|
|
38
|
+
*
|
|
39
|
+
* @param {string|null|undefined} mappedSessionId the raw permissionSessionMap entry
|
|
40
|
+
* @param {string|null|undefined} fallbackSessionId WS-only legacy fallback (client.activeSessionId); HTTP passes null
|
|
41
|
+
* @returns {string|null|undefined}
|
|
42
|
+
*/
|
|
43
|
+
export function resolveOriginSessionId(mappedSessionId, fallbackSessionId) {
|
|
44
|
+
return mappedSessionId ?? fallbackSessionId
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* @param {{
|
|
49
|
+
* permissionSessionMap: Map<string, string>,
|
|
50
|
+
* pendingPermissions: Map<string, any>,
|
|
51
|
+
* getSessionManager: () => ({ getSession: Function } | null),
|
|
52
|
+
* resolveLegacyPermission: (requestId: string, decision: string) => void,
|
|
53
|
+
* getPermissionAudit: () => ({ logDecision: Function } | null),
|
|
54
|
+
* onRouteTeardown?: (requestId: string) => void,
|
|
55
|
+
* }} deps
|
|
56
|
+
*/
|
|
57
|
+
export function createPermissionResolver({
|
|
58
|
+
permissionSessionMap,
|
|
59
|
+
pendingPermissions,
|
|
60
|
+
getSessionManager,
|
|
61
|
+
resolveLegacyPermission,
|
|
62
|
+
getPermissionAudit,
|
|
63
|
+
onRouteTeardown,
|
|
64
|
+
}) {
|
|
65
|
+
// #5704: a route is consumed (resolved or expired) here. Route the map delete
|
|
66
|
+
// through the WsServer teardown hook when wired so the permission-induced
|
|
67
|
+
// subscription refcount is decremented in lockstep with the map entry. Falls
|
|
68
|
+
// back to a bare delete for unit-test fixtures that don't provide the hook
|
|
69
|
+
// (no real clients to unsubscribe — behaviour-equivalent).
|
|
70
|
+
function consumeRoute(requestId) {
|
|
71
|
+
if (typeof onRouteTeardown === 'function') onRouteTeardown(requestId)
|
|
72
|
+
else permissionSessionMap.delete(requestId)
|
|
73
|
+
}
|
|
74
|
+
function audit(clientId, sessionId, requestId, decision) {
|
|
75
|
+
// #3059: only user-initiated resolutions reach here (auto-deny is audited by
|
|
76
|
+
// the unified pipeline), hence reason:'user'.
|
|
77
|
+
const a = getPermissionAudit?.()
|
|
78
|
+
if (a) a.logDecision({ clientId, sessionId, requestId, decision, reason: 'user' })
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* @param {string} requestId
|
|
83
|
+
* @param {string} decision
|
|
84
|
+
* @param {string|null} callerBoundSessionId token-bound id (HTTP) / client.boundSessionId (WS); null/undefined = unbound
|
|
85
|
+
* @param {{ clientId?: string|null, dispatchFallbackSessionId?: string|null }} [opts]
|
|
86
|
+
* `dispatchFallbackSessionId` is the WS-only legacy "map wasn't populated"
|
|
87
|
+
* fallback (client.activeSessionId). It is used ONLY to pick the dispatch
|
|
88
|
+
* session — NEVER for the binding check (invariant B). HTTP passes nothing.
|
|
89
|
+
* @returns {{ kind: string, [k: string]: any }} ResolveResult
|
|
90
|
+
*/
|
|
91
|
+
function resolve(requestId, decision, callerBoundSessionId, opts = {}) {
|
|
92
|
+
const { clientId = null, dispatchFallbackSessionId = null, editedInput = undefined } = opts
|
|
93
|
+
|
|
94
|
+
// Invariant B (#2806 residual): the binding check reads the RAW map entry —
|
|
95
|
+
// never an activeSessionId fallback. For a bound caller the request MUST be
|
|
96
|
+
// explicitly mapped to that session, or a missing mapping would let it slip
|
|
97
|
+
// through to the legacy resolver, which has no session check.
|
|
98
|
+
const mappedSessionId = permissionSessionMap.get(requestId)
|
|
99
|
+
|
|
100
|
+
// Invariant A: a bound caller may answer only its own bound session's prompts.
|
|
101
|
+
if (callerBoundSessionId) {
|
|
102
|
+
if (!mappedSessionId || mappedSessionId !== callerBoundSessionId) {
|
|
103
|
+
return { kind: 'binding_mismatch', boundSessionId: callerBoundSessionId }
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// Dispatch origin: the mapped session, or the WS-only legacy fallback. NEVER
|
|
108
|
+
// used for the binding check above. #6030: shared with the WS handler's guard
|
|
109
|
+
// via resolveOriginSessionId so both agree on empty-string/0-ish ids.
|
|
110
|
+
const originSessionId = resolveOriginSessionId(mappedSessionId, dispatchFallbackSessionId)
|
|
111
|
+
|
|
112
|
+
// Invariant F: SDK-mode (in-process) dispatch is attempted before the legacy
|
|
113
|
+
// store. Uses respondToPermission's RETURN VALUE as the resolved-vs-expired
|
|
114
|
+
// signal (the method's contract) — see the #5373 PR note on the WS
|
|
115
|
+
// _pendingPermissions pre-check this reconciles.
|
|
116
|
+
const sm = getSessionManager?.()
|
|
117
|
+
if (originSessionId && sm) {
|
|
118
|
+
const entry = sm.getSession(originSessionId)
|
|
119
|
+
if (entry && typeof entry.session.respondToPermission === 'function') {
|
|
120
|
+
// #6543 (feature B): editedInput flows ONLY to the in-process (SDK/BYOK)
|
|
121
|
+
// path — the legacy HTTP path below ignores it (CLI tool executes as-is).
|
|
122
|
+
const resolved = entry.session.respondToPermission(requestId, decision, editedInput)
|
|
123
|
+
consumeRoute(requestId)
|
|
124
|
+
if (resolved) {
|
|
125
|
+
audit(clientId, originSessionId, requestId, decision)
|
|
126
|
+
return { kind: 'resolved', via: 'sdk', sessionId: originSessionId }
|
|
127
|
+
}
|
|
128
|
+
return { kind: 'expired', sessionId: originSessionId }
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// Legacy HTTP-held / pendingPermissions store.
|
|
133
|
+
if (pendingPermissions.has(requestId)) {
|
|
134
|
+
consumeRoute(requestId)
|
|
135
|
+
resolveLegacyPermission(requestId, decision)
|
|
136
|
+
audit(clientId, originSessionId ?? null, requestId, decision)
|
|
137
|
+
return { kind: 'resolved', via: 'legacy', sessionId: originSessionId ?? null }
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
return { kind: 'not_found' }
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
return { resolve }
|
|
144
|
+
}
|
package/src/platform.js
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { writeFileSync, chmodSync, renameSync, unlinkSync } from 'fs'
|
|
2
|
+
import { createLogger } from './logger.js'
|
|
3
|
+
|
|
4
|
+
const log = createLogger('platform')
|
|
5
|
+
|
|
6
|
+
export const isWindows = process.platform === 'win32'
|
|
7
|
+
export const isMac = process.platform === 'darwin'
|
|
8
|
+
export const isLinux = process.platform === 'linux'
|
|
9
|
+
|
|
10
|
+
export function defaultShell() {
|
|
11
|
+
if (isWindows) return process.env.COMSPEC || 'cmd.exe'
|
|
12
|
+
return process.env.SHELL || '/bin/zsh'
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Write `data` to `filePath` atomically on both POSIX and Windows. The
|
|
17
|
+
* write goes to a sibling temp file `<filePath><tmpSuffix>` first and is
|
|
18
|
+
* then `rename`d over the destination. `rename` is atomic on the same
|
|
19
|
+
* filesystem on both POSIX (POSIX.1 `rename(2)`) and Windows (Node's
|
|
20
|
+
* `fs.renameSync` calls `MoveFileExW` with `MOVEFILE_REPLACE_EXISTING |
|
|
21
|
+
* MOVEFILE_WRITE_THROUGH` since v16), so a concurrent reader sees either
|
|
22
|
+
* the previous version or the new one — never a half-written file. This
|
|
23
|
+
* matters when the process is killed mid-write (SIGKILL / OOM); it is
|
|
24
|
+
* the file-level analogue of the "SIGTERM not SIGKILL for Chroxy"
|
|
25
|
+
* memory note. See #4850 (the original POSIX gap for `connection.json`
|
|
26
|
+
* and `device-preferences.json`) and #4913 (extension of the same
|
|
27
|
+
* crash-safety contract to Windows, after #4874 collapsed manual
|
|
28
|
+
* tmp+rename wrappers in `environment-manager.js` and `models.js` onto
|
|
29
|
+
* this helper).
|
|
30
|
+
*
|
|
31
|
+
* The temp file lives in the same directory as `filePath` (not
|
|
32
|
+
* `os.tmpdir()`) so the rename always stays within the same filesystem /
|
|
33
|
+
* volume. A cross-volume rename would fail with EXDEV on POSIX and
|
|
34
|
+
* ERROR_NOT_SAME_DEVICE on Windows and silently defeat the atomic
|
|
35
|
+
* guarantee.
|
|
36
|
+
*
|
|
37
|
+
* On POSIX the temp file is created with `0o600` and `chmod`ed for
|
|
38
|
+
* defence-in-depth before the rename. On Windows we deliberately do NOT
|
|
39
|
+
* pass `mode` to `writeFileSync` — Node maps the integer mode argument
|
|
40
|
+
* through `_open` on Windows where only the write bit (`0o200`) toggles
|
|
41
|
+
* the read-only attribute; the read / group / other bits are silently
|
|
42
|
+
* ignored. ACL inheritance from the parent directory is the correct
|
|
43
|
+
* mechanism on NTFS, and our existing storage paths (`~/.chroxy/`,
|
|
44
|
+
* `%APPDATA%/Chroxy/`) inherit user-only ACLs from the per-user profile
|
|
45
|
+
* directory that Chroxy creates them under. See #4913 for the threat
|
|
46
|
+
* model discussion.
|
|
47
|
+
*
|
|
48
|
+
* Options:
|
|
49
|
+
* - `tmpSuffix` (default `.tmp`): suffix appended to `filePath` for
|
|
50
|
+
* the intermediate atomic-write file. Callers that may collide on
|
|
51
|
+
* the same target path from multiple processes (e.g. the models
|
|
52
|
+
* cache rewritten by both the test runner and the main daemon)
|
|
53
|
+
* should pass a per-process suffix such as `.tmp-${process.pid}`
|
|
54
|
+
* so the intermediate files never overwrite each other. Honoured
|
|
55
|
+
* on POSIX since #4874, and on Windows since #4913.
|
|
56
|
+
* - `_isWindowsOverride` (test-only): force the Windows branch
|
|
57
|
+
* regardless of host platform. Mirrors the same hook in
|
|
58
|
+
* `SessionStatePersistence` and lets the cross-platform atomicity
|
|
59
|
+
* test exercise the Windows path on a POSIX runner (we cannot rely
|
|
60
|
+
* on a Windows CI runner being available — see #4913).
|
|
61
|
+
*
|
|
62
|
+
* On rename failure, the intermediate `<filePath><tmpSuffix>` file is
|
|
63
|
+
* unlinked before the error is rethrown so it does not leak across
|
|
64
|
+
* retries. The rename error is what the caller needs to surface, so it
|
|
65
|
+
* is always re-thrown; a non-ENOENT cleanup-unlink failure is logged via
|
|
66
|
+
* `log.warn` so the orphan `.tmp` is not invisible (#4906 — the bespoke
|
|
67
|
+
* cleanup wrappers in environment-manager.js / session-state-persistence.js
|
|
68
|
+
* had this warn before the hoist in #4874).
|
|
69
|
+
*
|
|
70
|
+
* AV-held-handle retry decision (#4927). On Windows, an open handle held
|
|
71
|
+
* by antivirus / Windows Search can cause `renameSync` to fail with
|
|
72
|
+
* EPERM / EACCES / EBUSY / EEXIST. `session-state-persistence.js._rotateToBak`
|
|
73
|
+
* handles this with a one-shot retry, but `writeFileRestricted` does NOT
|
|
74
|
+
* replicate that pattern — every existing caller already has its own
|
|
75
|
+
* retry / fallback path (session manager debounce loop, models cache TTL
|
|
76
|
+
* refresh, env manager next-tick re-persist), so an inner retry would
|
|
77
|
+
* mask the error from the caller without changing the outcome.
|
|
78
|
+
* `_rotateToBak`'s retry is special because rotation has no caller-level
|
|
79
|
+
* retry — a missed rotation silently loses the prior-generation `.bak`
|
|
80
|
+
* until the next write. If a future site without its own retry adopts
|
|
81
|
+
* `writeFileRestricted`, revisit this decision. See `platform-windows.test.js`
|
|
82
|
+
* for the full rationale.
|
|
83
|
+
*/
|
|
84
|
+
export function writeFileRestricted(
|
|
85
|
+
filePath,
|
|
86
|
+
data,
|
|
87
|
+
{ tmpSuffix = '.tmp', _isWindowsOverride } = {},
|
|
88
|
+
) {
|
|
89
|
+
const onWindows = _isWindowsOverride ?? isWindows
|
|
90
|
+
const tmpPath = `${filePath}${tmpSuffix}`
|
|
91
|
+
// POSIX: the `mode: 0o600` arg to `writeFileSync` is ONLY honoured on
|
|
92
|
+
// file CREATION (`O_CREAT`). When `tmpPath` already exists — e.g. a
|
|
93
|
+
// prior run crashed before the rename and left a stale sidecar at a
|
|
94
|
+
// looser mode, or another local user pre-created the path under a
|
|
95
|
+
// permissive umask — `writeFileSync` opens with `O_TRUNC` and
|
|
96
|
+
// preserves the existing mode bits. The explicit `chmodSync`
|
|
97
|
+
// afterward guarantees the FINAL file is 0o600, but does NOT
|
|
98
|
+
// eliminate the transient exposure window between the write and the
|
|
99
|
+
// chmod — during that window, a pre-existing looser mode means
|
|
100
|
+
// another local user could read the freshly-written bytes. Full
|
|
101
|
+
// mitigation would require openSync(O_CREAT|O_EXCL) + fchmodSync
|
|
102
|
+
// before write; the current belt-and-braces is intentional but only
|
|
103
|
+
// covers the at-rest final perms, not the in-flight window. These
|
|
104
|
+
// files may carry secrets (session bearer tokens, push subscriptions,
|
|
105
|
+
// BYOK creds). Same defensive pattern is in `logger.js` (dir mode),
|
|
106
|
+
// `byok-credentials.js`, `byok-mcp-trust.js`, and
|
|
107
|
+
// `notification-prefs.js`. See #4907 for the cleanup discussion that
|
|
108
|
+
// ended in "keep with comment + regression test".
|
|
109
|
+
//
|
|
110
|
+
// Windows: no POSIX mode bits — ACLs are the correct mechanism and
|
|
111
|
+
// `writeFileSync`'s `mode` is mostly a no-op on Win32. The temp+rename
|
|
112
|
+
// pattern still applies for atomicity (#4913).
|
|
113
|
+
if (onWindows) {
|
|
114
|
+
writeFileSync(tmpPath, data)
|
|
115
|
+
} else {
|
|
116
|
+
writeFileSync(tmpPath, data, { mode: 0o600 })
|
|
117
|
+
chmodSync(tmpPath, 0o600)
|
|
118
|
+
}
|
|
119
|
+
try {
|
|
120
|
+
renameSync(tmpPath, filePath)
|
|
121
|
+
} catch (err) {
|
|
122
|
+
try {
|
|
123
|
+
unlinkSync(tmpPath)
|
|
124
|
+
} catch (cleanupErr) {
|
|
125
|
+
if (cleanupErr && cleanupErr.code !== 'ENOENT') {
|
|
126
|
+
log.warn(`Failed to remove orphaned ${tmpPath}: ${cleanupErr.message}`)
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
throw err
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function forceKill(child) {
|
|
134
|
+
if (isWindows) {
|
|
135
|
+
child.kill('SIGKILL')
|
|
136
|
+
} else {
|
|
137
|
+
child.kill('SIGKILL')
|
|
138
|
+
}
|
|
139
|
+
}
|
|
@@ -0,0 +1,386 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Prompt evaluator (#3068, Step 1 of the ladder).
|
|
3
|
+
*
|
|
4
|
+
* Single-shot Claude call that evaluates a user's draft message and returns
|
|
5
|
+
* one of three verdicts:
|
|
6
|
+
*
|
|
7
|
+
* - 'forward' — the draft is clear, send as-is
|
|
8
|
+
* - 'rewrite' — the draft is vague; here's a sharpened version
|
|
9
|
+
* - 'clarify' — the draft is ambiguous in a way only the user can resolve
|
|
10
|
+
*
|
|
11
|
+
* This is the on-demand variant invoked from the dashboard "Evaluate" button.
|
|
12
|
+
* The auto-intercept-every-message variant proposed in the original issue is
|
|
13
|
+
* deliberately deferred until we measure whether the manual variant actually
|
|
14
|
+
* gets used (Step 2 of the ladder).
|
|
15
|
+
*
|
|
16
|
+
* Auth: reads ANTHROPIC_API_KEY from the environment. We don't try to share
|
|
17
|
+
* Claude Code's OAuth credentials here — a Step 1.5 follow-up can add that
|
|
18
|
+
* if missing-key turns out to be the dominant friction point.
|
|
19
|
+
*/
|
|
20
|
+
import Anthropic from '@anthropic-ai/sdk'
|
|
21
|
+
import { createLogger } from './logger.js'
|
|
22
|
+
|
|
23
|
+
const log = createLogger('prompt-evaluator')
|
|
24
|
+
|
|
25
|
+
// Stable default; user can override via CHROXY_EVALUATOR_MODEL. We default to
|
|
26
|
+
// opus because the evaluator's job is to catch things a cheaper session model
|
|
27
|
+
// would miss — using a less capable evaluator defeats the point of the feature.
|
|
28
|
+
// Kept in sync with the canonical Opus id used elsewhere in the server
|
|
29
|
+
// (see packages/server/src/models.js — `claude-opus-4-8`).
|
|
30
|
+
const DEFAULT_MODEL = 'claude-opus-4-8'
|
|
31
|
+
|
|
32
|
+
// Cap the response so a runaway evaluator can't burn the whole context window
|
|
33
|
+
// on its 'reasoning' field.
|
|
34
|
+
const MAX_OUTPUT_TOKENS = 1024
|
|
35
|
+
|
|
36
|
+
// #3651 — deadline for the Anthropic round-trip. The auto-evaluator hook
|
|
37
|
+
// (#3186) awaits `evaluateDraft` on the user_input hot path; without a cap
|
|
38
|
+
// a hung promise (network partition, slow upstream, 503 with no body) would
|
|
39
|
+
// block the user's input indefinitely. 30s is long enough for an Opus
|
|
40
|
+
// extended-thinking call, short enough to keep the dashboard usable. Operators
|
|
41
|
+
// can override via CHROXY_EVALUATOR_TIMEOUT_MS or per-call `timeoutMs`.
|
|
42
|
+
const DEFAULT_TIMEOUT_MS = 30_000
|
|
43
|
+
|
|
44
|
+
const SYSTEM_PROMPT = `You are a prompt evaluator. A user is about to send the draft below to a coding assistant. Your job is to decide ONE of three outcomes:
|
|
45
|
+
|
|
46
|
+
1. "forward" — The draft is clear and well-specified. The assistant has enough to act.
|
|
47
|
+
2. "rewrite" — The draft is vague, under-specified, or would clearly produce a better result if sharpened. Provide a tightened rewrite.
|
|
48
|
+
3. "clarify" — The draft is ambiguous in a way only the user can resolve (e.g. multiple valid interpretations, missing critical context). Provide a focused clarifying question.
|
|
49
|
+
|
|
50
|
+
Be conservative. Prefer "forward" unless there is a real improvement to be made — most everyday prompts ("yes do it", "fix that bug", "go ahead") are fine as-is. Reserve "rewrite" for cases where you can materially improve the chance of a good answer. Reserve "clarify" for genuine ambiguity, not for asking the user to write more.
|
|
51
|
+
|
|
52
|
+
You MUST reply with a single JSON object and nothing else. No prose before or after. Schema:
|
|
53
|
+
|
|
54
|
+
{
|
|
55
|
+
"verdict": "forward" | "rewrite" | "clarify",
|
|
56
|
+
"rewritten": string | null,
|
|
57
|
+
"clarification": string | null,
|
|
58
|
+
"reasoning": string
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
Rules:
|
|
62
|
+
- "rewritten" MUST be a non-empty string when verdict is "rewrite", and null otherwise.
|
|
63
|
+
- "clarification" MUST be a non-empty, single-question string when verdict is "clarify", and null otherwise.
|
|
64
|
+
- "reasoning" is always a 1-2 sentence explanation of your decision, addressed to the user.`
|
|
65
|
+
|
|
66
|
+
const VALID_VERDICTS = new Set(['forward', 'rewrite', 'clarify'])
|
|
67
|
+
|
|
68
|
+
// Minimum length (after trim) for a draft to be worth evaluating. Below this
|
|
69
|
+
// the message is almost certainly a continuation/ack ("y", "go ahead", "do it
|
|
70
|
+
// please") that won't benefit from an evaluator round-trip.
|
|
71
|
+
const SKIP_MIN_LENGTH = 20
|
|
72
|
+
|
|
73
|
+
// Default continuation/ack pattern. Matches single-word affirmatives and a few
|
|
74
|
+
// common short phrases ("looks good", "sounds good", "run it"). Anchored to
|
|
75
|
+
// the full string so substantive messages that happen to start with "yes" or
|
|
76
|
+
// "ok" still get evaluated.
|
|
77
|
+
const DEFAULT_SKIP_PATTERN = /^(y|n|yes|no|go|continue|run it|ok|okay|sure|sounds good|looks good|do it)\.?$/i
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Decide whether a draft message is too trivial to be worth running through
|
|
81
|
+
* `evaluateDraft`. The auto-evaluator hook (sibling sub-task) consults this
|
|
82
|
+
* before paying for an Anthropic round-trip.
|
|
83
|
+
*
|
|
84
|
+
* Returns `true` to SKIP evaluation (forward the message as-is).
|
|
85
|
+
*
|
|
86
|
+
* Skip rules:
|
|
87
|
+
* - Non-string or empty (after trim) — nothing to evaluate
|
|
88
|
+
* - Length (after trim) < SKIP_MIN_LENGTH (20)
|
|
89
|
+
* - Matches the default continuation regex, OR a session-supplied
|
|
90
|
+
* `promptEvaluatorSkipPattern` regex source
|
|
91
|
+
*
|
|
92
|
+
* @param {unknown} message - The draft user message
|
|
93
|
+
* @param {object} [config]
|
|
94
|
+
* @param {string} [config.promptEvaluatorSkipPattern] - Per-session regex
|
|
95
|
+
* source string to OR with the default pattern. Malformed sources are
|
|
96
|
+
* logged and ignored — the default pattern still applies.
|
|
97
|
+
* @returns {boolean} true if the message should skip the evaluator
|
|
98
|
+
*/
|
|
99
|
+
export function shouldSkipEvaluator(message, config = {}) {
|
|
100
|
+
if (typeof message !== 'string') return true
|
|
101
|
+
const trimmed = message.trim()
|
|
102
|
+
if (!trimmed) return true
|
|
103
|
+
if (trimmed.length < SKIP_MIN_LENGTH) return true
|
|
104
|
+
|
|
105
|
+
if (DEFAULT_SKIP_PATTERN.test(trimmed)) return true
|
|
106
|
+
|
|
107
|
+
const customSource = config?.promptEvaluatorSkipPattern
|
|
108
|
+
if (typeof customSource === 'string' && customSource.length > 0) {
|
|
109
|
+
const customPattern = _compileSkipPattern(customSource)
|
|
110
|
+
if (customPattern && customPattern.test(trimmed)) return true
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
return false
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// Compiled-regex cache keyed by source string. Avoids recompiling on every
|
|
117
|
+
// `shouldSkipEvaluator` call (the auto-evaluator hook will run this on the
|
|
118
|
+
// `user_input` hot path). Stores `null` for invalid sources so we don't
|
|
119
|
+
// re-warn on every message either.
|
|
120
|
+
//
|
|
121
|
+
// Bounded by SKIP_PATTERN_CACHE_MAX so a session that flips through many
|
|
122
|
+
// distinct patterns can't grow the cache unboundedly. LRU-ish eviction:
|
|
123
|
+
// when full we drop the oldest insertion (Map preserves insertion order).
|
|
124
|
+
const SKIP_PATTERN_CACHE_MAX = 64
|
|
125
|
+
const _skipPatternCache = new Map()
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Compile a user-supplied regex source, with caching for the hot path.
|
|
129
|
+
* Returns null for invalid sources so the caller falls back to the default
|
|
130
|
+
* pattern only. The warning log is intentionally GENERIC — the regex source
|
|
131
|
+
* is user-supplied config and `log.warn` is fanned out to paired WS clients
|
|
132
|
+
* via `log_entry` events, so echoing the raw source / the SDK's error
|
|
133
|
+
* message would create a config-leak channel.
|
|
134
|
+
*/
|
|
135
|
+
function _compileSkipPattern(source) {
|
|
136
|
+
if (_skipPatternCache.has(source)) return _skipPatternCache.get(source)
|
|
137
|
+
let compiled = null
|
|
138
|
+
try {
|
|
139
|
+
compiled = new RegExp(source, 'i')
|
|
140
|
+
} catch {
|
|
141
|
+
log.warn('Invalid promptEvaluatorSkipPattern (rejected source); falling back to default skip pattern only')
|
|
142
|
+
}
|
|
143
|
+
if (_skipPatternCache.size >= SKIP_PATTERN_CACHE_MAX) {
|
|
144
|
+
// Evict the oldest entry — Map iteration order is insertion order.
|
|
145
|
+
const oldestKey = _skipPatternCache.keys().next().value
|
|
146
|
+
_skipPatternCache.delete(oldestKey)
|
|
147
|
+
}
|
|
148
|
+
_skipPatternCache.set(source, compiled)
|
|
149
|
+
return compiled
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Reset the compiled-pattern cache. Test-only — production code should
|
|
154
|
+
* never need this. Exported so tests can isolate one another.
|
|
155
|
+
*/
|
|
156
|
+
export function _resetSkipPatternCache() {
|
|
157
|
+
_skipPatternCache.clear()
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Evaluate a draft user message.
|
|
162
|
+
*
|
|
163
|
+
* @param {object} args
|
|
164
|
+
* @param {string} args.draft - The user's draft message (required, non-empty)
|
|
165
|
+
* @param {string} [args.cwd] - Session cwd, included in the user prompt for context
|
|
166
|
+
* @param {string} [args.model] - Anthropic model id (default: claude-opus-4-8
|
|
167
|
+
* or value of CHROXY_EVALUATOR_MODEL)
|
|
168
|
+
* @param {string} [args.apiKey] - Anthropic API key (default: ANTHROPIC_API_KEY env)
|
|
169
|
+
* @param {object} [args.client] - Test seam: pre-built Anthropic client (skips
|
|
170
|
+
* construction). Used by tests to inject a stub.
|
|
171
|
+
* @param {number} [args.timeoutMs] - Deadline for the Anthropic round-trip
|
|
172
|
+
* (default: CHROXY_EVALUATOR_TIMEOUT_MS env or 30000). On expiry the call
|
|
173
|
+
* aborts and `evaluateDraft` rejects with code 'EVALUATOR_TIMEOUT'. The
|
|
174
|
+
* handler treats this the same as 'EVALUATOR_API_ERROR' (fail-open: forward
|
|
175
|
+
* the original draft). See #3651.
|
|
176
|
+
* @returns {Promise<{
|
|
177
|
+
* verdict: 'forward' | 'rewrite' | 'clarify',
|
|
178
|
+
* rewritten: string | null,
|
|
179
|
+
* clarification: string | null,
|
|
180
|
+
* reasoning: string,
|
|
181
|
+
* }>}
|
|
182
|
+
*/
|
|
183
|
+
export async function evaluateDraft({ draft, cwd, model, apiKey, client, timeoutMs } = {}) {
|
|
184
|
+
if (typeof draft !== 'string' || !draft.trim()) {
|
|
185
|
+
throw new Error('evaluateDraft: draft must be a non-empty string')
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const resolvedKey = apiKey || process.env.ANTHROPIC_API_KEY
|
|
189
|
+
if (!client && !resolvedKey) {
|
|
190
|
+
const err = new Error(
|
|
191
|
+
'ANTHROPIC_API_KEY is not set. The prompt evaluator needs an Anthropic API key — set ANTHROPIC_API_KEY in the chroxy server environment to use this feature.',
|
|
192
|
+
)
|
|
193
|
+
err.code = 'EVALUATOR_NO_API_KEY'
|
|
194
|
+
throw err
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const anthropic = client || new Anthropic({ apiKey: resolvedKey })
|
|
198
|
+
const resolvedModel = model || process.env.CHROXY_EVALUATOR_MODEL || DEFAULT_MODEL
|
|
199
|
+
|
|
200
|
+
const userMessage = cwd
|
|
201
|
+
? `Session cwd: ${cwd}\n\nDraft message:\n${draft}`
|
|
202
|
+
: `Draft message:\n${draft}`
|
|
203
|
+
|
|
204
|
+
const resolvedTimeoutMs = _resolveTimeoutMs(timeoutMs)
|
|
205
|
+
const controller = new AbortController()
|
|
206
|
+
const timer = setTimeout(() => controller.abort(), resolvedTimeoutMs)
|
|
207
|
+
|
|
208
|
+
let response
|
|
209
|
+
try {
|
|
210
|
+
response = await anthropic.messages.create(
|
|
211
|
+
{
|
|
212
|
+
model: resolvedModel,
|
|
213
|
+
max_tokens: MAX_OUTPUT_TOKENS,
|
|
214
|
+
system: SYSTEM_PROMPT,
|
|
215
|
+
messages: [{ role: 'user', content: userMessage }],
|
|
216
|
+
},
|
|
217
|
+
{ signal: controller.signal },
|
|
218
|
+
)
|
|
219
|
+
} catch (err) {
|
|
220
|
+
// #3651 — distinguish a timeout-driven abort from an upstream API error.
|
|
221
|
+
// `controller.signal.aborted` is true iff our setTimeout fired (we never
|
|
222
|
+
// abort for any other reason in this function), so it's the most
|
|
223
|
+
// reliable signal even if the SDK surfaces the rejection without an
|
|
224
|
+
// AbortError name. EVALUATOR_TIMEOUT bypasses the API-error sanitizer
|
|
225
|
+
// because there is no upstream status to surface. The auto-evaluator
|
|
226
|
+
// handler treats it the same as EVALUATOR_API_ERROR (fail-open: forward
|
|
227
|
+
// original draft) — see input-handlers.js fail-open catch.
|
|
228
|
+
if (controller.signal.aborted) {
|
|
229
|
+
const timeoutErr = new Error(`Evaluator request timed out after ${resolvedTimeoutMs}ms`)
|
|
230
|
+
timeoutErr.code = 'EVALUATOR_TIMEOUT'
|
|
231
|
+
timeoutErr.cause = err
|
|
232
|
+
log.warn(`Anthropic API call timed out after ${resolvedTimeoutMs}ms`)
|
|
233
|
+
throw timeoutErr
|
|
234
|
+
}
|
|
235
|
+
// Log the sanitized bucket only — `log.warn` is fanned out to paired WS
|
|
236
|
+
// clients as `log_entry` events (see addLogListener in ws-server.js), so
|
|
237
|
+
// the raw upstream message is just as much of a leak channel as the
|
|
238
|
+
// `evaluate_draft_result.error.message` payload we already sanitize.
|
|
239
|
+
const sanitized = _sanitizeApiError(err)
|
|
240
|
+
log.warn(`Anthropic API call failed: ${sanitized}`)
|
|
241
|
+
const wrapped = new Error(sanitized)
|
|
242
|
+
wrapped.code = 'EVALUATOR_API_ERROR'
|
|
243
|
+
// #3100: surface the upstream HTTP status so the WS handler (and
|
|
244
|
+
// dashboard) can branch on auth vs rate-limit vs 5xx without parsing
|
|
245
|
+
// the sanitized message string. Only set when the SDK gave us a real
|
|
246
|
+
// numeric status — network errors and timeouts leave it undefined.
|
|
247
|
+
if (typeof err?.status === 'number') {
|
|
248
|
+
wrapped.status = err.status
|
|
249
|
+
}
|
|
250
|
+
wrapped.cause = err
|
|
251
|
+
throw wrapped
|
|
252
|
+
} finally {
|
|
253
|
+
// Clear the timer regardless of outcome so we never leak a pending
|
|
254
|
+
// setTimeout into the event loop. clearTimeout is a no-op if the timer
|
|
255
|
+
// already fired (the abort path above) or hasn't fired (fast-path).
|
|
256
|
+
clearTimeout(timer)
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
const text = _extractText(response)
|
|
260
|
+
return _parseEvaluatorResponse(text)
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* Resolve the timeout in milliseconds for a single evaluator call.
|
|
265
|
+
*
|
|
266
|
+
* Precedence: explicit `timeoutMs` arg > `CHROXY_EVALUATOR_TIMEOUT_MS` env >
|
|
267
|
+
* `DEFAULT_TIMEOUT_MS`. Non-numeric, non-positive, or oversized values are
|
|
268
|
+
* rejected and fall through to the next source — we never want a 0/negative
|
|
269
|
+
* deadline to silently turn into "abort instantly", and Node `setTimeout`
|
|
270
|
+
* clamps delays above the i32 ceiling (`MAX_SAFE_TIMEOUT`, ~24.8 days) down
|
|
271
|
+
* to 1ms, which would turn a misconfigured "very large" timeout into a near-
|
|
272
|
+
* immediate abort. Reject oversized values rather than silently clamping —
|
|
273
|
+
* the operator gets the default (and a misconfigured env var doesn't
|
|
274
|
+
* silently break the feature).
|
|
275
|
+
*/
|
|
276
|
+
const MAX_SAFE_TIMEOUT_MS = 2_147_483_647
|
|
277
|
+
function _resolveTimeoutMs(arg) {
|
|
278
|
+
if (typeof arg === 'number' && Number.isFinite(arg) && arg > 0 && arg <= MAX_SAFE_TIMEOUT_MS) return arg
|
|
279
|
+
const envSource = process.env.CHROXY_EVALUATOR_TIMEOUT_MS
|
|
280
|
+
if (typeof envSource === 'string' && envSource.length > 0) {
|
|
281
|
+
const parsed = Number.parseInt(envSource, 10)
|
|
282
|
+
if (Number.isFinite(parsed) && parsed > 0 && parsed <= MAX_SAFE_TIMEOUT_MS) return parsed
|
|
283
|
+
}
|
|
284
|
+
return DEFAULT_TIMEOUT_MS
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* Map an Anthropic SDK / network error to a sanitized, client-safe message.
|
|
289
|
+
*
|
|
290
|
+
* The raw `err.message` from `@anthropic-ai/sdk` can leak internals — request
|
|
291
|
+
* IDs, account/billing hints, IPs, model identifiers — that we don't want to
|
|
292
|
+
* fan out to every paired WS client. We bucket on `err.status` (the SDK's
|
|
293
|
+
* `APIError` exposes it) and fall back to a generic string. The original
|
|
294
|
+
* error is attached to `wrapped.cause` for in-process propagation; the
|
|
295
|
+
* server logger is string-only and doesn't auto-stringify causes, so
|
|
296
|
+
* `wrapped.cause` is NOT visible in `log_entry` broadcasts.
|
|
297
|
+
*/
|
|
298
|
+
function _sanitizeApiError(err) {
|
|
299
|
+
const status = typeof err?.status === 'number' ? err.status : null
|
|
300
|
+
if (status === 401 || status === 403) {
|
|
301
|
+
return 'Evaluator authentication failed (check ANTHROPIC_API_KEY)'
|
|
302
|
+
}
|
|
303
|
+
if (status === 429) {
|
|
304
|
+
return 'Evaluator rate limited'
|
|
305
|
+
}
|
|
306
|
+
if (status !== null && status >= 500 && status < 600) {
|
|
307
|
+
return 'Evaluator service unavailable'
|
|
308
|
+
}
|
|
309
|
+
if (status === null) {
|
|
310
|
+
return 'Evaluator network error'
|
|
311
|
+
}
|
|
312
|
+
return 'Evaluator API call failed'
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* Extract the assistant text from a messages.create response.
|
|
317
|
+
* The SDK returns content as an array of typed blocks; we want the first text block.
|
|
318
|
+
*/
|
|
319
|
+
function _extractText(response) {
|
|
320
|
+
const blocks = Array.isArray(response?.content) ? response.content : []
|
|
321
|
+
for (const block of blocks) {
|
|
322
|
+
if (block?.type === 'text' && typeof block.text === 'string') return block.text
|
|
323
|
+
}
|
|
324
|
+
return ''
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/**
|
|
328
|
+
* Parse and validate the model's JSON response.
|
|
329
|
+
* Throws EVALUATOR_BAD_RESPONSE if the response isn't usable so the handler
|
|
330
|
+
* can surface a specific error to the client instead of silently 'forward'-ing.
|
|
331
|
+
*/
|
|
332
|
+
function _parseEvaluatorResponse(text) {
|
|
333
|
+
const trimmed = (text || '').trim()
|
|
334
|
+
if (!trimmed) {
|
|
335
|
+
const err = new Error('Evaluator returned an empty response')
|
|
336
|
+
err.code = 'EVALUATOR_BAD_RESPONSE'
|
|
337
|
+
throw err
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
// Models occasionally wrap the JSON in ```json fences despite instructions.
|
|
341
|
+
// Strip the most common wrapper before parsing.
|
|
342
|
+
const unwrapped = trimmed.replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/, '')
|
|
343
|
+
|
|
344
|
+
let parsed
|
|
345
|
+
try {
|
|
346
|
+
parsed = JSON.parse(unwrapped)
|
|
347
|
+
} catch (err) {
|
|
348
|
+
const wrapped = new Error(`Evaluator returned invalid JSON: ${err.message}`)
|
|
349
|
+
wrapped.code = 'EVALUATOR_BAD_RESPONSE'
|
|
350
|
+
throw wrapped
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
if (!parsed || typeof parsed !== 'object') {
|
|
354
|
+
const err = new Error('Evaluator response was not a JSON object')
|
|
355
|
+
err.code = 'EVALUATOR_BAD_RESPONSE'
|
|
356
|
+
throw err
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
const verdict = parsed.verdict
|
|
360
|
+
if (!VALID_VERDICTS.has(verdict)) {
|
|
361
|
+
const err = new Error(`Evaluator returned an unknown verdict: ${JSON.stringify(verdict)}`)
|
|
362
|
+
err.code = 'EVALUATOR_BAD_RESPONSE'
|
|
363
|
+
throw err
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
const rewritten = typeof parsed.rewritten === 'string' && parsed.rewritten.trim()
|
|
367
|
+
? parsed.rewritten.trim()
|
|
368
|
+
: null
|
|
369
|
+
const clarification = typeof parsed.clarification === 'string' && parsed.clarification.trim()
|
|
370
|
+
? parsed.clarification.trim()
|
|
371
|
+
: null
|
|
372
|
+
const reasoning = typeof parsed.reasoning === 'string' ? parsed.reasoning.trim() : ''
|
|
373
|
+
|
|
374
|
+
if (verdict === 'rewrite' && !rewritten) {
|
|
375
|
+
const err = new Error('Evaluator verdict was "rewrite" but no rewritten text was provided')
|
|
376
|
+
err.code = 'EVALUATOR_BAD_RESPONSE'
|
|
377
|
+
throw err
|
|
378
|
+
}
|
|
379
|
+
if (verdict === 'clarify' && !clarification) {
|
|
380
|
+
const err = new Error('Evaluator verdict was "clarify" but no clarification question was provided')
|
|
381
|
+
err.code = 'EVALUATOR_BAD_RESPONSE'
|
|
382
|
+
throw err
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
return { verdict, rewritten, clarification, reasoning }
|
|
386
|
+
}
|