@pixelbyte-software/pixcode 1.35.0 → 1.35.1

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 (150) hide show
  1. package/LICENSE +718 -718
  2. package/README.de.md +248 -248
  3. package/README.ja.md +240 -240
  4. package/README.ko.md +240 -240
  5. package/README.md +303 -303
  6. package/README.ru.md +248 -248
  7. package/README.tr.md +250 -250
  8. package/README.zh-CN.md +240 -240
  9. package/dist/api-docs.html +548 -548
  10. package/dist/assets/{index-Djuh0wHV.js → index-CBdsvGSR.js} +133 -133
  11. package/dist/clear-cache.html +85 -85
  12. package/dist/convert-icons.md +52 -52
  13. package/dist/generate-icons.js +48 -48
  14. package/dist/icons/codex-white.svg +3 -3
  15. package/dist/icons/codex.svg +3 -3
  16. package/dist/icons/cursor-white.svg +11 -11
  17. package/dist/icons/qwen-logo.svg +14 -14
  18. package/dist/index.html +58 -58
  19. package/dist/manifest.json +60 -60
  20. package/dist/openapi.yaml +1693 -1693
  21. package/dist/sw.js +124 -124
  22. package/dist-server/server/cli.js +96 -96
  23. package/dist-server/server/daemon/manager.js +33 -33
  24. package/dist-server/server/daemon-manager.js +64 -64
  25. package/dist-server/server/modules/orchestration/preview/preview-proxy.js +3 -3
  26. package/dist-server/server/modules/orchestration/preview/preview-proxy.js.map +1 -1
  27. package/dist-server/server/routes/commands.js +25 -25
  28. package/dist-server/server/routes/git.js +17 -17
  29. package/dist-server/server/routes/taskmaster.js +419 -419
  30. package/package.json +180 -180
  31. package/scripts/fix-node-pty.js +67 -67
  32. package/scripts/smoke/a2a-roundtrip.mjs +167 -167
  33. package/scripts/smoke/orchestration-api.mjs +172 -172
  34. package/scripts/smoke/orchestration-live-run.mjs +176 -176
  35. package/server/claude-sdk.js +898 -898
  36. package/server/cli.js +935 -935
  37. package/server/constants/config.js +4 -4
  38. package/server/cursor-cli.js +342 -342
  39. package/server/daemon/manager.js +564 -564
  40. package/server/daemon-manager.js +959 -959
  41. package/server/database/json-store.js +197 -197
  42. package/server/gemini-cli.js +535 -535
  43. package/server/gemini-response-handler.js +79 -79
  44. package/server/index.js +3135 -3135
  45. package/server/load-env.js +34 -34
  46. package/server/middleware/auth.js +173 -173
  47. package/server/modules/orchestration/a2a/adapter-registry.ts +108 -108
  48. package/server/modules/orchestration/a2a/adapters/abstract-a2a.adapter.ts +55 -55
  49. package/server/modules/orchestration/a2a/adapters/claude-code.adapter.ts +284 -284
  50. package/server/modules/orchestration/a2a/adapters/codex.adapter.ts +244 -244
  51. package/server/modules/orchestration/a2a/adapters/cursor.adapter.ts +249 -249
  52. package/server/modules/orchestration/a2a/adapters/gemini.adapter.ts +248 -248
  53. package/server/modules/orchestration/a2a/adapters/opencode.adapter.ts +248 -248
  54. package/server/modules/orchestration/a2a/adapters/qwen.adapter.ts +248 -248
  55. package/server/modules/orchestration/a2a/agent-card.ts +55 -55
  56. package/server/modules/orchestration/a2a/auth.middleware.ts +29 -29
  57. package/server/modules/orchestration/a2a/bus.ts +46 -46
  58. package/server/modules/orchestration/a2a/routes.ts +577 -577
  59. package/server/modules/orchestration/a2a/task-store.ts +178 -178
  60. package/server/modules/orchestration/a2a/types.ts +125 -125
  61. package/server/modules/orchestration/a2a/validator.ts +113 -113
  62. package/server/modules/orchestration/index.ts +66 -66
  63. package/server/modules/orchestration/preview/port-watcher.ts +112 -112
  64. package/server/modules/orchestration/preview/preview-proxy.ts +60 -60
  65. package/server/modules/orchestration/preview/types.ts +19 -19
  66. package/server/modules/orchestration/tasks/orchestration-task-store.ts +45 -45
  67. package/server/modules/orchestration/tasks/orchestration-task.routes.ts +73 -73
  68. package/server/modules/orchestration/tasks/orchestration-task.service.ts +145 -145
  69. package/server/modules/orchestration/tasks/orchestration-task.types.ts +29 -29
  70. package/server/modules/orchestration/workflows/built-in-workflows.ts +127 -127
  71. package/server/modules/orchestration/workflows/workflow-runner.ts +1206 -1206
  72. package/server/modules/orchestration/workflows/workflow-store.ts +97 -97
  73. package/server/modules/orchestration/workflows/workflow.routes.ts +169 -169
  74. package/server/modules/orchestration/workflows/workflow.types.ts +70 -70
  75. package/server/modules/orchestration/workflows/workspace-target.ts +120 -120
  76. package/server/modules/orchestration/workspace/docker-workspace.ts +135 -135
  77. package/server/modules/orchestration/workspace/path-safety.ts +55 -55
  78. package/server/modules/orchestration/workspace/types.ts +52 -52
  79. package/server/modules/orchestration/workspace/workspace-manager.ts +97 -97
  80. package/server/modules/orchestration/workspace/worktree-workspace.ts +125 -125
  81. package/server/modules/providers/index.ts +2 -2
  82. package/server/modules/providers/list/claude/claude-auth.provider.ts +145 -145
  83. package/server/modules/providers/list/claude/claude-mcp.provider.ts +135 -135
  84. package/server/modules/providers/list/claude/claude-sessions.provider.ts +306 -306
  85. package/server/modules/providers/list/claude/claude.provider.ts +15 -15
  86. package/server/modules/providers/list/codex/codex-auth.provider.ts +115 -115
  87. package/server/modules/providers/list/codex/codex-mcp.provider.ts +135 -135
  88. package/server/modules/providers/list/codex/codex-sessions.provider.ts +319 -319
  89. package/server/modules/providers/list/codex/codex.provider.ts +15 -15
  90. package/server/modules/providers/list/cursor/cursor-auth.provider.ts +143 -143
  91. package/server/modules/providers/list/cursor/cursor-mcp.provider.ts +108 -108
  92. package/server/modules/providers/list/cursor/cursor-sessions.provider.ts +421 -421
  93. package/server/modules/providers/list/cursor/cursor.provider.ts +15 -15
  94. package/server/modules/providers/list/gemini/gemini-auth.provider.ts +163 -163
  95. package/server/modules/providers/list/gemini/gemini-mcp.provider.ts +110 -110
  96. package/server/modules/providers/list/gemini/gemini-sessions.provider.ts +227 -227
  97. package/server/modules/providers/list/gemini/gemini.provider.ts +15 -15
  98. package/server/modules/providers/list/opencode/opencode-sessions.provider.ts +232 -232
  99. package/server/modules/providers/list/qwen/qwen-sessions.provider.ts +265 -265
  100. package/server/modules/providers/provider.registry.ts +40 -40
  101. package/server/modules/providers/provider.routes.ts +819 -819
  102. package/server/modules/providers/services/mcp.service.ts +86 -86
  103. package/server/modules/providers/services/provider-auth.service.ts +26 -26
  104. package/server/modules/providers/services/sessions.service.ts +45 -45
  105. package/server/modules/providers/shared/base/abstract.provider.ts +20 -20
  106. package/server/modules/providers/shared/mcp/mcp.provider.ts +151 -151
  107. package/server/modules/providers/tests/mcp.test.ts +293 -293
  108. package/server/openai-codex.js +462 -462
  109. package/server/opencode-cli.js +459 -459
  110. package/server/opencode-response-handler.js +107 -107
  111. package/server/projects.js +3105 -3105
  112. package/server/routes/agent.js +1365 -1365
  113. package/server/routes/auth.js +138 -138
  114. package/server/routes/codex.js +19 -19
  115. package/server/routes/commands.js +554 -554
  116. package/server/routes/cursor.js +52 -52
  117. package/server/routes/gemini.js +24 -24
  118. package/server/routes/git.js +1488 -1488
  119. package/server/routes/mcp-utils.js +31 -31
  120. package/server/routes/messages.js +61 -61
  121. package/server/routes/network.js +120 -120
  122. package/server/routes/plugins.js +318 -318
  123. package/server/routes/projects.js +915 -915
  124. package/server/routes/settings.js +286 -286
  125. package/server/routes/taskmaster.js +1496 -1496
  126. package/server/routes/telegram.js +125 -125
  127. package/server/routes/user.js +123 -123
  128. package/server/services/install-jobs.js +571 -571
  129. package/server/services/notification-orchestrator.js +242 -242
  130. package/server/services/provider-credentials.js +189 -189
  131. package/server/services/telegram/bot.js +279 -279
  132. package/server/services/telegram/translations.js +170 -170
  133. package/server/sessionManager.js +225 -225
  134. package/server/shared/interfaces.ts +54 -54
  135. package/server/shared/types.ts +172 -172
  136. package/server/shared/utils.ts +193 -193
  137. package/server/tsconfig.json +36 -36
  138. package/server/utils/colors.js +21 -21
  139. package/server/utils/commandParser.js +303 -303
  140. package/server/utils/frontmatter.js +18 -18
  141. package/server/utils/gitConfig.js +34 -34
  142. package/server/utils/mcp-detector.js +147 -147
  143. package/server/utils/plugin-loader.js +457 -457
  144. package/server/utils/plugin-process-manager.js +184 -184
  145. package/server/utils/runtime-paths.js +37 -37
  146. package/server/utils/taskmaster-websocket.js +128 -128
  147. package/server/utils/url-detection.js +71 -71
  148. package/server/vite-daemon.js +78 -78
  149. package/shared/modelConstants.js +162 -162
  150. package/shared/networkHosts.js +22 -22
@@ -1,535 +1,535 @@
1
- import { spawn } from 'child_process';
2
- import crossSpawn from 'cross-spawn';
3
-
4
- // Use cross-spawn on Windows for correct .cmd resolution (same pattern as cursor-cli.js)
5
- const spawnFunction = process.platform === 'win32' ? crossSpawn : spawn;
6
- import { promises as fs } from 'fs';
7
- import path from 'path';
8
- import os from 'os';
9
- import sessionManager from './sessionManager.js';
10
- import GeminiResponseHandler from './gemini-response-handler.js';
11
- import { notifyRunFailed, notifyRunStopped } from './services/notification-orchestrator.js';
12
- import { buildSpawnEnv } from './services/provider-credentials.js';
13
- import { providerAuthService } from './modules/providers/services/provider-auth.service.js';
14
- import { createNormalizedMessage } from './shared/utils.js';
15
-
16
- let activeGeminiProcesses = new Map(); // Track active processes by session ID
17
-
18
- /**
19
- * Auto-create `~/.gemini/settings.json` when the user has signed in via OAuth
20
- * (so `oauth_creds.json` exists) but never opened the Gemini TUI to write the
21
- * `selectedAuthType` field. Without this, `gemini --prompt … --output-format
22
- * stream-json --yolo` exits 41 with "Please set an Auth method in your
23
- * settings.json" — even though credentials are perfectly valid. We respect a
24
- * pre-existing `settings.json` and never overwrite a chosen auth type.
25
- *
26
- * Triggered every spawn (cheap: one fs.access + maybe one tiny write).
27
- */
28
- async function ensureGeminiSettingsJson() {
29
- const home = os.homedir();
30
- const dir = path.join(home, '.gemini');
31
- const settingsPath = path.join(dir, 'settings.json');
32
- const oauthPath = path.join(dir, 'oauth_creds.json');
33
- const apiKey = process.env.GEMINI_API_KEY;
34
-
35
- try {
36
- await fs.access(settingsPath);
37
- return; // user-managed, leave it.
38
- } catch { /* missing — we may create it */ }
39
-
40
- let selectedAuthType = null;
41
- if (apiKey && apiKey.trim()) {
42
- selectedAuthType = 'gemini-api-key';
43
- } else {
44
- try {
45
- await fs.access(oauthPath);
46
- selectedAuthType = 'oauth-personal';
47
- } catch { /* no oauth either */ }
48
- }
49
- if (!selectedAuthType) return;
50
-
51
- try {
52
- await fs.mkdir(dir, { recursive: true });
53
- await fs.writeFile(settingsPath, JSON.stringify({ selectedAuthType }, null, 2), { mode: 0o600 });
54
- console.log(`[gemini] auto-bootstrapped ~/.gemini/settings.json with selectedAuthType="${selectedAuthType}"`);
55
- } catch (error) {
56
- console.warn('[gemini] failed to bootstrap settings.json:', error?.message || error);
57
- }
58
- }
59
-
60
- async function spawnGemini(command, options = {}, ws) {
61
- const { sessionId, projectPath, cwd, toolsSettings, permissionMode, images, sessionSummary } = options;
62
- let capturedSessionId = sessionId; // Track session ID throughout the process
63
- let sessionCreatedSent = false; // Track if we've already sent session-created event
64
- let assistantBlocks = []; // Accumulate the full response blocks including tools
65
-
66
- // Use tools settings passed from frontend, or defaults
67
- const settings = toolsSettings || {
68
- allowedTools: [],
69
- disallowedTools: [],
70
- skipPermissions: false
71
- };
72
-
73
- // Build Gemini CLI command - start with print/resume flags first
74
- const args = [];
75
-
76
- // Add prompt flag with command if we have a command
77
- if (command && command.trim()) {
78
- args.push('--prompt', command);
79
- }
80
-
81
- // If we have a sessionId, we want to resume
82
- if (sessionId) {
83
- const session = sessionManager.getSession(sessionId);
84
- if (session && session.cliSessionId) {
85
- args.push('--resume', session.cliSessionId);
86
- }
87
- }
88
-
89
- // Use cwd (actual project directory) instead of projectPath (Gemini's metadata directory)
90
- // Clean the path by removing any non-printable characters
91
- const cleanPath = (cwd || projectPath || process.cwd()).replace(/[^\x20-\x7E]/g, '').trim();
92
- const workingDir = cleanPath;
93
-
94
- // Handle images by saving them to temporary files and passing paths to Gemini
95
- const tempImagePaths = [];
96
- let tempDir = null;
97
- if (images && images.length > 0) {
98
- try {
99
- // Create temp directory in the project directory so Gemini can access it
100
- tempDir = path.join(workingDir, '.tmp', 'images', Date.now().toString());
101
- await fs.mkdir(tempDir, { recursive: true });
102
-
103
- // Save each image to a temp file
104
- for (const [index, image] of images.entries()) {
105
- // Extract base64 data and mime type
106
- const matches = image.data.match(/^data:([^;]+);base64,(.+)$/);
107
- if (!matches) {
108
- continue;
109
- }
110
-
111
- const [, mimeType, base64Data] = matches;
112
- const extension = mimeType.split('/')[1] || 'png';
113
- const filename = `image_${index}.${extension}`;
114
- const filepath = path.join(tempDir, filename);
115
-
116
- // Write base64 data to file
117
- await fs.writeFile(filepath, Buffer.from(base64Data, 'base64'));
118
- tempImagePaths.push(filepath);
119
- }
120
-
121
- // Include the full image paths in the prompt for Gemini to reference
122
- // Gemini CLI can read images from file paths in the prompt
123
- if (tempImagePaths.length > 0 && command && command.trim()) {
124
- const imageNote = `\n\n[Images given: ${tempImagePaths.length} images are located at the following paths:]\n${tempImagePaths.map((p, i) => `${i + 1}. ${p}`).join('\n')}`;
125
- const modifiedCommand = command + imageNote;
126
-
127
- // Update the command in args
128
- const promptIndex = args.indexOf('--prompt');
129
- if (promptIndex !== -1 && args[promptIndex + 1] === command) {
130
- args[promptIndex + 1] = modifiedCommand;
131
- } else if (promptIndex !== -1) {
132
- // If we're using context, update the full prompt
133
- args[promptIndex + 1] = args[promptIndex + 1] + imageNote;
134
- }
135
- }
136
- } catch (error) {
137
- console.error('Error processing images for Gemini:', error);
138
- }
139
- }
140
-
141
- // Add basic flags for Gemini
142
- if (options.debug) {
143
- args.push('--debug');
144
- }
145
-
146
- // Add MCP config flag only if MCP servers are configured
147
- try {
148
- const geminiConfigPath = path.join(os.homedir(), '.gemini.json');
149
- let hasMcpServers = false;
150
-
151
- try {
152
- await fs.access(geminiConfigPath);
153
- const geminiConfigRaw = await fs.readFile(geminiConfigPath, 'utf8');
154
- const geminiConfig = JSON.parse(geminiConfigRaw);
155
-
156
- // Check global MCP servers
157
- if (geminiConfig.mcpServers && Object.keys(geminiConfig.mcpServers).length > 0) {
158
- hasMcpServers = true;
159
- }
160
-
161
- // Check project-specific MCP servers
162
- if (!hasMcpServers && geminiConfig.geminiProjects) {
163
- const currentProjectPath = process.cwd();
164
- const projectConfig = geminiConfig.geminiProjects[currentProjectPath];
165
- if (projectConfig && projectConfig.mcpServers && Object.keys(projectConfig.mcpServers).length > 0) {
166
- hasMcpServers = true;
167
- }
168
- }
169
- } catch (e) {
170
- // Ignore if file doesn't exist or isn't parsable
171
- }
172
-
173
- if (hasMcpServers) {
174
- args.push('--mcp-config', geminiConfigPath);
175
- }
176
- } catch (error) {
177
- // Ignore outer errors
178
- }
179
-
180
- // Add model for all sessions (both new and resumed)
181
- let modelToUse = options.model || 'gemini-2.5-flash';
182
- args.push('--model', modelToUse);
183
- args.push('--output-format', 'stream-json');
184
-
185
- // Handle approval modes and allowed tools
186
- if (settings.skipPermissions || options.skipPermissions || permissionMode === 'yolo') {
187
- args.push('--yolo');
188
- } else if (permissionMode === 'auto_edit') {
189
- args.push('--approval-mode', 'auto_edit');
190
- } else if (permissionMode === 'plan') {
191
- args.push('--approval-mode', 'plan');
192
- }
193
-
194
- if (settings.allowedTools && settings.allowedTools.length > 0) {
195
- args.push('--allowed-tools', settings.allowedTools.join(','));
196
- }
197
-
198
- // Try to find gemini in PATH first, then fall back to environment variable
199
- const geminiPath = process.env.GEMINI_PATH || 'gemini';
200
- console.log('Spawning Gemini CLI:', geminiPath, args.join(' '));
201
- console.log('Working directory:', workingDir);
202
-
203
- let spawnCmd = geminiPath;
204
- let spawnArgs = args;
205
-
206
- // On non-Windows platforms, wrap the execution in a shell to avoid ENOEXEC
207
- // which happens when the target is a script lacking a shebang.
208
- if (os.platform() !== 'win32') {
209
- spawnCmd = 'sh';
210
- // Use exec to replace the shell process, ensuring signals hit gemini directly
211
- spawnArgs = ['-c', 'exec "$0" "$@"', geminiPath, ...args];
212
- }
213
-
214
- // Pixcode UI-saved API key (stored in ~/.pixcode/provider-credentials.json)
215
- // overlays on top of process.env so Gemini picks it up without the user
216
- // exporting GEMINI_API_KEY in their shell.
217
- const spawnEnv = await buildSpawnEnv('gemini');
218
-
219
- // OAuth-only users never opened the TUI → no settings.json → spawn dies
220
- // with exit 41. Bootstrap it once.
221
- await ensureGeminiSettingsJson();
222
-
223
- // Headless OAuth handshake. Without this Gemini exits 41 with "Please
224
- // set an Auth method..." even when ~/.gemini/oauth_creds.json is fully
225
- // valid — the CLI gates oauth-personal mode behind GOOGLE_GENAI_USE_GCA
226
- // when running non-interactively. Only set when the user hasn't supplied
227
- // an API key (which has its own auth path).
228
- if (!spawnEnv.GEMINI_API_KEY) {
229
- spawnEnv.GOOGLE_GENAI_USE_GCA = 'true';
230
- }
231
- // `--yolo` skips approval prompts but Gemini still refuses to operate
232
- // on directories it doesn't recognise as trusted. There's no
233
- // interactive prompt available in our pty-less spawn, so we set the
234
- // documented headless escape hatch.
235
- spawnEnv.GEMINI_CLI_TRUST_WORKSPACE = 'true';
236
-
237
- return new Promise((resolve, reject) => {
238
- const geminiProcess = spawnFunction(spawnCmd, spawnArgs, {
239
- cwd: workingDir,
240
- stdio: ['pipe', 'pipe', 'pipe'],
241
- env: spawnEnv,
242
- });
243
- let terminalNotificationSent = false;
244
- let terminalFailureReason = null;
245
-
246
- const notifyTerminalState = ({ code = null, error = null } = {}) => {
247
- if (terminalNotificationSent) {
248
- return;
249
- }
250
-
251
- terminalNotificationSent = true;
252
-
253
- const finalSessionId = capturedSessionId || sessionId || processKey;
254
- if (code === 0 && !error) {
255
- notifyRunStopped({
256
- userId: ws?.userId || null,
257
- provider: 'gemini',
258
- sessionId: finalSessionId,
259
- sessionName: sessionSummary,
260
- stopReason: 'completed'
261
- });
262
- return;
263
- }
264
-
265
- notifyRunFailed({
266
- userId: ws?.userId || null,
267
- provider: 'gemini',
268
- sessionId: finalSessionId,
269
- sessionName: sessionSummary,
270
- error: error || terminalFailureReason || `Gemini CLI exited with code ${code}`
271
- });
272
- };
273
-
274
- // Attach temp file info to process for cleanup later
275
- geminiProcess.tempImagePaths = tempImagePaths;
276
- geminiProcess.tempDir = tempDir;
277
-
278
- // Store process reference for potential abort
279
- const processKey = capturedSessionId || sessionId || Date.now().toString();
280
- activeGeminiProcesses.set(processKey, geminiProcess);
281
-
282
- // Store sessionId on the process object for debugging
283
- geminiProcess.sessionId = processKey;
284
-
285
- // Close stdin to signal we're done sending input
286
- geminiProcess.stdin.end();
287
-
288
- // Add timeout handler
289
- const timeoutMs = 120000; // 120 seconds for slower models
290
- let timeout;
291
-
292
- const startTimeout = () => {
293
- if (timeout) clearTimeout(timeout);
294
- timeout = setTimeout(() => {
295
- const socketSessionId = typeof ws.getSessionId === 'function' ? ws.getSessionId() : (capturedSessionId || sessionId || processKey);
296
- terminalFailureReason = `Gemini CLI timeout - no response received for ${timeoutMs / 1000} seconds`;
297
- ws.send(createNormalizedMessage({ kind: 'error', content: terminalFailureReason, sessionId: socketSessionId, provider: 'gemini' }));
298
- try {
299
- geminiProcess.kill('SIGTERM');
300
- } catch (e) { }
301
- }, timeoutMs);
302
- };
303
-
304
- startTimeout();
305
-
306
- // Save user message to session when starting
307
- if (command && capturedSessionId) {
308
- sessionManager.addMessage(capturedSessionId, 'user', command);
309
- }
310
-
311
- // Create response handler for NDJSON buffering
312
- let responseHandler;
313
- if (ws) {
314
- responseHandler = new GeminiResponseHandler(ws, {
315
- onContentFragment: (content) => {
316
- if (assistantBlocks.length > 0 && assistantBlocks[assistantBlocks.length - 1].type === 'text') {
317
- assistantBlocks[assistantBlocks.length - 1].text += content;
318
- } else {
319
- assistantBlocks.push({ type: 'text', text: content });
320
- }
321
- },
322
- onToolUse: (event) => {
323
- assistantBlocks.push({
324
- type: 'tool_use',
325
- id: event.tool_id,
326
- name: event.tool_name,
327
- input: event.parameters
328
- });
329
- },
330
- onToolResult: (event) => {
331
- if (capturedSessionId) {
332
- if (assistantBlocks.length > 0) {
333
- sessionManager.addMessage(capturedSessionId, 'assistant', [...assistantBlocks]);
334
- assistantBlocks = [];
335
- }
336
- sessionManager.addMessage(capturedSessionId, 'user', [{
337
- type: 'tool_result',
338
- tool_use_id: event.tool_id,
339
- content: event.output === undefined ? null : event.output,
340
- is_error: event.status === 'error'
341
- }]);
342
- }
343
- },
344
- onInit: (event) => {
345
- if (capturedSessionId) {
346
- const sess = sessionManager.getSession(capturedSessionId);
347
- if (sess && !sess.cliSessionId) {
348
- sess.cliSessionId = event.session_id;
349
- sessionManager.saveSession(capturedSessionId);
350
- }
351
- }
352
- }
353
- });
354
- }
355
-
356
- // Handle stdout
357
- geminiProcess.stdout.on('data', (data) => {
358
- const rawOutput = data.toString();
359
- startTimeout(); // Re-arm the timeout
360
-
361
- // For new sessions, create a session ID FIRST
362
- if (!sessionId && !sessionCreatedSent && !capturedSessionId) {
363
- capturedSessionId = `gemini_${Date.now()}`;
364
- sessionCreatedSent = true;
365
-
366
- // Create session in session manager
367
- sessionManager.createSession(capturedSessionId, cwd || process.cwd());
368
-
369
- // Save the user message now that we have a session ID
370
- if (command) {
371
- sessionManager.addMessage(capturedSessionId, 'user', command);
372
- }
373
-
374
- // Update process key with captured session ID
375
- if (processKey !== capturedSessionId) {
376
- activeGeminiProcesses.delete(processKey);
377
- activeGeminiProcesses.set(capturedSessionId, geminiProcess);
378
- }
379
-
380
- ws.setSessionId && typeof ws.setSessionId === 'function' && ws.setSessionId(capturedSessionId);
381
-
382
- ws.send(createNormalizedMessage({ kind: 'session_created', newSessionId: capturedSessionId, sessionId: capturedSessionId, provider: 'gemini' }));
383
- }
384
-
385
- if (responseHandler) {
386
- responseHandler.processData(rawOutput);
387
- } else if (rawOutput) {
388
- // Fallback to direct sending for raw CLI mode without WS
389
- if (assistantBlocks.length > 0 && assistantBlocks[assistantBlocks.length - 1].type === 'text') {
390
- assistantBlocks[assistantBlocks.length - 1].text += rawOutput;
391
- } else {
392
- assistantBlocks.push({ type: 'text', text: rawOutput });
393
- }
394
- const socketSessionId = typeof ws.getSessionId === 'function' ? ws.getSessionId() : (capturedSessionId || sessionId);
395
- ws.send(createNormalizedMessage({ kind: 'stream_delta', content: rawOutput, sessionId: socketSessionId, provider: 'gemini' }));
396
- }
397
- });
398
-
399
- // Handle stderr
400
- geminiProcess.stderr.on('data', (data) => {
401
- const errorMsg = data.toString();
402
-
403
- // Filter out deprecation warnings and "Loaded cached credentials" message
404
- if (errorMsg.includes('[DEP0040]') ||
405
- errorMsg.includes('DeprecationWarning') ||
406
- errorMsg.includes('--trace-deprecation') ||
407
- errorMsg.includes('Loaded cached credentials')) {
408
- return;
409
- }
410
-
411
- const socketSessionId = typeof ws.getSessionId === 'function' ? ws.getSessionId() : (capturedSessionId || sessionId);
412
- ws.send(createNormalizedMessage({ kind: 'error', content: errorMsg, sessionId: socketSessionId, provider: 'gemini' }));
413
- });
414
-
415
- // Handle process completion
416
- geminiProcess.on('close', async (code) => {
417
- clearTimeout(timeout);
418
-
419
- // Flush any remaining buffered content
420
- if (responseHandler) {
421
- responseHandler.forceFlush();
422
- responseHandler.destroy();
423
- }
424
-
425
- // Clean up process reference
426
- const finalSessionId = capturedSessionId || sessionId || processKey;
427
- activeGeminiProcesses.delete(finalSessionId);
428
-
429
- // Save assistant response to session if we have one
430
- if (finalSessionId && assistantBlocks.length > 0) {
431
- sessionManager.addMessage(finalSessionId, 'assistant', assistantBlocks);
432
- }
433
-
434
- ws.send(createNormalizedMessage({ kind: 'complete', exitCode: code, isNewSession: !sessionId && !!command, sessionId: finalSessionId, provider: 'gemini' }));
435
-
436
- // Clean up temporary image files if any
437
- if (geminiProcess.tempImagePaths && geminiProcess.tempImagePaths.length > 0) {
438
- for (const imagePath of geminiProcess.tempImagePaths) {
439
- await fs.unlink(imagePath).catch(err => { });
440
- }
441
- if (geminiProcess.tempDir) {
442
- await fs.rm(geminiProcess.tempDir, { recursive: true, force: true }).catch(err => { });
443
- }
444
- }
445
-
446
- if (code === 0) {
447
- notifyTerminalState({ code });
448
- resolve();
449
- } else {
450
- // code 127 = shell "command not found" — check installation
451
- if (code === 127) {
452
- const installed = await providerAuthService.isProviderInstalled('gemini');
453
- if (!installed) {
454
- const socketSessionId = typeof ws.getSessionId === 'function' ? ws.getSessionId() : finalSessionId;
455
- ws.send(createNormalizedMessage({ kind: 'error', content: 'Gemini CLI is not installed. Please install it first: https://github.com/google-gemini/gemini-cli', sessionId: socketSessionId, provider: 'gemini' }));
456
- }
457
- }
458
-
459
- notifyTerminalState({
460
- code,
461
- error: code === null ? 'Gemini CLI process was terminated or timed out' : null
462
- });
463
- reject(new Error(code === null ? 'Gemini CLI process was terminated or timed out' : `Gemini CLI exited with code ${code}`));
464
- }
465
- });
466
-
467
- // Handle process errors
468
- geminiProcess.on('error', async (error) => {
469
- // Clean up process reference on error
470
- const finalSessionId = capturedSessionId || sessionId || processKey;
471
- activeGeminiProcesses.delete(finalSessionId);
472
-
473
- // Check if Gemini CLI is installed for a clearer error message
474
- const installed = await providerAuthService.isProviderInstalled('gemini');
475
- const errorContent = !installed
476
- ? 'Gemini CLI is not installed. Please install it first: https://github.com/google-gemini/gemini-cli'
477
- : error.message;
478
-
479
- const errorSessionId = typeof ws.getSessionId === 'function' ? ws.getSessionId() : finalSessionId;
480
- ws.send(createNormalizedMessage({ kind: 'error', content: errorContent, sessionId: errorSessionId, provider: 'gemini' }));
481
- notifyTerminalState({ error });
482
-
483
- reject(error);
484
- });
485
-
486
- });
487
- }
488
-
489
- function abortGeminiSession(sessionId) {
490
- let geminiProc = activeGeminiProcesses.get(sessionId);
491
- let processKey = sessionId;
492
-
493
- if (!geminiProc) {
494
- for (const [key, proc] of activeGeminiProcesses.entries()) {
495
- if (proc.sessionId === sessionId) {
496
- geminiProc = proc;
497
- processKey = key;
498
- break;
499
- }
500
- }
501
- }
502
-
503
- if (geminiProc) {
504
- try {
505
- geminiProc.kill('SIGTERM');
506
- setTimeout(() => {
507
- if (activeGeminiProcesses.has(processKey)) {
508
- try {
509
- geminiProc.kill('SIGKILL');
510
- } catch (e) { }
511
- }
512
- }, 2000); // Wait 2 seconds before force kill
513
-
514
- return true;
515
- } catch (error) {
516
- return false;
517
- }
518
- }
519
- return false;
520
- }
521
-
522
- function isGeminiSessionActive(sessionId) {
523
- return activeGeminiProcesses.has(sessionId);
524
- }
525
-
526
- function getActiveGeminiSessions() {
527
- return Array.from(activeGeminiProcesses.keys());
528
- }
529
-
530
- export {
531
- spawnGemini,
532
- abortGeminiSession,
533
- isGeminiSessionActive,
534
- getActiveGeminiSessions
535
- };
1
+ import { spawn } from 'child_process';
2
+ import crossSpawn from 'cross-spawn';
3
+
4
+ // Use cross-spawn on Windows for correct .cmd resolution (same pattern as cursor-cli.js)
5
+ const spawnFunction = process.platform === 'win32' ? crossSpawn : spawn;
6
+ import { promises as fs } from 'fs';
7
+ import path from 'path';
8
+ import os from 'os';
9
+ import sessionManager from './sessionManager.js';
10
+ import GeminiResponseHandler from './gemini-response-handler.js';
11
+ import { notifyRunFailed, notifyRunStopped } from './services/notification-orchestrator.js';
12
+ import { buildSpawnEnv } from './services/provider-credentials.js';
13
+ import { providerAuthService } from './modules/providers/services/provider-auth.service.js';
14
+ import { createNormalizedMessage } from './shared/utils.js';
15
+
16
+ let activeGeminiProcesses = new Map(); // Track active processes by session ID
17
+
18
+ /**
19
+ * Auto-create `~/.gemini/settings.json` when the user has signed in via OAuth
20
+ * (so `oauth_creds.json` exists) but never opened the Gemini TUI to write the
21
+ * `selectedAuthType` field. Without this, `gemini --prompt … --output-format
22
+ * stream-json --yolo` exits 41 with "Please set an Auth method in your
23
+ * settings.json" — even though credentials are perfectly valid. We respect a
24
+ * pre-existing `settings.json` and never overwrite a chosen auth type.
25
+ *
26
+ * Triggered every spawn (cheap: one fs.access + maybe one tiny write).
27
+ */
28
+ async function ensureGeminiSettingsJson() {
29
+ const home = os.homedir();
30
+ const dir = path.join(home, '.gemini');
31
+ const settingsPath = path.join(dir, 'settings.json');
32
+ const oauthPath = path.join(dir, 'oauth_creds.json');
33
+ const apiKey = process.env.GEMINI_API_KEY;
34
+
35
+ try {
36
+ await fs.access(settingsPath);
37
+ return; // user-managed, leave it.
38
+ } catch { /* missing — we may create it */ }
39
+
40
+ let selectedAuthType = null;
41
+ if (apiKey && apiKey.trim()) {
42
+ selectedAuthType = 'gemini-api-key';
43
+ } else {
44
+ try {
45
+ await fs.access(oauthPath);
46
+ selectedAuthType = 'oauth-personal';
47
+ } catch { /* no oauth either */ }
48
+ }
49
+ if (!selectedAuthType) return;
50
+
51
+ try {
52
+ await fs.mkdir(dir, { recursive: true });
53
+ await fs.writeFile(settingsPath, JSON.stringify({ selectedAuthType }, null, 2), { mode: 0o600 });
54
+ console.log(`[gemini] auto-bootstrapped ~/.gemini/settings.json with selectedAuthType="${selectedAuthType}"`);
55
+ } catch (error) {
56
+ console.warn('[gemini] failed to bootstrap settings.json:', error?.message || error);
57
+ }
58
+ }
59
+
60
+ async function spawnGemini(command, options = {}, ws) {
61
+ const { sessionId, projectPath, cwd, toolsSettings, permissionMode, images, sessionSummary } = options;
62
+ let capturedSessionId = sessionId; // Track session ID throughout the process
63
+ let sessionCreatedSent = false; // Track if we've already sent session-created event
64
+ let assistantBlocks = []; // Accumulate the full response blocks including tools
65
+
66
+ // Use tools settings passed from frontend, or defaults
67
+ const settings = toolsSettings || {
68
+ allowedTools: [],
69
+ disallowedTools: [],
70
+ skipPermissions: false
71
+ };
72
+
73
+ // Build Gemini CLI command - start with print/resume flags first
74
+ const args = [];
75
+
76
+ // Add prompt flag with command if we have a command
77
+ if (command && command.trim()) {
78
+ args.push('--prompt', command);
79
+ }
80
+
81
+ // If we have a sessionId, we want to resume
82
+ if (sessionId) {
83
+ const session = sessionManager.getSession(sessionId);
84
+ if (session && session.cliSessionId) {
85
+ args.push('--resume', session.cliSessionId);
86
+ }
87
+ }
88
+
89
+ // Use cwd (actual project directory) instead of projectPath (Gemini's metadata directory)
90
+ // Clean the path by removing any non-printable characters
91
+ const cleanPath = (cwd || projectPath || process.cwd()).replace(/[^\x20-\x7E]/g, '').trim();
92
+ const workingDir = cleanPath;
93
+
94
+ // Handle images by saving them to temporary files and passing paths to Gemini
95
+ const tempImagePaths = [];
96
+ let tempDir = null;
97
+ if (images && images.length > 0) {
98
+ try {
99
+ // Create temp directory in the project directory so Gemini can access it
100
+ tempDir = path.join(workingDir, '.tmp', 'images', Date.now().toString());
101
+ await fs.mkdir(tempDir, { recursive: true });
102
+
103
+ // Save each image to a temp file
104
+ for (const [index, image] of images.entries()) {
105
+ // Extract base64 data and mime type
106
+ const matches = image.data.match(/^data:([^;]+);base64,(.+)$/);
107
+ if (!matches) {
108
+ continue;
109
+ }
110
+
111
+ const [, mimeType, base64Data] = matches;
112
+ const extension = mimeType.split('/')[1] || 'png';
113
+ const filename = `image_${index}.${extension}`;
114
+ const filepath = path.join(tempDir, filename);
115
+
116
+ // Write base64 data to file
117
+ await fs.writeFile(filepath, Buffer.from(base64Data, 'base64'));
118
+ tempImagePaths.push(filepath);
119
+ }
120
+
121
+ // Include the full image paths in the prompt for Gemini to reference
122
+ // Gemini CLI can read images from file paths in the prompt
123
+ if (tempImagePaths.length > 0 && command && command.trim()) {
124
+ const imageNote = `\n\n[Images given: ${tempImagePaths.length} images are located at the following paths:]\n${tempImagePaths.map((p, i) => `${i + 1}. ${p}`).join('\n')}`;
125
+ const modifiedCommand = command + imageNote;
126
+
127
+ // Update the command in args
128
+ const promptIndex = args.indexOf('--prompt');
129
+ if (promptIndex !== -1 && args[promptIndex + 1] === command) {
130
+ args[promptIndex + 1] = modifiedCommand;
131
+ } else if (promptIndex !== -1) {
132
+ // If we're using context, update the full prompt
133
+ args[promptIndex + 1] = args[promptIndex + 1] + imageNote;
134
+ }
135
+ }
136
+ } catch (error) {
137
+ console.error('Error processing images for Gemini:', error);
138
+ }
139
+ }
140
+
141
+ // Add basic flags for Gemini
142
+ if (options.debug) {
143
+ args.push('--debug');
144
+ }
145
+
146
+ // Add MCP config flag only if MCP servers are configured
147
+ try {
148
+ const geminiConfigPath = path.join(os.homedir(), '.gemini.json');
149
+ let hasMcpServers = false;
150
+
151
+ try {
152
+ await fs.access(geminiConfigPath);
153
+ const geminiConfigRaw = await fs.readFile(geminiConfigPath, 'utf8');
154
+ const geminiConfig = JSON.parse(geminiConfigRaw);
155
+
156
+ // Check global MCP servers
157
+ if (geminiConfig.mcpServers && Object.keys(geminiConfig.mcpServers).length > 0) {
158
+ hasMcpServers = true;
159
+ }
160
+
161
+ // Check project-specific MCP servers
162
+ if (!hasMcpServers && geminiConfig.geminiProjects) {
163
+ const currentProjectPath = process.cwd();
164
+ const projectConfig = geminiConfig.geminiProjects[currentProjectPath];
165
+ if (projectConfig && projectConfig.mcpServers && Object.keys(projectConfig.mcpServers).length > 0) {
166
+ hasMcpServers = true;
167
+ }
168
+ }
169
+ } catch (e) {
170
+ // Ignore if file doesn't exist or isn't parsable
171
+ }
172
+
173
+ if (hasMcpServers) {
174
+ args.push('--mcp-config', geminiConfigPath);
175
+ }
176
+ } catch (error) {
177
+ // Ignore outer errors
178
+ }
179
+
180
+ // Add model for all sessions (both new and resumed)
181
+ let modelToUse = options.model || 'gemini-2.5-flash';
182
+ args.push('--model', modelToUse);
183
+ args.push('--output-format', 'stream-json');
184
+
185
+ // Handle approval modes and allowed tools
186
+ if (settings.skipPermissions || options.skipPermissions || permissionMode === 'yolo') {
187
+ args.push('--yolo');
188
+ } else if (permissionMode === 'auto_edit') {
189
+ args.push('--approval-mode', 'auto_edit');
190
+ } else if (permissionMode === 'plan') {
191
+ args.push('--approval-mode', 'plan');
192
+ }
193
+
194
+ if (settings.allowedTools && settings.allowedTools.length > 0) {
195
+ args.push('--allowed-tools', settings.allowedTools.join(','));
196
+ }
197
+
198
+ // Try to find gemini in PATH first, then fall back to environment variable
199
+ const geminiPath = process.env.GEMINI_PATH || 'gemini';
200
+ console.log('Spawning Gemini CLI:', geminiPath, args.join(' '));
201
+ console.log('Working directory:', workingDir);
202
+
203
+ let spawnCmd = geminiPath;
204
+ let spawnArgs = args;
205
+
206
+ // On non-Windows platforms, wrap the execution in a shell to avoid ENOEXEC
207
+ // which happens when the target is a script lacking a shebang.
208
+ if (os.platform() !== 'win32') {
209
+ spawnCmd = 'sh';
210
+ // Use exec to replace the shell process, ensuring signals hit gemini directly
211
+ spawnArgs = ['-c', 'exec "$0" "$@"', geminiPath, ...args];
212
+ }
213
+
214
+ // Pixcode UI-saved API key (stored in ~/.pixcode/provider-credentials.json)
215
+ // overlays on top of process.env so Gemini picks it up without the user
216
+ // exporting GEMINI_API_KEY in their shell.
217
+ const spawnEnv = await buildSpawnEnv('gemini');
218
+
219
+ // OAuth-only users never opened the TUI → no settings.json → spawn dies
220
+ // with exit 41. Bootstrap it once.
221
+ await ensureGeminiSettingsJson();
222
+
223
+ // Headless OAuth handshake. Without this Gemini exits 41 with "Please
224
+ // set an Auth method..." even when ~/.gemini/oauth_creds.json is fully
225
+ // valid — the CLI gates oauth-personal mode behind GOOGLE_GENAI_USE_GCA
226
+ // when running non-interactively. Only set when the user hasn't supplied
227
+ // an API key (which has its own auth path).
228
+ if (!spawnEnv.GEMINI_API_KEY) {
229
+ spawnEnv.GOOGLE_GENAI_USE_GCA = 'true';
230
+ }
231
+ // `--yolo` skips approval prompts but Gemini still refuses to operate
232
+ // on directories it doesn't recognise as trusted. There's no
233
+ // interactive prompt available in our pty-less spawn, so we set the
234
+ // documented headless escape hatch.
235
+ spawnEnv.GEMINI_CLI_TRUST_WORKSPACE = 'true';
236
+
237
+ return new Promise((resolve, reject) => {
238
+ const geminiProcess = spawnFunction(spawnCmd, spawnArgs, {
239
+ cwd: workingDir,
240
+ stdio: ['pipe', 'pipe', 'pipe'],
241
+ env: spawnEnv,
242
+ });
243
+ let terminalNotificationSent = false;
244
+ let terminalFailureReason = null;
245
+
246
+ const notifyTerminalState = ({ code = null, error = null } = {}) => {
247
+ if (terminalNotificationSent) {
248
+ return;
249
+ }
250
+
251
+ terminalNotificationSent = true;
252
+
253
+ const finalSessionId = capturedSessionId || sessionId || processKey;
254
+ if (code === 0 && !error) {
255
+ notifyRunStopped({
256
+ userId: ws?.userId || null,
257
+ provider: 'gemini',
258
+ sessionId: finalSessionId,
259
+ sessionName: sessionSummary,
260
+ stopReason: 'completed'
261
+ });
262
+ return;
263
+ }
264
+
265
+ notifyRunFailed({
266
+ userId: ws?.userId || null,
267
+ provider: 'gemini',
268
+ sessionId: finalSessionId,
269
+ sessionName: sessionSummary,
270
+ error: error || terminalFailureReason || `Gemini CLI exited with code ${code}`
271
+ });
272
+ };
273
+
274
+ // Attach temp file info to process for cleanup later
275
+ geminiProcess.tempImagePaths = tempImagePaths;
276
+ geminiProcess.tempDir = tempDir;
277
+
278
+ // Store process reference for potential abort
279
+ const processKey = capturedSessionId || sessionId || Date.now().toString();
280
+ activeGeminiProcesses.set(processKey, geminiProcess);
281
+
282
+ // Store sessionId on the process object for debugging
283
+ geminiProcess.sessionId = processKey;
284
+
285
+ // Close stdin to signal we're done sending input
286
+ geminiProcess.stdin.end();
287
+
288
+ // Add timeout handler
289
+ const timeoutMs = 120000; // 120 seconds for slower models
290
+ let timeout;
291
+
292
+ const startTimeout = () => {
293
+ if (timeout) clearTimeout(timeout);
294
+ timeout = setTimeout(() => {
295
+ const socketSessionId = typeof ws.getSessionId === 'function' ? ws.getSessionId() : (capturedSessionId || sessionId || processKey);
296
+ terminalFailureReason = `Gemini CLI timeout - no response received for ${timeoutMs / 1000} seconds`;
297
+ ws.send(createNormalizedMessage({ kind: 'error', content: terminalFailureReason, sessionId: socketSessionId, provider: 'gemini' }));
298
+ try {
299
+ geminiProcess.kill('SIGTERM');
300
+ } catch (e) { }
301
+ }, timeoutMs);
302
+ };
303
+
304
+ startTimeout();
305
+
306
+ // Save user message to session when starting
307
+ if (command && capturedSessionId) {
308
+ sessionManager.addMessage(capturedSessionId, 'user', command);
309
+ }
310
+
311
+ // Create response handler for NDJSON buffering
312
+ let responseHandler;
313
+ if (ws) {
314
+ responseHandler = new GeminiResponseHandler(ws, {
315
+ onContentFragment: (content) => {
316
+ if (assistantBlocks.length > 0 && assistantBlocks[assistantBlocks.length - 1].type === 'text') {
317
+ assistantBlocks[assistantBlocks.length - 1].text += content;
318
+ } else {
319
+ assistantBlocks.push({ type: 'text', text: content });
320
+ }
321
+ },
322
+ onToolUse: (event) => {
323
+ assistantBlocks.push({
324
+ type: 'tool_use',
325
+ id: event.tool_id,
326
+ name: event.tool_name,
327
+ input: event.parameters
328
+ });
329
+ },
330
+ onToolResult: (event) => {
331
+ if (capturedSessionId) {
332
+ if (assistantBlocks.length > 0) {
333
+ sessionManager.addMessage(capturedSessionId, 'assistant', [...assistantBlocks]);
334
+ assistantBlocks = [];
335
+ }
336
+ sessionManager.addMessage(capturedSessionId, 'user', [{
337
+ type: 'tool_result',
338
+ tool_use_id: event.tool_id,
339
+ content: event.output === undefined ? null : event.output,
340
+ is_error: event.status === 'error'
341
+ }]);
342
+ }
343
+ },
344
+ onInit: (event) => {
345
+ if (capturedSessionId) {
346
+ const sess = sessionManager.getSession(capturedSessionId);
347
+ if (sess && !sess.cliSessionId) {
348
+ sess.cliSessionId = event.session_id;
349
+ sessionManager.saveSession(capturedSessionId);
350
+ }
351
+ }
352
+ }
353
+ });
354
+ }
355
+
356
+ // Handle stdout
357
+ geminiProcess.stdout.on('data', (data) => {
358
+ const rawOutput = data.toString();
359
+ startTimeout(); // Re-arm the timeout
360
+
361
+ // For new sessions, create a session ID FIRST
362
+ if (!sessionId && !sessionCreatedSent && !capturedSessionId) {
363
+ capturedSessionId = `gemini_${Date.now()}`;
364
+ sessionCreatedSent = true;
365
+
366
+ // Create session in session manager
367
+ sessionManager.createSession(capturedSessionId, cwd || process.cwd());
368
+
369
+ // Save the user message now that we have a session ID
370
+ if (command) {
371
+ sessionManager.addMessage(capturedSessionId, 'user', command);
372
+ }
373
+
374
+ // Update process key with captured session ID
375
+ if (processKey !== capturedSessionId) {
376
+ activeGeminiProcesses.delete(processKey);
377
+ activeGeminiProcesses.set(capturedSessionId, geminiProcess);
378
+ }
379
+
380
+ ws.setSessionId && typeof ws.setSessionId === 'function' && ws.setSessionId(capturedSessionId);
381
+
382
+ ws.send(createNormalizedMessage({ kind: 'session_created', newSessionId: capturedSessionId, sessionId: capturedSessionId, provider: 'gemini' }));
383
+ }
384
+
385
+ if (responseHandler) {
386
+ responseHandler.processData(rawOutput);
387
+ } else if (rawOutput) {
388
+ // Fallback to direct sending for raw CLI mode without WS
389
+ if (assistantBlocks.length > 0 && assistantBlocks[assistantBlocks.length - 1].type === 'text') {
390
+ assistantBlocks[assistantBlocks.length - 1].text += rawOutput;
391
+ } else {
392
+ assistantBlocks.push({ type: 'text', text: rawOutput });
393
+ }
394
+ const socketSessionId = typeof ws.getSessionId === 'function' ? ws.getSessionId() : (capturedSessionId || sessionId);
395
+ ws.send(createNormalizedMessage({ kind: 'stream_delta', content: rawOutput, sessionId: socketSessionId, provider: 'gemini' }));
396
+ }
397
+ });
398
+
399
+ // Handle stderr
400
+ geminiProcess.stderr.on('data', (data) => {
401
+ const errorMsg = data.toString();
402
+
403
+ // Filter out deprecation warnings and "Loaded cached credentials" message
404
+ if (errorMsg.includes('[DEP0040]') ||
405
+ errorMsg.includes('DeprecationWarning') ||
406
+ errorMsg.includes('--trace-deprecation') ||
407
+ errorMsg.includes('Loaded cached credentials')) {
408
+ return;
409
+ }
410
+
411
+ const socketSessionId = typeof ws.getSessionId === 'function' ? ws.getSessionId() : (capturedSessionId || sessionId);
412
+ ws.send(createNormalizedMessage({ kind: 'error', content: errorMsg, sessionId: socketSessionId, provider: 'gemini' }));
413
+ });
414
+
415
+ // Handle process completion
416
+ geminiProcess.on('close', async (code) => {
417
+ clearTimeout(timeout);
418
+
419
+ // Flush any remaining buffered content
420
+ if (responseHandler) {
421
+ responseHandler.forceFlush();
422
+ responseHandler.destroy();
423
+ }
424
+
425
+ // Clean up process reference
426
+ const finalSessionId = capturedSessionId || sessionId || processKey;
427
+ activeGeminiProcesses.delete(finalSessionId);
428
+
429
+ // Save assistant response to session if we have one
430
+ if (finalSessionId && assistantBlocks.length > 0) {
431
+ sessionManager.addMessage(finalSessionId, 'assistant', assistantBlocks);
432
+ }
433
+
434
+ ws.send(createNormalizedMessage({ kind: 'complete', exitCode: code, isNewSession: !sessionId && !!command, sessionId: finalSessionId, provider: 'gemini' }));
435
+
436
+ // Clean up temporary image files if any
437
+ if (geminiProcess.tempImagePaths && geminiProcess.tempImagePaths.length > 0) {
438
+ for (const imagePath of geminiProcess.tempImagePaths) {
439
+ await fs.unlink(imagePath).catch(err => { });
440
+ }
441
+ if (geminiProcess.tempDir) {
442
+ await fs.rm(geminiProcess.tempDir, { recursive: true, force: true }).catch(err => { });
443
+ }
444
+ }
445
+
446
+ if (code === 0) {
447
+ notifyTerminalState({ code });
448
+ resolve();
449
+ } else {
450
+ // code 127 = shell "command not found" — check installation
451
+ if (code === 127) {
452
+ const installed = await providerAuthService.isProviderInstalled('gemini');
453
+ if (!installed) {
454
+ const socketSessionId = typeof ws.getSessionId === 'function' ? ws.getSessionId() : finalSessionId;
455
+ ws.send(createNormalizedMessage({ kind: 'error', content: 'Gemini CLI is not installed. Please install it first: https://github.com/google-gemini/gemini-cli', sessionId: socketSessionId, provider: 'gemini' }));
456
+ }
457
+ }
458
+
459
+ notifyTerminalState({
460
+ code,
461
+ error: code === null ? 'Gemini CLI process was terminated or timed out' : null
462
+ });
463
+ reject(new Error(code === null ? 'Gemini CLI process was terminated or timed out' : `Gemini CLI exited with code ${code}`));
464
+ }
465
+ });
466
+
467
+ // Handle process errors
468
+ geminiProcess.on('error', async (error) => {
469
+ // Clean up process reference on error
470
+ const finalSessionId = capturedSessionId || sessionId || processKey;
471
+ activeGeminiProcesses.delete(finalSessionId);
472
+
473
+ // Check if Gemini CLI is installed for a clearer error message
474
+ const installed = await providerAuthService.isProviderInstalled('gemini');
475
+ const errorContent = !installed
476
+ ? 'Gemini CLI is not installed. Please install it first: https://github.com/google-gemini/gemini-cli'
477
+ : error.message;
478
+
479
+ const errorSessionId = typeof ws.getSessionId === 'function' ? ws.getSessionId() : finalSessionId;
480
+ ws.send(createNormalizedMessage({ kind: 'error', content: errorContent, sessionId: errorSessionId, provider: 'gemini' }));
481
+ notifyTerminalState({ error });
482
+
483
+ reject(error);
484
+ });
485
+
486
+ });
487
+ }
488
+
489
+ function abortGeminiSession(sessionId) {
490
+ let geminiProc = activeGeminiProcesses.get(sessionId);
491
+ let processKey = sessionId;
492
+
493
+ if (!geminiProc) {
494
+ for (const [key, proc] of activeGeminiProcesses.entries()) {
495
+ if (proc.sessionId === sessionId) {
496
+ geminiProc = proc;
497
+ processKey = key;
498
+ break;
499
+ }
500
+ }
501
+ }
502
+
503
+ if (geminiProc) {
504
+ try {
505
+ geminiProc.kill('SIGTERM');
506
+ setTimeout(() => {
507
+ if (activeGeminiProcesses.has(processKey)) {
508
+ try {
509
+ geminiProc.kill('SIGKILL');
510
+ } catch (e) { }
511
+ }
512
+ }, 2000); // Wait 2 seconds before force kill
513
+
514
+ return true;
515
+ } catch (error) {
516
+ return false;
517
+ }
518
+ }
519
+ return false;
520
+ }
521
+
522
+ function isGeminiSessionActive(sessionId) {
523
+ return activeGeminiProcesses.has(sessionId);
524
+ }
525
+
526
+ function getActiveGeminiSessions() {
527
+ return Array.from(activeGeminiProcesses.keys());
528
+ }
529
+
530
+ export {
531
+ spawnGemini,
532
+ abortGeminiSession,
533
+ isGeminiSessionActive,
534
+ getActiveGeminiSessions
535
+ };