@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,201 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Conversation, history, and cost summary handlers.
|
|
3
|
+
*
|
|
4
|
+
* Handles: list_conversations, search_conversations, resume_conversation,
|
|
5
|
+
* request_full_history, request_session_context, request_cost_summary
|
|
6
|
+
*/
|
|
7
|
+
import { scanConversations as defaultScanConversations } from '../conversation-scanner.js'
|
|
8
|
+
import { searchConversations as defaultSearchConversations } from '../conversation-search.js'
|
|
9
|
+
import { validateCwdAllowed, broadcastFocusChanged, resolveSession, autoSubscribeOtherClients, buildSessionTokenMismatchPayload, sendSessionError } from '../handler-utils.js'
|
|
10
|
+
import { scopeConversationsToClient } from '../conversation-scope.js'
|
|
11
|
+
import { createLogger, loggerForSession } from '../logger.js'
|
|
12
|
+
|
|
13
|
+
const log = createLogger('ws')
|
|
14
|
+
|
|
15
|
+
async function handleListConversations(ws, client, msg, ctx) {
|
|
16
|
+
// ctx.scanConversations override allows tests to inject a stub and skip real fs.
|
|
17
|
+
const scan = ctx.scanConversations || defaultScanConversations
|
|
18
|
+
try {
|
|
19
|
+
// Pass provider-driven projectsDirs when available (#2965); falls back to
|
|
20
|
+
// the scanner's default (~/.claude/projects) when not set.
|
|
21
|
+
const scanOpts = ctx.runtime.projectsDirs ? { projectsDirs: ctx.runtime.projectsDirs } : {}
|
|
22
|
+
const all = await scan(scanOpts)
|
|
23
|
+
// Adversary A8: scope results so a bound pairing-issued client
|
|
24
|
+
// cannot enumerate conversations outside its session cwd.
|
|
25
|
+
const conversations = scopeConversationsToClient(all, client, ctx)
|
|
26
|
+
ctx.transport.send(ws, { type: 'conversations_list', conversations })
|
|
27
|
+
} catch (err) {
|
|
28
|
+
log.warn(`Failed to scan conversations: ${err.message}`)
|
|
29
|
+
ctx.transport.send(ws, { type: 'conversations_list', conversations: [] })
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
async function handleSearchConversations(ws, client, msg, ctx) {
|
|
34
|
+
const { query, maxResults } = msg
|
|
35
|
+
const search = ctx.searchConversations || defaultSearchConversations
|
|
36
|
+
try {
|
|
37
|
+
const all = await search(query, { maxResults })
|
|
38
|
+
// Adversary A8: scope the search result set to the bound session's
|
|
39
|
+
// cwd. Without this, a mobile client could substring-grep every
|
|
40
|
+
// JSONL on disk for secrets-in-transcripts.
|
|
41
|
+
const results = scopeConversationsToClient(all, client, ctx)
|
|
42
|
+
ctx.transport.send(ws, { type: 'search_results', query, results })
|
|
43
|
+
} catch (err) {
|
|
44
|
+
log.warn(`Failed to search conversations: ${err.message}`)
|
|
45
|
+
ctx.transport.send(ws, { type: 'search_results', query, results: [] })
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async function handleResumeConversation(ws, client, msg, ctx) {
|
|
50
|
+
// Bound clients cannot create new sessions via resume
|
|
51
|
+
if (client.boundSessionId) {
|
|
52
|
+
// See #2904 — include bound session name so the client can show an
|
|
53
|
+
// actionable message instead of an opaque "Not authorized".
|
|
54
|
+
// Issue #2912: shape is shared with every other SESSION_TOKEN_MISMATCH
|
|
55
|
+
// emit site via buildSessionTokenMismatchPayload.
|
|
56
|
+
ctx.transport.send(ws, {
|
|
57
|
+
type: 'session_error',
|
|
58
|
+
...buildSessionTokenMismatchPayload({
|
|
59
|
+
sessionManager: ctx.sessions.sessionManager,
|
|
60
|
+
boundSessionId: client.boundSessionId,
|
|
61
|
+
message: 'Not authorized: client is bound to a specific session',
|
|
62
|
+
}),
|
|
63
|
+
})
|
|
64
|
+
return
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// Check resume capability on the active session's provider
|
|
68
|
+
const activeEntry = client.activeSessionId && ctx.sessions.sessionManager.getSession(client.activeSessionId)
|
|
69
|
+
if (activeEntry && !activeEntry.session.constructor.capabilities?.resume) {
|
|
70
|
+
sendSessionError(ws, ctx, 'This provider does not support conversation resume')
|
|
71
|
+
return
|
|
72
|
+
}
|
|
73
|
+
const { conversationId, cwd } = msg
|
|
74
|
+
if (!conversationId || typeof conversationId !== 'string') {
|
|
75
|
+
sendSessionError(ws, ctx, 'Missing conversationId')
|
|
76
|
+
return
|
|
77
|
+
}
|
|
78
|
+
// Validate conversationId is a UUID to prevent path traversal
|
|
79
|
+
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(conversationId)) {
|
|
80
|
+
sendSessionError(ws, ctx, 'Invalid conversationId format')
|
|
81
|
+
return
|
|
82
|
+
}
|
|
83
|
+
if (cwd) {
|
|
84
|
+
const cwdError = validateCwdAllowed(cwd, ctx.services.config)
|
|
85
|
+
if (cwdError) {
|
|
86
|
+
sendSessionError(ws, ctx, cwdError)
|
|
87
|
+
return
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
try {
|
|
91
|
+
const name = (typeof msg.name === 'string' && msg.name.trim()) ? msg.name.trim() : 'Resumed'
|
|
92
|
+
const sessionId = ctx.sessions.sessionManager.createSession({
|
|
93
|
+
resumeSessionId: conversationId,
|
|
94
|
+
cwd: cwd || undefined,
|
|
95
|
+
name,
|
|
96
|
+
})
|
|
97
|
+
// #5563: index-maintaining helpers.
|
|
98
|
+
ctx.transport.setActiveSession(client, sessionId)
|
|
99
|
+
ctx.transport.subscribeClient(client, sessionId)
|
|
100
|
+
const entry = ctx.sessions.sessionManager.getSession(sessionId)
|
|
101
|
+
ctx.transport.send(ws, { type: 'session_switched', sessionId, name: entry.name, cwd: entry.cwd, conversationId: entry.session.resumeSessionId || null })
|
|
102
|
+
ctx.transport.sendSessionInfo(ws, sessionId)
|
|
103
|
+
ctx.transport.replayHistory(ws, sessionId)
|
|
104
|
+
ctx.transport.broadcastSessionList()
|
|
105
|
+
autoSubscribeOtherClients(sessionId, ws, ctx)
|
|
106
|
+
broadcastFocusChanged(client, sessionId, ctx)
|
|
107
|
+
} catch (err) {
|
|
108
|
+
sendSessionError(ws, ctx, err.message)
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async function handleRequestFullHistory(ws, client, msg, ctx) {
|
|
113
|
+
const targetId = (typeof msg.sessionId === 'string' && msg.sessionId) || client.activeSessionId
|
|
114
|
+
if (!targetId || !resolveSession(ctx, msg, client)) {
|
|
115
|
+
const message = msg.sessionId
|
|
116
|
+
? `Session not found: ${msg.sessionId}`
|
|
117
|
+
: 'No active session'
|
|
118
|
+
sendSessionError(ws, ctx, message)
|
|
119
|
+
return
|
|
120
|
+
}
|
|
121
|
+
const fullHistory = await ctx.sessions.sessionManager.getFullHistoryAsync(targetId)
|
|
122
|
+
ctx.transport.send(ws, { type: 'history_replay_start', sessionId: targetId, fullHistory: true })
|
|
123
|
+
for (const entry of fullHistory) {
|
|
124
|
+
if (entry.type === 'user_input' || entry.type === 'response' || entry.type === 'tool_use') {
|
|
125
|
+
ctx.transport.send(ws, {
|
|
126
|
+
type: 'message',
|
|
127
|
+
messageType: entry.type,
|
|
128
|
+
content: entry.content,
|
|
129
|
+
tool: entry.tool,
|
|
130
|
+
timestamp: entry.timestamp,
|
|
131
|
+
sessionId: targetId,
|
|
132
|
+
})
|
|
133
|
+
} else {
|
|
134
|
+
ctx.transport.send(ws, { ...entry, sessionId: targetId })
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
ctx.transport.send(ws, { type: 'history_replay_end', sessionId: targetId })
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async function handleRequestSessionContext(ws, client, msg, ctx) {
|
|
141
|
+
const targetId = (typeof msg.sessionId === 'string' && msg.sessionId) || client.activeSessionId
|
|
142
|
+
if (!targetId) {
|
|
143
|
+
sendSessionError(ws, ctx, 'No active session')
|
|
144
|
+
return
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// Enforce session binding
|
|
148
|
+
if (client.boundSessionId && client.boundSessionId !== targetId) {
|
|
149
|
+
ctx.transport.send(ws, {
|
|
150
|
+
type: 'session_error',
|
|
151
|
+
...buildSessionTokenMismatchPayload({
|
|
152
|
+
sessionManager: ctx.sessions.sessionManager,
|
|
153
|
+
boundSessionId: client.boundSessionId,
|
|
154
|
+
}),
|
|
155
|
+
})
|
|
156
|
+
return
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
try {
|
|
160
|
+
const sessionCtx = await ctx.sessions.sessionManager.getSessionContext(targetId)
|
|
161
|
+
if (sessionCtx) {
|
|
162
|
+
ctx.transport.send(ws, { type: 'session_context', ...sessionCtx })
|
|
163
|
+
} else {
|
|
164
|
+
sendSessionError(ws, ctx, `Session not found: ${targetId}`)
|
|
165
|
+
}
|
|
166
|
+
} catch (err) {
|
|
167
|
+
// #4828: session-scoped — `targetId` is the active session ID in
|
|
168
|
+
// scope. Legacy single-session callers may surface an empty value,
|
|
169
|
+
// so fall back to module-level `log` rather than throwing inside
|
|
170
|
+
// loggerForSession (same pattern as the settings-handlers sites).
|
|
171
|
+
;(targetId ? loggerForSession('ws', targetId) : log).warn(`Failed to read session context: ${err.message}`)
|
|
172
|
+
sendSessionError(ws, ctx, `Failed to read session context: ${err.message}`)
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function handleRequestCostSummary(ws, client, msg, ctx) {
|
|
177
|
+
const costSessions = ctx.sessions.sessionManager.listSessions()
|
|
178
|
+
const sessionCosts = costSessions.map(s => ({
|
|
179
|
+
sessionId: s.sessionId,
|
|
180
|
+
name: s.name,
|
|
181
|
+
cost: ctx.sessions.sessionManager.getSessionCost(s.sessionId),
|
|
182
|
+
model: s.model || null,
|
|
183
|
+
}))
|
|
184
|
+
ctx.transport.send(ws, {
|
|
185
|
+
type: 'cost_summary',
|
|
186
|
+
totalCost: ctx.sessions.sessionManager.getTotalCost(),
|
|
187
|
+
budget: ctx.sessions.sessionManager.getCostBudget(),
|
|
188
|
+
sessions: sessionCosts,
|
|
189
|
+
costByModel: ctx.sessions.sessionManager.getCostByModel(),
|
|
190
|
+
spendRate: ctx.sessions.sessionManager.getSpendRate(),
|
|
191
|
+
})
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
export const conversationHandlers = {
|
|
195
|
+
list_conversations: handleListConversations,
|
|
196
|
+
search_conversations: handleSearchConversations,
|
|
197
|
+
resume_conversation: handleResumeConversation,
|
|
198
|
+
request_full_history: handleRequestFullHistory,
|
|
199
|
+
request_session_context: handleRequestSessionContext,
|
|
200
|
+
request_cost_summary: handleRequestCostSummary,
|
|
201
|
+
}
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Provider credential settings handlers — split out of settings-handlers.js
|
|
3
|
+
* (audit P2-4, pure move). BYOK + generic provider credential get/set/delete/
|
|
4
|
+
* test + OAuth status. Writes require host-level authority (a pairing-bound
|
|
5
|
+
* token is rejected); status reads are open to any authenticated client.
|
|
6
|
+
*/
|
|
7
|
+
import { sendError } from '../handler-utils.js'
|
|
8
|
+
import { getAnthropicApiKeyStatus } from '../byok-credentials.js'
|
|
9
|
+
import {
|
|
10
|
+
getCredentialsStatus,
|
|
11
|
+
setStoredCredential,
|
|
12
|
+
deleteStoredCredential,
|
|
13
|
+
isKnownCredentialKey,
|
|
14
|
+
} from '../credential-store.js'
|
|
15
|
+
import { testCredential } from '../credential-test.js'
|
|
16
|
+
import {
|
|
17
|
+
hasClaudeOAuthCreds,
|
|
18
|
+
hasGeminiOAuthCreds,
|
|
19
|
+
hasCodexOAuthCreds,
|
|
20
|
+
} from '../auth-probes.js'
|
|
21
|
+
import { createLogger, loggerForSession } from '../logger.js'
|
|
22
|
+
|
|
23
|
+
const log = createLogger('ws')
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* #5155: gate credential WRITES (set/delete/clear) behind the primary token.
|
|
27
|
+
*
|
|
28
|
+
* Reads are safe (status is masked, value-free) and stay open to every
|
|
29
|
+
* authenticated client. But a WRITE lets the caller swap in or clear the
|
|
30
|
+
* operator's provider keys — a pairing-bound (share-a-session) token doing so is
|
|
31
|
+
* a billing-redirection / integrity / DoS risk distinct from "use the existing
|
|
32
|
+
* credentials". So credential mutations now require host-level authority: a
|
|
33
|
+
* pairing-issued session token (client.boundSessionId set) is rejected, exactly
|
|
34
|
+
* like the auto-permission-mode escalation gate above. Only the primary API
|
|
35
|
+
* token (or an unbound linking-mode pairing token, both with boundSessionId
|
|
36
|
+
* unset) can write.
|
|
37
|
+
*
|
|
38
|
+
* Returns true and sends the rejection if the client is bound (caller must
|
|
39
|
+
* early-return); false to proceed. See docs/security/bearer-token-authority.md.
|
|
40
|
+
*
|
|
41
|
+
* @param {object} ws
|
|
42
|
+
* @param {object} client
|
|
43
|
+
* @param {object} msg
|
|
44
|
+
* @returns {boolean} true if the write was rejected.
|
|
45
|
+
*/
|
|
46
|
+
function rejectCredentialWriteIfBound(ws, client, msg, ctx) {
|
|
47
|
+
if (!client?.boundSessionId) return false
|
|
48
|
+
loggerForSession('ws', client.boundSessionId).warn(`Client ${client.id} (bound to ${client.boundSessionId}) attempted to modify provider credentials — rejected`)
|
|
49
|
+
// #5632: route through ctx.transport so the error is encrypted for a
|
|
50
|
+
// post-handshake host.
|
|
51
|
+
sendError(ws, msg?.requestId, 'CREDENTIAL_WRITE_FORBIDDEN_BOUND_CLIENT',
|
|
52
|
+
'Pairing-issued session tokens cannot modify provider credentials. Use the primary API token from a device with physical access to this machine.', undefined, ctx)
|
|
53
|
+
return true
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* BYOK credentials handlers (#4052).
|
|
57
|
+
*
|
|
58
|
+
* Three message types: get status, set the key, clear the key. The full
|
|
59
|
+
* key is never sent back over the wire — only its masked form via
|
|
60
|
+
* `getAnthropicApiKeyStatus`. Errors are surfaced via sendError;
|
|
61
|
+
* success replies go back to the calling ws AND broadcast to all
|
|
62
|
+
* authenticated clients so additional dashboards / tabs stay in sync.
|
|
63
|
+
*
|
|
64
|
+
* Auth posture: status reads are open to any authenticated WS client. WRITES
|
|
65
|
+
* (set/clear) require host-level authority — a pairing-bound session token is
|
|
66
|
+
* rejected via `rejectCredentialWriteIfBound` (#5155).
|
|
67
|
+
*
|
|
68
|
+
* #5867: set/clear now go through the canonical `setStoredCredential` /
|
|
69
|
+
* `deleteStoredCredential` (merge + at-rest encryption) instead of the legacy
|
|
70
|
+
* whole-file overwrite/unlink, so a BYOK write no longer wipes sibling provider
|
|
71
|
+
* keys or downgrades an encrypted store to plaintext. The status surface stays
|
|
72
|
+
* the BYOK-specific `getAnthropicApiKeyStatus` for dashboard back-compat.
|
|
73
|
+
*/
|
|
74
|
+
function handleByokGetCredentialsStatus(ws, client, msg, ctx) {
|
|
75
|
+
const status = getAnthropicApiKeyStatus()
|
|
76
|
+
ctx.transport.send(ws, { type: 'byok_credentials_status', requestId: msg?.requestId, ...status })
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function handleByokSetCredentials(ws, client, msg, ctx) {
|
|
80
|
+
if (rejectCredentialWriteIfBound(ws, client, msg, ctx)) return
|
|
81
|
+
// Trim leading/trailing whitespace — pastes often carry surrounding
|
|
82
|
+
// spaces/newlines that would otherwise be persisted into the credentials
|
|
83
|
+
// file and silently fail when the SDK tries to use the key.
|
|
84
|
+
const key = typeof msg?.anthropicApiKey === 'string' ? msg.anthropicApiKey.trim() : msg?.anthropicApiKey
|
|
85
|
+
if (typeof key !== 'string' || key.length === 0) {
|
|
86
|
+
sendError(ws, msg?.requestId, 'INVALID_REQUEST', 'anthropicApiKey is required', undefined, ctx)
|
|
87
|
+
return
|
|
88
|
+
}
|
|
89
|
+
// Reject anything that doesn't even look like a key BEFORE persisting (the
|
|
90
|
+
// store validates too, but this gives the nicer BYOK-specific error). The
|
|
91
|
+
// Anthropic key format starts with `sk-ant-`; the prefix check catches
|
|
92
|
+
// obvious wrong-thing pastes (OpenAI keys, OAuth tokens).
|
|
93
|
+
if (!key.startsWith('sk-ant-')) {
|
|
94
|
+
sendError(ws, msg?.requestId, 'INVALID_REQUEST', 'API key must start with sk-ant-', undefined, ctx)
|
|
95
|
+
return
|
|
96
|
+
}
|
|
97
|
+
try {
|
|
98
|
+
// Merge into the canonical store (encrypt-at-rest aware) — never the legacy
|
|
99
|
+
// whole-file overwrite that wiped sibling provider keys (#5867).
|
|
100
|
+
setStoredCredential('ANTHROPIC_API_KEY', key)
|
|
101
|
+
} catch (err) {
|
|
102
|
+
log.warn(`byok_set_credentials write failed: ${err?.message}`)
|
|
103
|
+
sendError(ws, msg?.requestId, 'CREDENTIALS_WRITE_FAILED', err?.message || 'write failed', undefined, ctx)
|
|
104
|
+
return
|
|
105
|
+
}
|
|
106
|
+
const status = getAnthropicApiKeyStatus()
|
|
107
|
+
// Reply to the originating client with the requestId for await-resolution.
|
|
108
|
+
ctx.transport.send(ws, { type: 'byok_credentials_status', requestId: msg?.requestId, ...status })
|
|
109
|
+
// Broadcast without requestId so other dashboards / clients update too.
|
|
110
|
+
// Without this, a second dashboard would keep showing stale state until
|
|
111
|
+
// the user re-opened Settings.
|
|
112
|
+
if (typeof ctx.transport.broadcast === 'function') {
|
|
113
|
+
ctx.transport.broadcast({ type: 'byok_credentials_status', ...status })
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function handleByokClearCredentials(ws, client, msg, ctx) {
|
|
118
|
+
if (rejectCredentialWriteIfBound(ws, client, msg, ctx)) return
|
|
119
|
+
try {
|
|
120
|
+
// Remove only the Anthropic key from the canonical store — siblings (and
|
|
121
|
+
// the encrypted envelope) survive; the file is unlinked only when empty.
|
|
122
|
+
deleteStoredCredential('ANTHROPIC_API_KEY')
|
|
123
|
+
} catch (err) {
|
|
124
|
+
sendError(ws, msg?.requestId, 'CREDENTIALS_CLEAR_FAILED', err?.message || 'clear failed', undefined, ctx)
|
|
125
|
+
return
|
|
126
|
+
}
|
|
127
|
+
const status = getAnthropicApiKeyStatus()
|
|
128
|
+
ctx.transport.send(ws, { type: 'byok_credentials_status', requestId: msg?.requestId, ...status })
|
|
129
|
+
if (typeof ctx.transport.broadcast === 'function') {
|
|
130
|
+
ctx.transport.broadcast({ type: 'byok_credentials_status', ...status })
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Provider Credentials handlers (#3855).
|
|
136
|
+
*
|
|
137
|
+
* Generalizes the BYOK handlers above to every known provider credential key
|
|
138
|
+
* (ANTHROPIC_API_KEY, CLAUDE_CODE_OAUTH_TOKEN, GEMINI_API_KEY, OPENAI_API_KEY)
|
|
139
|
+
* plus read-only OAuth status. The raw value is NEVER sent back — set/delete
|
|
140
|
+
* reply with the same masked `credentials_status` snapshot the status query
|
|
141
|
+
* returns.
|
|
142
|
+
*
|
|
143
|
+
* Auth posture (#5155): status reads are open to any authenticated WS client
|
|
144
|
+
* (the snapshot is masked and value-free). WRITES (set/delete) require
|
|
145
|
+
* host-level authority — a pairing-bound session token is rejected via
|
|
146
|
+
* `rejectCredentialWriteIfBound`, mirroring the auto-permission-mode escalation
|
|
147
|
+
* gate. Overwriting the operator's provider keys is a billing/integrity/DoS
|
|
148
|
+
* vector distinct from "use the existing credentials a session resolves", so a
|
|
149
|
+
* bound token must not be able to swap or clear them. See
|
|
150
|
+
* docs/security/bearer-token-authority.md.
|
|
151
|
+
*/
|
|
152
|
+
const CREDENTIAL_OAUTH_HELPERS = Object.freeze({
|
|
153
|
+
hasClaudeOAuthCreds,
|
|
154
|
+
hasGeminiOAuthCreds,
|
|
155
|
+
hasCodexOAuthCreds,
|
|
156
|
+
})
|
|
157
|
+
|
|
158
|
+
// #3855 (Copilot review): the status is sent ONLY to the requesting client —
|
|
159
|
+
// no broadcast. The issue acceptance criteria require "no broadcast —
|
|
160
|
+
// credentials are admin state, sent only to the requester." Broadcasting (even
|
|
161
|
+
// masked) would leak which providers are configured + masked previews to other
|
|
162
|
+
// authenticated clients, including pairing-bound ones. Other dashboards refresh
|
|
163
|
+
// their own view on open via get_credentials_status instead.
|
|
164
|
+
function _sendCredentialsStatus(ctx, ws, requestId) {
|
|
165
|
+
const status = getCredentialsStatus(CREDENTIAL_OAUTH_HELPERS)
|
|
166
|
+
ctx.transport.send(ws, { type: 'credentials_status', requestId: requestId ?? null, ...status })
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function handleGetCredentialsStatus(ws, client, msg, ctx) {
|
|
170
|
+
_sendCredentialsStatus(ctx, ws, msg?.requestId)
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function handleSetCredential(ws, client, msg, ctx) {
|
|
174
|
+
if (rejectCredentialWriteIfBound(ws, client, msg, ctx)) return
|
|
175
|
+
const key = typeof msg?.key === 'string' ? msg.key : ''
|
|
176
|
+
if (!isKnownCredentialKey(key)) {
|
|
177
|
+
sendError(ws, msg?.requestId, 'INVALID_REQUEST', `Unknown credential key: ${key}`, undefined, ctx)
|
|
178
|
+
return
|
|
179
|
+
}
|
|
180
|
+
if (typeof msg?.value !== 'string' || msg.value.trim().length === 0) {
|
|
181
|
+
sendError(ws, msg?.requestId, 'INVALID_REQUEST', 'value is required', undefined, ctx)
|
|
182
|
+
return
|
|
183
|
+
}
|
|
184
|
+
try {
|
|
185
|
+
// setStoredCredential trims + validates the value (e.g. sk-ant- / sk-
|
|
186
|
+
// prefix) and persists atomically at mode 0600.
|
|
187
|
+
setStoredCredential(key, msg.value)
|
|
188
|
+
} catch (err) {
|
|
189
|
+
// err.message is validation text or a file-mode reason — never the value.
|
|
190
|
+
log.warn(`set_credential failed for ${key}: ${err?.message}`)
|
|
191
|
+
sendError(ws, msg?.requestId, 'CREDENTIAL_WRITE_FAILED', err?.message || 'write failed', undefined, ctx)
|
|
192
|
+
return
|
|
193
|
+
}
|
|
194
|
+
_sendCredentialsStatus(ctx, ws, msg?.requestId)
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function handleDeleteCredential(ws, client, msg, ctx) {
|
|
198
|
+
if (rejectCredentialWriteIfBound(ws, client, msg, ctx)) return
|
|
199
|
+
const key = typeof msg?.key === 'string' ? msg.key : ''
|
|
200
|
+
if (!isKnownCredentialKey(key)) {
|
|
201
|
+
sendError(ws, msg?.requestId, 'INVALID_REQUEST', `Unknown credential key: ${key}`, undefined, ctx)
|
|
202
|
+
return
|
|
203
|
+
}
|
|
204
|
+
try {
|
|
205
|
+
deleteStoredCredential(key)
|
|
206
|
+
} catch (err) {
|
|
207
|
+
sendError(ws, msg?.requestId, 'CREDENTIAL_CLEAR_FAILED', err?.message || 'clear failed', undefined, ctx)
|
|
208
|
+
return
|
|
209
|
+
}
|
|
210
|
+
_sendCredentialsStatus(ctx, ws, msg?.requestId)
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
async function handleTestCredential(ws, client, msg, ctx) {
|
|
214
|
+
const key = typeof msg?.key === 'string' ? msg.key : ''
|
|
215
|
+
if (!isKnownCredentialKey(key)) {
|
|
216
|
+
sendError(ws, msg?.requestId, 'INVALID_REQUEST', `Unknown credential key: ${key}`, undefined, ctx)
|
|
217
|
+
return
|
|
218
|
+
}
|
|
219
|
+
let result
|
|
220
|
+
try {
|
|
221
|
+
result = await testCredential(key)
|
|
222
|
+
} catch (err) {
|
|
223
|
+
// testCredential is defensive and shouldn't throw, but never let a raw
|
|
224
|
+
// error escape unmasked.
|
|
225
|
+
log.warn(`test_credential threw for ${key}: ${err?.message}`)
|
|
226
|
+
result = { ok: false, error: 'Credential test failed unexpectedly.' }
|
|
227
|
+
}
|
|
228
|
+
ctx.transport.send(ws, {
|
|
229
|
+
type: 'credential_test_result',
|
|
230
|
+
requestId: msg?.requestId ?? null,
|
|
231
|
+
key,
|
|
232
|
+
ok: Boolean(result.ok),
|
|
233
|
+
...(result.error ? { error: result.error } : {}),
|
|
234
|
+
...(result.model ? { model: result.model } : {}),
|
|
235
|
+
...(typeof result.latencyMs === 'number' ? { latencyMs: result.latencyMs } : {}),
|
|
236
|
+
})
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
export const credentialHandlers = {
|
|
240
|
+
byok_get_credentials_status: handleByokGetCredentialsStatus,
|
|
241
|
+
byok_set_credentials: handleByokSetCredentials,
|
|
242
|
+
byok_clear_credentials: handleByokClearCredentials,
|
|
243
|
+
get_credentials_status: handleGetCredentialsStatus,
|
|
244
|
+
set_credential: handleSetCredential,
|
|
245
|
+
delete_credential: handleDeleteCredential,
|
|
246
|
+
test_credential: handleTestCredential,
|
|
247
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Prompt evaluator WS handler (#3068, Step 1 of the ladder).
|
|
3
|
+
*
|
|
4
|
+
* Handles: evaluate_draft
|
|
5
|
+
*
|
|
6
|
+
* The handler is intentionally thin — all evaluation logic lives in
|
|
7
|
+
* prompt-evaluator.js. Here we only:
|
|
8
|
+
* - validate the inbound message shape
|
|
9
|
+
* - resolve the active session (for cwd context — optional, evaluation
|
|
10
|
+
* works without it)
|
|
11
|
+
* - call evaluateDraft and shape the response
|
|
12
|
+
* - propagate the requestId so the dashboard can correlate
|
|
13
|
+
*/
|
|
14
|
+
import { createLogger } from '../logger.js'
|
|
15
|
+
import { resolveSession } from '../handler-utils.js'
|
|
16
|
+
import { evaluateDraft as defaultEvaluateDraft } from '../prompt-evaluator.js'
|
|
17
|
+
|
|
18
|
+
const log = createLogger('ws')
|
|
19
|
+
|
|
20
|
+
// Cap the draft we'll forward to the evaluator. A 50KB draft is already
|
|
21
|
+
// pathological for a "what should I send" check; protect both the model bill
|
|
22
|
+
// and our own message-size budget.
|
|
23
|
+
const MAX_DRAFT_BYTES = 50 * 1024
|
|
24
|
+
|
|
25
|
+
async function handleEvaluateDraft(ws, client, msg, ctx) {
|
|
26
|
+
const requestId = typeof msg?.requestId === 'string' ? msg.requestId : null
|
|
27
|
+
const draft = typeof msg?.draft === 'string' ? msg.draft : ''
|
|
28
|
+
|
|
29
|
+
if (!draft.trim()) {
|
|
30
|
+
ctx.transport.send(ws, {
|
|
31
|
+
type: 'evaluate_draft_result',
|
|
32
|
+
requestId,
|
|
33
|
+
error: { code: 'INVALID_DRAFT', message: 'evaluate_draft requires a non-empty draft string' },
|
|
34
|
+
})
|
|
35
|
+
return
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
if (Buffer.byteLength(draft, 'utf8') > MAX_DRAFT_BYTES) {
|
|
39
|
+
ctx.transport.send(ws, {
|
|
40
|
+
type: 'evaluate_draft_result',
|
|
41
|
+
requestId,
|
|
42
|
+
error: {
|
|
43
|
+
code: 'DRAFT_TOO_LARGE',
|
|
44
|
+
message: `Draft exceeds ${Math.round(MAX_DRAFT_BYTES / 1024)}KB limit for evaluation`,
|
|
45
|
+
},
|
|
46
|
+
})
|
|
47
|
+
return
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// Optional: include the active session's cwd so the evaluator can ground
|
|
51
|
+
// ambiguity in the project context. Evaluation works without it; if there's
|
|
52
|
+
// no session bound, we just skip the cwd field.
|
|
53
|
+
const entry = resolveSession(ctx, msg, client)
|
|
54
|
+
const cwd = entry?.session?.cwd || null
|
|
55
|
+
|
|
56
|
+
// Tests can inject `ctx.evaluateDraft` to stub the network call without
|
|
57
|
+
// patching modules; production code never sets it and falls through to the
|
|
58
|
+
// real evaluator.
|
|
59
|
+
const evaluator = typeof ctx?.evaluateDraft === 'function' ? ctx.evaluateDraft : defaultEvaluateDraft
|
|
60
|
+
|
|
61
|
+
let result
|
|
62
|
+
try {
|
|
63
|
+
result = await evaluator({ draft, cwd })
|
|
64
|
+
} catch (err) {
|
|
65
|
+
log.warn(`evaluate_draft failed (${err.code || 'UNKNOWN'}): ${err.message}`)
|
|
66
|
+
// #3100: forward numeric upstream status when present so the dashboard
|
|
67
|
+
// can pick a recovery hint (auth vs rate-limit vs 5xx). Only attach
|
|
68
|
+
// the field when it's a real number — clients shouldn't see status
|
|
69
|
+
// for non-API errors (NO_API_KEY, BAD_RESPONSE) or network failures.
|
|
70
|
+
const errEnvelope = { code: err.code || 'EVALUATOR_ERROR', message: err.message }
|
|
71
|
+
if (typeof err.status === 'number') {
|
|
72
|
+
errEnvelope.status = err.status
|
|
73
|
+
}
|
|
74
|
+
ctx.transport.send(ws, {
|
|
75
|
+
type: 'evaluate_draft_result',
|
|
76
|
+
requestId,
|
|
77
|
+
error: errEnvelope,
|
|
78
|
+
})
|
|
79
|
+
return
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
ctx.transport.send(ws, {
|
|
83
|
+
type: 'evaluate_draft_result',
|
|
84
|
+
requestId,
|
|
85
|
+
verdict: result.verdict,
|
|
86
|
+
rewritten: result.rewritten,
|
|
87
|
+
clarification: result.clarification,
|
|
88
|
+
reasoning: result.reasoning,
|
|
89
|
+
})
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export const evaluatorHandlers = {
|
|
93
|
+
evaluate_draft: handleEvaluateDraft,
|
|
94
|
+
}
|