notioncode 0.1.1 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -4
- package/agent-runtime-server/package-lock.json +4377 -0
- package/agent-runtime-server/package.json +36 -0
- package/agent-runtime-server/scripts/fix-node-pty.js +67 -0
- package/agent-runtime-server/server/agent-session-service.js +816 -0
- package/agent-runtime-server/server/claude-sdk.js +836 -0
- package/agent-runtime-server/server/cli.js +330 -0
- package/agent-runtime-server/server/constants/config.js +5 -0
- package/agent-runtime-server/server/cursor-cli.js +335 -0
- package/agent-runtime-server/server/database/db.js +653 -0
- package/agent-runtime-server/server/database/init.sql +99 -0
- package/agent-runtime-server/server/gemini-cli.js +460 -0
- package/agent-runtime-server/server/gemini-response-handler.js +79 -0
- package/agent-runtime-server/server/index.js +2569 -0
- package/agent-runtime-server/server/load-env.js +32 -0
- package/agent-runtime-server/server/middleware/auth.js +132 -0
- package/agent-runtime-server/server/openai-codex.js +512 -0
- package/agent-runtime-server/server/projects.js +2594 -0
- package/agent-runtime-server/server/providers/claude/adapter.js +278 -0
- package/agent-runtime-server/server/providers/codex/adapter.js +248 -0
- package/agent-runtime-server/server/providers/cursor/adapter.js +353 -0
- package/agent-runtime-server/server/providers/gemini/adapter.js +186 -0
- package/agent-runtime-server/server/providers/registry.js +44 -0
- package/agent-runtime-server/server/providers/types.js +119 -0
- package/agent-runtime-server/server/providers/utils.js +29 -0
- package/agent-runtime-server/server/routes/agent-sessions.js +238 -0
- package/agent-runtime-server/server/routes/agent.js +1244 -0
- package/agent-runtime-server/server/routes/auth.js +144 -0
- package/agent-runtime-server/server/routes/cli-auth.js +478 -0
- package/agent-runtime-server/server/routes/codex.js +329 -0
- package/agent-runtime-server/server/routes/commands.js +596 -0
- package/agent-runtime-server/server/routes/cursor.js +798 -0
- package/agent-runtime-server/server/routes/gemini.js +24 -0
- package/agent-runtime-server/server/routes/git.js +1508 -0
- package/agent-runtime-server/server/routes/mcp-utils.js +48 -0
- package/agent-runtime-server/server/routes/mcp.js +552 -0
- package/agent-runtime-server/server/routes/messages.js +61 -0
- package/agent-runtime-server/server/routes/plugins.js +307 -0
- package/agent-runtime-server/server/routes/projects.js +548 -0
- package/agent-runtime-server/server/routes/settings.js +276 -0
- package/agent-runtime-server/server/routes/taskmaster.js +1963 -0
- package/agent-runtime-server/server/routes/user.js +123 -0
- package/agent-runtime-server/server/services/notification-orchestrator.js +227 -0
- package/agent-runtime-server/server/services/vapid-keys.js +35 -0
- package/agent-runtime-server/server/sessionManager.js +226 -0
- package/agent-runtime-server/server/utils/commandParser.js +303 -0
- package/agent-runtime-server/server/utils/frontmatter.js +18 -0
- package/agent-runtime-server/server/utils/gitConfig.js +34 -0
- package/agent-runtime-server/server/utils/mcp-detector.js +198 -0
- package/agent-runtime-server/server/utils/plugin-loader.js +457 -0
- package/agent-runtime-server/server/utils/plugin-process-manager.js +184 -0
- package/agent-runtime-server/server/utils/taskmaster-websocket.js +129 -0
- package/agent-runtime-server/shared/modelConstants.js +12 -0
- package/agent-runtime-server/shared/modelConstants.test.js +34 -0
- package/agent-runtime-server/shared/networkHosts.js +22 -0
- package/agent-runtime-server/test_sdk.mjs +16 -0
- package/bin/bridges/darwin-x64/nocode-bridge +0 -0
- package/bin/{nocode-local.js → notioncode.js} +0 -0
- package/dist/assets/icon-CQtd7WEB.png +0 -0
- package/dist/assets/index-D_1ZrHDe.js +1 -0
- package/dist/assets/index-DhCWie1Z.css +1 -0
- package/dist/assets/index-DkGqIiwF.js +689 -0
- package/dist/index.html +46 -0
- package/dist/onboarding/step1_create.png +0 -0
- package/dist/onboarding/step2_capabilities.png +0 -0
- package/dist/onboarding/step2b_content_access.png +0 -0
- package/dist/onboarding/step2c_page_access.png +0 -0
- package/dist/onboarding/step3_token.png +0 -0
- package/dist/onboarding/step4_webhook.png +0 -0
- package/dist/onboarding/step6a_verify.png +0 -0
- package/dist/onboarding/step6b_copy_verify_token.png +0 -0
- package/dist/tinyfish-fish-only.png +0 -0
- package/lib/install.js +33 -2
- package/lib/start.js +157 -25
- package/package.json +7 -4
- package/src/shared/modelRegistry.d.ts +24 -0
- package/src/shared/modelRegistry.js +163 -0
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
-- Initialize authentication database
|
|
2
|
+
PRAGMA foreign_keys = ON;
|
|
3
|
+
|
|
4
|
+
-- Users table (single user system)
|
|
5
|
+
CREATE TABLE IF NOT EXISTS users (
|
|
6
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
7
|
+
username TEXT UNIQUE NOT NULL,
|
|
8
|
+
password_hash TEXT NOT NULL,
|
|
9
|
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
10
|
+
last_login DATETIME,
|
|
11
|
+
is_active BOOLEAN DEFAULT 1,
|
|
12
|
+
git_name TEXT,
|
|
13
|
+
git_email TEXT,
|
|
14
|
+
has_completed_onboarding BOOLEAN DEFAULT 0
|
|
15
|
+
);
|
|
16
|
+
|
|
17
|
+
-- Indexes for performance
|
|
18
|
+
CREATE INDEX IF NOT EXISTS idx_users_username ON users(username);
|
|
19
|
+
CREATE INDEX IF NOT EXISTS idx_users_active ON users(is_active);
|
|
20
|
+
|
|
21
|
+
-- API Keys table for external API access
|
|
22
|
+
CREATE TABLE IF NOT EXISTS api_keys (
|
|
23
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
24
|
+
user_id INTEGER NOT NULL,
|
|
25
|
+
key_name TEXT NOT NULL,
|
|
26
|
+
api_key TEXT UNIQUE NOT NULL,
|
|
27
|
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
28
|
+
last_used DATETIME,
|
|
29
|
+
is_active BOOLEAN DEFAULT 1,
|
|
30
|
+
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
|
31
|
+
);
|
|
32
|
+
|
|
33
|
+
CREATE INDEX IF NOT EXISTS idx_api_keys_key ON api_keys(api_key);
|
|
34
|
+
CREATE INDEX IF NOT EXISTS idx_api_keys_user_id ON api_keys(user_id);
|
|
35
|
+
CREATE INDEX IF NOT EXISTS idx_api_keys_active ON api_keys(is_active);
|
|
36
|
+
|
|
37
|
+
-- User credentials table for storing various tokens/credentials (GitHub, GitLab, etc.)
|
|
38
|
+
CREATE TABLE IF NOT EXISTS user_credentials (
|
|
39
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
40
|
+
user_id INTEGER NOT NULL,
|
|
41
|
+
credential_name TEXT NOT NULL,
|
|
42
|
+
credential_type TEXT NOT NULL, -- 'github_token', 'gitlab_token', 'bitbucket_token', etc.
|
|
43
|
+
credential_value TEXT NOT NULL,
|
|
44
|
+
description TEXT,
|
|
45
|
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
46
|
+
is_active BOOLEAN DEFAULT 1,
|
|
47
|
+
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
|
48
|
+
);
|
|
49
|
+
|
|
50
|
+
CREATE INDEX IF NOT EXISTS idx_user_credentials_user_id ON user_credentials(user_id);
|
|
51
|
+
CREATE INDEX IF NOT EXISTS idx_user_credentials_type ON user_credentials(credential_type);
|
|
52
|
+
CREATE INDEX IF NOT EXISTS idx_user_credentials_active ON user_credentials(is_active);
|
|
53
|
+
|
|
54
|
+
-- User notification preferences (backend-owned, provider-agnostic)
|
|
55
|
+
CREATE TABLE IF NOT EXISTS user_notification_preferences (
|
|
56
|
+
user_id INTEGER PRIMARY KEY,
|
|
57
|
+
preferences_json TEXT NOT NULL,
|
|
58
|
+
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
59
|
+
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
|
60
|
+
);
|
|
61
|
+
|
|
62
|
+
-- VAPID key pair for Web Push notifications
|
|
63
|
+
CREATE TABLE IF NOT EXISTS vapid_keys (
|
|
64
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
65
|
+
public_key TEXT NOT NULL,
|
|
66
|
+
private_key TEXT NOT NULL,
|
|
67
|
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
68
|
+
);
|
|
69
|
+
|
|
70
|
+
-- Browser push subscriptions
|
|
71
|
+
CREATE TABLE IF NOT EXISTS push_subscriptions (
|
|
72
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
73
|
+
user_id INTEGER NOT NULL,
|
|
74
|
+
endpoint TEXT NOT NULL UNIQUE,
|
|
75
|
+
keys_p256dh TEXT NOT NULL,
|
|
76
|
+
keys_auth TEXT NOT NULL,
|
|
77
|
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
78
|
+
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
|
79
|
+
);
|
|
80
|
+
|
|
81
|
+
-- Session custom names (provider-agnostic display name overrides)
|
|
82
|
+
CREATE TABLE IF NOT EXISTS session_names (
|
|
83
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
84
|
+
session_id TEXT NOT NULL,
|
|
85
|
+
provider TEXT NOT NULL DEFAULT 'claude',
|
|
86
|
+
custom_name TEXT NOT NULL,
|
|
87
|
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
88
|
+
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
|
89
|
+
UNIQUE(session_id, provider)
|
|
90
|
+
);
|
|
91
|
+
|
|
92
|
+
CREATE INDEX IF NOT EXISTS idx_session_names_lookup ON session_names(session_id, provider);
|
|
93
|
+
|
|
94
|
+
-- App configuration table (auto-generated secrets, settings, etc.)
|
|
95
|
+
CREATE TABLE IF NOT EXISTS app_config (
|
|
96
|
+
key TEXT PRIMARY KEY,
|
|
97
|
+
value TEXT NOT NULL,
|
|
98
|
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
99
|
+
);
|
|
@@ -0,0 +1,460 @@
|
|
|
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 { createNormalizedMessage } from './providers/types.js';
|
|
13
|
+
|
|
14
|
+
let activeGeminiProcesses = new Map(); // Track active processes by session ID
|
|
15
|
+
|
|
16
|
+
async function spawnGemini(command, options = {}, ws) {
|
|
17
|
+
const { sessionId, projectPath, cwd, toolsSettings, permissionMode, images, sessionSummary } = options;
|
|
18
|
+
let capturedSessionId = sessionId; // Track session ID throughout the process
|
|
19
|
+
let sessionCreatedSent = false; // Track if we've already sent session-created event
|
|
20
|
+
let assistantBlocks = []; // Accumulate the full response blocks including tools
|
|
21
|
+
|
|
22
|
+
// Use tools settings passed from frontend, or defaults
|
|
23
|
+
const settings = toolsSettings || {
|
|
24
|
+
allowedTools: [],
|
|
25
|
+
disallowedTools: [],
|
|
26
|
+
skipPermissions: false
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
// Build Gemini CLI command - start with print/resume flags first
|
|
30
|
+
const args = [];
|
|
31
|
+
|
|
32
|
+
// Add prompt flag with command if we have a command
|
|
33
|
+
if (command && command.trim()) {
|
|
34
|
+
args.push('--prompt', command);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// If we have a sessionId, we want to resume
|
|
38
|
+
if (sessionId) {
|
|
39
|
+
const session = sessionManager.getSession(sessionId);
|
|
40
|
+
if (session && session.cliSessionId) {
|
|
41
|
+
args.push('--resume', session.cliSessionId);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Use cwd (actual project directory) instead of projectPath (Gemini's metadata directory)
|
|
46
|
+
// Clean the path by removing any non-printable characters
|
|
47
|
+
const cleanPath = (cwd || projectPath || process.cwd()).replace(/[^\x20-\x7E]/g, '').trim();
|
|
48
|
+
const workingDir = cleanPath;
|
|
49
|
+
|
|
50
|
+
// Handle images by saving them to temporary files and passing paths to Gemini
|
|
51
|
+
const tempImagePaths = [];
|
|
52
|
+
let tempDir = null;
|
|
53
|
+
if (images && images.length > 0) {
|
|
54
|
+
try {
|
|
55
|
+
// Create temp directory in the project directory so Gemini can access it
|
|
56
|
+
tempDir = path.join(workingDir, '.tmp', 'images', Date.now().toString());
|
|
57
|
+
await fs.mkdir(tempDir, { recursive: true });
|
|
58
|
+
|
|
59
|
+
// Save each image to a temp file
|
|
60
|
+
for (const [index, image] of images.entries()) {
|
|
61
|
+
// Extract base64 data and mime type
|
|
62
|
+
const matches = image.data.match(/^data:([^;]+);base64,(.+)$/);
|
|
63
|
+
if (!matches) {
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const [, mimeType, base64Data] = matches;
|
|
68
|
+
const extension = mimeType.split('/')[1] || 'png';
|
|
69
|
+
const filename = `image_${index}.${extension}`;
|
|
70
|
+
const filepath = path.join(tempDir, filename);
|
|
71
|
+
|
|
72
|
+
// Write base64 data to file
|
|
73
|
+
await fs.writeFile(filepath, Buffer.from(base64Data, 'base64'));
|
|
74
|
+
tempImagePaths.push(filepath);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Include the full image paths in the prompt for Gemini to reference
|
|
78
|
+
// Gemini CLI can read images from file paths in the prompt
|
|
79
|
+
if (tempImagePaths.length > 0 && command && command.trim()) {
|
|
80
|
+
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')}`;
|
|
81
|
+
const modifiedCommand = command + imageNote;
|
|
82
|
+
|
|
83
|
+
// Update the command in args
|
|
84
|
+
const promptIndex = args.indexOf('--prompt');
|
|
85
|
+
if (promptIndex !== -1 && args[promptIndex + 1] === command) {
|
|
86
|
+
args[promptIndex + 1] = modifiedCommand;
|
|
87
|
+
} else if (promptIndex !== -1) {
|
|
88
|
+
// If we're using context, update the full prompt
|
|
89
|
+
args[promptIndex + 1] = args[promptIndex + 1] + imageNote;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
} catch (error) {
|
|
93
|
+
console.error('Error processing images for Gemini:', error);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// Add basic flags for Gemini
|
|
98
|
+
if (options.debug) {
|
|
99
|
+
args.push('--debug');
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// Add MCP config flag only if MCP servers are configured
|
|
103
|
+
try {
|
|
104
|
+
const geminiConfigPath = path.join(os.homedir(), '.gemini.json');
|
|
105
|
+
let hasMcpServers = false;
|
|
106
|
+
|
|
107
|
+
try {
|
|
108
|
+
await fs.access(geminiConfigPath);
|
|
109
|
+
const geminiConfigRaw = await fs.readFile(geminiConfigPath, 'utf8');
|
|
110
|
+
const geminiConfig = JSON.parse(geminiConfigRaw);
|
|
111
|
+
|
|
112
|
+
// Check global MCP servers
|
|
113
|
+
if (geminiConfig.mcpServers && Object.keys(geminiConfig.mcpServers).length > 0) {
|
|
114
|
+
hasMcpServers = true;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// Check project-specific MCP servers
|
|
118
|
+
if (!hasMcpServers && geminiConfig.geminiProjects) {
|
|
119
|
+
const currentProjectPath = process.cwd();
|
|
120
|
+
const projectConfig = geminiConfig.geminiProjects[currentProjectPath];
|
|
121
|
+
if (projectConfig && projectConfig.mcpServers && Object.keys(projectConfig.mcpServers).length > 0) {
|
|
122
|
+
hasMcpServers = true;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
} catch (e) {
|
|
126
|
+
// Ignore if file doesn't exist or isn't parsable
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
if (hasMcpServers) {
|
|
130
|
+
args.push('--mcp-config', geminiConfigPath);
|
|
131
|
+
}
|
|
132
|
+
} catch (error) {
|
|
133
|
+
// Ignore outer errors
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// Add model for all sessions (both new and resumed)
|
|
137
|
+
let modelToUse = options.model || 'gemini-2.5-flash';
|
|
138
|
+
args.push('--model', modelToUse);
|
|
139
|
+
args.push('--output-format', 'stream-json');
|
|
140
|
+
|
|
141
|
+
// Handle approval modes and allowed tools
|
|
142
|
+
if (settings.skipPermissions || options.skipPermissions || permissionMode === 'yolo') {
|
|
143
|
+
args.push('--yolo');
|
|
144
|
+
} else if (permissionMode === 'auto_edit') {
|
|
145
|
+
args.push('--approval-mode', 'auto_edit');
|
|
146
|
+
} else if (permissionMode === 'plan') {
|
|
147
|
+
args.push('--approval-mode', 'plan');
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
if (settings.allowedTools && settings.allowedTools.length > 0) {
|
|
151
|
+
args.push('--allowed-tools', settings.allowedTools.join(','));
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// Try to find gemini in PATH first, then fall back to environment variable
|
|
155
|
+
const geminiPath = process.env.GEMINI_PATH || 'gemini';
|
|
156
|
+
console.log('Spawning Gemini CLI:', geminiPath, args.join(' '));
|
|
157
|
+
console.log('Working directory:', workingDir);
|
|
158
|
+
|
|
159
|
+
let spawnCmd = geminiPath;
|
|
160
|
+
let spawnArgs = args;
|
|
161
|
+
|
|
162
|
+
// On non-Windows platforms, wrap the execution in a shell to avoid ENOEXEC
|
|
163
|
+
// which happens when the target is a script lacking a shebang.
|
|
164
|
+
if (os.platform() !== 'win32') {
|
|
165
|
+
spawnCmd = 'sh';
|
|
166
|
+
// Use exec to replace the shell process, ensuring signals hit gemini directly
|
|
167
|
+
spawnArgs = ['-c', 'exec "$0" "$@"', geminiPath, ...args];
|
|
168
|
+
}
|
|
169
|
+
return new Promise((resolve, reject) => {
|
|
170
|
+
const envParams = { ...process.env };
|
|
171
|
+
|
|
172
|
+
if (process.env.GEMINI_API_BASE_URL) {
|
|
173
|
+
envParams.GEMINI_BASE_URL = process.env.GEMINI_API_BASE_URL;
|
|
174
|
+
envParams.GOOGLE_GEMINI_BASE_URL = process.env.GEMINI_API_BASE_URL;
|
|
175
|
+
envParams.GOOGLE_API_BASE_URL = process.env.GEMINI_API_BASE_URL;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const geminiProcess = spawnFunction(spawnCmd, spawnArgs, {
|
|
179
|
+
cwd: workingDir,
|
|
180
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
181
|
+
env: envParams // Pass the aggressively overridden proxy configuration
|
|
182
|
+
});
|
|
183
|
+
let terminalNotificationSent = false;
|
|
184
|
+
let terminalFailureReason = null;
|
|
185
|
+
|
|
186
|
+
const notifyTerminalState = ({ code = null, error = null } = {}) => {
|
|
187
|
+
if (terminalNotificationSent) {
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
terminalNotificationSent = true;
|
|
192
|
+
|
|
193
|
+
const finalSessionId = capturedSessionId || sessionId || processKey;
|
|
194
|
+
if (code === 0 && !error) {
|
|
195
|
+
notifyRunStopped({
|
|
196
|
+
userId: ws?.userId || null,
|
|
197
|
+
provider: 'gemini',
|
|
198
|
+
sessionId: finalSessionId,
|
|
199
|
+
sessionName: sessionSummary,
|
|
200
|
+
stopReason: 'completed'
|
|
201
|
+
});
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
notifyRunFailed({
|
|
206
|
+
userId: ws?.userId || null,
|
|
207
|
+
provider: 'gemini',
|
|
208
|
+
sessionId: finalSessionId,
|
|
209
|
+
sessionName: sessionSummary,
|
|
210
|
+
error: error || terminalFailureReason || `Gemini CLI exited with code ${code}`
|
|
211
|
+
});
|
|
212
|
+
};
|
|
213
|
+
|
|
214
|
+
// Attach temp file info to process for cleanup later
|
|
215
|
+
geminiProcess.tempImagePaths = tempImagePaths;
|
|
216
|
+
geminiProcess.tempDir = tempDir;
|
|
217
|
+
|
|
218
|
+
// Store process reference for potential abort
|
|
219
|
+
const processKey = capturedSessionId || sessionId || Date.now().toString();
|
|
220
|
+
activeGeminiProcesses.set(processKey, geminiProcess);
|
|
221
|
+
|
|
222
|
+
// Store sessionId on the process object for debugging
|
|
223
|
+
geminiProcess.sessionId = processKey;
|
|
224
|
+
|
|
225
|
+
// Close stdin to signal we're done sending input
|
|
226
|
+
geminiProcess.stdin.end();
|
|
227
|
+
|
|
228
|
+
// Add timeout handler
|
|
229
|
+
const timeoutMs = 120000; // 120 seconds for slower models
|
|
230
|
+
let timeout;
|
|
231
|
+
|
|
232
|
+
const startTimeout = () => {
|
|
233
|
+
if (timeout) clearTimeout(timeout);
|
|
234
|
+
timeout = setTimeout(() => {
|
|
235
|
+
const socketSessionId = typeof ws.getSessionId === 'function' ? ws.getSessionId() : (capturedSessionId || sessionId || processKey);
|
|
236
|
+
terminalFailureReason = `Gemini CLI timeout - no response received for ${timeoutMs / 1000} seconds`;
|
|
237
|
+
ws.send(createNormalizedMessage({ kind: 'error', content: terminalFailureReason, sessionId: socketSessionId, provider: 'gemini' }));
|
|
238
|
+
try {
|
|
239
|
+
geminiProcess.kill('SIGTERM');
|
|
240
|
+
} catch (e) { }
|
|
241
|
+
}, timeoutMs);
|
|
242
|
+
};
|
|
243
|
+
|
|
244
|
+
startTimeout();
|
|
245
|
+
|
|
246
|
+
// Save user message to session when starting
|
|
247
|
+
if (command && capturedSessionId) {
|
|
248
|
+
sessionManager.addMessage(capturedSessionId, 'user', command);
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// Create response handler for NDJSON buffering
|
|
252
|
+
let responseHandler;
|
|
253
|
+
if (ws) {
|
|
254
|
+
responseHandler = new GeminiResponseHandler(ws, {
|
|
255
|
+
onContentFragment: (content) => {
|
|
256
|
+
if (assistantBlocks.length > 0 && assistantBlocks[assistantBlocks.length - 1].type === 'text') {
|
|
257
|
+
assistantBlocks[assistantBlocks.length - 1].text += content;
|
|
258
|
+
} else {
|
|
259
|
+
assistantBlocks.push({ type: 'text', text: content });
|
|
260
|
+
}
|
|
261
|
+
},
|
|
262
|
+
onToolUse: (event) => {
|
|
263
|
+
assistantBlocks.push({
|
|
264
|
+
type: 'tool_use',
|
|
265
|
+
id: event.tool_id,
|
|
266
|
+
name: event.tool_name,
|
|
267
|
+
input: event.parameters
|
|
268
|
+
});
|
|
269
|
+
},
|
|
270
|
+
onToolResult: (event) => {
|
|
271
|
+
if (capturedSessionId) {
|
|
272
|
+
if (assistantBlocks.length > 0) {
|
|
273
|
+
sessionManager.addMessage(capturedSessionId, 'assistant', [...assistantBlocks]);
|
|
274
|
+
assistantBlocks = [];
|
|
275
|
+
}
|
|
276
|
+
sessionManager.addMessage(capturedSessionId, 'user', [{
|
|
277
|
+
type: 'tool_result',
|
|
278
|
+
tool_use_id: event.tool_id,
|
|
279
|
+
content: event.output === undefined ? null : event.output,
|
|
280
|
+
is_error: event.status === 'error'
|
|
281
|
+
}]);
|
|
282
|
+
}
|
|
283
|
+
},
|
|
284
|
+
onInit: (event) => {
|
|
285
|
+
if (capturedSessionId) {
|
|
286
|
+
const sess = sessionManager.getSession(capturedSessionId);
|
|
287
|
+
if (sess && !sess.cliSessionId) {
|
|
288
|
+
sess.cliSessionId = event.session_id;
|
|
289
|
+
sessionManager.saveSession(capturedSessionId);
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// Handle stdout
|
|
297
|
+
geminiProcess.stdout.on('data', (data) => {
|
|
298
|
+
const rawOutput = data.toString();
|
|
299
|
+
startTimeout(); // Re-arm the timeout
|
|
300
|
+
|
|
301
|
+
// For new sessions, create a session ID FIRST
|
|
302
|
+
if (!sessionId && !sessionCreatedSent && !capturedSessionId) {
|
|
303
|
+
capturedSessionId = `gemini_${Date.now()}`;
|
|
304
|
+
sessionCreatedSent = true;
|
|
305
|
+
|
|
306
|
+
// Create session in session manager
|
|
307
|
+
sessionManager.createSession(capturedSessionId, cwd || process.cwd());
|
|
308
|
+
|
|
309
|
+
// Save the user message now that we have a session ID
|
|
310
|
+
if (command) {
|
|
311
|
+
sessionManager.addMessage(capturedSessionId, 'user', command);
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
// Update process key with captured session ID
|
|
315
|
+
if (processKey !== capturedSessionId) {
|
|
316
|
+
activeGeminiProcesses.delete(processKey);
|
|
317
|
+
activeGeminiProcesses.set(capturedSessionId, geminiProcess);
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
ws.setSessionId && typeof ws.setSessionId === 'function' && ws.setSessionId(capturedSessionId);
|
|
321
|
+
|
|
322
|
+
ws.send(createNormalizedMessage({ kind: 'session_created', newSessionId: capturedSessionId, sessionId: capturedSessionId, provider: 'gemini' }));
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
if (responseHandler) {
|
|
326
|
+
responseHandler.processData(rawOutput);
|
|
327
|
+
} else if (rawOutput) {
|
|
328
|
+
// Fallback to direct sending for raw CLI mode without WS
|
|
329
|
+
if (assistantBlocks.length > 0 && assistantBlocks[assistantBlocks.length - 1].type === 'text') {
|
|
330
|
+
assistantBlocks[assistantBlocks.length - 1].text += rawOutput;
|
|
331
|
+
} else {
|
|
332
|
+
assistantBlocks.push({ type: 'text', text: rawOutput });
|
|
333
|
+
}
|
|
334
|
+
const socketSessionId = typeof ws.getSessionId === 'function' ? ws.getSessionId() : (capturedSessionId || sessionId);
|
|
335
|
+
ws.send(createNormalizedMessage({ kind: 'stream_delta', content: rawOutput, sessionId: socketSessionId, provider: 'gemini' }));
|
|
336
|
+
}
|
|
337
|
+
});
|
|
338
|
+
|
|
339
|
+
// Handle stderr
|
|
340
|
+
geminiProcess.stderr.on('data', (data) => {
|
|
341
|
+
const errorMsg = data.toString();
|
|
342
|
+
|
|
343
|
+
// Filter out deprecation warnings and "Loaded cached credentials" message
|
|
344
|
+
if (errorMsg.includes('[DEP0040]') ||
|
|
345
|
+
errorMsg.includes('DeprecationWarning') ||
|
|
346
|
+
errorMsg.includes('--trace-deprecation') ||
|
|
347
|
+
errorMsg.includes('Loaded cached credentials')) {
|
|
348
|
+
return;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
const socketSessionId = typeof ws.getSessionId === 'function' ? ws.getSessionId() : (capturedSessionId || sessionId);
|
|
352
|
+
ws.send(createNormalizedMessage({ kind: 'error', content: errorMsg, sessionId: socketSessionId, provider: 'gemini' }));
|
|
353
|
+
});
|
|
354
|
+
|
|
355
|
+
// Handle process completion
|
|
356
|
+
geminiProcess.on('close', async (code) => {
|
|
357
|
+
clearTimeout(timeout);
|
|
358
|
+
|
|
359
|
+
// Flush any remaining buffered content
|
|
360
|
+
if (responseHandler) {
|
|
361
|
+
responseHandler.forceFlush();
|
|
362
|
+
responseHandler.destroy();
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
// Clean up process reference
|
|
366
|
+
const finalSessionId = capturedSessionId || sessionId || processKey;
|
|
367
|
+
activeGeminiProcesses.delete(finalSessionId);
|
|
368
|
+
|
|
369
|
+
// Save assistant response to session if we have one
|
|
370
|
+
if (finalSessionId && assistantBlocks.length > 0) {
|
|
371
|
+
sessionManager.addMessage(finalSessionId, 'assistant', assistantBlocks);
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
ws.send(createNormalizedMessage({ kind: 'complete', exitCode: code, isNewSession: !sessionId && !!command, sessionId: finalSessionId, provider: 'gemini' }));
|
|
375
|
+
|
|
376
|
+
// Clean up temporary image files if any
|
|
377
|
+
if (geminiProcess.tempImagePaths && geminiProcess.tempImagePaths.length > 0) {
|
|
378
|
+
for (const imagePath of geminiProcess.tempImagePaths) {
|
|
379
|
+
await fs.unlink(imagePath).catch(err => { });
|
|
380
|
+
}
|
|
381
|
+
if (geminiProcess.tempDir) {
|
|
382
|
+
await fs.rm(geminiProcess.tempDir, { recursive: true, force: true }).catch(err => { });
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
if (code === 0) {
|
|
387
|
+
notifyTerminalState({ code });
|
|
388
|
+
resolve();
|
|
389
|
+
} else {
|
|
390
|
+
notifyTerminalState({
|
|
391
|
+
code,
|
|
392
|
+
error: code === null ? 'Gemini CLI process was terminated or timed out' : null
|
|
393
|
+
});
|
|
394
|
+
reject(new Error(code === null ? 'Gemini CLI process was terminated or timed out' : `Gemini CLI exited with code ${code}`));
|
|
395
|
+
}
|
|
396
|
+
});
|
|
397
|
+
|
|
398
|
+
// Handle process errors
|
|
399
|
+
geminiProcess.on('error', (error) => {
|
|
400
|
+
// Clean up process reference on error
|
|
401
|
+
const finalSessionId = capturedSessionId || sessionId || processKey;
|
|
402
|
+
activeGeminiProcesses.delete(finalSessionId);
|
|
403
|
+
|
|
404
|
+
const errorSessionId = typeof ws.getSessionId === 'function' ? ws.getSessionId() : finalSessionId;
|
|
405
|
+
ws.send(createNormalizedMessage({ kind: 'error', content: error.message, sessionId: errorSessionId, provider: 'gemini' }));
|
|
406
|
+
notifyTerminalState({ error });
|
|
407
|
+
|
|
408
|
+
reject(error);
|
|
409
|
+
});
|
|
410
|
+
|
|
411
|
+
});
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
function abortGeminiSession(sessionId) {
|
|
415
|
+
let geminiProc = activeGeminiProcesses.get(sessionId);
|
|
416
|
+
let processKey = sessionId;
|
|
417
|
+
|
|
418
|
+
if (!geminiProc) {
|
|
419
|
+
for (const [key, proc] of activeGeminiProcesses.entries()) {
|
|
420
|
+
if (proc.sessionId === sessionId) {
|
|
421
|
+
geminiProc = proc;
|
|
422
|
+
processKey = key;
|
|
423
|
+
break;
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
if (geminiProc) {
|
|
429
|
+
try {
|
|
430
|
+
geminiProc.kill('SIGTERM');
|
|
431
|
+
setTimeout(() => {
|
|
432
|
+
if (activeGeminiProcesses.has(processKey)) {
|
|
433
|
+
try {
|
|
434
|
+
geminiProc.kill('SIGKILL');
|
|
435
|
+
} catch (e) { }
|
|
436
|
+
}
|
|
437
|
+
}, 2000); // Wait 2 seconds before force kill
|
|
438
|
+
|
|
439
|
+
return true;
|
|
440
|
+
} catch (error) {
|
|
441
|
+
return false;
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
return false;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
function isGeminiSessionActive(sessionId) {
|
|
448
|
+
return activeGeminiProcesses.has(sessionId);
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
function getActiveGeminiSessions() {
|
|
452
|
+
return Array.from(activeGeminiProcesses.keys());
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
export {
|
|
456
|
+
spawnGemini,
|
|
457
|
+
abortGeminiSession,
|
|
458
|
+
isGeminiSessionActive,
|
|
459
|
+
getActiveGeminiSessions
|
|
460
|
+
};
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// Gemini Response Handler - JSON Stream processing
|
|
2
|
+
import { geminiAdapter } from './providers/gemini/adapter.js';
|
|
3
|
+
|
|
4
|
+
class GeminiResponseHandler {
|
|
5
|
+
constructor(ws, options = {}) {
|
|
6
|
+
this.ws = ws;
|
|
7
|
+
this.buffer = '';
|
|
8
|
+
this.onContentFragment = options.onContentFragment || null;
|
|
9
|
+
this.onInit = options.onInit || null;
|
|
10
|
+
this.onToolUse = options.onToolUse || null;
|
|
11
|
+
this.onToolResult = options.onToolResult || null;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// Process incoming raw data from Gemini stream-json
|
|
15
|
+
processData(data) {
|
|
16
|
+
this.buffer += data;
|
|
17
|
+
|
|
18
|
+
// Split by newline
|
|
19
|
+
const lines = this.buffer.split('\n');
|
|
20
|
+
|
|
21
|
+
// Keep the last incomplete line in the buffer
|
|
22
|
+
this.buffer = lines.pop() || '';
|
|
23
|
+
|
|
24
|
+
for (const line of lines) {
|
|
25
|
+
if (!line.trim()) continue;
|
|
26
|
+
|
|
27
|
+
try {
|
|
28
|
+
const event = JSON.parse(line);
|
|
29
|
+
this.handleEvent(event);
|
|
30
|
+
} catch (err) {
|
|
31
|
+
// Not a JSON line, probably debug output or CLI warnings
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
handleEvent(event) {
|
|
37
|
+
const sid = typeof this.ws.getSessionId === 'function' ? this.ws.getSessionId() : null;
|
|
38
|
+
|
|
39
|
+
if (event.type === 'init') {
|
|
40
|
+
if (this.onInit) {
|
|
41
|
+
this.onInit(event);
|
|
42
|
+
}
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// Invoke per-type callbacks for session tracking
|
|
47
|
+
if (event.type === 'message' && event.role === 'assistant') {
|
|
48
|
+
const content = event.content || '';
|
|
49
|
+
if (this.onContentFragment && content) {
|
|
50
|
+
this.onContentFragment(content);
|
|
51
|
+
}
|
|
52
|
+
} else if (event.type === 'tool_use' && this.onToolUse) {
|
|
53
|
+
this.onToolUse(event);
|
|
54
|
+
} else if (event.type === 'tool_result' && this.onToolResult) {
|
|
55
|
+
this.onToolResult(event);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Normalize via adapter and send all resulting messages
|
|
59
|
+
const normalized = geminiAdapter.normalizeMessage(event, sid);
|
|
60
|
+
for (const msg of normalized) {
|
|
61
|
+
this.ws.send(msg);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
forceFlush() {
|
|
66
|
+
if (this.buffer.trim()) {
|
|
67
|
+
try {
|
|
68
|
+
const event = JSON.parse(this.buffer);
|
|
69
|
+
this.handleEvent(event);
|
|
70
|
+
} catch (err) { }
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
destroy() {
|
|
75
|
+
this.buffer = '';
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export default GeminiResponseHandler;
|