svamp-cli 0.1.30 → 0.1.31

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.
@@ -1,4958 +0,0 @@
1
- import os from 'os';
2
- import fs from 'fs/promises';
3
- import { existsSync as existsSync$1, readFileSync as readFileSync$1, writeFileSync as writeFileSync$1, mkdirSync as mkdirSync$1, copyFileSync, unlinkSync, rmdirSync } from 'fs';
4
- import { dirname, join as join$1, resolve, basename } from 'path';
5
- import { fileURLToPath } from 'url';
6
- import { spawn as spawn$1 } from 'child_process';
7
- import { randomUUID as randomUUID$1 } from 'crypto';
8
- import { randomUUID } from 'node:crypto';
9
- import { existsSync, readFileSync, mkdirSync, appendFileSync, writeFileSync } from 'node:fs';
10
- import { join } from 'node:path';
11
- import { spawn, execSync, execFile } from 'node:child_process';
12
- import { ndJsonStream, ClientSideConnection } from '@agentclientprotocol/sdk';
13
- import { homedir, tmpdir } from 'node:os';
14
- import { Client } from '@modelcontextprotocol/sdk/client/index.js';
15
- import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
16
- import { ElicitRequestSchema } from '@modelcontextprotocol/sdk/types.js';
17
- import { z } from 'zod';
18
- import { mkdir, access, mkdtemp, rm, writeFile } from 'node:fs/promises';
19
- import { promisify } from 'node:util';
20
-
21
- let connectToServerFn = null;
22
- async function getConnectToServer() {
23
- if (!connectToServerFn) {
24
- const mod = await import('hypha-rpc');
25
- connectToServerFn = mod.connectToServer || mod.default && mod.default.connectToServer || mod.hyphaWebsocketClient && mod.hyphaWebsocketClient.connectToServer;
26
- if (!connectToServerFn) {
27
- throw new Error("Could not find connectToServer in hypha-rpc module");
28
- }
29
- }
30
- return connectToServerFn;
31
- }
32
- async function connectToHypha(config) {
33
- const connectToServer = await getConnectToServer();
34
- const workspace = config.token ? parseWorkspaceFromToken(config.token) : void 0;
35
- const server = await connectToServer({
36
- server_url: config.serverUrl,
37
- token: config.token,
38
- client_id: config.clientId,
39
- name: config.name || "svamp-cli",
40
- workspace,
41
- ...config.transport ? { transport: config.transport } : {}
42
- });
43
- return server;
44
- }
45
- function parseWorkspaceFromToken(token) {
46
- try {
47
- const payload = JSON.parse(Buffer.from(token.split(".")[1], "base64").toString());
48
- const scope = payload.scope || "";
49
- const match = scope.match(/wid:([^\s]+)/);
50
- return match ? match[1] : void 0;
51
- } catch {
52
- return void 0;
53
- }
54
- }
55
- function getHyphaServerUrl() {
56
- return process.env.HYPHA_SERVER_URL || "http://localhost:9527";
57
- }
58
-
59
- const ROLE_HIERARCHY = {
60
- view: 0,
61
- interact: 1,
62
- admin: 2
63
- };
64
- const ISOLATION_PREFERENCE = ["srt", "bwrap", "docker", "podman"];
65
-
66
- function authorizeRequest(context, sharing, requiredRole = "view") {
67
- if (!context?.user) return;
68
- const userEmail = context.user.email;
69
- if (!sharing) return;
70
- if (userEmail && userEmail === sharing.owner) return;
71
- if (!sharing.enabled) {
72
- throw new Error("Access denied: this resource is not shared");
73
- }
74
- if (!userEmail) {
75
- throw new Error("Access denied: no email in user context");
76
- }
77
- const sharedUser = sharing.allowedUsers.find(
78
- (u) => u.email.toLowerCase() === userEmail.toLowerCase()
79
- );
80
- if (!sharedUser) {
81
- throw new Error("Access denied: you are not in the allowed users list");
82
- }
83
- if (ROLE_HIERARCHY[sharedUser.role] < ROLE_HIERARCHY[requiredRole]) {
84
- throw new Error(
85
- `Access denied: requires '${requiredRole}' role, you have '${sharedUser.role}'`
86
- );
87
- }
88
- }
89
-
90
- async function registerMachineService(server, machineId, metadata, daemonState, handlers) {
91
- let currentMetadata = { ...metadata };
92
- let currentDaemonState = { ...daemonState };
93
- let metadataVersion = 1;
94
- let daemonStateVersion = 1;
95
- const listeners = [];
96
- const removeListener = (listener, reason) => {
97
- const idx = listeners.indexOf(listener);
98
- if (idx >= 0) {
99
- listeners.splice(idx, 1);
100
- console.log(`[HYPHA MACHINE] Listener removed (${reason}), remaining: ${listeners.length}`);
101
- const rintfId = listener._rintf_service_id;
102
- if (rintfId) {
103
- server.unregisterService(rintfId).catch(() => {
104
- });
105
- }
106
- }
107
- };
108
- const notifyListeners = (update) => {
109
- for (let i = listeners.length - 1; i >= 0; i--) {
110
- try {
111
- const result = listeners[i].onUpdate(update);
112
- if (result && typeof result.catch === "function") {
113
- const listener = listeners[i];
114
- result.catch((err) => {
115
- console.error(`[HYPHA MACHINE] Async listener error:`, err);
116
- removeListener(listener, "async error");
117
- });
118
- }
119
- } catch (err) {
120
- console.error(`[HYPHA MACHINE] Listener error:`, err);
121
- removeListener(listeners[i], "sync error");
122
- }
123
- }
124
- };
125
- const serviceInfo = await server.registerService(
126
- {
127
- id: "default",
128
- name: `Svamp Machine (${metadata.displayName || machineId})`,
129
- type: "svamp-machine",
130
- config: { visibility: "public", require_context: true },
131
- // Machine info
132
- getMachineInfo: async (context) => {
133
- authorizeRequest(context, currentMetadata.sharing, "view");
134
- return {
135
- machineId,
136
- metadata: currentMetadata,
137
- metadataVersion,
138
- daemonState: currentDaemonState,
139
- daemonStateVersion
140
- };
141
- },
142
- // Heartbeat
143
- heartbeat: async (context) => ({
144
- time: Date.now(),
145
- status: currentDaemonState.status,
146
- machineId
147
- }),
148
- // List active sessions on this machine
149
- listSessions: async (context) => {
150
- authorizeRequest(context, currentMetadata.sharing, "view");
151
- return handlers.getTrackedSessions();
152
- },
153
- // Spawn a new session
154
- spawnSession: async (options, context) => {
155
- authorizeRequest(context, currentMetadata.sharing, "interact");
156
- if (options.sharing?.enabled && !options.sharing.owner && context?.user?.email) {
157
- options = {
158
- ...options,
159
- sharing: { ...options.sharing, owner: context.user.email }
160
- };
161
- }
162
- const result = await handlers.spawnSession({
163
- ...options,
164
- machineId
165
- });
166
- if (result.type === "success" && result.sessionId) {
167
- notifyListeners({
168
- type: "new-session",
169
- sessionId: result.sessionId,
170
- machineId
171
- });
172
- }
173
- return result;
174
- },
175
- // Stop a session
176
- stopSession: async (sessionId, context) => {
177
- authorizeRequest(context, currentMetadata.sharing, "admin");
178
- const result = handlers.stopSession(sessionId);
179
- notifyListeners({
180
- type: "session-stopped",
181
- sessionId,
182
- machineId
183
- });
184
- return result;
185
- },
186
- // Stop the daemon
187
- stopDaemon: async (context) => {
188
- authorizeRequest(context, currentMetadata.sharing, "admin");
189
- handlers.requestShutdown();
190
- return { success: true };
191
- },
192
- // Metadata management (with optimistic concurrency)
193
- getMetadata: async (context) => {
194
- authorizeRequest(context, currentMetadata.sharing, "view");
195
- return {
196
- metadata: currentMetadata,
197
- version: metadataVersion
198
- };
199
- },
200
- updateMetadata: async (newMetadata, expectedVersion, context) => {
201
- authorizeRequest(context, currentMetadata.sharing, "admin");
202
- if (expectedVersion !== metadataVersion) {
203
- return {
204
- result: "version-mismatch",
205
- version: metadataVersion,
206
- metadata: currentMetadata
207
- };
208
- }
209
- currentMetadata = newMetadata;
210
- metadataVersion++;
211
- notifyListeners({
212
- type: "update-machine",
213
- machineId,
214
- metadata: { value: currentMetadata, version: metadataVersion }
215
- });
216
- return {
217
- result: "success",
218
- version: metadataVersion,
219
- metadata: currentMetadata
220
- };
221
- },
222
- // Daemon state management
223
- getDaemonState: async (context) => {
224
- authorizeRequest(context, currentMetadata.sharing, "view");
225
- return {
226
- daemonState: currentDaemonState,
227
- version: daemonStateVersion
228
- };
229
- },
230
- updateDaemonState: async (newState, expectedVersion, context) => {
231
- authorizeRequest(context, currentMetadata.sharing, "admin");
232
- if (expectedVersion !== daemonStateVersion) {
233
- return {
234
- result: "version-mismatch",
235
- version: daemonStateVersion,
236
- daemonState: currentDaemonState
237
- };
238
- }
239
- currentDaemonState = newState;
240
- daemonStateVersion++;
241
- notifyListeners({
242
- type: "update-machine",
243
- machineId,
244
- daemonState: { value: currentDaemonState, version: daemonStateVersion }
245
- });
246
- return {
247
- result: "success",
248
- version: daemonStateVersion,
249
- daemonState: currentDaemonState
250
- };
251
- },
252
- // ── Sharing Management ──
253
- getSharing: async (context) => {
254
- authorizeRequest(context, currentMetadata.sharing, "view");
255
- return { sharing: currentMetadata.sharing || null };
256
- },
257
- updateSharing: async (newSharing, context) => {
258
- authorizeRequest(context, currentMetadata.sharing, "admin");
259
- if (currentMetadata.sharing && context?.user?.email && context.user.email !== currentMetadata.sharing.owner) {
260
- throw new Error("Only the machine owner can update sharing settings");
261
- }
262
- currentMetadata = { ...currentMetadata, sharing: newSharing };
263
- metadataVersion++;
264
- notifyListeners({
265
- type: "update-machine",
266
- machineId,
267
- metadata: { value: currentMetadata, version: metadataVersion }
268
- });
269
- return { success: true, sharing: newSharing };
270
- },
271
- // Register a listener for real-time updates (app calls this with _rintf callback)
272
- registerListener: async (callback, context) => {
273
- authorizeRequest(context, currentMetadata.sharing, "view");
274
- listeners.push(callback);
275
- console.log(`[HYPHA MACHINE] Listener registered (total: ${listeners.length})`);
276
- return { success: true, listenerId: listeners.length - 1 };
277
- },
278
- // Shell access
279
- bash: async (command, cwd, context) => {
280
- authorizeRequest(context, currentMetadata.sharing, "admin");
281
- const { exec } = await import('child_process');
282
- const { homedir } = await import('os');
283
- return new Promise((resolve) => {
284
- exec(command, { cwd: cwd || homedir(), timeout: 3e4, maxBuffer: 1024 * 1024 }, (err, stdout, stderr) => {
285
- if (err) {
286
- resolve({ success: false, stdout: stdout || "", stderr: stderr || err.message, exitCode: err.code ?? 1 });
287
- } else {
288
- resolve({ success: true, stdout, stderr: stderr || "", exitCode: 0 });
289
- }
290
- });
291
- });
292
- },
293
- // WISE voice — create ephemeral token for OpenAI Realtime API
294
- wiseCreateEphemeralToken: async (params, context) => {
295
- authorizeRequest(context, currentMetadata.sharing, "interact");
296
- const apiKey = params.apiKey || process.env.OPENAI_API_KEY;
297
- if (!apiKey) {
298
- return { success: false, error: "No OpenAI API key found. Set OPENAI_API_KEY or pass apiKey." };
299
- }
300
- try {
301
- const response = await fetch("https://api.openai.com/v1/realtime/client_secrets", {
302
- method: "POST",
303
- headers: {
304
- "Authorization": `Bearer ${apiKey}`,
305
- "Content-Type": "application/json"
306
- },
307
- body: JSON.stringify({
308
- session: {
309
- type: "realtime",
310
- model: params.model || "gpt-realtime-mini"
311
- }
312
- })
313
- });
314
- if (!response.ok) {
315
- return { success: false, error: `OpenAI API error: ${response.status}` };
316
- }
317
- const result = await response.json();
318
- return { success: true, clientSecret: result.value };
319
- } catch (error) {
320
- return { success: false, error: error instanceof Error ? error.message : "Failed to create token" };
321
- }
322
- }
323
- },
324
- { overwrite: true }
325
- );
326
- console.log(`[HYPHA MACHINE] Machine service registered: ${serviceInfo.id}`);
327
- return {
328
- serviceInfo,
329
- updateMetadata: (newMetadata) => {
330
- currentMetadata = newMetadata;
331
- metadataVersion++;
332
- notifyListeners({
333
- type: "update-machine",
334
- machineId,
335
- metadata: { value: currentMetadata, version: metadataVersion }
336
- });
337
- },
338
- updateDaemonState: (newState) => {
339
- currentDaemonState = newState;
340
- daemonStateVersion++;
341
- notifyListeners({
342
- type: "update-machine",
343
- machineId,
344
- daemonState: { value: currentDaemonState, version: daemonStateVersion }
345
- });
346
- },
347
- disconnect: async () => {
348
- await server.unregisterService(serviceInfo.id);
349
- }
350
- };
351
- }
352
-
353
- function loadMessages(messagesDir, sessionId) {
354
- const filePath = join(messagesDir, "messages.jsonl");
355
- if (!existsSync(filePath)) return [];
356
- try {
357
- const lines = readFileSync(filePath, "utf-8").split("\n").filter((l) => l.trim());
358
- const messages = [];
359
- for (const line of lines) {
360
- try {
361
- messages.push(JSON.parse(line));
362
- } catch {
363
- }
364
- }
365
- return messages.slice(-5e3);
366
- } catch {
367
- return [];
368
- }
369
- }
370
- function appendMessage(messagesDir, sessionId, msg) {
371
- const filePath = join(messagesDir, "messages.jsonl");
372
- if (!existsSync(messagesDir)) {
373
- mkdirSync(messagesDir, { recursive: true });
374
- }
375
- appendFileSync(filePath, JSON.stringify(msg) + "\n");
376
- }
377
- async function registerSessionService(server, sessionId, initialMetadata, initialAgentState, callbacks, options) {
378
- const messages = options?.messagesDir ? loadMessages(options.messagesDir) : [];
379
- let nextSeq = messages.length > 0 ? messages[messages.length - 1].seq + 1 : 1;
380
- let metadata = { ...initialMetadata };
381
- let metadataVersion = 1;
382
- let agentState = initialAgentState ? { ...initialAgentState } : null;
383
- let agentStateVersion = 1;
384
- let lastActivity = {
385
- active: false,
386
- thinking: false,
387
- mode: "remote",
388
- time: Date.now()
389
- };
390
- const listeners = [];
391
- const removeListener = (listener, reason) => {
392
- const idx = listeners.indexOf(listener);
393
- if (idx >= 0) {
394
- listeners.splice(idx, 1);
395
- console.log(`[HYPHA SESSION ${sessionId}] Listener removed (${reason}), remaining: ${listeners.length}`);
396
- const rintfId = listener._rintf_service_id;
397
- if (rintfId) {
398
- server.unregisterService(rintfId).catch(() => {
399
- });
400
- }
401
- }
402
- };
403
- const notifyListeners = (update) => {
404
- for (let i = listeners.length - 1; i >= 0; i--) {
405
- try {
406
- const result = listeners[i].onUpdate(update);
407
- if (result && typeof result.catch === "function") {
408
- const listener = listeners[i];
409
- result.catch((err) => {
410
- console.error(`[HYPHA SESSION ${sessionId}] Async listener error:`, err);
411
- removeListener(listener, "async error");
412
- });
413
- }
414
- } catch (err) {
415
- console.error(`[HYPHA SESSION ${sessionId}] Listener error:`, err);
416
- removeListener(listeners[i], "sync error");
417
- }
418
- }
419
- };
420
- const pushMessage = (content, role = "agent") => {
421
- let wrappedContent;
422
- if (role === "agent") {
423
- const data = { ...content };
424
- if ((data.type === "assistant" || data.type === "user") && !data.uuid) {
425
- data.uuid = randomUUID();
426
- }
427
- wrappedContent = { role: "agent", content: { type: "output", data } };
428
- } else if (role === "event") {
429
- wrappedContent = { role: "agent", content: { type: "event", data: content } };
430
- } else if (role === "session") {
431
- wrappedContent = { role: "session", content: { type: "session", data: content } };
432
- } else {
433
- const text = typeof content === "string" ? content : content?.text || content?.content || JSON.stringify(content);
434
- wrappedContent = { role: "user", content: { type: "text", text } };
435
- }
436
- const msg = {
437
- id: randomUUID(),
438
- seq: nextSeq++,
439
- content: wrappedContent,
440
- localId: null,
441
- createdAt: Date.now(),
442
- updatedAt: Date.now()
443
- };
444
- messages.push(msg);
445
- if (messages.length > 1e3) messages.splice(0, messages.length - 1e3);
446
- if (options?.messagesDir) {
447
- appendMessage(options.messagesDir, sessionId, msg);
448
- }
449
- notifyListeners({
450
- type: "new-message",
451
- sessionId,
452
- message: msg
453
- });
454
- return msg;
455
- };
456
- const serviceInfo = await server.registerService(
457
- {
458
- id: `svamp-session-${sessionId}`,
459
- name: `Svamp Session ${sessionId.slice(0, 8)}`,
460
- type: "svamp-session",
461
- config: { visibility: "public", require_context: true },
462
- // ── Messages ──
463
- getMessages: async (afterSeq, limit, context) => {
464
- authorizeRequest(context, metadata.sharing, "view");
465
- const after = afterSeq ?? 0;
466
- const lim = Math.min(limit ?? 100, 500);
467
- const filtered = messages.filter((m) => m.seq > after);
468
- const page = filtered.slice(0, lim);
469
- return {
470
- messages: page,
471
- hasMore: filtered.length > lim
472
- };
473
- },
474
- sendMessage: async (content, localId, meta, context) => {
475
- authorizeRequest(context, metadata.sharing, "interact");
476
- if (localId) {
477
- const existing = messages.find((m) => m.localId === localId);
478
- if (existing) {
479
- return { id: existing.id, seq: existing.seq, localId: existing.localId };
480
- }
481
- }
482
- let parsed = content;
483
- if (typeof parsed === "string") {
484
- try {
485
- parsed = JSON.parse(parsed);
486
- } catch {
487
- }
488
- }
489
- if (parsed && typeof parsed.content === "string" && !parsed.role) {
490
- try {
491
- const inner = JSON.parse(parsed.content);
492
- if (inner && typeof inner === "object") parsed = inner;
493
- } catch {
494
- }
495
- }
496
- const wrappedContent = parsed && parsed.role === "user" ? { role: "user", content: parsed.content } : { role: "user", content: { type: "text", text: typeof parsed === "string" ? parsed : JSON.stringify(parsed) } };
497
- const msg = {
498
- id: randomUUID(),
499
- seq: nextSeq++,
500
- content: wrappedContent,
501
- localId: localId || randomUUID(),
502
- createdAt: Date.now(),
503
- updatedAt: Date.now()
504
- };
505
- messages.push(msg);
506
- if (messages.length > 1e3) messages.splice(0, messages.length - 1e3);
507
- if (options?.messagesDir) {
508
- appendMessage(options.messagesDir, sessionId, msg);
509
- }
510
- notifyListeners({
511
- type: "new-message",
512
- sessionId,
513
- message: msg
514
- });
515
- callbacks.onUserMessage(content, meta);
516
- return { id: msg.id, seq: msg.seq, localId: msg.localId };
517
- },
518
- // ── Metadata ──
519
- getMetadata: async (context) => {
520
- authorizeRequest(context, metadata.sharing, "view");
521
- return {
522
- metadata,
523
- version: metadataVersion
524
- };
525
- },
526
- updateMetadata: async (newMetadata, expectedVersion, context) => {
527
- authorizeRequest(context, metadata.sharing, "admin");
528
- if (expectedVersion !== void 0 && expectedVersion !== metadataVersion) {
529
- return {
530
- result: "version-mismatch",
531
- version: metadataVersion,
532
- metadata
533
- };
534
- }
535
- metadata = newMetadata;
536
- metadataVersion++;
537
- notifyListeners({
538
- type: "update-session",
539
- sessionId,
540
- metadata: { value: metadata, version: metadataVersion }
541
- });
542
- return {
543
- result: "success",
544
- version: metadataVersion,
545
- metadata
546
- };
547
- },
548
- // ── Agent State ──
549
- getAgentState: async (context) => {
550
- authorizeRequest(context, metadata.sharing, "view");
551
- return {
552
- agentState,
553
- version: agentStateVersion
554
- };
555
- },
556
- updateAgentState: async (newState, expectedVersion, context) => {
557
- authorizeRequest(context, metadata.sharing, "admin");
558
- if (expectedVersion !== void 0 && expectedVersion !== agentStateVersion) {
559
- return {
560
- result: "version-mismatch",
561
- version: agentStateVersion,
562
- agentState
563
- };
564
- }
565
- agentState = newState;
566
- agentStateVersion++;
567
- notifyListeners({
568
- type: "update-session",
569
- sessionId,
570
- agentState: { value: agentState, version: agentStateVersion }
571
- });
572
- return {
573
- result: "success",
574
- version: agentStateVersion,
575
- agentState
576
- };
577
- },
578
- // ── Session Control RPCs ──
579
- abort: async (context) => {
580
- authorizeRequest(context, metadata.sharing, "interact");
581
- callbacks.onAbort();
582
- return { success: true };
583
- },
584
- permissionResponse: async (params, context) => {
585
- authorizeRequest(context, metadata.sharing, "interact");
586
- callbacks.onPermissionResponse(params);
587
- return { success: true };
588
- },
589
- switchMode: async (mode, context) => {
590
- authorizeRequest(context, metadata.sharing, "interact");
591
- callbacks.onSwitchMode(mode);
592
- return { success: true };
593
- },
594
- restartClaude: async (context) => {
595
- authorizeRequest(context, metadata.sharing, "admin");
596
- return await callbacks.onRestartClaude();
597
- },
598
- killSession: async (context) => {
599
- authorizeRequest(context, metadata.sharing, "admin");
600
- callbacks.onKillSession();
601
- return { success: true };
602
- },
603
- // ── Activity ──
604
- keepAlive: async (thinking, mode, context) => {
605
- lastActivity = { active: true, thinking: thinking || false, mode: mode || "remote", time: Date.now() };
606
- notifyListeners({
607
- type: "activity",
608
- sessionId,
609
- ...lastActivity
610
- });
611
- },
612
- sessionEnd: async (context) => {
613
- lastActivity = { active: false, thinking: false, mode: "remote", time: Date.now() };
614
- notifyListeners({
615
- type: "activity",
616
- sessionId,
617
- ...lastActivity
618
- });
619
- },
620
- // ── Activity State Query ──
621
- getActivityState: async (context) => {
622
- authorizeRequest(context, metadata.sharing, "view");
623
- return { ...lastActivity, sessionId };
624
- },
625
- // ── File Operations (optional, admin-only) ──
626
- readFile: async (path, context) => {
627
- authorizeRequest(context, metadata.sharing, "admin");
628
- if (!callbacks.onReadFile) throw new Error("readFile not supported");
629
- return await callbacks.onReadFile(path);
630
- },
631
- writeFile: async (path, content, context) => {
632
- authorizeRequest(context, metadata.sharing, "admin");
633
- if (!callbacks.onWriteFile) throw new Error("writeFile not supported");
634
- await callbacks.onWriteFile(path, content);
635
- return { success: true };
636
- },
637
- listDirectory: async (path, context) => {
638
- authorizeRequest(context, metadata.sharing, "admin");
639
- if (!callbacks.onListDirectory) throw new Error("listDirectory not supported");
640
- return await callbacks.onListDirectory(path);
641
- },
642
- bash: async (command, cwd, context) => {
643
- authorizeRequest(context, metadata.sharing, "admin");
644
- if (!callbacks.onBash) throw new Error("bash not supported");
645
- return await callbacks.onBash(command, cwd);
646
- },
647
- ripgrep: async (args, cwd, context) => {
648
- authorizeRequest(context, metadata.sharing, "admin");
649
- if (!callbacks.onRipgrep) throw new Error("ripgrep not supported");
650
- try {
651
- const stdout = await callbacks.onRipgrep(args, cwd);
652
- return { success: true, stdout, stderr: "", exitCode: 0 };
653
- } catch (err) {
654
- return { success: false, stdout: "", stderr: err.message || "", exitCode: 1, error: err.message };
655
- }
656
- },
657
- getDirectoryTree: async (path, maxDepth, context) => {
658
- authorizeRequest(context, metadata.sharing, "admin");
659
- if (!callbacks.onGetDirectoryTree) throw new Error("getDirectoryTree not supported");
660
- return await callbacks.onGetDirectoryTree(path, maxDepth ?? 3);
661
- },
662
- // ── Sharing Management ──
663
- getSharing: async (context) => {
664
- authorizeRequest(context, metadata.sharing, "view");
665
- return { sharing: metadata.sharing || null };
666
- },
667
- updateSharing: async (newSharing, context) => {
668
- authorizeRequest(context, metadata.sharing, "admin");
669
- if (metadata.sharing && context?.user?.email && context.user.email !== metadata.sharing.owner) {
670
- throw new Error("Only the session owner can update sharing settings");
671
- }
672
- if (newSharing.enabled && !newSharing.owner && context?.user?.email) {
673
- newSharing = { ...newSharing, owner: context.user.email };
674
- }
675
- metadata = { ...metadata, sharing: newSharing };
676
- metadataVersion++;
677
- notifyListeners({
678
- type: "update-session",
679
- sessionId,
680
- metadata: { value: metadata, version: metadataVersion }
681
- });
682
- return { success: true, sharing: newSharing };
683
- },
684
- // ── Listener Registration ──
685
- registerListener: async (callback, context) => {
686
- authorizeRequest(context, metadata.sharing, "view");
687
- listeners.push(callback);
688
- const replayMessages = messages.slice(-50);
689
- console.log(`[HYPHA SESSION ${sessionId}] Listener registered (total: ${listeners.length}), replaying ${replayMessages.length} of ${messages.length} messages`);
690
- for (const msg of replayMessages) {
691
- if (listeners.indexOf(callback) < 0) break;
692
- try {
693
- const result = callback.onUpdate({
694
- type: "new-message",
695
- sessionId,
696
- message: msg
697
- });
698
- if (result && typeof result.catch === "function") {
699
- try {
700
- await result;
701
- } catch (err) {
702
- console.error(`[HYPHA SESSION ${sessionId}] Replay listener error, removing:`, err?.message ?? err);
703
- removeListener(callback, "replay error");
704
- return { success: false, error: "Listener removed during replay" };
705
- }
706
- }
707
- } catch (err) {
708
- console.error(`[HYPHA SESSION ${sessionId}] Replay listener error, removing:`, err?.message ?? err);
709
- removeListener(callback, "replay error");
710
- return { success: false, error: "Listener removed during replay" };
711
- }
712
- }
713
- if (listeners.indexOf(callback) < 0) {
714
- return { success: false, error: "Listener was removed during replay" };
715
- }
716
- try {
717
- const result = callback.onUpdate({
718
- type: "update-session",
719
- sessionId,
720
- metadata: { value: metadata, version: metadataVersion },
721
- agentState: { value: agentState, version: agentStateVersion }
722
- });
723
- if (result && typeof result.catch === "function") {
724
- result.catch(() => {
725
- });
726
- }
727
- } catch {
728
- }
729
- try {
730
- const result = callback.onUpdate({
731
- type: "activity",
732
- sessionId,
733
- ...lastActivity
734
- });
735
- if (result && typeof result.catch === "function") {
736
- result.catch(() => {
737
- });
738
- }
739
- } catch {
740
- }
741
- return { success: true, listenerId: listeners.length - 1 };
742
- }
743
- },
744
- { overwrite: true }
745
- );
746
- console.log(`[HYPHA SESSION] Session service registered: ${serviceInfo.id}`);
747
- return {
748
- serviceInfo,
749
- pushMessage,
750
- get _agentState() {
751
- return agentState;
752
- },
753
- updateMetadata: (newMetadata) => {
754
- metadata = newMetadata;
755
- metadataVersion++;
756
- notifyListeners({
757
- type: "update-session",
758
- sessionId,
759
- metadata: { value: metadata, version: metadataVersion }
760
- });
761
- },
762
- updateAgentState: (newAgentState) => {
763
- agentState = newAgentState;
764
- agentStateVersion++;
765
- notifyListeners({
766
- type: "update-session",
767
- sessionId,
768
- agentState: { value: agentState, version: agentStateVersion }
769
- });
770
- },
771
- sendKeepAlive: (thinking, mode) => {
772
- lastActivity = { active: true, thinking: thinking || false, mode: mode || "remote", time: Date.now() };
773
- notifyListeners({
774
- type: "activity",
775
- sessionId,
776
- ...lastActivity
777
- });
778
- },
779
- sendSessionEnd: () => {
780
- lastActivity = { active: false, thinking: false, mode: "remote", time: Date.now() };
781
- notifyListeners({
782
- type: "activity",
783
- sessionId,
784
- ...lastActivity
785
- });
786
- },
787
- disconnect: async () => {
788
- await server.unregisterService(serviceInfo.id);
789
- }
790
- };
791
- }
792
-
793
- async function registerDebugService(server, machineId, deps) {
794
- const serviceInfo = await server.registerService(
795
- {
796
- id: `svamp-debug-${machineId}`,
797
- name: `Svamp Debug ${machineId.slice(0, 8)}`,
798
- type: "svamp-debug",
799
- config: { visibility: "public" },
800
- healthCheck: async () => ({
801
- ok: true,
802
- machineId,
803
- uptime: process.uptime(),
804
- timestamp: Date.now()
805
- }),
806
- getSessionStates: async () => {
807
- const sessions = deps.getTrackedSessions();
808
- const states = [];
809
- for (const s of sessions) {
810
- let activityState = null;
811
- try {
812
- const svc = deps.getSessionService(s.sessionId);
813
- if (svc) {
814
- activityState = await svc.getActivityState?.();
815
- }
816
- } catch {
817
- }
818
- states.push({
819
- sessionId: s.sessionId,
820
- active: s.active,
821
- pid: s.pid,
822
- startedBy: s.startedBy,
823
- directory: s.directory,
824
- activityState
825
- });
826
- }
827
- return states;
828
- },
829
- getMachineInfo: async () => ({
830
- machineId,
831
- hostname: (await import('os')).hostname(),
832
- platform: (await import('os')).platform(),
833
- uptime: process.uptime(),
834
- sessions: deps.getTrackedSessions().length
835
- }),
836
- // ── Artifact Sync RPCs ──
837
- getArtifactSyncStatus: async () => {
838
- const sync = deps.getArtifactSync?.();
839
- if (!sync) return { error: "Artifact sync not available" };
840
- return sync.getStatus();
841
- },
842
- forceSyncAll: async () => {
843
- const sync = deps.getArtifactSync?.();
844
- const sessionsDir = deps.getSessionsDir?.();
845
- if (!sync || !sessionsDir) return { error: "Artifact sync not available" };
846
- await sync.syncAll(sessionsDir, machineId);
847
- return { success: true, status: sync.getStatus() };
848
- },
849
- listRemoteSessions: async () => {
850
- const sync = deps.getArtifactSync?.();
851
- if (!sync) return [];
852
- return await sync.listRemoteSessions();
853
- }
854
- },
855
- { overwrite: true }
856
- );
857
- return {
858
- disconnect: async () => {
859
- await server.unregisterService(serviceInfo.id);
860
- }
861
- };
862
- }
863
-
864
- const COLLECTION_ALIAS = "svamp-agent-sessions";
865
- class SessionArtifactSync {
866
- server;
867
- artifactManager = null;
868
- collectionId = null;
869
- initialized = false;
870
- syncing = false;
871
- lastSyncAt = null;
872
- syncedSessions = /* @__PURE__ */ new Set();
873
- error = null;
874
- syncTimers = /* @__PURE__ */ new Map();
875
- log;
876
- constructor(server, log) {
877
- this.server = server;
878
- this.log = log;
879
- }
880
- async init() {
881
- try {
882
- this.artifactManager = await this.server.getService("public/artifact-manager");
883
- if (!this.artifactManager) {
884
- this.log("[ARTIFACT SYNC] Artifact manager service not available");
885
- this.error = "Artifact manager not available";
886
- return;
887
- }
888
- await this.ensureCollection();
889
- this.initialized = true;
890
- this.log("[ARTIFACT SYNC] Initialized successfully");
891
- } catch (err) {
892
- this.error = `Init failed: ${err.message}`;
893
- this.log(`[ARTIFACT SYNC] Init failed: ${err.message}`);
894
- }
895
- }
896
- async ensureCollection() {
897
- try {
898
- const existing = await this.artifactManager.read({
899
- artifact_id: COLLECTION_ALIAS,
900
- _rkwargs: true
901
- });
902
- this.collectionId = existing.id;
903
- this.log(`[ARTIFACT SYNC] Found existing collection: ${this.collectionId}`);
904
- } catch {
905
- const collection = await this.artifactManager.create({
906
- alias: COLLECTION_ALIAS,
907
- type: "collection",
908
- manifest: {
909
- name: "Svamp Agent Sessions",
910
- description: "Cloud-persisted session data for cross-machine continuity"
911
- },
912
- _rkwargs: true
913
- });
914
- this.collectionId = collection.id;
915
- await this.artifactManager.commit({
916
- artifact_id: this.collectionId,
917
- _rkwargs: true
918
- });
919
- this.log(`[ARTIFACT SYNC] Created new collection: ${this.collectionId}`);
920
- }
921
- }
922
- /**
923
- * Upload a file to an artifact using the presigned URL pattern:
924
- * 1. put_file() returns a presigned upload URL
925
- * 2. HTTP PUT the content to that URL
926
- */
927
- async uploadFile(artifactId, filePath, content) {
928
- const putUrl = await this.artifactManager.put_file({
929
- artifact_id: artifactId,
930
- file_path: filePath,
931
- _rkwargs: true
932
- });
933
- if (!putUrl || typeof putUrl !== "string") {
934
- throw new Error(`put_file returned invalid URL for ${filePath}: ${putUrl}`);
935
- }
936
- const resp = await fetch(putUrl, {
937
- method: "PUT",
938
- body: content,
939
- headers: { "Content-Type": "application/octet-stream" }
940
- });
941
- if (!resp.ok) {
942
- throw new Error(`Upload failed for ${filePath}: ${resp.status} ${resp.statusText}`);
943
- }
944
- }
945
- /**
946
- * Download a file from an artifact using the presigned URL pattern:
947
- * 1. get_file() returns a presigned download URL
948
- * 2. HTTP GET the content from that URL
949
- */
950
- async downloadFile(artifactId, filePath) {
951
- const getUrl = await this.artifactManager.get_file({
952
- artifact_id: artifactId,
953
- file_path: filePath,
954
- _rkwargs: true
955
- });
956
- if (!getUrl || typeof getUrl !== "string") return null;
957
- const resp = await fetch(getUrl);
958
- if (!resp.ok) return null;
959
- return await resp.text();
960
- }
961
- /**
962
- * Sync a session's metadata and messages to the artifact store.
963
- * Creates the artifact if it doesn't exist, updates if it does.
964
- */
965
- async syncSession(sessionId, sessionsDir, metadata, machineId) {
966
- if (!this.initialized || !this.artifactManager || !this.collectionId) {
967
- this.log(`[ARTIFACT SYNC] Not initialized, skipping sync for ${sessionId}`);
968
- return;
969
- }
970
- this.syncing = true;
971
- try {
972
- const artifactAlias = `session-${sessionId}`;
973
- const sessionJsonPath = join(sessionsDir, "session.json");
974
- const messagesPath = join(sessionsDir, "messages.jsonl");
975
- const sessionData = existsSync(sessionJsonPath) ? JSON.parse(readFileSync(sessionJsonPath, "utf-8")) : null;
976
- const messagesExist = existsSync(messagesPath);
977
- const messageCount = messagesExist ? readFileSync(messagesPath, "utf-8").split("\n").filter((l) => l.trim()).length : 0;
978
- let artifactId;
979
- try {
980
- const existing = await this.artifactManager.read({
981
- artifact_id: artifactAlias,
982
- _rkwargs: true
983
- });
984
- artifactId = existing.id;
985
- await this.artifactManager.edit({
986
- artifact_id: artifactId,
987
- manifest: {
988
- sessionId,
989
- machineId,
990
- metadata,
991
- messageCount,
992
- lastSyncAt: Date.now(),
993
- ...sessionData || {}
994
- },
995
- stage: true,
996
- _rkwargs: true
997
- });
998
- } catch {
999
- const artifact = await this.artifactManager.create({
1000
- alias: artifactAlias,
1001
- parent_id: this.collectionId,
1002
- type: "session",
1003
- manifest: {
1004
- sessionId,
1005
- machineId,
1006
- metadata,
1007
- messageCount,
1008
- createdAt: Date.now(),
1009
- lastSyncAt: Date.now(),
1010
- ...sessionData || {}
1011
- },
1012
- stage: true,
1013
- _rkwargs: true
1014
- });
1015
- artifactId = artifact.id;
1016
- }
1017
- if (sessionData) {
1018
- await this.uploadFile(artifactId, "session.json", JSON.stringify(sessionData, null, 2));
1019
- }
1020
- if (messagesExist) {
1021
- const messagesContent = readFileSync(messagesPath, "utf-8");
1022
- await this.uploadFile(artifactId, "messages.jsonl", messagesContent);
1023
- }
1024
- await this.artifactManager.commit({
1025
- artifact_id: artifactId,
1026
- _rkwargs: true
1027
- });
1028
- this.syncedSessions.add(sessionId);
1029
- this.lastSyncAt = Date.now();
1030
- this.log(`[ARTIFACT SYNC] Synced session ${sessionId} (${messageCount} messages)`);
1031
- } catch (err) {
1032
- this.error = `Sync failed for ${sessionId}: ${err.message}`;
1033
- this.log(`[ARTIFACT SYNC] Sync failed for ${sessionId}: ${err.message}`);
1034
- } finally {
1035
- this.syncing = false;
1036
- }
1037
- }
1038
- /**
1039
- * Schedule a debounced sync for a session (e.g., on each new message).
1040
- * Waits 30 seconds before syncing to batch multiple messages.
1041
- */
1042
- scheduleDebouncedSync(sessionId, sessionsDir, metadata, machineId, delayMs = 3e4) {
1043
- const existing = this.syncTimers.get(sessionId);
1044
- if (existing) clearTimeout(existing);
1045
- const timer = setTimeout(() => {
1046
- this.syncSession(sessionId, sessionsDir, metadata, machineId).catch(() => {
1047
- });
1048
- this.syncTimers.delete(sessionId);
1049
- }, delayMs);
1050
- this.syncTimers.set(sessionId, timer);
1051
- }
1052
- /**
1053
- * Download a session from artifact store to local disk.
1054
- */
1055
- async downloadSession(sessionId, targetDir) {
1056
- if (!this.initialized || !this.artifactManager) return null;
1057
- try {
1058
- const artifactAlias = `session-${sessionId}`;
1059
- const artifact = await this.artifactManager.read({
1060
- artifact_id: artifactAlias,
1061
- _rkwargs: true
1062
- });
1063
- if (!existsSync(targetDir)) mkdirSync(targetDir, { recursive: true });
1064
- try {
1065
- const data = await this.downloadFile(artifact.id, "session.json");
1066
- if (data) {
1067
- writeFileSync(join(targetDir, "session.json"), data);
1068
- }
1069
- } catch {
1070
- }
1071
- try {
1072
- const data = await this.downloadFile(artifact.id, "messages.jsonl");
1073
- if (data) {
1074
- writeFileSync(join(targetDir, "messages.jsonl"), data);
1075
- }
1076
- } catch {
1077
- }
1078
- return {
1079
- sessionData: artifact.manifest,
1080
- messageCount: artifact.manifest?.messageCount || 0
1081
- };
1082
- } catch (err) {
1083
- this.log(`[ARTIFACT SYNC] Download failed for ${sessionId}: ${err.message}`);
1084
- return null;
1085
- }
1086
- }
1087
- /**
1088
- * List all sessions stored in the artifact collection.
1089
- */
1090
- async listRemoteSessions() {
1091
- if (!this.initialized || !this.artifactManager || !this.collectionId) return [];
1092
- try {
1093
- const children = await this.artifactManager.list({
1094
- parent_id: this.collectionId,
1095
- _rkwargs: true
1096
- });
1097
- return (children || []).map((child) => ({
1098
- sessionId: child.manifest?.sessionId || child.alias?.replace("session-", ""),
1099
- machineId: child.manifest?.machineId,
1100
- messageCount: child.manifest?.messageCount || 0,
1101
- lastSyncAt: child.manifest?.lastSyncAt || 0
1102
- }));
1103
- } catch (err) {
1104
- this.log(`[ARTIFACT SYNC] List failed: ${err.message}`);
1105
- return [];
1106
- }
1107
- }
1108
- /**
1109
- * Get current sync status.
1110
- */
1111
- getStatus() {
1112
- return {
1113
- initialized: this.initialized,
1114
- collectionId: this.collectionId,
1115
- lastSyncAt: this.lastSyncAt,
1116
- syncing: this.syncing,
1117
- syncedSessions: [...this.syncedSessions],
1118
- error: this.error
1119
- };
1120
- }
1121
- /**
1122
- * Force sync all known sessions using the session index.
1123
- * @param svampHome The ~/.svamp/ directory (reads sessions-index.json)
1124
- */
1125
- async syncAll(svampHome, machineId) {
1126
- if (!this.initialized) return;
1127
- const indexFile = join(svampHome, "sessions-index.json");
1128
- if (!existsSync(indexFile)) return;
1129
- try {
1130
- const index = JSON.parse(readFileSync(indexFile, "utf-8"));
1131
- for (const [sessionId, entry] of Object.entries(index)) {
1132
- const sessionDir = join(entry.directory, ".svamp", sessionId);
1133
- if (existsSync(join(sessionDir, "session.json"))) {
1134
- await this.syncSession(sessionId, sessionDir, void 0, machineId);
1135
- }
1136
- }
1137
- } catch {
1138
- }
1139
- }
1140
- /**
1141
- * Cleanup timers on shutdown.
1142
- */
1143
- destroy() {
1144
- for (const timer of this.syncTimers.values()) {
1145
- clearTimeout(timer);
1146
- }
1147
- this.syncTimers.clear();
1148
- }
1149
- }
1150
-
1151
- const DEFAULT_TIMEOUTS = {
1152
- init: 6e4,
1153
- toolCall: 12e4,
1154
- think: 3e4
1155
- };
1156
- class DefaultTransport {
1157
- agentName;
1158
- constructor(agentName = "generic-acp") {
1159
- this.agentName = agentName;
1160
- }
1161
- getInitTimeout() {
1162
- return DEFAULT_TIMEOUTS.init;
1163
- }
1164
- filterStdoutLine(line) {
1165
- const trimmed = line.trim();
1166
- if (!trimmed) return null;
1167
- if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) return null;
1168
- try {
1169
- const parsed = JSON.parse(trimmed);
1170
- if (typeof parsed !== "object" || parsed === null) return null;
1171
- return line;
1172
- } catch {
1173
- return null;
1174
- }
1175
- }
1176
- handleStderr(_text, _context) {
1177
- return { message: null };
1178
- }
1179
- getToolPatterns() {
1180
- return [];
1181
- }
1182
- isInvestigationTool(_toolCallId, _toolKind) {
1183
- return false;
1184
- }
1185
- getToolCallTimeout(_toolCallId, toolKind) {
1186
- if (toolKind === "think") return DEFAULT_TIMEOUTS.think;
1187
- return DEFAULT_TIMEOUTS.toolCall;
1188
- }
1189
- extractToolNameFromId(_toolCallId) {
1190
- return null;
1191
- }
1192
- determineToolName(toolName, _toolCallId, _input, _context) {
1193
- return toolName;
1194
- }
1195
- }
1196
-
1197
- var DefaultTransport$1 = /*#__PURE__*/Object.freeze({
1198
- __proto__: null,
1199
- DefaultTransport: DefaultTransport
1200
- });
1201
-
1202
- const SVAMP_TOOLS_DIR$1 = join(homedir(), ".svamp", "tools");
1203
- const SVAMP_TOOLS_BIN$1 = join(SVAMP_TOOLS_DIR$1, "node_modules", ".bin");
1204
- const SVAMP_TOOLS_RG_BIN$1 = join(SVAMP_TOOLS_DIR$1, "node_modules", "@vscode", "ripgrep", "bin");
1205
- function wrapWithIsolation(originalCommand, originalArgs, config) {
1206
- switch (config.method) {
1207
- case "srt":
1208
- return wrapWithSrt(originalCommand, originalArgs, config);
1209
- case "bwrap":
1210
- return wrapWithBwrap(originalCommand, originalArgs, config);
1211
- case "docker":
1212
- return wrapWithContainer("docker", originalCommand, originalArgs, config);
1213
- case "podman":
1214
- return wrapWithContainer("podman", originalCommand, originalArgs, config);
1215
- }
1216
- }
1217
- function wrapWithSrt(command, args, config) {
1218
- const settings = {
1219
- filesystem: {
1220
- denyRead: config.srtConfig?.filesystem?.denyRead ?? [],
1221
- allowWrite: config.srtConfig?.filesystem?.allowWrite ?? [config.workspacePath],
1222
- denyWrite: config.srtConfig?.filesystem?.denyWrite ?? []
1223
- },
1224
- network: {
1225
- allowedDomains: config.srtConfig?.network?.allowedDomains ?? [],
1226
- deniedDomains: config.srtConfig?.network?.deniedDomains ?? []
1227
- }
1228
- };
1229
- const settingsPath = join(tmpdir(), `srt-settings-${process.pid}-${Date.now()}.json`);
1230
- writeFileSync(settingsPath, JSON.stringify(settings));
1231
- const pathParts = [SVAMP_TOOLS_BIN$1, SVAMP_TOOLS_RG_BIN$1];
1232
- if (process.env.PATH) pathParts.push(process.env.PATH);
1233
- return {
1234
- command: config.binaryPath,
1235
- args: ["--settings", settingsPath, command, ...args],
1236
- env: { PATH: pathParts.join(":") },
1237
- cleanupFiles: [settingsPath]
1238
- };
1239
- }
1240
- function wrapWithBwrap(command, args, config) {
1241
- const bwrapArgs = [
1242
- // Mount root filesystem read-only
1243
- "--ro-bind",
1244
- "/",
1245
- "/",
1246
- // Mount workspace read-write
1247
- "--bind",
1248
- config.workspacePath,
1249
- config.workspacePath,
1250
- // Mount /tmp read-write (many tools need it)
1251
- "--bind",
1252
- "/tmp",
1253
- "/tmp",
1254
- // Mount /dev read-write
1255
- "--dev",
1256
- "/dev",
1257
- // Mount /proc
1258
- "--proc",
1259
- "/proc",
1260
- // Unshare network — no network access inside sandbox
1261
- "--unshare-net",
1262
- // Unshare PID namespace
1263
- "--unshare-pid",
1264
- // Die when parent dies
1265
- "--die-with-parent",
1266
- // The actual command
1267
- "--",
1268
- command,
1269
- ...args
1270
- ];
1271
- return {
1272
- command: config.binaryPath,
1273
- args: bwrapArgs
1274
- };
1275
- }
1276
- function wrapWithContainer(runtime, command, args, config) {
1277
- const image = config.containerConfig?.image || "node:lts-slim";
1278
- const networkMode = config.containerConfig?.networkMode || "none";
1279
- const containerArgs = [
1280
- "run",
1281
- "--rm",
1282
- "-i",
1283
- // interactive (for stdin/stdout piping)
1284
- `--network=${networkMode}`,
1285
- "-v",
1286
- `${config.workspacePath}:${config.workspacePath}`,
1287
- "-w",
1288
- config.workspacePath
1289
- ];
1290
- if (config.containerConfig?.extraMounts) {
1291
- for (const mount of config.containerConfig.extraMounts) {
1292
- containerArgs.push("-v", mount);
1293
- }
1294
- }
1295
- containerArgs.push(image, command, ...args);
1296
- return {
1297
- command: config.binaryPath,
1298
- args: containerArgs
1299
- };
1300
- }
1301
-
1302
- const DEFAULT_IDLE_TIMEOUT_MS = 500;
1303
- const DEFAULT_TOOL_CALL_TIMEOUT_MS = 12e4;
1304
- function parseArgsFromContent(content) {
1305
- if (Array.isArray(content)) return { items: content };
1306
- if (content && typeof content === "object" && content !== null) {
1307
- return content;
1308
- }
1309
- return {};
1310
- }
1311
- function extractErrorDetail(content) {
1312
- if (!content) return void 0;
1313
- if (typeof content === "string") return content;
1314
- if (typeof content === "object" && content !== null && !Array.isArray(content)) {
1315
- const obj = content;
1316
- if (obj.error) {
1317
- const error = obj.error;
1318
- if (typeof error === "string") return error;
1319
- if (error && typeof error === "object" && "message" in error) {
1320
- const errObj = error;
1321
- if (typeof errObj.message === "string") return errObj.message;
1322
- }
1323
- return JSON.stringify(error);
1324
- }
1325
- if (typeof obj.message === "string") return obj.message;
1326
- const status = typeof obj.status === "string" ? obj.status : void 0;
1327
- const reason = typeof obj.reason === "string" ? obj.reason : void 0;
1328
- return status || reason || JSON.stringify(obj).substring(0, 500);
1329
- }
1330
- return void 0;
1331
- }
1332
- function formatDuration(startTime) {
1333
- if (!startTime) return "unknown";
1334
- const duration = Date.now() - startTime;
1335
- return `${(duration / 1e3).toFixed(2)}s`;
1336
- }
1337
- function handleAgentMessageChunk(update, ctx) {
1338
- const content = update.content;
1339
- if (!content || typeof content !== "object" || !("text" in content)) {
1340
- return { handled: false };
1341
- }
1342
- const text = content.text;
1343
- if (typeof text !== "string") return { handled: false };
1344
- const isThinking = /^\*\*[^*]+\*\*\n/.test(text);
1345
- if (isThinking) {
1346
- ctx.emit({ type: "event", name: "thinking", payload: { text, streaming: true } });
1347
- } else {
1348
- ctx.emit({ type: "model-output", textDelta: text });
1349
- ctx.clearIdleTimeout();
1350
- const idleTimeoutMs = ctx.transport.getIdleTimeout?.() ?? DEFAULT_IDLE_TIMEOUT_MS;
1351
- ctx.setIdleTimeout(() => {
1352
- if (ctx.activeToolCalls.size === 0) {
1353
- ctx.emitIdleStatus();
1354
- }
1355
- }, idleTimeoutMs);
1356
- }
1357
- return { handled: true };
1358
- }
1359
- function handleAgentThoughtChunk(update, ctx) {
1360
- const content = update.content;
1361
- if (!content || typeof content !== "object" || !("text" in content)) {
1362
- return { handled: false };
1363
- }
1364
- const text = content.text;
1365
- if (typeof text !== "string") return { handled: false };
1366
- ctx.emit({ type: "event", name: "thinking", payload: { text, streaming: true } });
1367
- return { handled: true };
1368
- }
1369
- function startToolCall(toolCallId, toolKind, update, ctx, source) {
1370
- const startTime = Date.now();
1371
- const toolKindStr = typeof toolKind === "string" ? toolKind : void 0;
1372
- const isInvestigation = ctx.transport.isInvestigationTool?.(toolCallId, toolKindStr) ?? false;
1373
- const extractedName = ctx.transport.extractToolNameFromId?.(toolCallId);
1374
- const realToolName = extractedName ?? (toolKindStr || "unknown");
1375
- ctx.toolCallIdToNameMap.set(toolCallId, realToolName);
1376
- ctx.activeToolCalls.add(toolCallId);
1377
- ctx.toolCallStartTimes.set(toolCallId, startTime);
1378
- ctx.log(`Tool call START: ${toolCallId} (${toolKind} -> ${realToolName})${isInvestigation ? " [INVESTIGATION]" : ""} (from ${source})`);
1379
- const timeoutMs = ctx.transport.getToolCallTimeout?.(toolCallId, toolKindStr) ?? DEFAULT_TOOL_CALL_TIMEOUT_MS;
1380
- if (!ctx.toolCallTimeouts.has(toolCallId)) {
1381
- const timeout = setTimeout(() => {
1382
- ctx.activeToolCalls.delete(toolCallId);
1383
- ctx.toolCallStartTimes.delete(toolCallId);
1384
- ctx.toolCallTimeouts.delete(toolCallId);
1385
- ctx.log(`Tool call TIMEOUT: ${toolCallId} (${toolKind}) after ${(timeoutMs / 1e3).toFixed(0)}s`);
1386
- if (ctx.activeToolCalls.size === 0) {
1387
- ctx.emitIdleStatus();
1388
- }
1389
- }, timeoutMs);
1390
- ctx.toolCallTimeouts.set(toolCallId, timeout);
1391
- }
1392
- ctx.clearIdleTimeout();
1393
- ctx.emit({ type: "status", status: "running" });
1394
- const args = parseArgsFromContent(update.content);
1395
- if (update.locations && Array.isArray(update.locations)) {
1396
- args.locations = update.locations;
1397
- }
1398
- ctx.emit({
1399
- type: "tool-call",
1400
- toolName: toolKindStr || "unknown",
1401
- args,
1402
- callId: toolCallId
1403
- });
1404
- }
1405
- function completeToolCall(toolCallId, toolKind, content, ctx) {
1406
- const startTime = ctx.toolCallStartTimes.get(toolCallId);
1407
- const duration = formatDuration(startTime);
1408
- const toolKindStr = typeof toolKind === "string" ? toolKind : "unknown";
1409
- ctx.activeToolCalls.delete(toolCallId);
1410
- ctx.toolCallStartTimes.delete(toolCallId);
1411
- const timeout = ctx.toolCallTimeouts.get(toolCallId);
1412
- if (timeout) {
1413
- clearTimeout(timeout);
1414
- ctx.toolCallTimeouts.delete(toolCallId);
1415
- }
1416
- ctx.log(`Tool call COMPLETED: ${toolCallId} (${toolKindStr}) - ${duration}. Active: ${ctx.activeToolCalls.size}`);
1417
- ctx.emit({ type: "tool-result", toolName: toolKindStr, result: content, callId: toolCallId });
1418
- if (ctx.activeToolCalls.size === 0) {
1419
- ctx.clearIdleTimeout();
1420
- ctx.emitIdleStatus();
1421
- }
1422
- }
1423
- function failToolCall(toolCallId, status, toolKind, content, ctx) {
1424
- const startTime = ctx.toolCallStartTimes.get(toolCallId);
1425
- const duration = formatDuration(startTime);
1426
- const toolKindStr = typeof toolKind === "string" ? toolKind : "unknown";
1427
- ctx.activeToolCalls.delete(toolCallId);
1428
- ctx.toolCallStartTimes.delete(toolCallId);
1429
- const timeout = ctx.toolCallTimeouts.get(toolCallId);
1430
- if (timeout) {
1431
- clearTimeout(timeout);
1432
- ctx.toolCallTimeouts.delete(toolCallId);
1433
- }
1434
- const errorDetail = extractErrorDetail(content);
1435
- ctx.log(`Tool call ${status.toUpperCase()}: ${toolCallId} (${toolKindStr}) - ${duration}. Active: ${ctx.activeToolCalls.size}`);
1436
- ctx.emit({
1437
- type: "tool-result",
1438
- toolName: toolKindStr,
1439
- result: errorDetail ? { error: errorDetail, status } : { error: `Tool call ${status}`, status },
1440
- callId: toolCallId
1441
- });
1442
- if (ctx.activeToolCalls.size === 0) {
1443
- ctx.clearIdleTimeout();
1444
- ctx.emitIdleStatus();
1445
- }
1446
- }
1447
- function handleToolCallUpdate(update, ctx) {
1448
- const status = update.status;
1449
- const toolCallId = update.toolCallId;
1450
- if (!toolCallId) return { handled: false };
1451
- const toolKind = update.kind || "unknown";
1452
- let toolCallCountSincePrompt = ctx.toolCallCountSincePrompt;
1453
- if (status === "in_progress" || status === "pending") {
1454
- if (!ctx.activeToolCalls.has(toolCallId)) {
1455
- toolCallCountSincePrompt++;
1456
- startToolCall(toolCallId, toolKind, update, ctx, "tool_call_update");
1457
- }
1458
- } else if (status === "completed") {
1459
- completeToolCall(toolCallId, toolKind, update.content, ctx);
1460
- } else if (status === "failed" || status === "cancelled") {
1461
- failToolCall(toolCallId, status, toolKind, update.content, ctx);
1462
- }
1463
- return { handled: true, toolCallCountSincePrompt };
1464
- }
1465
- function handleToolCall(update, ctx) {
1466
- const toolCallId = update.toolCallId;
1467
- const status = update.status;
1468
- const isInProgress = !status || status === "in_progress" || status === "pending";
1469
- if (!toolCallId || !isInProgress) return { handled: false };
1470
- if (ctx.activeToolCalls.has(toolCallId)) return { handled: true };
1471
- startToolCall(toolCallId, update.kind, update, ctx, "tool_call");
1472
- return { handled: true };
1473
- }
1474
- function handleLegacyMessageChunk(update, ctx) {
1475
- if (!update.messageChunk) return { handled: false };
1476
- const chunk = update.messageChunk;
1477
- if (chunk.textDelta) {
1478
- ctx.emit({ type: "model-output", textDelta: chunk.textDelta });
1479
- return { handled: true };
1480
- }
1481
- return { handled: false };
1482
- }
1483
- function handlePlanUpdate(update, ctx) {
1484
- if (!update.plan) return { handled: false };
1485
- ctx.emit({ type: "event", name: "plan", payload: update.plan });
1486
- return { handled: true };
1487
- }
1488
- function handleThinkingUpdate(update, ctx) {
1489
- if (!update.thinking) return { handled: false };
1490
- ctx.emit({ type: "event", name: "thinking", payload: update.thinking });
1491
- return { handled: true };
1492
- }
1493
-
1494
- function delay(ms) {
1495
- return new Promise((resolve) => setTimeout(resolve, ms));
1496
- }
1497
- const RETRY_CONFIG = {
1498
- maxAttempts: 3,
1499
- baseDelayMs: 1e3,
1500
- maxDelayMs: 5e3
1501
- };
1502
- function nodeToWebStreams(stdin, stdout) {
1503
- const writable = new WritableStream({
1504
- write(chunk) {
1505
- return new Promise((resolve, reject) => {
1506
- const ok = stdin.write(chunk, (err) => {
1507
- if (err) reject(err);
1508
- });
1509
- if (ok) resolve();
1510
- else stdin.once("drain", resolve);
1511
- });
1512
- },
1513
- close() {
1514
- return new Promise((resolve) => {
1515
- stdin.end(resolve);
1516
- });
1517
- },
1518
- abort(reason) {
1519
- stdin.destroy(reason instanceof Error ? reason : new Error(String(reason)));
1520
- }
1521
- });
1522
- const readable = new ReadableStream({
1523
- start(controller) {
1524
- stdout.on("data", (chunk) => {
1525
- controller.enqueue(new Uint8Array(chunk));
1526
- });
1527
- stdout.on("end", () => {
1528
- controller.close();
1529
- });
1530
- stdout.on("error", (err) => {
1531
- controller.error(err);
1532
- });
1533
- },
1534
- cancel() {
1535
- stdout.destroy();
1536
- }
1537
- });
1538
- return { writable, readable };
1539
- }
1540
- async function withRetry(operation, opts) {
1541
- let lastError = null;
1542
- const log = opts.log || (() => {
1543
- });
1544
- for (let attempt = 1; attempt <= opts.maxAttempts; attempt++) {
1545
- try {
1546
- return await operation();
1547
- } catch (error) {
1548
- if (error instanceof Error) {
1549
- lastError = error;
1550
- } else if (typeof error === "object" && error !== null) {
1551
- const obj = error;
1552
- const msg = typeof obj.message === "string" ? obj.message : JSON.stringify(error);
1553
- lastError = new Error(msg);
1554
- } else {
1555
- lastError = new Error(String(error));
1556
- }
1557
- const shouldRetry = opts.shouldRetry ? opts.shouldRetry(lastError) : true;
1558
- if (attempt < opts.maxAttempts && shouldRetry) {
1559
- const delayMs = Math.min(opts.baseDelayMs * Math.pow(2, attempt - 1), opts.maxDelayMs);
1560
- log(`${opts.operationName} failed (attempt ${attempt}/${opts.maxAttempts}): ${lastError.message}. Retrying in ${delayMs}ms...`);
1561
- await delay(delayMs);
1562
- } else {
1563
- break;
1564
- }
1565
- }
1566
- }
1567
- throw lastError;
1568
- }
1569
- class AcpBackend {
1570
- constructor(options) {
1571
- this.options = options;
1572
- this.transport = options.transportHandler ?? new DefaultTransport(options.agentName);
1573
- this.log = options.log || ((...args) => {
1574
- });
1575
- }
1576
- listeners = [];
1577
- process = null;
1578
- connection = null;
1579
- acpSessionId = null;
1580
- disposed = false;
1581
- activeToolCalls = /* @__PURE__ */ new Set();
1582
- toolCallTimeouts = /* @__PURE__ */ new Map();
1583
- toolCallStartTimes = /* @__PURE__ */ new Map();
1584
- toolCallIdToNameMap = /* @__PURE__ */ new Map();
1585
- recentPromptHadChangeTitle = false;
1586
- toolCallCountSincePrompt = 0;
1587
- idleTimeout = null;
1588
- transport;
1589
- log;
1590
- // Promise resolver for waitForIdle
1591
- idleResolver = null;
1592
- waitingForResponse = false;
1593
- onMessage(handler) {
1594
- this.listeners.push(handler);
1595
- }
1596
- offMessage(handler) {
1597
- const index = this.listeners.indexOf(handler);
1598
- if (index !== -1) this.listeners.splice(index, 1);
1599
- }
1600
- emit(msg) {
1601
- if (this.disposed) return;
1602
- for (const listener of this.listeners) {
1603
- try {
1604
- listener(msg);
1605
- } catch {
1606
- }
1607
- }
1608
- }
1609
- /** Get the underlying child process (for cleanup) */
1610
- getProcess() {
1611
- return this.process;
1612
- }
1613
- async startSession(initialPrompt) {
1614
- if (this.disposed) throw new Error("Backend has been disposed");
1615
- const sessionId = randomUUID();
1616
- this.emit({ type: "status", status: "starting" });
1617
- let startupStatusErrorEmitted = false;
1618
- try {
1619
- const args = this.options.args || [];
1620
- let spawnCommand = this.options.command;
1621
- let spawnArgs = args;
1622
- let isoEnv = {};
1623
- let isoCleanupFiles = [];
1624
- if (this.options.isolationConfig) {
1625
- const wrapped = wrapWithIsolation(spawnCommand, spawnArgs, this.options.isolationConfig);
1626
- spawnCommand = wrapped.command;
1627
- spawnArgs = wrapped.args;
1628
- if (wrapped.env) isoEnv = wrapped.env;
1629
- if (wrapped.cleanupFiles) isoCleanupFiles = wrapped.cleanupFiles;
1630
- this.log(`[ACP] Isolation: ${this.options.isolationConfig.method}`);
1631
- }
1632
- const spawnEnv = { ...process.env, ...this.options.env, ...isoEnv };
1633
- if (process.platform === "win32") {
1634
- const fullCommand = [spawnCommand, ...spawnArgs].join(" ");
1635
- this.process = spawn("cmd.exe", ["/c", fullCommand], {
1636
- cwd: this.options.cwd,
1637
- env: spawnEnv,
1638
- stdio: ["pipe", "pipe", "pipe"],
1639
- windowsHide: true
1640
- });
1641
- } else {
1642
- this.process = spawn(spawnCommand, spawnArgs, {
1643
- cwd: this.options.cwd,
1644
- env: spawnEnv,
1645
- stdio: ["pipe", "pipe", "pipe"]
1646
- });
1647
- }
1648
- if (isoCleanupFiles.length > 0) {
1649
- this.process.on("exit", async () => {
1650
- const { rm } = await import('node:fs/promises');
1651
- for (const f of isoCleanupFiles) rm(f, { force: true }).catch(() => {
1652
- });
1653
- });
1654
- }
1655
- if (!this.process.stdin || !this.process.stdout || !this.process.stderr) {
1656
- throw new Error("Failed to create stdio pipes");
1657
- }
1658
- let startupFailure = null;
1659
- let startupFailureSettled = false;
1660
- let rejectStartupFailure = null;
1661
- const startupFailurePromise = new Promise((_, reject) => {
1662
- rejectStartupFailure = (error) => {
1663
- if (startupFailureSettled) return;
1664
- startupFailureSettled = true;
1665
- startupFailure = error;
1666
- reject(error);
1667
- };
1668
- });
1669
- const signalStartupFailure = (error) => {
1670
- rejectStartupFailure?.(error);
1671
- };
1672
- this.process.stderr.on("data", (data) => {
1673
- const text = data.toString();
1674
- if (!text.trim()) return;
1675
- const hasActiveInvestigation = this.transport.isInvestigationTool ? Array.from(this.activeToolCalls).some((id) => this.transport.isInvestigationTool(id)) : false;
1676
- const context = {
1677
- activeToolCalls: this.activeToolCalls,
1678
- hasActiveInvestigation
1679
- };
1680
- this.log(`[ACP] stderr: ${text.trim()}`);
1681
- if (this.transport.handleStderr) {
1682
- const result = this.transport.handleStderr(text, context);
1683
- if (result.message) this.emit(result.message);
1684
- }
1685
- });
1686
- this.process.on("error", (err) => {
1687
- signalStartupFailure(err);
1688
- this.log(`[ACP] Process error: ${err.message}`);
1689
- startupStatusErrorEmitted = true;
1690
- this.emit({ type: "status", status: "error", detail: err.message });
1691
- });
1692
- this.process.on("exit", (code, signal) => {
1693
- if (!this.disposed && code !== 0 && code !== null) {
1694
- signalStartupFailure(new Error(`Exit code: ${code}`));
1695
- this.log(`[ACP] Process exited: code=${code}, signal=${signal}`);
1696
- this.emit({ type: "status", status: "stopped", detail: `Exit code: ${code}` });
1697
- }
1698
- });
1699
- const streams = nodeToWebStreams(this.process.stdin, this.process.stdout);
1700
- const transport = this.transport;
1701
- const logFn = this.log;
1702
- const filteredReadable = new ReadableStream({
1703
- async start(controller) {
1704
- const reader = streams.readable.getReader();
1705
- const decoder = new TextDecoder();
1706
- const encoder = new TextEncoder();
1707
- let buffer = "";
1708
- let filteredCount = 0;
1709
- try {
1710
- while (true) {
1711
- const { done, value } = await reader.read();
1712
- if (done) {
1713
- if (buffer.trim()) {
1714
- const filtered = transport.filterStdoutLine?.(buffer);
1715
- if (filtered === void 0) controller.enqueue(encoder.encode(buffer));
1716
- else if (filtered !== null) controller.enqueue(encoder.encode(filtered));
1717
- else filteredCount++;
1718
- }
1719
- if (filteredCount > 0) {
1720
- logFn(`[ACP] Filtered ${filteredCount} non-JSON lines from ${transport.agentName} stdout`);
1721
- }
1722
- controller.close();
1723
- break;
1724
- }
1725
- buffer += decoder.decode(value, { stream: true });
1726
- const lines = buffer.split("\n");
1727
- buffer = lines.pop() || "";
1728
- for (const line of lines) {
1729
- if (!line.trim()) continue;
1730
- const filtered = transport.filterStdoutLine?.(line);
1731
- if (filtered === void 0) controller.enqueue(encoder.encode(line + "\n"));
1732
- else if (filtered !== null) controller.enqueue(encoder.encode(filtered + "\n"));
1733
- else filteredCount++;
1734
- }
1735
- }
1736
- } catch (error) {
1737
- controller.error(error);
1738
- } finally {
1739
- reader.releaseLock();
1740
- }
1741
- }
1742
- });
1743
- const stream = ndJsonStream(streams.writable, filteredReadable);
1744
- const client = {
1745
- sessionUpdate: async (params) => {
1746
- this.handleSessionUpdate(params);
1747
- },
1748
- requestPermission: async (params) => {
1749
- const extendedParams = params;
1750
- const toolCall = extendedParams.toolCall;
1751
- let toolName = toolCall?.kind || toolCall?.toolName || extendedParams.kind || "Unknown tool";
1752
- const toolCallId = toolCall?.id || randomUUID();
1753
- const permissionId = toolCallId;
1754
- let input = {};
1755
- if (toolCall) {
1756
- input = toolCall.input || toolCall.arguments || toolCall.content || {};
1757
- } else {
1758
- input = extendedParams.input || extendedParams.arguments || extendedParams.content || {};
1759
- }
1760
- const context = {
1761
- recentPromptHadChangeTitle: this.recentPromptHadChangeTitle,
1762
- toolCallCountSincePrompt: this.toolCallCountSincePrompt
1763
- };
1764
- toolName = this.transport.determineToolName?.(toolName, toolCallId, input, context) ?? toolName;
1765
- this.toolCallCountSincePrompt++;
1766
- const options = extendedParams.options || [];
1767
- this.log(`[ACP] Permission request: tool=${toolName}, toolCallId=${toolCallId}`);
1768
- this.emit({
1769
- type: "permission-request",
1770
- id: permissionId,
1771
- reason: toolName,
1772
- payload: {
1773
- ...params,
1774
- permissionId,
1775
- toolCallId,
1776
- toolName,
1777
- input,
1778
- options: options.map((opt) => ({
1779
- id: opt.optionId,
1780
- name: opt.name,
1781
- kind: opt.kind
1782
- }))
1783
- }
1784
- });
1785
- if (this.options.permissionHandler) {
1786
- try {
1787
- const result = await this.options.permissionHandler.handleToolCall(toolCallId, toolName, input);
1788
- let optionId = "cancel";
1789
- if (result.decision === "approved" || result.decision === "approved_for_session") {
1790
- const proceedOnceOption2 = options.find(
1791
- (opt) => opt.optionId === "proceed_once" || opt.name?.toLowerCase().includes("once")
1792
- );
1793
- const proceedAlwaysOption = options.find(
1794
- (opt) => opt.optionId === "proceed_always" || opt.name?.toLowerCase().includes("always")
1795
- );
1796
- if (result.decision === "approved_for_session" && proceedAlwaysOption) {
1797
- optionId = proceedAlwaysOption.optionId || "proceed_always";
1798
- } else if (proceedOnceOption2) {
1799
- optionId = proceedOnceOption2.optionId || "proceed_once";
1800
- } else if (options.length > 0) {
1801
- optionId = options[0].optionId || "proceed_once";
1802
- }
1803
- this.emit({
1804
- type: "tool-result",
1805
- toolName,
1806
- result: { status: "approved", decision: result.decision },
1807
- callId: permissionId
1808
- });
1809
- } else {
1810
- const cancelOption = options.find(
1811
- (opt) => opt.optionId === "cancel" || opt.name?.toLowerCase().includes("cancel")
1812
- );
1813
- if (cancelOption) optionId = cancelOption.optionId || "cancel";
1814
- this.emit({
1815
- type: "tool-result",
1816
- toolName,
1817
- result: { status: "denied", decision: result.decision },
1818
- callId: permissionId
1819
- });
1820
- }
1821
- return { outcome: { outcome: "selected", optionId } };
1822
- } catch (error) {
1823
- this.log("[ACP] Error in permission handler:", error);
1824
- return { outcome: { outcome: "selected", optionId: "cancel" } };
1825
- }
1826
- }
1827
- const proceedOnceOption = options.find(
1828
- (opt) => opt.optionId === "proceed_once" || typeof opt.name === "string" && opt.name.toLowerCase().includes("once")
1829
- );
1830
- const defaultOptionId = proceedOnceOption?.optionId || (options.length > 0 && options[0].optionId ? options[0].optionId : "proceed_once");
1831
- return { outcome: { outcome: "selected", optionId: defaultOptionId } };
1832
- }
1833
- };
1834
- this.connection = new ClientSideConnection(
1835
- (agent) => client,
1836
- stream
1837
- );
1838
- const initRequest = {
1839
- protocolVersion: 1,
1840
- clientCapabilities: {
1841
- fs: { readTextFile: false, writeTextFile: false }
1842
- },
1843
- clientInfo: { name: "svamp-cli", version: "0.1.0" }
1844
- };
1845
- const initTimeout = this.transport.getInitTimeout();
1846
- this.log(`[ACP] Initializing connection (timeout: ${initTimeout}ms)...`);
1847
- const isNonRetryableStartupError = (error) => {
1848
- const maybeErr = error;
1849
- if (startupFailure && error === startupFailure) return true;
1850
- if (maybeErr.code === "ENOENT" || maybeErr.code === "EACCES" || maybeErr.code === "EPIPE") return true;
1851
- const msg = error.message.toLowerCase();
1852
- if (msg.includes("api key") || msg.includes("not configured") || msg.includes("401") || msg.includes("403")) return true;
1853
- return false;
1854
- };
1855
- await withRetry(
1856
- async () => {
1857
- let timeoutHandle = null;
1858
- try {
1859
- const result = await Promise.race([
1860
- startupFailurePromise,
1861
- this.connection.initialize(initRequest).then((res) => {
1862
- if (timeoutHandle) {
1863
- clearTimeout(timeoutHandle);
1864
- timeoutHandle = null;
1865
- }
1866
- return res;
1867
- }),
1868
- new Promise((_, reject) => {
1869
- timeoutHandle = setTimeout(() => {
1870
- reject(new Error(`Initialize timeout after ${initTimeout}ms - ${this.transport.agentName} did not respond`));
1871
- }, initTimeout);
1872
- })
1873
- ]);
1874
- return result;
1875
- } finally {
1876
- if (timeoutHandle) clearTimeout(timeoutHandle);
1877
- }
1878
- },
1879
- {
1880
- operationName: "Initialize",
1881
- maxAttempts: RETRY_CONFIG.maxAttempts,
1882
- baseDelayMs: RETRY_CONFIG.baseDelayMs,
1883
- maxDelayMs: RETRY_CONFIG.maxDelayMs,
1884
- shouldRetry: (error) => !isNonRetryableStartupError(error),
1885
- log: this.log
1886
- }
1887
- );
1888
- this.log(`[ACP] Initialize completed`);
1889
- const mcpServers = this.options.mcpServers ? Object.entries(this.options.mcpServers).map(([name, config]) => {
1890
- if (config.type === "http" && config.url) {
1891
- return { name, url: config.url };
1892
- }
1893
- return {
1894
- name,
1895
- command: config.command || "",
1896
- args: config.args || [],
1897
- env: config.env ? Object.entries(config.env).map(([envName, envValue]) => ({ name: envName, value: envValue })) : []
1898
- };
1899
- }) : [];
1900
- const newSessionRequest = {
1901
- cwd: this.options.cwd,
1902
- mcpServers
1903
- };
1904
- this.log(`[ACP] Creating new session...`);
1905
- const sessionResponse = await withRetry(
1906
- async () => {
1907
- let timeoutHandle = null;
1908
- try {
1909
- const result = await Promise.race([
1910
- startupFailurePromise,
1911
- this.connection.newSession(newSessionRequest).then((res) => {
1912
- if (timeoutHandle) {
1913
- clearTimeout(timeoutHandle);
1914
- timeoutHandle = null;
1915
- }
1916
- return res;
1917
- }),
1918
- new Promise((_, reject) => {
1919
- timeoutHandle = setTimeout(() => {
1920
- reject(new Error(`New session timeout after ${initTimeout}ms - ${this.transport.agentName} did not respond`));
1921
- }, initTimeout);
1922
- })
1923
- ]);
1924
- return result;
1925
- } finally {
1926
- if (timeoutHandle) clearTimeout(timeoutHandle);
1927
- }
1928
- },
1929
- {
1930
- operationName: "NewSession",
1931
- maxAttempts: RETRY_CONFIG.maxAttempts,
1932
- baseDelayMs: RETRY_CONFIG.baseDelayMs,
1933
- maxDelayMs: RETRY_CONFIG.maxDelayMs,
1934
- shouldRetry: (error) => !isNonRetryableStartupError(error),
1935
- log: this.log
1936
- }
1937
- );
1938
- this.acpSessionId = sessionResponse.sessionId;
1939
- this.log(`[ACP] Session created: ${this.acpSessionId}`);
1940
- this.emitInitialSessionMetadata(sessionResponse);
1941
- this.emitIdleStatus();
1942
- if (initialPrompt) {
1943
- this.sendPrompt(sessionId, initialPrompt).catch((error) => {
1944
- this.log("[ACP] Error sending initial prompt:", error);
1945
- this.emit({ type: "status", status: "error", detail: String(error) });
1946
- });
1947
- }
1948
- return { sessionId };
1949
- } catch (error) {
1950
- this.log("[ACP] Error starting session:", error);
1951
- if (!startupStatusErrorEmitted) {
1952
- this.emit({
1953
- type: "status",
1954
- status: "error",
1955
- detail: error instanceof Error ? error.message : String(error)
1956
- });
1957
- }
1958
- throw error;
1959
- }
1960
- }
1961
- createHandlerContext() {
1962
- return {
1963
- transport: this.transport,
1964
- activeToolCalls: this.activeToolCalls,
1965
- toolCallStartTimes: this.toolCallStartTimes,
1966
- toolCallTimeouts: this.toolCallTimeouts,
1967
- toolCallIdToNameMap: this.toolCallIdToNameMap,
1968
- idleTimeout: this.idleTimeout,
1969
- toolCallCountSincePrompt: this.toolCallCountSincePrompt,
1970
- emit: (msg) => this.emit(msg),
1971
- emitIdleStatus: () => this.emitIdleStatus(),
1972
- clearIdleTimeout: () => {
1973
- if (this.idleTimeout) {
1974
- clearTimeout(this.idleTimeout);
1975
- this.idleTimeout = null;
1976
- }
1977
- },
1978
- setIdleTimeout: (callback, ms) => {
1979
- this.idleTimeout = setTimeout(() => {
1980
- callback();
1981
- this.idleTimeout = null;
1982
- }, ms);
1983
- },
1984
- log: this.log
1985
- };
1986
- }
1987
- emitInitialSessionMetadata(sessionResponse) {
1988
- if (Array.isArray(sessionResponse.configOptions)) {
1989
- this.emit({
1990
- type: "event",
1991
- name: "config_options_update",
1992
- payload: { configOptions: sessionResponse.configOptions }
1993
- });
1994
- }
1995
- if (sessionResponse.modes) {
1996
- this.emit({ type: "event", name: "modes_update", payload: sessionResponse.modes });
1997
- this.emit({ type: "event", name: "current_mode_update", payload: { currentModeId: sessionResponse.modes.currentModeId } });
1998
- }
1999
- if (sessionResponse.models) {
2000
- this.emit({ type: "event", name: "models_update", payload: sessionResponse.models });
2001
- }
2002
- }
2003
- handleSessionUpdate(params) {
2004
- const notification = params;
2005
- const update = notification.update;
2006
- if (!update) return;
2007
- const sessionUpdateType = update.sessionUpdate;
2008
- const updateType = sessionUpdateType;
2009
- this.log(`[ACP] sessionUpdate: ${sessionUpdateType}`);
2010
- const ctx = this.createHandlerContext();
2011
- if (sessionUpdateType === "agent_message_chunk") {
2012
- handleAgentMessageChunk(update, ctx);
2013
- return;
2014
- }
2015
- if (sessionUpdateType === "tool_call_update") {
2016
- const result = handleToolCallUpdate(update, ctx);
2017
- if (result.toolCallCountSincePrompt !== void 0) {
2018
- this.toolCallCountSincePrompt = result.toolCallCountSincePrompt;
2019
- }
2020
- return;
2021
- }
2022
- if (sessionUpdateType === "agent_thought_chunk") {
2023
- handleAgentThoughtChunk(update, ctx);
2024
- return;
2025
- }
2026
- if (sessionUpdateType === "tool_call") {
2027
- handleToolCall(update, ctx);
2028
- return;
2029
- }
2030
- if (sessionUpdateType === "available_commands_update") {
2031
- const commands = update.availableCommands;
2032
- if (Array.isArray(commands)) {
2033
- this.emit({ type: "event", name: "available_commands", payload: commands });
2034
- }
2035
- return;
2036
- }
2037
- if (updateType === "config_option_update" || updateType === "config_options_update") {
2038
- const configOptions = update.configOptions;
2039
- if (Array.isArray(configOptions)) {
2040
- this.emit({ type: "event", name: "config_options_update", payload: { configOptions } });
2041
- }
2042
- return;
2043
- }
2044
- if (updateType === "current_mode_update") {
2045
- const currentModeId = update.currentModeId;
2046
- if (typeof currentModeId === "string" && currentModeId.length > 0) {
2047
- this.emit({ type: "event", name: "current_mode_update", payload: { currentModeId } });
2048
- }
2049
- return;
2050
- }
2051
- handleLegacyMessageChunk(update, ctx);
2052
- handlePlanUpdate(update, ctx);
2053
- handleThinkingUpdate(update, ctx);
2054
- }
2055
- emitIdleStatus() {
2056
- this.emit({ type: "status", status: "idle" });
2057
- if (this.idleResolver) {
2058
- this.idleResolver();
2059
- }
2060
- }
2061
- async sendPrompt(sessionId, prompt) {
2062
- const promptHasChangeTitle = this.options.hasChangeTitleInstruction?.(prompt) ?? false;
2063
- this.toolCallCountSincePrompt = 0;
2064
- this.recentPromptHadChangeTitle = promptHasChangeTitle;
2065
- if (this.disposed) throw new Error("Backend has been disposed");
2066
- if (!this.connection || !this.acpSessionId) throw new Error("Session not started");
2067
- this.emit({ type: "status", status: "running" });
2068
- this.waitingForResponse = true;
2069
- try {
2070
- this.log(`[ACP] Sending prompt (length: ${prompt.length})`);
2071
- const contentBlock = { type: "text", text: prompt };
2072
- const promptRequest = {
2073
- sessionId: this.acpSessionId,
2074
- prompt: [contentBlock]
2075
- };
2076
- await this.connection.prompt(promptRequest);
2077
- this.log("[ACP] Prompt request sent");
2078
- } catch (error) {
2079
- this.log("[ACP] Error sending prompt:", error);
2080
- this.waitingForResponse = false;
2081
- let errorDetail;
2082
- if (error instanceof Error) {
2083
- errorDetail = error.message;
2084
- } else if (typeof error === "object" && error !== null) {
2085
- const errObj = error;
2086
- errorDetail = typeof errObj.message === "string" ? errObj.message : String(error);
2087
- } else {
2088
- errorDetail = String(error);
2089
- }
2090
- this.emit({ type: "status", status: "error", detail: errorDetail });
2091
- throw error;
2092
- }
2093
- }
2094
- async waitForResponseComplete(timeoutMs = 12e4) {
2095
- if (!this.waitingForResponse) return;
2096
- return new Promise((resolve, reject) => {
2097
- const timeout = setTimeout(() => {
2098
- this.idleResolver = null;
2099
- this.waitingForResponse = false;
2100
- reject(new Error("Timeout waiting for response to complete"));
2101
- }, timeoutMs);
2102
- this.idleResolver = () => {
2103
- clearTimeout(timeout);
2104
- this.idleResolver = null;
2105
- this.waitingForResponse = false;
2106
- resolve();
2107
- };
2108
- });
2109
- }
2110
- async cancel(sessionId) {
2111
- if (!this.connection || !this.acpSessionId) return;
2112
- try {
2113
- await this.connection.cancel({ sessionId: this.acpSessionId });
2114
- this.emit({ type: "status", status: "stopped", detail: "Cancelled by user" });
2115
- } catch (error) {
2116
- this.log("[ACP] Error cancelling:", error);
2117
- }
2118
- }
2119
- async respondToPermission(requestId, approved) {
2120
- this.log(`[ACP] Permission response (UI only): ${requestId} = ${approved}`);
2121
- this.emit({ type: "permission-response", id: requestId, approved });
2122
- }
2123
- async dispose() {
2124
- if (this.disposed) return;
2125
- this.log("[ACP] Disposing backend");
2126
- this.disposed = true;
2127
- if (this.connection && this.acpSessionId) {
2128
- try {
2129
- await Promise.race([
2130
- this.connection.cancel({ sessionId: this.acpSessionId }),
2131
- new Promise((resolve) => setTimeout(resolve, 2e3))
2132
- ]);
2133
- } catch {
2134
- }
2135
- }
2136
- if (this.process) {
2137
- this.process.kill("SIGTERM");
2138
- await new Promise((resolve) => {
2139
- const timeout = setTimeout(() => {
2140
- if (this.process) this.process.kill("SIGKILL");
2141
- resolve();
2142
- }, 1e3);
2143
- this.process?.once("exit", () => {
2144
- clearTimeout(timeout);
2145
- resolve();
2146
- });
2147
- });
2148
- this.process = null;
2149
- }
2150
- if (this.idleTimeout) {
2151
- clearTimeout(this.idleTimeout);
2152
- this.idleTimeout = null;
2153
- }
2154
- this.listeners = [];
2155
- this.connection = null;
2156
- this.acpSessionId = null;
2157
- this.activeToolCalls.clear();
2158
- for (const timeout of this.toolCallTimeouts.values()) clearTimeout(timeout);
2159
- this.toolCallTimeouts.clear();
2160
- this.toolCallStartTimes.clear();
2161
- }
2162
- }
2163
-
2164
- var acpBackend = /*#__PURE__*/Object.freeze({
2165
- __proto__: null,
2166
- AcpBackend: AcpBackend
2167
- });
2168
-
2169
- const KNOWN_ACP_AGENTS = {
2170
- gemini: { command: "gemini", args: ["--experimental-acp"] },
2171
- opencode: { command: "opencode", args: ["acp"] }
2172
- };
2173
- const KNOWN_MCP_AGENTS = {
2174
- codex: { command: "codex", args: ["mcp-server"] }
2175
- };
2176
- function resolveAcpAgentConfig(cliArgs) {
2177
- if (cliArgs.length === 0) {
2178
- throw new Error("Usage: svamp agent <agent-name> or svamp agent -- <command> [args]");
2179
- }
2180
- if (cliArgs[0] === "--") {
2181
- const command = cliArgs[1];
2182
- if (!command) {
2183
- throw new Error('Missing command after "--". Usage: svamp agent -- <command> [args]');
2184
- }
2185
- return {
2186
- agentName: command,
2187
- command,
2188
- args: cliArgs.slice(2)
2189
- };
2190
- }
2191
- const agentName = cliArgs[0];
2192
- const knownAcp = KNOWN_ACP_AGENTS[agentName];
2193
- if (knownAcp) {
2194
- const passthroughArgs = cliArgs.slice(1).filter((arg) => !(agentName === "opencode" && arg === "--acp"));
2195
- return {
2196
- agentName,
2197
- command: knownAcp.command,
2198
- args: [...knownAcp.args, ...passthroughArgs]
2199
- };
2200
- }
2201
- const knownMcp = KNOWN_MCP_AGENTS[agentName];
2202
- if (knownMcp) {
2203
- return {
2204
- agentName,
2205
- command: knownMcp.command,
2206
- args: [...knownMcp.args, ...cliArgs.slice(1)]
2207
- };
2208
- }
2209
- return {
2210
- agentName,
2211
- command: agentName,
2212
- args: cliArgs.slice(1)
2213
- };
2214
- }
2215
-
2216
- var acpAgentConfig = /*#__PURE__*/Object.freeze({
2217
- __proto__: null,
2218
- KNOWN_ACP_AGENTS: KNOWN_ACP_AGENTS,
2219
- KNOWN_MCP_AGENTS: KNOWN_MCP_AGENTS,
2220
- resolveAcpAgentConfig: resolveAcpAgentConfig
2221
- });
2222
-
2223
- function bridgeAcpToSession(backend, sessionService, getMetadata, setMetadata, log, onTurnEnd) {
2224
- let pendingText = "";
2225
- let flushTimer = null;
2226
- function flushText() {
2227
- if (pendingText) {
2228
- sessionService.pushMessage({
2229
- type: "assistant",
2230
- content: [{ type: "text", text: pendingText }]
2231
- }, "agent");
2232
- pendingText = "";
2233
- }
2234
- if (flushTimer) {
2235
- clearTimeout(flushTimer);
2236
- flushTimer = null;
2237
- }
2238
- }
2239
- backend.onMessage((msg) => {
2240
- switch (msg.type) {
2241
- case "model-output": {
2242
- if (msg.textDelta) {
2243
- pendingText += msg.textDelta;
2244
- if (!flushTimer) {
2245
- flushTimer = setTimeout(flushText, 100);
2246
- }
2247
- } else if (msg.fullText) {
2248
- flushText();
2249
- sessionService.pushMessage({
2250
- type: "assistant",
2251
- content: [{ type: "text", text: msg.fullText }]
2252
- }, "agent");
2253
- }
2254
- break;
2255
- }
2256
- case "status": {
2257
- if (msg.status === "idle") {
2258
- flushText();
2259
- sessionService.sendKeepAlive(false);
2260
- setMetadata((m) => ({ ...m, lifecycleState: "idle" }));
2261
- onTurnEnd?.();
2262
- } else if (msg.status === "running" || msg.status === "starting") {
2263
- sessionService.sendKeepAlive(true);
2264
- setMetadata((m) => ({ ...m, lifecycleState: "running" }));
2265
- } else if (msg.status === "error") {
2266
- flushText();
2267
- sessionService.pushMessage(
2268
- { type: "message", message: `Agent process exited unexpectedly: ${msg.detail || "Unknown error"}` },
2269
- "event"
2270
- );
2271
- sessionService.sendSessionEnd();
2272
- setMetadata((m) => ({ ...m, lifecycleState: "error" }));
2273
- } else if (msg.status === "stopped") {
2274
- flushText();
2275
- sessionService.sendSessionEnd();
2276
- setMetadata((m) => ({ ...m, lifecycleState: "stopped" }));
2277
- }
2278
- break;
2279
- }
2280
- case "tool-call": {
2281
- flushText();
2282
- sessionService.pushMessage({
2283
- type: "assistant",
2284
- content: [{
2285
- type: "tool_use",
2286
- id: msg.callId,
2287
- name: msg.toolName,
2288
- input: msg.args
2289
- }]
2290
- }, "agent");
2291
- break;
2292
- }
2293
- case "tool-result": {
2294
- sessionService.pushMessage({
2295
- type: "assistant",
2296
- content: [{
2297
- type: "tool_result",
2298
- tool_use_id: msg.callId,
2299
- content: typeof msg.result === "string" ? msg.result : JSON.stringify(msg.result)
2300
- }]
2301
- }, "agent");
2302
- break;
2303
- }
2304
- case "permission-request": {
2305
- const currentRequests = { ...sessionService._agentState?.requests };
2306
- const payload = msg.payload;
2307
- sessionService.updateAgentState({
2308
- controlledByUser: false,
2309
- requests: {
2310
- ...currentRequests,
2311
- [msg.id]: {
2312
- tool: payload?.toolName || msg.reason,
2313
- arguments: payload?.input || {},
2314
- createdAt: Date.now()
2315
- }
2316
- }
2317
- });
2318
- break;
2319
- }
2320
- case "permission-response": {
2321
- const reqs = { ...sessionService._agentState?.requests };
2322
- const completedReqs = { ...sessionService._agentState?.completedRequests };
2323
- const existingReq = reqs[msg.id];
2324
- delete reqs[msg.id];
2325
- sessionService.updateAgentState({
2326
- controlledByUser: false,
2327
- requests: reqs,
2328
- completedRequests: {
2329
- ...completedReqs,
2330
- [msg.id]: {
2331
- ...existingReq || {},
2332
- completedAt: Date.now(),
2333
- status: msg.approved ? "approved" : "denied"
2334
- }
2335
- }
2336
- });
2337
- break;
2338
- }
2339
- case "event": {
2340
- if (msg.name === "thinking") {
2341
- const payload = msg.payload;
2342
- const text = payload?.text || JSON.stringify(payload);
2343
- sessionService.pushMessage({
2344
- type: "assistant",
2345
- content: [{ type: "thinking", thinking: text }]
2346
- }, "agent");
2347
- } else {
2348
- sessionService.pushMessage({
2349
- type: "session_event",
2350
- message: `[${msg.name}] ${JSON.stringify(msg.payload)}`
2351
- }, "session");
2352
- }
2353
- break;
2354
- }
2355
- }
2356
- });
2357
- }
2358
- class HyphaPermissionHandler {
2359
- constructor(shouldAutoAllow, log) {
2360
- this.shouldAutoAllow = shouldAutoAllow;
2361
- this.log = log;
2362
- }
2363
- pendingPermissions = /* @__PURE__ */ new Map();
2364
- async handleToolCall(toolCallId, toolName, input) {
2365
- if (this.shouldAutoAllow(toolName, input)) {
2366
- this.log(`[ACP Permission] Auto-allowing ${toolName}`);
2367
- return { decision: "approved" };
2368
- }
2369
- return new Promise((resolve) => {
2370
- this.pendingPermissions.set(toolCallId, { resolve, toolName, input });
2371
- });
2372
- }
2373
- /**
2374
- * Called from the session service's onPermissionResponse callback
2375
- */
2376
- resolvePermission(requestId, approved) {
2377
- const pending = this.pendingPermissions.get(requestId);
2378
- if (pending) {
2379
- this.pendingPermissions.delete(requestId);
2380
- pending.resolve({
2381
- decision: approved ? "approved" : "denied"
2382
- });
2383
- } else {
2384
- this.log(`[ACP Permission] No pending permission for id=${requestId}`);
2385
- }
2386
- }
2387
- /** Reject all pending permissions (e.g. when process exits) */
2388
- rejectAll(reason) {
2389
- for (const [id, pending] of this.pendingPermissions) {
2390
- pending.resolve({ decision: "denied" });
2391
- }
2392
- this.pendingPermissions.clear();
2393
- }
2394
- }
2395
-
2396
- const DEFAULT_TIMEOUT = 14 * 24 * 60 * 60 * 1e3;
2397
- function getCodexMcpCommand() {
2398
- try {
2399
- const version = execSync("codex --version", { encoding: "utf8" }).trim();
2400
- const match = version.match(/codex-cli\s+(\d+\.\d+\.\d+(?:-alpha\.\d+)?)/);
2401
- if (!match) return "mcp-server";
2402
- const versionStr = match[1];
2403
- const [major, minor, patch] = versionStr.split(/[-.]/).map(Number);
2404
- if (major > 0 || minor > 43) return "mcp-server";
2405
- if (minor === 43 && patch === 0) {
2406
- if (versionStr.includes("-alpha.")) {
2407
- const alphaNum = parseInt(versionStr.split("-alpha.")[1]);
2408
- return alphaNum >= 5 ? "mcp-server" : "mcp";
2409
- }
2410
- return "mcp-server";
2411
- }
2412
- return "mcp";
2413
- } catch {
2414
- return null;
2415
- }
2416
- }
2417
- class CodexMcpBackend {
2418
- listeners = [];
2419
- client;
2420
- transport = null;
2421
- disposed = false;
2422
- codexSessionId = null;
2423
- conversationId = null;
2424
- svampSessionId = null;
2425
- log;
2426
- options;
2427
- connected = false;
2428
- // Pending elicitation approvals
2429
- pendingApprovals = /* @__PURE__ */ new Map();
2430
- // Temp files from isolation wrapping (cleaned up on disconnect)
2431
- _isolationCleanupFiles = [];
2432
- constructor(options) {
2433
- this.options = options;
2434
- this.log = options.log || (() => {
2435
- });
2436
- this.client = new Client(
2437
- { name: "svamp-codex-client", version: "1.0.0" },
2438
- { capabilities: { elicitation: {} } }
2439
- );
2440
- this.client.setNotificationHandler(z.object({
2441
- method: z.literal("codex/event"),
2442
- params: z.object({ msg: z.any() })
2443
- }).passthrough(), (data) => {
2444
- const msg = data.params.msg;
2445
- this.updateIdentifiersFromEvent(msg);
2446
- this.handleCodexEvent(msg);
2447
- });
2448
- }
2449
- // ── AgentBackend interface ──────────────────────────────────────────
2450
- onMessage(handler) {
2451
- this.listeners.push(handler);
2452
- }
2453
- offMessage(handler) {
2454
- const idx = this.listeners.indexOf(handler);
2455
- if (idx !== -1) this.listeners.splice(idx, 1);
2456
- }
2457
- async startSession(initialPrompt) {
2458
- const sessionId = randomUUID();
2459
- this.svampSessionId = sessionId;
2460
- this.emit({ type: "status", status: "starting" });
2461
- await this.connect();
2462
- this.emit({ type: "status", status: "idle" });
2463
- if (initialPrompt) {
2464
- this.sendPrompt(sessionId, initialPrompt).catch((err) => {
2465
- this.log(`[Codex] Error sending initial prompt: ${err.message}`);
2466
- this.emit({ type: "status", status: "error", detail: err.message });
2467
- });
2468
- }
2469
- return { sessionId };
2470
- }
2471
- async sendPrompt(sessionId, prompt) {
2472
- if (!this.connected) throw new Error("Codex not connected");
2473
- this.emit({ type: "status", status: "running" });
2474
- try {
2475
- let response;
2476
- if (this.codexSessionId) {
2477
- response = await this.continueSession(prompt);
2478
- } else {
2479
- const config = {
2480
- prompt,
2481
- cwd: this.options.cwd,
2482
- ...this.options.model ? { model: this.options.model } : {}
2483
- };
2484
- response = await this.startCodexSession(config);
2485
- }
2486
- if (response?.content && Array.isArray(response.content)) {
2487
- for (const block of response.content) {
2488
- if (block.type === "text" && block.text) {
2489
- this.emit({ type: "model-output", fullText: block.text });
2490
- }
2491
- }
2492
- }
2493
- } catch (err) {
2494
- this.log(`[Codex] Error in sendPrompt: ${err.message}`);
2495
- this.emit({ type: "status", status: "error", detail: err.message });
2496
- throw err;
2497
- } finally {
2498
- this.emit({ type: "status", status: "idle" });
2499
- }
2500
- }
2501
- async cancel(_sessionId) {
2502
- this.log("[Codex] Cancel requested");
2503
- this.emit({ type: "status", status: "idle" });
2504
- }
2505
- async respondToPermission(requestId, approved) {
2506
- const pending = this.pendingApprovals.get(requestId);
2507
- if (pending) {
2508
- this.pendingApprovals.delete(requestId);
2509
- pending.resolve({
2510
- action: approved ? "accept" : "decline",
2511
- content: { approval: approved ? "approve" : "deny" }
2512
- });
2513
- this.emit({ type: "permission-response", id: requestId, approved });
2514
- }
2515
- }
2516
- async dispose() {
2517
- if (this.disposed) return;
2518
- this.disposed = true;
2519
- this.log("[Codex] Disposing backend");
2520
- for (const [, pending] of this.pendingApprovals) {
2521
- pending.resolve({ action: "decline" });
2522
- }
2523
- this.pendingApprovals.clear();
2524
- await this.disconnect();
2525
- this.listeners = [];
2526
- }
2527
- /** Get the transport's child process PID for tracking */
2528
- get pid() {
2529
- return this.transport?.pid ?? null;
2530
- }
2531
- /**
2532
- * Return a process-like object for TrackedSession.childProcess.
2533
- * We expose a minimal { kill } object that closes the transport.
2534
- */
2535
- getProcess() {
2536
- if (!this.transport) return null;
2537
- const pid = this.pid;
2538
- return {
2539
- kill: (signal) => {
2540
- if (pid) {
2541
- try {
2542
- process.kill(pid, signal || "SIGTERM");
2543
- } catch {
2544
- }
2545
- }
2546
- }
2547
- };
2548
- }
2549
- // ── MCP connection ─────────────────────────────────────────────────
2550
- async connect() {
2551
- if (this.connected) return;
2552
- const mcpCommand = getCodexMcpCommand();
2553
- if (mcpCommand === null) {
2554
- throw new Error(
2555
- "Codex CLI not found or not executable.\n\nTo install codex:\n npm install -g @openai/codex\n"
2556
- );
2557
- }
2558
- this.log(`[Codex] Connecting via: codex ${mcpCommand}`);
2559
- const env = {};
2560
- for (const key of Object.keys(process.env)) {
2561
- const value = process.env[key];
2562
- if (typeof value === "string") env[key] = value;
2563
- }
2564
- if (this.options.env) {
2565
- Object.assign(env, this.options.env);
2566
- }
2567
- const rolloutFilter = "codex_core::rollout::list=off";
2568
- const existingRustLog = env.RUST_LOG?.trim();
2569
- if (!existingRustLog) {
2570
- env.RUST_LOG = rolloutFilter;
2571
- } else if (!existingRustLog.includes("codex_core::rollout::list=")) {
2572
- env.RUST_LOG = `${existingRustLog},${rolloutFilter}`;
2573
- }
2574
- let transportCommand = "codex";
2575
- let transportArgs = [mcpCommand];
2576
- if (this.options.isolationConfig) {
2577
- const wrapped = wrapWithIsolation(transportCommand, transportArgs, this.options.isolationConfig);
2578
- transportCommand = wrapped.command;
2579
- transportArgs = wrapped.args;
2580
- if (wrapped.env) Object.assign(env, wrapped.env);
2581
- if (wrapped.cleanupFiles) {
2582
- this._isolationCleanupFiles = wrapped.cleanupFiles;
2583
- }
2584
- this.log(`[Codex] Isolation: ${this.options.isolationConfig.method}`);
2585
- }
2586
- this.transport = new StdioClientTransport({
2587
- command: transportCommand,
2588
- args: transportArgs,
2589
- env
2590
- });
2591
- this.registerPermissionHandlers();
2592
- try {
2593
- await this.client.connect(this.transport);
2594
- this.connected = true;
2595
- this.log("[Codex] MCP connection established");
2596
- } catch (err) {
2597
- this.transport = null;
2598
- throw err;
2599
- }
2600
- }
2601
- async disconnect() {
2602
- if (!this.connected) return;
2603
- const pid = this.pid;
2604
- this.log(`[Codex] Disconnecting (pid=${pid ?? "none"})`);
2605
- try {
2606
- await this.client.close();
2607
- } catch {
2608
- try {
2609
- await this.transport?.close?.();
2610
- } catch {
2611
- }
2612
- }
2613
- if (pid) {
2614
- try {
2615
- process.kill(pid, 0);
2616
- try {
2617
- process.kill(pid, "SIGKILL");
2618
- } catch {
2619
- }
2620
- } catch {
2621
- }
2622
- }
2623
- this.transport = null;
2624
- this.connected = false;
2625
- if (this._isolationCleanupFiles.length > 0) {
2626
- const { rm } = await import('node:fs/promises');
2627
- for (const f of this._isolationCleanupFiles) rm(f, { force: true }).catch(() => {
2628
- });
2629
- this._isolationCleanupFiles = [];
2630
- }
2631
- }
2632
- // ── Permission handling ────────────────────────────────────────────
2633
- registerPermissionHandlers() {
2634
- this.client.setRequestHandler(
2635
- ElicitRequestSchema,
2636
- async (request) => {
2637
- const params = request.params;
2638
- const callId = params.codex_call_id || randomUUID();
2639
- this.log(`[Codex] Elicitation request: ${params.message}`);
2640
- this.emit({
2641
- type: "permission-request",
2642
- id: callId,
2643
- reason: params.codex_command ? `Execute: ${Array.isArray(params.codex_command) ? params.codex_command.join(" ") : params.codex_command}` : params.message || "Codex requires approval",
2644
- payload: {
2645
- toolName: "CodexBash",
2646
- input: {
2647
- command: params.codex_command,
2648
- cwd: params.codex_cwd
2649
- }
2650
- }
2651
- });
2652
- return new Promise((resolve) => {
2653
- this.pendingApprovals.set(callId, { resolve });
2654
- setTimeout(() => {
2655
- if (this.pendingApprovals.has(callId)) {
2656
- this.pendingApprovals.delete(callId);
2657
- resolve({ action: "decline" });
2658
- }
2659
- }, 5 * 60 * 1e3);
2660
- });
2661
- }
2662
- );
2663
- }
2664
- // ── Codex MCP tools ────────────────────────────────────────────────
2665
- async startCodexSession(config) {
2666
- const response = await this.client.callTool({
2667
- name: "codex",
2668
- arguments: config
2669
- }, void 0, { timeout: DEFAULT_TIMEOUT });
2670
- this.extractIdentifiers(response);
2671
- return response;
2672
- }
2673
- async continueSession(prompt) {
2674
- if (!this.conversationId) {
2675
- this.conversationId = this.codexSessionId;
2676
- }
2677
- const response = await this.client.callTool({
2678
- name: "codex-reply",
2679
- arguments: {
2680
- sessionId: this.codexSessionId,
2681
- conversationId: this.conversationId,
2682
- prompt
2683
- }
2684
- }, void 0, { timeout: DEFAULT_TIMEOUT });
2685
- this.extractIdentifiers(response);
2686
- return response;
2687
- }
2688
- // ── Event handling ─────────────────────────────────────────────────
2689
- handleCodexEvent(event) {
2690
- if (!event || typeof event !== "object") return;
2691
- const eventType = event.type;
2692
- this.log(`[Codex] Event: ${eventType}`);
2693
- switch (eventType) {
2694
- case "task_started":
2695
- this.emit({ type: "status", status: "running" });
2696
- break;
2697
- case "task_complete":
2698
- case "turn_aborted":
2699
- this.emit({ type: "status", status: "idle" });
2700
- break;
2701
- case "agent_message": {
2702
- const content = event.content;
2703
- if (Array.isArray(content)) {
2704
- for (const block of content) {
2705
- if (block.type === "output_text" && block.text) {
2706
- this.emit({ type: "model-output", fullText: block.text });
2707
- }
2708
- }
2709
- }
2710
- break;
2711
- }
2712
- case "agent_reasoning_delta": {
2713
- const text = event.delta?.text || event.text;
2714
- if (text) {
2715
- this.emit({ type: "event", name: "thinking", payload: { text } });
2716
- }
2717
- break;
2718
- }
2719
- case "agent_reasoning": {
2720
- const text = event.text || (Array.isArray(event.content) ? event.content.map((c) => c.text).join("") : "");
2721
- if (text) {
2722
- this.emit({ type: "event", name: "thinking", payload: { text } });
2723
- }
2724
- break;
2725
- }
2726
- case "exec_command_begin": {
2727
- const callId = event.call_id || event.callId || randomUUID();
2728
- const command = Array.isArray(event.command) ? event.command.join(" ") : String(event.command || "");
2729
- this.emit({
2730
- type: "tool-call",
2731
- toolName: "CodexBash",
2732
- callId,
2733
- args: { command, cwd: event.cwd }
2734
- });
2735
- break;
2736
- }
2737
- case "exec_command_end": {
2738
- const callId = event.call_id || event.callId || "";
2739
- this.emit({
2740
- type: "tool-result",
2741
- toolName: "CodexBash",
2742
- callId,
2743
- result: {
2744
- exitCode: event.exit_code ?? event.exitCode,
2745
- stdout: event.stdout || "",
2746
- stderr: event.stderr || ""
2747
- }
2748
- });
2749
- break;
2750
- }
2751
- case "patch_apply_begin": {
2752
- const callId = event.call_id || event.callId || randomUUID();
2753
- this.emit({
2754
- type: "tool-call",
2755
- toolName: "CodexPatch",
2756
- callId,
2757
- args: { filePath: event.file_path || event.filePath, patch: event.patch }
2758
- });
2759
- break;
2760
- }
2761
- case "patch_apply_end": {
2762
- const callId = event.call_id || event.callId || "";
2763
- this.emit({
2764
- type: "tool-result",
2765
- toolName: "CodexPatch",
2766
- callId,
2767
- result: {
2768
- filePath: event.file_path || event.filePath,
2769
- applied: event.applied,
2770
- error: event.error
2771
- }
2772
- });
2773
- break;
2774
- }
2775
- default:
2776
- this.log(`[Codex] Unhandled event: ${eventType}`);
2777
- break;
2778
- }
2779
- }
2780
- // ── Identifier extraction ──────────────────────────────────────────
2781
- updateIdentifiersFromEvent(event) {
2782
- if (!event || typeof event !== "object") return;
2783
- const candidates = [event];
2784
- if (event.data && typeof event.data === "object") candidates.push(event.data);
2785
- for (const c of candidates) {
2786
- const sid = c.session_id ?? c.sessionId;
2787
- if (sid) this.codexSessionId = sid;
2788
- const cid = c.conversation_id ?? c.conversationId;
2789
- if (cid) this.conversationId = cid;
2790
- }
2791
- }
2792
- extractIdentifiers(response) {
2793
- const meta = response?.meta || {};
2794
- this.codexSessionId = meta.sessionId || response?.sessionId || this.codexSessionId;
2795
- this.conversationId = meta.conversationId || response?.conversationId || this.conversationId;
2796
- const content = response?.content;
2797
- if (Array.isArray(content)) {
2798
- for (const item of content) {
2799
- if (!this.codexSessionId && item?.sessionId) this.codexSessionId = item.sessionId;
2800
- if (!this.conversationId && item?.conversationId) this.conversationId = item.conversationId;
2801
- }
2802
- }
2803
- }
2804
- // ── Helpers ────────────────────────────────────────────────────────
2805
- emit(msg) {
2806
- if (this.disposed) return;
2807
- for (const h of this.listeners) {
2808
- try {
2809
- h(msg);
2810
- } catch {
2811
- }
2812
- }
2813
- }
2814
- }
2815
-
2816
- const GEMINI_TIMEOUTS = {
2817
- init: 12e4,
2818
- toolCall: 12e4,
2819
- investigation: 6e5,
2820
- think: 3e4,
2821
- idle: 500
2822
- };
2823
- const GEMINI_TOOL_PATTERNS = [
2824
- {
2825
- name: "change_title",
2826
- patterns: ["change_title", "change-title", "svamp__change_title", "mcp__svamp__change_title"],
2827
- inputFields: ["title"],
2828
- emptyInputDefault: true
2829
- },
2830
- {
2831
- name: "set_session_link",
2832
- patterns: ["set_session_link", "set-session-link", "svamp__set_session_link", "mcp__svamp__set_session_link"],
2833
- inputFields: ["url"]
2834
- },
2835
- {
2836
- name: "save_memory",
2837
- patterns: ["save_memory", "save-memory"],
2838
- inputFields: ["memory", "content"]
2839
- },
2840
- {
2841
- name: "think",
2842
- patterns: ["think"],
2843
- inputFields: ["thought", "thinking"]
2844
- }
2845
- ];
2846
- const AVAILABLE_MODELS = [
2847
- "gemini-2.5-pro",
2848
- "gemini-2.5-flash",
2849
- "gemini-2.5-flash-lite"
2850
- ];
2851
- class GeminiTransport {
2852
- agentName = "gemini";
2853
- getInitTimeout() {
2854
- return GEMINI_TIMEOUTS.init;
2855
- }
2856
- filterStdoutLine(line) {
2857
- const trimmed = line.trim();
2858
- if (!trimmed) return null;
2859
- if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) return null;
2860
- try {
2861
- const parsed = JSON.parse(trimmed);
2862
- if (typeof parsed !== "object" || parsed === null) return null;
2863
- return line;
2864
- } catch {
2865
- return null;
2866
- }
2867
- }
2868
- handleStderr(text, context) {
2869
- const trimmed = text.trim();
2870
- if (!trimmed) return { message: null, suppress: true };
2871
- if (trimmed.includes("status 429") || trimmed.includes('code":429') || trimmed.includes("rateLimitExceeded") || trimmed.includes("RESOURCE_EXHAUSTED")) {
2872
- return { message: null, suppress: false };
2873
- }
2874
- if (trimmed.includes("status 404") || trimmed.includes('code":404')) {
2875
- const msg = {
2876
- type: "status",
2877
- status: "error",
2878
- detail: `Model not found. Available models: ${AVAILABLE_MODELS.join(", ")}`
2879
- };
2880
- return { message: msg };
2881
- }
2882
- if (context.hasActiveInvestigation) {
2883
- const hasError = trimmed.includes("timeout") || trimmed.includes("Timeout") || trimmed.includes("failed") || trimmed.includes("Failed") || trimmed.includes("error") || trimmed.includes("Error");
2884
- if (hasError) {
2885
- return { message: null, suppress: false };
2886
- }
2887
- }
2888
- return { message: null };
2889
- }
2890
- getToolPatterns() {
2891
- return GEMINI_TOOL_PATTERNS;
2892
- }
2893
- isInvestigationTool(toolCallId, toolKind) {
2894
- const lowerId = toolCallId.toLowerCase();
2895
- return lowerId.includes("codebase_investigator") || lowerId.includes("investigator") || typeof toolKind === "string" && toolKind.includes("investigator");
2896
- }
2897
- getToolCallTimeout(toolCallId, toolKind) {
2898
- if (this.isInvestigationTool(toolCallId, toolKind)) return GEMINI_TIMEOUTS.investigation;
2899
- if (toolKind === "think") return GEMINI_TIMEOUTS.think;
2900
- return GEMINI_TIMEOUTS.toolCall;
2901
- }
2902
- getIdleTimeout() {
2903
- return GEMINI_TIMEOUTS.idle;
2904
- }
2905
- extractToolNameFromId(toolCallId) {
2906
- const lowerId = toolCallId.toLowerCase();
2907
- for (const toolPattern of GEMINI_TOOL_PATTERNS) {
2908
- for (const pattern of toolPattern.patterns) {
2909
- if (lowerId.includes(pattern.toLowerCase())) {
2910
- return toolPattern.name;
2911
- }
2912
- }
2913
- }
2914
- return null;
2915
- }
2916
- isEmptyInput(input) {
2917
- if (!input) return true;
2918
- if (Array.isArray(input)) return input.length === 0;
2919
- if (typeof input === "object") return Object.keys(input).length === 0;
2920
- return false;
2921
- }
2922
- determineToolName(toolName, toolCallId, input, _context) {
2923
- if (toolName !== "other" && toolName !== "Unknown tool") return toolName;
2924
- const idToolName = this.extractToolNameFromId(toolCallId);
2925
- if (idToolName) return idToolName;
2926
- if (input && typeof input === "object" && !Array.isArray(input)) {
2927
- const inputKeys = Object.keys(input);
2928
- for (const toolPattern of GEMINI_TOOL_PATTERNS) {
2929
- if (toolPattern.inputFields) {
2930
- const hasMatchingField = toolPattern.inputFields.some(
2931
- (field) => inputKeys.some((key) => key.toLowerCase() === field.toLowerCase())
2932
- );
2933
- if (hasMatchingField) return toolPattern.name;
2934
- }
2935
- }
2936
- }
2937
- if (this.isEmptyInput(input) && toolName === "other") {
2938
- const defaultTool = GEMINI_TOOL_PATTERNS.find((p) => p.emptyInputDefault);
2939
- if (defaultTool) return defaultTool.name;
2940
- }
2941
- return toolName;
2942
- }
2943
- }
2944
-
2945
- var GeminiTransport$1 = /*#__PURE__*/Object.freeze({
2946
- __proto__: null,
2947
- GEMINI_TIMEOUTS: GEMINI_TIMEOUTS,
2948
- GeminiTransport: GeminiTransport
2949
- });
2950
-
2951
- const execFileAsync = promisify(execFile);
2952
- const SVAMP_TOOLS_DIR = join(homedir(), ".svamp", "tools");
2953
- const SVAMP_TOOLS_BIN = join(SVAMP_TOOLS_DIR, "node_modules", ".bin");
2954
- const SVAMP_TOOLS_RG_BIN = join(SVAMP_TOOLS_DIR, "node_modules", "@vscode", "ripgrep", "bin");
2955
- function getToolsPath() {
2956
- const parts = [SVAMP_TOOLS_BIN, SVAMP_TOOLS_RG_BIN];
2957
- if (process.env.PATH) parts.push(process.env.PATH);
2958
- return parts.join(":");
2959
- }
2960
- async function checkCommand(command, versionArgs, extraEnv) {
2961
- const envWithPath = extraEnv ? { ...process.env, ...extraEnv } : void 0;
2962
- try {
2963
- const { stdout } = await execFileAsync(command, versionArgs, {
2964
- timeout: 5e3,
2965
- env: envWithPath
2966
- });
2967
- const version = stdout.trim().split("\n")[0];
2968
- return { found: true, version, path: command };
2969
- } catch {
2970
- }
2971
- const localPath = join(SVAMP_TOOLS_BIN, command);
2972
- try {
2973
- const { stdout } = await execFileAsync(localPath, versionArgs, {
2974
- timeout: 5e3,
2975
- env: envWithPath
2976
- });
2977
- const version = stdout.trim().split("\n")[0];
2978
- return { found: true, version, path: localPath };
2979
- } catch {
2980
- }
2981
- return { found: false };
2982
- }
2983
- async function installSrt() {
2984
- const platform = process.platform;
2985
- if (platform !== "darwin" && platform !== "linux") {
2986
- return false;
2987
- }
2988
- console.log("[isolation] srt not found. Installing @anthropic-ai/sandbox-runtime...");
2989
- try {
2990
- await mkdir(SVAMP_TOOLS_DIR, { recursive: true });
2991
- await execFileAsync("npm", [
2992
- "install",
2993
- "--prefix",
2994
- SVAMP_TOOLS_DIR,
2995
- "@anthropic-ai/sandbox-runtime@latest",
2996
- "@vscode/ripgrep"
2997
- ], { timeout: 12e4 });
2998
- const srtPath = join(SVAMP_TOOLS_BIN, "srt");
2999
- try {
3000
- await access(srtPath);
3001
- console.log(`[isolation] srt installed successfully at ${srtPath}`);
3002
- return true;
3003
- } catch {
3004
- console.warn("[isolation] npm install completed but srt binary not found");
3005
- return false;
3006
- }
3007
- } catch (e) {
3008
- console.warn(`[isolation] Failed to install srt: ${e.message}`);
3009
- return false;
3010
- }
3011
- }
3012
- async function parseIsolationTestOutput(stdout, probeFile) {
3013
- const output = stdout.trim();
3014
- const wMatch = output.match(/W=(\d+)/);
3015
- const pMatch = output.match(/P=(\d+)/);
3016
- if (!wMatch || !pMatch) {
3017
- return { passed: false, error: `unexpected test output: ${output}` };
3018
- }
3019
- const workspaceWriteOk = wMatch[1] === "0";
3020
- const probeExitCode = parseInt(pMatch[1], 10);
3021
- if (!workspaceWriteOk) {
3022
- return { passed: false, error: "sandbox blocked writes to allowed workspace path" };
3023
- }
3024
- if (probeExitCode === 0) {
3025
- try {
3026
- await access(probeFile);
3027
- return {
3028
- passed: false,
3029
- error: "writes outside workspace were NOT blocked \u2014 file leaked to host filesystem"
3030
- };
3031
- } catch {
3032
- return { passed: true };
3033
- }
3034
- }
3035
- return { passed: true };
3036
- }
3037
- async function verifySrtIsolation(binaryPath) {
3038
- const testBase = "/tmp";
3039
- const workDir = await mkdtemp(join(testBase, "svamp-iso-work-"));
3040
- const probeDir = await mkdtemp(join(testBase, "svamp-iso-probe-"));
3041
- const probeFile = join(probeDir, "leak-test");
3042
- const settingsFile = join(workDir, "srt-settings.json");
3043
- try {
3044
- await writeFile(settingsFile, JSON.stringify({
3045
- filesystem: {
3046
- denyRead: [],
3047
- allowWrite: [workDir],
3048
- denyWrite: []
3049
- },
3050
- network: {
3051
- allowedDomains: [],
3052
- deniedDomains: []
3053
- }
3054
- }));
3055
- const testScript = [
3056
- `echo ok > "${workDir}/test" 2>/dev/null; W=$?`,
3057
- `echo leak > "${probeFile}" 2>/dev/null; P=$?`,
3058
- `echo "W=$W P=$P"`
3059
- ].join("; ");
3060
- const { stdout } = await execFileAsync(binaryPath, [
3061
- "--settings",
3062
- settingsFile,
3063
- "sh",
3064
- "-c",
3065
- testScript
3066
- ], {
3067
- timeout: 15e3,
3068
- env: { ...process.env, PATH: getToolsPath() }
3069
- });
3070
- return parseIsolationTestOutput(stdout, probeFile);
3071
- } catch (e) {
3072
- return { passed: false, error: e.message };
3073
- } finally {
3074
- await rm(workDir, { recursive: true, force: true }).catch(() => {
3075
- });
3076
- await rm(probeDir, { recursive: true, force: true }).catch(() => {
3077
- });
3078
- }
3079
- }
3080
- async function verifyBwrapIsolation(binaryPath) {
3081
- const testBase = "/tmp";
3082
- const workDir = await mkdtemp(join(testBase, "svamp-iso-work-"));
3083
- const probeDir = await mkdtemp(join(testBase, "svamp-iso-probe-"));
3084
- const probeFile = join(probeDir, "leak-test");
3085
- try {
3086
- const testScript = [
3087
- `echo ok > "${workDir}/test" 2>/dev/null; W=$?`,
3088
- `echo leak > "${probeFile}" 2>/dev/null; P=$?`,
3089
- `echo "W=$W P=$P"`
3090
- ].join("; ");
3091
- const { stdout } = await execFileAsync(binaryPath, [
3092
- "--ro-bind",
3093
- "/",
3094
- "/",
3095
- "--bind",
3096
- workDir,
3097
- workDir,
3098
- "--dev",
3099
- "/dev",
3100
- "--proc",
3101
- "/proc",
3102
- "--unshare-pid",
3103
- "--die-with-parent",
3104
- "--",
3105
- "sh",
3106
- "-c",
3107
- testScript
3108
- ], { timeout: 15e3 });
3109
- return parseIsolationTestOutput(stdout, probeFile);
3110
- } catch (e) {
3111
- return { passed: false, error: e.message };
3112
- } finally {
3113
- await rm(workDir, { recursive: true, force: true }).catch(() => {
3114
- });
3115
- await rm(probeDir, { recursive: true, force: true }).catch(() => {
3116
- });
3117
- }
3118
- }
3119
- async function verifyContainerIsolation(method, binaryPath) {
3120
- try {
3121
- await execFileAsync(binaryPath, ["info"], { timeout: 15e3 });
3122
- } catch (e) {
3123
- return { passed: false, error: `${method} daemon not accessible: ${e.message}` };
3124
- }
3125
- try {
3126
- const { stdout } = await execFileAsync(
3127
- binaryPath,
3128
- ["run", "--rm", "--network=none", "alpine", "echo", "isolation-ok"],
3129
- { timeout: 3e4 }
3130
- );
3131
- if (!stdout.includes("isolation-ok")) {
3132
- return { passed: false, error: `container test returned unexpected output: ${stdout.trim()}` };
3133
- }
3134
- return { passed: true };
3135
- } catch (e) {
3136
- if (e.message?.includes("pull access denied") || e.message?.includes("not found")) {
3137
- return { passed: true };
3138
- }
3139
- return { passed: false, error: `container test failed: ${e.message}` };
3140
- }
3141
- }
3142
- async function verifyIsolation(method, binaryPath) {
3143
- switch (method) {
3144
- case "srt":
3145
- return verifySrtIsolation(binaryPath);
3146
- case "bwrap":
3147
- return verifyBwrapIsolation(binaryPath);
3148
- case "docker":
3149
- case "podman":
3150
- return verifyContainerIsolation(method, binaryPath);
3151
- }
3152
- }
3153
- async function detectIsolationCapabilities() {
3154
- const srtEnv = { PATH: getToolsPath() };
3155
- const checks = {
3156
- srt: checkCommand("srt", ["--version"], srtEnv),
3157
- bwrap: checkCommand("bwrap", ["--version"]),
3158
- docker: checkCommand("docker", ["--version"]),
3159
- podman: checkCommand("podman", ["--version"])
3160
- };
3161
- const checkResults = await Promise.all(
3162
- Object.entries(checks).map(async ([method, promise]) => {
3163
- const detail = await promise;
3164
- return [method, detail];
3165
- })
3166
- );
3167
- const details = Object.fromEntries(checkResults);
3168
- if (!details.srt.found) {
3169
- const installed = await installSrt();
3170
- if (installed) {
3171
- details.srt = await checkCommand("srt", ["--version"], srtEnv);
3172
- }
3173
- }
3174
- const foundMethods = ISOLATION_PREFERENCE.filter((m) => details[m].found);
3175
- if (foundMethods.length > 0) {
3176
- console.log(`[isolation] Found runtimes: ${foundMethods.join(", ")}. Verifying isolation...`);
3177
- await Promise.all(
3178
- foundMethods.map(async (method) => {
3179
- const binaryPath = details[method].path || method;
3180
- const result = await verifyIsolation(method, binaryPath);
3181
- details[method].verified = result.passed;
3182
- if (!result.passed) {
3183
- details[method].verificationError = result.error;
3184
- console.warn(
3185
- `[isolation] WARNING: ${method} found but verification FAILED: ${result.error}. This runtime will NOT be used for isolation.`
3186
- );
3187
- } else {
3188
- console.log(`[isolation] ${method}: verified OK`);
3189
- }
3190
- })
3191
- );
3192
- }
3193
- const available = ISOLATION_PREFERENCE.filter(
3194
- (m) => details[m].found && details[m].verified === true
3195
- );
3196
- const preferred = available.length > 0 ? available[0] : null;
3197
- if (available.length === 0 && foundMethods.length > 0) {
3198
- console.warn(
3199
- `[isolation] No isolation runtime passed verification (found: ${foundMethods.join(", ")}). Session sharing will be DISABLED.`
3200
- );
3201
- } else if (available.length === 0) {
3202
- console.log("[isolation] No isolation runtimes found. Session sharing will be unavailable.");
3203
- } else {
3204
- console.log(`[isolation] Preferred isolation method: ${preferred}`);
3205
- }
3206
- return { available, preferred, details };
3207
- }
3208
-
3209
- const __filename$1 = fileURLToPath(import.meta.url);
3210
- const __dirname$1 = dirname(__filename$1);
3211
- function loadDotEnv() {
3212
- const envDir = process.env.SVAMP_HOME || join$1(os.homedir(), ".svamp");
3213
- const envFile = join$1(envDir, ".env");
3214
- if (existsSync$1(envFile)) {
3215
- const lines = readFileSync$1(envFile, "utf-8").split("\n");
3216
- for (const line of lines) {
3217
- const trimmed = line.trim();
3218
- if (!trimmed || trimmed.startsWith("#")) continue;
3219
- const eqIdx = trimmed.indexOf("=");
3220
- if (eqIdx === -1) continue;
3221
- const key = trimmed.slice(0, eqIdx).trim();
3222
- const value = trimmed.slice(eqIdx + 1).trim().replace(/^["']|["']$/g, "");
3223
- if (!process.env[key]) {
3224
- process.env[key] = value;
3225
- }
3226
- }
3227
- }
3228
- }
3229
- loadDotEnv();
3230
- const SVAMP_HOME = process.env.SVAMP_HOME || join$1(os.homedir(), ".svamp");
3231
- const DAEMON_STATE_FILE = join$1(SVAMP_HOME, "daemon.state.json");
3232
- const DAEMON_LOCK_FILE = join$1(SVAMP_HOME, "daemon.lock");
3233
- const LOGS_DIR = join$1(SVAMP_HOME, "logs");
3234
- const SESSION_INDEX_FILE = join$1(SVAMP_HOME, "sessions-index.json");
3235
- function readPackageVersion() {
3236
- try {
3237
- const pkgPath = join$1(__dirname$1, "../package.json");
3238
- if (existsSync$1(pkgPath)) {
3239
- return JSON.parse(readFileSync$1(pkgPath, "utf-8")).version || "unknown";
3240
- }
3241
- } catch {
3242
- }
3243
- return "unknown";
3244
- }
3245
- const DAEMON_VERSION = readPackageVersion();
3246
- function loadAgentConfig() {
3247
- const configPath = join$1(SVAMP_HOME, "agent-config.json");
3248
- if (existsSync$1(configPath)) {
3249
- try {
3250
- return JSON.parse(readFileSync$1(configPath, "utf-8"));
3251
- } catch {
3252
- return {};
3253
- }
3254
- }
3255
- return {};
3256
- }
3257
- function getSessionSvampDir(directory) {
3258
- return join$1(directory, ".svamp");
3259
- }
3260
- function getSessionDir(directory, sessionId) {
3261
- return join$1(getSessionSvampDir(directory), sessionId);
3262
- }
3263
- function getSessionFilePath(directory, sessionId) {
3264
- return join$1(getSessionDir(directory, sessionId), "session.json");
3265
- }
3266
- function getSessionMessagesPath(directory, sessionId) {
3267
- return join$1(getSessionDir(directory, sessionId), "messages.jsonl");
3268
- }
3269
- function getSvampConfigPath(directory, sessionId) {
3270
- return join$1(getSessionDir(directory, sessionId), "config.json");
3271
- }
3272
- function createSvampConfigChecker(directory, sessionId, getMetadata, setMetadata, sessionService, logger) {
3273
- const configPath = getSvampConfigPath(directory, sessionId);
3274
- let lastContent = "";
3275
- if (existsSync$1(configPath)) {
3276
- try {
3277
- lastContent = readFileSync$1(configPath, "utf-8");
3278
- } catch {
3279
- }
3280
- }
3281
- function processConfig(config, meta) {
3282
- if (typeof config.title === "string" && config.title.trim()) {
3283
- const newTitle = config.title.trim();
3284
- if (meta.summary?.text !== newTitle) {
3285
- setMetadata((m) => ({
3286
- ...m,
3287
- summary: { text: newTitle, updatedAt: Date.now() }
3288
- }));
3289
- sessionService.pushMessage({ type: "summary", summary: newTitle }, "session");
3290
- logger.log(`[svampConfig] Title updated: "${newTitle}"`);
3291
- }
3292
- }
3293
- if (config.session_link && typeof config.session_link.url === "string" && config.session_link.url.trim()) {
3294
- const url = config.session_link.url.trim();
3295
- const label = config.session_link.label || "View";
3296
- if (meta.sessionLink?.url !== url || meta.sessionLink?.label !== label) {
3297
- setMetadata((m) => ({
3298
- ...m,
3299
- sessionLink: { url, label, updatedAt: Date.now() }
3300
- }));
3301
- const currentSummary = getMetadata().summary?.text;
3302
- if (currentSummary) {
3303
- sessionService.pushMessage({ type: "summary", summary: currentSummary }, "session");
3304
- }
3305
- logger.log(`[svampConfig] Session link updated: "${label}" \u2192 ${url}`);
3306
- }
3307
- }
3308
- }
3309
- return () => {
3310
- try {
3311
- const meta = getMetadata();
3312
- if (existsSync$1(configPath)) {
3313
- const content = readFileSync$1(configPath, "utf-8");
3314
- if (content !== lastContent) {
3315
- lastContent = content;
3316
- processConfig(JSON.parse(content), meta);
3317
- }
3318
- }
3319
- } catch (err) {
3320
- }
3321
- };
3322
- }
3323
- function loadSessionIndex() {
3324
- if (!existsSync$1(SESSION_INDEX_FILE)) return {};
3325
- try {
3326
- return JSON.parse(readFileSync$1(SESSION_INDEX_FILE, "utf-8"));
3327
- } catch {
3328
- return {};
3329
- }
3330
- }
3331
- function saveSessionIndex(index) {
3332
- writeFileSync$1(SESSION_INDEX_FILE, JSON.stringify(index, null, 2), "utf-8");
3333
- }
3334
- function saveSession(session) {
3335
- const sessionDir = getSessionDir(session.directory, session.sessionId);
3336
- if (!existsSync$1(sessionDir)) {
3337
- mkdirSync$1(sessionDir, { recursive: true });
3338
- }
3339
- writeFileSync$1(
3340
- getSessionFilePath(session.directory, session.sessionId),
3341
- JSON.stringify(session, null, 2),
3342
- "utf-8"
3343
- );
3344
- const index = loadSessionIndex();
3345
- index[session.sessionId] = { directory: session.directory, createdAt: session.createdAt };
3346
- saveSessionIndex(index);
3347
- }
3348
- function deletePersistedSession(sessionId) {
3349
- const index = loadSessionIndex();
3350
- const entry = index[sessionId];
3351
- if (entry) {
3352
- const sessionFile = getSessionFilePath(entry.directory, sessionId);
3353
- try {
3354
- if (existsSync$1(sessionFile)) unlinkSync(sessionFile);
3355
- } catch {
3356
- }
3357
- const messagesFile = getSessionMessagesPath(entry.directory, sessionId);
3358
- try {
3359
- if (existsSync$1(messagesFile)) unlinkSync(messagesFile);
3360
- } catch {
3361
- }
3362
- const configFile = getSvampConfigPath(entry.directory, sessionId);
3363
- try {
3364
- if (existsSync$1(configFile)) unlinkSync(configFile);
3365
- } catch {
3366
- }
3367
- const sessionDir = getSessionDir(entry.directory, sessionId);
3368
- try {
3369
- rmdirSync(sessionDir);
3370
- } catch {
3371
- }
3372
- delete index[sessionId];
3373
- saveSessionIndex(index);
3374
- }
3375
- }
3376
- function loadPersistedSessions() {
3377
- const sessions = [];
3378
- const index = loadSessionIndex();
3379
- let indexChanged = false;
3380
- for (const [sessionId, entry] of Object.entries(index)) {
3381
- const filePath = getSessionFilePath(entry.directory, sessionId);
3382
- try {
3383
- const data = JSON.parse(readFileSync$1(filePath, "utf-8"));
3384
- if (data.sessionId && data.directory) {
3385
- if (!data.stopped) {
3386
- sessions.push(data);
3387
- }
3388
- }
3389
- } catch {
3390
- delete index[sessionId];
3391
- indexChanged = true;
3392
- }
3393
- }
3394
- if (indexChanged) {
3395
- saveSessionIndex(index);
3396
- }
3397
- return sessions;
3398
- }
3399
- function ensureHomeDir() {
3400
- if (!existsSync$1(SVAMP_HOME)) {
3401
- mkdirSync$1(SVAMP_HOME, { recursive: true });
3402
- }
3403
- if (!existsSync$1(LOGS_DIR)) {
3404
- mkdirSync$1(LOGS_DIR, { recursive: true });
3405
- }
3406
- }
3407
- function createLogger() {
3408
- ensureHomeDir();
3409
- const logFile = join$1(LOGS_DIR, `daemon-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.log`);
3410
- return {
3411
- logFilePath: logFile,
3412
- log: (...args) => {
3413
- const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${args.map((a) => typeof a === "string" ? a : JSON.stringify(a)).join(" ")}
3414
- `;
3415
- fs.appendFile(logFile, line).catch(() => {
3416
- });
3417
- if (process.env.DEBUG) {
3418
- console.log(...args);
3419
- }
3420
- },
3421
- error: (...args) => {
3422
- const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] ERROR: ${args.map((a) => typeof a === "string" ? a : JSON.stringify(a)).join(" ")}
3423
- `;
3424
- fs.appendFile(logFile, line).catch(() => {
3425
- });
3426
- console.error(...args);
3427
- }
3428
- };
3429
- }
3430
- function writeDaemonStateFile(state) {
3431
- ensureHomeDir();
3432
- writeFileSync$1(DAEMON_STATE_FILE, JSON.stringify(state, null, 2), "utf-8");
3433
- }
3434
- function readDaemonStateFile() {
3435
- try {
3436
- if (!existsSync$1(DAEMON_STATE_FILE)) return null;
3437
- return JSON.parse(readFileSync$1(DAEMON_STATE_FILE, "utf-8"));
3438
- } catch {
3439
- return null;
3440
- }
3441
- }
3442
- function cleanupDaemonStateFile() {
3443
- try {
3444
- if (existsSync$1(DAEMON_STATE_FILE)) {
3445
- fs.unlink(DAEMON_STATE_FILE).catch(() => {
3446
- });
3447
- }
3448
- if (existsSync$1(DAEMON_LOCK_FILE)) {
3449
- fs.unlink(DAEMON_LOCK_FILE).catch(() => {
3450
- });
3451
- }
3452
- } catch {
3453
- }
3454
- }
3455
- function isDaemonAlive() {
3456
- const state = readDaemonStateFile();
3457
- if (!state) return false;
3458
- try {
3459
- process.kill(state.pid, 0);
3460
- return true;
3461
- } catch {
3462
- return false;
3463
- }
3464
- }
3465
- async function startDaemon() {
3466
- const logger = createLogger();
3467
- const agentConfig = loadAgentConfig();
3468
- if (Object.keys(agentConfig).length > 0) {
3469
- logger.log("Loaded agent config:", JSON.stringify(agentConfig));
3470
- }
3471
- let shutdownRequested = false;
3472
- let requestShutdown;
3473
- const resolvesWhenShutdownRequested = new Promise((resolve2) => {
3474
- requestShutdown = (source, errorMessage) => {
3475
- if (shutdownRequested) return;
3476
- shutdownRequested = true;
3477
- logger.log(`Requesting shutdown (source: ${source}, errorMessage: ${errorMessage})`);
3478
- setTimeout(() => {
3479
- logger.log("Forced exit after timeout");
3480
- process.exit(1);
3481
- }, 5e3);
3482
- resolve2({ source, errorMessage });
3483
- };
3484
- });
3485
- let isReconnecting = false;
3486
- process.on("SIGINT", () => requestShutdown("os-signal"));
3487
- process.on("SIGTERM", () => requestShutdown("os-signal"));
3488
- process.on("SIGUSR1", () => requestShutdown("os-signal-cleanup"));
3489
- process.on("uncaughtException", (error) => {
3490
- if (shutdownRequested) return;
3491
- logger.error("Uncaught exception:", error);
3492
- requestShutdown("exception", error.message);
3493
- });
3494
- const TRANSIENT_REJECTION_PATTERNS = [
3495
- "_rintf",
3496
- // _rintf callback timeouts (app disconnected)
3497
- "Method call timed out",
3498
- // RPC timeout during reconnection
3499
- "WebSocket",
3500
- // WebSocket errors during reconnect
3501
- "ECONNRESET",
3502
- // TCP connection reset
3503
- "ECONNREFUSED",
3504
- // Server temporarily unreachable
3505
- "EPIPE",
3506
- // Broken pipe (write to closed socket)
3507
- "ETIMEDOUT",
3508
- // Connection timed out
3509
- "socket hang up",
3510
- // HTTP socket closed unexpectedly
3511
- "network",
3512
- // Generic network errors
3513
- "Connection closed",
3514
- // WebSocket closed during RPC call
3515
- "connection was closed",
3516
- // hypha-rpc connection closed message
3517
- "Client disconnected",
3518
- // Hypha client disconnect events
3519
- "fetch failed"
3520
- // Fetch API errors during reconnect
3521
- ];
3522
- let unhandledRejectionCount = 0;
3523
- let unhandledRejectionResetTimer = null;
3524
- const UNHANDLED_REJECTION_THRESHOLD = 10;
3525
- const UNHANDLED_REJECTION_WINDOW_MS = 6e4;
3526
- process.on("unhandledRejection", (reason) => {
3527
- if (shutdownRequested) return;
3528
- const msg = String(reason);
3529
- logger.error("Unhandled rejection:", reason);
3530
- const isTransient = TRANSIENT_REJECTION_PATTERNS.some((p) => msg.toLowerCase().includes(p.toLowerCase()));
3531
- if (isTransient || isReconnecting) {
3532
- logger.log(`Ignoring transient rejection (reconnecting=${isReconnecting}): ${msg.slice(0, 200)}`);
3533
- return;
3534
- }
3535
- unhandledRejectionCount++;
3536
- if (!unhandledRejectionResetTimer) {
3537
- unhandledRejectionResetTimer = setTimeout(() => {
3538
- unhandledRejectionCount = 0;
3539
- unhandledRejectionResetTimer = null;
3540
- }, UNHANDLED_REJECTION_WINDOW_MS);
3541
- }
3542
- if (unhandledRejectionCount >= UNHANDLED_REJECTION_THRESHOLD) {
3543
- logger.log(`Too many unhandled rejections (${unhandledRejectionCount} in ${UNHANDLED_REJECTION_WINDOW_MS / 1e3}s), shutting down`);
3544
- requestShutdown("exception", msg);
3545
- } else {
3546
- logger.log(`Unhandled rejection ${unhandledRejectionCount}/${UNHANDLED_REJECTION_THRESHOLD} (not crashing yet): ${msg.slice(0, 200)}`);
3547
- }
3548
- });
3549
- if (isDaemonAlive()) {
3550
- console.log("Svamp daemon is already running");
3551
- process.exit(0);
3552
- }
3553
- const hyphaServerUrl = process.env.HYPHA_SERVER_URL;
3554
- if (!hyphaServerUrl) {
3555
- console.error("HYPHA_SERVER_URL is required.");
3556
- console.error('Run "svamp login <server-url>" first, or set it in .env or environment.');
3557
- process.exit(1);
3558
- }
3559
- const hyphaToken = process.env.HYPHA_TOKEN;
3560
- const hyphaWorkspace = process.env.HYPHA_WORKSPACE;
3561
- const hyphaClientId = process.env.HYPHA_CLIENT_ID;
3562
- if (!hyphaToken) {
3563
- logger.log('Warning: No HYPHA_TOKEN set. Run "svamp login" to authenticate.');
3564
- logger.log("Connecting anonymously...");
3565
- }
3566
- const machineIdFile = join$1(SVAMP_HOME, "machine-id");
3567
- let machineId = process.env.SVAMP_MACHINE_ID;
3568
- if (!machineId) {
3569
- if (existsSync$1(machineIdFile)) {
3570
- machineId = readFileSync$1(machineIdFile, "utf-8").trim();
3571
- }
3572
- if (!machineId) {
3573
- machineId = `machine-${os.hostname()}-${randomUUID$1().slice(0, 8)}`;
3574
- try {
3575
- writeFileSync$1(machineIdFile, machineId, "utf-8");
3576
- } catch {
3577
- }
3578
- }
3579
- }
3580
- logger.log("Starting svamp daemon...");
3581
- logger.log(` Server: ${hyphaServerUrl}`);
3582
- logger.log(` Workspace: ${hyphaWorkspace || "(default)"}`);
3583
- logger.log(` Machine ID: ${machineId}`);
3584
- let server = null;
3585
- try {
3586
- logger.log("Connecting to Hypha server...");
3587
- server = await connectToHypha({
3588
- serverUrl: hyphaServerUrl,
3589
- token: hyphaToken,
3590
- name: `svamp-machine-${machineId}`,
3591
- ...hyphaClientId ? { clientId: hyphaClientId } : {}
3592
- });
3593
- logger.log(`Connected to Hypha (workspace: ${server.config.workspace})`);
3594
- server.on("disconnected", (reason) => {
3595
- logger.log(`Hypha connection permanently lost: ${reason}`);
3596
- isReconnecting = false;
3597
- requestShutdown("hypha-disconnected", String(reason));
3598
- });
3599
- server.on("services_registered", () => {
3600
- if (isReconnecting) {
3601
- logger.log("Hypha reconnection successful \u2014 services re-registered");
3602
- isReconnecting = false;
3603
- }
3604
- });
3605
- const pidToTrackedSession = /* @__PURE__ */ new Map();
3606
- const getCurrentChildren = () => {
3607
- return Array.from(pidToTrackedSession.values()).map((s) => ({
3608
- sessionId: s.svampSessionId || `PID-${s.pid}`,
3609
- pid: s.pid,
3610
- startedBy: s.startedBy,
3611
- directory: s.directory,
3612
- active: !s.stopped && s.hyphaService != null
3613
- }));
3614
- };
3615
- const spawnSession = async (options) => {
3616
- logger.log("Spawning session:", JSON.stringify(options));
3617
- const { directory, approvedNewDirectoryCreation = true, resumeSessionId } = options;
3618
- if (resumeSessionId) {
3619
- for (const tracked of pidToTrackedSession.values()) {
3620
- if (!tracked.stopped && tracked.svampSessionId && tracked.resumeSessionId === resumeSessionId) {
3621
- logger.log(`Dedup: found existing active session ${tracked.svampSessionId} for resume ID ${resumeSessionId}`);
3622
- return { type: "success", sessionId: tracked.svampSessionId };
3623
- }
3624
- }
3625
- }
3626
- try {
3627
- await fs.access(directory);
3628
- } catch {
3629
- if (!approvedNewDirectoryCreation) {
3630
- return { type: "requestToApproveDirectoryCreation", directory };
3631
- }
3632
- try {
3633
- await fs.mkdir(directory, { recursive: true });
3634
- } catch (err) {
3635
- return { type: "error", errorMessage: `Failed to create directory: ${err.message}` };
3636
- }
3637
- }
3638
- const sessionId = options.sessionId || randomUUID$1();
3639
- const agentName = options.agent || agentConfig.agent_type || "claude";
3640
- if (agentName !== "claude" && (KNOWN_ACP_AGENTS[agentName] || KNOWN_MCP_AGENTS[agentName])) {
3641
- return await spawnAgentSession(sessionId, directory, agentName, options, resumeSessionId);
3642
- }
3643
- try {
3644
- let parseBashPermission2 = function(permission) {
3645
- if (permission === "Bash") return;
3646
- const match = permission.match(/^Bash\((.+?)\)$/);
3647
- if (!match) return;
3648
- const command = match[1];
3649
- if (command.endsWith(":*")) {
3650
- allowedBashPrefixes.add(command.slice(0, -2));
3651
- } else {
3652
- allowedBashLiterals.add(command);
3653
- }
3654
- }, shouldAutoAllow2 = function(toolName, toolInput) {
3655
- if (toolName === "Bash") {
3656
- const inputObj = toolInput;
3657
- if (inputObj?.command) {
3658
- if (allowedBashLiterals.has(inputObj.command)) return true;
3659
- for (const prefix of allowedBashPrefixes) {
3660
- if (inputObj.command.startsWith(prefix)) return true;
3661
- }
3662
- }
3663
- } else if (allowedTools.has(toolName)) {
3664
- return true;
3665
- }
3666
- if (currentPermissionMode === "bypassPermissions" || currentPermissionMode === "yolo") return true;
3667
- if ((currentPermissionMode === "acceptEdits" || currentPermissionMode === "safe-yolo") && EDIT_TOOLS.has(toolName)) return true;
3668
- return false;
3669
- }, killAndWaitForExit2 = function(proc, signal = "SIGTERM", timeoutMs = 1e4) {
3670
- return new Promise((resolve2) => {
3671
- if (!proc || proc.exitCode !== null) {
3672
- resolve2();
3673
- return;
3674
- }
3675
- const timeout = setTimeout(() => {
3676
- try {
3677
- proc.kill("SIGKILL");
3678
- } catch {
3679
- }
3680
- resolve2();
3681
- }, timeoutMs);
3682
- proc.on("exit", () => {
3683
- clearTimeout(timeout);
3684
- resolve2();
3685
- });
3686
- if (!proc.killed) {
3687
- proc.kill(signal);
3688
- }
3689
- });
3690
- }, buildIsolationConfig2 = function(dir) {
3691
- if (!sessionMetadata.sharing?.enabled) return null;
3692
- const method = isolationCapabilities.preferred;
3693
- if (!method) return null;
3694
- const detail = isolationCapabilities.details[method];
3695
- if (!detail.found || detail.verified === false) return null;
3696
- return {
3697
- method,
3698
- binaryPath: detail.path || method,
3699
- workspacePath: dir
3700
- };
3701
- };
3702
- var parseBashPermission = parseBashPermission2, shouldAutoAllow = shouldAutoAllow2, killAndWaitForExit = killAndWaitForExit2, buildIsolationConfig = buildIsolationConfig2;
3703
- let sessionMetadata = {
3704
- path: directory,
3705
- host: os.hostname(),
3706
- version: "0.1.0",
3707
- machineId,
3708
- homeDir: os.homedir(),
3709
- svampHomeDir: SVAMP_HOME,
3710
- svampLibDir: join$1(__dirname$1, ".."),
3711
- svampToolsDir: join$1(__dirname$1, "..", "tools"),
3712
- startedFromDaemon: true,
3713
- startedBy: "daemon",
3714
- lifecycleState: resumeSessionId ? "idle" : "starting",
3715
- sharing: options.sharing
3716
- };
3717
- let claudeProcess = null;
3718
- const allPersisted = loadPersistedSessions();
3719
- const persisted = allPersisted.find((p) => p.sessionId === sessionId) || (resumeSessionId ? allPersisted.find((p) => p.claudeResumeId === resumeSessionId) : void 0);
3720
- let claudeResumeId = persisted?.claudeResumeId || (resumeSessionId || void 0);
3721
- let currentPermissionMode = persisted?.permissionMode || "default";
3722
- if (claudeResumeId) {
3723
- sessionMetadata = { ...sessionMetadata, claudeSessionId: claudeResumeId };
3724
- }
3725
- if (persisted && persisted.sessionId !== sessionId) {
3726
- const oldDir = persisted.directory || directory;
3727
- const newSessionDir = getSessionDir(directory, sessionId);
3728
- if (!existsSync$1(newSessionDir)) mkdirSync$1(newSessionDir, { recursive: true });
3729
- const oldMsgFile = getSessionMessagesPath(oldDir, persisted.sessionId);
3730
- const newMsgFile = getSessionMessagesPath(directory, sessionId);
3731
- try {
3732
- if (existsSync$1(oldMsgFile) && !existsSync$1(newMsgFile)) {
3733
- copyFileSync(oldMsgFile, newMsgFile);
3734
- logger.log(`[Session ${sessionId}] Copied messages from old session ${persisted.sessionId}`);
3735
- }
3736
- } catch (err) {
3737
- logger.log(`[Session ${sessionId}] Failed to copy messages: ${err.message}`);
3738
- }
3739
- }
3740
- const allowedTools = /* @__PURE__ */ new Set();
3741
- const allowedBashLiterals = /* @__PURE__ */ new Set();
3742
- const allowedBashPrefixes = /* @__PURE__ */ new Set();
3743
- const EDIT_TOOLS = /* @__PURE__ */ new Set(["Edit", "MultiEdit", "Write", "NotebookEdit"]);
3744
- const pendingPermissions = /* @__PURE__ */ new Map();
3745
- let backgroundTaskCount = 0;
3746
- let backgroundTaskNames = [];
3747
- let userMessagePending = false;
3748
- let turnInitiatedByUser = true;
3749
- let isKillingClaude = false;
3750
- let checkSvampConfig;
3751
- const CLAUDE_PERMISSION_MODE_MAP = {
3752
- "auto-approve-all": "bypassPermissions"
3753
- };
3754
- const toClaudePermissionMode = (mode) => CLAUDE_PERMISSION_MODE_MAP[mode] || mode;
3755
- let isolationCleanupFiles = [];
3756
- const spawnClaude = (initialMessage, meta) => {
3757
- const rawPermissionMode = meta?.permissionMode || agentConfig.default_permission_mode || currentPermissionMode;
3758
- const permissionMode = toClaudePermissionMode(rawPermissionMode);
3759
- currentPermissionMode = permissionMode;
3760
- const model = meta?.model || agentConfig.default_model || void 0;
3761
- const appendSystemPrompt = meta?.appendSystemPrompt || agentConfig.append_system_prompt || void 0;
3762
- const args = [
3763
- "--output-format",
3764
- "stream-json",
3765
- "--input-format",
3766
- "stream-json",
3767
- "--verbose",
3768
- "--permission-prompt-tool",
3769
- "stdio",
3770
- "--permission-mode",
3771
- permissionMode
3772
- ];
3773
- if (model) args.push("--model", model);
3774
- if (appendSystemPrompt) args.push("--append-system-prompt", appendSystemPrompt);
3775
- if (claudeResumeId) args.push("--resume", claudeResumeId);
3776
- let spawnCommand = "claude";
3777
- let spawnArgs = args;
3778
- let extraEnv = {};
3779
- isolationCleanupFiles = [];
3780
- const isoConfig = buildIsolationConfig2(directory);
3781
- if (isoConfig) {
3782
- const wrapped = wrapWithIsolation(spawnCommand, spawnArgs, isoConfig);
3783
- spawnCommand = wrapped.command;
3784
- spawnArgs = wrapped.args;
3785
- if (wrapped.env) extraEnv = wrapped.env;
3786
- if (wrapped.cleanupFiles) isolationCleanupFiles = wrapped.cleanupFiles;
3787
- sessionMetadata = { ...sessionMetadata, isolationMethod: isoConfig.method };
3788
- logger.log(`[Session ${sessionId}] Isolation: ${isoConfig.method} (binary: ${isoConfig.binaryPath})`);
3789
- } else {
3790
- sessionMetadata = { ...sessionMetadata, isolationMethod: void 0 };
3791
- }
3792
- logger.log(`[Session ${sessionId}] Spawning Claude: ${spawnCommand} ${spawnArgs.join(" ")} (cwd: ${directory})`);
3793
- const spawnEnv = { ...process.env, ...extraEnv };
3794
- delete spawnEnv.CLAUDECODE;
3795
- const child = spawn$1(spawnCommand, spawnArgs, {
3796
- cwd: directory,
3797
- stdio: ["pipe", "pipe", "pipe"],
3798
- env: spawnEnv,
3799
- shell: process.platform === "win32"
3800
- });
3801
- claudeProcess = child;
3802
- logger.log(`[Session ${sessionId}] Claude PID: ${child.pid}, stdin: ${!!child.stdin}, stdout: ${!!child.stdout}, stderr: ${!!child.stderr}`);
3803
- child.on("error", (err) => {
3804
- logger.log(`[Session ${sessionId}] Claude process error: ${err.message}`);
3805
- sessionService.pushMessage(
3806
- { type: "message", message: `Agent process exited unexpectedly: ${err.message}. Please ensure Claude Code CLI is installed.` },
3807
- "event"
3808
- );
3809
- sessionService.sendSessionEnd();
3810
- });
3811
- let stdoutBuffer = "";
3812
- let lastErrorMessagePushed = false;
3813
- child.stdout?.on("data", (chunk) => {
3814
- stdoutBuffer += chunk.toString();
3815
- const lines = stdoutBuffer.split("\n");
3816
- stdoutBuffer = lines.pop() || "";
3817
- for (const line of lines) {
3818
- if (!line.trim()) continue;
3819
- logger.log(`[Session ${sessionId}] stdout line (${line.length} chars): ${line.slice(0, 500)}`);
3820
- try {
3821
- const msg = JSON.parse(line);
3822
- logger.log(`[Session ${sessionId}] Parsed type=${msg.type} subtype=${msg.subtype || "n/a"}`);
3823
- if (msg.type === "control_request" && msg.request?.subtype === "can_use_tool") {
3824
- const requestId = msg.request_id;
3825
- const toolName = msg.request.tool_name;
3826
- const toolInput = msg.request.input;
3827
- logger.log(`[Session ${sessionId}] Permission request: ${requestId} tool=${toolName}`);
3828
- if (shouldAutoAllow2(toolName, toolInput)) {
3829
- logger.log(`[Session ${sessionId}] Auto-allowing ${toolName} (mode=${currentPermissionMode})`);
3830
- if (claudeProcess && !claudeProcess.killed && claudeProcess.stdin) {
3831
- const controlResponse = JSON.stringify({
3832
- type: "control_response",
3833
- response: {
3834
- subtype: "success",
3835
- request_id: requestId,
3836
- response: { behavior: "allow", updatedInput: toolInput || {} }
3837
- }
3838
- });
3839
- claudeProcess.stdin.write(controlResponse + "\n");
3840
- }
3841
- continue;
3842
- }
3843
- const permissionPromise = new Promise((resolve2) => {
3844
- pendingPermissions.set(requestId, { resolve: resolve2, toolName, input: toolInput });
3845
- });
3846
- const currentRequests = { ...sessionService._agentState?.requests };
3847
- sessionService.updateAgentState({
3848
- controlledByUser: false,
3849
- requests: {
3850
- ...currentRequests,
3851
- [requestId]: {
3852
- tool: toolName,
3853
- arguments: toolInput,
3854
- createdAt: Date.now()
3855
- }
3856
- }
3857
- });
3858
- permissionPromise.then((result) => {
3859
- if (claudeProcess && !claudeProcess.killed && claudeProcess.stdin) {
3860
- const controlResponse = JSON.stringify({
3861
- type: "control_response",
3862
- response: {
3863
- subtype: "success",
3864
- request_id: requestId,
3865
- response: result
3866
- }
3867
- });
3868
- logger.log(`[Session ${sessionId}] Sending control_response: ${controlResponse.slice(0, 200)}`);
3869
- claudeProcess.stdin.write(controlResponse + "\n");
3870
- }
3871
- const reqs = { ...sessionService._agentState?.requests };
3872
- delete reqs[requestId];
3873
- sessionService.updateAgentState({
3874
- controlledByUser: false,
3875
- requests: reqs,
3876
- completedRequests: {
3877
- ...sessionService._agentState?.completedRequests,
3878
- [requestId]: {
3879
- tool: toolName,
3880
- arguments: toolInput,
3881
- completedAt: Date.now(),
3882
- status: result.behavior === "allow" ? "approved" : "denied"
3883
- }
3884
- }
3885
- });
3886
- }).catch((err) => {
3887
- logger.log(`[Session ${sessionId}] Permission handler error (request ${requestId}): ${err}`);
3888
- });
3889
- } else if (msg.type === "control_cancel_request") {
3890
- const requestId = msg.request_id;
3891
- logger.log(`[Session ${sessionId}] Permission cancel: ${requestId}`);
3892
- const pending = pendingPermissions.get(requestId);
3893
- if (pending) {
3894
- pending.resolve({ behavior: "deny", message: "Cancelled" });
3895
- pendingPermissions.delete(requestId);
3896
- }
3897
- } else if (msg.type === "control_response") {
3898
- logger.log(`[Session ${sessionId}] Control response: ${JSON.stringify(msg).slice(0, 200)}`);
3899
- } else if (msg.type === "assistant" || msg.type === "result") {
3900
- if (msg.type === "assistant" && Array.isArray(msg.content)) {
3901
- for (const block of msg.content) {
3902
- if (block.type === "tool_use" && block.input?.run_in_background === true) {
3903
- backgroundTaskCount++;
3904
- const label = block.tool_name || block.name || "unknown";
3905
- backgroundTaskNames.push(label);
3906
- logger.log(`[Session ${sessionId}] Background task launched: ${label} (count=${backgroundTaskCount})`);
3907
- }
3908
- }
3909
- }
3910
- if (msg.type === "result") {
3911
- if (msg.is_error) {
3912
- const resultText = msg.result || "";
3913
- logger.error(`[Session ${sessionId}] Claude error (is_error=true, api_ms=${msg.duration_api_ms}): "${resultText}"`);
3914
- const lower = resultText.toLowerCase();
3915
- const isLoginIssue = lower.includes("login") || lower.includes("logged in") || lower.includes("auth") || lower.includes("api key") || lower.includes("unauthorized");
3916
- const isResumeIssue = lower.includes("tool_use.name") || lower.includes("invalid_request") || lower.includes("messages.");
3917
- let hint = "";
3918
- if (isLoginIssue) {
3919
- hint = "\n\nRun `claude login` in your terminal on the machine running the daemon to re-authenticate.";
3920
- } else if (isResumeIssue) {
3921
- hint = "\n\nThe conversation history may be corrupted. Try starting a fresh session.";
3922
- } else {
3923
- hint = "\n\nCheck that the Claude Code CLI is properly installed and configured.";
3924
- }
3925
- const displayMsg = resultText || "Claude Code exited with an error.";
3926
- sessionService.pushMessage({
3927
- type: "assistant",
3928
- content: [{ type: "text", text: `**Error:** ${displayMsg}${hint}` }]
3929
- }, "agent");
3930
- lastErrorMessagePushed = true;
3931
- }
3932
- }
3933
- if (msg.type === "result") {
3934
- if (!turnInitiatedByUser) {
3935
- logger.log(`[Session ${sessionId}] Skipping stale result from SDK-initiated turn`);
3936
- const hasBackgroundTasks = backgroundTaskCount > 0;
3937
- if (hasBackgroundTasks) {
3938
- const taskInfo = `Background tasks still running (${backgroundTaskCount}): ${backgroundTaskNames.join(", ")}`;
3939
- sessionService.pushMessage({ type: "session_event", message: taskInfo }, "session");
3940
- }
3941
- sessionService.sendKeepAlive(false);
3942
- turnInitiatedByUser = true;
3943
- continue;
3944
- }
3945
- sessionService.sendKeepAlive(false);
3946
- checkSvampConfig?.();
3947
- if (backgroundTaskCount > 0) {
3948
- const taskInfo = `Background tasks still running (${backgroundTaskCount}): ${backgroundTaskNames.join(", ")}`;
3949
- logger.log(`[Session ${sessionId}] ${taskInfo}`);
3950
- sessionService.pushMessage({ type: "session_event", message: taskInfo }, "session");
3951
- }
3952
- }
3953
- sessionService.pushMessage(msg, "agent");
3954
- if (msg.session_id) {
3955
- claudeResumeId = msg.session_id;
3956
- }
3957
- } else if (msg.type === "system" && msg.subtype === "init") {
3958
- if (!userMessagePending) {
3959
- turnInitiatedByUser = false;
3960
- logger.log(`[Session ${sessionId}] SDK-initiated turn (likely stale task_notification)`);
3961
- }
3962
- userMessagePending = false;
3963
- if (msg.session_id) {
3964
- claudeResumeId = msg.session_id;
3965
- sessionMetadata = { ...sessionMetadata, claudeSessionId: msg.session_id };
3966
- sessionService.updateMetadata(sessionMetadata);
3967
- saveSession({
3968
- sessionId,
3969
- directory,
3970
- claudeResumeId,
3971
- permissionMode: currentPermissionMode,
3972
- metadata: sessionMetadata,
3973
- createdAt: Date.now(),
3974
- machineId
3975
- });
3976
- artifactSync.scheduleDebouncedSync(sessionId, getSessionDir(directory, sessionId), sessionMetadata, machineId);
3977
- }
3978
- sessionService.pushMessage(msg, "session");
3979
- } else if (msg.type === "system" && msg.subtype === "task_notification" && msg.status === "completed") {
3980
- backgroundTaskCount = Math.max(0, backgroundTaskCount - 1);
3981
- if (backgroundTaskNames.length > 0) {
3982
- const completed = backgroundTaskNames.shift();
3983
- logger.log(`[Session ${sessionId}] Background task completed: ${completed} (remaining=${backgroundTaskCount})`);
3984
- }
3985
- sessionService.pushMessage(msg, "agent");
3986
- } else {
3987
- sessionService.pushMessage(msg, "agent");
3988
- }
3989
- } catch {
3990
- logger.log(`[Session ${sessionId}] Claude stdout (non-JSON): ${line}`);
3991
- }
3992
- }
3993
- });
3994
- let stderrBuffer = "";
3995
- child.stderr?.on("data", (chunk) => {
3996
- const text = chunk.toString();
3997
- logger.log(`[Session ${sessionId}] Claude stderr: ${text.trim()}`);
3998
- stderrBuffer += text;
3999
- });
4000
- child.on("exit", (code, signal) => {
4001
- logger.log(`[Session ${sessionId}] Claude exited: code=${code}, signal=${signal}`);
4002
- claudeProcess = null;
4003
- for (const f of isolationCleanupFiles) {
4004
- fs.rm(f, { force: true }).catch(() => {
4005
- });
4006
- }
4007
- isolationCleanupFiles = [];
4008
- for (const [id, pending] of pendingPermissions) {
4009
- pending.resolve({ behavior: "deny", message: "Claude process exited" });
4010
- }
4011
- pendingPermissions.clear();
4012
- if (code !== 0 && code !== null && !lastErrorMessagePushed) {
4013
- sessionService.pushMessage(
4014
- { type: "message", message: `Agent process exited unexpectedly (code ${code}${signal ? `, signal: ${signal}` : ""})` },
4015
- "event"
4016
- );
4017
- }
4018
- lastErrorMessagePushed = false;
4019
- sessionMetadata = { ...sessionMetadata, lifecycleState: claudeResumeId ? "idle" : "stopped" };
4020
- sessionService.updateMetadata(sessionMetadata);
4021
- sessionService.sendSessionEnd();
4022
- if (claudeResumeId && !trackedSession.stopped) {
4023
- saveSession({
4024
- sessionId,
4025
- directory,
4026
- claudeResumeId,
4027
- permissionMode: currentPermissionMode,
4028
- metadata: sessionMetadata,
4029
- createdAt: Date.now(),
4030
- machineId
4031
- });
4032
- artifactSync.syncSession(sessionId, getSessionDir(directory, sessionId), sessionMetadata, machineId).catch(() => {
4033
- });
4034
- }
4035
- });
4036
- if (initialMessage && child.stdin) {
4037
- const stdinMsg = JSON.stringify({
4038
- type: "user",
4039
- message: { role: "user", content: initialMessage }
4040
- });
4041
- child.stdin.write(stdinMsg + "\n");
4042
- }
4043
- return child;
4044
- };
4045
- const sessionService = await registerSessionService(
4046
- server,
4047
- sessionId,
4048
- sessionMetadata,
4049
- { controlledByUser: false },
4050
- {
4051
- onUserMessage: (content, meta) => {
4052
- logger.log(`[Session ${sessionId}] User message received`);
4053
- userMessagePending = true;
4054
- turnInitiatedByUser = true;
4055
- let text;
4056
- let msgMeta = meta;
4057
- try {
4058
- let parsed = typeof content === "string" ? JSON.parse(content) : content;
4059
- if (parsed?.content && typeof parsed.content === "string") {
4060
- try {
4061
- const inner = JSON.parse(parsed.content);
4062
- if (inner && typeof inner === "object") parsed = inner;
4063
- } catch {
4064
- }
4065
- }
4066
- text = parsed?.content?.text || parsed?.text || (typeof parsed === "string" ? parsed : JSON.stringify(parsed));
4067
- if (parsed?.meta) msgMeta = { ...msgMeta, ...parsed.meta };
4068
- } catch {
4069
- text = typeof content === "string" ? content : JSON.stringify(content);
4070
- }
4071
- if (msgMeta?.permissionMode) {
4072
- currentPermissionMode = toClaudePermissionMode(msgMeta.permissionMode);
4073
- logger.log(`[Session ${sessionId}] Permission mode updated to: ${currentPermissionMode}`);
4074
- }
4075
- if (isKillingClaude) {
4076
- logger.log(`[Session ${sessionId}] Message received while restarting Claude, ignoring to prevent ghost process`);
4077
- sessionService.sendKeepAlive(false);
4078
- return;
4079
- }
4080
- if (!claudeProcess || claudeProcess.exitCode !== null) {
4081
- spawnClaude(text, msgMeta);
4082
- } else {
4083
- const stdinMsg = JSON.stringify({
4084
- type: "user",
4085
- message: { role: "user", content: text }
4086
- });
4087
- claudeProcess.stdin?.write(stdinMsg + "\n");
4088
- }
4089
- sessionService.sendKeepAlive(true);
4090
- },
4091
- onAbort: () => {
4092
- logger.log(`[Session ${sessionId}] Abort requested`);
4093
- if (claudeProcess && !claudeProcess.killed) {
4094
- claudeProcess.kill("SIGINT");
4095
- }
4096
- },
4097
- onPermissionResponse: (params) => {
4098
- logger.log(`[Session ${sessionId}] Permission response:`, JSON.stringify(params));
4099
- const requestId = params.id;
4100
- const pending = pendingPermissions.get(requestId);
4101
- if (params.mode) {
4102
- currentPermissionMode = toClaudePermissionMode(params.mode);
4103
- logger.log(`[Session ${sessionId}] Permission mode changed to: ${currentPermissionMode}`);
4104
- }
4105
- if (params.allowTools && Array.isArray(params.allowTools)) {
4106
- for (const tool of params.allowTools) {
4107
- if (tool.startsWith("Bash(") || tool === "Bash") {
4108
- parseBashPermission2(tool);
4109
- } else {
4110
- allowedTools.add(tool);
4111
- }
4112
- }
4113
- logger.log(`[Session ${sessionId}] Updated allowed tools: ${[...allowedTools].join(", ")}`);
4114
- }
4115
- if (pending) {
4116
- pendingPermissions.delete(requestId);
4117
- if (params.approved) {
4118
- pending.resolve({
4119
- behavior: "allow",
4120
- updatedInput: pending.input || {}
4121
- });
4122
- } else {
4123
- pending.resolve({
4124
- behavior: "deny",
4125
- message: params.reason || "The user doesn't want to proceed with this tool use. The tool use was rejected (eg. if it was a file edit, the new_string was NOT written to the file). STOP what you are doing and wait for the user to tell you how to proceed."
4126
- });
4127
- }
4128
- } else {
4129
- logger.log(`[Session ${sessionId}] No pending permission for id=${requestId}`);
4130
- }
4131
- },
4132
- onSwitchMode: async (mode) => {
4133
- logger.log(`[Session ${sessionId}] Switch mode: ${mode}`);
4134
- currentPermissionMode = mode;
4135
- if (claudeProcess && claudeProcess.exitCode === null) {
4136
- isKillingClaude = true;
4137
- await killAndWaitForExit2(claudeProcess);
4138
- isKillingClaude = false;
4139
- spawnClaude(void 0, { permissionMode: mode });
4140
- }
4141
- },
4142
- onRestartClaude: async () => {
4143
- logger.log(`[Session ${sessionId}] Restart Claude requested`);
4144
- try {
4145
- if (claudeProcess && claudeProcess.exitCode === null) {
4146
- isKillingClaude = true;
4147
- sessionMetadata = { ...sessionMetadata, lifecycleState: "restarting" };
4148
- sessionService.updateMetadata(sessionMetadata);
4149
- await killAndWaitForExit2(claudeProcess);
4150
- isKillingClaude = false;
4151
- }
4152
- if (claudeResumeId) {
4153
- spawnClaude(void 0, { permissionMode: currentPermissionMode });
4154
- logger.log(`[Session ${sessionId}] Claude respawned with --resume ${claudeResumeId}`);
4155
- return { success: true, message: "Claude process restarted successfully." };
4156
- } else {
4157
- logger.log(`[Session ${sessionId}] No resume ID \u2014 cannot restart`);
4158
- return { success: false, message: "No session to resume. Send a message to start a new session." };
4159
- }
4160
- } catch (err) {
4161
- isKillingClaude = false;
4162
- logger.log(`[Session ${sessionId}] Restart failed: ${err.message}`);
4163
- return { success: false, message: `Restart failed: ${err.message}` };
4164
- }
4165
- },
4166
- onKillSession: () => {
4167
- logger.log(`[Session ${sessionId}] Kill session requested`);
4168
- stopSession(sessionId);
4169
- },
4170
- onBash: async (command, cwd) => {
4171
- logger.log(`[Session ${sessionId}] Bash: ${command} (cwd: ${cwd || directory})`);
4172
- const { exec } = await import('child_process');
4173
- return new Promise((resolve2) => {
4174
- exec(command, { cwd: cwd || directory, timeout: 3e4, maxBuffer: 1024 * 1024 }, (err, stdout, stderr) => {
4175
- if (err) {
4176
- resolve2({ success: false, stdout: stdout || "", stderr: stderr || err.message, exitCode: err.code ?? 1 });
4177
- } else {
4178
- resolve2({ success: true, stdout, stderr: stderr || "", exitCode: 0 });
4179
- }
4180
- });
4181
- });
4182
- },
4183
- onRipgrep: async (args, cwd) => {
4184
- const { exec } = await import('child_process');
4185
- const rgCwd = cwd || directory;
4186
- return new Promise((resolve2, reject) => {
4187
- exec(`rg ${args}`, { cwd: rgCwd, timeout: 3e4, maxBuffer: 5 * 1024 * 1024 }, (err, stdout) => {
4188
- if (err && !stdout) {
4189
- reject(new Error(err.message));
4190
- } else {
4191
- resolve2(stdout || "");
4192
- }
4193
- });
4194
- });
4195
- },
4196
- onReadFile: async (path) => {
4197
- const resolvedPath = resolve(directory, path);
4198
- if (!resolvedPath.startsWith(resolve(directory))) {
4199
- throw new Error("Path outside working directory");
4200
- }
4201
- const buffer = await fs.readFile(resolvedPath);
4202
- return buffer.toString("base64");
4203
- },
4204
- onWriteFile: async (path, content) => {
4205
- const resolvedPath = resolve(directory, path);
4206
- if (!resolvedPath.startsWith(resolve(directory))) {
4207
- throw new Error("Path outside working directory");
4208
- }
4209
- await fs.mkdir(dirname(resolvedPath), { recursive: true });
4210
- await fs.writeFile(resolvedPath, Buffer.from(content, "base64"));
4211
- },
4212
- onListDirectory: async (path) => {
4213
- const resolvedDir = resolve(directory, path || ".");
4214
- if (!resolvedDir.startsWith(resolve(directory))) {
4215
- throw new Error("Path outside working directory");
4216
- }
4217
- const entries = await fs.readdir(resolvedDir, { withFileTypes: true });
4218
- return entries.map((e) => ({ name: e.name, isDirectory: e.isDirectory() }));
4219
- },
4220
- onGetDirectoryTree: async (treePath, maxDepth) => {
4221
- async function buildTree(p, name, depth) {
4222
- try {
4223
- const stats = await fs.stat(p);
4224
- const node = {
4225
- name,
4226
- path: p,
4227
- type: stats.isDirectory() ? "directory" : "file",
4228
- size: stats.size,
4229
- modified: stats.mtime.getTime()
4230
- };
4231
- if (stats.isDirectory() && depth < maxDepth) {
4232
- const entries = await fs.readdir(p, { withFileTypes: true });
4233
- const children = [];
4234
- await Promise.all(entries.map(async (entry) => {
4235
- if (entry.isSymbolicLink()) return;
4236
- const childPath = join$1(p, entry.name);
4237
- const childNode = await buildTree(childPath, entry.name, depth + 1);
4238
- if (childNode) children.push(childNode);
4239
- }));
4240
- children.sort((a, b) => {
4241
- if (a.type === "directory" && b.type !== "directory") return -1;
4242
- if (a.type !== "directory" && b.type === "directory") return 1;
4243
- return a.name.localeCompare(b.name);
4244
- });
4245
- node.children = children;
4246
- }
4247
- return node;
4248
- } catch {
4249
- return null;
4250
- }
4251
- }
4252
- const resolvedPath = resolve(directory, treePath);
4253
- const tree = await buildTree(resolvedPath, basename(resolvedPath), 0);
4254
- return { success: !!tree, tree };
4255
- }
4256
- },
4257
- { messagesDir: getSessionDir(directory, sessionId) }
4258
- );
4259
- checkSvampConfig = createSvampConfigChecker(
4260
- directory,
4261
- sessionId,
4262
- () => sessionMetadata,
4263
- (updater) => {
4264
- sessionMetadata = updater(sessionMetadata);
4265
- sessionService.updateMetadata(sessionMetadata);
4266
- },
4267
- sessionService,
4268
- logger
4269
- );
4270
- const trackedSession = {
4271
- startedBy: "daemon",
4272
- pid: process.pid,
4273
- svampSessionId: sessionId,
4274
- hyphaService: sessionService,
4275
- checkSvampConfig,
4276
- directory,
4277
- resumeSessionId: claudeResumeId,
4278
- get childProcess() {
4279
- return claudeProcess || void 0;
4280
- }
4281
- };
4282
- pidToTrackedSession.set(process.pid + Math.floor(Math.random() * 1e5), trackedSession);
4283
- sessionMetadata = { ...sessionMetadata, lifecycleState: "idle" };
4284
- sessionService.updateMetadata(sessionMetadata);
4285
- logger.log(`Session ${sessionId} registered on Hypha, waiting for first message to spawn Claude`);
4286
- return {
4287
- type: "success",
4288
- sessionId,
4289
- message: `Session registered on Hypha as svamp-session-${sessionId}`
4290
- };
4291
- } catch (err) {
4292
- logger.error(`Failed to spawn session:`, err);
4293
- return {
4294
- type: "error",
4295
- errorMessage: `Failed to register session service: ${err.message}`
4296
- };
4297
- }
4298
- };
4299
- const spawnAgentSession = async (sessionId, directory, agentName, options, resumeSessionId) => {
4300
- logger.log(`[Agent] Spawning ${agentName} session: ${sessionId}`);
4301
- try {
4302
- let parseBashPermission2 = function(permission) {
4303
- if (permission === "Bash") return;
4304
- const match = permission.match(/^Bash\((.+?)\)$/);
4305
- if (!match) return;
4306
- const command = match[1];
4307
- if (command.endsWith(":*")) {
4308
- allowedBashPrefixes.add(command.slice(0, -2));
4309
- } else {
4310
- allowedBashLiterals.add(command);
4311
- }
4312
- }, shouldAutoAllow2 = function(toolName, toolInput) {
4313
- if (toolName === "Bash") {
4314
- const inputObj = toolInput;
4315
- if (inputObj?.command) {
4316
- if (allowedBashLiterals.has(inputObj.command)) return true;
4317
- for (const prefix of allowedBashPrefixes) {
4318
- if (inputObj.command.startsWith(prefix)) return true;
4319
- }
4320
- }
4321
- } else if (allowedTools.has(toolName)) {
4322
- return true;
4323
- }
4324
- if (currentPermissionMode === "bypassPermissions" || currentPermissionMode === "yolo") return true;
4325
- if ((currentPermissionMode === "acceptEdits" || currentPermissionMode === "safe-yolo") && EDIT_TOOLS.has(toolName)) return true;
4326
- return false;
4327
- };
4328
- var parseBashPermission = parseBashPermission2, shouldAutoAllow = shouldAutoAllow2;
4329
- let sessionMetadata = {
4330
- path: directory,
4331
- host: os.hostname(),
4332
- version: "0.1.0",
4333
- machineId,
4334
- homeDir: os.homedir(),
4335
- svampHomeDir: SVAMP_HOME,
4336
- svampLibDir: join$1(__dirname$1, ".."),
4337
- svampToolsDir: join$1(__dirname$1, "..", "tools"),
4338
- startedFromDaemon: true,
4339
- startedBy: "daemon",
4340
- lifecycleState: "starting",
4341
- flavor: agentName,
4342
- sharing: options.sharing
4343
- };
4344
- let currentPermissionMode = "default";
4345
- const allowedTools = /* @__PURE__ */ new Set();
4346
- const allowedBashLiterals = /* @__PURE__ */ new Set();
4347
- const allowedBashPrefixes = /* @__PURE__ */ new Set();
4348
- const EDIT_TOOLS = /* @__PURE__ */ new Set(["Edit", "MultiEdit", "Write", "NotebookEdit"]);
4349
- const sessionService = await registerSessionService(
4350
- server,
4351
- sessionId,
4352
- sessionMetadata,
4353
- { controlledByUser: false },
4354
- {
4355
- onUserMessage: (content, meta) => {
4356
- logger.log(`[${agentName} Session ${sessionId}] User message received`);
4357
- let text;
4358
- let msgMeta = meta;
4359
- try {
4360
- let parsed = typeof content === "string" ? JSON.parse(content) : content;
4361
- if (parsed?.content && typeof parsed.content === "string") {
4362
- try {
4363
- const inner = JSON.parse(parsed.content);
4364
- if (inner && typeof inner === "object") parsed = inner;
4365
- } catch {
4366
- }
4367
- }
4368
- text = parsed?.content?.text || parsed?.text || (typeof parsed === "string" ? parsed : JSON.stringify(parsed));
4369
- if (parsed?.meta) msgMeta = { ...msgMeta, ...parsed.meta };
4370
- } catch {
4371
- text = typeof content === "string" ? content : JSON.stringify(content);
4372
- }
4373
- if (msgMeta?.permissionMode) {
4374
- currentPermissionMode = msgMeta.permissionMode;
4375
- }
4376
- agentBackend.sendPrompt(sessionId, text).catch((err) => {
4377
- logger.error(`[${agentName} Session ${sessionId}] Error sending prompt:`, err);
4378
- });
4379
- },
4380
- onAbort: () => {
4381
- logger.log(`[${agentName} Session ${sessionId}] Abort requested`);
4382
- agentBackend.cancel(sessionId).catch(() => {
4383
- });
4384
- },
4385
- onPermissionResponse: (params) => {
4386
- logger.log(`[${agentName} Session ${sessionId}] Permission response:`, JSON.stringify(params));
4387
- const requestId = params.id;
4388
- if (params.mode) currentPermissionMode = params.mode;
4389
- if (params.allowTools && Array.isArray(params.allowTools)) {
4390
- for (const tool of params.allowTools) {
4391
- if (tool.startsWith("Bash(") || tool === "Bash") {
4392
- parseBashPermission2(tool);
4393
- } else {
4394
- allowedTools.add(tool);
4395
- }
4396
- }
4397
- }
4398
- permissionHandler.resolvePermission(requestId, params.approved);
4399
- agentBackend.respondToPermission?.(requestId, params.approved);
4400
- },
4401
- onSwitchMode: (mode) => {
4402
- logger.log(`[${agentName} Session ${sessionId}] Switch mode: ${mode}`);
4403
- currentPermissionMode = mode;
4404
- },
4405
- onRestartClaude: async () => {
4406
- logger.log(`[${agentName} Session ${sessionId}] Restart agent requested`);
4407
- return { success: false, message: "Restart is not supported for this agent type." };
4408
- },
4409
- onKillSession: () => {
4410
- logger.log(`[${agentName} Session ${sessionId}] Kill session requested`);
4411
- stopSession(sessionId);
4412
- },
4413
- onBash: async (command, cwd) => {
4414
- const { exec } = await import('child_process');
4415
- return new Promise((resolve2) => {
4416
- exec(command, { cwd: cwd || directory, timeout: 3e4, maxBuffer: 1024 * 1024 }, (err, stdout, stderr) => {
4417
- if (err) {
4418
- resolve2({ success: false, stdout: stdout || "", stderr: stderr || err.message, exitCode: err.code ?? 1 });
4419
- } else {
4420
- resolve2({ success: true, stdout, stderr: stderr || "", exitCode: 0 });
4421
- }
4422
- });
4423
- });
4424
- },
4425
- onRipgrep: async (args, cwd) => {
4426
- const { exec } = await import('child_process');
4427
- const rgCwd = cwd || directory;
4428
- return new Promise((resolve2, reject) => {
4429
- exec(`rg ${args}`, { cwd: rgCwd, timeout: 3e4, maxBuffer: 5 * 1024 * 1024 }, (err, stdout) => {
4430
- if (err && !stdout) {
4431
- reject(new Error(err.message));
4432
- } else {
4433
- resolve2(stdout || "");
4434
- }
4435
- });
4436
- });
4437
- },
4438
- onReadFile: async (path) => {
4439
- const resolvedPath = resolve(directory, path);
4440
- if (!resolvedPath.startsWith(resolve(directory))) {
4441
- throw new Error("Path outside working directory");
4442
- }
4443
- const buffer = await fs.readFile(resolvedPath);
4444
- return buffer.toString("base64");
4445
- },
4446
- onWriteFile: async (path, content) => {
4447
- const resolvedPath = resolve(directory, path);
4448
- if (!resolvedPath.startsWith(resolve(directory))) {
4449
- throw new Error("Path outside working directory");
4450
- }
4451
- await fs.mkdir(dirname(resolvedPath), { recursive: true });
4452
- await fs.writeFile(resolvedPath, Buffer.from(content, "base64"));
4453
- },
4454
- onListDirectory: async (path) => {
4455
- const resolvedDir = resolve(directory, path || ".");
4456
- if (!resolvedDir.startsWith(resolve(directory))) {
4457
- throw new Error("Path outside working directory");
4458
- }
4459
- const entries = await fs.readdir(resolvedDir, { withFileTypes: true });
4460
- return entries.map((e) => ({ name: e.name, isDirectory: e.isDirectory() }));
4461
- },
4462
- onGetDirectoryTree: async (treePath, maxDepth) => {
4463
- async function buildTree(p, name, depth) {
4464
- try {
4465
- const stats = await fs.stat(p);
4466
- const node = {
4467
- name,
4468
- path: p,
4469
- type: stats.isDirectory() ? "directory" : "file",
4470
- size: stats.size,
4471
- modified: stats.mtime.getTime()
4472
- };
4473
- if (stats.isDirectory() && depth < maxDepth) {
4474
- const entries = await fs.readdir(p, { withFileTypes: true });
4475
- const children = [];
4476
- await Promise.all(entries.map(async (entry) => {
4477
- if (entry.isSymbolicLink()) return;
4478
- const childPath = join$1(p, entry.name);
4479
- const childNode = await buildTree(childPath, entry.name, depth + 1);
4480
- if (childNode) children.push(childNode);
4481
- }));
4482
- children.sort((a, b) => {
4483
- if (a.type === "directory" && b.type !== "directory") return -1;
4484
- if (a.type !== "directory" && b.type === "directory") return 1;
4485
- return a.name.localeCompare(b.name);
4486
- });
4487
- node.children = children;
4488
- }
4489
- return node;
4490
- } catch {
4491
- return null;
4492
- }
4493
- }
4494
- const resolvedPath = resolve(directory, treePath);
4495
- const tree = await buildTree(resolvedPath, basename(resolvedPath), 0);
4496
- return { success: !!tree, tree };
4497
- }
4498
- },
4499
- { messagesDir: getSessionDir(directory, sessionId) }
4500
- );
4501
- const checkSvampConfig = createSvampConfigChecker(
4502
- directory,
4503
- sessionId,
4504
- () => sessionMetadata,
4505
- (updater) => {
4506
- sessionMetadata = updater(sessionMetadata);
4507
- sessionService.updateMetadata(sessionMetadata);
4508
- },
4509
- sessionService,
4510
- logger
4511
- );
4512
- const permissionHandler = new HyphaPermissionHandler(shouldAutoAllow2, logger.log);
4513
- let agentIsoConfig;
4514
- if (sessionMetadata.sharing?.enabled && isolationCapabilities.preferred) {
4515
- const method = isolationCapabilities.preferred;
4516
- const detail = isolationCapabilities.details[method];
4517
- if (detail.found && detail.verified !== false) {
4518
- agentIsoConfig = {
4519
- method,
4520
- binaryPath: detail.path || method,
4521
- workspacePath: directory
4522
- };
4523
- sessionMetadata = { ...sessionMetadata, isolationMethod: method };
4524
- logger.log(`[Agent Session ${sessionId}] Isolation: ${method}`);
4525
- }
4526
- }
4527
- let agentBackend;
4528
- if (KNOWN_MCP_AGENTS[agentName]) {
4529
- agentBackend = new CodexMcpBackend({
4530
- cwd: directory,
4531
- env: options.environmentVariables,
4532
- log: logger.log,
4533
- isolationConfig: agentIsoConfig
4534
- });
4535
- } else {
4536
- const transportHandler = agentName === "gemini" ? new GeminiTransport() : new DefaultTransport(agentName);
4537
- const acpConfig = KNOWN_ACP_AGENTS[agentName];
4538
- agentBackend = new AcpBackend({
4539
- agentName,
4540
- cwd: directory,
4541
- command: acpConfig.command,
4542
- args: acpConfig.args,
4543
- env: options.environmentVariables,
4544
- permissionHandler,
4545
- transportHandler,
4546
- log: logger.log,
4547
- isolationConfig: agentIsoConfig
4548
- });
4549
- }
4550
- bridgeAcpToSession(
4551
- agentBackend,
4552
- sessionService,
4553
- () => sessionMetadata,
4554
- (updater) => {
4555
- sessionMetadata = updater(sessionMetadata);
4556
- sessionService.updateMetadata(sessionMetadata);
4557
- },
4558
- logger.log,
4559
- checkSvampConfig
4560
- );
4561
- const trackedSession = {
4562
- startedBy: "daemon",
4563
- pid: process.pid,
4564
- svampSessionId: sessionId,
4565
- hyphaService: sessionService,
4566
- checkSvampConfig,
4567
- directory,
4568
- resumeSessionId,
4569
- get childProcess() {
4570
- return agentBackend.getProcess?.() || void 0;
4571
- }
4572
- };
4573
- pidToTrackedSession.set(process.pid + Math.floor(Math.random() * 1e5), trackedSession);
4574
- logger.log(`[Agent Session ${sessionId}] Starting ${agentName} backend...`);
4575
- agentBackend.startSession().then(() => {
4576
- logger.log(`[Agent Session ${sessionId}] ${agentName} backend started, waiting for first message`);
4577
- }).catch((err) => {
4578
- logger.error(`[Agent Session ${sessionId}] Failed to start ${agentName}:`, err);
4579
- sessionService.pushMessage(
4580
- { type: "message", message: `Agent process exited unexpectedly: ${err.message}. Please ensure the ${agentName} CLI is installed.` },
4581
- "event"
4582
- );
4583
- sessionService.sendSessionEnd();
4584
- });
4585
- return {
4586
- type: "success",
4587
- sessionId,
4588
- message: `Agent session (${agentName}) registered as svamp-session-${sessionId}`
4589
- };
4590
- } catch (err) {
4591
- logger.error(`[Agent] Failed to spawn ${agentName} session:`, err);
4592
- return {
4593
- type: "error",
4594
- errorMessage: `Failed to spawn ${agentName} session: ${err.message}`
4595
- };
4596
- }
4597
- };
4598
- const stopSession = (sessionId) => {
4599
- logger.log(`Stopping session: ${sessionId}`);
4600
- for (const [pid, session] of pidToTrackedSession) {
4601
- if (session.svampSessionId === sessionId) {
4602
- session.stopped = true;
4603
- session.hyphaService?.disconnect().catch(() => {
4604
- });
4605
- if (session.childProcess) {
4606
- try {
4607
- session.childProcess.kill("SIGTERM");
4608
- } catch {
4609
- }
4610
- }
4611
- pidToTrackedSession.delete(pid);
4612
- deletePersistedSession(sessionId);
4613
- logger.log(`Session ${sessionId} stopped`);
4614
- return true;
4615
- }
4616
- }
4617
- logger.log(`Session ${sessionId} not found`);
4618
- return false;
4619
- };
4620
- let isolationCapabilities;
4621
- try {
4622
- isolationCapabilities = await detectIsolationCapabilities();
4623
- logger.log(`Isolation capabilities: ${isolationCapabilities.available.join(", ") || "none"} (preferred: ${isolationCapabilities.preferred || "none"})`);
4624
- } catch (err) {
4625
- logger.log(`Failed to detect isolation capabilities: ${err}`);
4626
- isolationCapabilities = { available: [], preferred: null, details: { srt: { found: false }, bwrap: { found: false }, docker: { found: false }, podman: { found: false } } };
4627
- }
4628
- const defaultHomeDir = existsSync$1("/data") ? "/data" : os.homedir();
4629
- const machineMetadata = {
4630
- host: os.hostname(),
4631
- platform: os.platform(),
4632
- svampVersion: "0.1.0 (hypha)",
4633
- homeDir: defaultHomeDir,
4634
- svampHomeDir: SVAMP_HOME,
4635
- svampLibDir: join$1(__dirname$1, ".."),
4636
- displayName: process.env.SVAMP_DISPLAY_NAME || void 0,
4637
- isolationCapabilities
4638
- };
4639
- const initialDaemonState = {
4640
- status: "running",
4641
- pid: process.pid,
4642
- startedAt: Date.now()
4643
- };
4644
- const machineService = await registerMachineService(
4645
- server,
4646
- machineId,
4647
- machineMetadata,
4648
- initialDaemonState,
4649
- {
4650
- spawnSession,
4651
- stopSession,
4652
- requestShutdown: () => requestShutdown("hypha-app"),
4653
- getTrackedSessions: getCurrentChildren
4654
- }
4655
- );
4656
- logger.log(`Machine service registered: svamp-machine-${machineId}`);
4657
- const artifactSync = new SessionArtifactSync(server, logger.log);
4658
- const debugService = await registerDebugService(server, machineId, {
4659
- machineId,
4660
- getTrackedSessions: getCurrentChildren,
4661
- getSessionService: (sessionId) => {
4662
- for (const [, session] of pidToTrackedSession) {
4663
- if (session.svampSessionId === sessionId) {
4664
- return session.hyphaService;
4665
- }
4666
- }
4667
- return null;
4668
- },
4669
- getArtifactSync: () => artifactSync,
4670
- getSessionsDir: () => SVAMP_HOME
4671
- // Legacy; debug service uses session index now
4672
- });
4673
- logger.log(`Debug service registered: svamp-debug-${machineId}`);
4674
- const persistedSessions = loadPersistedSessions();
4675
- if (persistedSessions.length > 0) {
4676
- logger.log(`Restoring ${persistedSessions.length} persisted session(s)...`);
4677
- for (const persisted of persistedSessions) {
4678
- try {
4679
- const isOrphaned = persisted.machineId && persisted.machineId !== machineId;
4680
- if (isOrphaned) {
4681
- logger.log(`Session ${persisted.sessionId} is from a different machine (${persisted.machineId} vs ${machineId}), marking as orphaned`);
4682
- }
4683
- const result = await spawnSession({
4684
- directory: persisted.directory,
4685
- sessionId: persisted.sessionId,
4686
- resumeSessionId: persisted.claudeResumeId
4687
- });
4688
- if (result.type === "success") {
4689
- logger.log(`Restored session ${persisted.sessionId} (resume=${persisted.claudeResumeId})`);
4690
- if (isOrphaned) {
4691
- for (const [, tracked] of pidToTrackedSession) {
4692
- if (tracked.svampSessionId === persisted.sessionId && tracked.hyphaService) {
4693
- tracked.hyphaService.updateMetadata({
4694
- ...persisted.metadata || {},
4695
- isOrphaned: true,
4696
- originalMachineId: persisted.machineId
4697
- });
4698
- break;
4699
- }
4700
- }
4701
- }
4702
- } else {
4703
- logger.log(`Failed to restore session ${persisted.sessionId}: ${result.type}`);
4704
- }
4705
- } catch (err) {
4706
- logger.error(`Error restoring session ${persisted.sessionId}:`, err.message);
4707
- }
4708
- }
4709
- }
4710
- (async () => {
4711
- try {
4712
- await artifactSync.init();
4713
- logger.log(`[ARTIFACT SYNC] Ready (upload-only, remote sessions stay in artifact store)`);
4714
- } catch (err) {
4715
- logger.log(`[ARTIFACT SYNC] Background init failed: ${err.message}`);
4716
- }
4717
- })();
4718
- let appToken;
4719
- try {
4720
- appToken = await server.generateToken({});
4721
- logger.log(`App connection token generated`);
4722
- } catch (err) {
4723
- logger.log("Could not generate token (server may not support it):", err);
4724
- }
4725
- const supervised = process.env.SVAMP_SUPERVISED === "1";
4726
- const localState = {
4727
- pid: process.pid,
4728
- startTime: (/* @__PURE__ */ new Date()).toISOString(),
4729
- version: DAEMON_VERSION,
4730
- hyphaServerUrl,
4731
- workspace: server.config.workspace,
4732
- machineId,
4733
- supervised
4734
- };
4735
- writeDaemonStateFile(localState);
4736
- console.log("Svamp daemon started successfully!");
4737
- console.log(` Machine ID: ${machineId}`);
4738
- console.log(` Hypha server: ${hyphaServerUrl}`);
4739
- console.log(` Workspace: ${server.config.workspace}`);
4740
- if (appToken) {
4741
- console.log(` App token: ${appToken}`);
4742
- }
4743
- console.log(` Service: svamp-machine-${machineId}`);
4744
- console.log(` Log file: ${logger.logFilePath}`);
4745
- let consecutiveHeartbeatFailures = 0;
4746
- const MAX_HEARTBEAT_FAILURES = 60;
4747
- const heartbeatInterval = setInterval(async () => {
4748
- try {
4749
- const state = readDaemonStateFile();
4750
- if (state && state.pid === process.pid) {
4751
- state.lastHeartbeat = (/* @__PURE__ */ new Date()).toISOString();
4752
- writeDaemonStateFile(state);
4753
- }
4754
- } catch {
4755
- }
4756
- try {
4757
- const installedVersion = readPackageVersion();
4758
- if (installedVersion !== "unknown" && installedVersion !== DAEMON_VERSION) {
4759
- logger.log(`svamp-cli version changed on disk: ${DAEMON_VERSION} \u2192 ${installedVersion}. Self-restarting...`);
4760
- const supervised2 = process.env.SVAMP_SUPERVISED === "1";
4761
- if (!supervised2) {
4762
- const { spawn: spawnSelf } = await import('child_process');
4763
- spawnSelf(process.argv[0], process.argv.slice(1), {
4764
- detached: true,
4765
- stdio: "ignore",
4766
- env: process.env
4767
- }).unref();
4768
- await new Promise((r) => setTimeout(r, 500));
4769
- }
4770
- requestShutdown("version-update", `Updated ${DAEMON_VERSION} \u2192 ${installedVersion}`);
4771
- return;
4772
- }
4773
- } catch {
4774
- }
4775
- for (const [key, session] of pidToTrackedSession) {
4776
- const child = session.childProcess;
4777
- if (child && child.pid) {
4778
- try {
4779
- process.kill(child.pid, 0);
4780
- } catch {
4781
- logger.log(`Removing stale session (child PID ${child.pid} dead): ${session.svampSessionId}`);
4782
- session.hyphaService?.disconnect().catch(() => {
4783
- });
4784
- pidToTrackedSession.delete(key);
4785
- }
4786
- }
4787
- }
4788
- const serverAny = server;
4789
- const rpcReconnecting = serverAny._connection?._reconnecting === true;
4790
- if (rpcReconnecting && !isReconnecting) {
4791
- isReconnecting = true;
4792
- logger.log("Detected hypha-rpc reconnection in progress");
4793
- }
4794
- if (isReconnecting) {
4795
- consecutiveHeartbeatFailures++;
4796
- logger.log(`Heartbeat skipped (reconnecting), failures=${consecutiveHeartbeatFailures}/${MAX_HEARTBEAT_FAILURES}`);
4797
- if (consecutiveHeartbeatFailures >= MAX_HEARTBEAT_FAILURES) {
4798
- logger.log("Too many consecutive heartbeat failures during reconnection. Shutting down.");
4799
- requestShutdown("heartbeat-timeout", "Reconnection taking too long");
4800
- }
4801
- return;
4802
- }
4803
- try {
4804
- await Promise.race([
4805
- server.echo("ping"),
4806
- new Promise((_, reject) => setTimeout(() => reject(new Error("Heartbeat ping timed out after 30s")), 3e4))
4807
- ]);
4808
- if (consecutiveHeartbeatFailures > 0) {
4809
- logger.log(`Heartbeat recovered after ${consecutiveHeartbeatFailures} failures`);
4810
- }
4811
- consecutiveHeartbeatFailures = 0;
4812
- isReconnecting = false;
4813
- } catch (err) {
4814
- consecutiveHeartbeatFailures++;
4815
- logger.log(`Hypha keep-alive ping failed (${consecutiveHeartbeatFailures}/${MAX_HEARTBEAT_FAILURES}): ${err.message}`);
4816
- if (!isReconnecting) {
4817
- isReconnecting = true;
4818
- logger.log("Entering reconnection state \u2014 hypha-rpc will attempt to reconnect");
4819
- }
4820
- if (consecutiveHeartbeatFailures >= MAX_HEARTBEAT_FAILURES) {
4821
- logger.log(`Heartbeat failed ${MAX_HEARTBEAT_FAILURES} consecutive times. Shutting down.`);
4822
- requestShutdown("heartbeat-timeout", err.message);
4823
- }
4824
- }
4825
- }, 6e4);
4826
- const cleanup = async (source) => {
4827
- logger.log(`Cleaning up (source: ${source})...`);
4828
- clearInterval(heartbeatInterval);
4829
- if (unhandledRejectionResetTimer) clearTimeout(unhandledRejectionResetTimer);
4830
- machineService.updateDaemonState({
4831
- ...initialDaemonState,
4832
- status: "shutting-down",
4833
- shutdownRequestedAt: Date.now(),
4834
- shutdownSource: source
4835
- });
4836
- await new Promise((r) => setTimeout(r, 200));
4837
- for (const [pid, session] of pidToTrackedSession) {
4838
- session.hyphaService?.disconnect().catch(() => {
4839
- });
4840
- if (session.childProcess) {
4841
- try {
4842
- session.childProcess.kill("SIGTERM");
4843
- } catch {
4844
- }
4845
- }
4846
- }
4847
- const shouldMarkStopped = source === "os-signal-cleanup";
4848
- if (shouldMarkStopped) {
4849
- try {
4850
- const index = loadSessionIndex();
4851
- for (const [sessionId, entry] of Object.entries(index)) {
4852
- const filePath = getSessionFilePath(entry.directory, sessionId);
4853
- if (existsSync$1(filePath)) {
4854
- const data = JSON.parse(readFileSync$1(filePath, "utf-8"));
4855
- writeFileSync$1(filePath, JSON.stringify({ ...data, stopped: true }, null, 2), "utf-8");
4856
- }
4857
- }
4858
- logger.log("Marked all sessions as stopped (--cleanup mode)");
4859
- } catch {
4860
- }
4861
- } else {
4862
- logger.log("Sessions preserved for auto-restore on next start");
4863
- }
4864
- try {
4865
- await machineService.disconnect();
4866
- } catch {
4867
- }
4868
- try {
4869
- await debugService.disconnect();
4870
- } catch {
4871
- }
4872
- artifactSync.destroy();
4873
- try {
4874
- await server.disconnect();
4875
- } catch {
4876
- }
4877
- cleanupDaemonStateFile();
4878
- logger.log("Cleanup complete");
4879
- };
4880
- const shutdownReq = await resolvesWhenShutdownRequested;
4881
- await cleanup(shutdownReq.source);
4882
- if (process.env.SVAMP_SUPERVISED === "1" && shutdownReq.source === "version-update") {
4883
- process.exit(1);
4884
- }
4885
- process.exit(0);
4886
- } catch (error) {
4887
- logger.error("Fatal error:", error);
4888
- cleanupDaemonStateFile();
4889
- if (server) {
4890
- try {
4891
- await server.disconnect();
4892
- } catch {
4893
- }
4894
- }
4895
- process.exit(1);
4896
- }
4897
- }
4898
- async function stopDaemon(options) {
4899
- const state = readDaemonStateFile();
4900
- if (!state) {
4901
- console.log("No daemon running");
4902
- return;
4903
- }
4904
- const signal = options?.cleanup ? "SIGUSR1" : "SIGTERM";
4905
- const mode = options?.cleanup ? "cleanup (sessions will be stopped)" : "quick (sessions preserved for auto-restore)";
4906
- try {
4907
- process.kill(state.pid, 0);
4908
- process.kill(state.pid, signal);
4909
- console.log(`Sent ${signal} to daemon PID ${state.pid} \u2014 ${mode}`);
4910
- for (let i = 0; i < 30; i++) {
4911
- await new Promise((r) => setTimeout(r, 100));
4912
- try {
4913
- process.kill(state.pid, 0);
4914
- } catch {
4915
- console.log("Daemon stopped");
4916
- cleanupDaemonStateFile();
4917
- return;
4918
- }
4919
- }
4920
- console.log("Daemon did not stop in time, sending SIGKILL");
4921
- process.kill(state.pid, "SIGKILL");
4922
- } catch {
4923
- console.log("Daemon is not running (stale state file)");
4924
- }
4925
- cleanupDaemonStateFile();
4926
- }
4927
- function daemonStatus() {
4928
- const state = readDaemonStateFile();
4929
- if (!state) {
4930
- const plistPath = join$1(os.homedir(), "Library", "LaunchAgents", "io.hypha.svamp.daemon.plist");
4931
- if (existsSync$1(plistPath)) {
4932
- console.log("Status: Not running (launchd service installed \u2014 may be starting)");
4933
- } else {
4934
- console.log("Status: Not running");
4935
- }
4936
- return;
4937
- }
4938
- const alive = isDaemonAlive();
4939
- console.log(`Status: ${alive ? "Running" : "Dead (stale state)"}`);
4940
- console.log(` PID: ${state.pid}`);
4941
- console.log(` Started: ${state.startTime}`);
4942
- console.log(` Version: ${state.version || "unknown"}`);
4943
- console.log(` Hypha server: ${state.hyphaServerUrl}`);
4944
- if (state.workspace) {
4945
- console.log(` Workspace: ${state.workspace}`);
4946
- }
4947
- if (state.lastHeartbeat) {
4948
- console.log(` Last heartbeat: ${state.lastHeartbeat}`);
4949
- }
4950
- if (state.supervised) {
4951
- console.log(` Managed by: supervisor (auto-restart on crash enabled)`);
4952
- }
4953
- if (!alive) {
4954
- cleanupDaemonStateFile();
4955
- }
4956
- }
4957
-
4958
- export { DefaultTransport$1 as D, GeminiTransport$1 as G, registerSessionService as a, stopDaemon as b, connectToHypha as c, daemonStatus as d, acpBackend as e, acpAgentConfig as f, getHyphaServerUrl as g, registerMachineService as r, startDaemon as s };