svamp-cli 0.1.2 → 0.1.4

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.
@@ -0,0 +1,2100 @@
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, readdirSync, mkdirSync as mkdirSync$1, unlinkSync } from 'fs';
4
+ import { dirname, join as join$1, resolve, basename } from 'path';
5
+ import { fileURLToPath } from 'url';
6
+ import { spawn } 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 { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
12
+ import { createServer } from 'node:http';
13
+ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
14
+ import { z } from 'zod';
15
+
16
+ let connectToServerFn = null;
17
+ async function getConnectToServer() {
18
+ if (!connectToServerFn) {
19
+ const mod = await import('hypha-rpc');
20
+ connectToServerFn = mod.connectToServer || mod.default && mod.default.connectToServer || mod.hyphaWebsocketClient && mod.hyphaWebsocketClient.connectToServer;
21
+ if (!connectToServerFn) {
22
+ throw new Error("Could not find connectToServer in hypha-rpc module");
23
+ }
24
+ }
25
+ return connectToServerFn;
26
+ }
27
+ async function connectToHypha(config) {
28
+ const connectToServer = await getConnectToServer();
29
+ const workspace = config.token ? parseWorkspaceFromToken(config.token) : void 0;
30
+ const server = await connectToServer({
31
+ server_url: config.serverUrl,
32
+ token: config.token,
33
+ client_id: config.clientId,
34
+ name: config.name || "svamp-cli",
35
+ workspace
36
+ });
37
+ return server;
38
+ }
39
+ function parseWorkspaceFromToken(token) {
40
+ try {
41
+ const payload = JSON.parse(Buffer.from(token.split(".")[1], "base64").toString());
42
+ const scope = payload.scope || "";
43
+ const match = scope.match(/wid:([^\s]+)/);
44
+ return match ? match[1] : void 0;
45
+ } catch {
46
+ return void 0;
47
+ }
48
+ }
49
+ function getHyphaServerUrl() {
50
+ return process.env.HYPHA_SERVER_URL || "http://localhost:9527";
51
+ }
52
+
53
+ async function registerMachineService(server, machineId, metadata, daemonState, handlers) {
54
+ let currentMetadata = { ...metadata };
55
+ let currentDaemonState = { ...daemonState };
56
+ let metadataVersion = 1;
57
+ let daemonStateVersion = 1;
58
+ const listeners = [];
59
+ const removeListener = (listener, reason) => {
60
+ const idx = listeners.indexOf(listener);
61
+ if (idx >= 0) {
62
+ listeners.splice(idx, 1);
63
+ console.log(`[HYPHA MACHINE] Listener removed (${reason}), remaining: ${listeners.length}`);
64
+ const rintfId = listener._rintf_service_id;
65
+ if (rintfId) {
66
+ server.unregisterService(rintfId).catch(() => {
67
+ });
68
+ }
69
+ }
70
+ };
71
+ const notifyListeners = (update) => {
72
+ for (let i = listeners.length - 1; i >= 0; i--) {
73
+ try {
74
+ const result = listeners[i].onUpdate(update);
75
+ if (result && typeof result.catch === "function") {
76
+ const listener = listeners[i];
77
+ result.catch((err) => {
78
+ console.error(`[HYPHA MACHINE] Async listener error:`, err);
79
+ removeListener(listener, "async error");
80
+ });
81
+ }
82
+ } catch (err) {
83
+ console.error(`[HYPHA MACHINE] Listener error:`, err);
84
+ removeListener(listeners[i], "sync error");
85
+ }
86
+ }
87
+ };
88
+ const serviceInfo = await server.registerService(
89
+ {
90
+ id: `svamp-machine-${machineId}`,
91
+ name: `Svamp Machine ${machineId}`,
92
+ type: "svamp-machine",
93
+ config: { visibility: "public" },
94
+ // Machine info
95
+ getMachineInfo: async () => ({
96
+ machineId,
97
+ metadata: currentMetadata,
98
+ metadataVersion,
99
+ daemonState: currentDaemonState,
100
+ daemonStateVersion
101
+ }),
102
+ // Heartbeat
103
+ heartbeat: async () => ({
104
+ time: Date.now(),
105
+ status: currentDaemonState.status,
106
+ machineId
107
+ }),
108
+ // List active sessions on this machine
109
+ listSessions: async () => {
110
+ return handlers.getTrackedSessions();
111
+ },
112
+ // Spawn a new session
113
+ spawnSession: async (options) => {
114
+ return await handlers.spawnSession({
115
+ ...options,
116
+ machineId
117
+ });
118
+ },
119
+ // Stop a session
120
+ stopSession: async (sessionId) => {
121
+ return handlers.stopSession(sessionId);
122
+ },
123
+ // Stop the daemon
124
+ stopDaemon: async () => {
125
+ handlers.requestShutdown();
126
+ return { success: true };
127
+ },
128
+ // Metadata management (with optimistic concurrency)
129
+ getMetadata: async () => ({
130
+ metadata: currentMetadata,
131
+ version: metadataVersion
132
+ }),
133
+ updateMetadata: async (newMetadata, expectedVersion) => {
134
+ if (expectedVersion !== metadataVersion) {
135
+ return {
136
+ result: "version-mismatch",
137
+ version: metadataVersion,
138
+ metadata: currentMetadata
139
+ };
140
+ }
141
+ currentMetadata = newMetadata;
142
+ metadataVersion++;
143
+ notifyListeners({
144
+ type: "update-machine",
145
+ machineId,
146
+ metadata: { value: currentMetadata, version: metadataVersion }
147
+ });
148
+ return {
149
+ result: "success",
150
+ version: metadataVersion,
151
+ metadata: currentMetadata
152
+ };
153
+ },
154
+ // Daemon state management
155
+ getDaemonState: async () => ({
156
+ daemonState: currentDaemonState,
157
+ version: daemonStateVersion
158
+ }),
159
+ updateDaemonState: async (newState, expectedVersion) => {
160
+ if (expectedVersion !== daemonStateVersion) {
161
+ return {
162
+ result: "version-mismatch",
163
+ version: daemonStateVersion,
164
+ daemonState: currentDaemonState
165
+ };
166
+ }
167
+ currentDaemonState = newState;
168
+ daemonStateVersion++;
169
+ notifyListeners({
170
+ type: "update-machine",
171
+ machineId,
172
+ daemonState: { value: currentDaemonState, version: daemonStateVersion }
173
+ });
174
+ return {
175
+ result: "success",
176
+ version: daemonStateVersion,
177
+ daemonState: currentDaemonState
178
+ };
179
+ },
180
+ // Register a listener for real-time updates (app calls this with _rintf callback)
181
+ registerListener: async (callback) => {
182
+ listeners.push(callback);
183
+ console.log(`[HYPHA MACHINE] Listener registered (total: ${listeners.length})`);
184
+ return { success: true, listenerId: listeners.length - 1 };
185
+ },
186
+ // Shell access
187
+ bash: async (command, cwd) => {
188
+ const { exec } = await import('child_process');
189
+ const { homedir } = await import('os');
190
+ return new Promise((resolve) => {
191
+ exec(command, { cwd: cwd || homedir(), timeout: 3e4, maxBuffer: 1024 * 1024 }, (err, stdout, stderr) => {
192
+ if (err) {
193
+ resolve({ success: false, stdout: stdout || "", stderr: stderr || err.message, exitCode: err.code ?? 1 });
194
+ } else {
195
+ resolve({ success: true, stdout, stderr: stderr || "", exitCode: 0 });
196
+ }
197
+ });
198
+ });
199
+ },
200
+ // WISE voice — create ephemeral token for OpenAI Realtime API
201
+ wiseCreateEphemeralToken: async (params) => {
202
+ const apiKey = params.apiKey || process.env.OPENAI_API_KEY;
203
+ if (!apiKey) {
204
+ return { success: false, error: "No OpenAI API key found. Set OPENAI_API_KEY or pass apiKey." };
205
+ }
206
+ try {
207
+ const response = await fetch("https://api.openai.com/v1/realtime/client_secrets", {
208
+ method: "POST",
209
+ headers: {
210
+ "Authorization": `Bearer ${apiKey}`,
211
+ "Content-Type": "application/json"
212
+ },
213
+ body: JSON.stringify({
214
+ session: {
215
+ type: "realtime",
216
+ model: params.model || "gpt-realtime-mini"
217
+ }
218
+ })
219
+ });
220
+ if (!response.ok) {
221
+ return { success: false, error: `OpenAI API error: ${response.status}` };
222
+ }
223
+ const result = await response.json();
224
+ return { success: true, clientSecret: result.value };
225
+ } catch (error) {
226
+ return { success: false, error: error instanceof Error ? error.message : "Failed to create token" };
227
+ }
228
+ }
229
+ },
230
+ { overwrite: true }
231
+ );
232
+ console.log(`[HYPHA MACHINE] Machine service registered: ${serviceInfo.id}`);
233
+ return {
234
+ serviceInfo,
235
+ updateMetadata: (newMetadata) => {
236
+ currentMetadata = newMetadata;
237
+ metadataVersion++;
238
+ notifyListeners({
239
+ type: "update-machine",
240
+ machineId,
241
+ metadata: { value: currentMetadata, version: metadataVersion }
242
+ });
243
+ },
244
+ updateDaemonState: (newState) => {
245
+ currentDaemonState = newState;
246
+ daemonStateVersion++;
247
+ notifyListeners({
248
+ type: "update-machine",
249
+ machineId,
250
+ daemonState: { value: currentDaemonState, version: daemonStateVersion }
251
+ });
252
+ },
253
+ disconnect: async () => {
254
+ await server.unregisterService(serviceInfo.id);
255
+ }
256
+ };
257
+ }
258
+
259
+ function loadMessages(messagesDir, sessionId) {
260
+ const filePath = join(messagesDir, `${sessionId}.messages.jsonl`);
261
+ if (!existsSync(filePath)) return [];
262
+ try {
263
+ const lines = readFileSync(filePath, "utf-8").split("\n").filter((l) => l.trim());
264
+ const messages = [];
265
+ for (const line of lines) {
266
+ try {
267
+ messages.push(JSON.parse(line));
268
+ } catch {
269
+ }
270
+ }
271
+ return messages.slice(-5e3);
272
+ } catch {
273
+ return [];
274
+ }
275
+ }
276
+ function appendMessage(messagesDir, sessionId, msg) {
277
+ const filePath = join(messagesDir, `${sessionId}.messages.jsonl`);
278
+ if (!existsSync(messagesDir)) {
279
+ mkdirSync(messagesDir, { recursive: true });
280
+ }
281
+ appendFileSync(filePath, JSON.stringify(msg) + "\n");
282
+ }
283
+ async function registerSessionService(server, sessionId, initialMetadata, initialAgentState, callbacks, options) {
284
+ const messages = options?.messagesDir ? loadMessages(options.messagesDir, sessionId) : [];
285
+ let nextSeq = messages.length > 0 ? messages[messages.length - 1].seq + 1 : 1;
286
+ let metadata = { ...initialMetadata };
287
+ let metadataVersion = 1;
288
+ let agentState = initialAgentState ? { ...initialAgentState } : null;
289
+ let agentStateVersion = 1;
290
+ let lastActivity = {
291
+ active: false,
292
+ thinking: false,
293
+ mode: "remote",
294
+ time: Date.now()
295
+ };
296
+ const listeners = [];
297
+ const removeListener = (listener, reason) => {
298
+ const idx = listeners.indexOf(listener);
299
+ if (idx >= 0) {
300
+ listeners.splice(idx, 1);
301
+ console.log(`[HYPHA SESSION ${sessionId}] Listener removed (${reason}), remaining: ${listeners.length}`);
302
+ const rintfId = listener._rintf_service_id;
303
+ if (rintfId) {
304
+ server.unregisterService(rintfId).catch(() => {
305
+ });
306
+ }
307
+ }
308
+ };
309
+ const notifyListeners = (update) => {
310
+ for (let i = listeners.length - 1; i >= 0; i--) {
311
+ try {
312
+ const result = listeners[i].onUpdate(update);
313
+ if (result && typeof result.catch === "function") {
314
+ const listener = listeners[i];
315
+ result.catch((err) => {
316
+ console.error(`[HYPHA SESSION ${sessionId}] Async listener error:`, err);
317
+ removeListener(listener, "async error");
318
+ });
319
+ }
320
+ } catch (err) {
321
+ console.error(`[HYPHA SESSION ${sessionId}] Listener error:`, err);
322
+ removeListener(listeners[i], "sync error");
323
+ }
324
+ }
325
+ };
326
+ const pushMessage = (content, role = "agent") => {
327
+ let wrappedContent;
328
+ if (role === "agent") {
329
+ const data = { ...content };
330
+ if ((data.type === "assistant" || data.type === "user") && !data.uuid) {
331
+ data.uuid = randomUUID();
332
+ }
333
+ wrappedContent = { role: "agent", content: { type: "output", data } };
334
+ } else if (role === "session") {
335
+ wrappedContent = { role: "session", content: { type: "session", data: content } };
336
+ } else {
337
+ const text = typeof content === "string" ? content : content?.text || content?.content || JSON.stringify(content);
338
+ wrappedContent = { role: "user", content: { type: "text", text } };
339
+ }
340
+ const msg = {
341
+ id: randomUUID(),
342
+ seq: nextSeq++,
343
+ content: wrappedContent,
344
+ localId: null,
345
+ createdAt: Date.now(),
346
+ updatedAt: Date.now()
347
+ };
348
+ messages.push(msg);
349
+ if (options?.messagesDir) {
350
+ appendMessage(options.messagesDir, sessionId, msg);
351
+ }
352
+ notifyListeners({
353
+ type: "new-message",
354
+ sessionId,
355
+ message: msg
356
+ });
357
+ return msg;
358
+ };
359
+ const serviceInfo = await server.registerService(
360
+ {
361
+ id: `svamp-session-${sessionId}`,
362
+ name: `Svamp Session ${sessionId.slice(0, 8)}`,
363
+ type: "svamp-session",
364
+ config: { visibility: "public" },
365
+ // ── Messages ──
366
+ getMessages: async (afterSeq, limit) => {
367
+ const after = afterSeq ?? 0;
368
+ const lim = Math.min(limit ?? 100, 500);
369
+ const filtered = messages.filter((m) => m.seq > after);
370
+ const page = filtered.slice(0, lim);
371
+ return {
372
+ messages: page,
373
+ hasMore: filtered.length > lim
374
+ };
375
+ },
376
+ sendMessage: async (content, localId, meta) => {
377
+ if (localId) {
378
+ const existing = messages.find((m) => m.localId === localId);
379
+ if (existing) {
380
+ return { id: existing.id, seq: existing.seq, localId: existing.localId };
381
+ }
382
+ }
383
+ let parsed = content;
384
+ if (typeof parsed === "string") {
385
+ try {
386
+ parsed = JSON.parse(parsed);
387
+ } catch {
388
+ }
389
+ }
390
+ if (parsed && typeof parsed.content === "string" && !parsed.role) {
391
+ try {
392
+ const inner = JSON.parse(parsed.content);
393
+ if (inner && typeof inner === "object") parsed = inner;
394
+ } catch {
395
+ }
396
+ }
397
+ const wrappedContent = parsed && parsed.role === "user" ? { role: "user", content: parsed.content } : { role: "user", content: { type: "text", text: typeof parsed === "string" ? parsed : JSON.stringify(parsed) } };
398
+ const msg = {
399
+ id: randomUUID(),
400
+ seq: nextSeq++,
401
+ content: wrappedContent,
402
+ localId: localId || randomUUID(),
403
+ createdAt: Date.now(),
404
+ updatedAt: Date.now()
405
+ };
406
+ messages.push(msg);
407
+ if (options?.messagesDir) {
408
+ appendMessage(options.messagesDir, sessionId, msg);
409
+ }
410
+ notifyListeners({
411
+ type: "new-message",
412
+ sessionId,
413
+ message: msg
414
+ });
415
+ callbacks.onUserMessage(content, meta);
416
+ return { id: msg.id, seq: msg.seq, localId: msg.localId };
417
+ },
418
+ // ── Metadata ──
419
+ getMetadata: async () => ({
420
+ metadata,
421
+ version: metadataVersion
422
+ }),
423
+ updateMetadata: async (newMetadata, expectedVersion) => {
424
+ if (expectedVersion !== void 0 && expectedVersion !== metadataVersion) {
425
+ return {
426
+ result: "version-mismatch",
427
+ version: metadataVersion,
428
+ metadata
429
+ };
430
+ }
431
+ metadata = newMetadata;
432
+ metadataVersion++;
433
+ notifyListeners({
434
+ type: "update-session",
435
+ sessionId,
436
+ metadata: { value: metadata, version: metadataVersion }
437
+ });
438
+ return {
439
+ result: "success",
440
+ version: metadataVersion,
441
+ metadata
442
+ };
443
+ },
444
+ // ── Agent State ──
445
+ getAgentState: async () => ({
446
+ agentState,
447
+ version: agentStateVersion
448
+ }),
449
+ updateAgentState: async (newState, expectedVersion) => {
450
+ if (expectedVersion !== void 0 && expectedVersion !== agentStateVersion) {
451
+ return {
452
+ result: "version-mismatch",
453
+ version: agentStateVersion,
454
+ agentState
455
+ };
456
+ }
457
+ agentState = newState;
458
+ agentStateVersion++;
459
+ notifyListeners({
460
+ type: "update-session",
461
+ sessionId,
462
+ agentState: { value: agentState, version: agentStateVersion }
463
+ });
464
+ return {
465
+ result: "success",
466
+ version: agentStateVersion,
467
+ agentState
468
+ };
469
+ },
470
+ // ── Session Control RPCs ──
471
+ abort: async () => {
472
+ callbacks.onAbort();
473
+ return { success: true };
474
+ },
475
+ permissionResponse: async (params) => {
476
+ callbacks.onPermissionResponse(params);
477
+ return { success: true };
478
+ },
479
+ switchMode: async (mode) => {
480
+ callbacks.onSwitchMode(mode);
481
+ return { success: true };
482
+ },
483
+ restartClaude: async () => {
484
+ callbacks.onRestartClaude();
485
+ return { success: true };
486
+ },
487
+ killSession: async () => {
488
+ callbacks.onKillSession();
489
+ return { success: true };
490
+ },
491
+ // ── Activity ──
492
+ keepAlive: async (thinking, mode) => {
493
+ lastActivity = { active: true, thinking: thinking || false, mode: mode || "remote", time: Date.now() };
494
+ notifyListeners({
495
+ type: "activity",
496
+ sessionId,
497
+ ...lastActivity
498
+ });
499
+ },
500
+ sessionEnd: async () => {
501
+ lastActivity = { active: false, thinking: false, mode: "remote", time: Date.now() };
502
+ notifyListeners({
503
+ type: "activity",
504
+ sessionId,
505
+ ...lastActivity
506
+ });
507
+ },
508
+ // ── Activity State Query ──
509
+ getActivityState: async () => {
510
+ return { ...lastActivity, sessionId };
511
+ },
512
+ // ── File Operations (optional) ──
513
+ readFile: async (path) => {
514
+ if (!callbacks.onReadFile) throw new Error("readFile not supported");
515
+ return await callbacks.onReadFile(path);
516
+ },
517
+ writeFile: async (path, content) => {
518
+ if (!callbacks.onWriteFile) throw new Error("writeFile not supported");
519
+ await callbacks.onWriteFile(path, content);
520
+ return { success: true };
521
+ },
522
+ listDirectory: async (path) => {
523
+ if (!callbacks.onListDirectory) throw new Error("listDirectory not supported");
524
+ return await callbacks.onListDirectory(path);
525
+ },
526
+ bash: async (command, cwd) => {
527
+ if (!callbacks.onBash) throw new Error("bash not supported");
528
+ return await callbacks.onBash(command, cwd);
529
+ },
530
+ ripgrep: async (args, cwd) => {
531
+ if (!callbacks.onRipgrep) throw new Error("ripgrep not supported");
532
+ return await callbacks.onRipgrep(args, cwd);
533
+ },
534
+ getDirectoryTree: async (path, maxDepth) => {
535
+ if (!callbacks.onGetDirectoryTree) throw new Error("getDirectoryTree not supported");
536
+ return await callbacks.onGetDirectoryTree(path, maxDepth ?? 3);
537
+ },
538
+ // ── Listener Registration ──
539
+ registerListener: async (callback) => {
540
+ listeners.push(callback);
541
+ console.log(`[HYPHA SESSION ${sessionId}] Listener registered (total: ${listeners.length}), replaying ${messages.length} messages`);
542
+ for (const msg of messages) {
543
+ try {
544
+ const result = callback.onUpdate({
545
+ type: "new-message",
546
+ sessionId,
547
+ message: msg
548
+ });
549
+ if (result && typeof result.catch === "function") {
550
+ result.catch((err) => {
551
+ console.error(`[HYPHA SESSION ${sessionId}] Replay listener error:`, err);
552
+ });
553
+ }
554
+ } catch (err) {
555
+ console.error(`[HYPHA SESSION ${sessionId}] Replay listener error:`, err);
556
+ }
557
+ }
558
+ try {
559
+ const result = callback.onUpdate({
560
+ type: "update-session",
561
+ sessionId,
562
+ metadata: { value: metadata, version: metadataVersion },
563
+ agentState: { value: agentState, version: agentStateVersion }
564
+ });
565
+ if (result && typeof result.catch === "function") {
566
+ result.catch(() => {
567
+ });
568
+ }
569
+ } catch {
570
+ }
571
+ try {
572
+ const result = callback.onUpdate({
573
+ type: "activity",
574
+ sessionId,
575
+ ...lastActivity
576
+ });
577
+ if (result && typeof result.catch === "function") {
578
+ result.catch(() => {
579
+ });
580
+ }
581
+ } catch {
582
+ }
583
+ return { success: true, listenerId: listeners.length - 1 };
584
+ }
585
+ },
586
+ { overwrite: true }
587
+ );
588
+ console.log(`[HYPHA SESSION] Session service registered: ${serviceInfo.id}`);
589
+ return {
590
+ serviceInfo,
591
+ pushMessage,
592
+ get _agentState() {
593
+ return agentState;
594
+ },
595
+ updateMetadata: (newMetadata) => {
596
+ metadata = newMetadata;
597
+ metadataVersion++;
598
+ notifyListeners({
599
+ type: "update-session",
600
+ sessionId,
601
+ metadata: { value: metadata, version: metadataVersion }
602
+ });
603
+ },
604
+ updateAgentState: (newAgentState) => {
605
+ agentState = newAgentState;
606
+ agentStateVersion++;
607
+ notifyListeners({
608
+ type: "update-session",
609
+ sessionId,
610
+ agentState: { value: agentState, version: agentStateVersion }
611
+ });
612
+ },
613
+ sendKeepAlive: (thinking, mode) => {
614
+ lastActivity = { active: true, thinking: thinking || false, mode: mode || "remote", time: Date.now() };
615
+ notifyListeners({
616
+ type: "activity",
617
+ sessionId,
618
+ ...lastActivity
619
+ });
620
+ },
621
+ sendSessionEnd: () => {
622
+ lastActivity = { active: false, thinking: false, mode: "remote", time: Date.now() };
623
+ notifyListeners({
624
+ type: "activity",
625
+ sessionId,
626
+ ...lastActivity
627
+ });
628
+ },
629
+ disconnect: async () => {
630
+ await server.unregisterService(serviceInfo.id);
631
+ }
632
+ };
633
+ }
634
+
635
+ async function registerDebugService(server, machineId, deps) {
636
+ const serviceInfo = await server.registerService(
637
+ {
638
+ id: `svamp-debug-${machineId}`,
639
+ name: `Svamp Debug ${machineId.slice(0, 8)}`,
640
+ type: "svamp-debug",
641
+ config: { visibility: "public" },
642
+ healthCheck: async () => ({
643
+ ok: true,
644
+ machineId,
645
+ uptime: process.uptime(),
646
+ timestamp: Date.now()
647
+ }),
648
+ getSessionStates: async () => {
649
+ const sessions = deps.getTrackedSessions();
650
+ const states = [];
651
+ for (const s of sessions) {
652
+ let activityState = null;
653
+ try {
654
+ const svc = deps.getSessionService(s.sessionId);
655
+ if (svc) {
656
+ activityState = await svc.getActivityState?.();
657
+ }
658
+ } catch {
659
+ }
660
+ states.push({
661
+ sessionId: s.sessionId,
662
+ active: s.active,
663
+ pid: s.pid,
664
+ startedBy: s.startedBy,
665
+ directory: s.directory,
666
+ activityState
667
+ });
668
+ }
669
+ return states;
670
+ },
671
+ getMachineInfo: async () => ({
672
+ machineId,
673
+ hostname: (await import('os')).hostname(),
674
+ platform: (await import('os')).platform(),
675
+ uptime: process.uptime(),
676
+ sessions: deps.getTrackedSessions().length
677
+ }),
678
+ // ── Artifact Sync RPCs ──
679
+ getArtifactSyncStatus: async () => {
680
+ const sync = deps.getArtifactSync?.();
681
+ if (!sync) return { error: "Artifact sync not available" };
682
+ return sync.getStatus();
683
+ },
684
+ forceSyncAll: async () => {
685
+ const sync = deps.getArtifactSync?.();
686
+ const sessionsDir = deps.getSessionsDir?.();
687
+ if (!sync || !sessionsDir) return { error: "Artifact sync not available" };
688
+ await sync.syncAll(sessionsDir, machineId);
689
+ return { success: true, status: sync.getStatus() };
690
+ },
691
+ listRemoteSessions: async () => {
692
+ const sync = deps.getArtifactSync?.();
693
+ if (!sync) return [];
694
+ return await sync.listRemoteSessions();
695
+ }
696
+ },
697
+ { overwrite: true }
698
+ );
699
+ return {
700
+ disconnect: async () => {
701
+ await server.unregisterService(serviceInfo.id);
702
+ }
703
+ };
704
+ }
705
+
706
+ const COLLECTION_ALIAS = "svamp-agent-sessions";
707
+ class SessionArtifactSync {
708
+ server;
709
+ artifactManager = null;
710
+ collectionId = null;
711
+ initialized = false;
712
+ syncing = false;
713
+ lastSyncAt = null;
714
+ syncedSessions = /* @__PURE__ */ new Set();
715
+ error = null;
716
+ syncTimers = /* @__PURE__ */ new Map();
717
+ log;
718
+ constructor(server, log) {
719
+ this.server = server;
720
+ this.log = log;
721
+ }
722
+ async init() {
723
+ try {
724
+ this.artifactManager = await this.server.getService("public/artifact-manager");
725
+ if (!this.artifactManager) {
726
+ this.log("[ARTIFACT SYNC] Artifact manager service not available");
727
+ this.error = "Artifact manager not available";
728
+ return;
729
+ }
730
+ await this.ensureCollection();
731
+ this.initialized = true;
732
+ this.log("[ARTIFACT SYNC] Initialized successfully");
733
+ } catch (err) {
734
+ this.error = `Init failed: ${err.message}`;
735
+ this.log(`[ARTIFACT SYNC] Init failed: ${err.message}`);
736
+ }
737
+ }
738
+ async ensureCollection() {
739
+ try {
740
+ const existing = await this.artifactManager.read({
741
+ artifact_id: COLLECTION_ALIAS,
742
+ _rkwargs: true
743
+ });
744
+ this.collectionId = existing.id;
745
+ this.log(`[ARTIFACT SYNC] Found existing collection: ${this.collectionId}`);
746
+ } catch {
747
+ const collection = await this.artifactManager.create({
748
+ alias: COLLECTION_ALIAS,
749
+ type: "collection",
750
+ manifest: {
751
+ name: "Svamp Agent Sessions",
752
+ description: "Cloud-persisted session data for cross-machine continuity"
753
+ },
754
+ _rkwargs: true
755
+ });
756
+ this.collectionId = collection.id;
757
+ await this.artifactManager.commit({
758
+ artifact_id: this.collectionId,
759
+ _rkwargs: true
760
+ });
761
+ this.log(`[ARTIFACT SYNC] Created new collection: ${this.collectionId}`);
762
+ }
763
+ }
764
+ /**
765
+ * Upload a file to an artifact using the presigned URL pattern:
766
+ * 1. put_file() returns a presigned upload URL
767
+ * 2. HTTP PUT the content to that URL
768
+ */
769
+ async uploadFile(artifactId, filePath, content) {
770
+ const putUrl = await this.artifactManager.put_file({
771
+ artifact_id: artifactId,
772
+ file_path: filePath,
773
+ _rkwargs: true
774
+ });
775
+ if (!putUrl || typeof putUrl !== "string") {
776
+ throw new Error(`put_file returned invalid URL for ${filePath}: ${putUrl}`);
777
+ }
778
+ const resp = await fetch(putUrl, {
779
+ method: "PUT",
780
+ body: content,
781
+ headers: { "Content-Type": "application/octet-stream" }
782
+ });
783
+ if (!resp.ok) {
784
+ throw new Error(`Upload failed for ${filePath}: ${resp.status} ${resp.statusText}`);
785
+ }
786
+ }
787
+ /**
788
+ * Download a file from an artifact using the presigned URL pattern:
789
+ * 1. get_file() returns a presigned download URL
790
+ * 2. HTTP GET the content from that URL
791
+ */
792
+ async downloadFile(artifactId, filePath) {
793
+ const getUrl = await this.artifactManager.get_file({
794
+ artifact_id: artifactId,
795
+ file_path: filePath,
796
+ _rkwargs: true
797
+ });
798
+ if (!getUrl || typeof getUrl !== "string") return null;
799
+ const resp = await fetch(getUrl);
800
+ if (!resp.ok) return null;
801
+ return await resp.text();
802
+ }
803
+ /**
804
+ * Sync a session's metadata and messages to the artifact store.
805
+ * Creates the artifact if it doesn't exist, updates if it does.
806
+ */
807
+ async syncSession(sessionId, sessionsDir, metadata, machineId) {
808
+ if (!this.initialized || !this.artifactManager || !this.collectionId) {
809
+ this.log(`[ARTIFACT SYNC] Not initialized, skipping sync for ${sessionId}`);
810
+ return;
811
+ }
812
+ this.syncing = true;
813
+ try {
814
+ const artifactAlias = `session-${sessionId}`;
815
+ const sessionJsonPath = join(sessionsDir, `${sessionId}.json`);
816
+ const messagesPath = join(sessionsDir, `${sessionId}.messages.jsonl`);
817
+ const sessionData = existsSync(sessionJsonPath) ? JSON.parse(readFileSync(sessionJsonPath, "utf-8")) : null;
818
+ const messagesExist = existsSync(messagesPath);
819
+ const messageCount = messagesExist ? readFileSync(messagesPath, "utf-8").split("\n").filter((l) => l.trim()).length : 0;
820
+ let artifactId;
821
+ try {
822
+ const existing = await this.artifactManager.read({
823
+ artifact_id: artifactAlias,
824
+ _rkwargs: true
825
+ });
826
+ artifactId = existing.id;
827
+ await this.artifactManager.edit({
828
+ artifact_id: artifactId,
829
+ manifest: {
830
+ sessionId,
831
+ machineId,
832
+ metadata,
833
+ messageCount,
834
+ lastSyncAt: Date.now(),
835
+ ...sessionData || {}
836
+ },
837
+ _rkwargs: true
838
+ });
839
+ } catch {
840
+ const artifact = await this.artifactManager.create({
841
+ alias: artifactAlias,
842
+ parent_id: this.collectionId,
843
+ type: "session",
844
+ manifest: {
845
+ sessionId,
846
+ machineId,
847
+ metadata,
848
+ messageCount,
849
+ createdAt: Date.now(),
850
+ lastSyncAt: Date.now(),
851
+ ...sessionData || {}
852
+ },
853
+ _rkwargs: true
854
+ });
855
+ artifactId = artifact.id;
856
+ }
857
+ if (sessionData) {
858
+ await this.uploadFile(artifactId, "session.json", JSON.stringify(sessionData, null, 2));
859
+ }
860
+ if (messagesExist) {
861
+ const messagesContent = readFileSync(messagesPath, "utf-8");
862
+ await this.uploadFile(artifactId, "messages.jsonl", messagesContent);
863
+ }
864
+ await this.artifactManager.commit({
865
+ artifact_id: artifactId,
866
+ _rkwargs: true
867
+ });
868
+ this.syncedSessions.add(sessionId);
869
+ this.lastSyncAt = Date.now();
870
+ this.log(`[ARTIFACT SYNC] Synced session ${sessionId} (${messageCount} messages)`);
871
+ } catch (err) {
872
+ this.error = `Sync failed for ${sessionId}: ${err.message}`;
873
+ this.log(`[ARTIFACT SYNC] Sync failed for ${sessionId}: ${err.message}`);
874
+ } finally {
875
+ this.syncing = false;
876
+ }
877
+ }
878
+ /**
879
+ * Schedule a debounced sync for a session (e.g., on each new message).
880
+ * Waits 30 seconds before syncing to batch multiple messages.
881
+ */
882
+ scheduleDebouncedSync(sessionId, sessionsDir, metadata, machineId, delayMs = 3e4) {
883
+ const existing = this.syncTimers.get(sessionId);
884
+ if (existing) clearTimeout(existing);
885
+ const timer = setTimeout(() => {
886
+ this.syncSession(sessionId, sessionsDir, metadata, machineId).catch(() => {
887
+ });
888
+ this.syncTimers.delete(sessionId);
889
+ }, delayMs);
890
+ this.syncTimers.set(sessionId, timer);
891
+ }
892
+ /**
893
+ * Download a session from artifact store to local disk.
894
+ */
895
+ async downloadSession(sessionId, targetDir) {
896
+ if (!this.initialized || !this.artifactManager) return null;
897
+ try {
898
+ const artifactAlias = `session-${sessionId}`;
899
+ const artifact = await this.artifactManager.read({
900
+ artifact_id: artifactAlias,
901
+ _rkwargs: true
902
+ });
903
+ if (!existsSync(targetDir)) mkdirSync(targetDir, { recursive: true });
904
+ try {
905
+ const data = await this.downloadFile(artifact.id, "session.json");
906
+ if (data) {
907
+ writeFileSync(join(targetDir, `${sessionId}.json`), data);
908
+ }
909
+ } catch {
910
+ }
911
+ try {
912
+ const data = await this.downloadFile(artifact.id, "messages.jsonl");
913
+ if (data) {
914
+ writeFileSync(join(targetDir, `${sessionId}.messages.jsonl`), data);
915
+ }
916
+ } catch {
917
+ }
918
+ return {
919
+ sessionData: artifact.manifest,
920
+ messageCount: artifact.manifest?.messageCount || 0
921
+ };
922
+ } catch (err) {
923
+ this.log(`[ARTIFACT SYNC] Download failed for ${sessionId}: ${err.message}`);
924
+ return null;
925
+ }
926
+ }
927
+ /**
928
+ * List all sessions stored in the artifact collection.
929
+ */
930
+ async listRemoteSessions() {
931
+ if (!this.initialized || !this.artifactManager || !this.collectionId) return [];
932
+ try {
933
+ const children = await this.artifactManager.list({
934
+ parent_id: this.collectionId,
935
+ _rkwargs: true
936
+ });
937
+ return (children || []).map((child) => ({
938
+ sessionId: child.manifest?.sessionId || child.alias?.replace("session-", ""),
939
+ machineId: child.manifest?.machineId,
940
+ messageCount: child.manifest?.messageCount || 0,
941
+ lastSyncAt: child.manifest?.lastSyncAt || 0
942
+ }));
943
+ } catch (err) {
944
+ this.log(`[ARTIFACT SYNC] List failed: ${err.message}`);
945
+ return [];
946
+ }
947
+ }
948
+ /**
949
+ * Get current sync status.
950
+ */
951
+ getStatus() {
952
+ return {
953
+ initialized: this.initialized,
954
+ collectionId: this.collectionId,
955
+ lastSyncAt: this.lastSyncAt,
956
+ syncing: this.syncing,
957
+ syncedSessions: [...this.syncedSessions],
958
+ error: this.error
959
+ };
960
+ }
961
+ /**
962
+ * Force sync all known sessions.
963
+ */
964
+ async syncAll(sessionsDir, machineId) {
965
+ if (!this.initialized || !existsSync(sessionsDir)) return;
966
+ const { readdirSync } = await import('node:fs');
967
+ for (const file of readdirSync(sessionsDir)) {
968
+ if (!file.endsWith(".json") || file.includes(".messages.")) continue;
969
+ const sessionId = file.replace(".json", "");
970
+ await this.syncSession(sessionId, sessionsDir, void 0, machineId);
971
+ }
972
+ }
973
+ /**
974
+ * Cleanup timers on shutdown.
975
+ */
976
+ destroy() {
977
+ for (const timer of this.syncTimers.values()) {
978
+ clearTimeout(timer);
979
+ }
980
+ this.syncTimers.clear();
981
+ }
982
+ }
983
+
984
+ async function startSvampServer(ctx) {
985
+ const { sessionService, getMetadata, setMetadata, logger } = ctx;
986
+ logger.log("[svampMCP] Starting MCP server");
987
+ const mcp = new McpServer({
988
+ name: "Svamp MCP",
989
+ version: "1.0.0"
990
+ });
991
+ mcp.registerTool("change_title", {
992
+ description: "Change the title of the current chat session",
993
+ title: "Change Chat Title",
994
+ inputSchema: {
995
+ title: z.string().describe("The new title for the chat session")
996
+ }
997
+ }, async (args) => {
998
+ try {
999
+ setMetadata((m) => ({
1000
+ ...m,
1001
+ summary: { text: args.title, updatedAt: Date.now() }
1002
+ }));
1003
+ sessionService.pushMessage({
1004
+ type: "summary",
1005
+ summary: args.title
1006
+ }, "session");
1007
+ return {
1008
+ content: [{ type: "text", text: `Successfully changed chat title to: "${args.title}"` }],
1009
+ isError: false
1010
+ };
1011
+ } catch (error) {
1012
+ return {
1013
+ content: [{ type: "text", text: `Failed to change chat title: ${String(error)}` }],
1014
+ isError: true
1015
+ };
1016
+ }
1017
+ });
1018
+ mcp.registerTool("set_session_link", {
1019
+ description: "Set a link for the current session. A clickable button with the label will appear next to the session title. Use this after creating a dashboard, report, or any web page the user should access.",
1020
+ title: "Set Session Link",
1021
+ inputSchema: {
1022
+ url: z.string().describe("The URL to display"),
1023
+ label: z.string().optional().describe('Short button label (1-2 chars or up to 2 words). Defaults to "View"')
1024
+ }
1025
+ }, async (args) => {
1026
+ const label = args.label || "View";
1027
+ try {
1028
+ setMetadata((m) => ({
1029
+ ...m,
1030
+ sessionLink: { url: args.url, label, updatedAt: Date.now() }
1031
+ }));
1032
+ const currentSummary = getMetadata().summary?.text;
1033
+ if (currentSummary) {
1034
+ sessionService.pushMessage({
1035
+ type: "summary",
1036
+ summary: currentSummary
1037
+ }, "session");
1038
+ }
1039
+ return {
1040
+ content: [{ type: "text", text: `Session link set: "${label}" \u2192 ${args.url}. A button will appear next to the session title.` }],
1041
+ isError: false
1042
+ };
1043
+ } catch (error) {
1044
+ return {
1045
+ content: [{ type: "text", text: `Failed to set session link: ${String(error)}` }],
1046
+ isError: true
1047
+ };
1048
+ }
1049
+ });
1050
+ const transport = new StreamableHTTPServerTransport({
1051
+ sessionIdGenerator: () => crypto.randomUUID()
1052
+ });
1053
+ await mcp.connect(transport);
1054
+ const server = createServer(async (req, res) => {
1055
+ try {
1056
+ await transport.handleRequest(req, res);
1057
+ } catch (error) {
1058
+ logger.log(`[svampMCP] Error handling request: ${error}`);
1059
+ if (!res.headersSent) {
1060
+ res.writeHead(500).end();
1061
+ }
1062
+ }
1063
+ });
1064
+ const baseUrl = await new Promise((resolve) => {
1065
+ server.listen(0, "127.0.0.1", () => {
1066
+ const addr = server.address();
1067
+ resolve(new URL(`http://127.0.0.1:${addr.port}`));
1068
+ });
1069
+ });
1070
+ logger.log(`[svampMCP] Server ready at ${baseUrl.toString()}`);
1071
+ return {
1072
+ url: baseUrl.toString(),
1073
+ toolNames: ["change_title", "set_session_link"],
1074
+ stop: () => {
1075
+ logger.log("[svampMCP] Stopping server");
1076
+ mcp.close();
1077
+ server.close();
1078
+ }
1079
+ };
1080
+ }
1081
+
1082
+ const __filename$1 = fileURLToPath(import.meta.url);
1083
+ const __dirname$1 = dirname(__filename$1);
1084
+ function loadDotEnv() {
1085
+ const envDir = process.env.SVAMP_HOME || join$1(os.homedir(), ".svamp");
1086
+ const envFile = join$1(envDir, ".env");
1087
+ if (existsSync$1(envFile)) {
1088
+ const lines = readFileSync$1(envFile, "utf-8").split("\n");
1089
+ for (const line of lines) {
1090
+ const trimmed = line.trim();
1091
+ if (!trimmed || trimmed.startsWith("#")) continue;
1092
+ const eqIdx = trimmed.indexOf("=");
1093
+ if (eqIdx === -1) continue;
1094
+ const key = trimmed.slice(0, eqIdx).trim();
1095
+ const value = trimmed.slice(eqIdx + 1).trim().replace(/^["']|["']$/g, "");
1096
+ if (!process.env[key]) {
1097
+ process.env[key] = value;
1098
+ }
1099
+ }
1100
+ }
1101
+ }
1102
+ loadDotEnv();
1103
+ const SVAMP_HOME = process.env.SVAMP_HOME || join$1(os.homedir(), ".svamp");
1104
+ const DAEMON_STATE_FILE = join$1(SVAMP_HOME, "daemon.state.json");
1105
+ const DAEMON_LOCK_FILE = join$1(SVAMP_HOME, "daemon.lock");
1106
+ const LOGS_DIR = join$1(SVAMP_HOME, "logs");
1107
+ const SESSIONS_DIR = join$1(SVAMP_HOME, "sessions");
1108
+ function saveSession(session) {
1109
+ if (!existsSync$1(SESSIONS_DIR)) {
1110
+ mkdirSync$1(SESSIONS_DIR, { recursive: true });
1111
+ }
1112
+ writeFileSync$1(
1113
+ join$1(SESSIONS_DIR, `${session.sessionId}.json`),
1114
+ JSON.stringify(session, null, 2),
1115
+ "utf-8"
1116
+ );
1117
+ }
1118
+ function deletePersistedSession(sessionId) {
1119
+ const sessionFile = join$1(SESSIONS_DIR, `${sessionId}.json`);
1120
+ try {
1121
+ if (existsSync$1(sessionFile)) unlinkSync(sessionFile);
1122
+ } catch {
1123
+ }
1124
+ const messagesFile = join$1(SESSIONS_DIR, `${sessionId}.messages.jsonl`);
1125
+ try {
1126
+ if (existsSync$1(messagesFile)) unlinkSync(messagesFile);
1127
+ } catch {
1128
+ }
1129
+ }
1130
+ function loadPersistedSessions() {
1131
+ if (!existsSync$1(SESSIONS_DIR)) return [];
1132
+ const sessions = [];
1133
+ for (const file of readdirSync(SESSIONS_DIR)) {
1134
+ if (!file.endsWith(".json")) continue;
1135
+ try {
1136
+ const data = JSON.parse(readFileSync$1(join$1(SESSIONS_DIR, file), "utf-8"));
1137
+ if (data.sessionId && data.directory) {
1138
+ sessions.push(data);
1139
+ }
1140
+ } catch {
1141
+ }
1142
+ }
1143
+ return sessions;
1144
+ }
1145
+ function ensureHomeDir() {
1146
+ if (!existsSync$1(SVAMP_HOME)) {
1147
+ mkdirSync$1(SVAMP_HOME, { recursive: true });
1148
+ }
1149
+ if (!existsSync$1(LOGS_DIR)) {
1150
+ mkdirSync$1(LOGS_DIR, { recursive: true });
1151
+ }
1152
+ if (!existsSync$1(SESSIONS_DIR)) {
1153
+ mkdirSync$1(SESSIONS_DIR, { recursive: true });
1154
+ }
1155
+ }
1156
+ function createLogger() {
1157
+ ensureHomeDir();
1158
+ const logFile = join$1(LOGS_DIR, `daemon-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.log`);
1159
+ return {
1160
+ logFilePath: logFile,
1161
+ log: (...args) => {
1162
+ const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${args.map((a) => typeof a === "string" ? a : JSON.stringify(a)).join(" ")}
1163
+ `;
1164
+ fs.appendFile(logFile, line).catch(() => {
1165
+ });
1166
+ if (process.env.DEBUG) {
1167
+ console.log(...args);
1168
+ }
1169
+ },
1170
+ error: (...args) => {
1171
+ const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] ERROR: ${args.map((a) => typeof a === "string" ? a : JSON.stringify(a)).join(" ")}
1172
+ `;
1173
+ fs.appendFile(logFile, line).catch(() => {
1174
+ });
1175
+ console.error(...args);
1176
+ }
1177
+ };
1178
+ }
1179
+ function writeDaemonStateFile(state) {
1180
+ ensureHomeDir();
1181
+ writeFileSync$1(DAEMON_STATE_FILE, JSON.stringify(state, null, 2), "utf-8");
1182
+ }
1183
+ function readDaemonStateFile() {
1184
+ try {
1185
+ if (!existsSync$1(DAEMON_STATE_FILE)) return null;
1186
+ return JSON.parse(readFileSync$1(DAEMON_STATE_FILE, "utf-8"));
1187
+ } catch {
1188
+ return null;
1189
+ }
1190
+ }
1191
+ function cleanupDaemonStateFile() {
1192
+ try {
1193
+ if (existsSync$1(DAEMON_STATE_FILE)) {
1194
+ fs.unlink(DAEMON_STATE_FILE).catch(() => {
1195
+ });
1196
+ }
1197
+ if (existsSync$1(DAEMON_LOCK_FILE)) {
1198
+ fs.unlink(DAEMON_LOCK_FILE).catch(() => {
1199
+ });
1200
+ }
1201
+ } catch {
1202
+ }
1203
+ }
1204
+ function isDaemonAlive() {
1205
+ const state = readDaemonStateFile();
1206
+ if (!state) return false;
1207
+ try {
1208
+ process.kill(state.pid, 0);
1209
+ return true;
1210
+ } catch {
1211
+ return false;
1212
+ }
1213
+ }
1214
+ async function startDaemon() {
1215
+ const logger = createLogger();
1216
+ let requestShutdown;
1217
+ const resolvesWhenShutdownRequested = new Promise((resolve2) => {
1218
+ requestShutdown = (source, errorMessage) => {
1219
+ logger.log(`Requesting shutdown (source: ${source}, errorMessage: ${errorMessage})`);
1220
+ setTimeout(() => {
1221
+ logger.log("Forced exit after timeout");
1222
+ process.exit(1);
1223
+ }, 5e3);
1224
+ resolve2({ source, errorMessage });
1225
+ };
1226
+ });
1227
+ process.on("SIGINT", () => requestShutdown("os-signal"));
1228
+ process.on("SIGTERM", () => requestShutdown("os-signal"));
1229
+ process.on("uncaughtException", (error) => {
1230
+ logger.error("Uncaught exception:", error);
1231
+ requestShutdown("exception", error.message);
1232
+ });
1233
+ process.on("unhandledRejection", (reason) => {
1234
+ const msg = String(reason);
1235
+ logger.error("Unhandled rejection:", reason);
1236
+ if (msg.includes("_rintf") || msg.includes("Method call timed out")) {
1237
+ logger.log("Ignoring _rintf callback timeout (app likely disconnected)");
1238
+ return;
1239
+ }
1240
+ requestShutdown("exception", msg);
1241
+ });
1242
+ if (isDaemonAlive()) {
1243
+ console.log("Svamp daemon is already running");
1244
+ process.exit(0);
1245
+ }
1246
+ const hyphaServerUrl = process.env.HYPHA_SERVER_URL;
1247
+ if (!hyphaServerUrl) {
1248
+ console.error("HYPHA_SERVER_URL is required.");
1249
+ console.error('Run "svamp login <server-url>" first, or set it in .env or environment.');
1250
+ process.exit(1);
1251
+ }
1252
+ const hyphaToken = process.env.HYPHA_TOKEN;
1253
+ const hyphaWorkspace = process.env.HYPHA_WORKSPACE;
1254
+ if (!hyphaToken) {
1255
+ logger.log('Warning: No HYPHA_TOKEN set. Run "svamp login" to authenticate.');
1256
+ logger.log("Connecting anonymously...");
1257
+ }
1258
+ const machineId = process.env.SVAMP_MACHINE_ID || `machine-${os.hostname()}-${randomUUID$1().slice(0, 8)}`;
1259
+ logger.log("Starting svamp daemon...");
1260
+ logger.log(` Server: ${hyphaServerUrl}`);
1261
+ logger.log(` Workspace: ${hyphaWorkspace || "(default)"}`);
1262
+ logger.log(` Machine ID: ${machineId}`);
1263
+ let server = null;
1264
+ try {
1265
+ logger.log("Connecting to Hypha server...");
1266
+ server = await connectToHypha({
1267
+ serverUrl: hyphaServerUrl,
1268
+ token: hyphaToken,
1269
+ name: `svamp-machine-${machineId}`
1270
+ });
1271
+ logger.log(`Connected to Hypha (workspace: ${server.config.workspace})`);
1272
+ const pidToTrackedSession = /* @__PURE__ */ new Map();
1273
+ const getCurrentChildren = () => {
1274
+ return Array.from(pidToTrackedSession.values()).map((s) => ({
1275
+ sessionId: s.svampSessionId || `PID-${s.pid}`,
1276
+ pid: s.pid,
1277
+ startedBy: s.startedBy,
1278
+ directory: s.directory,
1279
+ active: !s.stopped && s.hyphaService != null
1280
+ }));
1281
+ };
1282
+ const spawnSession = async (options) => {
1283
+ logger.log("Spawning session:", JSON.stringify(options));
1284
+ const { directory, approvedNewDirectoryCreation = true, resumeSessionId } = options;
1285
+ try {
1286
+ await fs.access(directory);
1287
+ } catch {
1288
+ if (!approvedNewDirectoryCreation) {
1289
+ return { type: "requestToApproveDirectoryCreation", directory };
1290
+ }
1291
+ try {
1292
+ await fs.mkdir(directory, { recursive: true });
1293
+ } catch (err) {
1294
+ return { type: "error", errorMessage: `Failed to create directory: ${err.message}` };
1295
+ }
1296
+ }
1297
+ const sessionId = options.sessionId || randomUUID$1();
1298
+ try {
1299
+ let parseBashPermission2 = function(permission) {
1300
+ if (permission === "Bash") return;
1301
+ const match = permission.match(/^Bash\((.+?)\)$/);
1302
+ if (!match) return;
1303
+ const command = match[1];
1304
+ if (command.endsWith(":*")) {
1305
+ allowedBashPrefixes.add(command.slice(0, -2));
1306
+ } else {
1307
+ allowedBashLiterals.add(command);
1308
+ }
1309
+ }, shouldAutoAllow2 = function(toolName, toolInput) {
1310
+ if (toolName === "Bash") {
1311
+ const inputObj = toolInput;
1312
+ if (inputObj?.command) {
1313
+ if (allowedBashLiterals.has(inputObj.command)) return true;
1314
+ for (const prefix of allowedBashPrefixes) {
1315
+ if (inputObj.command.startsWith(prefix)) return true;
1316
+ }
1317
+ }
1318
+ } else if (allowedTools.has(toolName)) {
1319
+ return true;
1320
+ }
1321
+ if (currentPermissionMode === "bypassPermissions") return true;
1322
+ if (currentPermissionMode === "acceptEdits" && EDIT_TOOLS.has(toolName)) return true;
1323
+ return false;
1324
+ };
1325
+ var parseBashPermission = parseBashPermission2, shouldAutoAllow = shouldAutoAllow2;
1326
+ let sessionMetadata = {
1327
+ path: directory,
1328
+ host: os.hostname(),
1329
+ version: "0.1.0",
1330
+ machineId,
1331
+ homeDir: os.homedir(),
1332
+ svampHomeDir: SVAMP_HOME,
1333
+ svampLibDir: join$1(__dirname$1, ".."),
1334
+ svampToolsDir: join$1(__dirname$1, "..", "tools"),
1335
+ startedFromDaemon: true,
1336
+ startedBy: "daemon",
1337
+ lifecycleState: resumeSessionId ? "idle" : "starting"
1338
+ };
1339
+ let claudeProcess = null;
1340
+ const persisted = loadPersistedSessions().find((p) => p.sessionId === sessionId);
1341
+ let claudeResumeId = persisted?.claudeResumeId || (resumeSessionId || void 0);
1342
+ let currentPermissionMode = persisted?.permissionMode || "default";
1343
+ const allowedTools = /* @__PURE__ */ new Set();
1344
+ const allowedBashLiterals = /* @__PURE__ */ new Set();
1345
+ const allowedBashPrefixes = /* @__PURE__ */ new Set();
1346
+ const EDIT_TOOLS = /* @__PURE__ */ new Set(["Edit", "MultiEdit", "Write", "NotebookEdit"]);
1347
+ const pendingPermissions = /* @__PURE__ */ new Map();
1348
+ let backgroundTaskCount = 0;
1349
+ let backgroundTaskNames = [];
1350
+ let userMessagePending = false;
1351
+ let turnInitiatedByUser = true;
1352
+ const spawnClaude = (initialMessage, meta) => {
1353
+ const permissionMode = meta?.permissionMode || currentPermissionMode;
1354
+ currentPermissionMode = permissionMode;
1355
+ const model = meta?.model || void 0;
1356
+ const appendSystemPrompt = meta?.appendSystemPrompt || void 0;
1357
+ const mcpConfigPath = join$1(SVAMP_HOME, "logs", `mcp-config-${sessionId}.json`);
1358
+ writeFileSync$1(mcpConfigPath, JSON.stringify({
1359
+ mcpServers: {
1360
+ svamp: { type: "http", url: svampServer.url }
1361
+ }
1362
+ }));
1363
+ const args = [
1364
+ "--output-format",
1365
+ "stream-json",
1366
+ "--input-format",
1367
+ "stream-json",
1368
+ "--verbose",
1369
+ "--permission-prompt-tool",
1370
+ "stdio",
1371
+ "--permission-mode",
1372
+ permissionMode,
1373
+ "--mcp-config",
1374
+ mcpConfigPath,
1375
+ "--allowedTools",
1376
+ svampServer.toolNames.map((t) => `mcp__svamp__${t}`).join(",")
1377
+ ];
1378
+ if (model) args.push("--model", model);
1379
+ if (appendSystemPrompt) args.push("--append-system-prompt", appendSystemPrompt);
1380
+ if (claudeResumeId) args.push("--resume", claudeResumeId);
1381
+ logger.log(`[Session ${sessionId}] Spawning Claude: claude ${args.join(" ")} (cwd: ${directory})`);
1382
+ const spawnEnv = { ...process.env };
1383
+ delete spawnEnv.CLAUDECODE;
1384
+ const child = spawn("claude", args, {
1385
+ cwd: directory,
1386
+ stdio: ["pipe", "pipe", "pipe"],
1387
+ env: spawnEnv,
1388
+ shell: process.platform === "win32"
1389
+ });
1390
+ claudeProcess = child;
1391
+ logger.log(`[Session ${sessionId}] Claude PID: ${child.pid}, stdin: ${!!child.stdin}, stdout: ${!!child.stdout}, stderr: ${!!child.stderr}`);
1392
+ child.on("error", (err) => {
1393
+ logger.log(`[Session ${sessionId}] Claude process error: ${err.message}`);
1394
+ sessionService.pushMessage({
1395
+ type: "assistant",
1396
+ content: [{
1397
+ type: "text",
1398
+ text: `Error: Failed to start Claude Code CLI: ${err.message}
1399
+
1400
+ Please ensure Claude Code CLI is installed on this machine. You can install it with:
1401
+ \`npm install -g @anthropic-ai/claude-code\``
1402
+ }]
1403
+ }, "agent");
1404
+ sessionService.sendKeepAlive(false);
1405
+ });
1406
+ let stdoutBuffer = "";
1407
+ child.stdout?.on("data", (chunk) => {
1408
+ stdoutBuffer += chunk.toString();
1409
+ const lines = stdoutBuffer.split("\n");
1410
+ stdoutBuffer = lines.pop() || "";
1411
+ for (const line of lines) {
1412
+ if (!line.trim()) continue;
1413
+ logger.log(`[Session ${sessionId}] stdout line (${line.length} chars): ${line.slice(0, 100)}`);
1414
+ try {
1415
+ const msg = JSON.parse(line);
1416
+ logger.log(`[Session ${sessionId}] Parsed type=${msg.type} subtype=${msg.subtype || "n/a"}`);
1417
+ if (msg.type === "control_request" && msg.request?.subtype === "can_use_tool") {
1418
+ const requestId = msg.request_id;
1419
+ const toolName = msg.request.tool_name;
1420
+ const toolInput = msg.request.input;
1421
+ logger.log(`[Session ${sessionId}] Permission request: ${requestId} tool=${toolName}`);
1422
+ if (shouldAutoAllow2(toolName, toolInput)) {
1423
+ logger.log(`[Session ${sessionId}] Auto-allowing ${toolName} (mode=${currentPermissionMode})`);
1424
+ if (claudeProcess && !claudeProcess.killed && claudeProcess.stdin) {
1425
+ const controlResponse = JSON.stringify({
1426
+ type: "control_response",
1427
+ response: {
1428
+ subtype: "success",
1429
+ request_id: requestId,
1430
+ response: { behavior: "allow", updatedInput: toolInput || {} }
1431
+ }
1432
+ });
1433
+ claudeProcess.stdin.write(controlResponse + "\n");
1434
+ }
1435
+ continue;
1436
+ }
1437
+ const permissionPromise = new Promise((resolve2) => {
1438
+ pendingPermissions.set(requestId, { resolve: resolve2, toolName, input: toolInput });
1439
+ });
1440
+ const currentRequests = { ...sessionService._agentState?.requests };
1441
+ sessionService.updateAgentState({
1442
+ controlledByUser: false,
1443
+ requests: {
1444
+ ...currentRequests,
1445
+ [requestId]: {
1446
+ tool: toolName,
1447
+ arguments: toolInput,
1448
+ createdAt: Date.now()
1449
+ }
1450
+ }
1451
+ });
1452
+ permissionPromise.then((result) => {
1453
+ if (claudeProcess && !claudeProcess.killed && claudeProcess.stdin) {
1454
+ const controlResponse = JSON.stringify({
1455
+ type: "control_response",
1456
+ response: {
1457
+ subtype: "success",
1458
+ request_id: requestId,
1459
+ response: result
1460
+ }
1461
+ });
1462
+ logger.log(`[Session ${sessionId}] Sending control_response: ${controlResponse.slice(0, 200)}`);
1463
+ claudeProcess.stdin.write(controlResponse + "\n");
1464
+ }
1465
+ const reqs = { ...sessionService._agentState?.requests };
1466
+ delete reqs[requestId];
1467
+ sessionService.updateAgentState({
1468
+ controlledByUser: false,
1469
+ requests: reqs,
1470
+ completedRequests: {
1471
+ ...sessionService._agentState?.completedRequests,
1472
+ [requestId]: {
1473
+ tool: toolName,
1474
+ arguments: toolInput,
1475
+ completedAt: Date.now(),
1476
+ status: result.behavior === "allow" ? "approved" : "denied"
1477
+ }
1478
+ }
1479
+ });
1480
+ });
1481
+ } else if (msg.type === "control_cancel_request") {
1482
+ const requestId = msg.request_id;
1483
+ logger.log(`[Session ${sessionId}] Permission cancel: ${requestId}`);
1484
+ const pending = pendingPermissions.get(requestId);
1485
+ if (pending) {
1486
+ pending.resolve({ behavior: "deny", message: "Cancelled" });
1487
+ pendingPermissions.delete(requestId);
1488
+ }
1489
+ } else if (msg.type === "control_response") {
1490
+ logger.log(`[Session ${sessionId}] Control response: ${JSON.stringify(msg).slice(0, 200)}`);
1491
+ } else if (msg.type === "assistant" || msg.type === "result") {
1492
+ if (msg.type === "assistant" && Array.isArray(msg.content)) {
1493
+ for (const block of msg.content) {
1494
+ if (block.type === "tool_use" && block.input?.run_in_background === true) {
1495
+ backgroundTaskCount++;
1496
+ const label = block.tool_name || block.name || "unknown";
1497
+ backgroundTaskNames.push(label);
1498
+ logger.log(`[Session ${sessionId}] Background task launched: ${label} (count=${backgroundTaskCount})`);
1499
+ }
1500
+ }
1501
+ }
1502
+ if (msg.type === "result") {
1503
+ if (!turnInitiatedByUser) {
1504
+ logger.log(`[Session ${sessionId}] Skipping stale result from SDK-initiated turn`);
1505
+ const hasBackgroundTasks = backgroundTaskCount > 0;
1506
+ if (hasBackgroundTasks) {
1507
+ const taskInfo = `Background tasks still running (${backgroundTaskCount}): ${backgroundTaskNames.join(", ")}`;
1508
+ sessionService.pushMessage({ type: "session_event", message: taskInfo }, "session");
1509
+ }
1510
+ sessionService.sendKeepAlive(false);
1511
+ turnInitiatedByUser = true;
1512
+ continue;
1513
+ }
1514
+ sessionService.sendKeepAlive(false);
1515
+ if (backgroundTaskCount > 0) {
1516
+ const taskInfo = `Background tasks still running (${backgroundTaskCount}): ${backgroundTaskNames.join(", ")}`;
1517
+ logger.log(`[Session ${sessionId}] ${taskInfo}`);
1518
+ sessionService.pushMessage({ type: "session_event", message: taskInfo }, "session");
1519
+ }
1520
+ }
1521
+ sessionService.pushMessage(msg, "agent");
1522
+ if (msg.session_id) {
1523
+ claudeResumeId = msg.session_id;
1524
+ }
1525
+ } else if (msg.type === "system" && msg.subtype === "init") {
1526
+ if (!userMessagePending) {
1527
+ turnInitiatedByUser = false;
1528
+ logger.log(`[Session ${sessionId}] SDK-initiated turn (likely stale task_notification)`);
1529
+ }
1530
+ userMessagePending = false;
1531
+ if (msg.session_id) {
1532
+ claudeResumeId = msg.session_id;
1533
+ sessionService.updateMetadata({
1534
+ ...sessionMetadata,
1535
+ claudeSessionId: msg.session_id
1536
+ });
1537
+ saveSession({
1538
+ sessionId,
1539
+ directory,
1540
+ claudeResumeId,
1541
+ permissionMode: currentPermissionMode,
1542
+ metadata: sessionMetadata,
1543
+ createdAt: Date.now(),
1544
+ machineId
1545
+ });
1546
+ artifactSync.scheduleDebouncedSync(sessionId, SESSIONS_DIR, sessionMetadata, machineId);
1547
+ }
1548
+ sessionService.pushMessage(msg, "session");
1549
+ } else if (msg.type === "system" && msg.subtype === "task_notification" && msg.status === "completed") {
1550
+ backgroundTaskCount = Math.max(0, backgroundTaskCount - 1);
1551
+ if (backgroundTaskNames.length > 0) {
1552
+ const completed = backgroundTaskNames.shift();
1553
+ logger.log(`[Session ${sessionId}] Background task completed: ${completed} (remaining=${backgroundTaskCount})`);
1554
+ }
1555
+ sessionService.pushMessage(msg, "agent");
1556
+ } else {
1557
+ sessionService.pushMessage(msg, "agent");
1558
+ }
1559
+ } catch {
1560
+ logger.log(`[Session ${sessionId}] Claude stdout (non-JSON): ${line}`);
1561
+ }
1562
+ }
1563
+ });
1564
+ child.stderr?.on("data", (chunk) => {
1565
+ logger.log(`[Session ${sessionId}] Claude stderr: ${chunk.toString().trim()}`);
1566
+ });
1567
+ child.on("exit", (code, signal) => {
1568
+ logger.log(`[Session ${sessionId}] Claude exited: code=${code}, signal=${signal}`);
1569
+ claudeProcess = null;
1570
+ for (const [id, pending] of pendingPermissions) {
1571
+ pending.resolve({ behavior: "deny", message: "Claude process exited" });
1572
+ }
1573
+ pendingPermissions.clear();
1574
+ if (code !== 0 && code !== null && !claudeResumeId) {
1575
+ sessionService.pushMessage({
1576
+ type: "assistant",
1577
+ content: [{
1578
+ type: "text",
1579
+ text: `Error: Claude process exited with code ${code}${signal ? ` (signal: ${signal})` : ""}.
1580
+
1581
+ This may indicate that Claude Code CLI is not properly installed or configured.`
1582
+ }]
1583
+ }, "agent");
1584
+ }
1585
+ sessionService.updateMetadata({
1586
+ ...sessionMetadata,
1587
+ lifecycleState: claudeResumeId ? "idle" : "stopped"
1588
+ });
1589
+ sessionService.sendKeepAlive(false);
1590
+ if (claudeResumeId && !trackedSession.stopped) {
1591
+ saveSession({
1592
+ sessionId,
1593
+ directory,
1594
+ claudeResumeId,
1595
+ permissionMode: currentPermissionMode,
1596
+ metadata: sessionMetadata,
1597
+ createdAt: Date.now(),
1598
+ machineId
1599
+ });
1600
+ artifactSync.syncSession(sessionId, SESSIONS_DIR, sessionMetadata, machineId).catch(() => {
1601
+ });
1602
+ }
1603
+ });
1604
+ if (initialMessage && child.stdin) {
1605
+ const stdinMsg = JSON.stringify({
1606
+ type: "user",
1607
+ message: { role: "user", content: initialMessage }
1608
+ });
1609
+ child.stdin.write(stdinMsg + "\n");
1610
+ }
1611
+ return child;
1612
+ };
1613
+ const sessionService = await registerSessionService(
1614
+ server,
1615
+ sessionId,
1616
+ sessionMetadata,
1617
+ { controlledByUser: false },
1618
+ {
1619
+ onUserMessage: (content, meta) => {
1620
+ logger.log(`[Session ${sessionId}] User message received`);
1621
+ userMessagePending = true;
1622
+ turnInitiatedByUser = true;
1623
+ let text;
1624
+ let msgMeta = meta;
1625
+ try {
1626
+ let parsed = typeof content === "string" ? JSON.parse(content) : content;
1627
+ if (parsed?.content && typeof parsed.content === "string") {
1628
+ try {
1629
+ const inner = JSON.parse(parsed.content);
1630
+ if (inner && typeof inner === "object") parsed = inner;
1631
+ } catch {
1632
+ }
1633
+ }
1634
+ text = parsed?.content?.text || parsed?.text || (typeof parsed === "string" ? parsed : JSON.stringify(parsed));
1635
+ if (parsed?.meta) msgMeta = { ...msgMeta, ...parsed.meta };
1636
+ } catch {
1637
+ text = typeof content === "string" ? content : JSON.stringify(content);
1638
+ }
1639
+ if (msgMeta?.permissionMode) {
1640
+ currentPermissionMode = msgMeta.permissionMode;
1641
+ logger.log(`[Session ${sessionId}] Permission mode updated to: ${currentPermissionMode}`);
1642
+ }
1643
+ if (!claudeProcess || claudeProcess.killed) {
1644
+ spawnClaude(text, msgMeta);
1645
+ } else {
1646
+ const stdinMsg = JSON.stringify({
1647
+ type: "user",
1648
+ message: { role: "user", content: text }
1649
+ });
1650
+ claudeProcess.stdin?.write(stdinMsg + "\n");
1651
+ }
1652
+ sessionService.sendKeepAlive(true);
1653
+ },
1654
+ onAbort: () => {
1655
+ logger.log(`[Session ${sessionId}] Abort requested`);
1656
+ if (claudeProcess && !claudeProcess.killed) {
1657
+ claudeProcess.kill("SIGINT");
1658
+ }
1659
+ },
1660
+ onPermissionResponse: (params) => {
1661
+ logger.log(`[Session ${sessionId}] Permission response:`, JSON.stringify(params));
1662
+ const requestId = params.id;
1663
+ const pending = pendingPermissions.get(requestId);
1664
+ if (params.mode) {
1665
+ logger.log(`[Session ${sessionId}] Permission mode changed to: ${params.mode}`);
1666
+ currentPermissionMode = params.mode;
1667
+ }
1668
+ if (params.allowTools && Array.isArray(params.allowTools)) {
1669
+ for (const tool of params.allowTools) {
1670
+ if (tool.startsWith("Bash(") || tool === "Bash") {
1671
+ parseBashPermission2(tool);
1672
+ } else {
1673
+ allowedTools.add(tool);
1674
+ }
1675
+ }
1676
+ logger.log(`[Session ${sessionId}] Updated allowed tools: ${[...allowedTools].join(", ")}`);
1677
+ }
1678
+ if (pending) {
1679
+ pendingPermissions.delete(requestId);
1680
+ if (params.approved) {
1681
+ pending.resolve({
1682
+ behavior: "allow",
1683
+ updatedInput: pending.input || {}
1684
+ });
1685
+ } else {
1686
+ pending.resolve({
1687
+ behavior: "deny",
1688
+ 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."
1689
+ });
1690
+ }
1691
+ } else {
1692
+ logger.log(`[Session ${sessionId}] No pending permission for id=${requestId}`);
1693
+ }
1694
+ },
1695
+ onSwitchMode: (mode) => {
1696
+ logger.log(`[Session ${sessionId}] Switch mode: ${mode}`);
1697
+ currentPermissionMode = mode;
1698
+ if (claudeProcess && !claudeProcess.killed) {
1699
+ claudeProcess.kill("SIGTERM");
1700
+ setTimeout(() => {
1701
+ if (!claudeProcess || claudeProcess.killed) {
1702
+ spawnClaude(void 0, { permissionMode: mode });
1703
+ }
1704
+ }, 1e3);
1705
+ }
1706
+ },
1707
+ onRestartClaude: () => {
1708
+ logger.log(`[Session ${sessionId}] Restart Claude requested`);
1709
+ if (claudeProcess && !claudeProcess.killed) {
1710
+ claudeProcess.kill("SIGTERM");
1711
+ }
1712
+ },
1713
+ onKillSession: () => {
1714
+ logger.log(`[Session ${sessionId}] Kill session requested`);
1715
+ stopSession(sessionId);
1716
+ },
1717
+ onBash: async (command, cwd) => {
1718
+ logger.log(`[Session ${sessionId}] Bash: ${command} (cwd: ${cwd || directory})`);
1719
+ const { exec } = await import('child_process');
1720
+ return new Promise((resolve2) => {
1721
+ exec(command, { cwd: cwd || directory, timeout: 3e4, maxBuffer: 1024 * 1024 }, (err, stdout, stderr) => {
1722
+ if (err) {
1723
+ resolve2({ success: false, stdout: stdout || "", stderr: stderr || err.message, exitCode: err.code ?? 1 });
1724
+ } else {
1725
+ resolve2({ success: true, stdout, stderr: stderr || "", exitCode: 0 });
1726
+ }
1727
+ });
1728
+ });
1729
+ },
1730
+ onReadFile: async (path) => {
1731
+ return await fs.readFile(path, "utf-8");
1732
+ },
1733
+ onWriteFile: async (path, content) => {
1734
+ const resolvedPath = resolve(directory, path);
1735
+ if (!resolvedPath.startsWith(resolve(directory))) {
1736
+ throw new Error("Path outside working directory");
1737
+ }
1738
+ await fs.mkdir(dirname(resolvedPath), { recursive: true });
1739
+ await fs.writeFile(resolvedPath, Buffer.from(content, "base64"));
1740
+ },
1741
+ onListDirectory: async (path) => {
1742
+ const entries = await fs.readdir(path, { withFileTypes: true });
1743
+ return entries.map((e) => ({ name: e.name, isDirectory: e.isDirectory() }));
1744
+ },
1745
+ onGetDirectoryTree: async (treePath, maxDepth) => {
1746
+ async function buildTree(p, name, depth) {
1747
+ try {
1748
+ const stats = await fs.stat(p);
1749
+ const node = {
1750
+ name,
1751
+ path: p,
1752
+ type: stats.isDirectory() ? "directory" : "file",
1753
+ size: stats.size,
1754
+ modified: stats.mtime.getTime()
1755
+ };
1756
+ if (stats.isDirectory() && depth < maxDepth) {
1757
+ const entries = await fs.readdir(p, { withFileTypes: true });
1758
+ const children = [];
1759
+ await Promise.all(entries.map(async (entry) => {
1760
+ if (entry.isSymbolicLink()) return;
1761
+ const childPath = join$1(p, entry.name);
1762
+ const childNode = await buildTree(childPath, entry.name, depth + 1);
1763
+ if (childNode) children.push(childNode);
1764
+ }));
1765
+ children.sort((a, b) => {
1766
+ if (a.type === "directory" && b.type !== "directory") return -1;
1767
+ if (a.type !== "directory" && b.type === "directory") return 1;
1768
+ return a.name.localeCompare(b.name);
1769
+ });
1770
+ node.children = children;
1771
+ }
1772
+ return node;
1773
+ } catch {
1774
+ return null;
1775
+ }
1776
+ }
1777
+ const resolvedPath = resolve(directory, treePath);
1778
+ const tree = await buildTree(resolvedPath, basename(resolvedPath), 0);
1779
+ return { success: !!tree, tree };
1780
+ }
1781
+ },
1782
+ { messagesDir: SESSIONS_DIR }
1783
+ );
1784
+ const svampServer = await startSvampServer({
1785
+ sessionService,
1786
+ getMetadata: () => sessionMetadata,
1787
+ setMetadata: (updater) => {
1788
+ sessionMetadata = updater(sessionMetadata);
1789
+ sessionService.updateMetadata(sessionMetadata);
1790
+ },
1791
+ logger
1792
+ });
1793
+ const trackedSession = {
1794
+ startedBy: "daemon",
1795
+ pid: process.pid,
1796
+ svampSessionId: sessionId,
1797
+ hyphaService: sessionService,
1798
+ svampMcpServer: svampServer,
1799
+ directory,
1800
+ get childProcess() {
1801
+ return claudeProcess || void 0;
1802
+ }
1803
+ };
1804
+ pidToTrackedSession.set(process.pid + Math.floor(Math.random() * 1e5), trackedSession);
1805
+ sessionService.updateMetadata({
1806
+ ...sessionMetadata,
1807
+ lifecycleState: "idle"
1808
+ });
1809
+ logger.log(`Session ${sessionId} registered on Hypha, waiting for first message to spawn Claude`);
1810
+ return {
1811
+ type: "success",
1812
+ sessionId,
1813
+ message: `Session registered on Hypha as svamp-session-${sessionId}`
1814
+ };
1815
+ } catch (err) {
1816
+ logger.error(`Failed to spawn session:`, err);
1817
+ return {
1818
+ type: "error",
1819
+ errorMessage: `Failed to register session service: ${err.message}`
1820
+ };
1821
+ }
1822
+ };
1823
+ const stopSession = (sessionId) => {
1824
+ logger.log(`Stopping session: ${sessionId}`);
1825
+ for (const [pid, session] of pidToTrackedSession) {
1826
+ if (session.svampSessionId === sessionId) {
1827
+ session.stopped = true;
1828
+ session.svampMcpServer?.stop();
1829
+ session.hyphaService?.disconnect().catch(() => {
1830
+ });
1831
+ if (session.childProcess) {
1832
+ try {
1833
+ session.childProcess.kill("SIGTERM");
1834
+ } catch {
1835
+ }
1836
+ }
1837
+ pidToTrackedSession.delete(pid);
1838
+ deletePersistedSession(sessionId);
1839
+ logger.log(`Session ${sessionId} stopped`);
1840
+ return true;
1841
+ }
1842
+ }
1843
+ logger.log(`Session ${sessionId} not found`);
1844
+ return false;
1845
+ };
1846
+ const defaultHomeDir = existsSync$1("/data") ? "/data" : os.homedir();
1847
+ const machineMetadata = {
1848
+ host: os.hostname(),
1849
+ platform: os.platform(),
1850
+ svampVersion: "0.1.0 (hypha)",
1851
+ homeDir: defaultHomeDir,
1852
+ svampHomeDir: SVAMP_HOME,
1853
+ svampLibDir: join$1(__dirname$1, ".."),
1854
+ displayName: process.env.SVAMP_DISPLAY_NAME || void 0
1855
+ };
1856
+ const initialDaemonState = {
1857
+ status: "running",
1858
+ pid: process.pid,
1859
+ startedAt: Date.now()
1860
+ };
1861
+ const machineService = await registerMachineService(
1862
+ server,
1863
+ machineId,
1864
+ machineMetadata,
1865
+ initialDaemonState,
1866
+ {
1867
+ spawnSession,
1868
+ stopSession,
1869
+ requestShutdown: () => requestShutdown("hypha-app"),
1870
+ getTrackedSessions: getCurrentChildren
1871
+ }
1872
+ );
1873
+ logger.log(`Machine service registered: svamp-machine-${machineId}`);
1874
+ const artifactSync = new SessionArtifactSync(server, logger.log);
1875
+ await artifactSync.init().catch((err) => {
1876
+ logger.log(`[ARTIFACT SYNC] Background init failed: ${err}`);
1877
+ });
1878
+ const debugService = await registerDebugService(server, machineId, {
1879
+ machineId,
1880
+ getTrackedSessions: getCurrentChildren,
1881
+ getSessionService: (sessionId) => {
1882
+ for (const [, session] of pidToTrackedSession) {
1883
+ if (session.svampSessionId === sessionId) {
1884
+ return session.hyphaService;
1885
+ }
1886
+ }
1887
+ return null;
1888
+ },
1889
+ getArtifactSync: () => artifactSync,
1890
+ getSessionsDir: () => SESSIONS_DIR
1891
+ });
1892
+ logger.log(`Debug service registered: svamp-debug-${machineId}`);
1893
+ const persistedSessions = loadPersistedSessions();
1894
+ try {
1895
+ const remoteSessions = await artifactSync.listRemoteSessions();
1896
+ const localIds = new Set(persistedSessions.map((p) => p.sessionId));
1897
+ for (const remote of remoteSessions) {
1898
+ if (!localIds.has(remote.sessionId)) {
1899
+ logger.log(`[ARTIFACT SYNC] Downloading remote session ${remote.sessionId} (from machine ${remote.machineId || "unknown"})`);
1900
+ const downloaded = await artifactSync.downloadSession(remote.sessionId, SESSIONS_DIR);
1901
+ if (downloaded?.sessionData) {
1902
+ persistedSessions.push({
1903
+ sessionId: remote.sessionId,
1904
+ directory: downloaded.sessionData.directory || "/tmp",
1905
+ claudeResumeId: downloaded.sessionData.claudeResumeId,
1906
+ permissionMode: downloaded.sessionData.permissionMode || "default",
1907
+ metadata: downloaded.sessionData.metadata,
1908
+ createdAt: downloaded.sessionData.createdAt || Date.now(),
1909
+ machineId: remote.machineId
1910
+ });
1911
+ logger.log(`[ARTIFACT SYNC] Downloaded session ${remote.sessionId} (${downloaded.messageCount} messages)`);
1912
+ }
1913
+ }
1914
+ }
1915
+ } catch (err) {
1916
+ logger.log(`[ARTIFACT SYNC] Remote session restore failed: ${err.message}`);
1917
+ }
1918
+ if (persistedSessions.length > 0) {
1919
+ logger.log(`Restoring ${persistedSessions.length} persisted session(s)...`);
1920
+ for (const persisted of persistedSessions) {
1921
+ try {
1922
+ const isOrphaned = persisted.machineId && persisted.machineId !== machineId;
1923
+ if (isOrphaned) {
1924
+ logger.log(`Session ${persisted.sessionId} is from a different machine (${persisted.machineId} vs ${machineId}), marking as orphaned`);
1925
+ }
1926
+ const result = await spawnSession({
1927
+ directory: persisted.directory,
1928
+ sessionId: persisted.sessionId,
1929
+ resumeSessionId: persisted.claudeResumeId
1930
+ });
1931
+ if (result.type === "success") {
1932
+ logger.log(`Restored session ${persisted.sessionId} (resume=${persisted.claudeResumeId})`);
1933
+ if (isOrphaned) {
1934
+ for (const [, tracked] of pidToTrackedSession) {
1935
+ if (tracked.svampSessionId === persisted.sessionId && tracked.hyphaService) {
1936
+ tracked.hyphaService.updateMetadata({
1937
+ ...persisted.metadata || {},
1938
+ isOrphaned: true,
1939
+ originalMachineId: persisted.machineId
1940
+ });
1941
+ break;
1942
+ }
1943
+ }
1944
+ }
1945
+ } else {
1946
+ logger.log(`Failed to restore session ${persisted.sessionId}: ${result.type}`);
1947
+ }
1948
+ } catch (err) {
1949
+ logger.error(`Error restoring session ${persisted.sessionId}:`, err.message);
1950
+ }
1951
+ }
1952
+ }
1953
+ let appToken;
1954
+ try {
1955
+ appToken = await server.generateToken({});
1956
+ logger.log(`App connection token generated`);
1957
+ } catch (err) {
1958
+ logger.log("Could not generate token (server may not support it):", err);
1959
+ }
1960
+ const localState = {
1961
+ pid: process.pid,
1962
+ startTime: (/* @__PURE__ */ new Date()).toISOString(),
1963
+ version: "0.1.0",
1964
+ hyphaServerUrl,
1965
+ workspace: server.config.workspace
1966
+ };
1967
+ writeDaemonStateFile(localState);
1968
+ console.log("Svamp daemon started successfully!");
1969
+ console.log(` Machine ID: ${machineId}`);
1970
+ console.log(` Hypha server: ${hyphaServerUrl}`);
1971
+ console.log(` Workspace: ${server.config.workspace}`);
1972
+ if (appToken) {
1973
+ console.log(` App token: ${appToken}`);
1974
+ }
1975
+ console.log(` Service: svamp-machine-${machineId}`);
1976
+ console.log(` Log file: ${logger.logFilePath}`);
1977
+ const heartbeatInterval = setInterval(async () => {
1978
+ for (const [key, session] of pidToTrackedSession) {
1979
+ const child = session.childProcess;
1980
+ if (child && child.pid) {
1981
+ try {
1982
+ process.kill(child.pid, 0);
1983
+ } catch {
1984
+ logger.log(`Removing stale session (child PID ${child.pid} dead): ${session.svampSessionId}`);
1985
+ session.hyphaService?.disconnect().catch(() => {
1986
+ });
1987
+ pidToTrackedSession.delete(key);
1988
+ }
1989
+ }
1990
+ }
1991
+ try {
1992
+ const state = readDaemonStateFile();
1993
+ if (state && state.pid === process.pid) {
1994
+ state.lastHeartbeat = (/* @__PURE__ */ new Date()).toISOString();
1995
+ writeDaemonStateFile(state);
1996
+ }
1997
+ } catch {
1998
+ }
1999
+ }, 6e4);
2000
+ const cleanup = async (source) => {
2001
+ logger.log(`Cleaning up (source: ${source})...`);
2002
+ clearInterval(heartbeatInterval);
2003
+ machineService.updateDaemonState({
2004
+ ...initialDaemonState,
2005
+ status: "shutting-down",
2006
+ shutdownRequestedAt: Date.now(),
2007
+ shutdownSource: source
2008
+ });
2009
+ await new Promise((r) => setTimeout(r, 200));
2010
+ for (const [pid, session] of pidToTrackedSession) {
2011
+ session.hyphaService?.disconnect().catch(() => {
2012
+ });
2013
+ if (session.childProcess) {
2014
+ try {
2015
+ session.childProcess.kill("SIGTERM");
2016
+ } catch {
2017
+ }
2018
+ }
2019
+ }
2020
+ try {
2021
+ await machineService.disconnect();
2022
+ } catch {
2023
+ }
2024
+ try {
2025
+ await debugService.disconnect();
2026
+ } catch {
2027
+ }
2028
+ artifactSync.destroy();
2029
+ try {
2030
+ await server.disconnect();
2031
+ } catch {
2032
+ }
2033
+ cleanupDaemonStateFile();
2034
+ logger.log("Cleanup complete");
2035
+ };
2036
+ const shutdownReq = await resolvesWhenShutdownRequested;
2037
+ await cleanup(shutdownReq.source);
2038
+ process.exit(0);
2039
+ } catch (error) {
2040
+ logger.error("Fatal error:", error);
2041
+ cleanupDaemonStateFile();
2042
+ if (server) {
2043
+ try {
2044
+ await server.disconnect();
2045
+ } catch {
2046
+ }
2047
+ }
2048
+ process.exit(1);
2049
+ }
2050
+ }
2051
+ async function stopDaemon() {
2052
+ const state = readDaemonStateFile();
2053
+ if (!state) {
2054
+ console.log("No daemon running");
2055
+ return;
2056
+ }
2057
+ try {
2058
+ process.kill(state.pid, 0);
2059
+ process.kill(state.pid, "SIGTERM");
2060
+ console.log(`Sent SIGTERM to daemon PID ${state.pid}`);
2061
+ for (let i = 0; i < 30; i++) {
2062
+ await new Promise((r) => setTimeout(r, 100));
2063
+ try {
2064
+ process.kill(state.pid, 0);
2065
+ } catch {
2066
+ console.log("Daemon stopped");
2067
+ cleanupDaemonStateFile();
2068
+ return;
2069
+ }
2070
+ }
2071
+ console.log("Daemon did not stop in time, sending SIGKILL");
2072
+ process.kill(state.pid, "SIGKILL");
2073
+ } catch {
2074
+ console.log("Daemon is not running (stale state file)");
2075
+ }
2076
+ cleanupDaemonStateFile();
2077
+ }
2078
+ function daemonStatus() {
2079
+ const state = readDaemonStateFile();
2080
+ if (!state) {
2081
+ console.log("Status: Not running");
2082
+ return;
2083
+ }
2084
+ const alive = isDaemonAlive();
2085
+ console.log(`Status: ${alive ? "Running" : "Dead (stale state)"}`);
2086
+ console.log(` PID: ${state.pid}`);
2087
+ console.log(` Started: ${state.startTime}`);
2088
+ console.log(` Hypha server: ${state.hyphaServerUrl}`);
2089
+ if (state.workspace) {
2090
+ console.log(` Workspace: ${state.workspace}`);
2091
+ }
2092
+ if (state.lastHeartbeat) {
2093
+ console.log(` Last heartbeat: ${state.lastHeartbeat}`);
2094
+ }
2095
+ if (!alive) {
2096
+ cleanupDaemonStateFile();
2097
+ }
2098
+ }
2099
+
2100
+ export { registerSessionService as a, stopDaemon as b, connectToHypha as c, daemonStatus as d, getHyphaServerUrl as g, registerMachineService as r, startDaemon as s };