@pixelbyte-software/pixcode 1.54.6 → 1.54.8

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 (288) hide show
  1. package/CODE_OF_CONDUCT.md +41 -41
  2. package/CONTRIBUTING.md +155 -155
  3. package/LICENSE +718 -718
  4. package/README.de.md +169 -169
  5. package/README.ja.md +167 -167
  6. package/README.ko.md +167 -167
  7. package/README.md +418 -418
  8. package/README.ru.md +169 -169
  9. package/README.tr.md +298 -298
  10. package/README.zh-CN.md +167 -167
  11. package/SECURITY.md +46 -46
  12. package/dist/api-automation.html +110 -110
  13. package/dist/api-docs.html +548 -548
  14. package/dist/assets/{index-DJ_KIN2W.js → index-BU3Z3zrh.js} +186 -184
  15. package/dist/assets/index-Dz1luE0u.css +32 -0
  16. package/dist/clear-cache.html +85 -85
  17. package/dist/convert-icons.md +52 -52
  18. package/dist/docs.html +308 -308
  19. package/dist/features.html +133 -133
  20. package/dist/generate-icons.js +48 -48
  21. package/dist/humans.txt +15 -15
  22. package/dist/icons/codex-white.svg +3 -3
  23. package/dist/icons/codex.svg +3 -3
  24. package/dist/icons/cursor-white.svg +11 -11
  25. package/dist/icons/qwen-logo.svg +14 -14
  26. package/dist/index.html +59 -59
  27. package/dist/landing.html +268 -268
  28. package/dist/llms-full.txt +119 -119
  29. package/dist/llms.txt +53 -53
  30. package/dist/manifest.json +60 -60
  31. package/dist/openapi.yaml +1696 -1696
  32. package/dist/orchestration.html +125 -125
  33. package/dist/robots.txt +4 -4
  34. package/dist/site.css +692 -692
  35. package/dist/sitemap.xml +51 -51
  36. package/dist/sw.js +132 -132
  37. package/dist-server/server/cli.js +100 -100
  38. package/dist-server/server/daemon/manager.js +33 -33
  39. package/dist-server/server/daemon-manager.js +64 -64
  40. package/dist-server/server/index.js +113 -31
  41. package/dist-server/server/index.js.map +1 -1
  42. package/dist-server/server/routes/auth.js +17 -5
  43. package/dist-server/server/routes/auth.js.map +1 -1
  44. package/dist-server/server/routes/commands.js +25 -25
  45. package/dist-server/server/routes/git.js +17 -17
  46. package/dist-server/server/routes/live-view.js +46 -46
  47. package/dist-server/server/services/public-api-manifest.js +51 -51
  48. package/package.json +224 -224
  49. package/scripts/fix-node-pty.js +67 -67
  50. package/scripts/github/create-v1.38-issues.mjs +351 -351
  51. package/scripts/github/create-vscode-workbench-issues.mjs +121 -121
  52. package/scripts/smoke/backend-resource-bounds.mjs +152 -152
  53. package/scripts/smoke/changes-panel-layout.mjs +48 -48
  54. package/scripts/smoke/chat-composer-fixed-layout.mjs +55 -55
  55. package/scripts/smoke/chat-message-timeline-order.mjs +41 -41
  56. package/scripts/smoke/chat-realtime-hydration.mjs +44 -44
  57. package/scripts/smoke/chat-session-provider-pools.mjs +35 -35
  58. package/scripts/smoke/chat-session-state.mjs +19 -19
  59. package/scripts/smoke/code-editor-theme.mjs +55 -55
  60. package/scripts/smoke/code-editor-vscode-engine.mjs +91 -91
  61. package/scripts/smoke/command-center-agent-writes.mjs +79 -79
  62. package/scripts/smoke/command-center-non-git.mjs +46 -46
  63. package/scripts/smoke/context-packet.mjs +43 -43
  64. package/scripts/smoke/control-room-ux-redesign.mjs +91 -91
  65. package/scripts/smoke/daemon-entrypoint.mjs +20 -20
  66. package/scripts/smoke/default-landing-routing.mjs +33 -33
  67. package/scripts/smoke/desktop-native-notifications.mjs +30 -30
  68. package/scripts/smoke/desktop-tray-icon.mjs +33 -33
  69. package/scripts/smoke/discord-release-workflow.mjs +24 -24
  70. package/scripts/smoke/git-install-update.mjs +255 -255
  71. package/scripts/smoke/handoff-artifact-protocol.mjs +50 -50
  72. package/scripts/smoke/live-view-diagnostics.mjs +53 -53
  73. package/scripts/smoke/live-view-environment.mjs +92 -92
  74. package/scripts/smoke/live-view-integration.mjs +450 -450
  75. package/scripts/smoke/mac-desktop-runtime.mjs +37 -37
  76. package/scripts/smoke/mobile-tunnel-guidance.mjs +29 -29
  77. package/scripts/smoke/mobile-ux.mjs +76 -76
  78. package/scripts/smoke/model-registry.mjs +36 -36
  79. package/scripts/smoke/multi-project-ui.mjs +45 -45
  80. package/scripts/smoke/multi-worker-slots.mjs +42 -42
  81. package/scripts/smoke/notification-center.mjs +87 -87
  82. package/scripts/smoke/notification-inapp-preference.mjs +23 -23
  83. package/scripts/smoke/notification-taxonomy.mjs +58 -58
  84. package/scripts/smoke/orchestration-api.mjs +172 -172
  85. package/scripts/smoke/orchestration-execution-dashboard.mjs +33 -33
  86. package/scripts/smoke/orchestration-live-run.mjs +176 -176
  87. package/scripts/smoke/orchestration-mobile-scroll.mjs +29 -29
  88. package/scripts/smoke/orchestration-model-sync.mjs +30 -30
  89. package/scripts/smoke/orchestration-permission-fallback.mjs +34 -34
  90. package/scripts/smoke/orchestration-runtime-guards.mjs +48 -48
  91. package/scripts/smoke/orchestration-user-facing-output.mjs +25 -25
  92. package/scripts/smoke/permission-policy.mjs +50 -50
  93. package/scripts/smoke/pixcode-workbench-1-48.mjs +167 -167
  94. package/scripts/smoke/provider-models-opencode-live.mjs +66 -66
  95. package/scripts/smoke/provider-rest-api.mjs +124 -124
  96. package/scripts/smoke/provider-selection-status.mjs +52 -52
  97. package/scripts/smoke/run-state-refresh.mjs +52 -52
  98. package/scripts/smoke/runtime-manager.mjs +99 -99
  99. package/scripts/smoke/shell-manual-disconnect.mjs +30 -30
  100. package/scripts/smoke/side-panel-editor-layout.mjs +34 -34
  101. package/scripts/smoke/static-root-routing.mjs +21 -21
  102. package/scripts/smoke/strict-handoff-compact.mjs +60 -60
  103. package/scripts/smoke/taskmaster-config.mjs +24 -24
  104. package/scripts/smoke/taskmaster-execution-telegram.mjs +3 -3
  105. package/scripts/smoke/taskmaster-onboarding.mjs +3 -3
  106. package/scripts/smoke/taskmaster-run-graph.mjs +3 -3
  107. package/scripts/smoke/telegram-control.mjs +331 -331
  108. package/scripts/smoke/tunnel-persistence.mjs +56 -56
  109. package/scripts/smoke/update-issue-progress.mjs +69 -69
  110. package/scripts/smoke/update-ux.mjs +55 -55
  111. package/scripts/smoke/v138-completion.mjs +132 -132
  112. package/scripts/smoke/v138-desktop-release-hardening.mjs +69 -69
  113. package/scripts/smoke/v138-diagnostics.mjs +63 -63
  114. package/scripts/smoke/v138-issue-planner.mjs +33 -33
  115. package/scripts/smoke/v143-remote-control.mjs +76 -76
  116. package/scripts/smoke/v144-production-loop.mjs +47 -47
  117. package/scripts/smoke/v145-platformization.mjs +46 -46
  118. package/scripts/smoke/v146-control-room-ui.mjs +150 -150
  119. package/scripts/smoke/version-modal-autoshow.mjs +29 -29
  120. package/scripts/smoke/vscode-workbench-layout.mjs +63 -63
  121. package/scripts/smoke/vscode-workbench-polish.mjs +461 -461
  122. package/scripts/smoke/workflow-fallback-replay.mjs +56 -56
  123. package/scripts/smoke/workflow-templates.mjs +43 -43
  124. package/scripts/smoke/workflow-trace-timeline.mjs +46 -46
  125. package/scripts/update-git-install.mjs +298 -298
  126. package/server/claude-sdk.js +927 -927
  127. package/server/cli.js +1106 -1106
  128. package/server/constants/config.js +4 -4
  129. package/server/cursor-cli.js +344 -344
  130. package/server/daemon/manager.js +563 -563
  131. package/server/daemon-manager.js +964 -964
  132. package/server/database/db.js +988 -988
  133. package/server/database/json-store.js +197 -197
  134. package/server/gemini-cli.js +550 -550
  135. package/server/gemini-response-handler.js +79 -79
  136. package/server/index.js +5620 -5544
  137. package/server/load-env.js +35 -35
  138. package/server/middleware/account-lockout.js +112 -112
  139. package/server/middleware/auth.js +277 -277
  140. package/server/middleware/rate-limiter.js +87 -87
  141. package/server/modules/orchestration/a2a/adapter-registry.ts +108 -108
  142. package/server/modules/orchestration/a2a/adapters/abstract-a2a.adapter.ts +63 -63
  143. package/server/modules/orchestration/a2a/adapters/claude-code.adapter.ts +286 -286
  144. package/server/modules/orchestration/a2a/adapters/codex.adapter.ts +244 -244
  145. package/server/modules/orchestration/a2a/adapters/cursor.adapter.ts +249 -249
  146. package/server/modules/orchestration/a2a/adapters/gemini.adapter.ts +248 -248
  147. package/server/modules/orchestration/a2a/adapters/json-event.adapter.test.ts +60 -60
  148. package/server/modules/orchestration/a2a/adapters/json-event.adapter.ts +101 -101
  149. package/server/modules/orchestration/a2a/adapters/opencode.adapter.ts +248 -248
  150. package/server/modules/orchestration/a2a/adapters/qwen.adapter.ts +248 -248
  151. package/server/modules/orchestration/a2a/agent-card.ts +55 -55
  152. package/server/modules/orchestration/a2a/auth.middleware.ts +29 -29
  153. package/server/modules/orchestration/a2a/bus.ts +46 -46
  154. package/server/modules/orchestration/a2a/routes.ts +586 -586
  155. package/server/modules/orchestration/a2a/task-dispatcher.ts +345 -345
  156. package/server/modules/orchestration/a2a/task-store.ts +178 -178
  157. package/server/modules/orchestration/a2a/types.ts +126 -126
  158. package/server/modules/orchestration/a2a/validator.ts +113 -113
  159. package/server/modules/orchestration/index.ts +99 -99
  160. package/server/modules/orchestration/preview/port-watcher.ts +112 -112
  161. package/server/modules/orchestration/preview/preview-proxy.ts +60 -60
  162. package/server/modules/orchestration/preview/types.ts +19 -19
  163. package/server/modules/orchestration/security/permission-policy.ts +401 -401
  164. package/server/modules/orchestration/tasks/orchestration-task-store.ts +41 -41
  165. package/server/modules/orchestration/tasks/orchestration-task.routes.ts +81 -81
  166. package/server/modules/orchestration/tasks/orchestration-task.service.ts +201 -201
  167. package/server/modules/orchestration/tasks/orchestration-task.types.ts +40 -40
  168. package/server/modules/orchestration/tasks/task-run-graph.ts +155 -155
  169. package/server/modules/orchestration/workflows/approval-queue.ts +106 -106
  170. package/server/modules/orchestration/workflows/built-in-workflows.ts +127 -127
  171. package/server/modules/orchestration/workflows/context-packet.ts +186 -186
  172. package/server/modules/orchestration/workflows/handoff-artifact.ts +175 -175
  173. package/server/modules/orchestration/workflows/workflow-fallback-policy.ts +161 -161
  174. package/server/modules/orchestration/workflows/workflow-replay.ts +254 -254
  175. package/server/modules/orchestration/workflows/workflow-runner.ts +2062 -2062
  176. package/server/modules/orchestration/workflows/workflow-store.ts +97 -97
  177. package/server/modules/orchestration/workflows/workflow-templates.ts +272 -272
  178. package/server/modules/orchestration/workflows/workflow-trace.ts +424 -424
  179. package/server/modules/orchestration/workflows/workflow.routes.ts +586 -586
  180. package/server/modules/orchestration/workflows/workflow.types.ts +111 -111
  181. package/server/modules/orchestration/workflows/workspace-target.ts +122 -122
  182. package/server/modules/orchestration/workspace/docker-workspace.ts +136 -136
  183. package/server/modules/orchestration/workspace/path-safety.ts +55 -55
  184. package/server/modules/orchestration/workspace/types.ts +52 -52
  185. package/server/modules/orchestration/workspace/workspace-manager.ts +102 -102
  186. package/server/modules/orchestration/workspace/worktree-workspace.ts +126 -126
  187. package/server/modules/providers/index.ts +2 -2
  188. package/server/modules/providers/list/claude/claude-auth.provider.ts +146 -146
  189. package/server/modules/providers/list/claude/claude-mcp.provider.ts +135 -135
  190. package/server/modules/providers/list/claude/claude-sessions.provider.ts +306 -306
  191. package/server/modules/providers/list/claude/claude.provider.ts +15 -15
  192. package/server/modules/providers/list/codex/codex-auth.provider.ts +117 -117
  193. package/server/modules/providers/list/codex/codex-mcp.provider.ts +135 -135
  194. package/server/modules/providers/list/codex/codex-sessions.provider.ts +319 -319
  195. package/server/modules/providers/list/codex/codex.provider.ts +15 -15
  196. package/server/modules/providers/list/cursor/cursor-auth.provider.ts +147 -147
  197. package/server/modules/providers/list/cursor/cursor-mcp.provider.ts +108 -108
  198. package/server/modules/providers/list/cursor/cursor-sessions.provider.ts +421 -421
  199. package/server/modules/providers/list/cursor/cursor.provider.ts +15 -15
  200. package/server/modules/providers/list/gemini/gemini-auth.provider.ts +173 -173
  201. package/server/modules/providers/list/gemini/gemini-mcp.provider.ts +110 -110
  202. package/server/modules/providers/list/gemini/gemini-sessions.provider.ts +227 -227
  203. package/server/modules/providers/list/gemini/gemini.provider.ts +15 -15
  204. package/server/modules/providers/list/opencode/opencode-auth.provider.ts +131 -131
  205. package/server/modules/providers/list/opencode/opencode-sessions.provider.ts +286 -286
  206. package/server/modules/providers/list/qwen/qwen-auth.provider.ts +146 -146
  207. package/server/modules/providers/list/qwen/qwen-sessions.provider.ts +265 -265
  208. package/server/modules/providers/provider.registry.ts +40 -40
  209. package/server/modules/providers/provider.routes.ts +982 -982
  210. package/server/modules/providers/services/mcp.service.ts +86 -86
  211. package/server/modules/providers/services/provider-auth.service.ts +26 -26
  212. package/server/modules/providers/services/sessions.service.ts +45 -45
  213. package/server/modules/providers/shared/base/abstract.provider.ts +20 -20
  214. package/server/modules/providers/shared/mcp/mcp.provider.ts +151 -151
  215. package/server/modules/providers/tests/mcp.test.ts +293 -293
  216. package/server/openai-codex.js +468 -468
  217. package/server/opencode-cli.js +491 -491
  218. package/server/opencode-response-handler.js +111 -111
  219. package/server/projects.js +3125 -3125
  220. package/server/qwen-code-cli.js +410 -410
  221. package/server/routes/agent.js +1451 -1451
  222. package/server/routes/auth.js +298 -286
  223. package/server/routes/codex.js +20 -20
  224. package/server/routes/commands.js +581 -581
  225. package/server/routes/cursor.js +61 -61
  226. package/server/routes/diagnostics.js +44 -44
  227. package/server/routes/gemini.js +25 -25
  228. package/server/routes/git.js +1822 -1822
  229. package/server/routes/live-view.js +434 -434
  230. package/server/routes/mcp-utils.js +13 -13
  231. package/server/routes/messages.js +97 -97
  232. package/server/routes/network.js +143 -143
  233. package/server/routes/platformization.js +231 -231
  234. package/server/routes/plugins.js +690 -690
  235. package/server/routes/production-agent-loop.js +90 -90
  236. package/server/routes/projects.js +918 -918
  237. package/server/routes/public-api.js +34 -34
  238. package/server/routes/qwen.js +27 -27
  239. package/server/routes/remote.js +56 -56
  240. package/server/routes/settings.js +321 -321
  241. package/server/routes/telegram.js +163 -163
  242. package/server/routes/user.js +125 -125
  243. package/server/routes/webhooks.js +63 -63
  244. package/server/services/control-room.js +102 -102
  245. package/server/services/diagnostics.js +165 -165
  246. package/server/services/external-access.js +403 -403
  247. package/server/services/install-jobs.js +715 -715
  248. package/server/services/live-view.js +956 -956
  249. package/server/services/managed-runtimes.js +493 -493
  250. package/server/services/model-registry.js +144 -144
  251. package/server/services/notification-orchestrator.js +365 -365
  252. package/server/services/notification-taxonomy.js +204 -204
  253. package/server/services/platformization.js +1052 -1052
  254. package/server/services/production-agent-loop.js +248 -248
  255. package/server/services/provider-cli-versions.js +149 -149
  256. package/server/services/provider-credentials.js +189 -189
  257. package/server/services/provider-models.js +396 -396
  258. package/server/services/public-api-manifest.js +181 -181
  259. package/server/services/qr-login.js +126 -126
  260. package/server/services/remote-connection.js +127 -127
  261. package/server/services/runtime-manager.js +323 -323
  262. package/server/services/startup-update.js +259 -259
  263. package/server/services/telegram/bot.js +393 -393
  264. package/server/services/telegram/control-center.js +2453 -2453
  265. package/server/services/telegram/telegram-gateway.js +314 -314
  266. package/server/services/telegram/telegram-http-client.js +201 -201
  267. package/server/services/telegram/translations.js +470 -470
  268. package/server/services/webhooks.js +216 -216
  269. package/server/sessionManager.js +225 -225
  270. package/server/setup-wizard.js +283 -283
  271. package/server/shared/interfaces.ts +54 -54
  272. package/server/shared/types.ts +172 -172
  273. package/server/shared/utils.ts +193 -193
  274. package/server/tsconfig.json +36 -36
  275. package/server/utils/colors.js +21 -21
  276. package/server/utils/commandParser.js +305 -305
  277. package/server/utils/frontmatter.js +18 -18
  278. package/server/utils/gitConfig.js +34 -34
  279. package/server/utils/plugin-loader.js +461 -461
  280. package/server/utils/plugin-process-manager.js +185 -185
  281. package/server/utils/port-access.js +227 -227
  282. package/server/utils/runtime-paths.js +37 -37
  283. package/server/utils/security-log.js +84 -84
  284. package/server/utils/url-detection.js +71 -71
  285. package/server/vite-daemon.js +79 -79
  286. package/shared/modelConstants.js +161 -161
  287. package/shared/networkHosts.js +22 -22
  288. package/dist/assets/index-DvudRU5X.css +0 -32
@@ -1,927 +1,927 @@
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 crypto from 'crypto';
16
- import { existsSync, readFileSync, promises as fs } from 'fs';
17
- import path from 'path';
18
- import os from 'os';
19
-
20
- import { query } from '@anthropic-ai/claude-agent-sdk';
21
-
22
- import {
23
- createNotificationEvent,
24
- notifyRunFailed,
25
- notifyRunStopped,
26
- notifyUserIfEnabled
27
- } from './services/notification-orchestrator.js';
28
- import { sessionsService } from './modules/providers/services/sessions.service.js';
29
- import { providerAuthService } from './modules/providers/services/provider-auth.service.js';
30
- import { resolveClaudeExecutable, resolveGitBashPath } from './services/install-jobs.js';
31
- import { createNormalizedMessage } from './shared/utils.js';
32
- import { evaluatePermissionRequest } from './modules/orchestration/security/permission-policy.js';
33
-
34
- const activeSessions = new Map();
35
- const pendingToolApprovals = new Map();
36
-
37
- const TOOL_APPROVAL_TIMEOUT_MS = parseInt(process.env.CLAUDE_TOOL_APPROVAL_TIMEOUT_MS, 10) || 55000;
38
-
39
- const TOOLS_REQUIRING_INTERACTION = new Set(['AskUserQuestion', 'ExitPlanMode']);
40
-
41
- function createRequestId() {
42
- if (typeof crypto.randomUUID === 'function') {
43
- return crypto.randomUUID();
44
- }
45
- return crypto.randomBytes(16).toString('hex');
46
- }
47
-
48
- function waitForToolApproval(requestId, options = {}) {
49
- const { timeoutMs = TOOL_APPROVAL_TIMEOUT_MS, signal, onCancel, metadata } = options;
50
-
51
- return new Promise(resolve => {
52
- let settled = false;
53
-
54
- const finalize = (decision) => {
55
- if (settled) return;
56
- settled = true;
57
- cleanup();
58
- resolve(decision);
59
- };
60
-
61
- let timeout;
62
-
63
- const cleanup = () => {
64
- pendingToolApprovals.delete(requestId);
65
- if (timeout) clearTimeout(timeout);
66
- if (signal && abortHandler) {
67
- signal.removeEventListener('abort', abortHandler);
68
- }
69
- };
70
-
71
- // timeoutMs 0 = wait indefinitely (interactive tools)
72
- if (timeoutMs > 0) {
73
- timeout = setTimeout(() => {
74
- onCancel?.('timeout');
75
- finalize(null);
76
- }, timeoutMs);
77
- }
78
-
79
- const abortHandler = () => {
80
- onCancel?.('cancelled');
81
- finalize({ cancelled: true });
82
- };
83
-
84
- if (signal) {
85
- if (signal.aborted) {
86
- onCancel?.('cancelled');
87
- finalize({ cancelled: true });
88
- return;
89
- }
90
- signal.addEventListener('abort', abortHandler, { once: true });
91
- }
92
-
93
- const resolver = (decision) => {
94
- finalize(decision);
95
- };
96
- // Attach metadata for getPendingApprovalsForSession lookup
97
- if (metadata) {
98
- Object.assign(resolver, metadata);
99
- }
100
- pendingToolApprovals.set(requestId, resolver);
101
- });
102
- }
103
-
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
- function readClaudeSettingsEnv(filePath) {
146
- try {
147
- if (!existsSync(filePath)) return {};
148
- const parsed = JSON.parse(readFileSync(filePath, 'utf8'));
149
- const env = parsed?.env;
150
- if (!env || typeof env !== 'object') return {};
151
-
152
- return Object.fromEntries(
153
- Object.entries(env)
154
- .filter(([key, value]) =>
155
- typeof value === 'string' &&
156
- value.trim() &&
157
- !key.startsWith('//'),
158
- ),
159
- );
160
- } catch {
161
- return {};
162
- }
163
- }
164
-
165
- function loadClaudeSettingsEnv(cwd) {
166
- const files = [
167
- path.join(os.homedir(), '.claude', 'settings.json'),
168
- ];
169
- if (cwd) {
170
- files.push(
171
- path.join(cwd, '.claude', 'settings.json'),
172
- path.join(cwd, '.claude', 'settings.local.json'),
173
- );
174
- }
175
-
176
- return files.reduce((env, filePath) => ({
177
- ...env,
178
- ...readClaudeSettingsEnv(filePath),
179
- }), {});
180
- }
181
-
182
- /**
183
- * Maps CLI options to SDK-compatible options format
184
- * @param {Object} options - CLI options
185
- * @returns {Object} SDK-compatible options
186
- */
187
- function mapCliOptionsToSDK(options = {}) {
188
- const { sessionId, cwd, toolsSettings, permissionMode, permissionPolicy, permissionPolicyContext } = options;
189
-
190
- const sdkOptions = {};
191
-
192
- // Forward all host env vars (e.g. ANTHROPIC_BASE_URL, ANTHROPIC_AUTH_TOKEN) to the subprocess.
193
- // Since claude-agent-sdk 0.2.113+, options.env REPLACES process.env in the subprocess
194
- // instead of overlaying it. Without spreading process.env here, users who rely on
195
- // ANTHROPIC_BASE_URL, HTTP(S)_PROXY, etc. would silently lose those settings.
196
- sdkOptions.env = { ...process.env, ...loadClaudeSettingsEnv(cwd) };
197
-
198
- // When running as root, Claude CLI refuses --dangerously-skip-permissions.
199
- // IS_SANDBOX=1 tells it the environment is sandboxed so the flag is accepted.
200
- const isRunningAsRoot = typeof process.getuid === 'function' && process.getuid() === 0;
201
- if (isRunningAsRoot) {
202
- sdkOptions.env.IS_SANDBOX = '1';
203
- }
204
-
205
- // Claude Code on Windows hard-requires a POSIX bash (typically from Git
206
- // for Windows) and reads its path from CLAUDE_CODE_GIT_BASH_PATH. If the
207
- // user has git-bash installed but hasn't exported that var, the CLI
208
- // exits with code 1 + a guidance message and the pixcode UI just sees
209
- // an opaque "Claude Code process exited with code 1" error. Auto-probing
210
- // a handful of known install locations lets the CLI boot transparently.
211
- if (!sdkOptions.env.CLAUDE_CODE_GIT_BASH_PATH) {
212
- const bashPath = resolveGitBashPath();
213
- if (bashPath) sdkOptions.env.CLAUDE_CODE_GIT_BASH_PATH = bashPath;
214
- }
215
-
216
- // Resolve the Claude Code CLI path cross-platform. The SDK uses plain
217
- // `child_process.spawn(command, args)` with no shell — and its own
218
- // `nb()` helper treats anything not ending in .js/.mjs/.ts as a native
219
- // executable. That means:
220
- // - Unix: bare `"claude"` works (kernel PATH + shebang handle it).
221
- // - Windows: bare `"claude"` fails ("native binary not found"). A
222
- // `.cmd` shim fails with EINVAL (post-CVE-2024 Node refuses .cmd
223
- // without shell:true). We need the underlying `.exe` instead.
224
- // `resolveClaudeExecutable()` does a `where`/`which` lookup and, on
225
- // Windows, peeks inside npm .cmd shims to recover the real .exe target.
226
- // If nothing is found we leave the option unset so the SDK falls through
227
- // to its own bundled-native-binary resolver.
228
- const resolvedClaudePath = process.env.CLAUDE_CLI_PATH || resolveClaudeExecutable();
229
- if (resolvedClaudePath) {
230
- sdkOptions.pathToClaudeCodeExecutable = resolvedClaudePath;
231
- }
232
-
233
- // Map working directory
234
- if (cwd) {
235
- sdkOptions.cwd = cwd;
236
- }
237
-
238
- // Map permission mode
239
- if (permissionMode && permissionMode !== 'default') {
240
- sdkOptions.permissionMode = permissionMode;
241
- }
242
- sdkOptions.permissionPolicy = permissionPolicy;
243
- sdkOptions.permissionPolicyContext = permissionPolicyContext;
244
-
245
- // Map tool settings
246
- const settings = toolsSettings || {
247
- allowedTools: [],
248
- disallowedTools: [],
249
- skipPermissions: false
250
- };
251
-
252
- // Handle tool permissions
253
- if (settings.skipPermissions && permissionMode !== 'plan') {
254
- // When skipping permissions, use bypassPermissions mode
255
- sdkOptions.permissionMode = 'bypassPermissions';
256
- }
257
-
258
- let allowedTools = [...(settings.allowedTools || [])];
259
-
260
- // Add plan mode default tools
261
- if (permissionMode === 'plan') {
262
- const planModeTools = ['Read', 'Task', 'exit_plan_mode', 'TodoRead', 'TodoWrite', 'WebFetch', 'WebSearch'];
263
- for (const tool of planModeTools) {
264
- if (!allowedTools.includes(tool)) {
265
- allowedTools.push(tool);
266
- }
267
- }
268
- }
269
-
270
- sdkOptions.allowedTools = allowedTools;
271
-
272
- // Use the tools preset to make all default built-in tools available (including AskUserQuestion).
273
- // This was introduced in SDK 0.1.57. Omitting this preserves existing behavior (all tools available),
274
- // but being explicit ensures forward compatibility and clarity.
275
- sdkOptions.tools = { type: 'preset', preset: 'claude_code' };
276
-
277
- sdkOptions.disallowedTools = settings.disallowedTools || [];
278
-
279
- // Map model only when Pixcode explicitly passes one. If omitted, let
280
- // Claude Code load the user's own project/user/local settings, including
281
- // ~/.claude/settings.json "model".
282
- if (typeof options.model === 'string' && options.model.trim()) {
283
- sdkOptions.model = options.model.trim();
284
- }
285
- // Model logged at query start below
286
-
287
- // Map system prompt configuration
288
- sdkOptions.systemPrompt = {
289
- type: 'preset',
290
- preset: 'claude_code' // Required to use CLAUDE.md
291
- };
292
-
293
- // Map setting sources for CLAUDE.md loading
294
- // This loads CLAUDE.md from project, user (~/.config/claude/CLAUDE.md), and local directories
295
- sdkOptions.settingSources = ['project', 'user', 'local'];
296
-
297
- // Map resume session
298
- if (sessionId) {
299
- sdkOptions.resume = sessionId;
300
- }
301
-
302
- return sdkOptions;
303
- }
304
-
305
- /**
306
- * Adds a session to the active sessions map
307
- * @param {string} sessionId - Session identifier
308
- * @param {Object} queryInstance - SDK query instance
309
- * @param {Array<string>} tempImagePaths - Temp image file paths for cleanup
310
- * @param {string} tempDir - Temp directory for cleanup
311
- */
312
- function addSession(sessionId, queryInstance, tempImagePaths = [], tempDir = null, writer = null) {
313
- activeSessions.set(sessionId, {
314
- instance: queryInstance,
315
- startTime: Date.now(),
316
- status: 'active',
317
- tempImagePaths,
318
- tempDir,
319
- writer
320
- });
321
- }
322
-
323
- /**
324
- * Removes a session from the active sessions map
325
- * @param {string} sessionId - Session identifier
326
- */
327
- function removeSession(sessionId) {
328
- activeSessions.delete(sessionId);
329
- }
330
-
331
- /**
332
- * Gets a session from the active sessions map
333
- * @param {string} sessionId - Session identifier
334
- * @returns {Object|undefined} Session data or undefined
335
- */
336
- function getSession(sessionId) {
337
- return activeSessions.get(sessionId);
338
- }
339
-
340
- /**
341
- * Gets all active session IDs
342
- * @returns {Array<string>} Array of active session IDs
343
- */
344
- function getAllSessions() {
345
- return Array.from(activeSessions.keys());
346
- }
347
-
348
- /**
349
- * Transforms SDK messages to WebSocket format expected by frontend
350
- * @param {Object} sdkMessage - SDK message object
351
- * @returns {Object} Transformed message ready for WebSocket
352
- */
353
- function transformMessage(sdkMessage) {
354
- // Extract parent_tool_use_id for subagent tool grouping
355
- if (sdkMessage.parent_tool_use_id) {
356
- return {
357
- ...sdkMessage,
358
- parentToolUseId: sdkMessage.parent_tool_use_id
359
- };
360
- }
361
- return sdkMessage;
362
- }
363
-
364
- /**
365
- * Extracts token usage from SDK result messages
366
- * @param {Object} resultMessage - SDK result message
367
- * @returns {Object|null} Token budget object or null
368
- */
369
- function extractTokenBudget(resultMessage) {
370
- if (resultMessage.type !== 'result' || !resultMessage.modelUsage) {
371
- return null;
372
- }
373
-
374
- // Get the first model's usage data
375
- const modelKey = Object.keys(resultMessage.modelUsage)[0];
376
- const modelData = resultMessage.modelUsage[modelKey];
377
-
378
- if (!modelData) {
379
- return null;
380
- }
381
-
382
- // Use cumulative tokens if available (tracks total for the session)
383
- // Otherwise fall back to per-request tokens
384
- const inputTokens = modelData.cumulativeInputTokens || modelData.inputTokens || 0;
385
- const outputTokens = modelData.cumulativeOutputTokens || modelData.outputTokens || 0;
386
- const cacheReadTokens = modelData.cumulativeCacheReadInputTokens || modelData.cacheReadInputTokens || 0;
387
- const cacheCreationTokens = modelData.cumulativeCacheCreationInputTokens || modelData.cacheCreationInputTokens || 0;
388
-
389
- // Total used = input + output + cache tokens
390
- const totalUsed = inputTokens + outputTokens + cacheReadTokens + cacheCreationTokens;
391
-
392
- // Use configured context window budget from environment (default 160000)
393
- // This is the user's budget limit, not the model's context window
394
- const contextWindow = parseInt(process.env.CONTEXT_WINDOW) || 160000;
395
-
396
- // Token calc logged via token-budget WS event
397
-
398
- return {
399
- used: totalUsed,
400
- total: contextWindow
401
- };
402
- }
403
-
404
- /**
405
- * Handles image processing for SDK queries
406
- * Saves base64 images to temporary files and returns modified prompt with file paths
407
- * @param {string} command - Original user prompt
408
- * @param {Array} images - Array of image objects with base64 data
409
- * @param {string} cwd - Working directory for temp file creation
410
- * @returns {Promise<Object>} {modifiedCommand, tempImagePaths, tempDir}
411
- */
412
- async function handleImages(command, images, cwd) {
413
- const tempImagePaths = [];
414
- let tempDir = null;
415
-
416
- if (!images || images.length === 0) {
417
- return { modifiedCommand: command, tempImagePaths, tempDir };
418
- }
419
-
420
- try {
421
- // Create temp directory in the project directory
422
- const workingDir = cwd || process.cwd();
423
- tempDir = path.join(workingDir, '.tmp', 'images', Date.now().toString());
424
- await fs.mkdir(tempDir, { recursive: true });
425
-
426
- // Save each image to a temp file
427
- for (const [index, image] of images.entries()) {
428
- // Extract base64 data and mime type
429
- const matches = image.data.match(/^data:([^;]+);base64,(.+)$/);
430
- if (!matches) {
431
- console.error('Invalid image data format');
432
- continue;
433
- }
434
-
435
- const [, mimeType, base64Data] = matches;
436
- const extension = mimeType.split('/')[1] || 'png';
437
- const filename = `image_${index}.${extension}`;
438
- const filepath = path.join(tempDir, filename);
439
-
440
- // Write base64 data to file
441
- await fs.writeFile(filepath, Buffer.from(base64Data, 'base64'));
442
- tempImagePaths.push(filepath);
443
- }
444
-
445
- // Include the full image paths in the prompt
446
- let modifiedCommand = command;
447
- if (tempImagePaths.length > 0 && command && command.trim()) {
448
- const imageNote = `\n\n[Images provided at the following paths:]\n${tempImagePaths.map((p, i) => `${i + 1}. ${p}`).join('\n')}`;
449
- modifiedCommand = command + imageNote;
450
- }
451
-
452
- // Images processed
453
- return { modifiedCommand, tempImagePaths, tempDir };
454
- } catch (error) {
455
- console.error('Error processing images for SDK:', error);
456
- return { modifiedCommand: command, tempImagePaths, tempDir };
457
- }
458
- }
459
-
460
- /**
461
- * Cleans up temporary image files
462
- * @param {Array<string>} tempImagePaths - Array of temp file paths to delete
463
- * @param {string} tempDir - Temp directory to remove
464
- */
465
- async function cleanupTempFiles(tempImagePaths, tempDir) {
466
- if (!tempImagePaths || tempImagePaths.length === 0) {
467
- return;
468
- }
469
-
470
- try {
471
- // Delete individual temp files
472
- for (const imagePath of tempImagePaths) {
473
- await fs.unlink(imagePath).catch(err =>
474
- console.error(`Failed to delete temp image ${imagePath}:`, err)
475
- );
476
- }
477
-
478
- // Delete temp directory
479
- if (tempDir) {
480
- await fs.rm(tempDir, { recursive: true, force: true }).catch(err =>
481
- console.error(`Failed to delete temp directory ${tempDir}:`, err)
482
- );
483
- }
484
-
485
- // Temp files cleaned
486
- } catch (error) {
487
- console.error('Error during temp file cleanup:', error);
488
- }
489
- }
490
-
491
- /**
492
- * Loads MCP server configurations from ~/.claude.json
493
- * @param {string} cwd - Current working directory for project-specific configs
494
- * @returns {Object|null} MCP servers object or null if none found
495
- */
496
- async function loadMcpConfig(cwd) {
497
- try {
498
- const claudeConfigPath = path.join(os.homedir(), '.claude.json');
499
-
500
- // Check if config file exists
501
- try {
502
- await fs.access(claudeConfigPath);
503
- } catch (error) {
504
- // File doesn't exist, return null
505
- // No config file
506
- return null;
507
- }
508
-
509
- // Read and parse config file
510
- let claudeConfig;
511
- try {
512
- const configContent = await fs.readFile(claudeConfigPath, 'utf8');
513
- claudeConfig = JSON.parse(configContent);
514
- } catch (error) {
515
- console.error('Failed to parse ~/.claude.json:', error.message);
516
- return null;
517
- }
518
-
519
- // Extract MCP servers (merge global and project-specific)
520
- let mcpServers = {};
521
-
522
- // Add global MCP servers
523
- if (claudeConfig.mcpServers && typeof claudeConfig.mcpServers === 'object') {
524
- mcpServers = { ...claudeConfig.mcpServers };
525
- // Global MCP servers loaded
526
- }
527
-
528
- // Add/override with project-specific MCP servers
529
- if (claudeConfig.claudeProjects && cwd) {
530
- const projectConfig = claudeConfig.claudeProjects[cwd];
531
- if (projectConfig && projectConfig.mcpServers && typeof projectConfig.mcpServers === 'object') {
532
- mcpServers = { ...mcpServers, ...projectConfig.mcpServers };
533
- // Project MCP servers merged
534
- }
535
- }
536
-
537
- // Return null if no servers found
538
- if (Object.keys(mcpServers).length === 0) {
539
- return null;
540
- }
541
- return mcpServers;
542
- } catch (error) {
543
- console.error('Error loading MCP config:', error.message);
544
- return null;
545
- }
546
- }
547
-
548
- /**
549
- * Executes a Claude query using the SDK
550
- * @param {string} command - User prompt/command
551
- * @param {Object} options - Query options
552
- * @param {Object} ws - WebSocket connection
553
- * @returns {Promise<void>}
554
- */
555
- async function queryClaudeSDK(command, options = {}, ws) {
556
- const { sessionId, sessionSummary, suppressNotifications = false } = options;
557
- let capturedSessionId = sessionId;
558
- let sessionCreatedSent = false;
559
- let tempImagePaths = [];
560
- let tempDir = null;
561
-
562
- const emitNotification = (event) => {
563
- notifyUserIfEnabled({
564
- userId: ws?.userId || null,
565
- writer: ws,
566
- event
567
- });
568
- };
569
-
570
- try {
571
- // Map CLI options to SDK format
572
- const sdkOptions = mapCliOptionsToSDK(options);
573
-
574
- // Load MCP configuration
575
- const mcpServers = await loadMcpConfig(options.cwd);
576
- if (mcpServers) {
577
- sdkOptions.mcpServers = mcpServers;
578
- }
579
-
580
- // Handle images - save to temp files and modify prompt
581
- const imageResult = await handleImages(command, options.images, options.cwd);
582
- const finalCommand = imageResult.modifiedCommand;
583
- tempImagePaths = imageResult.tempImagePaths;
584
- tempDir = imageResult.tempDir;
585
-
586
- sdkOptions.hooks = {
587
- Notification: [{
588
- matcher: '',
589
- hooks: [async (input) => {
590
- const message = typeof input?.message === 'string' ? input.message : 'Claude requires your attention.';
591
- emitNotification(createNotificationEvent({
592
- provider: 'claude',
593
- sessionId: capturedSessionId || sessionId || null,
594
- kind: 'action_required',
595
- code: 'agent.notification',
596
- meta: { message, sessionName: sessionSummary },
597
- severity: 'warning',
598
- requiresUserAction: true,
599
- dedupeKey: `claude:hook:notification:${capturedSessionId || sessionId || 'none'}:${message}`
600
- }));
601
- return {};
602
- }]
603
- }]
604
- };
605
-
606
- sdkOptions.canUseTool = async (toolName, input, context) => {
607
- const requiresInteraction = TOOLS_REQUIRING_INTERACTION.has(toolName);
608
- const policyDecision = evaluatePermissionRequest({
609
- policy: sdkOptions.permissionPolicy,
610
- request: {
611
- source: 'provider_tool',
612
- toolName,
613
- input,
614
- command: input && typeof input === 'object' && typeof input.command === 'string'
615
- ? input.command
616
- : undefined,
617
- cwd: options.cwd,
618
- workspacePath: options.cwd,
619
- summary: `${toolName} tool request`,
620
- },
621
- context: sdkOptions.permissionPolicyContext,
622
- });
623
-
624
- if (policyDecision.behavior === 'deny') {
625
- return { behavior: 'deny', message: policyDecision.message };
626
- }
627
-
628
- if (!requiresInteraction && policyDecision.behavior !== 'prompt') {
629
- if (sdkOptions.permissionMode === 'bypassPermissions') {
630
- return { behavior: 'allow', updatedInput: input };
631
- }
632
-
633
- const isDisallowed = (sdkOptions.disallowedTools || []).some(entry =>
634
- matchesToolPermission(entry, toolName, input)
635
- );
636
- if (isDisallowed) {
637
- return { behavior: 'deny', message: 'Tool disallowed by settings' };
638
- }
639
-
640
- const isAllowed = (sdkOptions.allowedTools || []).some(entry =>
641
- matchesToolPermission(entry, toolName, input)
642
- );
643
- if (isAllowed) {
644
- return { behavior: 'allow', updatedInput: input };
645
- }
646
- }
647
-
648
- const requestId = createRequestId();
649
- ws.send(createNormalizedMessage({ kind: 'permission_request', requestId, toolName, input, sessionId: capturedSessionId || sessionId || null, provider: 'claude' }));
650
- emitNotification(createNotificationEvent({
651
- provider: 'claude',
652
- sessionId: capturedSessionId || sessionId || null,
653
- kind: 'action_required',
654
- code: 'permission.required',
655
- meta: { toolName, sessionName: sessionSummary },
656
- severity: 'warning',
657
- requiresUserAction: true,
658
- dedupeKey: `claude:permission:${capturedSessionId || sessionId || 'none'}:${requestId}`
659
- }));
660
-
661
- const decision = await waitForToolApproval(requestId, {
662
- timeoutMs: requiresInteraction ? 0 : undefined,
663
- signal: context?.signal,
664
- metadata: {
665
- _sessionId: capturedSessionId || sessionId || null,
666
- _toolName: toolName,
667
- _input: input,
668
- _receivedAt: new Date(),
669
- },
670
- onCancel: (reason) => {
671
- ws.send(createNormalizedMessage({ kind: 'permission_cancelled', requestId, reason, sessionId: capturedSessionId || sessionId || null, provider: 'claude' }));
672
- }
673
- });
674
- if (!decision) {
675
- return { behavior: 'deny', message: 'Permission request timed out' };
676
- }
677
-
678
- if (decision.cancelled) {
679
- return { behavior: 'deny', message: 'Permission request cancelled' };
680
- }
681
-
682
- if (decision.allow) {
683
- if (decision.rememberEntry && typeof decision.rememberEntry === 'string') {
684
- if (!sdkOptions.allowedTools.includes(decision.rememberEntry)) {
685
- sdkOptions.allowedTools.push(decision.rememberEntry);
686
- }
687
- if (Array.isArray(sdkOptions.disallowedTools)) {
688
- sdkOptions.disallowedTools = sdkOptions.disallowedTools.filter(entry => entry !== decision.rememberEntry);
689
- }
690
- }
691
- return { behavior: 'allow', updatedInput: decision.updatedInput ?? input };
692
- }
693
-
694
- return { behavior: 'deny', message: decision.message ?? 'User denied tool use' };
695
- };
696
-
697
- // Set stream-close timeout for interactive tools (Query constructor reads it synchronously). Claude Agent SDK has a default of 5s and this overrides it
698
- const prevStreamTimeout = process.env.CLAUDE_CODE_STREAM_CLOSE_TIMEOUT;
699
- process.env.CLAUDE_CODE_STREAM_CLOSE_TIMEOUT = '300000';
700
-
701
- let queryInstance;
702
- try {
703
- queryInstance = query({
704
- prompt: finalCommand,
705
- options: sdkOptions
706
- });
707
- } catch (hookError) {
708
- // Older/newer SDK versions may not accept hook shapes yet.
709
- // Keep notification behavior operational via runtime events even if hook registration fails.
710
- console.warn('Failed to initialize Claude query with hooks, retrying without hooks:', hookError?.message || hookError);
711
- delete sdkOptions.hooks;
712
- queryInstance = query({
713
- prompt: finalCommand,
714
- options: sdkOptions
715
- });
716
- }
717
-
718
- // Restore immediately — Query constructor already captured the value
719
- if (prevStreamTimeout !== undefined) {
720
- process.env.CLAUDE_CODE_STREAM_CLOSE_TIMEOUT = prevStreamTimeout;
721
- } else {
722
- delete process.env.CLAUDE_CODE_STREAM_CLOSE_TIMEOUT;
723
- }
724
-
725
- // Track the query instance for abort capability
726
- if (capturedSessionId) {
727
- addSession(capturedSessionId, queryInstance, tempImagePaths, tempDir, ws);
728
- }
729
-
730
- // Process streaming messages
731
- console.log('Starting async generator loop for session:', capturedSessionId || 'NEW');
732
- for await (const message of queryInstance) {
733
- // Capture session ID from first message
734
- if (message.session_id && !capturedSessionId) {
735
-
736
- capturedSessionId = message.session_id;
737
- addSession(capturedSessionId, queryInstance, tempImagePaths, tempDir, ws);
738
-
739
- // Set session ID on writer
740
- if (ws.setSessionId && typeof ws.setSessionId === 'function') {
741
- ws.setSessionId(capturedSessionId);
742
- }
743
-
744
- // Send session-created event only once for new sessions
745
- if (!sessionId && !sessionCreatedSent) {
746
- sessionCreatedSent = true;
747
- ws.send(createNormalizedMessage({ kind: 'session_created', newSessionId: capturedSessionId, sessionId: capturedSessionId, provider: 'claude' }));
748
- }
749
- } else {
750
- // session_id already captured
751
- }
752
-
753
- // Transform and normalize message via adapter
754
- const transformedMessage = transformMessage(message);
755
- const sid = capturedSessionId || sessionId || null;
756
-
757
- // Use adapter to normalize SDK events into NormalizedMessage[]
758
- const normalized = sessionsService.normalizeMessage('claude', transformedMessage, sid);
759
- for (const msg of normalized) {
760
- // Preserve parentToolUseId from SDK wrapper for subagent tool grouping
761
- if (transformedMessage.parentToolUseId && !msg.parentToolUseId) {
762
- msg.parentToolUseId = transformedMessage.parentToolUseId;
763
- }
764
- ws.send(msg);
765
- }
766
-
767
- // Extract and send token budget updates from result messages
768
- if (message.type === 'result') {
769
- const models = Object.keys(message.modelUsage || {});
770
- if (models.length > 0) {
771
- // Model info available in result message
772
- }
773
- const tokenBudgetData = extractTokenBudget(message);
774
- if (tokenBudgetData) {
775
- ws.send(createNormalizedMessage({ kind: 'status', text: 'token_budget', tokenBudget: tokenBudgetData, sessionId: capturedSessionId || sessionId || null, provider: 'claude' }));
776
- }
777
- }
778
- }
779
-
780
- // Clean up session on completion
781
- if (capturedSessionId) {
782
- removeSession(capturedSessionId);
783
- }
784
-
785
- // Clean up temporary image files
786
- await cleanupTempFiles(tempImagePaths, tempDir);
787
-
788
- // Send completion event
789
- ws.send(createNormalizedMessage({ kind: 'complete', exitCode: 0, isNewSession: !sessionId && !!command, sessionId: capturedSessionId, provider: 'claude' }));
790
- if (!suppressNotifications) notifyRunStopped({
791
- userId: ws?.userId || null,
792
- provider: 'claude',
793
- sessionId: capturedSessionId || sessionId || null,
794
- sessionName: sessionSummary,
795
- stopReason: 'completed'
796
- });
797
- // Complete
798
-
799
- } catch (error) {
800
- console.error('SDK query error:', error);
801
-
802
- // Clean up session on error
803
- if (capturedSessionId) {
804
- removeSession(capturedSessionId);
805
- }
806
-
807
- // Clean up temporary image files on error
808
- await cleanupTempFiles(tempImagePaths, tempDir);
809
-
810
- // Check if Claude CLI is installed for a clearer error message
811
- const installed = await providerAuthService.isProviderInstalled('claude');
812
- const errorContent = !installed
813
- ? 'Claude Code is not installed. Please install it first: https://docs.anthropic.com/en/docs/claude-code'
814
- : error.message;
815
-
816
- // Send error to WebSocket
817
- ws.send(createNormalizedMessage({ kind: 'error', content: errorContent, sessionId: capturedSessionId || sessionId || null, provider: 'claude' }));
818
- if (!suppressNotifications) notifyRunFailed({
819
- userId: ws?.userId || null,
820
- provider: 'claude',
821
- sessionId: capturedSessionId || sessionId || null,
822
- sessionName: sessionSummary,
823
- error
824
- });
825
- }
826
- }
827
-
828
- /**
829
- * Aborts an active SDK session
830
- * @param {string} sessionId - Session identifier
831
- * @returns {boolean} True if session was aborted, false if not found
832
- */
833
- async function abortClaudeSDKSession(sessionId) {
834
- const session = getSession(sessionId);
835
-
836
- if (!session) {
837
- console.log(`Session ${sessionId} not found`);
838
- return false;
839
- }
840
-
841
- try {
842
- console.log(`Aborting SDK session: ${sessionId}`);
843
-
844
- // Call interrupt() on the query instance
845
- await session.instance.interrupt();
846
-
847
- // Update session status
848
- session.status = 'aborted';
849
-
850
- // Clean up temporary image files
851
- await cleanupTempFiles(session.tempImagePaths, session.tempDir);
852
-
853
- // Clean up session
854
- removeSession(sessionId);
855
-
856
- return true;
857
- } catch (error) {
858
- console.error(`Error aborting session ${sessionId}:`, error);
859
- return false;
860
- }
861
- }
862
-
863
- /**
864
- * Checks if an SDK session is currently active
865
- * @param {string} sessionId - Session identifier
866
- * @returns {boolean} True if session is active
867
- */
868
- function isClaudeSDKSessionActive(sessionId) {
869
- const session = getSession(sessionId);
870
- return session && session.status === 'active';
871
- }
872
-
873
- /**
874
- * Gets all active SDK session IDs
875
- * @returns {Array<string>} Array of active session IDs
876
- */
877
- function getActiveClaudeSDKSessions() {
878
- return getAllSessions();
879
- }
880
-
881
- /**
882
- * Get pending tool approvals for a specific session.
883
- * @param {string} sessionId - The session ID
884
- * @returns {Array} Array of pending permission request objects
885
- */
886
- function getPendingApprovalsForSession(sessionId) {
887
- const pending = [];
888
- for (const [requestId, resolver] of pendingToolApprovals.entries()) {
889
- if (resolver._sessionId === sessionId) {
890
- pending.push({
891
- requestId,
892
- toolName: resolver._toolName || 'UnknownTool',
893
- input: resolver._input,
894
- context: resolver._context,
895
- sessionId,
896
- receivedAt: resolver._receivedAt || new Date(),
897
- });
898
- }
899
- }
900
- return pending;
901
- }
902
-
903
- /**
904
- * Reconnect a session's WebSocketWriter to a new raw WebSocket.
905
- * Called when client reconnects (e.g. page refresh) while SDK is still running.
906
- * @param {string} sessionId - The session ID
907
- * @param {Object} newRawWs - The new raw WebSocket connection
908
- * @returns {boolean} True if writer was successfully reconnected
909
- */
910
- function reconnectSessionWriter(sessionId, newRawWs) {
911
- const session = getSession(sessionId);
912
- if (!session?.writer?.updateWebSocket) return false;
913
- session.writer.updateWebSocket(newRawWs);
914
- console.log(`[RECONNECT] Writer swapped for session ${sessionId}`);
915
- return true;
916
- }
917
-
918
- // Export public API
919
- export {
920
- queryClaudeSDK,
921
- abortClaudeSDKSession,
922
- isClaudeSDKSessionActive,
923
- getActiveClaudeSDKSessions,
924
- resolveToolApproval,
925
- getPendingApprovalsForSession,
926
- reconnectSessionWriter
927
- };
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 crypto from 'crypto';
16
+ import { existsSync, readFileSync, promises as fs } from 'fs';
17
+ import path from 'path';
18
+ import os from 'os';
19
+
20
+ import { query } from '@anthropic-ai/claude-agent-sdk';
21
+
22
+ import {
23
+ createNotificationEvent,
24
+ notifyRunFailed,
25
+ notifyRunStopped,
26
+ notifyUserIfEnabled
27
+ } from './services/notification-orchestrator.js';
28
+ import { sessionsService } from './modules/providers/services/sessions.service.js';
29
+ import { providerAuthService } from './modules/providers/services/provider-auth.service.js';
30
+ import { resolveClaudeExecutable, resolveGitBashPath } from './services/install-jobs.js';
31
+ import { createNormalizedMessage } from './shared/utils.js';
32
+ import { evaluatePermissionRequest } from './modules/orchestration/security/permission-policy.js';
33
+
34
+ const activeSessions = new Map();
35
+ const pendingToolApprovals = new Map();
36
+
37
+ const TOOL_APPROVAL_TIMEOUT_MS = parseInt(process.env.CLAUDE_TOOL_APPROVAL_TIMEOUT_MS, 10) || 55000;
38
+
39
+ const TOOLS_REQUIRING_INTERACTION = new Set(['AskUserQuestion', 'ExitPlanMode']);
40
+
41
+ function createRequestId() {
42
+ if (typeof crypto.randomUUID === 'function') {
43
+ return crypto.randomUUID();
44
+ }
45
+ return crypto.randomBytes(16).toString('hex');
46
+ }
47
+
48
+ function waitForToolApproval(requestId, options = {}) {
49
+ const { timeoutMs = TOOL_APPROVAL_TIMEOUT_MS, signal, onCancel, metadata } = options;
50
+
51
+ return new Promise(resolve => {
52
+ let settled = false;
53
+
54
+ const finalize = (decision) => {
55
+ if (settled) return;
56
+ settled = true;
57
+ cleanup();
58
+ resolve(decision);
59
+ };
60
+
61
+ let timeout;
62
+
63
+ const cleanup = () => {
64
+ pendingToolApprovals.delete(requestId);
65
+ if (timeout) clearTimeout(timeout);
66
+ if (signal && abortHandler) {
67
+ signal.removeEventListener('abort', abortHandler);
68
+ }
69
+ };
70
+
71
+ // timeoutMs 0 = wait indefinitely (interactive tools)
72
+ if (timeoutMs > 0) {
73
+ timeout = setTimeout(() => {
74
+ onCancel?.('timeout');
75
+ finalize(null);
76
+ }, timeoutMs);
77
+ }
78
+
79
+ const abortHandler = () => {
80
+ onCancel?.('cancelled');
81
+ finalize({ cancelled: true });
82
+ };
83
+
84
+ if (signal) {
85
+ if (signal.aborted) {
86
+ onCancel?.('cancelled');
87
+ finalize({ cancelled: true });
88
+ return;
89
+ }
90
+ signal.addEventListener('abort', abortHandler, { once: true });
91
+ }
92
+
93
+ const resolver = (decision) => {
94
+ finalize(decision);
95
+ };
96
+ // Attach metadata for getPendingApprovalsForSession lookup
97
+ if (metadata) {
98
+ Object.assign(resolver, metadata);
99
+ }
100
+ pendingToolApprovals.set(requestId, resolver);
101
+ });
102
+ }
103
+
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
+ function readClaudeSettingsEnv(filePath) {
146
+ try {
147
+ if (!existsSync(filePath)) return {};
148
+ const parsed = JSON.parse(readFileSync(filePath, 'utf8'));
149
+ const env = parsed?.env;
150
+ if (!env || typeof env !== 'object') return {};
151
+
152
+ return Object.fromEntries(
153
+ Object.entries(env)
154
+ .filter(([key, value]) =>
155
+ typeof value === 'string' &&
156
+ value.trim() &&
157
+ !key.startsWith('//'),
158
+ ),
159
+ );
160
+ } catch {
161
+ return {};
162
+ }
163
+ }
164
+
165
+ function loadClaudeSettingsEnv(cwd) {
166
+ const files = [
167
+ path.join(os.homedir(), '.claude', 'settings.json'),
168
+ ];
169
+ if (cwd) {
170
+ files.push(
171
+ path.join(cwd, '.claude', 'settings.json'),
172
+ path.join(cwd, '.claude', 'settings.local.json'),
173
+ );
174
+ }
175
+
176
+ return files.reduce((env, filePath) => ({
177
+ ...env,
178
+ ...readClaudeSettingsEnv(filePath),
179
+ }), {});
180
+ }
181
+
182
+ /**
183
+ * Maps CLI options to SDK-compatible options format
184
+ * @param {Object} options - CLI options
185
+ * @returns {Object} SDK-compatible options
186
+ */
187
+ function mapCliOptionsToSDK(options = {}) {
188
+ const { sessionId, cwd, toolsSettings, permissionMode, permissionPolicy, permissionPolicyContext } = options;
189
+
190
+ const sdkOptions = {};
191
+
192
+ // Forward all host env vars (e.g. ANTHROPIC_BASE_URL, ANTHROPIC_AUTH_TOKEN) to the subprocess.
193
+ // Since claude-agent-sdk 0.2.113+, options.env REPLACES process.env in the subprocess
194
+ // instead of overlaying it. Without spreading process.env here, users who rely on
195
+ // ANTHROPIC_BASE_URL, HTTP(S)_PROXY, etc. would silently lose those settings.
196
+ sdkOptions.env = { ...process.env, ...loadClaudeSettingsEnv(cwd) };
197
+
198
+ // When running as root, Claude CLI refuses --dangerously-skip-permissions.
199
+ // IS_SANDBOX=1 tells it the environment is sandboxed so the flag is accepted.
200
+ const isRunningAsRoot = typeof process.getuid === 'function' && process.getuid() === 0;
201
+ if (isRunningAsRoot) {
202
+ sdkOptions.env.IS_SANDBOX = '1';
203
+ }
204
+
205
+ // Claude Code on Windows hard-requires a POSIX bash (typically from Git
206
+ // for Windows) and reads its path from CLAUDE_CODE_GIT_BASH_PATH. If the
207
+ // user has git-bash installed but hasn't exported that var, the CLI
208
+ // exits with code 1 + a guidance message and the pixcode UI just sees
209
+ // an opaque "Claude Code process exited with code 1" error. Auto-probing
210
+ // a handful of known install locations lets the CLI boot transparently.
211
+ if (!sdkOptions.env.CLAUDE_CODE_GIT_BASH_PATH) {
212
+ const bashPath = resolveGitBashPath();
213
+ if (bashPath) sdkOptions.env.CLAUDE_CODE_GIT_BASH_PATH = bashPath;
214
+ }
215
+
216
+ // Resolve the Claude Code CLI path cross-platform. The SDK uses plain
217
+ // `child_process.spawn(command, args)` with no shell — and its own
218
+ // `nb()` helper treats anything not ending in .js/.mjs/.ts as a native
219
+ // executable. That means:
220
+ // - Unix: bare `"claude"` works (kernel PATH + shebang handle it).
221
+ // - Windows: bare `"claude"` fails ("native binary not found"). A
222
+ // `.cmd` shim fails with EINVAL (post-CVE-2024 Node refuses .cmd
223
+ // without shell:true). We need the underlying `.exe` instead.
224
+ // `resolveClaudeExecutable()` does a `where`/`which` lookup and, on
225
+ // Windows, peeks inside npm .cmd shims to recover the real .exe target.
226
+ // If nothing is found we leave the option unset so the SDK falls through
227
+ // to its own bundled-native-binary resolver.
228
+ const resolvedClaudePath = process.env.CLAUDE_CLI_PATH || resolveClaudeExecutable();
229
+ if (resolvedClaudePath) {
230
+ sdkOptions.pathToClaudeCodeExecutable = resolvedClaudePath;
231
+ }
232
+
233
+ // Map working directory
234
+ if (cwd) {
235
+ sdkOptions.cwd = cwd;
236
+ }
237
+
238
+ // Map permission mode
239
+ if (permissionMode && permissionMode !== 'default') {
240
+ sdkOptions.permissionMode = permissionMode;
241
+ }
242
+ sdkOptions.permissionPolicy = permissionPolicy;
243
+ sdkOptions.permissionPolicyContext = permissionPolicyContext;
244
+
245
+ // Map tool settings
246
+ const settings = toolsSettings || {
247
+ allowedTools: [],
248
+ disallowedTools: [],
249
+ skipPermissions: false
250
+ };
251
+
252
+ // Handle tool permissions
253
+ if (settings.skipPermissions && permissionMode !== 'plan') {
254
+ // When skipping permissions, use bypassPermissions mode
255
+ sdkOptions.permissionMode = 'bypassPermissions';
256
+ }
257
+
258
+ let allowedTools = [...(settings.allowedTools || [])];
259
+
260
+ // Add plan mode default tools
261
+ if (permissionMode === 'plan') {
262
+ const planModeTools = ['Read', 'Task', 'exit_plan_mode', 'TodoRead', 'TodoWrite', 'WebFetch', 'WebSearch'];
263
+ for (const tool of planModeTools) {
264
+ if (!allowedTools.includes(tool)) {
265
+ allowedTools.push(tool);
266
+ }
267
+ }
268
+ }
269
+
270
+ sdkOptions.allowedTools = allowedTools;
271
+
272
+ // Use the tools preset to make all default built-in tools available (including AskUserQuestion).
273
+ // This was introduced in SDK 0.1.57. Omitting this preserves existing behavior (all tools available),
274
+ // but being explicit ensures forward compatibility and clarity.
275
+ sdkOptions.tools = { type: 'preset', preset: 'claude_code' };
276
+
277
+ sdkOptions.disallowedTools = settings.disallowedTools || [];
278
+
279
+ // Map model only when Pixcode explicitly passes one. If omitted, let
280
+ // Claude Code load the user's own project/user/local settings, including
281
+ // ~/.claude/settings.json "model".
282
+ if (typeof options.model === 'string' && options.model.trim()) {
283
+ sdkOptions.model = options.model.trim();
284
+ }
285
+ // Model logged at query start below
286
+
287
+ // Map system prompt configuration
288
+ sdkOptions.systemPrompt = {
289
+ type: 'preset',
290
+ preset: 'claude_code' // Required to use CLAUDE.md
291
+ };
292
+
293
+ // Map setting sources for CLAUDE.md loading
294
+ // This loads CLAUDE.md from project, user (~/.config/claude/CLAUDE.md), and local directories
295
+ sdkOptions.settingSources = ['project', 'user', 'local'];
296
+
297
+ // Map resume session
298
+ if (sessionId) {
299
+ sdkOptions.resume = sessionId;
300
+ }
301
+
302
+ return sdkOptions;
303
+ }
304
+
305
+ /**
306
+ * Adds a session to the active sessions map
307
+ * @param {string} sessionId - Session identifier
308
+ * @param {Object} queryInstance - SDK query instance
309
+ * @param {Array<string>} tempImagePaths - Temp image file paths for cleanup
310
+ * @param {string} tempDir - Temp directory for cleanup
311
+ */
312
+ function addSession(sessionId, queryInstance, tempImagePaths = [], tempDir = null, writer = null) {
313
+ activeSessions.set(sessionId, {
314
+ instance: queryInstance,
315
+ startTime: Date.now(),
316
+ status: 'active',
317
+ tempImagePaths,
318
+ tempDir,
319
+ writer
320
+ });
321
+ }
322
+
323
+ /**
324
+ * Removes a session from the active sessions map
325
+ * @param {string} sessionId - Session identifier
326
+ */
327
+ function removeSession(sessionId) {
328
+ activeSessions.delete(sessionId);
329
+ }
330
+
331
+ /**
332
+ * Gets a session from the active sessions map
333
+ * @param {string} sessionId - Session identifier
334
+ * @returns {Object|undefined} Session data or undefined
335
+ */
336
+ function getSession(sessionId) {
337
+ return activeSessions.get(sessionId);
338
+ }
339
+
340
+ /**
341
+ * Gets all active session IDs
342
+ * @returns {Array<string>} Array of active session IDs
343
+ */
344
+ function getAllSessions() {
345
+ return Array.from(activeSessions.keys());
346
+ }
347
+
348
+ /**
349
+ * Transforms SDK messages to WebSocket format expected by frontend
350
+ * @param {Object} sdkMessage - SDK message object
351
+ * @returns {Object} Transformed message ready for WebSocket
352
+ */
353
+ function transformMessage(sdkMessage) {
354
+ // Extract parent_tool_use_id for subagent tool grouping
355
+ if (sdkMessage.parent_tool_use_id) {
356
+ return {
357
+ ...sdkMessage,
358
+ parentToolUseId: sdkMessage.parent_tool_use_id
359
+ };
360
+ }
361
+ return sdkMessage;
362
+ }
363
+
364
+ /**
365
+ * Extracts token usage from SDK result messages
366
+ * @param {Object} resultMessage - SDK result message
367
+ * @returns {Object|null} Token budget object or null
368
+ */
369
+ function extractTokenBudget(resultMessage) {
370
+ if (resultMessage.type !== 'result' || !resultMessage.modelUsage) {
371
+ return null;
372
+ }
373
+
374
+ // Get the first model's usage data
375
+ const modelKey = Object.keys(resultMessage.modelUsage)[0];
376
+ const modelData = resultMessage.modelUsage[modelKey];
377
+
378
+ if (!modelData) {
379
+ return null;
380
+ }
381
+
382
+ // Use cumulative tokens if available (tracks total for the session)
383
+ // Otherwise fall back to per-request tokens
384
+ const inputTokens = modelData.cumulativeInputTokens || modelData.inputTokens || 0;
385
+ const outputTokens = modelData.cumulativeOutputTokens || modelData.outputTokens || 0;
386
+ const cacheReadTokens = modelData.cumulativeCacheReadInputTokens || modelData.cacheReadInputTokens || 0;
387
+ const cacheCreationTokens = modelData.cumulativeCacheCreationInputTokens || modelData.cacheCreationInputTokens || 0;
388
+
389
+ // Total used = input + output + cache tokens
390
+ const totalUsed = inputTokens + outputTokens + cacheReadTokens + cacheCreationTokens;
391
+
392
+ // Use configured context window budget from environment (default 160000)
393
+ // This is the user's budget limit, not the model's context window
394
+ const contextWindow = parseInt(process.env.CONTEXT_WINDOW) || 160000;
395
+
396
+ // Token calc logged via token-budget WS event
397
+
398
+ return {
399
+ used: totalUsed,
400
+ total: contextWindow
401
+ };
402
+ }
403
+
404
+ /**
405
+ * Handles image processing for SDK queries
406
+ * Saves base64 images to temporary files and returns modified prompt with file paths
407
+ * @param {string} command - Original user prompt
408
+ * @param {Array} images - Array of image objects with base64 data
409
+ * @param {string} cwd - Working directory for temp file creation
410
+ * @returns {Promise<Object>} {modifiedCommand, tempImagePaths, tempDir}
411
+ */
412
+ async function handleImages(command, images, cwd) {
413
+ const tempImagePaths = [];
414
+ let tempDir = null;
415
+
416
+ if (!images || images.length === 0) {
417
+ return { modifiedCommand: command, tempImagePaths, tempDir };
418
+ }
419
+
420
+ try {
421
+ // Create temp directory in the project directory
422
+ const workingDir = cwd || process.cwd();
423
+ tempDir = path.join(workingDir, '.tmp', 'images', Date.now().toString());
424
+ await fs.mkdir(tempDir, { recursive: true });
425
+
426
+ // Save each image to a temp file
427
+ for (const [index, image] of images.entries()) {
428
+ // Extract base64 data and mime type
429
+ const matches = image.data.match(/^data:([^;]+);base64,(.+)$/);
430
+ if (!matches) {
431
+ console.error('Invalid image data format');
432
+ continue;
433
+ }
434
+
435
+ const [, mimeType, base64Data] = matches;
436
+ const extension = mimeType.split('/')[1] || 'png';
437
+ const filename = `image_${index}.${extension}`;
438
+ const filepath = path.join(tempDir, filename);
439
+
440
+ // Write base64 data to file
441
+ await fs.writeFile(filepath, Buffer.from(base64Data, 'base64'));
442
+ tempImagePaths.push(filepath);
443
+ }
444
+
445
+ // Include the full image paths in the prompt
446
+ let modifiedCommand = command;
447
+ if (tempImagePaths.length > 0 && command && command.trim()) {
448
+ const imageNote = `\n\n[Images provided at the following paths:]\n${tempImagePaths.map((p, i) => `${i + 1}. ${p}`).join('\n')}`;
449
+ modifiedCommand = command + imageNote;
450
+ }
451
+
452
+ // Images processed
453
+ return { modifiedCommand, tempImagePaths, tempDir };
454
+ } catch (error) {
455
+ console.error('Error processing images for SDK:', error);
456
+ return { modifiedCommand: command, tempImagePaths, tempDir };
457
+ }
458
+ }
459
+
460
+ /**
461
+ * Cleans up temporary image files
462
+ * @param {Array<string>} tempImagePaths - Array of temp file paths to delete
463
+ * @param {string} tempDir - Temp directory to remove
464
+ */
465
+ async function cleanupTempFiles(tempImagePaths, tempDir) {
466
+ if (!tempImagePaths || tempImagePaths.length === 0) {
467
+ return;
468
+ }
469
+
470
+ try {
471
+ // Delete individual temp files
472
+ for (const imagePath of tempImagePaths) {
473
+ await fs.unlink(imagePath).catch(err =>
474
+ console.error(`Failed to delete temp image ${imagePath}:`, err)
475
+ );
476
+ }
477
+
478
+ // Delete temp directory
479
+ if (tempDir) {
480
+ await fs.rm(tempDir, { recursive: true, force: true }).catch(err =>
481
+ console.error(`Failed to delete temp directory ${tempDir}:`, err)
482
+ );
483
+ }
484
+
485
+ // Temp files cleaned
486
+ } catch (error) {
487
+ console.error('Error during temp file cleanup:', error);
488
+ }
489
+ }
490
+
491
+ /**
492
+ * Loads MCP server configurations from ~/.claude.json
493
+ * @param {string} cwd - Current working directory for project-specific configs
494
+ * @returns {Object|null} MCP servers object or null if none found
495
+ */
496
+ async function loadMcpConfig(cwd) {
497
+ try {
498
+ const claudeConfigPath = path.join(os.homedir(), '.claude.json');
499
+
500
+ // Check if config file exists
501
+ try {
502
+ await fs.access(claudeConfigPath);
503
+ } catch (error) {
504
+ // File doesn't exist, return null
505
+ // No config file
506
+ return null;
507
+ }
508
+
509
+ // Read and parse config file
510
+ let claudeConfig;
511
+ try {
512
+ const configContent = await fs.readFile(claudeConfigPath, 'utf8');
513
+ claudeConfig = JSON.parse(configContent);
514
+ } catch (error) {
515
+ console.error('Failed to parse ~/.claude.json:', error.message);
516
+ return null;
517
+ }
518
+
519
+ // Extract MCP servers (merge global and project-specific)
520
+ let mcpServers = {};
521
+
522
+ // Add global MCP servers
523
+ if (claudeConfig.mcpServers && typeof claudeConfig.mcpServers === 'object') {
524
+ mcpServers = { ...claudeConfig.mcpServers };
525
+ // Global MCP servers loaded
526
+ }
527
+
528
+ // Add/override with project-specific MCP servers
529
+ if (claudeConfig.claudeProjects && cwd) {
530
+ const projectConfig = claudeConfig.claudeProjects[cwd];
531
+ if (projectConfig && projectConfig.mcpServers && typeof projectConfig.mcpServers === 'object') {
532
+ mcpServers = { ...mcpServers, ...projectConfig.mcpServers };
533
+ // Project MCP servers merged
534
+ }
535
+ }
536
+
537
+ // Return null if no servers found
538
+ if (Object.keys(mcpServers).length === 0) {
539
+ return null;
540
+ }
541
+ return mcpServers;
542
+ } catch (error) {
543
+ console.error('Error loading MCP config:', error.message);
544
+ return null;
545
+ }
546
+ }
547
+
548
+ /**
549
+ * Executes a Claude query using the SDK
550
+ * @param {string} command - User prompt/command
551
+ * @param {Object} options - Query options
552
+ * @param {Object} ws - WebSocket connection
553
+ * @returns {Promise<void>}
554
+ */
555
+ async function queryClaudeSDK(command, options = {}, ws) {
556
+ const { sessionId, sessionSummary, suppressNotifications = false } = options;
557
+ let capturedSessionId = sessionId;
558
+ let sessionCreatedSent = false;
559
+ let tempImagePaths = [];
560
+ let tempDir = null;
561
+
562
+ const emitNotification = (event) => {
563
+ notifyUserIfEnabled({
564
+ userId: ws?.userId || null,
565
+ writer: ws,
566
+ event
567
+ });
568
+ };
569
+
570
+ try {
571
+ // Map CLI options to SDK format
572
+ const sdkOptions = mapCliOptionsToSDK(options);
573
+
574
+ // Load MCP configuration
575
+ const mcpServers = await loadMcpConfig(options.cwd);
576
+ if (mcpServers) {
577
+ sdkOptions.mcpServers = mcpServers;
578
+ }
579
+
580
+ // Handle images - save to temp files and modify prompt
581
+ const imageResult = await handleImages(command, options.images, options.cwd);
582
+ const finalCommand = imageResult.modifiedCommand;
583
+ tempImagePaths = imageResult.tempImagePaths;
584
+ tempDir = imageResult.tempDir;
585
+
586
+ sdkOptions.hooks = {
587
+ Notification: [{
588
+ matcher: '',
589
+ hooks: [async (input) => {
590
+ const message = typeof input?.message === 'string' ? input.message : 'Claude requires your attention.';
591
+ emitNotification(createNotificationEvent({
592
+ provider: 'claude',
593
+ sessionId: capturedSessionId || sessionId || null,
594
+ kind: 'action_required',
595
+ code: 'agent.notification',
596
+ meta: { message, sessionName: sessionSummary },
597
+ severity: 'warning',
598
+ requiresUserAction: true,
599
+ dedupeKey: `claude:hook:notification:${capturedSessionId || sessionId || 'none'}:${message}`
600
+ }));
601
+ return {};
602
+ }]
603
+ }]
604
+ };
605
+
606
+ sdkOptions.canUseTool = async (toolName, input, context) => {
607
+ const requiresInteraction = TOOLS_REQUIRING_INTERACTION.has(toolName);
608
+ const policyDecision = evaluatePermissionRequest({
609
+ policy: sdkOptions.permissionPolicy,
610
+ request: {
611
+ source: 'provider_tool',
612
+ toolName,
613
+ input,
614
+ command: input && typeof input === 'object' && typeof input.command === 'string'
615
+ ? input.command
616
+ : undefined,
617
+ cwd: options.cwd,
618
+ workspacePath: options.cwd,
619
+ summary: `${toolName} tool request`,
620
+ },
621
+ context: sdkOptions.permissionPolicyContext,
622
+ });
623
+
624
+ if (policyDecision.behavior === 'deny') {
625
+ return { behavior: 'deny', message: policyDecision.message };
626
+ }
627
+
628
+ if (!requiresInteraction && policyDecision.behavior !== 'prompt') {
629
+ if (sdkOptions.permissionMode === 'bypassPermissions') {
630
+ return { behavior: 'allow', updatedInput: input };
631
+ }
632
+
633
+ const isDisallowed = (sdkOptions.disallowedTools || []).some(entry =>
634
+ matchesToolPermission(entry, toolName, input)
635
+ );
636
+ if (isDisallowed) {
637
+ return { behavior: 'deny', message: 'Tool disallowed by settings' };
638
+ }
639
+
640
+ const isAllowed = (sdkOptions.allowedTools || []).some(entry =>
641
+ matchesToolPermission(entry, toolName, input)
642
+ );
643
+ if (isAllowed) {
644
+ return { behavior: 'allow', updatedInput: input };
645
+ }
646
+ }
647
+
648
+ const requestId = createRequestId();
649
+ ws.send(createNormalizedMessage({ kind: 'permission_request', requestId, toolName, input, sessionId: capturedSessionId || sessionId || null, provider: 'claude' }));
650
+ emitNotification(createNotificationEvent({
651
+ provider: 'claude',
652
+ sessionId: capturedSessionId || sessionId || null,
653
+ kind: 'action_required',
654
+ code: 'permission.required',
655
+ meta: { toolName, sessionName: sessionSummary },
656
+ severity: 'warning',
657
+ requiresUserAction: true,
658
+ dedupeKey: `claude:permission:${capturedSessionId || sessionId || 'none'}:${requestId}`
659
+ }));
660
+
661
+ const decision = await waitForToolApproval(requestId, {
662
+ timeoutMs: requiresInteraction ? 0 : undefined,
663
+ signal: context?.signal,
664
+ metadata: {
665
+ _sessionId: capturedSessionId || sessionId || null,
666
+ _toolName: toolName,
667
+ _input: input,
668
+ _receivedAt: new Date(),
669
+ },
670
+ onCancel: (reason) => {
671
+ ws.send(createNormalizedMessage({ kind: 'permission_cancelled', requestId, reason, sessionId: capturedSessionId || sessionId || null, provider: 'claude' }));
672
+ }
673
+ });
674
+ if (!decision) {
675
+ return { behavior: 'deny', message: 'Permission request timed out' };
676
+ }
677
+
678
+ if (decision.cancelled) {
679
+ return { behavior: 'deny', message: 'Permission request cancelled' };
680
+ }
681
+
682
+ if (decision.allow) {
683
+ if (decision.rememberEntry && typeof decision.rememberEntry === 'string') {
684
+ if (!sdkOptions.allowedTools.includes(decision.rememberEntry)) {
685
+ sdkOptions.allowedTools.push(decision.rememberEntry);
686
+ }
687
+ if (Array.isArray(sdkOptions.disallowedTools)) {
688
+ sdkOptions.disallowedTools = sdkOptions.disallowedTools.filter(entry => entry !== decision.rememberEntry);
689
+ }
690
+ }
691
+ return { behavior: 'allow', updatedInput: decision.updatedInput ?? input };
692
+ }
693
+
694
+ return { behavior: 'deny', message: decision.message ?? 'User denied tool use' };
695
+ };
696
+
697
+ // Set stream-close timeout for interactive tools (Query constructor reads it synchronously). Claude Agent SDK has a default of 5s and this overrides it
698
+ const prevStreamTimeout = process.env.CLAUDE_CODE_STREAM_CLOSE_TIMEOUT;
699
+ process.env.CLAUDE_CODE_STREAM_CLOSE_TIMEOUT = '300000';
700
+
701
+ let queryInstance;
702
+ try {
703
+ queryInstance = query({
704
+ prompt: finalCommand,
705
+ options: sdkOptions
706
+ });
707
+ } catch (hookError) {
708
+ // Older/newer SDK versions may not accept hook shapes yet.
709
+ // Keep notification behavior operational via runtime events even if hook registration fails.
710
+ console.warn('Failed to initialize Claude query with hooks, retrying without hooks:', hookError?.message || hookError);
711
+ delete sdkOptions.hooks;
712
+ queryInstance = query({
713
+ prompt: finalCommand,
714
+ options: sdkOptions
715
+ });
716
+ }
717
+
718
+ // Restore immediately — Query constructor already captured the value
719
+ if (prevStreamTimeout !== undefined) {
720
+ process.env.CLAUDE_CODE_STREAM_CLOSE_TIMEOUT = prevStreamTimeout;
721
+ } else {
722
+ delete process.env.CLAUDE_CODE_STREAM_CLOSE_TIMEOUT;
723
+ }
724
+
725
+ // Track the query instance for abort capability
726
+ if (capturedSessionId) {
727
+ addSession(capturedSessionId, queryInstance, tempImagePaths, tempDir, ws);
728
+ }
729
+
730
+ // Process streaming messages
731
+ console.log('Starting async generator loop for session:', capturedSessionId || 'NEW');
732
+ for await (const message of queryInstance) {
733
+ // Capture session ID from first message
734
+ if (message.session_id && !capturedSessionId) {
735
+
736
+ capturedSessionId = message.session_id;
737
+ addSession(capturedSessionId, queryInstance, tempImagePaths, tempDir, ws);
738
+
739
+ // Set session ID on writer
740
+ if (ws.setSessionId && typeof ws.setSessionId === 'function') {
741
+ ws.setSessionId(capturedSessionId);
742
+ }
743
+
744
+ // Send session-created event only once for new sessions
745
+ if (!sessionId && !sessionCreatedSent) {
746
+ sessionCreatedSent = true;
747
+ ws.send(createNormalizedMessage({ kind: 'session_created', newSessionId: capturedSessionId, sessionId: capturedSessionId, provider: 'claude' }));
748
+ }
749
+ } else {
750
+ // session_id already captured
751
+ }
752
+
753
+ // Transform and normalize message via adapter
754
+ const transformedMessage = transformMessage(message);
755
+ const sid = capturedSessionId || sessionId || null;
756
+
757
+ // Use adapter to normalize SDK events into NormalizedMessage[]
758
+ const normalized = sessionsService.normalizeMessage('claude', transformedMessage, sid);
759
+ for (const msg of normalized) {
760
+ // Preserve parentToolUseId from SDK wrapper for subagent tool grouping
761
+ if (transformedMessage.parentToolUseId && !msg.parentToolUseId) {
762
+ msg.parentToolUseId = transformedMessage.parentToolUseId;
763
+ }
764
+ ws.send(msg);
765
+ }
766
+
767
+ // Extract and send token budget updates from result messages
768
+ if (message.type === 'result') {
769
+ const models = Object.keys(message.modelUsage || {});
770
+ if (models.length > 0) {
771
+ // Model info available in result message
772
+ }
773
+ const tokenBudgetData = extractTokenBudget(message);
774
+ if (tokenBudgetData) {
775
+ ws.send(createNormalizedMessage({ kind: 'status', text: 'token_budget', tokenBudget: tokenBudgetData, sessionId: capturedSessionId || sessionId || null, provider: 'claude' }));
776
+ }
777
+ }
778
+ }
779
+
780
+ // Clean up session on completion
781
+ if (capturedSessionId) {
782
+ removeSession(capturedSessionId);
783
+ }
784
+
785
+ // Clean up temporary image files
786
+ await cleanupTempFiles(tempImagePaths, tempDir);
787
+
788
+ // Send completion event
789
+ ws.send(createNormalizedMessage({ kind: 'complete', exitCode: 0, isNewSession: !sessionId && !!command, sessionId: capturedSessionId, provider: 'claude' }));
790
+ if (!suppressNotifications) notifyRunStopped({
791
+ userId: ws?.userId || null,
792
+ provider: 'claude',
793
+ sessionId: capturedSessionId || sessionId || null,
794
+ sessionName: sessionSummary,
795
+ stopReason: 'completed'
796
+ });
797
+ // Complete
798
+
799
+ } catch (error) {
800
+ console.error('SDK query error:', error);
801
+
802
+ // Clean up session on error
803
+ if (capturedSessionId) {
804
+ removeSession(capturedSessionId);
805
+ }
806
+
807
+ // Clean up temporary image files on error
808
+ await cleanupTempFiles(tempImagePaths, tempDir);
809
+
810
+ // Check if Claude CLI is installed for a clearer error message
811
+ const installed = await providerAuthService.isProviderInstalled('claude');
812
+ const errorContent = !installed
813
+ ? 'Claude Code is not installed. Please install it first: https://docs.anthropic.com/en/docs/claude-code'
814
+ : error.message;
815
+
816
+ // Send error to WebSocket
817
+ ws.send(createNormalizedMessage({ kind: 'error', content: errorContent, sessionId: capturedSessionId || sessionId || null, provider: 'claude' }));
818
+ if (!suppressNotifications) notifyRunFailed({
819
+ userId: ws?.userId || null,
820
+ provider: 'claude',
821
+ sessionId: capturedSessionId || sessionId || null,
822
+ sessionName: sessionSummary,
823
+ error
824
+ });
825
+ }
826
+ }
827
+
828
+ /**
829
+ * Aborts an active SDK session
830
+ * @param {string} sessionId - Session identifier
831
+ * @returns {boolean} True if session was aborted, false if not found
832
+ */
833
+ async function abortClaudeSDKSession(sessionId) {
834
+ const session = getSession(sessionId);
835
+
836
+ if (!session) {
837
+ console.log(`Session ${sessionId} not found`);
838
+ return false;
839
+ }
840
+
841
+ try {
842
+ console.log(`Aborting SDK session: ${sessionId}`);
843
+
844
+ // Call interrupt() on the query instance
845
+ await session.instance.interrupt();
846
+
847
+ // Update session status
848
+ session.status = 'aborted';
849
+
850
+ // Clean up temporary image files
851
+ await cleanupTempFiles(session.tempImagePaths, session.tempDir);
852
+
853
+ // Clean up session
854
+ removeSession(sessionId);
855
+
856
+ return true;
857
+ } catch (error) {
858
+ console.error(`Error aborting session ${sessionId}:`, error);
859
+ return false;
860
+ }
861
+ }
862
+
863
+ /**
864
+ * Checks if an SDK session is currently active
865
+ * @param {string} sessionId - Session identifier
866
+ * @returns {boolean} True if session is active
867
+ */
868
+ function isClaudeSDKSessionActive(sessionId) {
869
+ const session = getSession(sessionId);
870
+ return session && session.status === 'active';
871
+ }
872
+
873
+ /**
874
+ * Gets all active SDK session IDs
875
+ * @returns {Array<string>} Array of active session IDs
876
+ */
877
+ function getActiveClaudeSDKSessions() {
878
+ return getAllSessions();
879
+ }
880
+
881
+ /**
882
+ * Get pending tool approvals for a specific session.
883
+ * @param {string} sessionId - The session ID
884
+ * @returns {Array} Array of pending permission request objects
885
+ */
886
+ function getPendingApprovalsForSession(sessionId) {
887
+ const pending = [];
888
+ for (const [requestId, resolver] of pendingToolApprovals.entries()) {
889
+ if (resolver._sessionId === sessionId) {
890
+ pending.push({
891
+ requestId,
892
+ toolName: resolver._toolName || 'UnknownTool',
893
+ input: resolver._input,
894
+ context: resolver._context,
895
+ sessionId,
896
+ receivedAt: resolver._receivedAt || new Date(),
897
+ });
898
+ }
899
+ }
900
+ return pending;
901
+ }
902
+
903
+ /**
904
+ * Reconnect a session's WebSocketWriter to a new raw WebSocket.
905
+ * Called when client reconnects (e.g. page refresh) while SDK is still running.
906
+ * @param {string} sessionId - The session ID
907
+ * @param {Object} newRawWs - The new raw WebSocket connection
908
+ * @returns {boolean} True if writer was successfully reconnected
909
+ */
910
+ function reconnectSessionWriter(sessionId, newRawWs) {
911
+ const session = getSession(sessionId);
912
+ if (!session?.writer?.updateWebSocket) return false;
913
+ session.writer.updateWebSocket(newRawWs);
914
+ console.log(`[RECONNECT] Writer swapped for session ${sessionId}`);
915
+ return true;
916
+ }
917
+
918
+ // Export public API
919
+ export {
920
+ queryClaudeSDK,
921
+ abortClaudeSDKSession,
922
+ isClaudeSDKSessionActive,
923
+ getActiveClaudeSDKSessions,
924
+ resolveToolApproval,
925
+ getPendingApprovalsForSession,
926
+ reconnectSessionWriter
927
+ };