claude-wec 1.0.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/LICENSE +675 -0
- package/README.md +371 -0
- package/dist/api-docs.html +879 -0
- package/dist/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
- package/dist/assets/KaTeX_AMS-Regular-DMm9YOAa.woff +0 -0
- package/dist/assets/KaTeX_AMS-Regular-DRggAlZN.ttf +0 -0
- package/dist/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf +0 -0
- package/dist/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff +0 -0
- package/dist/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
- package/dist/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff +0 -0
- package/dist/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
- package/dist/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf +0 -0
- package/dist/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf +0 -0
- package/dist/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff +0 -0
- package/dist/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
- package/dist/assets/KaTeX_Fraktur-Regular-CB_wures.ttf +0 -0
- package/dist/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
- package/dist/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff +0 -0
- package/dist/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
- package/dist/assets/KaTeX_Main-Bold-Jm3AIy58.woff +0 -0
- package/dist/assets/KaTeX_Main-Bold-waoOVXN0.ttf +0 -0
- package/dist/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
- package/dist/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf +0 -0
- package/dist/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff +0 -0
- package/dist/assets/KaTeX_Main-Italic-3WenGoN9.ttf +0 -0
- package/dist/assets/KaTeX_Main-Italic-BMLOBm91.woff +0 -0
- package/dist/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
- package/dist/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
- package/dist/assets/KaTeX_Main-Regular-Dr94JaBh.woff +0 -0
- package/dist/assets/KaTeX_Main-Regular-ypZvNtVU.ttf +0 -0
- package/dist/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf +0 -0
- package/dist/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
- package/dist/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff +0 -0
- package/dist/assets/KaTeX_Math-Italic-DA0__PXp.woff +0 -0
- package/dist/assets/KaTeX_Math-Italic-flOr_0UB.ttf +0 -0
- package/dist/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
- package/dist/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf +0 -0
- package/dist/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
- package/dist/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff +0 -0
- package/dist/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
- package/dist/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff +0 -0
- package/dist/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf +0 -0
- package/dist/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf +0 -0
- package/dist/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff +0 -0
- package/dist/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
- package/dist/assets/KaTeX_Script-Regular-C5JkGWo-.ttf +0 -0
- package/dist/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
- package/dist/assets/KaTeX_Script-Regular-D5yQViql.woff +0 -0
- package/dist/assets/KaTeX_Size1-Regular-C195tn64.woff +0 -0
- package/dist/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf +0 -0
- package/dist/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
- package/dist/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf +0 -0
- package/dist/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
- package/dist/assets/KaTeX_Size2-Regular-oD1tc_U0.woff +0 -0
- package/dist/assets/KaTeX_Size3-Regular-CTq5MqoE.woff +0 -0
- package/dist/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf +0 -0
- package/dist/assets/KaTeX_Size4-Regular-BF-4gkZK.woff +0 -0
- package/dist/assets/KaTeX_Size4-Regular-DWFBv043.ttf +0 -0
- package/dist/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
- package/dist/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff +0 -0
- package/dist/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
- package/dist/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf +0 -0
- package/dist/assets/index-cIxJ4RXb.js +1226 -0
- package/dist/assets/index-oyEz69sP.css +32 -0
- package/dist/assets/vendor-codemirror-CJLzwpLB.js +39 -0
- package/dist/assets/vendor-react-DcyRfQm3.js +59 -0
- package/dist/assets/vendor-xterm-DfaPXD3y.js +66 -0
- package/dist/clear-cache.html +85 -0
- package/dist/convert-icons.md +53 -0
- package/dist/favicon.png +0 -0
- package/dist/favicon.svg +9 -0
- package/dist/generate-icons.js +49 -0
- package/dist/icons/claude-ai-icon.svg +1 -0
- package/dist/icons/codex-white.svg +3 -0
- package/dist/icons/codex.svg +3 -0
- package/dist/icons/cursor-white.svg +12 -0
- package/dist/icons/cursor.svg +1 -0
- package/dist/icons/generate-icons.md +19 -0
- package/dist/icons/icon-128x128.png +0 -0
- package/dist/icons/icon-128x128.svg +12 -0
- package/dist/icons/icon-144x144.png +0 -0
- package/dist/icons/icon-144x144.svg +12 -0
- package/dist/icons/icon-152x152.png +0 -0
- package/dist/icons/icon-152x152.svg +12 -0
- package/dist/icons/icon-192x192.png +0 -0
- package/dist/icons/icon-192x192.svg +12 -0
- package/dist/icons/icon-384x384.png +0 -0
- package/dist/icons/icon-384x384.svg +12 -0
- package/dist/icons/icon-512x512.png +0 -0
- package/dist/icons/icon-512x512.svg +12 -0
- package/dist/icons/icon-72x72.png +0 -0
- package/dist/icons/icon-72x72.svg +12 -0
- package/dist/icons/icon-96x96.png +0 -0
- package/dist/icons/icon-96x96.svg +12 -0
- package/dist/icons/icon-template.svg +12 -0
- package/dist/index.html +52 -0
- package/dist/logo-128.png +0 -0
- package/dist/logo-256.png +0 -0
- package/dist/logo-32.png +0 -0
- package/dist/logo-512.png +0 -0
- package/dist/logo-64.png +0 -0
- package/dist/logo.svg +17 -0
- package/dist/manifest.json +61 -0
- package/dist/screenshots/cli-selection.png +0 -0
- package/dist/screenshots/desktop-main.png +0 -0
- package/dist/screenshots/mobile-chat.png +0 -0
- package/dist/screenshots/tools-modal.png +0 -0
- package/dist/sw.js +49 -0
- package/package.json +109 -0
- package/server/claude-sdk.js +721 -0
- package/server/cli.js +327 -0
- package/server/cursor-cli.js +267 -0
- package/server/database/auth.db +0 -0
- package/server/database/db.js +361 -0
- package/server/database/init.sql +52 -0
- package/server/index.js +1747 -0
- package/server/middleware/auth.js +111 -0
- package/server/openai-codex.js +389 -0
- package/server/projects.js +1604 -0
- package/server/routes/agent.js +1230 -0
- package/server/routes/auth.js +135 -0
- package/server/routes/cli-auth.js +263 -0
- package/server/routes/codex.js +345 -0
- package/server/routes/commands.js +521 -0
- package/server/routes/cursor.js +795 -0
- package/server/routes/git.js +1128 -0
- package/server/routes/mcp-utils.js +48 -0
- package/server/routes/mcp.js +552 -0
- package/server/routes/projects.js +378 -0
- package/server/routes/settings.js +178 -0
- package/server/routes/taskmaster.js +1963 -0
- package/server/routes/user.js +106 -0
- package/server/utils/commandParser.js +303 -0
- package/server/utils/gitConfig.js +24 -0
- package/server/utils/mcp-detector.js +198 -0
- package/server/utils/taskmaster-websocket.js +129 -0
- package/shared/modelConstants.js +65 -0
|
@@ -0,0 +1,721 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Claude SDK Integration
|
|
3
|
+
*
|
|
4
|
+
* This module provides SDK-based integration with Claude using the @anthropic-ai/claude-agent-sdk.
|
|
5
|
+
* It mirrors the interface of claude-cli.js but uses the SDK internally for better performance
|
|
6
|
+
* and maintainability.
|
|
7
|
+
*
|
|
8
|
+
* Key features:
|
|
9
|
+
* - Direct SDK integration without child processes
|
|
10
|
+
* - Session management with abort capability
|
|
11
|
+
* - Options mapping between CLI and SDK formats
|
|
12
|
+
* - WebSocket message streaming
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { query } from '@anthropic-ai/claude-agent-sdk';
|
|
16
|
+
// Used to mint unique approval request IDs when randomUUID is not available.
|
|
17
|
+
// This keeps parallel tool approvals from colliding; it does not add any crypto/security guarantees.
|
|
18
|
+
import crypto from 'crypto';
|
|
19
|
+
import { promises as fs } from 'fs';
|
|
20
|
+
import path from 'path';
|
|
21
|
+
import os from 'os';
|
|
22
|
+
import { CLAUDE_MODELS } from '../shared/modelConstants.js';
|
|
23
|
+
|
|
24
|
+
// Session tracking: Map of session IDs to active query instances
|
|
25
|
+
const activeSessions = new Map();
|
|
26
|
+
// In-memory registry of pending tool approvals keyed by requestId.
|
|
27
|
+
// This does not persist approvals or share across processes; it exists so the
|
|
28
|
+
// SDK can pause tool execution while the UI decides what to do.
|
|
29
|
+
const pendingToolApprovals = new Map();
|
|
30
|
+
|
|
31
|
+
// Default approval timeout kept under the SDK's 60s control timeout.
|
|
32
|
+
// This does not change SDK limits; it only defines how long we wait for the UI,
|
|
33
|
+
// introduced to avoid hanging the run when no decision arrives.
|
|
34
|
+
const TOOL_APPROVAL_TIMEOUT_MS = parseInt(process.env.CLAUDE_TOOL_APPROVAL_TIMEOUT_MS, 10) || 55000;
|
|
35
|
+
|
|
36
|
+
// Generate a stable request ID for UI approval flows.
|
|
37
|
+
// This does not encode tool details or get shown to users; it exists so the UI
|
|
38
|
+
// can respond to the correct pending request without collisions.
|
|
39
|
+
function createRequestId() {
|
|
40
|
+
// if clause is used because randomUUID is not available in older Node.js versions
|
|
41
|
+
if (typeof crypto.randomUUID === 'function') {
|
|
42
|
+
return crypto.randomUUID();
|
|
43
|
+
}
|
|
44
|
+
return crypto.randomBytes(16).toString('hex');
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Wait for a UI approval decision, honoring SDK cancellation.
|
|
48
|
+
// This does not auto-approve or auto-deny; it only resolves with UI input,
|
|
49
|
+
// and it cleans up the pending map to avoid leaks, introduced to prevent
|
|
50
|
+
// replying after the SDK cancels the control request.
|
|
51
|
+
function waitForToolApproval(requestId, options = {}) {
|
|
52
|
+
const { timeoutMs = TOOL_APPROVAL_TIMEOUT_MS, signal, onCancel } = options;
|
|
53
|
+
|
|
54
|
+
return new Promise(resolve => {
|
|
55
|
+
let settled = false;
|
|
56
|
+
|
|
57
|
+
const finalize = (decision) => {
|
|
58
|
+
if (settled) return;
|
|
59
|
+
settled = true;
|
|
60
|
+
cleanup();
|
|
61
|
+
resolve(decision);
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
const cleanup = () => {
|
|
65
|
+
pendingToolApprovals.delete(requestId);
|
|
66
|
+
clearTimeout(timeout);
|
|
67
|
+
if (signal && abortHandler) {
|
|
68
|
+
signal.removeEventListener('abort', abortHandler);
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
// Timeout is local to this process; it does not override SDK timing.
|
|
73
|
+
// It exists to prevent the UI prompt from lingering indefinitely.
|
|
74
|
+
const timeout = setTimeout(() => {
|
|
75
|
+
onCancel?.('timeout');
|
|
76
|
+
finalize(null);
|
|
77
|
+
}, timeoutMs);
|
|
78
|
+
|
|
79
|
+
const abortHandler = () => {
|
|
80
|
+
// If the SDK cancels the control request, stop waiting to avoid
|
|
81
|
+
// replying after the process is no longer ready for writes.
|
|
82
|
+
onCancel?.('cancelled');
|
|
83
|
+
finalize({ cancelled: true });
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
if (signal) {
|
|
87
|
+
if (signal.aborted) {
|
|
88
|
+
onCancel?.('cancelled');
|
|
89
|
+
finalize({ cancelled: true });
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
signal.addEventListener('abort', abortHandler, { once: true });
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
pendingToolApprovals.set(requestId, (decision) => {
|
|
96
|
+
finalize(decision);
|
|
97
|
+
});
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// Resolve a pending approval. This does not validate the decision payload;
|
|
102
|
+
// validation and tool matching remain in canUseTool, which keeps this as a
|
|
103
|
+
// lightweight WebSocket -> SDK relay.
|
|
104
|
+
function resolveToolApproval(requestId, decision) {
|
|
105
|
+
const resolver = pendingToolApprovals.get(requestId);
|
|
106
|
+
if (resolver) {
|
|
107
|
+
resolver(decision);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// Match stored permission entries against a tool + input combo.
|
|
112
|
+
// This only supports exact tool names and the Bash(command:*) shorthand
|
|
113
|
+
// used by the UI; it intentionally does not implement full glob semantics,
|
|
114
|
+
// introduced to stay consistent with the UI's "Allow rule" format.
|
|
115
|
+
function matchesToolPermission(entry, toolName, input) {
|
|
116
|
+
if (!entry || !toolName) {
|
|
117
|
+
return false;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
if (entry === toolName) {
|
|
121
|
+
return true;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const bashMatch = entry.match(/^Bash\((.+):\*\)$/);
|
|
125
|
+
if (toolName === 'Bash' && bashMatch) {
|
|
126
|
+
const allowedPrefix = bashMatch[1];
|
|
127
|
+
let command = '';
|
|
128
|
+
|
|
129
|
+
if (typeof input === 'string') {
|
|
130
|
+
command = input.trim();
|
|
131
|
+
} else if (input && typeof input === 'object' && typeof input.command === 'string') {
|
|
132
|
+
command = input.command.trim();
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
if (!command) {
|
|
136
|
+
return false;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
return command.startsWith(allowedPrefix);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
return false;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Maps CLI options to SDK-compatible options format
|
|
147
|
+
* @param {Object} options - CLI options
|
|
148
|
+
* @returns {Object} SDK-compatible options
|
|
149
|
+
*/
|
|
150
|
+
function mapCliOptionsToSDK(options = {}) {
|
|
151
|
+
const { sessionId, cwd, toolsSettings, permissionMode, images } = options;
|
|
152
|
+
|
|
153
|
+
const sdkOptions = {};
|
|
154
|
+
|
|
155
|
+
// Map working directory
|
|
156
|
+
if (cwd) {
|
|
157
|
+
sdkOptions.cwd = cwd;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// Map permission mode
|
|
161
|
+
if (permissionMode && permissionMode !== 'default') {
|
|
162
|
+
sdkOptions.permissionMode = permissionMode;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// Map tool settings
|
|
166
|
+
const settings = toolsSettings || {
|
|
167
|
+
allowedTools: [],
|
|
168
|
+
disallowedTools: [],
|
|
169
|
+
skipPermissions: false
|
|
170
|
+
};
|
|
171
|
+
|
|
172
|
+
// Handle tool permissions
|
|
173
|
+
if (settings.skipPermissions && permissionMode !== 'plan') {
|
|
174
|
+
// When skipping permissions, use bypassPermissions mode
|
|
175
|
+
sdkOptions.permissionMode = 'bypassPermissions';
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// Map allowed tools (always set to avoid implicit "allow all" defaults).
|
|
179
|
+
// This does not grant permissions by itself; it just configures the SDK,
|
|
180
|
+
// introduced because leaving it undefined made the SDK treat it as "all tools allowed."
|
|
181
|
+
let allowedTools = [...(settings.allowedTools || [])];
|
|
182
|
+
|
|
183
|
+
// Add plan mode default tools
|
|
184
|
+
if (permissionMode === 'plan') {
|
|
185
|
+
const planModeTools = ['Read', 'Task', 'exit_plan_mode', 'TodoRead', 'TodoWrite', 'WebFetch', 'WebSearch'];
|
|
186
|
+
for (const tool of planModeTools) {
|
|
187
|
+
if (!allowedTools.includes(tool)) {
|
|
188
|
+
allowedTools.push(tool);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
sdkOptions.allowedTools = allowedTools;
|
|
194
|
+
|
|
195
|
+
// Map disallowed tools (always set so the SDK doesn't treat "undefined" as permissive).
|
|
196
|
+
// This does not override allowlists; it only feeds the canUseTool gate.
|
|
197
|
+
sdkOptions.disallowedTools = settings.disallowedTools || [];
|
|
198
|
+
|
|
199
|
+
// Map model (default to sonnet)
|
|
200
|
+
// Valid models: sonnet, opus, haiku, opusplan, sonnet[1m]
|
|
201
|
+
sdkOptions.model = options.model || CLAUDE_MODELS.DEFAULT;
|
|
202
|
+
console.log(`Using model: ${sdkOptions.model}`);
|
|
203
|
+
|
|
204
|
+
// Map system prompt configuration
|
|
205
|
+
sdkOptions.systemPrompt = {
|
|
206
|
+
type: 'preset',
|
|
207
|
+
preset: 'claude_code' // Required to use CLAUDE.md
|
|
208
|
+
};
|
|
209
|
+
|
|
210
|
+
// Map setting sources for CLAUDE.md loading
|
|
211
|
+
// This loads CLAUDE.md from project, user (~/.config/claude/CLAUDE.md), and local directories
|
|
212
|
+
sdkOptions.settingSources = ['project', 'user', 'local'];
|
|
213
|
+
|
|
214
|
+
// Map resume session
|
|
215
|
+
if (sessionId) {
|
|
216
|
+
sdkOptions.resume = sessionId;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
return sdkOptions;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Adds a session to the active sessions map
|
|
224
|
+
* @param {string} sessionId - Session identifier
|
|
225
|
+
* @param {Object} queryInstance - SDK query instance
|
|
226
|
+
* @param {Array<string>} tempImagePaths - Temp image file paths for cleanup
|
|
227
|
+
* @param {string} tempDir - Temp directory for cleanup
|
|
228
|
+
*/
|
|
229
|
+
function addSession(sessionId, queryInstance, tempImagePaths = [], tempDir = null) {
|
|
230
|
+
activeSessions.set(sessionId, {
|
|
231
|
+
instance: queryInstance,
|
|
232
|
+
startTime: Date.now(),
|
|
233
|
+
status: 'active',
|
|
234
|
+
tempImagePaths,
|
|
235
|
+
tempDir
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Removes a session from the active sessions map
|
|
241
|
+
* @param {string} sessionId - Session identifier
|
|
242
|
+
*/
|
|
243
|
+
function removeSession(sessionId) {
|
|
244
|
+
activeSessions.delete(sessionId);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Gets a session from the active sessions map
|
|
249
|
+
* @param {string} sessionId - Session identifier
|
|
250
|
+
* @returns {Object|undefined} Session data or undefined
|
|
251
|
+
*/
|
|
252
|
+
function getSession(sessionId) {
|
|
253
|
+
return activeSessions.get(sessionId);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* Gets all active session IDs
|
|
258
|
+
* @returns {Array<string>} Array of active session IDs
|
|
259
|
+
*/
|
|
260
|
+
function getAllSessions() {
|
|
261
|
+
return Array.from(activeSessions.keys());
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* Transforms SDK messages to WebSocket format expected by frontend
|
|
266
|
+
* @param {Object} sdkMessage - SDK message object
|
|
267
|
+
* @returns {Object} Transformed message ready for WebSocket
|
|
268
|
+
*/
|
|
269
|
+
function transformMessage(sdkMessage) {
|
|
270
|
+
// SDK messages are already in a format compatible with the frontend
|
|
271
|
+
// The CLI sends them wrapped in {type: 'claude-response', data: message}
|
|
272
|
+
// We'll do the same here to maintain compatibility
|
|
273
|
+
return sdkMessage;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* Extracts token usage from SDK result messages
|
|
278
|
+
* @param {Object} resultMessage - SDK result message
|
|
279
|
+
* @returns {Object|null} Token budget object or null
|
|
280
|
+
*/
|
|
281
|
+
function extractTokenBudget(resultMessage) {
|
|
282
|
+
if (resultMessage.type !== 'result' || !resultMessage.modelUsage) {
|
|
283
|
+
return null;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// Get the first model's usage data
|
|
287
|
+
const modelKey = Object.keys(resultMessage.modelUsage)[0];
|
|
288
|
+
const modelData = resultMessage.modelUsage[modelKey];
|
|
289
|
+
|
|
290
|
+
if (!modelData) {
|
|
291
|
+
return null;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
// Use cumulative tokens if available (tracks total for the session)
|
|
295
|
+
// Otherwise fall back to per-request tokens
|
|
296
|
+
const inputTokens = modelData.cumulativeInputTokens || modelData.inputTokens || 0;
|
|
297
|
+
const outputTokens = modelData.cumulativeOutputTokens || modelData.outputTokens || 0;
|
|
298
|
+
const cacheReadTokens = modelData.cumulativeCacheReadInputTokens || modelData.cacheReadInputTokens || 0;
|
|
299
|
+
const cacheCreationTokens = modelData.cumulativeCacheCreationInputTokens || modelData.cacheCreationInputTokens || 0;
|
|
300
|
+
|
|
301
|
+
// Total used = input + output + cache tokens
|
|
302
|
+
const totalUsed = inputTokens + outputTokens + cacheReadTokens + cacheCreationTokens;
|
|
303
|
+
|
|
304
|
+
// Use configured context window budget from environment (default 160000)
|
|
305
|
+
// This is the user's budget limit, not the model's context window
|
|
306
|
+
const contextWindow = parseInt(process.env.CONTEXT_WINDOW) || 160000;
|
|
307
|
+
|
|
308
|
+
console.log(`Token calculation: input=${inputTokens}, output=${outputTokens}, cache=${cacheReadTokens + cacheCreationTokens}, total=${totalUsed}/${contextWindow}`);
|
|
309
|
+
|
|
310
|
+
return {
|
|
311
|
+
used: totalUsed,
|
|
312
|
+
total: contextWindow
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* Handles image processing for SDK queries
|
|
318
|
+
* Saves base64 images to temporary files and returns modified prompt with file paths
|
|
319
|
+
* @param {string} command - Original user prompt
|
|
320
|
+
* @param {Array} images - Array of image objects with base64 data
|
|
321
|
+
* @param {string} cwd - Working directory for temp file creation
|
|
322
|
+
* @returns {Promise<Object>} {modifiedCommand, tempImagePaths, tempDir}
|
|
323
|
+
*/
|
|
324
|
+
async function handleImages(command, images, cwd) {
|
|
325
|
+
const tempImagePaths = [];
|
|
326
|
+
let tempDir = null;
|
|
327
|
+
|
|
328
|
+
if (!images || images.length === 0) {
|
|
329
|
+
return { modifiedCommand: command, tempImagePaths, tempDir };
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
try {
|
|
333
|
+
// Create temp directory in the project directory
|
|
334
|
+
const workingDir = cwd || process.cwd();
|
|
335
|
+
tempDir = path.join(workingDir, '.tmp', 'images', Date.now().toString());
|
|
336
|
+
await fs.mkdir(tempDir, { recursive: true });
|
|
337
|
+
|
|
338
|
+
// Save each image to a temp file
|
|
339
|
+
for (const [index, image] of images.entries()) {
|
|
340
|
+
// Extract base64 data and mime type
|
|
341
|
+
const matches = image.data.match(/^data:([^;]+);base64,(.+)$/);
|
|
342
|
+
if (!matches) {
|
|
343
|
+
console.error('Invalid image data format');
|
|
344
|
+
continue;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
const [, mimeType, base64Data] = matches;
|
|
348
|
+
const extension = mimeType.split('/')[1] || 'png';
|
|
349
|
+
const filename = `image_${index}.${extension}`;
|
|
350
|
+
const filepath = path.join(tempDir, filename);
|
|
351
|
+
|
|
352
|
+
// Write base64 data to file
|
|
353
|
+
await fs.writeFile(filepath, Buffer.from(base64Data, 'base64'));
|
|
354
|
+
tempImagePaths.push(filepath);
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
// Include the full image paths in the prompt
|
|
358
|
+
let modifiedCommand = command;
|
|
359
|
+
if (tempImagePaths.length > 0 && command && command.trim()) {
|
|
360
|
+
const imageNote = `\n\n[Images provided at the following paths:]\n${tempImagePaths.map((p, i) => `${i + 1}. ${p}`).join('\n')}`;
|
|
361
|
+
modifiedCommand = command + imageNote;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
console.log(`Processed ${tempImagePaths.length} images to temp directory: ${tempDir}`);
|
|
365
|
+
return { modifiedCommand, tempImagePaths, tempDir };
|
|
366
|
+
} catch (error) {
|
|
367
|
+
console.error('Error processing images for SDK:', error);
|
|
368
|
+
return { modifiedCommand: command, tempImagePaths, tempDir };
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/**
|
|
373
|
+
* Cleans up temporary image files
|
|
374
|
+
* @param {Array<string>} tempImagePaths - Array of temp file paths to delete
|
|
375
|
+
* @param {string} tempDir - Temp directory to remove
|
|
376
|
+
*/
|
|
377
|
+
async function cleanupTempFiles(tempImagePaths, tempDir) {
|
|
378
|
+
if (!tempImagePaths || tempImagePaths.length === 0) {
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
try {
|
|
383
|
+
// Delete individual temp files
|
|
384
|
+
for (const imagePath of tempImagePaths) {
|
|
385
|
+
await fs.unlink(imagePath).catch(err =>
|
|
386
|
+
console.error(`Failed to delete temp image ${imagePath}:`, err)
|
|
387
|
+
);
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
// Delete temp directory
|
|
391
|
+
if (tempDir) {
|
|
392
|
+
await fs.rm(tempDir, { recursive: true, force: true }).catch(err =>
|
|
393
|
+
console.error(`Failed to delete temp directory ${tempDir}:`, err)
|
|
394
|
+
);
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
console.log(`Cleaned up ${tempImagePaths.length} temp image files`);
|
|
398
|
+
} catch (error) {
|
|
399
|
+
console.error('Error during temp file cleanup:', error);
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/**
|
|
404
|
+
* Loads MCP server configurations from ~/.claude.json
|
|
405
|
+
* @param {string} cwd - Current working directory for project-specific configs
|
|
406
|
+
* @returns {Object|null} MCP servers object or null if none found
|
|
407
|
+
*/
|
|
408
|
+
async function loadMcpConfig(cwd) {
|
|
409
|
+
try {
|
|
410
|
+
const claudeConfigPath = path.join(os.homedir(), '.claude.json');
|
|
411
|
+
|
|
412
|
+
// Check if config file exists
|
|
413
|
+
try {
|
|
414
|
+
await fs.access(claudeConfigPath);
|
|
415
|
+
} catch (error) {
|
|
416
|
+
// File doesn't exist, return null
|
|
417
|
+
console.log('No ~/.claude.json found, proceeding without MCP servers');
|
|
418
|
+
return null;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
// Read and parse config file
|
|
422
|
+
let claudeConfig;
|
|
423
|
+
try {
|
|
424
|
+
const configContent = await fs.readFile(claudeConfigPath, 'utf8');
|
|
425
|
+
claudeConfig = JSON.parse(configContent);
|
|
426
|
+
} catch (error) {
|
|
427
|
+
console.error('Failed to parse ~/.claude.json:', error.message);
|
|
428
|
+
return null;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
// Extract MCP servers (merge global and project-specific)
|
|
432
|
+
let mcpServers = {};
|
|
433
|
+
|
|
434
|
+
// Add global MCP servers
|
|
435
|
+
if (claudeConfig.mcpServers && typeof claudeConfig.mcpServers === 'object') {
|
|
436
|
+
mcpServers = { ...claudeConfig.mcpServers };
|
|
437
|
+
console.log(`Loaded ${Object.keys(mcpServers).length} global MCP servers`);
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
// Add/override with project-specific MCP servers
|
|
441
|
+
if (claudeConfig.claudeProjects && cwd) {
|
|
442
|
+
const projectConfig = claudeConfig.claudeProjects[cwd];
|
|
443
|
+
if (projectConfig && projectConfig.mcpServers && typeof projectConfig.mcpServers === 'object') {
|
|
444
|
+
mcpServers = { ...mcpServers, ...projectConfig.mcpServers };
|
|
445
|
+
console.log(`Loaded ${Object.keys(projectConfig.mcpServers).length} project-specific MCP servers`);
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
// Return null if no servers found
|
|
450
|
+
if (Object.keys(mcpServers).length === 0) {
|
|
451
|
+
console.log('No MCP servers configured');
|
|
452
|
+
return null;
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
console.log(`Total MCP servers loaded: ${Object.keys(mcpServers).length}`);
|
|
456
|
+
return mcpServers;
|
|
457
|
+
} catch (error) {
|
|
458
|
+
console.error('Error loading MCP config:', error.message);
|
|
459
|
+
return null;
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/**
|
|
464
|
+
* Executes a Claude query using the SDK
|
|
465
|
+
* @param {string} command - User prompt/command
|
|
466
|
+
* @param {Object} options - Query options
|
|
467
|
+
* @param {Object} ws - WebSocket connection
|
|
468
|
+
* @returns {Promise<void>}
|
|
469
|
+
*/
|
|
470
|
+
async function queryClaudeSDK(command, options = {}, ws) {
|
|
471
|
+
const { sessionId } = options;
|
|
472
|
+
let capturedSessionId = sessionId;
|
|
473
|
+
let sessionCreatedSent = false;
|
|
474
|
+
let tempImagePaths = [];
|
|
475
|
+
let tempDir = null;
|
|
476
|
+
|
|
477
|
+
try {
|
|
478
|
+
// Map CLI options to SDK format
|
|
479
|
+
const sdkOptions = mapCliOptionsToSDK(options);
|
|
480
|
+
|
|
481
|
+
// Load MCP configuration
|
|
482
|
+
const mcpServers = await loadMcpConfig(options.cwd);
|
|
483
|
+
if (mcpServers) {
|
|
484
|
+
sdkOptions.mcpServers = mcpServers;
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
// Handle images - save to temp files and modify prompt
|
|
488
|
+
const imageResult = await handleImages(command, options.images, options.cwd);
|
|
489
|
+
const finalCommand = imageResult.modifiedCommand;
|
|
490
|
+
tempImagePaths = imageResult.tempImagePaths;
|
|
491
|
+
tempDir = imageResult.tempDir;
|
|
492
|
+
|
|
493
|
+
// Gate tool usage with explicit UI approval when not auto-approved.
|
|
494
|
+
// This does not render UI or persist permissions; it only bridges to the UI
|
|
495
|
+
// via WebSocket and waits for the response, introduced so tool calls pause
|
|
496
|
+
// instead of auto-running when the allowlist is empty.
|
|
497
|
+
sdkOptions.canUseTool = async (toolName, input, context) => {
|
|
498
|
+
if (sdkOptions.permissionMode === 'bypassPermissions') {
|
|
499
|
+
return { behavior: 'allow', updatedInput: input };
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
const isDisallowed = (sdkOptions.disallowedTools || []).some(entry =>
|
|
503
|
+
matchesToolPermission(entry, toolName, input)
|
|
504
|
+
);
|
|
505
|
+
if (isDisallowed) {
|
|
506
|
+
return { behavior: 'deny', message: 'Tool disallowed by settings' };
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
const isAllowed = (sdkOptions.allowedTools || []).some(entry =>
|
|
510
|
+
matchesToolPermission(entry, toolName, input)
|
|
511
|
+
);
|
|
512
|
+
if (isAllowed) {
|
|
513
|
+
return { behavior: 'allow', updatedInput: input };
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
const requestId = createRequestId();
|
|
517
|
+
ws.send({
|
|
518
|
+
type: 'claude-permission-request',
|
|
519
|
+
requestId,
|
|
520
|
+
toolName,
|
|
521
|
+
input,
|
|
522
|
+
sessionId: capturedSessionId || sessionId || null
|
|
523
|
+
});
|
|
524
|
+
|
|
525
|
+
// Wait for the UI; if the SDK cancels, notify the UI so it can dismiss the banner.
|
|
526
|
+
// This does not retry or resurface the prompt; it just reflects the cancellation.
|
|
527
|
+
const decision = await waitForToolApproval(requestId, {
|
|
528
|
+
signal: context?.signal,
|
|
529
|
+
onCancel: (reason) => {
|
|
530
|
+
ws.send({
|
|
531
|
+
type: 'claude-permission-cancelled',
|
|
532
|
+
requestId,
|
|
533
|
+
reason,
|
|
534
|
+
sessionId: capturedSessionId || sessionId || null
|
|
535
|
+
});
|
|
536
|
+
}
|
|
537
|
+
});
|
|
538
|
+
if (!decision) {
|
|
539
|
+
return { behavior: 'deny', message: 'Permission request timed out' };
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
if (decision.cancelled) {
|
|
543
|
+
return { behavior: 'deny', message: 'Permission request cancelled' };
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
if (decision.allow) {
|
|
547
|
+
// rememberEntry only updates this run's in-memory allowlist to prevent
|
|
548
|
+
// repeated prompts in the same session; persistence is handled by the UI.
|
|
549
|
+
if (decision.rememberEntry && typeof decision.rememberEntry === 'string') {
|
|
550
|
+
if (!sdkOptions.allowedTools.includes(decision.rememberEntry)) {
|
|
551
|
+
sdkOptions.allowedTools.push(decision.rememberEntry);
|
|
552
|
+
}
|
|
553
|
+
if (Array.isArray(sdkOptions.disallowedTools)) {
|
|
554
|
+
sdkOptions.disallowedTools = sdkOptions.disallowedTools.filter(entry => entry !== decision.rememberEntry);
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
return { behavior: 'allow', updatedInput: decision.updatedInput ?? input };
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
return { behavior: 'deny', message: decision.message ?? 'User denied tool use' };
|
|
561
|
+
};
|
|
562
|
+
|
|
563
|
+
// Create SDK query instance
|
|
564
|
+
const queryInstance = query({
|
|
565
|
+
prompt: finalCommand,
|
|
566
|
+
options: sdkOptions
|
|
567
|
+
});
|
|
568
|
+
|
|
569
|
+
// Track the query instance for abort capability
|
|
570
|
+
if (capturedSessionId) {
|
|
571
|
+
addSession(capturedSessionId, queryInstance, tempImagePaths, tempDir);
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
// Process streaming messages
|
|
575
|
+
console.log('Starting async generator loop for session:', capturedSessionId || 'NEW');
|
|
576
|
+
for await (const message of queryInstance) {
|
|
577
|
+
// Capture session ID from first message
|
|
578
|
+
if (message.session_id && !capturedSessionId) {
|
|
579
|
+
|
|
580
|
+
capturedSessionId = message.session_id;
|
|
581
|
+
addSession(capturedSessionId, queryInstance, tempImagePaths, tempDir);
|
|
582
|
+
|
|
583
|
+
// Set session ID on writer
|
|
584
|
+
if (ws.setSessionId && typeof ws.setSessionId === 'function') {
|
|
585
|
+
ws.setSessionId(capturedSessionId);
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
// Send session-created event only once for new sessions
|
|
589
|
+
if (!sessionId && !sessionCreatedSent) {
|
|
590
|
+
sessionCreatedSent = true;
|
|
591
|
+
ws.send({
|
|
592
|
+
type: 'session-created',
|
|
593
|
+
sessionId: capturedSessionId
|
|
594
|
+
});
|
|
595
|
+
} else {
|
|
596
|
+
console.log('Not sending session-created. sessionId:', sessionId, 'sessionCreatedSent:', sessionCreatedSent);
|
|
597
|
+
}
|
|
598
|
+
} else {
|
|
599
|
+
console.log('No session_id in message or already captured. message.session_id:', message.session_id, 'capturedSessionId:', capturedSessionId);
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
// Transform and send message to WebSocket
|
|
603
|
+
const transformedMessage = transformMessage(message);
|
|
604
|
+
ws.send({
|
|
605
|
+
type: 'claude-response',
|
|
606
|
+
data: transformedMessage
|
|
607
|
+
});
|
|
608
|
+
|
|
609
|
+
// Extract and send token budget updates from result messages
|
|
610
|
+
if (message.type === 'result') {
|
|
611
|
+
const tokenBudget = extractTokenBudget(message);
|
|
612
|
+
if (tokenBudget) {
|
|
613
|
+
console.log('Token budget from modelUsage:', tokenBudget);
|
|
614
|
+
ws.send({
|
|
615
|
+
type: 'token-budget',
|
|
616
|
+
data: tokenBudget
|
|
617
|
+
});
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
// Clean up session on completion
|
|
623
|
+
if (capturedSessionId) {
|
|
624
|
+
removeSession(capturedSessionId);
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
// Clean up temporary image files
|
|
628
|
+
await cleanupTempFiles(tempImagePaths, tempDir);
|
|
629
|
+
|
|
630
|
+
// Send completion event
|
|
631
|
+
console.log('Streaming complete, sending claude-complete event');
|
|
632
|
+
ws.send({
|
|
633
|
+
type: 'claude-complete',
|
|
634
|
+
sessionId: capturedSessionId,
|
|
635
|
+
exitCode: 0,
|
|
636
|
+
isNewSession: !sessionId && !!command
|
|
637
|
+
});
|
|
638
|
+
console.log('claude-complete event sent');
|
|
639
|
+
|
|
640
|
+
} catch (error) {
|
|
641
|
+
console.error('SDK query error:', error);
|
|
642
|
+
|
|
643
|
+
// Clean up session on error
|
|
644
|
+
if (capturedSessionId) {
|
|
645
|
+
removeSession(capturedSessionId);
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
// Clean up temporary image files on error
|
|
649
|
+
await cleanupTempFiles(tempImagePaths, tempDir);
|
|
650
|
+
|
|
651
|
+
// Send error to WebSocket
|
|
652
|
+
ws.send({
|
|
653
|
+
type: 'claude-error',
|
|
654
|
+
error: error.message
|
|
655
|
+
});
|
|
656
|
+
|
|
657
|
+
throw error;
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
/**
|
|
662
|
+
* Aborts an active SDK session
|
|
663
|
+
* @param {string} sessionId - Session identifier
|
|
664
|
+
* @returns {boolean} True if session was aborted, false if not found
|
|
665
|
+
*/
|
|
666
|
+
async function abortClaudeSDKSession(sessionId) {
|
|
667
|
+
const session = getSession(sessionId);
|
|
668
|
+
|
|
669
|
+
if (!session) {
|
|
670
|
+
console.log(`Session ${sessionId} not found`);
|
|
671
|
+
return false;
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
try {
|
|
675
|
+
console.log(`Aborting SDK session: ${sessionId}`);
|
|
676
|
+
|
|
677
|
+
// Call interrupt() on the query instance
|
|
678
|
+
await session.instance.interrupt();
|
|
679
|
+
|
|
680
|
+
// Update session status
|
|
681
|
+
session.status = 'aborted';
|
|
682
|
+
|
|
683
|
+
// Clean up temporary image files
|
|
684
|
+
await cleanupTempFiles(session.tempImagePaths, session.tempDir);
|
|
685
|
+
|
|
686
|
+
// Clean up session
|
|
687
|
+
removeSession(sessionId);
|
|
688
|
+
|
|
689
|
+
return true;
|
|
690
|
+
} catch (error) {
|
|
691
|
+
console.error(`Error aborting session ${sessionId}:`, error);
|
|
692
|
+
return false;
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
/**
|
|
697
|
+
* Checks if an SDK session is currently active
|
|
698
|
+
* @param {string} sessionId - Session identifier
|
|
699
|
+
* @returns {boolean} True if session is active
|
|
700
|
+
*/
|
|
701
|
+
function isClaudeSDKSessionActive(sessionId) {
|
|
702
|
+
const session = getSession(sessionId);
|
|
703
|
+
return session && session.status === 'active';
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
/**
|
|
707
|
+
* Gets all active SDK session IDs
|
|
708
|
+
* @returns {Array<string>} Array of active session IDs
|
|
709
|
+
*/
|
|
710
|
+
function getActiveClaudeSDKSessions() {
|
|
711
|
+
return getAllSessions();
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
// Export public API
|
|
715
|
+
export {
|
|
716
|
+
queryClaudeSDK,
|
|
717
|
+
abortClaudeSDKSession,
|
|
718
|
+
isClaudeSDKSessionActive,
|
|
719
|
+
getActiveClaudeSDKSessions,
|
|
720
|
+
resolveToolApproval
|
|
721
|
+
};
|