wherever-dev 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1264 -0
- package/dist/index.js.map +1 -0
- package/dist/protocol.d.ts +157 -0
- package/dist/protocol.d.ts.map +1 -0
- package/dist/protocol.js +2 -0
- package/dist/protocol.js.map +1 -0
- package/dist/session-pool.d.ts +119 -0
- package/dist/session-pool.d.ts.map +1 -0
- package/dist/session-pool.js +909 -0
- package/dist/session-pool.js.map +1 -0
- package/dist/session-types.d.ts +44 -0
- package/dist/session-types.d.ts.map +1 -0
- package/dist/session-types.js +2 -0
- package/dist/session-types.js.map +1 -0
- package/package.json +42 -0
- package/public/_app/env.js +1 -0
- package/public/_app/immutable/assets/0.DvZxoQjW.css +2754 -0
- package/public/_app/immutable/chunks/B5WJGjcR.js +23 -0
- package/public/_app/immutable/chunks/B5WJGjcR.js.map +1 -0
- package/public/_app/immutable/chunks/BEWoN05F.js +110 -0
- package/public/_app/immutable/chunks/BEWoN05F.js.map +1 -0
- package/public/_app/immutable/chunks/BqMutrfe.js +2129 -0
- package/public/_app/immutable/chunks/BqMutrfe.js.map +1 -0
- package/public/_app/immutable/chunks/DFxBx2vA.js +897 -0
- package/public/_app/immutable/chunks/DFxBx2vA.js.map +1 -0
- package/public/_app/immutable/chunks/DiYtJzYU.js +396 -0
- package/public/_app/immutable/chunks/DiYtJzYU.js.map +1 -0
- package/public/_app/immutable/chunks/_lppinj8.js +879 -0
- package/public/_app/immutable/chunks/_lppinj8.js.map +1 -0
- package/public/_app/immutable/chunks/rMw82gDs.js +3048 -0
- package/public/_app/immutable/chunks/rMw82gDs.js.map +1 -0
- package/public/_app/immutable/entry/app.BFki2czn.js +309 -0
- package/public/_app/immutable/entry/app.BFki2czn.js.map +1 -0
- package/public/_app/immutable/entry/start.BceUuq27.js +6 -0
- package/public/_app/immutable/entry/start.BceUuq27.js.map +1 -0
- package/public/_app/immutable/nodes/0.BzvDOlXz.js +546 -0
- package/public/_app/immutable/nodes/0.BzvDOlXz.js.map +1 -0
- package/public/_app/immutable/nodes/1.DMtW3tA5.js +24 -0
- package/public/_app/immutable/nodes/1.DMtW3tA5.js.map +1 -0
- package/public/_app/immutable/nodes/2.CnZp8abw.js +5152 -0
- package/public/_app/immutable/nodes/2.CnZp8abw.js.map +1 -0
- package/public/_app/version.json +1 -0
- package/public/icon.png +0 -0
- package/public/index.html +84 -0
- package/public/logo.svg +52 -0
- package/public/pwa/apple-touch-icon.png +0 -0
- package/public/pwa/favicon-192.png +0 -0
- package/public/pwa/favicon-512.png +0 -0
- package/public/pwa/favicon.ico +0 -0
- package/public/pwa/favicon.png +0 -0
- package/public/pwa/manifest.webmanifest +27 -0
- package/public/service-worker.js +305 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1264 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createServer as createHttpServer } from 'node:http';
|
|
3
|
+
import { createServer as createHttpsServer, request as httpRequest } from 'node:https';
|
|
4
|
+
import { WebSocketServer, WebSocket } from 'ws';
|
|
5
|
+
import { SessionPool, getWhereverConfig } from './session-pool.js';
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { fileURLToPath } from 'node:url';
|
|
9
|
+
import os from 'node:os';
|
|
10
|
+
import { execSync } from 'node:child_process';
|
|
11
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
12
|
+
const __dirname = path.dirname(__filename);
|
|
13
|
+
const devStaticPath = path.resolve(__dirname, '../../web/build');
|
|
14
|
+
const prodStaticPath = path.resolve(__dirname, '../public');
|
|
15
|
+
const staticDir = fs.existsSync(devStaticPath) ? devStaticPath : prodStaticPath;
|
|
16
|
+
function serveStaticFile(reqPath, res) {
|
|
17
|
+
let filePath = path.join(staticDir, reqPath === '/' ? 'index.html' : reqPath);
|
|
18
|
+
if (!filePath.startsWith(staticDir)) {
|
|
19
|
+
res.writeHead(403);
|
|
20
|
+
res.end('Forbidden');
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
if (fs.existsSync(filePath) && fs.statSync(filePath).isDirectory()) {
|
|
24
|
+
filePath = path.join(filePath, 'index.html');
|
|
25
|
+
}
|
|
26
|
+
if (!fs.existsSync(filePath)) {
|
|
27
|
+
filePath = path.join(staticDir, 'index.html');
|
|
28
|
+
}
|
|
29
|
+
const ext = path.extname(filePath).toLowerCase();
|
|
30
|
+
const mimeTypes = {
|
|
31
|
+
'.html': 'text/html',
|
|
32
|
+
'.js': 'text/javascript',
|
|
33
|
+
'.css': 'text/css',
|
|
34
|
+
'.json': 'application/json',
|
|
35
|
+
'.png': 'image/png',
|
|
36
|
+
'.jpg': 'image/jpeg',
|
|
37
|
+
'.gif': 'image/gif',
|
|
38
|
+
'.svg': 'image/svg+xml',
|
|
39
|
+
'.ico': 'image/x-icon',
|
|
40
|
+
'.wasm': 'application/wasm'
|
|
41
|
+
};
|
|
42
|
+
const contentType = mimeTypes[ext] || 'application/octet-stream';
|
|
43
|
+
fs.readFile(filePath, (err, data) => {
|
|
44
|
+
if (err) {
|
|
45
|
+
res.writeHead(500);
|
|
46
|
+
res.end(`Server Error: ${err.code}`);
|
|
47
|
+
}
|
|
48
|
+
else {
|
|
49
|
+
res.writeHead(200, { 'Content-Type': contentType });
|
|
50
|
+
res.end(data);
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
function generateId() {
|
|
55
|
+
return Math.random().toString(36).substring(2) + Date.now().toString(36);
|
|
56
|
+
}
|
|
57
|
+
function parseArgs() {
|
|
58
|
+
const args = process.argv.slice(2);
|
|
59
|
+
let port = parseInt(process.env.PI_REMOTE_PORT || '31415', 10);
|
|
60
|
+
let host = process.env.PI_REMOTE_HOST || '127.0.0.1';
|
|
61
|
+
let token = process.env.PI_REMOTE_TOKEN || undefined;
|
|
62
|
+
let idleTimeout = parseInt(process.env.PI_IDLE_TIMEOUT || '300000', 10);
|
|
63
|
+
let sslKey = process.env.PI_REMOTE_SSL_KEY || undefined;
|
|
64
|
+
let sslCert = process.env.PI_REMOTE_SSL_CERT || undefined;
|
|
65
|
+
let noSsl = process.env.PI_REMOTE_NO_SSL === 'true' || process.env.PI_REMOTE_HTTP === 'true';
|
|
66
|
+
for (let i = 0; i < args.length; i++) {
|
|
67
|
+
switch (args[i]) {
|
|
68
|
+
case '--port':
|
|
69
|
+
port = parseInt(args[++i] || '31415', 10);
|
|
70
|
+
break;
|
|
71
|
+
case '--host':
|
|
72
|
+
host = args[++i] || '127.0.0.1';
|
|
73
|
+
break;
|
|
74
|
+
case '--token':
|
|
75
|
+
token = args[++i];
|
|
76
|
+
break;
|
|
77
|
+
case '--idle-timeout':
|
|
78
|
+
idleTimeout = parseInt(args[++i] || '300000', 10);
|
|
79
|
+
break;
|
|
80
|
+
case '--ssl-key':
|
|
81
|
+
sslKey = args[++i];
|
|
82
|
+
break;
|
|
83
|
+
case '--ssl-cert':
|
|
84
|
+
sslCert = args[++i];
|
|
85
|
+
break;
|
|
86
|
+
case '--no-ssl':
|
|
87
|
+
case '--http':
|
|
88
|
+
noSsl = true;
|
|
89
|
+
break;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return { port, host, token, idleTimeout, sslKey, sslCert, noSsl };
|
|
93
|
+
}
|
|
94
|
+
function authenticate(req, token) {
|
|
95
|
+
if (!token)
|
|
96
|
+
return true;
|
|
97
|
+
const url = new URL(req.url || '', `http://${req.headers.host || 'localhost'}`);
|
|
98
|
+
const provided = url.searchParams.get('token') || req.headers.authorization?.replace('Bearer ', '') || '';
|
|
99
|
+
return provided === token;
|
|
100
|
+
}
|
|
101
|
+
function resolveUploadDir(config, cwd) {
|
|
102
|
+
const type = config.uploads?.type || 'tmp';
|
|
103
|
+
if (type === 'session' && cwd) {
|
|
104
|
+
const subDir = config.uploads?.subDir || '.wherever/uploads';
|
|
105
|
+
const resolved = path.resolve(cwd, subDir);
|
|
106
|
+
return resolved;
|
|
107
|
+
}
|
|
108
|
+
if (type === 'custom' && config.uploads?.dir) {
|
|
109
|
+
let customDir = config.uploads.dir;
|
|
110
|
+
if (customDir.startsWith('~')) {
|
|
111
|
+
customDir = path.join(os.homedir(), customDir.slice(1));
|
|
112
|
+
}
|
|
113
|
+
return path.resolve(customDir);
|
|
114
|
+
}
|
|
115
|
+
// Default to tmp
|
|
116
|
+
return os.tmpdir();
|
|
117
|
+
}
|
|
118
|
+
function sendJSON(res, status, data) {
|
|
119
|
+
res.writeHead(status, { 'Content-Type': 'application/json' });
|
|
120
|
+
res.end(JSON.stringify(data));
|
|
121
|
+
}
|
|
122
|
+
function readBody(req, maxLimitBytes = 1e6) {
|
|
123
|
+
return new Promise((resolve, reject) => {
|
|
124
|
+
let body = '';
|
|
125
|
+
req.on('data', (chunk) => {
|
|
126
|
+
body += chunk.toString();
|
|
127
|
+
if (body.length > maxLimitBytes) {
|
|
128
|
+
req.destroy();
|
|
129
|
+
reject(new Error('Payload too large'));
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
req.on('end', () => resolve(body));
|
|
133
|
+
req.on('error', (err) => reject(err));
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
function sendWS(ws, msg) {
|
|
137
|
+
if (ws.readyState === WebSocket.OPEN) {
|
|
138
|
+
try {
|
|
139
|
+
ws.send(JSON.stringify(msg));
|
|
140
|
+
}
|
|
141
|
+
catch (err) {
|
|
142
|
+
console.error('Failed to send WS message:', err);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
async function main() {
|
|
147
|
+
const { port, host, token, idleTimeout, sslKey, sslCert, noSsl } = parseArgs();
|
|
148
|
+
const sessionPool = new SessionPool(idleTimeout);
|
|
149
|
+
await sessionPool.initialize();
|
|
150
|
+
const clients = new Map();
|
|
151
|
+
let actualSslKey = sslKey;
|
|
152
|
+
let actualSslCert = sslCert;
|
|
153
|
+
let isSecure = !noSsl;
|
|
154
|
+
if (isSecure) {
|
|
155
|
+
if (!actualSslKey || !actualSslCert) {
|
|
156
|
+
// Automatic self-signed certificate generation
|
|
157
|
+
const homeDir = os.homedir();
|
|
158
|
+
const certsDir = path.join(homeDir, '.wherever', 'certs');
|
|
159
|
+
const defaultKeyPath = path.join(certsDir, 'localhost.key');
|
|
160
|
+
const defaultCertPath = path.join(certsDir, 'localhost.crt');
|
|
161
|
+
if (!fs.existsSync(defaultKeyPath) || !fs.existsSync(defaultCertPath)) {
|
|
162
|
+
console.log('Generating self-signed SSL certificates for secure HTTPS/WSS...');
|
|
163
|
+
try {
|
|
164
|
+
fs.mkdirSync(certsDir, { recursive: true });
|
|
165
|
+
const cmd = `openssl req -x509 -newkey rsa:2048 -keyout "${defaultKeyPath}" -out "${defaultCertPath}" -sha256 -days 3650 -nodes -subj "/CN=localhost"`;
|
|
166
|
+
execSync(cmd, { stdio: 'ignore' });
|
|
167
|
+
console.log(`Self-signed certificates generated successfully in ${certsDir}`);
|
|
168
|
+
}
|
|
169
|
+
catch (err) {
|
|
170
|
+
console.warn('Failed to generate self-signed certificates using OpenSSL. Falling back to HTTP.', err.message);
|
|
171
|
+
isSecure = false;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
if (isSecure) {
|
|
175
|
+
actualSslKey = defaultKeyPath;
|
|
176
|
+
actualSslCert = defaultCertPath;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
function broadcastToSession(sessionFile, msg, excludeClientId) {
|
|
181
|
+
const tracked = sessionPool.getSession(sessionFile);
|
|
182
|
+
if (!tracked)
|
|
183
|
+
return;
|
|
184
|
+
for (const cid of tracked.clients) {
|
|
185
|
+
if (cid === excludeClientId)
|
|
186
|
+
continue;
|
|
187
|
+
const c = clients.get(cid);
|
|
188
|
+
if (c)
|
|
189
|
+
sendWS(c.ws, msg);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
function broadcastSessionsUpdated() {
|
|
193
|
+
const updateMsg = { type: 'sessions_updated' };
|
|
194
|
+
for (const c of clients.values()) {
|
|
195
|
+
sendWS(c.ws, updateMsg);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
function broadcastAgentEvent(sessionFile, event) {
|
|
199
|
+
let msg = null;
|
|
200
|
+
const sessionId = sessionPool.getSession(sessionFile)?.sessionId || '';
|
|
201
|
+
switch (event.type) {
|
|
202
|
+
case 'agent_start':
|
|
203
|
+
msg = { type: 'agent_start', sessionId };
|
|
204
|
+
break;
|
|
205
|
+
case 'message_update': {
|
|
206
|
+
if (event.message.role !== 'assistant')
|
|
207
|
+
break;
|
|
208
|
+
const evt = event.assistantMessageEvent;
|
|
209
|
+
if (evt?.type === 'text_delta') {
|
|
210
|
+
msg = { type: 'message_update', sessionId, delta: evt.delta };
|
|
211
|
+
}
|
|
212
|
+
else if (evt?.type === 'thinking_delta') {
|
|
213
|
+
msg = { type: 'thinking_update', sessionId, delta: evt.delta };
|
|
214
|
+
}
|
|
215
|
+
break;
|
|
216
|
+
}
|
|
217
|
+
case 'message_end': {
|
|
218
|
+
const role = event.message?.role;
|
|
219
|
+
if (role !== 'assistant' && role !== 'user')
|
|
220
|
+
break;
|
|
221
|
+
const content = extractText(event.message);
|
|
222
|
+
msg = { type: 'message_end', sessionId, content, role };
|
|
223
|
+
break;
|
|
224
|
+
}
|
|
225
|
+
case 'agent_end': {
|
|
226
|
+
msg = { type: 'agent_end', sessionId };
|
|
227
|
+
const messages = event.messages;
|
|
228
|
+
if (Array.isArray(messages) && messages.length > 0) {
|
|
229
|
+
const lastMsg = messages[messages.length - 1];
|
|
230
|
+
if (lastMsg && lastMsg.stopReason === 'error' && lastMsg.errorMessage) {
|
|
231
|
+
// Send a session_error message to all clients of this session
|
|
232
|
+
const errMsg = {
|
|
233
|
+
type: 'session_error',
|
|
234
|
+
sessionId,
|
|
235
|
+
error: lastMsg.errorMessage
|
|
236
|
+
};
|
|
237
|
+
for (const c of clients.values()) {
|
|
238
|
+
if (c.sessionId === sessionFile) {
|
|
239
|
+
sendWS(c.ws, errMsg);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
break;
|
|
245
|
+
}
|
|
246
|
+
case 'auto_retry_start': {
|
|
247
|
+
const evt = event;
|
|
248
|
+
const errMsg = {
|
|
249
|
+
type: 'session_error',
|
|
250
|
+
sessionId,
|
|
251
|
+
error: `Error: ${evt.errorMessage}. Retrying (attempt ${evt.attempt}/${evt.maxAttempts}) in ${Math.round(evt.delayMs / 1000)}s...`
|
|
252
|
+
};
|
|
253
|
+
for (const c of clients.values()) {
|
|
254
|
+
if (c.sessionId === sessionFile) {
|
|
255
|
+
sendWS(c.ws, errMsg);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
break;
|
|
259
|
+
}
|
|
260
|
+
case 'auto_retry_end': {
|
|
261
|
+
const evt = event;
|
|
262
|
+
if (!evt.success && evt.finalError) {
|
|
263
|
+
const errMsg = {
|
|
264
|
+
type: 'session_error',
|
|
265
|
+
sessionId,
|
|
266
|
+
error: `Retry failed: ${evt.finalError}`
|
|
267
|
+
};
|
|
268
|
+
for (const c of clients.values()) {
|
|
269
|
+
if (c.sessionId === sessionFile) {
|
|
270
|
+
sendWS(c.ws, errMsg);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
else if (evt.success) {
|
|
275
|
+
for (const c of clients.values()) {
|
|
276
|
+
if (c.sessionId === sessionFile) {
|
|
277
|
+
sendWS(c.ws, { type: 'session_error', sessionId, error: '' });
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
break;
|
|
282
|
+
}
|
|
283
|
+
case 'tool_execution_start':
|
|
284
|
+
msg = { type: 'tool_start', sessionId, toolName: event.toolName, args: event.args };
|
|
285
|
+
break;
|
|
286
|
+
case 'tool_execution_update': {
|
|
287
|
+
const evt = event;
|
|
288
|
+
msg = { type: 'tool_update', sessionId, toolName: event.toolName, delta: evt.delta || '' };
|
|
289
|
+
break;
|
|
290
|
+
}
|
|
291
|
+
case 'tool_execution_end':
|
|
292
|
+
const toolResult = extractToolResult(event);
|
|
293
|
+
msg = { type: 'tool_end', sessionId, toolName: event.toolName, isError: event.isError, result: toolResult };
|
|
294
|
+
break;
|
|
295
|
+
case 'model_select': {
|
|
296
|
+
const evt = event;
|
|
297
|
+
const modelStr = typeof evt.model === 'string'
|
|
298
|
+
? evt.model
|
|
299
|
+
: (evt.model ? `${evt.model.provider}:${evt.model.id}` : '');
|
|
300
|
+
if (modelStr) {
|
|
301
|
+
msg = { type: 'model_changed', sessionId, model: modelStr };
|
|
302
|
+
}
|
|
303
|
+
break;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
if (msg) {
|
|
307
|
+
for (const c of clients.values()) {
|
|
308
|
+
if (c.sessionId === sessionFile) {
|
|
309
|
+
sendWS(c.ws, msg);
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
if (event.type === 'message_end' || event.type === 'agent_end') {
|
|
314
|
+
broadcastSessionsUpdated();
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
sessionPool.onEvent = broadcastAgentEvent;
|
|
318
|
+
const requestHandler = async (req, res) => {
|
|
319
|
+
res.setHeader('Access-Control-Allow-Origin', '*');
|
|
320
|
+
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
|
|
321
|
+
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
|
|
322
|
+
if (req.method === 'OPTIONS') {
|
|
323
|
+
res.writeHead(200);
|
|
324
|
+
res.end();
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
const url = new URL(req.url || '', `http://${req.headers.host || 'localhost'}`);
|
|
328
|
+
const pathname = url.pathname;
|
|
329
|
+
if (pathname === '/health') {
|
|
330
|
+
sendJSON(res, 200, { status: 'ok', timestamp: Date.now() });
|
|
331
|
+
return;
|
|
332
|
+
}
|
|
333
|
+
const isApiRequest = pathname.startsWith('/sessions') ||
|
|
334
|
+
pathname.startsWith('/models') ||
|
|
335
|
+
pathname.startsWith('/config') ||
|
|
336
|
+
pathname.startsWith('/check-path') ||
|
|
337
|
+
pathname.startsWith('/autocomplete-path') ||
|
|
338
|
+
pathname.startsWith('/session/');
|
|
339
|
+
if (isApiRequest && !authenticate(req, token)) {
|
|
340
|
+
sendJSON(res, 401, { error: 'Unauthorized' });
|
|
341
|
+
return;
|
|
342
|
+
}
|
|
343
|
+
if (pathname === '/sessions' && req.method === 'GET') {
|
|
344
|
+
const folders = await sessionPool.listSessions();
|
|
345
|
+
const active = sessionPool.getActiveSessions();
|
|
346
|
+
sendJSON(res, 200, { folders, activeSessions: active });
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
if (pathname === '/models' && req.method === 'GET') {
|
|
350
|
+
const models = sessionPool.getAvailableModels();
|
|
351
|
+
sendJSON(res, 200, { models });
|
|
352
|
+
return;
|
|
353
|
+
}
|
|
354
|
+
if (pathname === '/config' && req.method === 'GET') {
|
|
355
|
+
const config = getWhereverConfig();
|
|
356
|
+
sendJSON(res, 200, {
|
|
357
|
+
gitInitDefault: !!config.gitInitDefault,
|
|
358
|
+
uploadMethod: config.uploads?.method || 'websocket'
|
|
359
|
+
});
|
|
360
|
+
return;
|
|
361
|
+
}
|
|
362
|
+
if (pathname === '/check-path' && req.method === 'GET') {
|
|
363
|
+
const qPath = url.searchParams.get('path');
|
|
364
|
+
if (!qPath) {
|
|
365
|
+
sendJSON(res, 400, { error: 'Missing path' });
|
|
366
|
+
return;
|
|
367
|
+
}
|
|
368
|
+
let resolved = qPath;
|
|
369
|
+
if (qPath.startsWith('~')) {
|
|
370
|
+
resolved = path.join(os.homedir(), qPath.slice(1));
|
|
371
|
+
}
|
|
372
|
+
else if (!path.isAbsolute(qPath)) {
|
|
373
|
+
resolved = path.join(os.homedir(), qPath);
|
|
374
|
+
}
|
|
375
|
+
else {
|
|
376
|
+
resolved = path.resolve(qPath);
|
|
377
|
+
}
|
|
378
|
+
const exists = fs.existsSync(resolved);
|
|
379
|
+
let isGit = false;
|
|
380
|
+
if (exists) {
|
|
381
|
+
isGit = fs.existsSync(path.join(resolved, '.git'));
|
|
382
|
+
}
|
|
383
|
+
// Check matching remote rules
|
|
384
|
+
let matchingRule = null;
|
|
385
|
+
const config = getWhereverConfig();
|
|
386
|
+
if (config.remoteRepoRules && Array.isArray(config.remoteRepoRules)) {
|
|
387
|
+
const rule = config.remoteRepoRules.find(r => new RegExp(r.pattern).test(resolved));
|
|
388
|
+
if (rule) {
|
|
389
|
+
matchingRule = {
|
|
390
|
+
provider: rule.provider,
|
|
391
|
+
visibility: rule.visibility || 'private'
|
|
392
|
+
};
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
sendJSON(res, 200, { exists, isGit, resolvedPath: resolved, matchingRule });
|
|
396
|
+
return;
|
|
397
|
+
}
|
|
398
|
+
if (pathname === '/autocomplete-path' && req.method === 'GET') {
|
|
399
|
+
const qPath = url.searchParams.get('path') || '';
|
|
400
|
+
let parentPath = '';
|
|
401
|
+
let prefix = '';
|
|
402
|
+
const lastSlashIndex = qPath.lastIndexOf('/');
|
|
403
|
+
if (lastSlashIndex === -1) {
|
|
404
|
+
parentPath = '~';
|
|
405
|
+
prefix = qPath;
|
|
406
|
+
}
|
|
407
|
+
else {
|
|
408
|
+
parentPath = qPath.slice(0, lastSlashIndex + 1);
|
|
409
|
+
prefix = qPath.slice(lastSlashIndex + 1);
|
|
410
|
+
}
|
|
411
|
+
let resolvedParent = parentPath;
|
|
412
|
+
if (parentPath.startsWith('~')) {
|
|
413
|
+
resolvedParent = path.join(os.homedir(), parentPath.slice(1));
|
|
414
|
+
}
|
|
415
|
+
else if (!path.isAbsolute(parentPath)) {
|
|
416
|
+
resolvedParent = path.join(os.homedir(), parentPath);
|
|
417
|
+
}
|
|
418
|
+
else {
|
|
419
|
+
resolvedParent = path.resolve(parentPath);
|
|
420
|
+
}
|
|
421
|
+
const config = getWhereverConfig();
|
|
422
|
+
// Resolve the query path
|
|
423
|
+
let resolvedQuery = qPath;
|
|
424
|
+
if (qPath.startsWith('~')) {
|
|
425
|
+
resolvedQuery = path.join(os.homedir(), qPath.slice(1));
|
|
426
|
+
}
|
|
427
|
+
else if (!path.isAbsolute(qPath)) {
|
|
428
|
+
resolvedQuery = path.join(os.homedir(), qPath);
|
|
429
|
+
}
|
|
430
|
+
else {
|
|
431
|
+
resolvedQuery = path.resolve(qPath);
|
|
432
|
+
}
|
|
433
|
+
const resolvedQueryLower = resolvedQuery.toLowerCase();
|
|
434
|
+
// Format matched common folder to match the user's input prefix style
|
|
435
|
+
const formatCommonFolder = (folderPath) => {
|
|
436
|
+
let resolved = folderPath;
|
|
437
|
+
if (folderPath.startsWith('~')) {
|
|
438
|
+
resolved = path.join(os.homedir(), folderPath.slice(1));
|
|
439
|
+
}
|
|
440
|
+
else if (!path.isAbsolute(folderPath)) {
|
|
441
|
+
resolved = path.join(os.homedir(), folderPath);
|
|
442
|
+
}
|
|
443
|
+
else {
|
|
444
|
+
resolved = path.resolve(folderPath);
|
|
445
|
+
}
|
|
446
|
+
// Apply trailing slash if missing
|
|
447
|
+
if (!resolved.endsWith('/')) {
|
|
448
|
+
resolved = resolved + '/';
|
|
449
|
+
}
|
|
450
|
+
if (qPath.startsWith('~')) {
|
|
451
|
+
const home = os.homedir() + '/';
|
|
452
|
+
if (resolved.startsWith(home)) {
|
|
453
|
+
return '~/' + resolved.slice(home.length);
|
|
454
|
+
}
|
|
455
|
+
return resolved;
|
|
456
|
+
}
|
|
457
|
+
else if (qPath.startsWith('/')) {
|
|
458
|
+
return resolved;
|
|
459
|
+
}
|
|
460
|
+
else {
|
|
461
|
+
const home = os.homedir() + '/';
|
|
462
|
+
if (resolved.startsWith(home)) {
|
|
463
|
+
return resolved.slice(home.length);
|
|
464
|
+
}
|
|
465
|
+
return resolved;
|
|
466
|
+
}
|
|
467
|
+
};
|
|
468
|
+
// Filter and format matching common folders
|
|
469
|
+
const matchingCommons = (config.commonFolders || [])
|
|
470
|
+
.filter(folder => {
|
|
471
|
+
let resolved = folder;
|
|
472
|
+
if (folder.startsWith('~')) {
|
|
473
|
+
resolved = path.join(os.homedir(), folder.slice(1));
|
|
474
|
+
}
|
|
475
|
+
else if (!path.isAbsolute(folder)) {
|
|
476
|
+
resolved = path.join(os.homedir(), folder);
|
|
477
|
+
}
|
|
478
|
+
else {
|
|
479
|
+
resolved = path.resolve(folder);
|
|
480
|
+
}
|
|
481
|
+
return resolved.toLowerCase().startsWith(resolvedQueryLower);
|
|
482
|
+
})
|
|
483
|
+
.map(folder => formatCommonFolder(folder));
|
|
484
|
+
try {
|
|
485
|
+
if (!fs.existsSync(resolvedParent)) {
|
|
486
|
+
sendJSON(res, 200, { completions: matchingCommons });
|
|
487
|
+
return;
|
|
488
|
+
}
|
|
489
|
+
const stat = fs.statSync(resolvedParent);
|
|
490
|
+
if (!stat.isDirectory()) {
|
|
491
|
+
sendJSON(res, 200, { completions: matchingCommons });
|
|
492
|
+
return;
|
|
493
|
+
}
|
|
494
|
+
const entries = fs.readdirSync(resolvedParent, { withFileTypes: true });
|
|
495
|
+
const actualCompletionsWithStats = entries
|
|
496
|
+
.filter(entry => {
|
|
497
|
+
if (!entry.isDirectory())
|
|
498
|
+
return false;
|
|
499
|
+
if (entry.name.startsWith('.') && !prefix.startsWith('.'))
|
|
500
|
+
return false;
|
|
501
|
+
return entry.name.toLowerCase().startsWith(prefix.toLowerCase());
|
|
502
|
+
})
|
|
503
|
+
.map(entry => {
|
|
504
|
+
const entryPath = path.join(resolvedParent, entry.name);
|
|
505
|
+
let mtimeMs = 0;
|
|
506
|
+
try {
|
|
507
|
+
mtimeMs = fs.statSync(entryPath).mtimeMs;
|
|
508
|
+
}
|
|
509
|
+
catch (e) {
|
|
510
|
+
// Ignore stats errors
|
|
511
|
+
}
|
|
512
|
+
return {
|
|
513
|
+
name: entry.name,
|
|
514
|
+
mtimeMs
|
|
515
|
+
};
|
|
516
|
+
});
|
|
517
|
+
// Sort by mtimeMs descending (most recent first)
|
|
518
|
+
actualCompletionsWithStats.sort((a, b) => b.mtimeMs - a.mtimeMs);
|
|
519
|
+
const actualCompletions = actualCompletionsWithStats.map(item => {
|
|
520
|
+
let formattedParent = parentPath;
|
|
521
|
+
if (parentPath === '~') {
|
|
522
|
+
formattedParent = '~/';
|
|
523
|
+
}
|
|
524
|
+
return formattedParent + item.name + '/';
|
|
525
|
+
});
|
|
526
|
+
const combined = [...matchingCommons, ...actualCompletions];
|
|
527
|
+
const uniqueCompletions = Array.from(new Set(combined));
|
|
528
|
+
sendJSON(res, 200, { completions: uniqueCompletions });
|
|
529
|
+
}
|
|
530
|
+
catch (e) {
|
|
531
|
+
sendJSON(res, 200, { completions: matchingCommons });
|
|
532
|
+
}
|
|
533
|
+
return;
|
|
534
|
+
}
|
|
535
|
+
if (pathname === '/session/model' && req.method === 'POST') {
|
|
536
|
+
try {
|
|
537
|
+
const body = await readBody(req);
|
|
538
|
+
const { sessionId, model } = JSON.parse(body);
|
|
539
|
+
if (!sessionId || !model) {
|
|
540
|
+
sendJSON(res, 400, { error: 'Missing sessionId or model' });
|
|
541
|
+
return;
|
|
542
|
+
}
|
|
543
|
+
const result = await sessionPool.changeModel(sessionId, model);
|
|
544
|
+
if (result.error) {
|
|
545
|
+
sendJSON(res, 400, { error: result.error });
|
|
546
|
+
}
|
|
547
|
+
else {
|
|
548
|
+
const tracked = sessionPool.getSession(sessionId);
|
|
549
|
+
if (tracked) {
|
|
550
|
+
const wsMsg = {
|
|
551
|
+
type: 'model_changed',
|
|
552
|
+
sessionId: tracked.sessionId,
|
|
553
|
+
model,
|
|
554
|
+
};
|
|
555
|
+
for (const cid of tracked.clients) {
|
|
556
|
+
const c = clients.get(cid);
|
|
557
|
+
if (c)
|
|
558
|
+
sendWS(c.ws, wsMsg);
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
sendJSON(res, 200, { status: 'changed', model });
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
catch (err) {
|
|
565
|
+
sendJSON(res, 400, { error: err.message || 'Invalid request' });
|
|
566
|
+
}
|
|
567
|
+
return;
|
|
568
|
+
}
|
|
569
|
+
if (pathname === '/session/destroy' && req.method === 'POST') {
|
|
570
|
+
try {
|
|
571
|
+
const body = await readBody(req);
|
|
572
|
+
const { sessionId } = JSON.parse(body);
|
|
573
|
+
if (!sessionId) {
|
|
574
|
+
sendJSON(res, 400, { error: 'Missing sessionId' });
|
|
575
|
+
return;
|
|
576
|
+
}
|
|
577
|
+
const tracked = sessionPool.getSession(sessionId);
|
|
578
|
+
if (tracked) {
|
|
579
|
+
const wsMsg = {
|
|
580
|
+
type: 'session_destroyed',
|
|
581
|
+
sessionId: tracked.sessionId,
|
|
582
|
+
reason: 'Session destroyed manually'
|
|
583
|
+
};
|
|
584
|
+
for (const cid of tracked.clients) {
|
|
585
|
+
const c = clients.get(cid);
|
|
586
|
+
if (c) {
|
|
587
|
+
sendWS(c.ws, wsMsg);
|
|
588
|
+
c.sessionId = null;
|
|
589
|
+
c.readOnly = false;
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
sessionPool.destroySession(sessionId, 'manual');
|
|
594
|
+
sendJSON(res, 200, { status: 'destroyed' });
|
|
595
|
+
}
|
|
596
|
+
catch (err) {
|
|
597
|
+
sendJSON(res, 400, { error: err.message || 'Invalid request' });
|
|
598
|
+
}
|
|
599
|
+
return;
|
|
600
|
+
}
|
|
601
|
+
if (pathname === '/session/delete' && req.method === 'POST') {
|
|
602
|
+
try {
|
|
603
|
+
const body = await readBody(req);
|
|
604
|
+
const { sessionFile } = JSON.parse(body);
|
|
605
|
+
if (!sessionFile) {
|
|
606
|
+
sendJSON(res, 400, { error: 'Missing sessionFile' });
|
|
607
|
+
return;
|
|
608
|
+
}
|
|
609
|
+
let resolved = sessionFile;
|
|
610
|
+
if (sessionFile.startsWith('~')) {
|
|
611
|
+
resolved = path.join(os.homedir(), sessionFile.slice(1));
|
|
612
|
+
}
|
|
613
|
+
else if (!path.isAbsolute(sessionFile)) {
|
|
614
|
+
resolved = path.join(os.homedir(), sessionFile);
|
|
615
|
+
}
|
|
616
|
+
else {
|
|
617
|
+
resolved = path.resolve(sessionFile);
|
|
618
|
+
}
|
|
619
|
+
// Security check: only allow deleting files ending with .jsonl
|
|
620
|
+
if (!resolved.endsWith('.jsonl')) {
|
|
621
|
+
sendJSON(res, 400, { error: 'Invalid session file format' });
|
|
622
|
+
return;
|
|
623
|
+
}
|
|
624
|
+
// Get the active session if any, using either the sessionFile path or resolved path
|
|
625
|
+
const tracked = sessionPool.getSession(sessionFile) || sessionPool.getSession(resolved);
|
|
626
|
+
if (tracked) {
|
|
627
|
+
const wsMsg = {
|
|
628
|
+
type: 'session_destroyed',
|
|
629
|
+
sessionId: tracked.sessionId,
|
|
630
|
+
reason: 'Session deleted'
|
|
631
|
+
};
|
|
632
|
+
for (const cid of tracked.clients) {
|
|
633
|
+
const c = clients.get(cid);
|
|
634
|
+
if (c) {
|
|
635
|
+
sendWS(c.ws, wsMsg);
|
|
636
|
+
c.sessionId = null;
|
|
637
|
+
c.readOnly = false;
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
sessionPool.destroySession(tracked.sessionFile, 'deleted');
|
|
641
|
+
}
|
|
642
|
+
if (fs.existsSync(resolved)) {
|
|
643
|
+
fs.unlinkSync(resolved);
|
|
644
|
+
}
|
|
645
|
+
// Broadcast 'sessions_updated' to all connected websocket clients
|
|
646
|
+
const updateMsg = {
|
|
647
|
+
type: 'sessions_updated'
|
|
648
|
+
};
|
|
649
|
+
for (const c of clients.values()) {
|
|
650
|
+
sendWS(c.ws, updateMsg);
|
|
651
|
+
}
|
|
652
|
+
sendJSON(res, 200, { status: 'deleted' });
|
|
653
|
+
}
|
|
654
|
+
catch (err) {
|
|
655
|
+
sendJSON(res, 400, { error: err.message || 'Invalid request' });
|
|
656
|
+
}
|
|
657
|
+
return;
|
|
658
|
+
}
|
|
659
|
+
if (pathname === '/session/new' && req.method === 'POST') {
|
|
660
|
+
try {
|
|
661
|
+
const body = await readBody(req);
|
|
662
|
+
const { cwd, model, gitInit, createRemote, repoVisibility } = JSON.parse(body);
|
|
663
|
+
if (!cwd) {
|
|
664
|
+
sendJSON(res, 400, { error: 'Missing cwd' });
|
|
665
|
+
return;
|
|
666
|
+
}
|
|
667
|
+
const result = await sessionPool.createNewSession(cwd, model, gitInit, createRemote, repoVisibility);
|
|
668
|
+
if (result.error) {
|
|
669
|
+
sendJSON(res, 500, { error: result.error });
|
|
670
|
+
}
|
|
671
|
+
else {
|
|
672
|
+
broadcastSessionsUpdated();
|
|
673
|
+
sendJSON(res, 201, {
|
|
674
|
+
sessionId: result.tracked.sessionId,
|
|
675
|
+
sessionFile: result.tracked.sessionFile,
|
|
676
|
+
cwd: result.tracked.cwd,
|
|
677
|
+
model: result.tracked.model,
|
|
678
|
+
});
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
catch (err) {
|
|
682
|
+
sendJSON(res, 400, { error: err.message || 'Invalid request' });
|
|
683
|
+
}
|
|
684
|
+
return;
|
|
685
|
+
}
|
|
686
|
+
if (pathname === '/session/upload' && req.method === 'POST') {
|
|
687
|
+
try {
|
|
688
|
+
const qSessionId = url.searchParams.get('sessionId') || '';
|
|
689
|
+
const qFilename = url.searchParams.get('filename') || '';
|
|
690
|
+
if (!qSessionId || !qFilename) {
|
|
691
|
+
sendJSON(res, 400, { error: 'Missing sessionId or filename' });
|
|
692
|
+
return;
|
|
693
|
+
}
|
|
694
|
+
const tracked = sessionPool.getSession(qSessionId);
|
|
695
|
+
const cwd = tracked?.cwd;
|
|
696
|
+
const config = getWhereverConfig();
|
|
697
|
+
const targetDir = resolveUploadDir(config, cwd);
|
|
698
|
+
fs.mkdirSync(targetDir, { recursive: true });
|
|
699
|
+
const timestamp = Date.now();
|
|
700
|
+
const safeFilename = `${timestamp}_${path.basename(qFilename)}`;
|
|
701
|
+
const destPath = path.join(targetDir, safeFilename);
|
|
702
|
+
const writeStream = fs.createWriteStream(destPath);
|
|
703
|
+
req.pipe(writeStream);
|
|
704
|
+
writeStream.on('finish', () => {
|
|
705
|
+
sendJSON(res, 200, {
|
|
706
|
+
status: 'uploaded',
|
|
707
|
+
filename: qFilename,
|
|
708
|
+
savedPath: destPath
|
|
709
|
+
});
|
|
710
|
+
});
|
|
711
|
+
writeStream.on('error', (err) => {
|
|
712
|
+
sendJSON(res, 500, { error: `Failed to write file: ${err.message}` });
|
|
713
|
+
});
|
|
714
|
+
}
|
|
715
|
+
catch (err) {
|
|
716
|
+
sendJSON(res, 500, { error: `Upload error: ${err.message}` });
|
|
717
|
+
}
|
|
718
|
+
return;
|
|
719
|
+
}
|
|
720
|
+
if (pathname === '/session/transcribe' && req.method === 'POST') {
|
|
721
|
+
const config = getWhereverConfig();
|
|
722
|
+
const apiKey = config.speech?.apiKey || process.env.SPEECH_API_KEY;
|
|
723
|
+
const apiUrl = config.speech?.apiUrl || process.env.SPEECH_API_URL || 'https://api.z.ai/api/paas/v4/audio/transcriptions';
|
|
724
|
+
const apiModel = config.speech?.model || process.env.SPEECH_MODEL || 'glm-asr-2512';
|
|
725
|
+
if (!apiKey) {
|
|
726
|
+
sendJSON(res, 400, { error: 'Server speech transcription API key not configured' });
|
|
727
|
+
return;
|
|
728
|
+
}
|
|
729
|
+
const chunks = [];
|
|
730
|
+
req.on('data', (chunk) => chunks.push(chunk));
|
|
731
|
+
req.on('end', () => {
|
|
732
|
+
const audioBuffer = Buffer.concat(chunks);
|
|
733
|
+
if (audioBuffer.length === 0) {
|
|
734
|
+
sendJSON(res, 400, { error: 'Empty audio payload' });
|
|
735
|
+
return;
|
|
736
|
+
}
|
|
737
|
+
const boundary = '----SpeechBoundary' + Math.random().toString(16);
|
|
738
|
+
const header = `--${boundary}\r\n` +
|
|
739
|
+
`Content-Disposition: form-data; name="model"\r\n\r\n` +
|
|
740
|
+
`${apiModel}\r\n` +
|
|
741
|
+
`--${boundary}\r\n` +
|
|
742
|
+
`Content-Disposition: form-data; name="file"; filename="audio.wav"\r\n` +
|
|
743
|
+
`Content-Type: audio/wav\r\n\r\n`;
|
|
744
|
+
const footer = `\r\n--${boundary}--\r\n`;
|
|
745
|
+
const headerBuffer = Buffer.from(header, 'utf-8');
|
|
746
|
+
const footerBuffer = Buffer.from(footer, 'utf-8');
|
|
747
|
+
const totalPayload = Buffer.concat([headerBuffer, audioBuffer, footerBuffer]);
|
|
748
|
+
const parsedUrl = new URL(apiUrl);
|
|
749
|
+
const apiReq = httpRequest({
|
|
750
|
+
hostname: parsedUrl.hostname,
|
|
751
|
+
path: parsedUrl.pathname + parsedUrl.search,
|
|
752
|
+
method: 'POST',
|
|
753
|
+
headers: {
|
|
754
|
+
'Authorization': `Bearer ${apiKey}`,
|
|
755
|
+
'Content-Type': `multipart/form-data; boundary=${boundary}`,
|
|
756
|
+
'Content-Length': totalPayload.length
|
|
757
|
+
}
|
|
758
|
+
}, (apiRes) => {
|
|
759
|
+
let responseBody = '';
|
|
760
|
+
apiRes.on('data', (chunk) => responseBody += chunk);
|
|
761
|
+
apiRes.on('end', () => {
|
|
762
|
+
try {
|
|
763
|
+
const parsed = JSON.parse(responseBody);
|
|
764
|
+
if (apiRes.statusCode && apiRes.statusCode >= 400) {
|
|
765
|
+
sendJSON(res, apiRes.statusCode, { error: parsed.error?.message || parsed.message || 'API request failed' });
|
|
766
|
+
}
|
|
767
|
+
else {
|
|
768
|
+
sendJSON(res, 200, { text: parsed.text || '' });
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
catch (e) {
|
|
772
|
+
sendJSON(res, 500, { error: 'Failed to parse cloud response' });
|
|
773
|
+
}
|
|
774
|
+
});
|
|
775
|
+
});
|
|
776
|
+
apiReq.on('error', (err) => {
|
|
777
|
+
sendJSON(res, 500, { error: err.message });
|
|
778
|
+
});
|
|
779
|
+
apiReq.write(totalPayload);
|
|
780
|
+
apiReq.end();
|
|
781
|
+
});
|
|
782
|
+
return;
|
|
783
|
+
}
|
|
784
|
+
serveStaticFile(pathname, res);
|
|
785
|
+
};
|
|
786
|
+
let server;
|
|
787
|
+
let isSecureServer = false;
|
|
788
|
+
if (isSecure && actualSslKey && actualSslCert) {
|
|
789
|
+
try {
|
|
790
|
+
const options = {
|
|
791
|
+
key: fs.readFileSync(actualSslKey),
|
|
792
|
+
cert: fs.readFileSync(actualSslCert),
|
|
793
|
+
};
|
|
794
|
+
server = createHttpsServer(options, requestHandler);
|
|
795
|
+
isSecureServer = true;
|
|
796
|
+
}
|
|
797
|
+
catch (err) {
|
|
798
|
+
console.error(`Failed to load SSL certificates from ${actualSslKey} and ${actualSslCert}. Falling back to HTTP.`, err.message);
|
|
799
|
+
server = createHttpServer(requestHandler);
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
else {
|
|
803
|
+
server = createHttpServer(requestHandler);
|
|
804
|
+
}
|
|
805
|
+
const wss = new WebSocketServer({ noServer: true });
|
|
806
|
+
server.on('upgrade', (req, socket, head) => {
|
|
807
|
+
if (req.url?.startsWith('/ws')) {
|
|
808
|
+
if (!authenticate(req, token)) {
|
|
809
|
+
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
|
|
810
|
+
socket.destroy();
|
|
811
|
+
return;
|
|
812
|
+
}
|
|
813
|
+
wss.handleUpgrade(req, socket, head, (ws) => {
|
|
814
|
+
wss.emit('connection', ws, req);
|
|
815
|
+
});
|
|
816
|
+
}
|
|
817
|
+
else {
|
|
818
|
+
socket.destroy();
|
|
819
|
+
}
|
|
820
|
+
});
|
|
821
|
+
wss.on('connection', (ws) => {
|
|
822
|
+
const clientId = generateId();
|
|
823
|
+
const client = {
|
|
824
|
+
id: clientId,
|
|
825
|
+
ws,
|
|
826
|
+
sessionId: null,
|
|
827
|
+
readOnly: false,
|
|
828
|
+
};
|
|
829
|
+
clients.set(clientId, client);
|
|
830
|
+
sendWS(ws, { type: 'connected', clientId });
|
|
831
|
+
ws.on('message', async (data) => {
|
|
832
|
+
let msg;
|
|
833
|
+
try {
|
|
834
|
+
msg = JSON.parse(data.toString());
|
|
835
|
+
}
|
|
836
|
+
catch (err) {
|
|
837
|
+
console.error('WS parse error:', err);
|
|
838
|
+
sendWS(ws, {
|
|
839
|
+
type: 'session_error',
|
|
840
|
+
error: 'Invalid message format (JSON parse failed)'
|
|
841
|
+
});
|
|
842
|
+
return;
|
|
843
|
+
}
|
|
844
|
+
try {
|
|
845
|
+
await handleWSMessage(msg, client, sessionPool, clients, broadcastToSession, broadcastSessionsUpdated);
|
|
846
|
+
}
|
|
847
|
+
catch (err) {
|
|
848
|
+
console.error('WS message processing error:', err);
|
|
849
|
+
const errorText = err.message || 'An error occurred';
|
|
850
|
+
if (client.sessionId) {
|
|
851
|
+
const tracked = sessionPool.getSession(client.sessionId);
|
|
852
|
+
const sId = tracked?.sessionId;
|
|
853
|
+
const errMsg = {
|
|
854
|
+
type: 'session_error',
|
|
855
|
+
sessionId: sId,
|
|
856
|
+
error: errorText
|
|
857
|
+
};
|
|
858
|
+
if (tracked) {
|
|
859
|
+
for (const cid of tracked.clients) {
|
|
860
|
+
const c = clients.get(cid);
|
|
861
|
+
if (c) {
|
|
862
|
+
sendWS(c.ws, errMsg);
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
else {
|
|
868
|
+
sendWS(ws, {
|
|
869
|
+
type: 'session_error',
|
|
870
|
+
error: errorText
|
|
871
|
+
});
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
});
|
|
875
|
+
ws.on('close', async () => {
|
|
876
|
+
if (client.sessionId) {
|
|
877
|
+
if (client.isCliBridge) {
|
|
878
|
+
await sessionPool.unregisterCliSession(client.sessionId);
|
|
879
|
+
}
|
|
880
|
+
else {
|
|
881
|
+
sessionPool.removeClient(client.sessionId, clientId);
|
|
882
|
+
}
|
|
883
|
+
broadcastSessionsUpdated();
|
|
884
|
+
}
|
|
885
|
+
clients.delete(clientId);
|
|
886
|
+
});
|
|
887
|
+
ws.on('error', (err) => {
|
|
888
|
+
console.error(`WS error for ${clientId}:`, err.message);
|
|
889
|
+
});
|
|
890
|
+
});
|
|
891
|
+
server.listen(port, host, () => {
|
|
892
|
+
const protocol = isSecureServer ? 'https' : 'http';
|
|
893
|
+
const authInfo = token ? ' (token-protected)' : ' (no authentication)';
|
|
894
|
+
console.log(`\n🔐 Wherever Server: ${protocol}://${host}:${port}${authInfo}`);
|
|
895
|
+
if (isSecureServer) {
|
|
896
|
+
console.log(`
|
|
897
|
+
👉 FIRST TIME CONNECTING?
|
|
898
|
+
Since the server uses an automatically generated self-signed SSL certificate:
|
|
899
|
+
1. Open https://${host}:${port} in your browser/phone.
|
|
900
|
+
2. You will see a "Your connection is not private" warning.
|
|
901
|
+
3. Click "Advanced" (or "More Info") and choose "Proceed to ${host} (unsafe)".
|
|
902
|
+
This encrypts all network traffic securely and enables safe, private remote access!
|
|
903
|
+
`);
|
|
904
|
+
}
|
|
905
|
+
});
|
|
906
|
+
server.on('error', (err) => {
|
|
907
|
+
console.error('Server error:', err.message);
|
|
908
|
+
});
|
|
909
|
+
const shutdown = async () => {
|
|
910
|
+
console.log('Shutting down...');
|
|
911
|
+
for (const c of clients.values()) {
|
|
912
|
+
c.ws.close();
|
|
913
|
+
}
|
|
914
|
+
await sessionPool.disposeAll();
|
|
915
|
+
server.close();
|
|
916
|
+
process.exit(0);
|
|
917
|
+
};
|
|
918
|
+
process.on('SIGTERM', shutdown);
|
|
919
|
+
process.on('SIGINT', shutdown);
|
|
920
|
+
}
|
|
921
|
+
function switchClientSession(client, newSessionFile, pool, onSessionsUpdated) {
|
|
922
|
+
if (client.sessionId && client.sessionId !== newSessionFile) {
|
|
923
|
+
pool.removeClient(client.sessionId, client.id);
|
|
924
|
+
}
|
|
925
|
+
client.sessionId = newSessionFile;
|
|
926
|
+
if (onSessionsUpdated) {
|
|
927
|
+
onSessionsUpdated();
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
async function handleWSMessage(msg, client, pool, clients, broadcast, onSessionsUpdated) {
|
|
931
|
+
switch (msg.type) {
|
|
932
|
+
case 'cli_register': {
|
|
933
|
+
client.isCliBridge = true;
|
|
934
|
+
client.sessionId = msg.sessionFile;
|
|
935
|
+
const result = await pool.registerCliSession(msg.sessionFile, msg.cwd, msg.model || '', client.ws);
|
|
936
|
+
if (result.error) {
|
|
937
|
+
sendWS(client.ws, { type: 'session_error', error: result.error });
|
|
938
|
+
}
|
|
939
|
+
else {
|
|
940
|
+
console.log(`Registered CLI Bridge for session ${msg.sessionFile} at ${msg.cwd}`);
|
|
941
|
+
onSessionsUpdated();
|
|
942
|
+
const sId = result.tracked.sessionId;
|
|
943
|
+
const msgToWeb = {
|
|
944
|
+
type: 'session_created',
|
|
945
|
+
sessionId: sId,
|
|
946
|
+
sessionFile: msg.sessionFile,
|
|
947
|
+
cwd: msg.cwd,
|
|
948
|
+
model: msg.model || '',
|
|
949
|
+
isStreaming: pool.isStreaming(msg.sessionFile),
|
|
950
|
+
};
|
|
951
|
+
for (const c of clients.values()) {
|
|
952
|
+
if (c.sessionId === msg.sessionFile && !c.isCliBridge) {
|
|
953
|
+
sendWS(c.ws, msgToWeb);
|
|
954
|
+
const history = pool.getSessionHistory(msg.sessionFile);
|
|
955
|
+
sendWS(c.ws, {
|
|
956
|
+
type: 'message_history',
|
|
957
|
+
sessionId: sId,
|
|
958
|
+
messages: history,
|
|
959
|
+
});
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
break;
|
|
964
|
+
}
|
|
965
|
+
case 'cli_event': {
|
|
966
|
+
if (!client.isCliBridge || !client.sessionId)
|
|
967
|
+
return;
|
|
968
|
+
pool.handleCliEvent(client.sessionId, msg.event);
|
|
969
|
+
break;
|
|
970
|
+
}
|
|
971
|
+
case 'connect':
|
|
972
|
+
break;
|
|
973
|
+
case 'ping':
|
|
974
|
+
sendWS(client.ws, { type: 'pong', timestamp: Date.now() });
|
|
975
|
+
break;
|
|
976
|
+
case 'session_load': {
|
|
977
|
+
const result = await pool.loadSession(msg.sessionFile, msg.cwd, msg.model);
|
|
978
|
+
if (result.error) {
|
|
979
|
+
sendWS(client.ws, { type: 'session_error', error: result.error });
|
|
980
|
+
return;
|
|
981
|
+
}
|
|
982
|
+
const conflict = pool.detectConflict(result.tracked.sessionFile, result.tracked.cwd);
|
|
983
|
+
if (conflict.conflict && conflict.otherSessionId) {
|
|
984
|
+
sendWS(client.ws, {
|
|
985
|
+
type: 'session_conflict',
|
|
986
|
+
sessionId: result.tracked.sessionId,
|
|
987
|
+
conflictingSession: conflict.otherSessionId,
|
|
988
|
+
conflictingCwd: conflict.otherCwd,
|
|
989
|
+
});
|
|
990
|
+
return;
|
|
991
|
+
}
|
|
992
|
+
pool.addClient(result.tracked.sessionFile, client.id);
|
|
993
|
+
switchClientSession(client, result.tracked.sessionFile, pool, onSessionsUpdated);
|
|
994
|
+
client.readOnly = false;
|
|
995
|
+
sendWS(client.ws, {
|
|
996
|
+
type: 'session_created',
|
|
997
|
+
sessionId: result.tracked.sessionId,
|
|
998
|
+
sessionFile: result.tracked.sessionFile,
|
|
999
|
+
cwd: result.tracked.cwd,
|
|
1000
|
+
model: result.tracked.model,
|
|
1001
|
+
isStreaming: pool.isStreaming(result.tracked.sessionFile),
|
|
1002
|
+
});
|
|
1003
|
+
const history = pool.getSessionHistory(result.tracked.sessionFile);
|
|
1004
|
+
sendWS(client.ws, {
|
|
1005
|
+
type: 'message_history',
|
|
1006
|
+
sessionId: result.tracked.sessionId,
|
|
1007
|
+
messages: history,
|
|
1008
|
+
});
|
|
1009
|
+
break;
|
|
1010
|
+
}
|
|
1011
|
+
case 'session_new': {
|
|
1012
|
+
const existing = pool.findActiveSessionByCwd(msg.cwd);
|
|
1013
|
+
const hasOtherClients = existing && (existing.clients.size > 1 ||
|
|
1014
|
+
(existing.clients.size === 1 && !existing.clients.has(client.id)));
|
|
1015
|
+
if (hasOtherClients && existing) {
|
|
1016
|
+
sendWS(client.ws, {
|
|
1017
|
+
type: 'session_conflict',
|
|
1018
|
+
sessionId: '',
|
|
1019
|
+
conflictingSession: existing.sessionId,
|
|
1020
|
+
conflictingCwd: existing.cwd,
|
|
1021
|
+
});
|
|
1022
|
+
return;
|
|
1023
|
+
}
|
|
1024
|
+
// If the client is currently associated with the existing session in this CWD and wants to start a fresh new one,
|
|
1025
|
+
// let's switch their session to null first so that the existing session has 0 clients. This ensures
|
|
1026
|
+
// pool.createNewSession will create a brand new session instead of returning the existing one.
|
|
1027
|
+
if (existing && existing.clients.has(client.id)) {
|
|
1028
|
+
switchClientSession(client, null, pool, onSessionsUpdated);
|
|
1029
|
+
}
|
|
1030
|
+
const result = await pool.createNewSession(msg.cwd, msg.model, msg.gitInit, msg.createRemote, msg.repoVisibility);
|
|
1031
|
+
if (result.error) {
|
|
1032
|
+
sendWS(client.ws, { type: 'session_error', error: result.error });
|
|
1033
|
+
return;
|
|
1034
|
+
}
|
|
1035
|
+
pool.addClient(result.tracked.sessionFile, client.id);
|
|
1036
|
+
switchClientSession(client, result.tracked.sessionFile, pool, onSessionsUpdated);
|
|
1037
|
+
client.readOnly = false;
|
|
1038
|
+
sendWS(client.ws, {
|
|
1039
|
+
type: 'session_created',
|
|
1040
|
+
sessionId: result.tracked.sessionId,
|
|
1041
|
+
sessionFile: result.tracked.sessionFile,
|
|
1042
|
+
cwd: result.tracked.cwd,
|
|
1043
|
+
model: result.tracked.model,
|
|
1044
|
+
isStreaming: pool.isStreaming(result.tracked.sessionFile),
|
|
1045
|
+
});
|
|
1046
|
+
sendWS(client.ws, {
|
|
1047
|
+
type: 'message_history',
|
|
1048
|
+
sessionId: result.tracked.sessionId,
|
|
1049
|
+
messages: [],
|
|
1050
|
+
});
|
|
1051
|
+
break;
|
|
1052
|
+
}
|
|
1053
|
+
case 'session_leave': {
|
|
1054
|
+
if (client.sessionId) {
|
|
1055
|
+
switchClientSession(client, null, pool, onSessionsUpdated);
|
|
1056
|
+
client.readOnly = false;
|
|
1057
|
+
}
|
|
1058
|
+
break;
|
|
1059
|
+
}
|
|
1060
|
+
case 'session_resolve_conflict': {
|
|
1061
|
+
let tracked = pool.getSession(msg.sessionId);
|
|
1062
|
+
const isNewSessionConflict = !msg.sessionId;
|
|
1063
|
+
// For new sessions, targetSessionId is empty; find by cwd
|
|
1064
|
+
const existingTracked = tracked || (msg.cwd ? pool.findActiveSessionByCwd(msg.cwd) : null);
|
|
1065
|
+
if (existingTracked) {
|
|
1066
|
+
if (msg.action === 'take_over') {
|
|
1067
|
+
const interrupted = await pool.takeOver(existingTracked.cwd, msg.sessionId);
|
|
1068
|
+
for (const intClientId of interrupted) {
|
|
1069
|
+
// Do not interrupt the current client itself if we are creating a new session
|
|
1070
|
+
if (isNewSessionConflict && intClientId === client.id)
|
|
1071
|
+
continue;
|
|
1072
|
+
const intClient = clients.get(intClientId);
|
|
1073
|
+
if (intClient) {
|
|
1074
|
+
sendWS(intClient.ws, {
|
|
1075
|
+
type: 'session_interrupted',
|
|
1076
|
+
sessionId: intClient.sessionId || '',
|
|
1077
|
+
reason: isNewSessionConflict
|
|
1078
|
+
? 'Another client started a new session in this folder'
|
|
1079
|
+
: 'Another client took over this folder',
|
|
1080
|
+
});
|
|
1081
|
+
switchClientSession(intClient, null, pool, onSessionsUpdated);
|
|
1082
|
+
}
|
|
1083
|
+
}
|
|
1084
|
+
if (isNewSessionConflict) {
|
|
1085
|
+
// Create a brand-new session as requested!
|
|
1086
|
+
const result = await pool.createNewSession(msg.cwd, undefined);
|
|
1087
|
+
if (result.error) {
|
|
1088
|
+
sendWS(client.ws, { type: 'session_error', error: result.error });
|
|
1089
|
+
return;
|
|
1090
|
+
}
|
|
1091
|
+
pool.addClient(result.tracked.sessionFile, client.id);
|
|
1092
|
+
switchClientSession(client, result.tracked.sessionFile, pool, onSessionsUpdated);
|
|
1093
|
+
client.readOnly = false;
|
|
1094
|
+
sendWS(client.ws, {
|
|
1095
|
+
type: 'session_created',
|
|
1096
|
+
sessionId: result.tracked.sessionId,
|
|
1097
|
+
sessionFile: result.tracked.sessionFile,
|
|
1098
|
+
cwd: result.tracked.cwd,
|
|
1099
|
+
model: result.tracked.model,
|
|
1100
|
+
isStreaming: pool.isStreaming(result.tracked.sessionFile),
|
|
1101
|
+
});
|
|
1102
|
+
sendWS(client.ws, {
|
|
1103
|
+
type: 'message_history',
|
|
1104
|
+
sessionId: result.tracked.sessionId,
|
|
1105
|
+
messages: [],
|
|
1106
|
+
});
|
|
1107
|
+
}
|
|
1108
|
+
else if (tracked) {
|
|
1109
|
+
// Join the existing session
|
|
1110
|
+
pool.addClient(tracked.sessionFile, client.id);
|
|
1111
|
+
switchClientSession(client, tracked.sessionFile, pool, onSessionsUpdated);
|
|
1112
|
+
client.readOnly = false;
|
|
1113
|
+
sendWS(client.ws, {
|
|
1114
|
+
type: 'session_created',
|
|
1115
|
+
sessionId: tracked.sessionId,
|
|
1116
|
+
sessionFile: tracked.sessionFile,
|
|
1117
|
+
cwd: tracked.cwd,
|
|
1118
|
+
model: tracked.model,
|
|
1119
|
+
isStreaming: pool.isStreaming(tracked.sessionFile),
|
|
1120
|
+
});
|
|
1121
|
+
const history = pool.getSessionHistory(tracked.sessionFile);
|
|
1122
|
+
sendWS(client.ws, {
|
|
1123
|
+
type: 'message_history',
|
|
1124
|
+
sessionId: tracked.sessionId,
|
|
1125
|
+
messages: history,
|
|
1126
|
+
});
|
|
1127
|
+
}
|
|
1128
|
+
}
|
|
1129
|
+
else {
|
|
1130
|
+
// Join the existing session as read-only
|
|
1131
|
+
pool.addClient(existingTracked.sessionFile, client.id);
|
|
1132
|
+
switchClientSession(client, existingTracked.sessionFile, pool, onSessionsUpdated);
|
|
1133
|
+
client.readOnly = true;
|
|
1134
|
+
sendWS(client.ws, {
|
|
1135
|
+
type: 'session_created',
|
|
1136
|
+
sessionId: existingTracked.sessionId,
|
|
1137
|
+
sessionFile: existingTracked.sessionFile,
|
|
1138
|
+
cwd: existingTracked.cwd,
|
|
1139
|
+
model: existingTracked.model,
|
|
1140
|
+
isStreaming: pool.isStreaming(existingTracked.sessionFile),
|
|
1141
|
+
});
|
|
1142
|
+
const history = pool.getSessionHistory(existingTracked.sessionFile);
|
|
1143
|
+
sendWS(client.ws, {
|
|
1144
|
+
type: 'message_history',
|
|
1145
|
+
sessionId: existingTracked.sessionId,
|
|
1146
|
+
messages: history,
|
|
1147
|
+
});
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
1150
|
+
break;
|
|
1151
|
+
}
|
|
1152
|
+
case 'message': {
|
|
1153
|
+
if (!client.sessionId)
|
|
1154
|
+
return;
|
|
1155
|
+
if (client.readOnly)
|
|
1156
|
+
return;
|
|
1157
|
+
const streaming = pool.isStreaming(client.sessionId);
|
|
1158
|
+
await pool.sendUserMessage(client.sessionId, msg.message, streaming ? 'steer' : undefined);
|
|
1159
|
+
break;
|
|
1160
|
+
}
|
|
1161
|
+
case 'abort': {
|
|
1162
|
+
if (!client.sessionId)
|
|
1163
|
+
return;
|
|
1164
|
+
await pool.abortSession(client.sessionId);
|
|
1165
|
+
break;
|
|
1166
|
+
}
|
|
1167
|
+
case 'model_change': {
|
|
1168
|
+
if (!client.sessionId)
|
|
1169
|
+
return;
|
|
1170
|
+
const result = await pool.changeModel(client.sessionId, msg.model);
|
|
1171
|
+
if (result.error) {
|
|
1172
|
+
sendWS(client.ws, { type: 'session_error', error: result.error });
|
|
1173
|
+
}
|
|
1174
|
+
else {
|
|
1175
|
+
const tracked = pool.getSession(client.sessionId);
|
|
1176
|
+
const sId = tracked?.sessionId || '';
|
|
1177
|
+
const modelChangedMsg = { type: 'model_changed', sessionId: sId, model: msg.model };
|
|
1178
|
+
for (const c of clients.values()) {
|
|
1179
|
+
if (c.sessionId === client.sessionId) {
|
|
1180
|
+
sendWS(c.ws, modelChangedMsg);
|
|
1181
|
+
}
|
|
1182
|
+
}
|
|
1183
|
+
}
|
|
1184
|
+
break;
|
|
1185
|
+
}
|
|
1186
|
+
case 'file_upload': {
|
|
1187
|
+
const { uploadId, sessionId, filename, data } = msg;
|
|
1188
|
+
if (!uploadId || !sessionId || !filename || !data) {
|
|
1189
|
+
sendWS(client.ws, {
|
|
1190
|
+
type: 'file_upload_error',
|
|
1191
|
+
uploadId: uploadId || '',
|
|
1192
|
+
sessionId: sessionId || '',
|
|
1193
|
+
error: 'Missing parameters for file upload'
|
|
1194
|
+
});
|
|
1195
|
+
break;
|
|
1196
|
+
}
|
|
1197
|
+
try {
|
|
1198
|
+
const tracked = pool.getSession(sessionId);
|
|
1199
|
+
const cwd = tracked?.cwd;
|
|
1200
|
+
const config = getWhereverConfig();
|
|
1201
|
+
const targetDir = resolveUploadDir(config, cwd);
|
|
1202
|
+
fs.mkdirSync(targetDir, { recursive: true });
|
|
1203
|
+
const timestamp = Date.now();
|
|
1204
|
+
const safeFilename = `${timestamp}_${path.basename(filename)}`;
|
|
1205
|
+
const destPath = path.join(targetDir, safeFilename);
|
|
1206
|
+
const fileBuffer = Buffer.from(data, 'base64');
|
|
1207
|
+
fs.writeFileSync(destPath, fileBuffer);
|
|
1208
|
+
sendWS(client.ws, {
|
|
1209
|
+
type: 'file_uploaded',
|
|
1210
|
+
uploadId,
|
|
1211
|
+
sessionId,
|
|
1212
|
+
filename,
|
|
1213
|
+
savedPath: destPath
|
|
1214
|
+
});
|
|
1215
|
+
}
|
|
1216
|
+
catch (err) {
|
|
1217
|
+
sendWS(client.ws, {
|
|
1218
|
+
type: 'file_upload_error',
|
|
1219
|
+
uploadId,
|
|
1220
|
+
sessionId,
|
|
1221
|
+
error: err.message || 'Failed to save file'
|
|
1222
|
+
});
|
|
1223
|
+
}
|
|
1224
|
+
break;
|
|
1225
|
+
}
|
|
1226
|
+
}
|
|
1227
|
+
}
|
|
1228
|
+
function extractToolResult(event) {
|
|
1229
|
+
const result = event.result;
|
|
1230
|
+
if (!result)
|
|
1231
|
+
return '';
|
|
1232
|
+
if (typeof result === 'string')
|
|
1233
|
+
return result;
|
|
1234
|
+
if (typeof result === 'object') {
|
|
1235
|
+
if (result.content) {
|
|
1236
|
+
if (typeof result.content === 'string')
|
|
1237
|
+
return result.content;
|
|
1238
|
+
if (Array.isArray(result.content)) {
|
|
1239
|
+
return result.content
|
|
1240
|
+
.filter((c) => c.type === 'text')
|
|
1241
|
+
.map((c) => c.text || '')
|
|
1242
|
+
.join('\n');
|
|
1243
|
+
}
|
|
1244
|
+
}
|
|
1245
|
+
return JSON.stringify(result, null, 2);
|
|
1246
|
+
}
|
|
1247
|
+
return String(result);
|
|
1248
|
+
}
|
|
1249
|
+
function extractText(msg) {
|
|
1250
|
+
if (typeof msg.content === 'string')
|
|
1251
|
+
return msg.content;
|
|
1252
|
+
if (Array.isArray(msg.content)) {
|
|
1253
|
+
return msg.content
|
|
1254
|
+
.filter((c) => c.type === 'text')
|
|
1255
|
+
.map((c) => c.text || '')
|
|
1256
|
+
.join('\n');
|
|
1257
|
+
}
|
|
1258
|
+
return '';
|
|
1259
|
+
}
|
|
1260
|
+
main().catch((err) => {
|
|
1261
|
+
console.error('Fatal server startup error:', err);
|
|
1262
|
+
process.exit(1);
|
|
1263
|
+
});
|
|
1264
|
+
//# sourceMappingURL=index.js.map
|