@cloudcli-ai/cloudcli 1.28.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.
Files changed (163) hide show
  1. package/LICENSE +718 -0
  2. package/README.de.md +239 -0
  3. package/README.ja.md +231 -0
  4. package/README.ko.md +230 -0
  5. package/README.md +242 -0
  6. package/README.ru.md +239 -0
  7. package/README.zh-CN.md +230 -0
  8. package/dist/api-docs.html +879 -0
  9. package/dist/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
  10. package/dist/assets/KaTeX_AMS-Regular-DMm9YOAa.woff +0 -0
  11. package/dist/assets/KaTeX_AMS-Regular-DRggAlZN.ttf +0 -0
  12. package/dist/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf +0 -0
  13. package/dist/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff +0 -0
  14. package/dist/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
  15. package/dist/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff +0 -0
  16. package/dist/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
  17. package/dist/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf +0 -0
  18. package/dist/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf +0 -0
  19. package/dist/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff +0 -0
  20. package/dist/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
  21. package/dist/assets/KaTeX_Fraktur-Regular-CB_wures.ttf +0 -0
  22. package/dist/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
  23. package/dist/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff +0 -0
  24. package/dist/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
  25. package/dist/assets/KaTeX_Main-Bold-Jm3AIy58.woff +0 -0
  26. package/dist/assets/KaTeX_Main-Bold-waoOVXN0.ttf +0 -0
  27. package/dist/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
  28. package/dist/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf +0 -0
  29. package/dist/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff +0 -0
  30. package/dist/assets/KaTeX_Main-Italic-3WenGoN9.ttf +0 -0
  31. package/dist/assets/KaTeX_Main-Italic-BMLOBm91.woff +0 -0
  32. package/dist/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
  33. package/dist/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
  34. package/dist/assets/KaTeX_Main-Regular-Dr94JaBh.woff +0 -0
  35. package/dist/assets/KaTeX_Main-Regular-ypZvNtVU.ttf +0 -0
  36. package/dist/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf +0 -0
  37. package/dist/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
  38. package/dist/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff +0 -0
  39. package/dist/assets/KaTeX_Math-Italic-DA0__PXp.woff +0 -0
  40. package/dist/assets/KaTeX_Math-Italic-flOr_0UB.ttf +0 -0
  41. package/dist/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
  42. package/dist/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf +0 -0
  43. package/dist/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
  44. package/dist/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff +0 -0
  45. package/dist/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
  46. package/dist/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff +0 -0
  47. package/dist/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf +0 -0
  48. package/dist/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf +0 -0
  49. package/dist/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff +0 -0
  50. package/dist/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
  51. package/dist/assets/KaTeX_Script-Regular-C5JkGWo-.ttf +0 -0
  52. package/dist/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
  53. package/dist/assets/KaTeX_Script-Regular-D5yQViql.woff +0 -0
  54. package/dist/assets/KaTeX_Size1-Regular-C195tn64.woff +0 -0
  55. package/dist/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf +0 -0
  56. package/dist/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
  57. package/dist/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf +0 -0
  58. package/dist/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
  59. package/dist/assets/KaTeX_Size2-Regular-oD1tc_U0.woff +0 -0
  60. package/dist/assets/KaTeX_Size3-Regular-CTq5MqoE.woff +0 -0
  61. package/dist/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf +0 -0
  62. package/dist/assets/KaTeX_Size4-Regular-BF-4gkZK.woff +0 -0
  63. package/dist/assets/KaTeX_Size4-Regular-DWFBv043.ttf +0 -0
  64. package/dist/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
  65. package/dist/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff +0 -0
  66. package/dist/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
  67. package/dist/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf +0 -0
  68. package/dist/assets/index-B1XAhG_4.css +32 -0
  69. package/dist/assets/index-BWQPmiP5.js +1275 -0
  70. package/dist/assets/vendor-codemirror-C8f1vU1x.js +41 -0
  71. package/dist/assets/vendor-react-CdSTmIF1.js +59 -0
  72. package/dist/assets/vendor-xterm-CJZjLICi.js +66 -0
  73. package/dist/clear-cache.html +85 -0
  74. package/dist/convert-icons.md +53 -0
  75. package/dist/favicon.png +0 -0
  76. package/dist/favicon.svg +9 -0
  77. package/dist/generate-icons.js +49 -0
  78. package/dist/icons/claude-ai-icon.svg +1 -0
  79. package/dist/icons/codex-white.svg +3 -0
  80. package/dist/icons/codex.svg +3 -0
  81. package/dist/icons/cursor-white.svg +12 -0
  82. package/dist/icons/cursor.svg +1 -0
  83. package/dist/icons/gemini-ai-icon.svg +1 -0
  84. package/dist/icons/icon-128x128.png +0 -0
  85. package/dist/icons/icon-128x128.svg +12 -0
  86. package/dist/icons/icon-144x144.png +0 -0
  87. package/dist/icons/icon-144x144.svg +12 -0
  88. package/dist/icons/icon-152x152.png +0 -0
  89. package/dist/icons/icon-152x152.svg +12 -0
  90. package/dist/icons/icon-192x192.png +0 -0
  91. package/dist/icons/icon-192x192.svg +12 -0
  92. package/dist/icons/icon-384x384.png +0 -0
  93. package/dist/icons/icon-384x384.svg +12 -0
  94. package/dist/icons/icon-512x512.png +0 -0
  95. package/dist/icons/icon-512x512.svg +12 -0
  96. package/dist/icons/icon-72x72.png +0 -0
  97. package/dist/icons/icon-72x72.svg +12 -0
  98. package/dist/icons/icon-96x96.png +0 -0
  99. package/dist/icons/icon-96x96.svg +12 -0
  100. package/dist/icons/icon-template.svg +12 -0
  101. package/dist/index.html +52 -0
  102. package/dist/logo-128.png +0 -0
  103. package/dist/logo-256.png +0 -0
  104. package/dist/logo-32.png +0 -0
  105. package/dist/logo-512.png +0 -0
  106. package/dist/logo-64.png +0 -0
  107. package/dist/logo.svg +17 -0
  108. package/dist/manifest.json +61 -0
  109. package/dist/screenshots/cli-selection.png +0 -0
  110. package/dist/screenshots/desktop-main.png +0 -0
  111. package/dist/screenshots/mobile-chat.png +0 -0
  112. package/dist/screenshots/tools-modal.png +0 -0
  113. package/dist/sw.js +124 -0
  114. package/package.json +153 -0
  115. package/scripts/fix-node-pty.js +67 -0
  116. package/server/claude-sdk.js +817 -0
  117. package/server/cli.js +330 -0
  118. package/server/constants/config.js +5 -0
  119. package/server/cursor-cli.js +335 -0
  120. package/server/database/db.js +630 -0
  121. package/server/database/init.sql +99 -0
  122. package/server/gemini-cli.js +453 -0
  123. package/server/gemini-response-handler.js +79 -0
  124. package/server/index.js +2577 -0
  125. package/server/load-env.js +29 -0
  126. package/server/middleware/auth.js +132 -0
  127. package/server/openai-codex.js +418 -0
  128. package/server/projects.js +2561 -0
  129. package/server/providers/claude/adapter.js +278 -0
  130. package/server/providers/codex/adapter.js +248 -0
  131. package/server/providers/cursor/adapter.js +353 -0
  132. package/server/providers/gemini/adapter.js +186 -0
  133. package/server/providers/registry.js +44 -0
  134. package/server/providers/types.js +119 -0
  135. package/server/providers/utils.js +29 -0
  136. package/server/routes/agent.js +1245 -0
  137. package/server/routes/auth.js +135 -0
  138. package/server/routes/cli-auth.js +434 -0
  139. package/server/routes/codex.js +329 -0
  140. package/server/routes/commands.js +601 -0
  141. package/server/routes/cursor.js +798 -0
  142. package/server/routes/gemini.js +24 -0
  143. package/server/routes/git.js +1488 -0
  144. package/server/routes/mcp-utils.js +48 -0
  145. package/server/routes/mcp.js +552 -0
  146. package/server/routes/messages.js +61 -0
  147. package/server/routes/plugins.js +307 -0
  148. package/server/routes/projects.js +548 -0
  149. package/server/routes/settings.js +276 -0
  150. package/server/routes/taskmaster.js +1963 -0
  151. package/server/routes/user.js +123 -0
  152. package/server/services/notification-orchestrator.js +227 -0
  153. package/server/services/vapid-keys.js +35 -0
  154. package/server/sessionManager.js +226 -0
  155. package/server/utils/commandParser.js +303 -0
  156. package/server/utils/frontmatter.js +18 -0
  157. package/server/utils/gitConfig.js +34 -0
  158. package/server/utils/mcp-detector.js +198 -0
  159. package/server/utils/plugin-loader.js +457 -0
  160. package/server/utils/plugin-process-manager.js +184 -0
  161. package/server/utils/taskmaster-websocket.js +129 -0
  162. package/shared/modelConstants.js +92 -0
  163. package/shared/networkHosts.js +22 -0
@@ -0,0 +1,817 @@
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
+ import crypto from 'crypto';
17
+ import { promises as fs } from 'fs';
18
+ import path from 'path';
19
+ import os from 'os';
20
+ import { CLAUDE_MODELS } from '../shared/modelConstants.js';
21
+ import {
22
+ createNotificationEvent,
23
+ notifyRunFailed,
24
+ notifyRunStopped,
25
+ notifyUserIfEnabled
26
+ } from './services/notification-orchestrator.js';
27
+ import { claudeAdapter } from './providers/claude/adapter.js';
28
+ import { createNormalizedMessage } from './providers/types.js';
29
+
30
+ const activeSessions = new Map();
31
+ const pendingToolApprovals = new Map();
32
+
33
+ const TOOL_APPROVAL_TIMEOUT_MS = parseInt(process.env.CLAUDE_TOOL_APPROVAL_TIMEOUT_MS, 10) || 55000;
34
+
35
+ const TOOLS_REQUIRING_INTERACTION = new Set(['AskUserQuestion']);
36
+
37
+ function createRequestId() {
38
+ if (typeof crypto.randomUUID === 'function') {
39
+ return crypto.randomUUID();
40
+ }
41
+ return crypto.randomBytes(16).toString('hex');
42
+ }
43
+
44
+ function waitForToolApproval(requestId, options = {}) {
45
+ const { timeoutMs = TOOL_APPROVAL_TIMEOUT_MS, signal, onCancel, metadata } = options;
46
+
47
+ return new Promise(resolve => {
48
+ let settled = false;
49
+
50
+ const finalize = (decision) => {
51
+ if (settled) return;
52
+ settled = true;
53
+ cleanup();
54
+ resolve(decision);
55
+ };
56
+
57
+ let timeout;
58
+
59
+ const cleanup = () => {
60
+ pendingToolApprovals.delete(requestId);
61
+ if (timeout) clearTimeout(timeout);
62
+ if (signal && abortHandler) {
63
+ signal.removeEventListener('abort', abortHandler);
64
+ }
65
+ };
66
+
67
+ // timeoutMs 0 = wait indefinitely (interactive tools)
68
+ if (timeoutMs > 0) {
69
+ timeout = setTimeout(() => {
70
+ onCancel?.('timeout');
71
+ finalize(null);
72
+ }, timeoutMs);
73
+ }
74
+
75
+ const abortHandler = () => {
76
+ onCancel?.('cancelled');
77
+ finalize({ cancelled: true });
78
+ };
79
+
80
+ if (signal) {
81
+ if (signal.aborted) {
82
+ onCancel?.('cancelled');
83
+ finalize({ cancelled: true });
84
+ return;
85
+ }
86
+ signal.addEventListener('abort', abortHandler, { once: true });
87
+ }
88
+
89
+ const resolver = (decision) => {
90
+ finalize(decision);
91
+ };
92
+ // Attach metadata for getPendingApprovalsForSession lookup
93
+ if (metadata) {
94
+ Object.assign(resolver, metadata);
95
+ }
96
+ pendingToolApprovals.set(requestId, resolver);
97
+ });
98
+ }
99
+
100
+ function resolveToolApproval(requestId, decision) {
101
+ const resolver = pendingToolApprovals.get(requestId);
102
+ if (resolver) {
103
+ resolver(decision);
104
+ }
105
+ }
106
+
107
+ // Match stored permission entries against a tool + input combo.
108
+ // This only supports exact tool names and the Bash(command:*) shorthand
109
+ // used by the UI; it intentionally does not implement full glob semantics,
110
+ // introduced to stay consistent with the UI's "Allow rule" format.
111
+ function matchesToolPermission(entry, toolName, input) {
112
+ if (!entry || !toolName) {
113
+ return false;
114
+ }
115
+
116
+ if (entry === toolName) {
117
+ return true;
118
+ }
119
+
120
+ const bashMatch = entry.match(/^Bash\((.+):\*\)$/);
121
+ if (toolName === 'Bash' && bashMatch) {
122
+ const allowedPrefix = bashMatch[1];
123
+ let command = '';
124
+
125
+ if (typeof input === 'string') {
126
+ command = input.trim();
127
+ } else if (input && typeof input === 'object' && typeof input.command === 'string') {
128
+ command = input.command.trim();
129
+ }
130
+
131
+ if (!command) {
132
+ return false;
133
+ }
134
+
135
+ return command.startsWith(allowedPrefix);
136
+ }
137
+
138
+ return false;
139
+ }
140
+
141
+ /**
142
+ * Maps CLI options to SDK-compatible options format
143
+ * @param {Object} options - CLI options
144
+ * @returns {Object} SDK-compatible options
145
+ */
146
+ function mapCliOptionsToSDK(options = {}) {
147
+ const { sessionId, cwd, toolsSettings, permissionMode } = options;
148
+
149
+ const sdkOptions = {};
150
+
151
+ // Map working directory
152
+ if (cwd) {
153
+ sdkOptions.cwd = cwd;
154
+ }
155
+
156
+ // Map permission mode
157
+ if (permissionMode && permissionMode !== 'default') {
158
+ sdkOptions.permissionMode = permissionMode;
159
+ }
160
+
161
+ // Map tool settings
162
+ const settings = toolsSettings || {
163
+ allowedTools: [],
164
+ disallowedTools: [],
165
+ skipPermissions: false
166
+ };
167
+
168
+ // Handle tool permissions
169
+ if (settings.skipPermissions && permissionMode !== 'plan') {
170
+ // When skipping permissions, use bypassPermissions mode
171
+ sdkOptions.permissionMode = 'bypassPermissions';
172
+ }
173
+
174
+ let allowedTools = [...(settings.allowedTools || [])];
175
+
176
+ // Add plan mode default tools
177
+ if (permissionMode === 'plan') {
178
+ const planModeTools = ['Read', 'Task', 'exit_plan_mode', 'TodoRead', 'TodoWrite', 'WebFetch', 'WebSearch'];
179
+ for (const tool of planModeTools) {
180
+ if (!allowedTools.includes(tool)) {
181
+ allowedTools.push(tool);
182
+ }
183
+ }
184
+ }
185
+
186
+ sdkOptions.allowedTools = allowedTools;
187
+
188
+ // Use the tools preset to make all default built-in tools available (including AskUserQuestion).
189
+ // This was introduced in SDK 0.1.57. Omitting this preserves existing behavior (all tools available),
190
+ // but being explicit ensures forward compatibility and clarity.
191
+ sdkOptions.tools = { type: 'preset', preset: 'claude_code' };
192
+
193
+ sdkOptions.disallowedTools = settings.disallowedTools || [];
194
+
195
+ // Map model (default to sonnet)
196
+ // Valid models: sonnet, opus, haiku, opusplan, sonnet[1m]
197
+ sdkOptions.model = options.model || CLAUDE_MODELS.DEFAULT;
198
+ // Model logged at query start below
199
+
200
+ // Map system prompt configuration
201
+ sdkOptions.systemPrompt = {
202
+ type: 'preset',
203
+ preset: 'claude_code' // Required to use CLAUDE.md
204
+ };
205
+
206
+ // Map setting sources for CLAUDE.md loading
207
+ // This loads CLAUDE.md from project, user (~/.config/claude/CLAUDE.md), and local directories
208
+ sdkOptions.settingSources = ['project', 'user', 'local'];
209
+
210
+ // Map resume session
211
+ if (sessionId) {
212
+ sdkOptions.resume = sessionId;
213
+ }
214
+
215
+ return sdkOptions;
216
+ }
217
+
218
+ /**
219
+ * Adds a session to the active sessions map
220
+ * @param {string} sessionId - Session identifier
221
+ * @param {Object} queryInstance - SDK query instance
222
+ * @param {Array<string>} tempImagePaths - Temp image file paths for cleanup
223
+ * @param {string} tempDir - Temp directory for cleanup
224
+ */
225
+ function addSession(sessionId, queryInstance, tempImagePaths = [], tempDir = null, writer = null) {
226
+ activeSessions.set(sessionId, {
227
+ instance: queryInstance,
228
+ startTime: Date.now(),
229
+ status: 'active',
230
+ tempImagePaths,
231
+ tempDir,
232
+ writer
233
+ });
234
+ }
235
+
236
+ /**
237
+ * Removes a session from the active sessions map
238
+ * @param {string} sessionId - Session identifier
239
+ */
240
+ function removeSession(sessionId) {
241
+ activeSessions.delete(sessionId);
242
+ }
243
+
244
+ /**
245
+ * Gets a session from the active sessions map
246
+ * @param {string} sessionId - Session identifier
247
+ * @returns {Object|undefined} Session data or undefined
248
+ */
249
+ function getSession(sessionId) {
250
+ return activeSessions.get(sessionId);
251
+ }
252
+
253
+ /**
254
+ * Gets all active session IDs
255
+ * @returns {Array<string>} Array of active session IDs
256
+ */
257
+ function getAllSessions() {
258
+ return Array.from(activeSessions.keys());
259
+ }
260
+
261
+ /**
262
+ * Transforms SDK messages to WebSocket format expected by frontend
263
+ * @param {Object} sdkMessage - SDK message object
264
+ * @returns {Object} Transformed message ready for WebSocket
265
+ */
266
+ function transformMessage(sdkMessage) {
267
+ // Extract parent_tool_use_id for subagent tool grouping
268
+ if (sdkMessage.parent_tool_use_id) {
269
+ return {
270
+ ...sdkMessage,
271
+ parentToolUseId: sdkMessage.parent_tool_use_id
272
+ };
273
+ }
274
+ return sdkMessage;
275
+ }
276
+
277
+ /**
278
+ * Extracts token usage from SDK result messages
279
+ * @param {Object} resultMessage - SDK result message
280
+ * @returns {Object|null} Token budget object or null
281
+ */
282
+ function extractTokenBudget(resultMessage) {
283
+ if (resultMessage.type !== 'result' || !resultMessage.modelUsage) {
284
+ return null;
285
+ }
286
+
287
+ // Get the first model's usage data
288
+ const modelKey = Object.keys(resultMessage.modelUsage)[0];
289
+ const modelData = resultMessage.modelUsage[modelKey];
290
+
291
+ if (!modelData) {
292
+ return null;
293
+ }
294
+
295
+ // Use cumulative tokens if available (tracks total for the session)
296
+ // Otherwise fall back to per-request tokens
297
+ const inputTokens = modelData.cumulativeInputTokens || modelData.inputTokens || 0;
298
+ const outputTokens = modelData.cumulativeOutputTokens || modelData.outputTokens || 0;
299
+ const cacheReadTokens = modelData.cumulativeCacheReadInputTokens || modelData.cacheReadInputTokens || 0;
300
+ const cacheCreationTokens = modelData.cumulativeCacheCreationInputTokens || modelData.cacheCreationInputTokens || 0;
301
+
302
+ // Total used = input + output + cache tokens
303
+ const totalUsed = inputTokens + outputTokens + cacheReadTokens + cacheCreationTokens;
304
+
305
+ // Use configured context window budget from environment (default 160000)
306
+ // This is the user's budget limit, not the model's context window
307
+ const contextWindow = parseInt(process.env.CONTEXT_WINDOW) || 160000;
308
+
309
+ // Token calc logged via token-budget WS event
310
+
311
+ return {
312
+ used: totalUsed,
313
+ total: contextWindow
314
+ };
315
+ }
316
+
317
+ /**
318
+ * Handles image processing for SDK queries
319
+ * Saves base64 images to temporary files and returns modified prompt with file paths
320
+ * @param {string} command - Original user prompt
321
+ * @param {Array} images - Array of image objects with base64 data
322
+ * @param {string} cwd - Working directory for temp file creation
323
+ * @returns {Promise<Object>} {modifiedCommand, tempImagePaths, tempDir}
324
+ */
325
+ async function handleImages(command, images, cwd) {
326
+ const tempImagePaths = [];
327
+ let tempDir = null;
328
+
329
+ if (!images || images.length === 0) {
330
+ return { modifiedCommand: command, tempImagePaths, tempDir };
331
+ }
332
+
333
+ try {
334
+ // Create temp directory in the project directory
335
+ const workingDir = cwd || process.cwd();
336
+ tempDir = path.join(workingDir, '.tmp', 'images', Date.now().toString());
337
+ await fs.mkdir(tempDir, { recursive: true });
338
+
339
+ // Save each image to a temp file
340
+ for (const [index, image] of images.entries()) {
341
+ // Extract base64 data and mime type
342
+ const matches = image.data.match(/^data:([^;]+);base64,(.+)$/);
343
+ if (!matches) {
344
+ console.error('Invalid image data format');
345
+ continue;
346
+ }
347
+
348
+ const [, mimeType, base64Data] = matches;
349
+ const extension = mimeType.split('/')[1] || 'png';
350
+ const filename = `image_${index}.${extension}`;
351
+ const filepath = path.join(tempDir, filename);
352
+
353
+ // Write base64 data to file
354
+ await fs.writeFile(filepath, Buffer.from(base64Data, 'base64'));
355
+ tempImagePaths.push(filepath);
356
+ }
357
+
358
+ // Include the full image paths in the prompt
359
+ let modifiedCommand = command;
360
+ if (tempImagePaths.length > 0 && command && command.trim()) {
361
+ const imageNote = `\n\n[Images provided at the following paths:]\n${tempImagePaths.map((p, i) => `${i + 1}. ${p}`).join('\n')}`;
362
+ modifiedCommand = command + imageNote;
363
+ }
364
+
365
+ // Images processed
366
+ return { modifiedCommand, tempImagePaths, tempDir };
367
+ } catch (error) {
368
+ console.error('Error processing images for SDK:', error);
369
+ return { modifiedCommand: command, tempImagePaths, tempDir };
370
+ }
371
+ }
372
+
373
+ /**
374
+ * Cleans up temporary image files
375
+ * @param {Array<string>} tempImagePaths - Array of temp file paths to delete
376
+ * @param {string} tempDir - Temp directory to remove
377
+ */
378
+ async function cleanupTempFiles(tempImagePaths, tempDir) {
379
+ if (!tempImagePaths || tempImagePaths.length === 0) {
380
+ return;
381
+ }
382
+
383
+ try {
384
+ // Delete individual temp files
385
+ for (const imagePath of tempImagePaths) {
386
+ await fs.unlink(imagePath).catch(err =>
387
+ console.error(`Failed to delete temp image ${imagePath}:`, err)
388
+ );
389
+ }
390
+
391
+ // Delete temp directory
392
+ if (tempDir) {
393
+ await fs.rm(tempDir, { recursive: true, force: true }).catch(err =>
394
+ console.error(`Failed to delete temp directory ${tempDir}:`, err)
395
+ );
396
+ }
397
+
398
+ // Temp files cleaned
399
+ } catch (error) {
400
+ console.error('Error during temp file cleanup:', error);
401
+ }
402
+ }
403
+
404
+ /**
405
+ * Loads MCP server configurations from ~/.claude.json
406
+ * @param {string} cwd - Current working directory for project-specific configs
407
+ * @returns {Object|null} MCP servers object or null if none found
408
+ */
409
+ async function loadMcpConfig(cwd) {
410
+ try {
411
+ const claudeConfigPath = path.join(os.homedir(), '.claude.json');
412
+
413
+ // Check if config file exists
414
+ try {
415
+ await fs.access(claudeConfigPath);
416
+ } catch (error) {
417
+ // File doesn't exist, return null
418
+ // No config file
419
+ return null;
420
+ }
421
+
422
+ // Read and parse config file
423
+ let claudeConfig;
424
+ try {
425
+ const configContent = await fs.readFile(claudeConfigPath, 'utf8');
426
+ claudeConfig = JSON.parse(configContent);
427
+ } catch (error) {
428
+ console.error('Failed to parse ~/.claude.json:', error.message);
429
+ return null;
430
+ }
431
+
432
+ // Extract MCP servers (merge global and project-specific)
433
+ let mcpServers = {};
434
+
435
+ // Add global MCP servers
436
+ if (claudeConfig.mcpServers && typeof claudeConfig.mcpServers === 'object') {
437
+ mcpServers = { ...claudeConfig.mcpServers };
438
+ // Global MCP servers loaded
439
+ }
440
+
441
+ // Add/override with project-specific MCP servers
442
+ if (claudeConfig.claudeProjects && cwd) {
443
+ const projectConfig = claudeConfig.claudeProjects[cwd];
444
+ if (projectConfig && projectConfig.mcpServers && typeof projectConfig.mcpServers === 'object') {
445
+ mcpServers = { ...mcpServers, ...projectConfig.mcpServers };
446
+ // Project MCP servers merged
447
+ }
448
+ }
449
+
450
+ // Return null if no servers found
451
+ if (Object.keys(mcpServers).length === 0) {
452
+ return null;
453
+ }
454
+ return mcpServers;
455
+ } catch (error) {
456
+ console.error('Error loading MCP config:', error.message);
457
+ return null;
458
+ }
459
+ }
460
+
461
+ /**
462
+ * Executes a Claude query using the SDK
463
+ * @param {string} command - User prompt/command
464
+ * @param {Object} options - Query options
465
+ * @param {Object} ws - WebSocket connection
466
+ * @returns {Promise<void>}
467
+ */
468
+ async function queryClaudeSDK(command, options = {}, ws) {
469
+ const { sessionId, sessionSummary } = options;
470
+ let capturedSessionId = sessionId;
471
+ let sessionCreatedSent = false;
472
+ let tempImagePaths = [];
473
+ let tempDir = null;
474
+
475
+ const emitNotification = (event) => {
476
+ notifyUserIfEnabled({
477
+ userId: ws?.userId || null,
478
+ writer: ws,
479
+ event
480
+ });
481
+ };
482
+
483
+ try {
484
+ // Map CLI options to SDK format
485
+ const sdkOptions = mapCliOptionsToSDK(options);
486
+
487
+ // Load MCP configuration
488
+ const mcpServers = await loadMcpConfig(options.cwd);
489
+ if (mcpServers) {
490
+ sdkOptions.mcpServers = mcpServers;
491
+ }
492
+
493
+ // Handle images - save to temp files and modify prompt
494
+ const imageResult = await handleImages(command, options.images, options.cwd);
495
+ const finalCommand = imageResult.modifiedCommand;
496
+ tempImagePaths = imageResult.tempImagePaths;
497
+ tempDir = imageResult.tempDir;
498
+
499
+ sdkOptions.hooks = {
500
+ Notification: [{
501
+ matcher: '',
502
+ hooks: [async (input) => {
503
+ const message = typeof input?.message === 'string' ? input.message : 'Claude requires your attention.';
504
+ emitNotification(createNotificationEvent({
505
+ provider: 'claude',
506
+ sessionId: capturedSessionId || sessionId || null,
507
+ kind: 'action_required',
508
+ code: 'agent.notification',
509
+ meta: { message, sessionName: sessionSummary },
510
+ severity: 'warning',
511
+ requiresUserAction: true,
512
+ dedupeKey: `claude:hook:notification:${capturedSessionId || sessionId || 'none'}:${message}`
513
+ }));
514
+ return {};
515
+ }]
516
+ }]
517
+ };
518
+
519
+ sdkOptions.canUseTool = async (toolName, input, context) => {
520
+ const requiresInteraction = TOOLS_REQUIRING_INTERACTION.has(toolName);
521
+
522
+ if (!requiresInteraction) {
523
+ if (sdkOptions.permissionMode === 'bypassPermissions') {
524
+ return { behavior: 'allow', updatedInput: input };
525
+ }
526
+
527
+ const isDisallowed = (sdkOptions.disallowedTools || []).some(entry =>
528
+ matchesToolPermission(entry, toolName, input)
529
+ );
530
+ if (isDisallowed) {
531
+ return { behavior: 'deny', message: 'Tool disallowed by settings' };
532
+ }
533
+
534
+ const isAllowed = (sdkOptions.allowedTools || []).some(entry =>
535
+ matchesToolPermission(entry, toolName, input)
536
+ );
537
+ if (isAllowed) {
538
+ return { behavior: 'allow', updatedInput: input };
539
+ }
540
+ }
541
+
542
+ const requestId = createRequestId();
543
+ ws.send(createNormalizedMessage({ kind: 'permission_request', requestId, toolName, input, sessionId: capturedSessionId || sessionId || null, provider: 'claude' }));
544
+ emitNotification(createNotificationEvent({
545
+ provider: 'claude',
546
+ sessionId: capturedSessionId || sessionId || null,
547
+ kind: 'action_required',
548
+ code: 'permission.required',
549
+ meta: { toolName, sessionName: sessionSummary },
550
+ severity: 'warning',
551
+ requiresUserAction: true,
552
+ dedupeKey: `claude:permission:${capturedSessionId || sessionId || 'none'}:${requestId}`
553
+ }));
554
+
555
+ const decision = await waitForToolApproval(requestId, {
556
+ timeoutMs: requiresInteraction ? 0 : undefined,
557
+ signal: context?.signal,
558
+ metadata: {
559
+ _sessionId: capturedSessionId || sessionId || null,
560
+ _toolName: toolName,
561
+ _input: input,
562
+ _receivedAt: new Date(),
563
+ },
564
+ onCancel: (reason) => {
565
+ ws.send(createNormalizedMessage({ kind: 'permission_cancelled', requestId, reason, sessionId: capturedSessionId || sessionId || null, provider: 'claude' }));
566
+ }
567
+ });
568
+ if (!decision) {
569
+ return { behavior: 'deny', message: 'Permission request timed out' };
570
+ }
571
+
572
+ if (decision.cancelled) {
573
+ return { behavior: 'deny', message: 'Permission request cancelled' };
574
+ }
575
+
576
+ if (decision.allow) {
577
+ if (decision.rememberEntry && typeof decision.rememberEntry === 'string') {
578
+ if (!sdkOptions.allowedTools.includes(decision.rememberEntry)) {
579
+ sdkOptions.allowedTools.push(decision.rememberEntry);
580
+ }
581
+ if (Array.isArray(sdkOptions.disallowedTools)) {
582
+ sdkOptions.disallowedTools = sdkOptions.disallowedTools.filter(entry => entry !== decision.rememberEntry);
583
+ }
584
+ }
585
+ return { behavior: 'allow', updatedInput: decision.updatedInput ?? input };
586
+ }
587
+
588
+ return { behavior: 'deny', message: decision.message ?? 'User denied tool use' };
589
+ };
590
+
591
+ // Set stream-close timeout for interactive tools (Query constructor reads it synchronously). Claude Agent SDK has a default of 5s and this overrides it
592
+ const prevStreamTimeout = process.env.CLAUDE_CODE_STREAM_CLOSE_TIMEOUT;
593
+ process.env.CLAUDE_CODE_STREAM_CLOSE_TIMEOUT = '300000';
594
+
595
+ let queryInstance;
596
+ try {
597
+ queryInstance = query({
598
+ prompt: finalCommand,
599
+ options: sdkOptions
600
+ });
601
+ } catch (hookError) {
602
+ // Older/newer SDK versions may not accept hook shapes yet.
603
+ // Keep notification behavior operational via runtime events even if hook registration fails.
604
+ console.warn('Failed to initialize Claude query with hooks, retrying without hooks:', hookError?.message || hookError);
605
+ delete sdkOptions.hooks;
606
+ queryInstance = query({
607
+ prompt: finalCommand,
608
+ options: sdkOptions
609
+ });
610
+ }
611
+
612
+ // Restore immediately — Query constructor already captured the value
613
+ if (prevStreamTimeout !== undefined) {
614
+ process.env.CLAUDE_CODE_STREAM_CLOSE_TIMEOUT = prevStreamTimeout;
615
+ } else {
616
+ delete process.env.CLAUDE_CODE_STREAM_CLOSE_TIMEOUT;
617
+ }
618
+
619
+ // Track the query instance for abort capability
620
+ if (capturedSessionId) {
621
+ addSession(capturedSessionId, queryInstance, tempImagePaths, tempDir, ws);
622
+ }
623
+
624
+ // Process streaming messages
625
+ console.log('Starting async generator loop for session:', capturedSessionId || 'NEW');
626
+ for await (const message of queryInstance) {
627
+ // Capture session ID from first message
628
+ if (message.session_id && !capturedSessionId) {
629
+
630
+ capturedSessionId = message.session_id;
631
+ addSession(capturedSessionId, queryInstance, tempImagePaths, tempDir, ws);
632
+
633
+ // Set session ID on writer
634
+ if (ws.setSessionId && typeof ws.setSessionId === 'function') {
635
+ ws.setSessionId(capturedSessionId);
636
+ }
637
+
638
+ // Send session-created event only once for new sessions
639
+ if (!sessionId && !sessionCreatedSent) {
640
+ sessionCreatedSent = true;
641
+ ws.send(createNormalizedMessage({ kind: 'session_created', newSessionId: capturedSessionId, sessionId: capturedSessionId, provider: 'claude' }));
642
+ }
643
+ } else {
644
+ // session_id already captured
645
+ }
646
+
647
+ // Transform and normalize message via adapter
648
+ const transformedMessage = transformMessage(message);
649
+ const sid = capturedSessionId || sessionId || null;
650
+
651
+ // Use adapter to normalize SDK events into NormalizedMessage[]
652
+ const normalized = claudeAdapter.normalizeMessage(transformedMessage, sid);
653
+ for (const msg of normalized) {
654
+ // Preserve parentToolUseId from SDK wrapper for subagent tool grouping
655
+ if (transformedMessage.parentToolUseId && !msg.parentToolUseId) {
656
+ msg.parentToolUseId = transformedMessage.parentToolUseId;
657
+ }
658
+ ws.send(msg);
659
+ }
660
+
661
+ // Extract and send token budget updates from result messages
662
+ if (message.type === 'result') {
663
+ const models = Object.keys(message.modelUsage || {});
664
+ if (models.length > 0) {
665
+ // Model info available in result message
666
+ }
667
+ const tokenBudgetData = extractTokenBudget(message);
668
+ if (tokenBudgetData) {
669
+ ws.send(createNormalizedMessage({ kind: 'status', text: 'token_budget', tokenBudget: tokenBudgetData, sessionId: capturedSessionId || sessionId || null, provider: 'claude' }));
670
+ }
671
+ }
672
+ }
673
+
674
+ // Clean up session on completion
675
+ if (capturedSessionId) {
676
+ removeSession(capturedSessionId);
677
+ }
678
+
679
+ // Clean up temporary image files
680
+ await cleanupTempFiles(tempImagePaths, tempDir);
681
+
682
+ // Send completion event
683
+ ws.send(createNormalizedMessage({ kind: 'complete', exitCode: 0, isNewSession: !sessionId && !!command, sessionId: capturedSessionId, provider: 'claude' }));
684
+ notifyRunStopped({
685
+ userId: ws?.userId || null,
686
+ provider: 'claude',
687
+ sessionId: capturedSessionId || sessionId || null,
688
+ sessionName: sessionSummary,
689
+ stopReason: 'completed'
690
+ });
691
+ // Complete
692
+
693
+ } catch (error) {
694
+ console.error('SDK query error:', error);
695
+
696
+ // Clean up session on error
697
+ if (capturedSessionId) {
698
+ removeSession(capturedSessionId);
699
+ }
700
+
701
+ // Clean up temporary image files on error
702
+ await cleanupTempFiles(tempImagePaths, tempDir);
703
+
704
+ // Send error to WebSocket
705
+ ws.send(createNormalizedMessage({ kind: 'error', content: error.message, sessionId: capturedSessionId || sessionId || null, provider: 'claude' }));
706
+ notifyRunFailed({
707
+ userId: ws?.userId || null,
708
+ provider: 'claude',
709
+ sessionId: capturedSessionId || sessionId || null,
710
+ sessionName: sessionSummary,
711
+ error
712
+ });
713
+
714
+ throw error;
715
+ }
716
+ }
717
+
718
+ /**
719
+ * Aborts an active SDK session
720
+ * @param {string} sessionId - Session identifier
721
+ * @returns {boolean} True if session was aborted, false if not found
722
+ */
723
+ async function abortClaudeSDKSession(sessionId) {
724
+ const session = getSession(sessionId);
725
+
726
+ if (!session) {
727
+ console.log(`Session ${sessionId} not found`);
728
+ return false;
729
+ }
730
+
731
+ try {
732
+ console.log(`Aborting SDK session: ${sessionId}`);
733
+
734
+ // Call interrupt() on the query instance
735
+ await session.instance.interrupt();
736
+
737
+ // Update session status
738
+ session.status = 'aborted';
739
+
740
+ // Clean up temporary image files
741
+ await cleanupTempFiles(session.tempImagePaths, session.tempDir);
742
+
743
+ // Clean up session
744
+ removeSession(sessionId);
745
+
746
+ return true;
747
+ } catch (error) {
748
+ console.error(`Error aborting session ${sessionId}:`, error);
749
+ return false;
750
+ }
751
+ }
752
+
753
+ /**
754
+ * Checks if an SDK session is currently active
755
+ * @param {string} sessionId - Session identifier
756
+ * @returns {boolean} True if session is active
757
+ */
758
+ function isClaudeSDKSessionActive(sessionId) {
759
+ const session = getSession(sessionId);
760
+ return session && session.status === 'active';
761
+ }
762
+
763
+ /**
764
+ * Gets all active SDK session IDs
765
+ * @returns {Array<string>} Array of active session IDs
766
+ */
767
+ function getActiveClaudeSDKSessions() {
768
+ return getAllSessions();
769
+ }
770
+
771
+ /**
772
+ * Get pending tool approvals for a specific session.
773
+ * @param {string} sessionId - The session ID
774
+ * @returns {Array} Array of pending permission request objects
775
+ */
776
+ function getPendingApprovalsForSession(sessionId) {
777
+ const pending = [];
778
+ for (const [requestId, resolver] of pendingToolApprovals.entries()) {
779
+ if (resolver._sessionId === sessionId) {
780
+ pending.push({
781
+ requestId,
782
+ toolName: resolver._toolName || 'UnknownTool',
783
+ input: resolver._input,
784
+ context: resolver._context,
785
+ sessionId,
786
+ receivedAt: resolver._receivedAt || new Date(),
787
+ });
788
+ }
789
+ }
790
+ return pending;
791
+ }
792
+
793
+ /**
794
+ * Reconnect a session's WebSocketWriter to a new raw WebSocket.
795
+ * Called when client reconnects (e.g. page refresh) while SDK is still running.
796
+ * @param {string} sessionId - The session ID
797
+ * @param {Object} newRawWs - The new raw WebSocket connection
798
+ * @returns {boolean} True if writer was successfully reconnected
799
+ */
800
+ function reconnectSessionWriter(sessionId, newRawWs) {
801
+ const session = getSession(sessionId);
802
+ if (!session?.writer?.updateWebSocket) return false;
803
+ session.writer.updateWebSocket(newRawWs);
804
+ console.log(`[RECONNECT] Writer swapped for session ${sessionId}`);
805
+ return true;
806
+ }
807
+
808
+ // Export public API
809
+ export {
810
+ queryClaudeSDK,
811
+ abortClaudeSDKSession,
812
+ isClaudeSDKSessionActive,
813
+ getActiveClaudeSDKSessions,
814
+ resolveToolApproval,
815
+ getPendingApprovalsForSession,
816
+ reconnectSessionWriter
817
+ };