svamp-cli 0.1.28 → 0.1.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/dist/cli.mjs +114 -42
  2. package/dist/commands-B2xQb9u7.mjs +862 -0
  3. package/dist/commands-C5pW2VmI.mjs +862 -0
  4. package/dist/commands-CtO1WRt4.mjs +862 -0
  5. package/dist/commands-TZkNivgV.mjs +862 -0
  6. package/dist/index.mjs +8 -2
  7. package/dist/{package-CgBD49cA.mjs → package-CKOQ5lA7.mjs} +2 -2
  8. package/dist/{run-DjfPjgOb.mjs → run-BCSNMhiz.mjs} +1200 -132
  9. package/dist/{run-Cmostc0S.mjs → run-CtCTd6if.mjs} +1225 -169
  10. package/dist/{run-DYhBROuo.mjs → run-Cxdc5Zmw.mjs} +1253 -211
  11. package/dist/{run-CL-FS4Yc.mjs → run-dBWhjQRf.mjs} +1255 -211
  12. package/package.json +3 -6
  13. package/bin/svamp-agent.mjs +0 -34
  14. package/dist/agent-cli.mjs +0 -453
  15. package/dist/commands-1CYZC6Xh.mjs +0 -481
  16. package/dist/commands-B1DcpgLW.mjs +0 -481
  17. package/dist/commands-BGmdgMAC.mjs +0 -485
  18. package/dist/commands-BOeSil-P.mjs +0 -459
  19. package/dist/commands-BU4GZQuH.mjs +0 -481
  20. package/dist/commands-Ba66PxtQ.mjs +0 -481
  21. package/dist/commands-C0-xqIIc.mjs +0 -481
  22. package/dist/commands-C7Qy5n6d.mjs +0 -481
  23. package/dist/commands-CKpC8R9T.mjs +0 -481
  24. package/dist/commands-CNqOjR1y.mjs +0 -481
  25. package/dist/commands-CVKh1tWr.mjs +0 -485
  26. package/dist/commands-CYBblX73.mjs +0 -485
  27. package/dist/commands-CZBYmj16.mjs +0 -485
  28. package/dist/commands-CcWIvCA4.mjs +0 -481
  29. package/dist/commands-Cfwf-cQG.mjs +0 -481
  30. package/dist/commands-DCNO2m66.mjs +0 -471
  31. package/dist/commands-DRIFvhmC.mjs +0 -481
  32. package/dist/commands-DXmw2dzy.mjs +0 -481
  33. package/dist/commands-DkSvlKFF.mjs +0 -485
  34. package/dist/commands-DnDd4Sew.mjs +0 -481
  35. package/dist/commands-DnpnAFQW.mjs +0 -485
  36. package/dist/commands-Do-TVYFm.mjs +0 -481
  37. package/dist/commands-Kzm0_XNH.mjs +0 -481
  38. package/dist/commands-MQvNbIid.mjs +0 -481
  39. package/dist/commands-_uCC3U1U.mjs +0 -481
  40. package/dist/commands-y2WG29W9.mjs +0 -485
  41. package/dist/hyphaClient-DLkclazm.mjs +0 -39
  42. package/dist/package-B2FOzHaM.mjs +0 -57
  43. package/dist/package-Bk_PFVA0.mjs +0 -57
  44. package/dist/package-Bnij-ZtR.mjs +0 -57
  45. package/dist/package-BtRbHfjz.mjs +0 -57
  46. package/dist/package-C5B0twb8.mjs +0 -57
  47. package/dist/package-CC5d8_0L.mjs +0 -57
  48. package/dist/package-CCJ045H0.mjs +0 -60
  49. package/dist/package-CS219SXn.mjs +0 -57
  50. package/dist/package-Cd-9ktpd.mjs +0 -60
  51. package/dist/package-CvnNnsm7.mjs +0 -60
  52. package/dist/package-DpqWz9Cr.mjs +0 -60
  53. package/dist/package-JqEt5Ib4.mjs +0 -57
  54. package/dist/package-nzkXV1aM.mjs +0 -57
  55. package/dist/package-pNo6GC3a.mjs +0 -60
  56. package/dist/package-pZp14zKI.mjs +0 -57
  57. package/dist/run-4fyJcaRE.mjs +0 -3856
  58. package/dist/run-BI32lPRK.mjs +0 -3870
  59. package/dist/run-BQHneHfW.mjs +0 -3834
  60. package/dist/run-Bb4fyIWZ.mjs +0 -3812
  61. package/dist/run-BglwnB-A.mjs +0 -3889
  62. package/dist/run-BjVWuitO.mjs +0 -3919
  63. package/dist/run-BzUE-JUT.mjs +0 -3708
  64. package/dist/run-BzqS97Sx.mjs +0 -3666
  65. package/dist/run-C6snRxyh.mjs +0 -3826
  66. package/dist/run-C8CI8Ujj.mjs +0 -3693
  67. package/dist/run-CS1Z4GcM.mjs +0 -3786
  68. package/dist/run-CW26vPqj.mjs +0 -3919
  69. package/dist/run-CkTufc0D.mjs +0 -3875
  70. package/dist/run-Cp3kKdzm.mjs +0 -3865
  71. package/dist/run-D0bCTY72.mjs +0 -3816
  72. package/dist/run-DMW8ibIw.mjs +0 -3958
  73. package/dist/run-DO52unxE.mjs +0 -3950
  74. package/dist/run-Dptna3Je.mjs +0 -3867
  75. package/dist/run-DwK3dfHd.mjs +0 -3875
  76. package/dist/run-M_SMt96j.mjs +0 -3913
  77. package/dist/run-MlpxQUPN.mjs +0 -3869
  78. package/dist/run-PuTIelbv.mjs +0 -3706
  79. package/dist/run-h37iSCUB.mjs +0 -3934
  80. package/dist/run-lpV0oguG.mjs +0 -3897
@@ -1,3897 +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 { c as connectToHypha } from './hyphaClient-DLkclazm.mjs';
9
- import { randomUUID } from 'node:crypto';
10
- import { existsSync, readFileSync, mkdirSync, appendFileSync, writeFileSync } from 'node:fs';
11
- import { join } from 'node:path';
12
- import { spawn } from 'node:child_process';
13
- import { ndJsonStream, ClientSideConnection } from '@agentclientprotocol/sdk';
14
-
15
- async function registerMachineService(server, machineId, metadata, daemonState, handlers) {
16
- let currentMetadata = { ...metadata };
17
- let currentDaemonState = { ...daemonState };
18
- let metadataVersion = 1;
19
- let daemonStateVersion = 1;
20
- const listeners = [];
21
- const removeListener = (listener, reason) => {
22
- const idx = listeners.indexOf(listener);
23
- if (idx >= 0) {
24
- listeners.splice(idx, 1);
25
- console.log(`[HYPHA MACHINE] Listener removed (${reason}), remaining: ${listeners.length}`);
26
- const rintfId = listener._rintf_service_id;
27
- if (rintfId) {
28
- server.unregisterService(rintfId).catch(() => {
29
- });
30
- }
31
- }
32
- };
33
- const notifyListeners = (update) => {
34
- for (let i = listeners.length - 1; i >= 0; i--) {
35
- try {
36
- const result = listeners[i].onUpdate(update);
37
- if (result && typeof result.catch === "function") {
38
- const listener = listeners[i];
39
- result.catch((err) => {
40
- console.error(`[HYPHA MACHINE] Async listener error:`, err);
41
- removeListener(listener, "async error");
42
- });
43
- }
44
- } catch (err) {
45
- console.error(`[HYPHA MACHINE] Listener error:`, err);
46
- removeListener(listeners[i], "sync error");
47
- }
48
- }
49
- };
50
- const serviceInfo = await server.registerService(
51
- {
52
- id: "default",
53
- name: `Svamp Machine (${metadata.displayName || machineId})`,
54
- type: "svamp-machine",
55
- config: { visibility: "public" },
56
- // Machine info
57
- getMachineInfo: async () => ({
58
- machineId,
59
- metadata: currentMetadata,
60
- metadataVersion,
61
- daemonState: currentDaemonState,
62
- daemonStateVersion
63
- }),
64
- // Heartbeat
65
- heartbeat: async () => ({
66
- time: Date.now(),
67
- status: currentDaemonState.status,
68
- machineId
69
- }),
70
- // List active sessions on this machine
71
- listSessions: async () => {
72
- return handlers.getTrackedSessions();
73
- },
74
- // Spawn a new session
75
- spawnSession: async (options) => {
76
- const result = await handlers.spawnSession({
77
- ...options,
78
- machineId
79
- });
80
- if (result.type === "success" && result.sessionId) {
81
- notifyListeners({
82
- type: "new-session",
83
- sessionId: result.sessionId,
84
- machineId
85
- });
86
- }
87
- return result;
88
- },
89
- // Stop a session
90
- stopSession: async (sessionId) => {
91
- const result = handlers.stopSession(sessionId);
92
- notifyListeners({
93
- type: "session-stopped",
94
- sessionId,
95
- machineId
96
- });
97
- return result;
98
- },
99
- // Stop the daemon
100
- stopDaemon: async () => {
101
- handlers.requestShutdown();
102
- return { success: true };
103
- },
104
- // Metadata management (with optimistic concurrency)
105
- getMetadata: async () => ({
106
- metadata: currentMetadata,
107
- version: metadataVersion
108
- }),
109
- updateMetadata: async (newMetadata, expectedVersion) => {
110
- if (expectedVersion !== metadataVersion) {
111
- return {
112
- result: "version-mismatch",
113
- version: metadataVersion,
114
- metadata: currentMetadata
115
- };
116
- }
117
- currentMetadata = newMetadata;
118
- metadataVersion++;
119
- notifyListeners({
120
- type: "update-machine",
121
- machineId,
122
- metadata: { value: currentMetadata, version: metadataVersion }
123
- });
124
- return {
125
- result: "success",
126
- version: metadataVersion,
127
- metadata: currentMetadata
128
- };
129
- },
130
- // Daemon state management
131
- getDaemonState: async () => ({
132
- daemonState: currentDaemonState,
133
- version: daemonStateVersion
134
- }),
135
- updateDaemonState: async (newState, expectedVersion) => {
136
- if (expectedVersion !== daemonStateVersion) {
137
- return {
138
- result: "version-mismatch",
139
- version: daemonStateVersion,
140
- daemonState: currentDaemonState
141
- };
142
- }
143
- currentDaemonState = newState;
144
- daemonStateVersion++;
145
- notifyListeners({
146
- type: "update-machine",
147
- machineId,
148
- daemonState: { value: currentDaemonState, version: daemonStateVersion }
149
- });
150
- return {
151
- result: "success",
152
- version: daemonStateVersion,
153
- daemonState: currentDaemonState
154
- };
155
- },
156
- // Register a listener for real-time updates (app calls this with _rintf callback)
157
- registerListener: async (callback) => {
158
- listeners.push(callback);
159
- console.log(`[HYPHA MACHINE] Listener registered (total: ${listeners.length})`);
160
- return { success: true, listenerId: listeners.length - 1 };
161
- },
162
- // Shell access
163
- bash: async (command, cwd) => {
164
- const { exec } = await import('child_process');
165
- const { homedir } = await import('os');
166
- return new Promise((resolve) => {
167
- exec(command, { cwd: cwd || homedir(), timeout: 3e4, maxBuffer: 1024 * 1024 }, (err, stdout, stderr) => {
168
- if (err) {
169
- resolve({ success: false, stdout: stdout || "", stderr: stderr || err.message, exitCode: err.code ?? 1 });
170
- } else {
171
- resolve({ success: true, stdout, stderr: stderr || "", exitCode: 0 });
172
- }
173
- });
174
- });
175
- },
176
- // WISE voice — create ephemeral token for OpenAI Realtime API
177
- wiseCreateEphemeralToken: async (params) => {
178
- const apiKey = params.apiKey || process.env.OPENAI_API_KEY;
179
- if (!apiKey) {
180
- return { success: false, error: "No OpenAI API key found. Set OPENAI_API_KEY or pass apiKey." };
181
- }
182
- try {
183
- const response = await fetch("https://api.openai.com/v1/realtime/client_secrets", {
184
- method: "POST",
185
- headers: {
186
- "Authorization": `Bearer ${apiKey}`,
187
- "Content-Type": "application/json"
188
- },
189
- body: JSON.stringify({
190
- session: {
191
- type: "realtime",
192
- model: params.model || "gpt-realtime-mini"
193
- }
194
- })
195
- });
196
- if (!response.ok) {
197
- return { success: false, error: `OpenAI API error: ${response.status}` };
198
- }
199
- const result = await response.json();
200
- return { success: true, clientSecret: result.value };
201
- } catch (error) {
202
- return { success: false, error: error instanceof Error ? error.message : "Failed to create token" };
203
- }
204
- }
205
- },
206
- { overwrite: true }
207
- );
208
- console.log(`[HYPHA MACHINE] Machine service registered: ${serviceInfo.id}`);
209
- return {
210
- serviceInfo,
211
- updateMetadata: (newMetadata) => {
212
- currentMetadata = newMetadata;
213
- metadataVersion++;
214
- notifyListeners({
215
- type: "update-machine",
216
- machineId,
217
- metadata: { value: currentMetadata, version: metadataVersion }
218
- });
219
- },
220
- updateDaemonState: (newState) => {
221
- currentDaemonState = newState;
222
- daemonStateVersion++;
223
- notifyListeners({
224
- type: "update-machine",
225
- machineId,
226
- daemonState: { value: currentDaemonState, version: daemonStateVersion }
227
- });
228
- },
229
- disconnect: async () => {
230
- await server.unregisterService(serviceInfo.id);
231
- }
232
- };
233
- }
234
-
235
- function loadMessages(messagesDir, sessionId) {
236
- const filePath = join(messagesDir, "messages.jsonl");
237
- if (!existsSync(filePath)) return [];
238
- try {
239
- const lines = readFileSync(filePath, "utf-8").split("\n").filter((l) => l.trim());
240
- const messages = [];
241
- for (const line of lines) {
242
- try {
243
- messages.push(JSON.parse(line));
244
- } catch {
245
- }
246
- }
247
- return messages.slice(-5e3);
248
- } catch {
249
- return [];
250
- }
251
- }
252
- function appendMessage(messagesDir, sessionId, msg) {
253
- const filePath = join(messagesDir, "messages.jsonl");
254
- if (!existsSync(messagesDir)) {
255
- mkdirSync(messagesDir, { recursive: true });
256
- }
257
- appendFileSync(filePath, JSON.stringify(msg) + "\n");
258
- }
259
- async function registerSessionService(server, sessionId, initialMetadata, initialAgentState, callbacks, options) {
260
- const messages = options?.messagesDir ? loadMessages(options.messagesDir) : [];
261
- let nextSeq = messages.length > 0 ? messages[messages.length - 1].seq + 1 : 1;
262
- let metadata = { ...initialMetadata };
263
- let metadataVersion = 1;
264
- let agentState = initialAgentState ? { ...initialAgentState } : null;
265
- let agentStateVersion = 1;
266
- let lastActivity = {
267
- active: false,
268
- thinking: false,
269
- mode: "remote",
270
- time: Date.now()
271
- };
272
- const listeners = [];
273
- const removeListener = (listener, reason) => {
274
- const idx = listeners.indexOf(listener);
275
- if (idx >= 0) {
276
- listeners.splice(idx, 1);
277
- console.log(`[HYPHA SESSION ${sessionId}] Listener removed (${reason}), remaining: ${listeners.length}`);
278
- const rintfId = listener._rintf_service_id;
279
- if (rintfId) {
280
- server.unregisterService(rintfId).catch(() => {
281
- });
282
- }
283
- }
284
- };
285
- const notifyListeners = (update) => {
286
- for (let i = listeners.length - 1; i >= 0; i--) {
287
- try {
288
- const result = listeners[i].onUpdate(update);
289
- if (result && typeof result.catch === "function") {
290
- const listener = listeners[i];
291
- result.catch((err) => {
292
- console.error(`[HYPHA SESSION ${sessionId}] Async listener error:`, err);
293
- removeListener(listener, "async error");
294
- });
295
- }
296
- } catch (err) {
297
- console.error(`[HYPHA SESSION ${sessionId}] Listener error:`, err);
298
- removeListener(listeners[i], "sync error");
299
- }
300
- }
301
- };
302
- const pushMessage = (content, role = "agent") => {
303
- let wrappedContent;
304
- if (role === "agent") {
305
- const data = { ...content };
306
- if ((data.type === "assistant" || data.type === "user") && !data.uuid) {
307
- data.uuid = randomUUID();
308
- }
309
- wrappedContent = { role: "agent", content: { type: "output", data } };
310
- } else if (role === "session") {
311
- wrappedContent = { role: "session", content: { type: "session", data: content } };
312
- } else {
313
- const text = typeof content === "string" ? content : content?.text || content?.content || JSON.stringify(content);
314
- wrappedContent = { role: "user", content: { type: "text", text } };
315
- }
316
- const msg = {
317
- id: randomUUID(),
318
- seq: nextSeq++,
319
- content: wrappedContent,
320
- localId: null,
321
- createdAt: Date.now(),
322
- updatedAt: Date.now()
323
- };
324
- messages.push(msg);
325
- if (options?.messagesDir) {
326
- appendMessage(options.messagesDir, sessionId, msg);
327
- }
328
- notifyListeners({
329
- type: "new-message",
330
- sessionId,
331
- message: msg
332
- });
333
- return msg;
334
- };
335
- const serviceInfo = await server.registerService(
336
- {
337
- id: `svamp-session-${sessionId}`,
338
- name: `Svamp Session ${sessionId.slice(0, 8)}`,
339
- type: "svamp-session",
340
- config: { visibility: "public" },
341
- // ── Messages ──
342
- getMessages: async (afterSeq, limit) => {
343
- const after = afterSeq ?? 0;
344
- const lim = Math.min(limit ?? 100, 500);
345
- const filtered = messages.filter((m) => m.seq > after);
346
- const page = filtered.slice(0, lim);
347
- return {
348
- messages: page,
349
- hasMore: filtered.length > lim
350
- };
351
- },
352
- sendMessage: async (content, localId, meta) => {
353
- if (localId) {
354
- const existing = messages.find((m) => m.localId === localId);
355
- if (existing) {
356
- return { id: existing.id, seq: existing.seq, localId: existing.localId };
357
- }
358
- }
359
- let parsed = content;
360
- if (typeof parsed === "string") {
361
- try {
362
- parsed = JSON.parse(parsed);
363
- } catch {
364
- }
365
- }
366
- if (parsed && typeof parsed.content === "string" && !parsed.role) {
367
- try {
368
- const inner = JSON.parse(parsed.content);
369
- if (inner && typeof inner === "object") parsed = inner;
370
- } catch {
371
- }
372
- }
373
- const wrappedContent = parsed && parsed.role === "user" ? { role: "user", content: parsed.content } : { role: "user", content: { type: "text", text: typeof parsed === "string" ? parsed : JSON.stringify(parsed) } };
374
- const msg = {
375
- id: randomUUID(),
376
- seq: nextSeq++,
377
- content: wrappedContent,
378
- localId: localId || randomUUID(),
379
- createdAt: Date.now(),
380
- updatedAt: Date.now()
381
- };
382
- messages.push(msg);
383
- if (options?.messagesDir) {
384
- appendMessage(options.messagesDir, sessionId, msg);
385
- }
386
- notifyListeners({
387
- type: "new-message",
388
- sessionId,
389
- message: msg
390
- });
391
- callbacks.onUserMessage(content, meta);
392
- return { id: msg.id, seq: msg.seq, localId: msg.localId };
393
- },
394
- // ── Metadata ──
395
- getMetadata: async () => ({
396
- metadata,
397
- version: metadataVersion
398
- }),
399
- updateMetadata: async (newMetadata, expectedVersion) => {
400
- if (expectedVersion !== void 0 && expectedVersion !== metadataVersion) {
401
- return {
402
- result: "version-mismatch",
403
- version: metadataVersion,
404
- metadata
405
- };
406
- }
407
- metadata = newMetadata;
408
- metadataVersion++;
409
- notifyListeners({
410
- type: "update-session",
411
- sessionId,
412
- metadata: { value: metadata, version: metadataVersion }
413
- });
414
- return {
415
- result: "success",
416
- version: metadataVersion,
417
- metadata
418
- };
419
- },
420
- // ── Agent State ──
421
- getAgentState: async () => ({
422
- agentState,
423
- version: agentStateVersion
424
- }),
425
- updateAgentState: async (newState, expectedVersion) => {
426
- if (expectedVersion !== void 0 && expectedVersion !== agentStateVersion) {
427
- return {
428
- result: "version-mismatch",
429
- version: agentStateVersion,
430
- agentState
431
- };
432
- }
433
- agentState = newState;
434
- agentStateVersion++;
435
- notifyListeners({
436
- type: "update-session",
437
- sessionId,
438
- agentState: { value: agentState, version: agentStateVersion }
439
- });
440
- return {
441
- result: "success",
442
- version: agentStateVersion,
443
- agentState
444
- };
445
- },
446
- // ── Session Control RPCs ──
447
- abort: async () => {
448
- callbacks.onAbort();
449
- return { success: true };
450
- },
451
- permissionResponse: async (params) => {
452
- callbacks.onPermissionResponse(params);
453
- return { success: true };
454
- },
455
- switchMode: async (mode) => {
456
- callbacks.onSwitchMode(mode);
457
- return { success: true };
458
- },
459
- restartClaude: async () => {
460
- return await callbacks.onRestartClaude();
461
- },
462
- killSession: async () => {
463
- callbacks.onKillSession();
464
- return { success: true };
465
- },
466
- // ── Activity ──
467
- keepAlive: async (thinking, mode) => {
468
- lastActivity = { active: true, thinking: thinking || false, mode: mode || "remote", time: Date.now() };
469
- notifyListeners({
470
- type: "activity",
471
- sessionId,
472
- ...lastActivity
473
- });
474
- },
475
- sessionEnd: async () => {
476
- lastActivity = { active: false, thinking: false, mode: "remote", time: Date.now() };
477
- notifyListeners({
478
- type: "activity",
479
- sessionId,
480
- ...lastActivity
481
- });
482
- },
483
- // ── Activity State Query ──
484
- getActivityState: async () => {
485
- return { ...lastActivity, sessionId };
486
- },
487
- // ── File Operations (optional) ──
488
- readFile: async (path) => {
489
- if (!callbacks.onReadFile) throw new Error("readFile not supported");
490
- return await callbacks.onReadFile(path);
491
- },
492
- writeFile: async (path, content) => {
493
- if (!callbacks.onWriteFile) throw new Error("writeFile not supported");
494
- await callbacks.onWriteFile(path, content);
495
- return { success: true };
496
- },
497
- listDirectory: async (path) => {
498
- if (!callbacks.onListDirectory) throw new Error("listDirectory not supported");
499
- return await callbacks.onListDirectory(path);
500
- },
501
- bash: async (command, cwd) => {
502
- if (!callbacks.onBash) throw new Error("bash not supported");
503
- return await callbacks.onBash(command, cwd);
504
- },
505
- ripgrep: async (args, cwd) => {
506
- if (!callbacks.onRipgrep) throw new Error("ripgrep not supported");
507
- try {
508
- const stdout = await callbacks.onRipgrep(args, cwd);
509
- return { success: true, stdout, stderr: "", exitCode: 0 };
510
- } catch (err) {
511
- return { success: false, stdout: "", stderr: err.message || "", exitCode: 1, error: err.message };
512
- }
513
- },
514
- getDirectoryTree: async (path, maxDepth) => {
515
- if (!callbacks.onGetDirectoryTree) throw new Error("getDirectoryTree not supported");
516
- return await callbacks.onGetDirectoryTree(path, maxDepth ?? 3);
517
- },
518
- // ── Listener Registration ──
519
- registerListener: async (callback) => {
520
- listeners.push(callback);
521
- console.log(`[HYPHA SESSION ${sessionId}] Listener registered (total: ${listeners.length}), replaying ${messages.length} messages`);
522
- for (const msg of messages) {
523
- try {
524
- const result = callback.onUpdate({
525
- type: "new-message",
526
- sessionId,
527
- message: msg
528
- });
529
- if (result && typeof result.catch === "function") {
530
- result.catch((err) => {
531
- console.error(`[HYPHA SESSION ${sessionId}] Replay listener error:`, err);
532
- });
533
- }
534
- } catch (err) {
535
- console.error(`[HYPHA SESSION ${sessionId}] Replay listener error:`, err);
536
- }
537
- }
538
- try {
539
- const result = callback.onUpdate({
540
- type: "update-session",
541
- sessionId,
542
- metadata: { value: metadata, version: metadataVersion },
543
- agentState: { value: agentState, version: agentStateVersion }
544
- });
545
- if (result && typeof result.catch === "function") {
546
- result.catch(() => {
547
- });
548
- }
549
- } catch {
550
- }
551
- try {
552
- const result = callback.onUpdate({
553
- type: "activity",
554
- sessionId,
555
- ...lastActivity
556
- });
557
- if (result && typeof result.catch === "function") {
558
- result.catch(() => {
559
- });
560
- }
561
- } catch {
562
- }
563
- return { success: true, listenerId: listeners.length - 1 };
564
- }
565
- },
566
- { overwrite: true }
567
- );
568
- console.log(`[HYPHA SESSION] Session service registered: ${serviceInfo.id}`);
569
- return {
570
- serviceInfo,
571
- pushMessage,
572
- get _agentState() {
573
- return agentState;
574
- },
575
- updateMetadata: (newMetadata) => {
576
- metadata = newMetadata;
577
- metadataVersion++;
578
- notifyListeners({
579
- type: "update-session",
580
- sessionId,
581
- metadata: { value: metadata, version: metadataVersion }
582
- });
583
- },
584
- updateAgentState: (newAgentState) => {
585
- agentState = newAgentState;
586
- agentStateVersion++;
587
- notifyListeners({
588
- type: "update-session",
589
- sessionId,
590
- agentState: { value: agentState, version: agentStateVersion }
591
- });
592
- },
593
- sendKeepAlive: (thinking, mode) => {
594
- lastActivity = { active: true, thinking: thinking || false, mode: mode || "remote", time: Date.now() };
595
- notifyListeners({
596
- type: "activity",
597
- sessionId,
598
- ...lastActivity
599
- });
600
- },
601
- sendSessionEnd: () => {
602
- lastActivity = { active: false, thinking: false, mode: "remote", time: Date.now() };
603
- notifyListeners({
604
- type: "activity",
605
- sessionId,
606
- ...lastActivity
607
- });
608
- },
609
- disconnect: async () => {
610
- await server.unregisterService(serviceInfo.id);
611
- }
612
- };
613
- }
614
-
615
- async function registerDebugService(server, machineId, deps) {
616
- const serviceInfo = await server.registerService(
617
- {
618
- id: `svamp-debug-${machineId}`,
619
- name: `Svamp Debug ${machineId.slice(0, 8)}`,
620
- type: "svamp-debug",
621
- config: { visibility: "public" },
622
- healthCheck: async () => ({
623
- ok: true,
624
- machineId,
625
- uptime: process.uptime(),
626
- timestamp: Date.now()
627
- }),
628
- getSessionStates: async () => {
629
- const sessions = deps.getTrackedSessions();
630
- const states = [];
631
- for (const s of sessions) {
632
- let activityState = null;
633
- try {
634
- const svc = deps.getSessionService(s.sessionId);
635
- if (svc) {
636
- activityState = await svc.getActivityState?.();
637
- }
638
- } catch {
639
- }
640
- states.push({
641
- sessionId: s.sessionId,
642
- active: s.active,
643
- pid: s.pid,
644
- startedBy: s.startedBy,
645
- directory: s.directory,
646
- activityState
647
- });
648
- }
649
- return states;
650
- },
651
- getMachineInfo: async () => ({
652
- machineId,
653
- hostname: (await import('os')).hostname(),
654
- platform: (await import('os')).platform(),
655
- uptime: process.uptime(),
656
- sessions: deps.getTrackedSessions().length
657
- }),
658
- // ── Artifact Sync RPCs ──
659
- getArtifactSyncStatus: async () => {
660
- const sync = deps.getArtifactSync?.();
661
- if (!sync) return { error: "Artifact sync not available" };
662
- return sync.getStatus();
663
- },
664
- forceSyncAll: async () => {
665
- const sync = deps.getArtifactSync?.();
666
- const sessionsDir = deps.getSessionsDir?.();
667
- if (!sync || !sessionsDir) return { error: "Artifact sync not available" };
668
- await sync.syncAll(sessionsDir, machineId);
669
- return { success: true, status: sync.getStatus() };
670
- },
671
- listRemoteSessions: async () => {
672
- const sync = deps.getArtifactSync?.();
673
- if (!sync) return [];
674
- return await sync.listRemoteSessions();
675
- }
676
- },
677
- { overwrite: true }
678
- );
679
- return {
680
- disconnect: async () => {
681
- await server.unregisterService(serviceInfo.id);
682
- }
683
- };
684
- }
685
-
686
- const COLLECTION_ALIAS = "svamp-agent-sessions";
687
- class SessionArtifactSync {
688
- server;
689
- artifactManager = null;
690
- collectionId = null;
691
- initialized = false;
692
- syncing = false;
693
- lastSyncAt = null;
694
- syncedSessions = /* @__PURE__ */ new Set();
695
- error = null;
696
- syncTimers = /* @__PURE__ */ new Map();
697
- log;
698
- constructor(server, log) {
699
- this.server = server;
700
- this.log = log;
701
- }
702
- async init() {
703
- try {
704
- this.artifactManager = await this.server.getService("public/artifact-manager");
705
- if (!this.artifactManager) {
706
- this.log("[ARTIFACT SYNC] Artifact manager service not available");
707
- this.error = "Artifact manager not available";
708
- return;
709
- }
710
- await this.ensureCollection();
711
- this.initialized = true;
712
- this.log("[ARTIFACT SYNC] Initialized successfully");
713
- } catch (err) {
714
- this.error = `Init failed: ${err.message}`;
715
- this.log(`[ARTIFACT SYNC] Init failed: ${err.message}`);
716
- }
717
- }
718
- async ensureCollection() {
719
- try {
720
- const existing = await this.artifactManager.read({
721
- artifact_id: COLLECTION_ALIAS,
722
- _rkwargs: true
723
- });
724
- this.collectionId = existing.id;
725
- this.log(`[ARTIFACT SYNC] Found existing collection: ${this.collectionId}`);
726
- } catch {
727
- const collection = await this.artifactManager.create({
728
- alias: COLLECTION_ALIAS,
729
- type: "collection",
730
- manifest: {
731
- name: "Svamp Agent Sessions",
732
- description: "Cloud-persisted session data for cross-machine continuity"
733
- },
734
- _rkwargs: true
735
- });
736
- this.collectionId = collection.id;
737
- await this.artifactManager.commit({
738
- artifact_id: this.collectionId,
739
- _rkwargs: true
740
- });
741
- this.log(`[ARTIFACT SYNC] Created new collection: ${this.collectionId}`);
742
- }
743
- }
744
- /**
745
- * Upload a file to an artifact using the presigned URL pattern:
746
- * 1. put_file() returns a presigned upload URL
747
- * 2. HTTP PUT the content to that URL
748
- */
749
- async uploadFile(artifactId, filePath, content) {
750
- const putUrl = await this.artifactManager.put_file({
751
- artifact_id: artifactId,
752
- file_path: filePath,
753
- _rkwargs: true
754
- });
755
- if (!putUrl || typeof putUrl !== "string") {
756
- throw new Error(`put_file returned invalid URL for ${filePath}: ${putUrl}`);
757
- }
758
- const resp = await fetch(putUrl, {
759
- method: "PUT",
760
- body: content,
761
- headers: { "Content-Type": "application/octet-stream" }
762
- });
763
- if (!resp.ok) {
764
- throw new Error(`Upload failed for ${filePath}: ${resp.status} ${resp.statusText}`);
765
- }
766
- }
767
- /**
768
- * Download a file from an artifact using the presigned URL pattern:
769
- * 1. get_file() returns a presigned download URL
770
- * 2. HTTP GET the content from that URL
771
- */
772
- async downloadFile(artifactId, filePath) {
773
- const getUrl = await this.artifactManager.get_file({
774
- artifact_id: artifactId,
775
- file_path: filePath,
776
- _rkwargs: true
777
- });
778
- if (!getUrl || typeof getUrl !== "string") return null;
779
- const resp = await fetch(getUrl);
780
- if (!resp.ok) return null;
781
- return await resp.text();
782
- }
783
- /**
784
- * Sync a session's metadata and messages to the artifact store.
785
- * Creates the artifact if it doesn't exist, updates if it does.
786
- */
787
- async syncSession(sessionId, sessionsDir, metadata, machineId) {
788
- if (!this.initialized || !this.artifactManager || !this.collectionId) {
789
- this.log(`[ARTIFACT SYNC] Not initialized, skipping sync for ${sessionId}`);
790
- return;
791
- }
792
- this.syncing = true;
793
- try {
794
- const artifactAlias = `session-${sessionId}`;
795
- const sessionJsonPath = join(sessionsDir, "session.json");
796
- const messagesPath = join(sessionsDir, "messages.jsonl");
797
- const sessionData = existsSync(sessionJsonPath) ? JSON.parse(readFileSync(sessionJsonPath, "utf-8")) : null;
798
- const messagesExist = existsSync(messagesPath);
799
- const messageCount = messagesExist ? readFileSync(messagesPath, "utf-8").split("\n").filter((l) => l.trim()).length : 0;
800
- let artifactId;
801
- try {
802
- const existing = await this.artifactManager.read({
803
- artifact_id: artifactAlias,
804
- _rkwargs: true
805
- });
806
- artifactId = existing.id;
807
- await this.artifactManager.edit({
808
- artifact_id: artifactId,
809
- manifest: {
810
- sessionId,
811
- machineId,
812
- metadata,
813
- messageCount,
814
- lastSyncAt: Date.now(),
815
- ...sessionData || {}
816
- },
817
- _rkwargs: true
818
- });
819
- } catch {
820
- const artifact = await this.artifactManager.create({
821
- alias: artifactAlias,
822
- parent_id: this.collectionId,
823
- type: "session",
824
- manifest: {
825
- sessionId,
826
- machineId,
827
- metadata,
828
- messageCount,
829
- createdAt: Date.now(),
830
- lastSyncAt: Date.now(),
831
- ...sessionData || {}
832
- },
833
- _rkwargs: true
834
- });
835
- artifactId = artifact.id;
836
- }
837
- if (sessionData) {
838
- await this.uploadFile(artifactId, "session.json", JSON.stringify(sessionData, null, 2));
839
- }
840
- if (messagesExist) {
841
- const messagesContent = readFileSync(messagesPath, "utf-8");
842
- await this.uploadFile(artifactId, "messages.jsonl", messagesContent);
843
- }
844
- await this.artifactManager.commit({
845
- artifact_id: artifactId,
846
- _rkwargs: true
847
- });
848
- this.syncedSessions.add(sessionId);
849
- this.lastSyncAt = Date.now();
850
- this.log(`[ARTIFACT SYNC] Synced session ${sessionId} (${messageCount} messages)`);
851
- } catch (err) {
852
- this.error = `Sync failed for ${sessionId}: ${err.message}`;
853
- this.log(`[ARTIFACT SYNC] Sync failed for ${sessionId}: ${err.message}`);
854
- } finally {
855
- this.syncing = false;
856
- }
857
- }
858
- /**
859
- * Schedule a debounced sync for a session (e.g., on each new message).
860
- * Waits 30 seconds before syncing to batch multiple messages.
861
- */
862
- scheduleDebouncedSync(sessionId, sessionsDir, metadata, machineId, delayMs = 3e4) {
863
- const existing = this.syncTimers.get(sessionId);
864
- if (existing) clearTimeout(existing);
865
- const timer = setTimeout(() => {
866
- this.syncSession(sessionId, sessionsDir, metadata, machineId).catch(() => {
867
- });
868
- this.syncTimers.delete(sessionId);
869
- }, delayMs);
870
- this.syncTimers.set(sessionId, timer);
871
- }
872
- /**
873
- * Download a session from artifact store to local disk.
874
- */
875
- async downloadSession(sessionId, targetDir) {
876
- if (!this.initialized || !this.artifactManager) return null;
877
- try {
878
- const artifactAlias = `session-${sessionId}`;
879
- const artifact = await this.artifactManager.read({
880
- artifact_id: artifactAlias,
881
- _rkwargs: true
882
- });
883
- if (!existsSync(targetDir)) mkdirSync(targetDir, { recursive: true });
884
- try {
885
- const data = await this.downloadFile(artifact.id, "session.json");
886
- if (data) {
887
- writeFileSync(join(targetDir, "session.json"), data);
888
- }
889
- } catch {
890
- }
891
- try {
892
- const data = await this.downloadFile(artifact.id, "messages.jsonl");
893
- if (data) {
894
- writeFileSync(join(targetDir, "messages.jsonl"), data);
895
- }
896
- } catch {
897
- }
898
- return {
899
- sessionData: artifact.manifest,
900
- messageCount: artifact.manifest?.messageCount || 0
901
- };
902
- } catch (err) {
903
- this.log(`[ARTIFACT SYNC] Download failed for ${sessionId}: ${err.message}`);
904
- return null;
905
- }
906
- }
907
- /**
908
- * List all sessions stored in the artifact collection.
909
- */
910
- async listRemoteSessions() {
911
- if (!this.initialized || !this.artifactManager || !this.collectionId) return [];
912
- try {
913
- const children = await this.artifactManager.list({
914
- parent_id: this.collectionId,
915
- _rkwargs: true
916
- });
917
- return (children || []).map((child) => ({
918
- sessionId: child.manifest?.sessionId || child.alias?.replace("session-", ""),
919
- machineId: child.manifest?.machineId,
920
- messageCount: child.manifest?.messageCount || 0,
921
- lastSyncAt: child.manifest?.lastSyncAt || 0
922
- }));
923
- } catch (err) {
924
- this.log(`[ARTIFACT SYNC] List failed: ${err.message}`);
925
- return [];
926
- }
927
- }
928
- /**
929
- * Get current sync status.
930
- */
931
- getStatus() {
932
- return {
933
- initialized: this.initialized,
934
- collectionId: this.collectionId,
935
- lastSyncAt: this.lastSyncAt,
936
- syncing: this.syncing,
937
- syncedSessions: [...this.syncedSessions],
938
- error: this.error
939
- };
940
- }
941
- /**
942
- * Force sync all known sessions using the session index.
943
- * @param svampHome The ~/.svamp/ directory (reads sessions-index.json)
944
- */
945
- async syncAll(svampHome, machineId) {
946
- if (!this.initialized) return;
947
- const indexFile = join(svampHome, "sessions-index.json");
948
- if (!existsSync(indexFile)) return;
949
- try {
950
- const index = JSON.parse(readFileSync(indexFile, "utf-8"));
951
- for (const [sessionId, entry] of Object.entries(index)) {
952
- const sessionDir = join(entry.directory, ".svamp", sessionId);
953
- if (existsSync(join(sessionDir, "session.json"))) {
954
- await this.syncSession(sessionId, sessionDir, void 0, machineId);
955
- }
956
- }
957
- } catch {
958
- }
959
- }
960
- /**
961
- * Cleanup timers on shutdown.
962
- */
963
- destroy() {
964
- for (const timer of this.syncTimers.values()) {
965
- clearTimeout(timer);
966
- }
967
- this.syncTimers.clear();
968
- }
969
- }
970
-
971
- const DEFAULT_TIMEOUTS = {
972
- init: 6e4,
973
- toolCall: 12e4,
974
- think: 3e4
975
- };
976
- class DefaultTransport {
977
- agentName;
978
- constructor(agentName = "generic-acp") {
979
- this.agentName = agentName;
980
- }
981
- getInitTimeout() {
982
- return DEFAULT_TIMEOUTS.init;
983
- }
984
- filterStdoutLine(line) {
985
- const trimmed = line.trim();
986
- if (!trimmed) return null;
987
- if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) return null;
988
- try {
989
- const parsed = JSON.parse(trimmed);
990
- if (typeof parsed !== "object" || parsed === null) return null;
991
- return line;
992
- } catch {
993
- return null;
994
- }
995
- }
996
- handleStderr(_text, _context) {
997
- return { message: null };
998
- }
999
- getToolPatterns() {
1000
- return [];
1001
- }
1002
- isInvestigationTool(_toolCallId, _toolKind) {
1003
- return false;
1004
- }
1005
- getToolCallTimeout(_toolCallId, toolKind) {
1006
- if (toolKind === "think") return DEFAULT_TIMEOUTS.think;
1007
- return DEFAULT_TIMEOUTS.toolCall;
1008
- }
1009
- extractToolNameFromId(_toolCallId) {
1010
- return null;
1011
- }
1012
- determineToolName(toolName, _toolCallId, _input, _context) {
1013
- return toolName;
1014
- }
1015
- }
1016
-
1017
- var DefaultTransport$1 = /*#__PURE__*/Object.freeze({
1018
- __proto__: null,
1019
- DefaultTransport: DefaultTransport
1020
- });
1021
-
1022
- const DEFAULT_IDLE_TIMEOUT_MS = 500;
1023
- const DEFAULT_TOOL_CALL_TIMEOUT_MS = 12e4;
1024
- function parseArgsFromContent(content) {
1025
- if (Array.isArray(content)) return { items: content };
1026
- if (content && typeof content === "object" && content !== null) {
1027
- return content;
1028
- }
1029
- return {};
1030
- }
1031
- function extractErrorDetail(content) {
1032
- if (!content) return void 0;
1033
- if (typeof content === "string") return content;
1034
- if (typeof content === "object" && content !== null && !Array.isArray(content)) {
1035
- const obj = content;
1036
- if (obj.error) {
1037
- const error = obj.error;
1038
- if (typeof error === "string") return error;
1039
- if (error && typeof error === "object" && "message" in error) {
1040
- const errObj = error;
1041
- if (typeof errObj.message === "string") return errObj.message;
1042
- }
1043
- return JSON.stringify(error);
1044
- }
1045
- if (typeof obj.message === "string") return obj.message;
1046
- const status = typeof obj.status === "string" ? obj.status : void 0;
1047
- const reason = typeof obj.reason === "string" ? obj.reason : void 0;
1048
- return status || reason || JSON.stringify(obj).substring(0, 500);
1049
- }
1050
- return void 0;
1051
- }
1052
- function formatDuration(startTime) {
1053
- if (!startTime) return "unknown";
1054
- const duration = Date.now() - startTime;
1055
- return `${(duration / 1e3).toFixed(2)}s`;
1056
- }
1057
- function handleAgentMessageChunk(update, ctx) {
1058
- const content = update.content;
1059
- if (!content || typeof content !== "object" || !("text" in content)) {
1060
- return { handled: false };
1061
- }
1062
- const text = content.text;
1063
- if (typeof text !== "string") return { handled: false };
1064
- const isThinking = /^\*\*[^*]+\*\*\n/.test(text);
1065
- if (isThinking) {
1066
- ctx.emit({ type: "event", name: "thinking", payload: { text, streaming: true } });
1067
- } else {
1068
- ctx.emit({ type: "model-output", textDelta: text });
1069
- ctx.clearIdleTimeout();
1070
- const idleTimeoutMs = ctx.transport.getIdleTimeout?.() ?? DEFAULT_IDLE_TIMEOUT_MS;
1071
- ctx.setIdleTimeout(() => {
1072
- if (ctx.activeToolCalls.size === 0) {
1073
- ctx.emitIdleStatus();
1074
- }
1075
- }, idleTimeoutMs);
1076
- }
1077
- return { handled: true };
1078
- }
1079
- function handleAgentThoughtChunk(update, ctx) {
1080
- const content = update.content;
1081
- if (!content || typeof content !== "object" || !("text" in content)) {
1082
- return { handled: false };
1083
- }
1084
- const text = content.text;
1085
- if (typeof text !== "string") return { handled: false };
1086
- ctx.emit({ type: "event", name: "thinking", payload: { text, streaming: true } });
1087
- return { handled: true };
1088
- }
1089
- function startToolCall(toolCallId, toolKind, update, ctx, source) {
1090
- const startTime = Date.now();
1091
- const toolKindStr = typeof toolKind === "string" ? toolKind : void 0;
1092
- const isInvestigation = ctx.transport.isInvestigationTool?.(toolCallId, toolKindStr) ?? false;
1093
- const extractedName = ctx.transport.extractToolNameFromId?.(toolCallId);
1094
- const realToolName = extractedName ?? (toolKindStr || "unknown");
1095
- ctx.toolCallIdToNameMap.set(toolCallId, realToolName);
1096
- ctx.activeToolCalls.add(toolCallId);
1097
- ctx.toolCallStartTimes.set(toolCallId, startTime);
1098
- ctx.log(`Tool call START: ${toolCallId} (${toolKind} -> ${realToolName})${isInvestigation ? " [INVESTIGATION]" : ""} (from ${source})`);
1099
- const timeoutMs = ctx.transport.getToolCallTimeout?.(toolCallId, toolKindStr) ?? DEFAULT_TOOL_CALL_TIMEOUT_MS;
1100
- if (!ctx.toolCallTimeouts.has(toolCallId)) {
1101
- const timeout = setTimeout(() => {
1102
- ctx.activeToolCalls.delete(toolCallId);
1103
- ctx.toolCallStartTimes.delete(toolCallId);
1104
- ctx.toolCallTimeouts.delete(toolCallId);
1105
- ctx.log(`Tool call TIMEOUT: ${toolCallId} (${toolKind}) after ${(timeoutMs / 1e3).toFixed(0)}s`);
1106
- if (ctx.activeToolCalls.size === 0) {
1107
- ctx.emitIdleStatus();
1108
- }
1109
- }, timeoutMs);
1110
- ctx.toolCallTimeouts.set(toolCallId, timeout);
1111
- }
1112
- ctx.clearIdleTimeout();
1113
- ctx.emit({ type: "status", status: "running" });
1114
- const args = parseArgsFromContent(update.content);
1115
- if (update.locations && Array.isArray(update.locations)) {
1116
- args.locations = update.locations;
1117
- }
1118
- ctx.emit({
1119
- type: "tool-call",
1120
- toolName: toolKindStr || "unknown",
1121
- args,
1122
- callId: toolCallId
1123
- });
1124
- }
1125
- function completeToolCall(toolCallId, toolKind, content, ctx) {
1126
- const startTime = ctx.toolCallStartTimes.get(toolCallId);
1127
- const duration = formatDuration(startTime);
1128
- const toolKindStr = typeof toolKind === "string" ? toolKind : "unknown";
1129
- ctx.activeToolCalls.delete(toolCallId);
1130
- ctx.toolCallStartTimes.delete(toolCallId);
1131
- const timeout = ctx.toolCallTimeouts.get(toolCallId);
1132
- if (timeout) {
1133
- clearTimeout(timeout);
1134
- ctx.toolCallTimeouts.delete(toolCallId);
1135
- }
1136
- ctx.log(`Tool call COMPLETED: ${toolCallId} (${toolKindStr}) - ${duration}. Active: ${ctx.activeToolCalls.size}`);
1137
- ctx.emit({ type: "tool-result", toolName: toolKindStr, result: content, callId: toolCallId });
1138
- if (ctx.activeToolCalls.size === 0) {
1139
- ctx.clearIdleTimeout();
1140
- ctx.emitIdleStatus();
1141
- }
1142
- }
1143
- function failToolCall(toolCallId, status, toolKind, content, ctx) {
1144
- const startTime = ctx.toolCallStartTimes.get(toolCallId);
1145
- const duration = formatDuration(startTime);
1146
- const toolKindStr = typeof toolKind === "string" ? toolKind : "unknown";
1147
- ctx.activeToolCalls.delete(toolCallId);
1148
- ctx.toolCallStartTimes.delete(toolCallId);
1149
- const timeout = ctx.toolCallTimeouts.get(toolCallId);
1150
- if (timeout) {
1151
- clearTimeout(timeout);
1152
- ctx.toolCallTimeouts.delete(toolCallId);
1153
- }
1154
- const errorDetail = extractErrorDetail(content);
1155
- ctx.log(`Tool call ${status.toUpperCase()}: ${toolCallId} (${toolKindStr}) - ${duration}. Active: ${ctx.activeToolCalls.size}`);
1156
- ctx.emit({
1157
- type: "tool-result",
1158
- toolName: toolKindStr,
1159
- result: errorDetail ? { error: errorDetail, status } : { error: `Tool call ${status}`, status },
1160
- callId: toolCallId
1161
- });
1162
- if (ctx.activeToolCalls.size === 0) {
1163
- ctx.clearIdleTimeout();
1164
- ctx.emitIdleStatus();
1165
- }
1166
- }
1167
- function handleToolCallUpdate(update, ctx) {
1168
- const status = update.status;
1169
- const toolCallId = update.toolCallId;
1170
- if (!toolCallId) return { handled: false };
1171
- const toolKind = update.kind || "unknown";
1172
- let toolCallCountSincePrompt = ctx.toolCallCountSincePrompt;
1173
- if (status === "in_progress" || status === "pending") {
1174
- if (!ctx.activeToolCalls.has(toolCallId)) {
1175
- toolCallCountSincePrompt++;
1176
- startToolCall(toolCallId, toolKind, update, ctx, "tool_call_update");
1177
- }
1178
- } else if (status === "completed") {
1179
- completeToolCall(toolCallId, toolKind, update.content, ctx);
1180
- } else if (status === "failed" || status === "cancelled") {
1181
- failToolCall(toolCallId, status, toolKind, update.content, ctx);
1182
- }
1183
- return { handled: true, toolCallCountSincePrompt };
1184
- }
1185
- function handleToolCall(update, ctx) {
1186
- const toolCallId = update.toolCallId;
1187
- const status = update.status;
1188
- const isInProgress = !status || status === "in_progress" || status === "pending";
1189
- if (!toolCallId || !isInProgress) return { handled: false };
1190
- if (ctx.activeToolCalls.has(toolCallId)) return { handled: true };
1191
- startToolCall(toolCallId, update.kind, update, ctx, "tool_call");
1192
- return { handled: true };
1193
- }
1194
- function handleLegacyMessageChunk(update, ctx) {
1195
- if (!update.messageChunk) return { handled: false };
1196
- const chunk = update.messageChunk;
1197
- if (chunk.textDelta) {
1198
- ctx.emit({ type: "model-output", textDelta: chunk.textDelta });
1199
- return { handled: true };
1200
- }
1201
- return { handled: false };
1202
- }
1203
- function handlePlanUpdate(update, ctx) {
1204
- if (!update.plan) return { handled: false };
1205
- ctx.emit({ type: "event", name: "plan", payload: update.plan });
1206
- return { handled: true };
1207
- }
1208
- function handleThinkingUpdate(update, ctx) {
1209
- if (!update.thinking) return { handled: false };
1210
- ctx.emit({ type: "event", name: "thinking", payload: update.thinking });
1211
- return { handled: true };
1212
- }
1213
-
1214
- function delay(ms) {
1215
- return new Promise((resolve) => setTimeout(resolve, ms));
1216
- }
1217
- const RETRY_CONFIG = {
1218
- maxAttempts: 3,
1219
- baseDelayMs: 1e3,
1220
- maxDelayMs: 5e3
1221
- };
1222
- function nodeToWebStreams(stdin, stdout) {
1223
- const writable = new WritableStream({
1224
- write(chunk) {
1225
- return new Promise((resolve, reject) => {
1226
- const ok = stdin.write(chunk, (err) => {
1227
- if (err) reject(err);
1228
- });
1229
- if (ok) resolve();
1230
- else stdin.once("drain", resolve);
1231
- });
1232
- },
1233
- close() {
1234
- return new Promise((resolve) => {
1235
- stdin.end(resolve);
1236
- });
1237
- },
1238
- abort(reason) {
1239
- stdin.destroy(reason instanceof Error ? reason : new Error(String(reason)));
1240
- }
1241
- });
1242
- const readable = new ReadableStream({
1243
- start(controller) {
1244
- stdout.on("data", (chunk) => {
1245
- controller.enqueue(new Uint8Array(chunk));
1246
- });
1247
- stdout.on("end", () => {
1248
- controller.close();
1249
- });
1250
- stdout.on("error", (err) => {
1251
- controller.error(err);
1252
- });
1253
- },
1254
- cancel() {
1255
- stdout.destroy();
1256
- }
1257
- });
1258
- return { writable, readable };
1259
- }
1260
- async function withRetry(operation, opts) {
1261
- let lastError = null;
1262
- const log = opts.log || (() => {
1263
- });
1264
- for (let attempt = 1; attempt <= opts.maxAttempts; attempt++) {
1265
- try {
1266
- return await operation();
1267
- } catch (error) {
1268
- if (error instanceof Error) {
1269
- lastError = error;
1270
- } else if (typeof error === "object" && error !== null) {
1271
- const obj = error;
1272
- const msg = typeof obj.message === "string" ? obj.message : JSON.stringify(error);
1273
- lastError = new Error(msg);
1274
- } else {
1275
- lastError = new Error(String(error));
1276
- }
1277
- const shouldRetry = opts.shouldRetry ? opts.shouldRetry(lastError) : true;
1278
- if (attempt < opts.maxAttempts && shouldRetry) {
1279
- const delayMs = Math.min(opts.baseDelayMs * Math.pow(2, attempt - 1), opts.maxDelayMs);
1280
- log(`${opts.operationName} failed (attempt ${attempt}/${opts.maxAttempts}): ${lastError.message}. Retrying in ${delayMs}ms...`);
1281
- await delay(delayMs);
1282
- } else {
1283
- break;
1284
- }
1285
- }
1286
- }
1287
- throw lastError;
1288
- }
1289
- class AcpBackend {
1290
- constructor(options) {
1291
- this.options = options;
1292
- this.transport = options.transportHandler ?? new DefaultTransport(options.agentName);
1293
- this.log = options.log || ((...args) => {
1294
- });
1295
- }
1296
- listeners = [];
1297
- process = null;
1298
- connection = null;
1299
- acpSessionId = null;
1300
- disposed = false;
1301
- activeToolCalls = /* @__PURE__ */ new Set();
1302
- toolCallTimeouts = /* @__PURE__ */ new Map();
1303
- toolCallStartTimes = /* @__PURE__ */ new Map();
1304
- toolCallIdToNameMap = /* @__PURE__ */ new Map();
1305
- recentPromptHadChangeTitle = false;
1306
- toolCallCountSincePrompt = 0;
1307
- idleTimeout = null;
1308
- transport;
1309
- log;
1310
- // Promise resolver for waitForIdle
1311
- idleResolver = null;
1312
- waitingForResponse = false;
1313
- onMessage(handler) {
1314
- this.listeners.push(handler);
1315
- }
1316
- offMessage(handler) {
1317
- const index = this.listeners.indexOf(handler);
1318
- if (index !== -1) this.listeners.splice(index, 1);
1319
- }
1320
- emit(msg) {
1321
- if (this.disposed) return;
1322
- for (const listener of this.listeners) {
1323
- try {
1324
- listener(msg);
1325
- } catch {
1326
- }
1327
- }
1328
- }
1329
- /** Get the underlying child process (for cleanup) */
1330
- getProcess() {
1331
- return this.process;
1332
- }
1333
- async startSession(initialPrompt) {
1334
- if (this.disposed) throw new Error("Backend has been disposed");
1335
- const sessionId = randomUUID();
1336
- this.emit({ type: "status", status: "starting" });
1337
- let startupStatusErrorEmitted = false;
1338
- try {
1339
- const args = this.options.args || [];
1340
- if (process.platform === "win32") {
1341
- const fullCommand = [this.options.command, ...args].join(" ");
1342
- this.process = spawn("cmd.exe", ["/c", fullCommand], {
1343
- cwd: this.options.cwd,
1344
- env: { ...process.env, ...this.options.env },
1345
- stdio: ["pipe", "pipe", "pipe"],
1346
- windowsHide: true
1347
- });
1348
- } else {
1349
- this.process = spawn(this.options.command, args, {
1350
- cwd: this.options.cwd,
1351
- env: { ...process.env, ...this.options.env },
1352
- stdio: ["pipe", "pipe", "pipe"]
1353
- });
1354
- }
1355
- if (!this.process.stdin || !this.process.stdout || !this.process.stderr) {
1356
- throw new Error("Failed to create stdio pipes");
1357
- }
1358
- let startupFailure = null;
1359
- let startupFailureSettled = false;
1360
- let rejectStartupFailure = null;
1361
- const startupFailurePromise = new Promise((_, reject) => {
1362
- rejectStartupFailure = (error) => {
1363
- if (startupFailureSettled) return;
1364
- startupFailureSettled = true;
1365
- startupFailure = error;
1366
- reject(error);
1367
- };
1368
- });
1369
- const signalStartupFailure = (error) => {
1370
- rejectStartupFailure?.(error);
1371
- };
1372
- this.process.stderr.on("data", (data) => {
1373
- const text = data.toString();
1374
- if (!text.trim()) return;
1375
- const hasActiveInvestigation = this.transport.isInvestigationTool ? Array.from(this.activeToolCalls).some((id) => this.transport.isInvestigationTool(id)) : false;
1376
- const context = {
1377
- activeToolCalls: this.activeToolCalls,
1378
- hasActiveInvestigation
1379
- };
1380
- this.log(`[ACP] stderr: ${text.trim()}`);
1381
- if (this.transport.handleStderr) {
1382
- const result = this.transport.handleStderr(text, context);
1383
- if (result.message) this.emit(result.message);
1384
- }
1385
- });
1386
- this.process.on("error", (err) => {
1387
- signalStartupFailure(err);
1388
- this.log(`[ACP] Process error: ${err.message}`);
1389
- startupStatusErrorEmitted = true;
1390
- this.emit({ type: "status", status: "error", detail: err.message });
1391
- });
1392
- this.process.on("exit", (code, signal) => {
1393
- if (!this.disposed && code !== 0 && code !== null) {
1394
- signalStartupFailure(new Error(`Exit code: ${code}`));
1395
- this.log(`[ACP] Process exited: code=${code}, signal=${signal}`);
1396
- this.emit({ type: "status", status: "stopped", detail: `Exit code: ${code}` });
1397
- }
1398
- });
1399
- const streams = nodeToWebStreams(this.process.stdin, this.process.stdout);
1400
- const transport = this.transport;
1401
- const logFn = this.log;
1402
- const filteredReadable = new ReadableStream({
1403
- async start(controller) {
1404
- const reader = streams.readable.getReader();
1405
- const decoder = new TextDecoder();
1406
- const encoder = new TextEncoder();
1407
- let buffer = "";
1408
- let filteredCount = 0;
1409
- try {
1410
- while (true) {
1411
- const { done, value } = await reader.read();
1412
- if (done) {
1413
- if (buffer.trim()) {
1414
- const filtered = transport.filterStdoutLine?.(buffer);
1415
- if (filtered === void 0) controller.enqueue(encoder.encode(buffer));
1416
- else if (filtered !== null) controller.enqueue(encoder.encode(filtered));
1417
- else filteredCount++;
1418
- }
1419
- if (filteredCount > 0) {
1420
- logFn(`[ACP] Filtered ${filteredCount} non-JSON lines from ${transport.agentName} stdout`);
1421
- }
1422
- controller.close();
1423
- break;
1424
- }
1425
- buffer += decoder.decode(value, { stream: true });
1426
- const lines = buffer.split("\n");
1427
- buffer = lines.pop() || "";
1428
- for (const line of lines) {
1429
- if (!line.trim()) continue;
1430
- const filtered = transport.filterStdoutLine?.(line);
1431
- if (filtered === void 0) controller.enqueue(encoder.encode(line + "\n"));
1432
- else if (filtered !== null) controller.enqueue(encoder.encode(filtered + "\n"));
1433
- else filteredCount++;
1434
- }
1435
- }
1436
- } catch (error) {
1437
- controller.error(error);
1438
- } finally {
1439
- reader.releaseLock();
1440
- }
1441
- }
1442
- });
1443
- const stream = ndJsonStream(streams.writable, filteredReadable);
1444
- const client = {
1445
- sessionUpdate: async (params) => {
1446
- this.handleSessionUpdate(params);
1447
- },
1448
- requestPermission: async (params) => {
1449
- const extendedParams = params;
1450
- const toolCall = extendedParams.toolCall;
1451
- let toolName = toolCall?.kind || toolCall?.toolName || extendedParams.kind || "Unknown tool";
1452
- const toolCallId = toolCall?.id || randomUUID();
1453
- const permissionId = toolCallId;
1454
- let input = {};
1455
- if (toolCall) {
1456
- input = toolCall.input || toolCall.arguments || toolCall.content || {};
1457
- } else {
1458
- input = extendedParams.input || extendedParams.arguments || extendedParams.content || {};
1459
- }
1460
- const context = {
1461
- recentPromptHadChangeTitle: this.recentPromptHadChangeTitle,
1462
- toolCallCountSincePrompt: this.toolCallCountSincePrompt
1463
- };
1464
- toolName = this.transport.determineToolName?.(toolName, toolCallId, input, context) ?? toolName;
1465
- this.toolCallCountSincePrompt++;
1466
- const options = extendedParams.options || [];
1467
- this.log(`[ACP] Permission request: tool=${toolName}, toolCallId=${toolCallId}`);
1468
- this.emit({
1469
- type: "permission-request",
1470
- id: permissionId,
1471
- reason: toolName,
1472
- payload: {
1473
- ...params,
1474
- permissionId,
1475
- toolCallId,
1476
- toolName,
1477
- input,
1478
- options: options.map((opt) => ({
1479
- id: opt.optionId,
1480
- name: opt.name,
1481
- kind: opt.kind
1482
- }))
1483
- }
1484
- });
1485
- if (this.options.permissionHandler) {
1486
- try {
1487
- const result = await this.options.permissionHandler.handleToolCall(toolCallId, toolName, input);
1488
- let optionId = "cancel";
1489
- if (result.decision === "approved" || result.decision === "approved_for_session") {
1490
- const proceedOnceOption2 = options.find(
1491
- (opt) => opt.optionId === "proceed_once" || opt.name?.toLowerCase().includes("once")
1492
- );
1493
- const proceedAlwaysOption = options.find(
1494
- (opt) => opt.optionId === "proceed_always" || opt.name?.toLowerCase().includes("always")
1495
- );
1496
- if (result.decision === "approved_for_session" && proceedAlwaysOption) {
1497
- optionId = proceedAlwaysOption.optionId || "proceed_always";
1498
- } else if (proceedOnceOption2) {
1499
- optionId = proceedOnceOption2.optionId || "proceed_once";
1500
- } else if (options.length > 0) {
1501
- optionId = options[0].optionId || "proceed_once";
1502
- }
1503
- this.emit({
1504
- type: "tool-result",
1505
- toolName,
1506
- result: { status: "approved", decision: result.decision },
1507
- callId: permissionId
1508
- });
1509
- } else {
1510
- const cancelOption = options.find(
1511
- (opt) => opt.optionId === "cancel" || opt.name?.toLowerCase().includes("cancel")
1512
- );
1513
- if (cancelOption) optionId = cancelOption.optionId || "cancel";
1514
- this.emit({
1515
- type: "tool-result",
1516
- toolName,
1517
- result: { status: "denied", decision: result.decision },
1518
- callId: permissionId
1519
- });
1520
- }
1521
- return { outcome: { outcome: "selected", optionId } };
1522
- } catch (error) {
1523
- this.log("[ACP] Error in permission handler:", error);
1524
- return { outcome: { outcome: "selected", optionId: "cancel" } };
1525
- }
1526
- }
1527
- const proceedOnceOption = options.find(
1528
- (opt) => opt.optionId === "proceed_once" || typeof opt.name === "string" && opt.name.toLowerCase().includes("once")
1529
- );
1530
- const defaultOptionId = proceedOnceOption?.optionId || (options.length > 0 && options[0].optionId ? options[0].optionId : "proceed_once");
1531
- return { outcome: { outcome: "selected", optionId: defaultOptionId } };
1532
- }
1533
- };
1534
- this.connection = new ClientSideConnection(
1535
- (agent) => client,
1536
- stream
1537
- );
1538
- const initRequest = {
1539
- protocolVersion: 1,
1540
- clientCapabilities: {
1541
- fs: { readTextFile: false, writeTextFile: false }
1542
- },
1543
- clientInfo: { name: "svamp-cli", version: "0.1.0" }
1544
- };
1545
- const initTimeout = this.transport.getInitTimeout();
1546
- this.log(`[ACP] Initializing connection (timeout: ${initTimeout}ms)...`);
1547
- const isNonRetryableStartupError = (error) => {
1548
- const maybeErr = error;
1549
- if (startupFailure && error === startupFailure) return true;
1550
- if (maybeErr.code === "ENOENT" || maybeErr.code === "EACCES" || maybeErr.code === "EPIPE") return true;
1551
- const msg = error.message.toLowerCase();
1552
- if (msg.includes("api key") || msg.includes("not configured") || msg.includes("401") || msg.includes("403")) return true;
1553
- return false;
1554
- };
1555
- await withRetry(
1556
- async () => {
1557
- let timeoutHandle = null;
1558
- try {
1559
- const result = await Promise.race([
1560
- startupFailurePromise,
1561
- this.connection.initialize(initRequest).then((res) => {
1562
- if (timeoutHandle) {
1563
- clearTimeout(timeoutHandle);
1564
- timeoutHandle = null;
1565
- }
1566
- return res;
1567
- }),
1568
- new Promise((_, reject) => {
1569
- timeoutHandle = setTimeout(() => {
1570
- reject(new Error(`Initialize timeout after ${initTimeout}ms - ${this.transport.agentName} did not respond`));
1571
- }, initTimeout);
1572
- })
1573
- ]);
1574
- return result;
1575
- } finally {
1576
- if (timeoutHandle) clearTimeout(timeoutHandle);
1577
- }
1578
- },
1579
- {
1580
- operationName: "Initialize",
1581
- maxAttempts: RETRY_CONFIG.maxAttempts,
1582
- baseDelayMs: RETRY_CONFIG.baseDelayMs,
1583
- maxDelayMs: RETRY_CONFIG.maxDelayMs,
1584
- shouldRetry: (error) => !isNonRetryableStartupError(error),
1585
- log: this.log
1586
- }
1587
- );
1588
- this.log(`[ACP] Initialize completed`);
1589
- const mcpServers = this.options.mcpServers ? Object.entries(this.options.mcpServers).map(([name, config]) => {
1590
- if (config.type === "http" && config.url) {
1591
- return { name, url: config.url };
1592
- }
1593
- return {
1594
- name,
1595
- command: config.command || "",
1596
- args: config.args || [],
1597
- env: config.env ? Object.entries(config.env).map(([envName, envValue]) => ({ name: envName, value: envValue })) : []
1598
- };
1599
- }) : [];
1600
- const newSessionRequest = {
1601
- cwd: this.options.cwd,
1602
- mcpServers
1603
- };
1604
- this.log(`[ACP] Creating new session...`);
1605
- const sessionResponse = await withRetry(
1606
- async () => {
1607
- let timeoutHandle = null;
1608
- try {
1609
- const result = await Promise.race([
1610
- startupFailurePromise,
1611
- this.connection.newSession(newSessionRequest).then((res) => {
1612
- if (timeoutHandle) {
1613
- clearTimeout(timeoutHandle);
1614
- timeoutHandle = null;
1615
- }
1616
- return res;
1617
- }),
1618
- new Promise((_, reject) => {
1619
- timeoutHandle = setTimeout(() => {
1620
- reject(new Error(`New session timeout after ${initTimeout}ms - ${this.transport.agentName} did not respond`));
1621
- }, initTimeout);
1622
- })
1623
- ]);
1624
- return result;
1625
- } finally {
1626
- if (timeoutHandle) clearTimeout(timeoutHandle);
1627
- }
1628
- },
1629
- {
1630
- operationName: "NewSession",
1631
- maxAttempts: RETRY_CONFIG.maxAttempts,
1632
- baseDelayMs: RETRY_CONFIG.baseDelayMs,
1633
- maxDelayMs: RETRY_CONFIG.maxDelayMs,
1634
- shouldRetry: (error) => !isNonRetryableStartupError(error),
1635
- log: this.log
1636
- }
1637
- );
1638
- this.acpSessionId = sessionResponse.sessionId;
1639
- this.log(`[ACP] Session created: ${this.acpSessionId}`);
1640
- this.emitInitialSessionMetadata(sessionResponse);
1641
- this.emitIdleStatus();
1642
- if (initialPrompt) {
1643
- this.sendPrompt(sessionId, initialPrompt).catch((error) => {
1644
- this.log("[ACP] Error sending initial prompt:", error);
1645
- this.emit({ type: "status", status: "error", detail: String(error) });
1646
- });
1647
- }
1648
- return { sessionId };
1649
- } catch (error) {
1650
- this.log("[ACP] Error starting session:", error);
1651
- if (!startupStatusErrorEmitted) {
1652
- this.emit({
1653
- type: "status",
1654
- status: "error",
1655
- detail: error instanceof Error ? error.message : String(error)
1656
- });
1657
- }
1658
- throw error;
1659
- }
1660
- }
1661
- createHandlerContext() {
1662
- return {
1663
- transport: this.transport,
1664
- activeToolCalls: this.activeToolCalls,
1665
- toolCallStartTimes: this.toolCallStartTimes,
1666
- toolCallTimeouts: this.toolCallTimeouts,
1667
- toolCallIdToNameMap: this.toolCallIdToNameMap,
1668
- idleTimeout: this.idleTimeout,
1669
- toolCallCountSincePrompt: this.toolCallCountSincePrompt,
1670
- emit: (msg) => this.emit(msg),
1671
- emitIdleStatus: () => this.emitIdleStatus(),
1672
- clearIdleTimeout: () => {
1673
- if (this.idleTimeout) {
1674
- clearTimeout(this.idleTimeout);
1675
- this.idleTimeout = null;
1676
- }
1677
- },
1678
- setIdleTimeout: (callback, ms) => {
1679
- this.idleTimeout = setTimeout(() => {
1680
- callback();
1681
- this.idleTimeout = null;
1682
- }, ms);
1683
- },
1684
- log: this.log
1685
- };
1686
- }
1687
- emitInitialSessionMetadata(sessionResponse) {
1688
- if (Array.isArray(sessionResponse.configOptions)) {
1689
- this.emit({
1690
- type: "event",
1691
- name: "config_options_update",
1692
- payload: { configOptions: sessionResponse.configOptions }
1693
- });
1694
- }
1695
- if (sessionResponse.modes) {
1696
- this.emit({ type: "event", name: "modes_update", payload: sessionResponse.modes });
1697
- this.emit({ type: "event", name: "current_mode_update", payload: { currentModeId: sessionResponse.modes.currentModeId } });
1698
- }
1699
- if (sessionResponse.models) {
1700
- this.emit({ type: "event", name: "models_update", payload: sessionResponse.models });
1701
- }
1702
- }
1703
- handleSessionUpdate(params) {
1704
- const notification = params;
1705
- const update = notification.update;
1706
- if (!update) return;
1707
- const sessionUpdateType = update.sessionUpdate;
1708
- const updateType = sessionUpdateType;
1709
- this.log(`[ACP] sessionUpdate: ${sessionUpdateType}`);
1710
- const ctx = this.createHandlerContext();
1711
- if (sessionUpdateType === "agent_message_chunk") {
1712
- handleAgentMessageChunk(update, ctx);
1713
- return;
1714
- }
1715
- if (sessionUpdateType === "tool_call_update") {
1716
- const result = handleToolCallUpdate(update, ctx);
1717
- if (result.toolCallCountSincePrompt !== void 0) {
1718
- this.toolCallCountSincePrompt = result.toolCallCountSincePrompt;
1719
- }
1720
- return;
1721
- }
1722
- if (sessionUpdateType === "agent_thought_chunk") {
1723
- handleAgentThoughtChunk(update, ctx);
1724
- return;
1725
- }
1726
- if (sessionUpdateType === "tool_call") {
1727
- handleToolCall(update, ctx);
1728
- return;
1729
- }
1730
- if (sessionUpdateType === "available_commands_update") {
1731
- const commands = update.availableCommands;
1732
- if (Array.isArray(commands)) {
1733
- this.emit({ type: "event", name: "available_commands", payload: commands });
1734
- }
1735
- return;
1736
- }
1737
- if (updateType === "config_option_update" || updateType === "config_options_update") {
1738
- const configOptions = update.configOptions;
1739
- if (Array.isArray(configOptions)) {
1740
- this.emit({ type: "event", name: "config_options_update", payload: { configOptions } });
1741
- }
1742
- return;
1743
- }
1744
- if (updateType === "current_mode_update") {
1745
- const currentModeId = update.currentModeId;
1746
- if (typeof currentModeId === "string" && currentModeId.length > 0) {
1747
- this.emit({ type: "event", name: "current_mode_update", payload: { currentModeId } });
1748
- }
1749
- return;
1750
- }
1751
- handleLegacyMessageChunk(update, ctx);
1752
- handlePlanUpdate(update, ctx);
1753
- handleThinkingUpdate(update, ctx);
1754
- }
1755
- emitIdleStatus() {
1756
- this.emit({ type: "status", status: "idle" });
1757
- if (this.idleResolver) {
1758
- this.idleResolver();
1759
- }
1760
- }
1761
- async sendPrompt(sessionId, prompt) {
1762
- const promptHasChangeTitle = this.options.hasChangeTitleInstruction?.(prompt) ?? false;
1763
- this.toolCallCountSincePrompt = 0;
1764
- this.recentPromptHadChangeTitle = promptHasChangeTitle;
1765
- if (this.disposed) throw new Error("Backend has been disposed");
1766
- if (!this.connection || !this.acpSessionId) throw new Error("Session not started");
1767
- this.emit({ type: "status", status: "running" });
1768
- this.waitingForResponse = true;
1769
- try {
1770
- this.log(`[ACP] Sending prompt (length: ${prompt.length})`);
1771
- const contentBlock = { type: "text", text: prompt };
1772
- const promptRequest = {
1773
- sessionId: this.acpSessionId,
1774
- prompt: [contentBlock]
1775
- };
1776
- await this.connection.prompt(promptRequest);
1777
- this.log("[ACP] Prompt request sent");
1778
- } catch (error) {
1779
- this.log("[ACP] Error sending prompt:", error);
1780
- this.waitingForResponse = false;
1781
- let errorDetail;
1782
- if (error instanceof Error) {
1783
- errorDetail = error.message;
1784
- } else if (typeof error === "object" && error !== null) {
1785
- const errObj = error;
1786
- errorDetail = typeof errObj.message === "string" ? errObj.message : String(error);
1787
- } else {
1788
- errorDetail = String(error);
1789
- }
1790
- this.emit({ type: "status", status: "error", detail: errorDetail });
1791
- throw error;
1792
- }
1793
- }
1794
- async waitForResponseComplete(timeoutMs = 12e4) {
1795
- if (!this.waitingForResponse) return;
1796
- return new Promise((resolve, reject) => {
1797
- const timeout = setTimeout(() => {
1798
- this.idleResolver = null;
1799
- this.waitingForResponse = false;
1800
- reject(new Error("Timeout waiting for response to complete"));
1801
- }, timeoutMs);
1802
- this.idleResolver = () => {
1803
- clearTimeout(timeout);
1804
- this.idleResolver = null;
1805
- this.waitingForResponse = false;
1806
- resolve();
1807
- };
1808
- });
1809
- }
1810
- async cancel(sessionId) {
1811
- if (!this.connection || !this.acpSessionId) return;
1812
- try {
1813
- await this.connection.cancel({ sessionId: this.acpSessionId });
1814
- this.emit({ type: "status", status: "stopped", detail: "Cancelled by user" });
1815
- } catch (error) {
1816
- this.log("[ACP] Error cancelling:", error);
1817
- }
1818
- }
1819
- async respondToPermission(requestId, approved) {
1820
- this.log(`[ACP] Permission response (UI only): ${requestId} = ${approved}`);
1821
- this.emit({ type: "permission-response", id: requestId, approved });
1822
- }
1823
- async dispose() {
1824
- if (this.disposed) return;
1825
- this.log("[ACP] Disposing backend");
1826
- this.disposed = true;
1827
- if (this.connection && this.acpSessionId) {
1828
- try {
1829
- await Promise.race([
1830
- this.connection.cancel({ sessionId: this.acpSessionId }),
1831
- new Promise((resolve) => setTimeout(resolve, 2e3))
1832
- ]);
1833
- } catch {
1834
- }
1835
- }
1836
- if (this.process) {
1837
- this.process.kill("SIGTERM");
1838
- await new Promise((resolve) => {
1839
- const timeout = setTimeout(() => {
1840
- if (this.process) this.process.kill("SIGKILL");
1841
- resolve();
1842
- }, 1e3);
1843
- this.process?.once("exit", () => {
1844
- clearTimeout(timeout);
1845
- resolve();
1846
- });
1847
- });
1848
- this.process = null;
1849
- }
1850
- if (this.idleTimeout) {
1851
- clearTimeout(this.idleTimeout);
1852
- this.idleTimeout = null;
1853
- }
1854
- this.listeners = [];
1855
- this.connection = null;
1856
- this.acpSessionId = null;
1857
- this.activeToolCalls.clear();
1858
- for (const timeout of this.toolCallTimeouts.values()) clearTimeout(timeout);
1859
- this.toolCallTimeouts.clear();
1860
- this.toolCallStartTimes.clear();
1861
- }
1862
- }
1863
-
1864
- var acpBackend = /*#__PURE__*/Object.freeze({
1865
- __proto__: null,
1866
- AcpBackend: AcpBackend
1867
- });
1868
-
1869
- const KNOWN_ACP_AGENTS = {
1870
- gemini: { command: "gemini", args: ["--experimental-acp"] },
1871
- opencode: { command: "opencode", args: ["acp"] }
1872
- };
1873
- function resolveAcpAgentConfig(cliArgs) {
1874
- if (cliArgs.length === 0) {
1875
- throw new Error("Usage: svamp agent <agent-name> or svamp agent -- <command> [args]");
1876
- }
1877
- if (cliArgs[0] === "--") {
1878
- const command = cliArgs[1];
1879
- if (!command) {
1880
- throw new Error('Missing command after "--". Usage: svamp agent -- <command> [args]');
1881
- }
1882
- return {
1883
- agentName: command,
1884
- command,
1885
- args: cliArgs.slice(2)
1886
- };
1887
- }
1888
- const agentName = cliArgs[0];
1889
- const known = KNOWN_ACP_AGENTS[agentName];
1890
- if (known) {
1891
- const passthroughArgs = cliArgs.slice(1).filter((arg) => !(agentName === "opencode" && arg === "--acp"));
1892
- return {
1893
- agentName,
1894
- command: known.command,
1895
- args: [...known.args, ...passthroughArgs]
1896
- };
1897
- }
1898
- return {
1899
- agentName,
1900
- command: agentName,
1901
- args: cliArgs.slice(1)
1902
- };
1903
- }
1904
-
1905
- var acpAgentConfig = /*#__PURE__*/Object.freeze({
1906
- __proto__: null,
1907
- KNOWN_ACP_AGENTS: KNOWN_ACP_AGENTS,
1908
- resolveAcpAgentConfig: resolveAcpAgentConfig
1909
- });
1910
-
1911
- function bridgeAcpToSession(backend, sessionService, getMetadata, setMetadata, log, onTurnEnd) {
1912
- let pendingText = "";
1913
- let flushTimer = null;
1914
- function flushText() {
1915
- if (pendingText) {
1916
- sessionService.pushMessage({
1917
- type: "assistant",
1918
- content: [{ type: "text", text: pendingText }]
1919
- }, "agent");
1920
- pendingText = "";
1921
- }
1922
- if (flushTimer) {
1923
- clearTimeout(flushTimer);
1924
- flushTimer = null;
1925
- }
1926
- }
1927
- backend.onMessage((msg) => {
1928
- switch (msg.type) {
1929
- case "model-output": {
1930
- if (msg.textDelta) {
1931
- pendingText += msg.textDelta;
1932
- if (!flushTimer) {
1933
- flushTimer = setTimeout(flushText, 100);
1934
- }
1935
- } else if (msg.fullText) {
1936
- flushText();
1937
- sessionService.pushMessage({
1938
- type: "assistant",
1939
- content: [{ type: "text", text: msg.fullText }]
1940
- }, "agent");
1941
- }
1942
- break;
1943
- }
1944
- case "status": {
1945
- if (msg.status === "idle") {
1946
- flushText();
1947
- sessionService.sendKeepAlive(false);
1948
- setMetadata((m) => ({ ...m, lifecycleState: "idle" }));
1949
- onTurnEnd?.();
1950
- } else if (msg.status === "running" || msg.status === "starting") {
1951
- sessionService.sendKeepAlive(true);
1952
- setMetadata((m) => ({ ...m, lifecycleState: "running" }));
1953
- } else if (msg.status === "error") {
1954
- flushText();
1955
- sessionService.pushMessage({
1956
- type: "assistant",
1957
- content: [{ type: "text", text: `Error: ${msg.detail || "Unknown error"}` }]
1958
- }, "agent");
1959
- sessionService.sendKeepAlive(false);
1960
- setMetadata((m) => ({ ...m, lifecycleState: "error" }));
1961
- } else if (msg.status === "stopped") {
1962
- flushText();
1963
- sessionService.sendKeepAlive(false);
1964
- setMetadata((m) => ({ ...m, lifecycleState: "stopped" }));
1965
- }
1966
- break;
1967
- }
1968
- case "tool-call": {
1969
- flushText();
1970
- sessionService.pushMessage({
1971
- type: "assistant",
1972
- content: [{
1973
- type: "tool_use",
1974
- id: msg.callId,
1975
- name: msg.toolName,
1976
- input: msg.args
1977
- }]
1978
- }, "agent");
1979
- break;
1980
- }
1981
- case "tool-result": {
1982
- sessionService.pushMessage({
1983
- type: "assistant",
1984
- content: [{
1985
- type: "tool_result",
1986
- tool_use_id: msg.callId,
1987
- content: typeof msg.result === "string" ? msg.result : JSON.stringify(msg.result)
1988
- }]
1989
- }, "agent");
1990
- break;
1991
- }
1992
- case "permission-request": {
1993
- const currentRequests = { ...sessionService._agentState?.requests };
1994
- const payload = msg.payload;
1995
- sessionService.updateAgentState({
1996
- controlledByUser: false,
1997
- requests: {
1998
- ...currentRequests,
1999
- [msg.id]: {
2000
- tool: payload?.toolName || msg.reason,
2001
- arguments: payload?.input || {},
2002
- createdAt: Date.now()
2003
- }
2004
- }
2005
- });
2006
- break;
2007
- }
2008
- case "permission-response": {
2009
- const reqs = { ...sessionService._agentState?.requests };
2010
- const completedReqs = { ...sessionService._agentState?.completedRequests };
2011
- const existingReq = reqs[msg.id];
2012
- delete reqs[msg.id];
2013
- sessionService.updateAgentState({
2014
- controlledByUser: false,
2015
- requests: reqs,
2016
- completedRequests: {
2017
- ...completedReqs,
2018
- [msg.id]: {
2019
- ...existingReq || {},
2020
- completedAt: Date.now(),
2021
- status: msg.approved ? "approved" : "denied"
2022
- }
2023
- }
2024
- });
2025
- break;
2026
- }
2027
- case "event": {
2028
- if (msg.name === "thinking") {
2029
- const payload = msg.payload;
2030
- const text = payload?.text || JSON.stringify(payload);
2031
- sessionService.pushMessage({
2032
- type: "assistant",
2033
- content: [{ type: "thinking", thinking: text }]
2034
- }, "agent");
2035
- } else {
2036
- sessionService.pushMessage({
2037
- type: "session_event",
2038
- message: `[${msg.name}] ${JSON.stringify(msg.payload)}`
2039
- }, "session");
2040
- }
2041
- break;
2042
- }
2043
- }
2044
- });
2045
- }
2046
- class HyphaPermissionHandler {
2047
- constructor(shouldAutoAllow, log) {
2048
- this.shouldAutoAllow = shouldAutoAllow;
2049
- this.log = log;
2050
- }
2051
- pendingPermissions = /* @__PURE__ */ new Map();
2052
- async handleToolCall(toolCallId, toolName, input) {
2053
- if (this.shouldAutoAllow(toolName, input)) {
2054
- this.log(`[ACP Permission] Auto-allowing ${toolName}`);
2055
- return { decision: "approved" };
2056
- }
2057
- return new Promise((resolve) => {
2058
- this.pendingPermissions.set(toolCallId, { resolve, toolName, input });
2059
- });
2060
- }
2061
- /**
2062
- * Called from the session service's onPermissionResponse callback
2063
- */
2064
- resolvePermission(requestId, approved) {
2065
- const pending = this.pendingPermissions.get(requestId);
2066
- if (pending) {
2067
- this.pendingPermissions.delete(requestId);
2068
- pending.resolve({
2069
- decision: approved ? "approved" : "denied"
2070
- });
2071
- } else {
2072
- this.log(`[ACP Permission] No pending permission for id=${requestId}`);
2073
- }
2074
- }
2075
- /** Reject all pending permissions (e.g. when process exits) */
2076
- rejectAll(reason) {
2077
- for (const [id, pending] of this.pendingPermissions) {
2078
- pending.resolve({ decision: "denied" });
2079
- }
2080
- this.pendingPermissions.clear();
2081
- }
2082
- }
2083
-
2084
- const GEMINI_TIMEOUTS = {
2085
- init: 12e4,
2086
- toolCall: 12e4,
2087
- investigation: 6e5,
2088
- think: 3e4,
2089
- idle: 500
2090
- };
2091
- const GEMINI_TOOL_PATTERNS = [
2092
- {
2093
- name: "change_title",
2094
- patterns: ["change_title", "change-title", "svamp__change_title", "mcp__svamp__change_title"],
2095
- inputFields: ["title"],
2096
- emptyInputDefault: true
2097
- },
2098
- {
2099
- name: "set_session_link",
2100
- patterns: ["set_session_link", "set-session-link", "svamp__set_session_link", "mcp__svamp__set_session_link"],
2101
- inputFields: ["url"]
2102
- },
2103
- {
2104
- name: "save_memory",
2105
- patterns: ["save_memory", "save-memory"],
2106
- inputFields: ["memory", "content"]
2107
- },
2108
- {
2109
- name: "think",
2110
- patterns: ["think"],
2111
- inputFields: ["thought", "thinking"]
2112
- }
2113
- ];
2114
- const AVAILABLE_MODELS = [
2115
- "gemini-2.5-pro",
2116
- "gemini-2.5-flash",
2117
- "gemini-2.5-flash-lite"
2118
- ];
2119
- class GeminiTransport {
2120
- agentName = "gemini";
2121
- getInitTimeout() {
2122
- return GEMINI_TIMEOUTS.init;
2123
- }
2124
- filterStdoutLine(line) {
2125
- const trimmed = line.trim();
2126
- if (!trimmed) return null;
2127
- if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) return null;
2128
- try {
2129
- const parsed = JSON.parse(trimmed);
2130
- if (typeof parsed !== "object" || parsed === null) return null;
2131
- return line;
2132
- } catch {
2133
- return null;
2134
- }
2135
- }
2136
- handleStderr(text, context) {
2137
- const trimmed = text.trim();
2138
- if (!trimmed) return { message: null, suppress: true };
2139
- if (trimmed.includes("status 429") || trimmed.includes('code":429') || trimmed.includes("rateLimitExceeded") || trimmed.includes("RESOURCE_EXHAUSTED")) {
2140
- return { message: null, suppress: false };
2141
- }
2142
- if (trimmed.includes("status 404") || trimmed.includes('code":404')) {
2143
- const msg = {
2144
- type: "status",
2145
- status: "error",
2146
- detail: `Model not found. Available models: ${AVAILABLE_MODELS.join(", ")}`
2147
- };
2148
- return { message: msg };
2149
- }
2150
- if (context.hasActiveInvestigation) {
2151
- const hasError = trimmed.includes("timeout") || trimmed.includes("Timeout") || trimmed.includes("failed") || trimmed.includes("Failed") || trimmed.includes("error") || trimmed.includes("Error");
2152
- if (hasError) {
2153
- return { message: null, suppress: false };
2154
- }
2155
- }
2156
- return { message: null };
2157
- }
2158
- getToolPatterns() {
2159
- return GEMINI_TOOL_PATTERNS;
2160
- }
2161
- isInvestigationTool(toolCallId, toolKind) {
2162
- const lowerId = toolCallId.toLowerCase();
2163
- return lowerId.includes("codebase_investigator") || lowerId.includes("investigator") || typeof toolKind === "string" && toolKind.includes("investigator");
2164
- }
2165
- getToolCallTimeout(toolCallId, toolKind) {
2166
- if (this.isInvestigationTool(toolCallId, toolKind)) return GEMINI_TIMEOUTS.investigation;
2167
- if (toolKind === "think") return GEMINI_TIMEOUTS.think;
2168
- return GEMINI_TIMEOUTS.toolCall;
2169
- }
2170
- getIdleTimeout() {
2171
- return GEMINI_TIMEOUTS.idle;
2172
- }
2173
- extractToolNameFromId(toolCallId) {
2174
- const lowerId = toolCallId.toLowerCase();
2175
- for (const toolPattern of GEMINI_TOOL_PATTERNS) {
2176
- for (const pattern of toolPattern.patterns) {
2177
- if (lowerId.includes(pattern.toLowerCase())) {
2178
- return toolPattern.name;
2179
- }
2180
- }
2181
- }
2182
- return null;
2183
- }
2184
- isEmptyInput(input) {
2185
- if (!input) return true;
2186
- if (Array.isArray(input)) return input.length === 0;
2187
- if (typeof input === "object") return Object.keys(input).length === 0;
2188
- return false;
2189
- }
2190
- determineToolName(toolName, toolCallId, input, _context) {
2191
- if (toolName !== "other" && toolName !== "Unknown tool") return toolName;
2192
- const idToolName = this.extractToolNameFromId(toolCallId);
2193
- if (idToolName) return idToolName;
2194
- if (input && typeof input === "object" && !Array.isArray(input)) {
2195
- const inputKeys = Object.keys(input);
2196
- for (const toolPattern of GEMINI_TOOL_PATTERNS) {
2197
- if (toolPattern.inputFields) {
2198
- const hasMatchingField = toolPattern.inputFields.some(
2199
- (field) => inputKeys.some((key) => key.toLowerCase() === field.toLowerCase())
2200
- );
2201
- if (hasMatchingField) return toolPattern.name;
2202
- }
2203
- }
2204
- }
2205
- if (this.isEmptyInput(input) && toolName === "other") {
2206
- const defaultTool = GEMINI_TOOL_PATTERNS.find((p) => p.emptyInputDefault);
2207
- if (defaultTool) return defaultTool.name;
2208
- }
2209
- return toolName;
2210
- }
2211
- }
2212
-
2213
- var GeminiTransport$1 = /*#__PURE__*/Object.freeze({
2214
- __proto__: null,
2215
- GEMINI_TIMEOUTS: GEMINI_TIMEOUTS,
2216
- GeminiTransport: GeminiTransport
2217
- });
2218
-
2219
- const __filename$1 = fileURLToPath(import.meta.url);
2220
- const __dirname$1 = dirname(__filename$1);
2221
- function loadDotEnv() {
2222
- const envDir = process.env.SVAMP_HOME || join$1(os.homedir(), ".svamp");
2223
- const envFile = join$1(envDir, ".env");
2224
- if (existsSync$1(envFile)) {
2225
- const lines = readFileSync$1(envFile, "utf-8").split("\n");
2226
- for (const line of lines) {
2227
- const trimmed = line.trim();
2228
- if (!trimmed || trimmed.startsWith("#")) continue;
2229
- const eqIdx = trimmed.indexOf("=");
2230
- if (eqIdx === -1) continue;
2231
- const key = trimmed.slice(0, eqIdx).trim();
2232
- const value = trimmed.slice(eqIdx + 1).trim().replace(/^["']|["']$/g, "");
2233
- if (!process.env[key]) {
2234
- process.env[key] = value;
2235
- }
2236
- }
2237
- }
2238
- }
2239
- loadDotEnv();
2240
- const SVAMP_HOME = process.env.SVAMP_HOME || join$1(os.homedir(), ".svamp");
2241
- const DAEMON_STATE_FILE = join$1(SVAMP_HOME, "daemon.state.json");
2242
- const DAEMON_LOCK_FILE = join$1(SVAMP_HOME, "daemon.lock");
2243
- const LOGS_DIR = join$1(SVAMP_HOME, "logs");
2244
- const SESSION_INDEX_FILE = join$1(SVAMP_HOME, "sessions-index.json");
2245
- function readPackageVersion() {
2246
- try {
2247
- const pkgPath = join$1(__dirname$1, "../package.json");
2248
- if (existsSync$1(pkgPath)) {
2249
- return JSON.parse(readFileSync$1(pkgPath, "utf-8")).version || "unknown";
2250
- }
2251
- } catch {
2252
- }
2253
- return "unknown";
2254
- }
2255
- const DAEMON_VERSION = readPackageVersion();
2256
- function loadAgentConfig() {
2257
- const configPath = join$1(SVAMP_HOME, "agent-config.json");
2258
- if (existsSync$1(configPath)) {
2259
- try {
2260
- return JSON.parse(readFileSync$1(configPath, "utf-8"));
2261
- } catch {
2262
- return {};
2263
- }
2264
- }
2265
- return {};
2266
- }
2267
- function getSessionSvampDir(directory) {
2268
- return join$1(directory, ".svamp");
2269
- }
2270
- function getSessionDir(directory, sessionId) {
2271
- return join$1(getSessionSvampDir(directory), sessionId);
2272
- }
2273
- function getSessionFilePath(directory, sessionId) {
2274
- return join$1(getSessionDir(directory, sessionId), "session.json");
2275
- }
2276
- function getSessionMessagesPath(directory, sessionId) {
2277
- return join$1(getSessionDir(directory, sessionId), "messages.jsonl");
2278
- }
2279
- function getSvampConfigPath(directory, sessionId) {
2280
- return join$1(getSessionDir(directory, sessionId), "config.json");
2281
- }
2282
- function createSvampConfigChecker(directory, sessionId, getMetadata, setMetadata, sessionService, logger) {
2283
- const configPath = getSvampConfigPath(directory, sessionId);
2284
- let lastContent = "";
2285
- if (existsSync$1(configPath)) {
2286
- try {
2287
- lastContent = readFileSync$1(configPath, "utf-8");
2288
- } catch {
2289
- }
2290
- }
2291
- function processConfig(config, meta) {
2292
- if (typeof config.title === "string" && config.title.trim()) {
2293
- const newTitle = config.title.trim();
2294
- if (meta.summary?.text !== newTitle) {
2295
- setMetadata((m) => ({
2296
- ...m,
2297
- summary: { text: newTitle, updatedAt: Date.now() }
2298
- }));
2299
- sessionService.pushMessage({ type: "summary", summary: newTitle }, "session");
2300
- logger.log(`[svampConfig] Title updated: "${newTitle}"`);
2301
- }
2302
- }
2303
- if (config.session_link && typeof config.session_link.url === "string" && config.session_link.url.trim()) {
2304
- const url = config.session_link.url.trim();
2305
- const label = config.session_link.label || "View";
2306
- if (meta.sessionLink?.url !== url || meta.sessionLink?.label !== label) {
2307
- setMetadata((m) => ({
2308
- ...m,
2309
- sessionLink: { url, label, updatedAt: Date.now() }
2310
- }));
2311
- const currentSummary = getMetadata().summary?.text;
2312
- if (currentSummary) {
2313
- sessionService.pushMessage({ type: "summary", summary: currentSummary }, "session");
2314
- }
2315
- logger.log(`[svampConfig] Session link updated: "${label}" \u2192 ${url}`);
2316
- }
2317
- }
2318
- }
2319
- return () => {
2320
- try {
2321
- const meta = getMetadata();
2322
- if (existsSync$1(configPath)) {
2323
- const content = readFileSync$1(configPath, "utf-8");
2324
- if (content !== lastContent) {
2325
- lastContent = content;
2326
- processConfig(JSON.parse(content), meta);
2327
- }
2328
- }
2329
- } catch (err) {
2330
- }
2331
- };
2332
- }
2333
- function loadSessionIndex() {
2334
- if (!existsSync$1(SESSION_INDEX_FILE)) return {};
2335
- try {
2336
- return JSON.parse(readFileSync$1(SESSION_INDEX_FILE, "utf-8"));
2337
- } catch {
2338
- return {};
2339
- }
2340
- }
2341
- function saveSessionIndex(index) {
2342
- writeFileSync$1(SESSION_INDEX_FILE, JSON.stringify(index, null, 2), "utf-8");
2343
- }
2344
- function saveSession(session) {
2345
- const sessionDir = getSessionDir(session.directory, session.sessionId);
2346
- if (!existsSync$1(sessionDir)) {
2347
- mkdirSync$1(sessionDir, { recursive: true });
2348
- }
2349
- writeFileSync$1(
2350
- getSessionFilePath(session.directory, session.sessionId),
2351
- JSON.stringify(session, null, 2),
2352
- "utf-8"
2353
- );
2354
- const index = loadSessionIndex();
2355
- index[session.sessionId] = { directory: session.directory, createdAt: session.createdAt };
2356
- saveSessionIndex(index);
2357
- }
2358
- function deletePersistedSession(sessionId) {
2359
- const index = loadSessionIndex();
2360
- const entry = index[sessionId];
2361
- if (entry) {
2362
- const sessionFile = getSessionFilePath(entry.directory, sessionId);
2363
- try {
2364
- if (existsSync$1(sessionFile)) unlinkSync(sessionFile);
2365
- } catch {
2366
- }
2367
- const messagesFile = getSessionMessagesPath(entry.directory, sessionId);
2368
- try {
2369
- if (existsSync$1(messagesFile)) unlinkSync(messagesFile);
2370
- } catch {
2371
- }
2372
- const configFile = getSvampConfigPath(entry.directory, sessionId);
2373
- try {
2374
- if (existsSync$1(configFile)) unlinkSync(configFile);
2375
- } catch {
2376
- }
2377
- const sessionDir = getSessionDir(entry.directory, sessionId);
2378
- try {
2379
- rmdirSync(sessionDir);
2380
- } catch {
2381
- }
2382
- delete index[sessionId];
2383
- saveSessionIndex(index);
2384
- }
2385
- }
2386
- function loadPersistedSessions() {
2387
- const sessions = [];
2388
- const index = loadSessionIndex();
2389
- for (const [sessionId, entry] of Object.entries(index)) {
2390
- const filePath = getSessionFilePath(entry.directory, sessionId);
2391
- try {
2392
- const data = JSON.parse(readFileSync$1(filePath, "utf-8"));
2393
- if (data.sessionId && data.directory) {
2394
- if (data.stopped) {
2395
- delete index[sessionId];
2396
- } else {
2397
- sessions.push(data);
2398
- }
2399
- }
2400
- } catch {
2401
- delete index[sessionId];
2402
- }
2403
- }
2404
- saveSessionIndex(index);
2405
- return sessions;
2406
- }
2407
- function ensureHomeDir() {
2408
- if (!existsSync$1(SVAMP_HOME)) {
2409
- mkdirSync$1(SVAMP_HOME, { recursive: true });
2410
- }
2411
- if (!existsSync$1(LOGS_DIR)) {
2412
- mkdirSync$1(LOGS_DIR, { recursive: true });
2413
- }
2414
- }
2415
- function createLogger() {
2416
- ensureHomeDir();
2417
- const logFile = join$1(LOGS_DIR, `daemon-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.log`);
2418
- return {
2419
- logFilePath: logFile,
2420
- log: (...args) => {
2421
- const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${args.map((a) => typeof a === "string" ? a : JSON.stringify(a)).join(" ")}
2422
- `;
2423
- fs.appendFile(logFile, line).catch(() => {
2424
- });
2425
- if (process.env.DEBUG) {
2426
- console.log(...args);
2427
- }
2428
- },
2429
- error: (...args) => {
2430
- const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] ERROR: ${args.map((a) => typeof a === "string" ? a : JSON.stringify(a)).join(" ")}
2431
- `;
2432
- fs.appendFile(logFile, line).catch(() => {
2433
- });
2434
- console.error(...args);
2435
- }
2436
- };
2437
- }
2438
- function writeDaemonStateFile(state) {
2439
- ensureHomeDir();
2440
- writeFileSync$1(DAEMON_STATE_FILE, JSON.stringify(state, null, 2), "utf-8");
2441
- }
2442
- function readDaemonStateFile() {
2443
- try {
2444
- if (!existsSync$1(DAEMON_STATE_FILE)) return null;
2445
- return JSON.parse(readFileSync$1(DAEMON_STATE_FILE, "utf-8"));
2446
- } catch {
2447
- return null;
2448
- }
2449
- }
2450
- function cleanupDaemonStateFile() {
2451
- try {
2452
- if (existsSync$1(DAEMON_STATE_FILE)) {
2453
- fs.unlink(DAEMON_STATE_FILE).catch(() => {
2454
- });
2455
- }
2456
- if (existsSync$1(DAEMON_LOCK_FILE)) {
2457
- fs.unlink(DAEMON_LOCK_FILE).catch(() => {
2458
- });
2459
- }
2460
- } catch {
2461
- }
2462
- }
2463
- function isDaemonAlive() {
2464
- const state = readDaemonStateFile();
2465
- if (!state) return false;
2466
- try {
2467
- process.kill(state.pid, 0);
2468
- return true;
2469
- } catch {
2470
- return false;
2471
- }
2472
- }
2473
- async function startDaemon() {
2474
- const logger = createLogger();
2475
- const agentConfig = loadAgentConfig();
2476
- if (Object.keys(agentConfig).length > 0) {
2477
- logger.log("Loaded agent config:", JSON.stringify(agentConfig));
2478
- }
2479
- let shutdownRequested = false;
2480
- let requestShutdown;
2481
- const resolvesWhenShutdownRequested = new Promise((resolve2) => {
2482
- requestShutdown = (source, errorMessage) => {
2483
- if (shutdownRequested) return;
2484
- shutdownRequested = true;
2485
- logger.log(`Requesting shutdown (source: ${source}, errorMessage: ${errorMessage})`);
2486
- setTimeout(() => {
2487
- logger.log("Forced exit after timeout");
2488
- process.exit(1);
2489
- }, 5e3);
2490
- resolve2({ source, errorMessage });
2491
- };
2492
- });
2493
- let isReconnecting = false;
2494
- process.on("SIGINT", () => requestShutdown("os-signal"));
2495
- process.on("SIGTERM", () => requestShutdown("os-signal"));
2496
- process.on("uncaughtException", (error) => {
2497
- if (shutdownRequested) return;
2498
- logger.error("Uncaught exception:", error);
2499
- requestShutdown("exception", error.message);
2500
- });
2501
- const TRANSIENT_REJECTION_PATTERNS = [
2502
- "_rintf",
2503
- // _rintf callback timeouts (app disconnected)
2504
- "Method call timed out",
2505
- // RPC timeout during reconnection
2506
- "WebSocket",
2507
- // WebSocket errors during reconnect
2508
- "ECONNRESET",
2509
- // TCP connection reset
2510
- "ECONNREFUSED",
2511
- // Server temporarily unreachable
2512
- "EPIPE",
2513
- // Broken pipe (write to closed socket)
2514
- "ETIMEDOUT",
2515
- // Connection timed out
2516
- "socket hang up",
2517
- // HTTP socket closed unexpectedly
2518
- "network",
2519
- // Generic network errors
2520
- "Connection closed",
2521
- // WebSocket closed during RPC call
2522
- "connection was closed",
2523
- // hypha-rpc connection closed message
2524
- "Client disconnected",
2525
- // Hypha client disconnect events
2526
- "fetch failed"
2527
- // Fetch API errors during reconnect
2528
- ];
2529
- let unhandledRejectionCount = 0;
2530
- let unhandledRejectionResetTimer = null;
2531
- const UNHANDLED_REJECTION_THRESHOLD = 10;
2532
- const UNHANDLED_REJECTION_WINDOW_MS = 6e4;
2533
- process.on("unhandledRejection", (reason) => {
2534
- if (shutdownRequested) return;
2535
- const msg = String(reason);
2536
- logger.error("Unhandled rejection:", reason);
2537
- const isTransient = TRANSIENT_REJECTION_PATTERNS.some((p) => msg.toLowerCase().includes(p.toLowerCase()));
2538
- if (isTransient || isReconnecting) {
2539
- logger.log(`Ignoring transient rejection (reconnecting=${isReconnecting}): ${msg.slice(0, 200)}`);
2540
- return;
2541
- }
2542
- unhandledRejectionCount++;
2543
- if (!unhandledRejectionResetTimer) {
2544
- unhandledRejectionResetTimer = setTimeout(() => {
2545
- unhandledRejectionCount = 0;
2546
- unhandledRejectionResetTimer = null;
2547
- }, UNHANDLED_REJECTION_WINDOW_MS);
2548
- }
2549
- if (unhandledRejectionCount >= UNHANDLED_REJECTION_THRESHOLD) {
2550
- logger.log(`Too many unhandled rejections (${unhandledRejectionCount} in ${UNHANDLED_REJECTION_WINDOW_MS / 1e3}s), shutting down`);
2551
- requestShutdown("exception", msg);
2552
- } else {
2553
- logger.log(`Unhandled rejection ${unhandledRejectionCount}/${UNHANDLED_REJECTION_THRESHOLD} (not crashing yet): ${msg.slice(0, 200)}`);
2554
- }
2555
- });
2556
- if (isDaemonAlive()) {
2557
- console.log("Svamp daemon is already running");
2558
- process.exit(0);
2559
- }
2560
- const hyphaServerUrl = process.env.HYPHA_SERVER_URL;
2561
- if (!hyphaServerUrl) {
2562
- console.error("HYPHA_SERVER_URL is required.");
2563
- console.error('Run "svamp login <server-url>" first, or set it in .env or environment.');
2564
- process.exit(1);
2565
- }
2566
- const hyphaToken = process.env.HYPHA_TOKEN;
2567
- const hyphaWorkspace = process.env.HYPHA_WORKSPACE;
2568
- const hyphaClientId = process.env.HYPHA_CLIENT_ID;
2569
- if (!hyphaToken) {
2570
- logger.log('Warning: No HYPHA_TOKEN set. Run "svamp login" to authenticate.');
2571
- logger.log("Connecting anonymously...");
2572
- }
2573
- const machineIdFile = join$1(SVAMP_HOME, "machine-id");
2574
- let machineId = process.env.SVAMP_MACHINE_ID;
2575
- if (!machineId) {
2576
- if (existsSync$1(machineIdFile)) {
2577
- machineId = readFileSync$1(machineIdFile, "utf-8").trim();
2578
- }
2579
- if (!machineId) {
2580
- machineId = `machine-${os.hostname()}-${randomUUID$1().slice(0, 8)}`;
2581
- try {
2582
- writeFileSync$1(machineIdFile, machineId, "utf-8");
2583
- } catch {
2584
- }
2585
- }
2586
- }
2587
- logger.log("Starting svamp daemon...");
2588
- logger.log(` Server: ${hyphaServerUrl}`);
2589
- logger.log(` Workspace: ${hyphaWorkspace || "(default)"}`);
2590
- logger.log(` Machine ID: ${machineId}`);
2591
- let server = null;
2592
- try {
2593
- logger.log("Connecting to Hypha server...");
2594
- server = await connectToHypha({
2595
- serverUrl: hyphaServerUrl,
2596
- token: hyphaToken,
2597
- name: `svamp-machine-${machineId}`,
2598
- ...hyphaClientId ? { clientId: hyphaClientId } : {}
2599
- });
2600
- logger.log(`Connected to Hypha (workspace: ${server.config.workspace})`);
2601
- server.on("disconnected", (reason) => {
2602
- logger.log(`Hypha connection permanently lost: ${reason}`);
2603
- isReconnecting = false;
2604
- requestShutdown("hypha-disconnected", String(reason));
2605
- });
2606
- server.on("services_registered", () => {
2607
- if (isReconnecting) {
2608
- logger.log("Hypha reconnection successful \u2014 services re-registered");
2609
- isReconnecting = false;
2610
- }
2611
- });
2612
- const pidToTrackedSession = /* @__PURE__ */ new Map();
2613
- const getCurrentChildren = () => {
2614
- return Array.from(pidToTrackedSession.values()).map((s) => ({
2615
- sessionId: s.svampSessionId || `PID-${s.pid}`,
2616
- pid: s.pid,
2617
- startedBy: s.startedBy,
2618
- directory: s.directory,
2619
- active: !s.stopped && s.hyphaService != null
2620
- }));
2621
- };
2622
- const spawnSession = async (options) => {
2623
- logger.log("Spawning session:", JSON.stringify(options));
2624
- const { directory, approvedNewDirectoryCreation = true, resumeSessionId } = options;
2625
- if (resumeSessionId) {
2626
- for (const tracked of pidToTrackedSession.values()) {
2627
- if (!tracked.stopped && tracked.svampSessionId && tracked.resumeSessionId === resumeSessionId) {
2628
- logger.log(`Dedup: found existing active session ${tracked.svampSessionId} for resume ID ${resumeSessionId}`);
2629
- return { type: "success", sessionId: tracked.svampSessionId };
2630
- }
2631
- }
2632
- }
2633
- try {
2634
- await fs.access(directory);
2635
- } catch {
2636
- if (!approvedNewDirectoryCreation) {
2637
- return { type: "requestToApproveDirectoryCreation", directory };
2638
- }
2639
- try {
2640
- await fs.mkdir(directory, { recursive: true });
2641
- } catch (err) {
2642
- return { type: "error", errorMessage: `Failed to create directory: ${err.message}` };
2643
- }
2644
- }
2645
- const sessionId = options.sessionId || randomUUID$1();
2646
- const agentName = options.agent || agentConfig.agent_type || "claude";
2647
- if (agentName !== "claude" && KNOWN_ACP_AGENTS[agentName]) {
2648
- return await spawnAcpSession(sessionId, directory, agentName, options, resumeSessionId);
2649
- }
2650
- try {
2651
- let parseBashPermission2 = function(permission) {
2652
- if (permission === "Bash") return;
2653
- const match = permission.match(/^Bash\((.+?)\)$/);
2654
- if (!match) return;
2655
- const command = match[1];
2656
- if (command.endsWith(":*")) {
2657
- allowedBashPrefixes.add(command.slice(0, -2));
2658
- } else {
2659
- allowedBashLiterals.add(command);
2660
- }
2661
- }, shouldAutoAllow2 = function(toolName, toolInput) {
2662
- if (toolName === "Bash") {
2663
- const inputObj = toolInput;
2664
- if (inputObj?.command) {
2665
- if (allowedBashLiterals.has(inputObj.command)) return true;
2666
- for (const prefix of allowedBashPrefixes) {
2667
- if (inputObj.command.startsWith(prefix)) return true;
2668
- }
2669
- }
2670
- } else if (allowedTools.has(toolName)) {
2671
- return true;
2672
- }
2673
- if (currentPermissionMode === "bypassPermissions" || currentPermissionMode === "yolo") return true;
2674
- if ((currentPermissionMode === "acceptEdits" || currentPermissionMode === "safe-yolo") && EDIT_TOOLS.has(toolName)) return true;
2675
- return false;
2676
- }, killAndWaitForExit2 = function(proc, signal = "SIGTERM", timeoutMs = 1e4) {
2677
- return new Promise((resolve2) => {
2678
- if (!proc || proc.exitCode !== null) {
2679
- resolve2();
2680
- return;
2681
- }
2682
- const timeout = setTimeout(() => {
2683
- try {
2684
- proc.kill("SIGKILL");
2685
- } catch {
2686
- }
2687
- resolve2();
2688
- }, timeoutMs);
2689
- proc.on("exit", () => {
2690
- clearTimeout(timeout);
2691
- resolve2();
2692
- });
2693
- if (!proc.killed) {
2694
- proc.kill(signal);
2695
- }
2696
- });
2697
- };
2698
- var parseBashPermission = parseBashPermission2, shouldAutoAllow = shouldAutoAllow2, killAndWaitForExit = killAndWaitForExit2;
2699
- let sessionMetadata = {
2700
- path: directory,
2701
- host: os.hostname(),
2702
- version: "0.1.0",
2703
- machineId,
2704
- homeDir: os.homedir(),
2705
- svampHomeDir: SVAMP_HOME,
2706
- svampLibDir: join$1(__dirname$1, ".."),
2707
- svampToolsDir: join$1(__dirname$1, "..", "tools"),
2708
- startedFromDaemon: true,
2709
- startedBy: "daemon",
2710
- lifecycleState: resumeSessionId ? "idle" : "starting"
2711
- };
2712
- let claudeProcess = null;
2713
- const allPersisted = loadPersistedSessions();
2714
- const persisted = allPersisted.find((p) => p.sessionId === sessionId) || (resumeSessionId ? allPersisted.find((p) => p.claudeResumeId === resumeSessionId) : void 0);
2715
- let claudeResumeId = persisted?.claudeResumeId || (resumeSessionId || void 0);
2716
- let currentPermissionMode = persisted?.permissionMode || "default";
2717
- if (claudeResumeId) {
2718
- sessionMetadata = { ...sessionMetadata, claudeSessionId: claudeResumeId };
2719
- }
2720
- if (persisted && persisted.sessionId !== sessionId) {
2721
- const oldDir = persisted.directory || directory;
2722
- const newSessionDir = getSessionDir(directory, sessionId);
2723
- if (!existsSync$1(newSessionDir)) mkdirSync$1(newSessionDir, { recursive: true });
2724
- const oldMsgFile = getSessionMessagesPath(oldDir, persisted.sessionId);
2725
- const newMsgFile = getSessionMessagesPath(directory, sessionId);
2726
- try {
2727
- if (existsSync$1(oldMsgFile) && !existsSync$1(newMsgFile)) {
2728
- copyFileSync(oldMsgFile, newMsgFile);
2729
- logger.log(`[Session ${sessionId}] Copied messages from old session ${persisted.sessionId}`);
2730
- }
2731
- } catch (err) {
2732
- logger.log(`[Session ${sessionId}] Failed to copy messages: ${err.message}`);
2733
- }
2734
- }
2735
- const allowedTools = /* @__PURE__ */ new Set();
2736
- const allowedBashLiterals = /* @__PURE__ */ new Set();
2737
- const allowedBashPrefixes = /* @__PURE__ */ new Set();
2738
- const EDIT_TOOLS = /* @__PURE__ */ new Set(["Edit", "MultiEdit", "Write", "NotebookEdit"]);
2739
- const pendingPermissions = /* @__PURE__ */ new Map();
2740
- let backgroundTaskCount = 0;
2741
- let backgroundTaskNames = [];
2742
- let userMessagePending = false;
2743
- let turnInitiatedByUser = true;
2744
- let isKillingClaude = false;
2745
- let checkSvampConfig;
2746
- const spawnClaude = (initialMessage, meta) => {
2747
- const permissionMode = meta?.permissionMode || agentConfig.default_permission_mode || currentPermissionMode;
2748
- currentPermissionMode = permissionMode;
2749
- const model = meta?.model || agentConfig.default_model || void 0;
2750
- const appendSystemPrompt = meta?.appendSystemPrompt || agentConfig.append_system_prompt || void 0;
2751
- const args = [
2752
- "--output-format",
2753
- "stream-json",
2754
- "--input-format",
2755
- "stream-json",
2756
- "--verbose",
2757
- "--permission-prompt-tool",
2758
- "stdio",
2759
- "--permission-mode",
2760
- permissionMode
2761
- ];
2762
- if (model) args.push("--model", model);
2763
- if (appendSystemPrompt) args.push("--append-system-prompt", appendSystemPrompt);
2764
- if (claudeResumeId) args.push("--resume", claudeResumeId);
2765
- logger.log(`[Session ${sessionId}] Spawning Claude: claude ${args.join(" ")} (cwd: ${directory})`);
2766
- const spawnEnv = { ...process.env };
2767
- delete spawnEnv.CLAUDECODE;
2768
- const child = spawn$1("claude", args, {
2769
- cwd: directory,
2770
- stdio: ["pipe", "pipe", "pipe"],
2771
- env: spawnEnv,
2772
- shell: process.platform === "win32"
2773
- });
2774
- claudeProcess = child;
2775
- logger.log(`[Session ${sessionId}] Claude PID: ${child.pid}, stdin: ${!!child.stdin}, stdout: ${!!child.stdout}, stderr: ${!!child.stderr}`);
2776
- child.on("error", (err) => {
2777
- logger.log(`[Session ${sessionId}] Claude process error: ${err.message}`);
2778
- sessionService.pushMessage({
2779
- type: "assistant",
2780
- content: [{
2781
- type: "text",
2782
- text: `Error: Failed to start Claude Code CLI: ${err.message}
2783
-
2784
- Please ensure Claude Code CLI is installed on this machine. You can install it with:
2785
- \`npm install -g @anthropic-ai/claude-code\``
2786
- }]
2787
- }, "agent");
2788
- sessionService.sendKeepAlive(false);
2789
- });
2790
- let stdoutBuffer = "";
2791
- let lastErrorMessagePushed = false;
2792
- child.stdout?.on("data", (chunk) => {
2793
- stdoutBuffer += chunk.toString();
2794
- const lines = stdoutBuffer.split("\n");
2795
- stdoutBuffer = lines.pop() || "";
2796
- for (const line of lines) {
2797
- if (!line.trim()) continue;
2798
- logger.log(`[Session ${sessionId}] stdout line (${line.length} chars): ${line.slice(0, 500)}`);
2799
- try {
2800
- const msg = JSON.parse(line);
2801
- logger.log(`[Session ${sessionId}] Parsed type=${msg.type} subtype=${msg.subtype || "n/a"}`);
2802
- if (msg.type === "control_request" && msg.request?.subtype === "can_use_tool") {
2803
- const requestId = msg.request_id;
2804
- const toolName = msg.request.tool_name;
2805
- const toolInput = msg.request.input;
2806
- logger.log(`[Session ${sessionId}] Permission request: ${requestId} tool=${toolName}`);
2807
- if (shouldAutoAllow2(toolName, toolInput)) {
2808
- logger.log(`[Session ${sessionId}] Auto-allowing ${toolName} (mode=${currentPermissionMode})`);
2809
- if (claudeProcess && !claudeProcess.killed && claudeProcess.stdin) {
2810
- const controlResponse = JSON.stringify({
2811
- type: "control_response",
2812
- response: {
2813
- subtype: "success",
2814
- request_id: requestId,
2815
- response: { behavior: "allow", updatedInput: toolInput || {} }
2816
- }
2817
- });
2818
- claudeProcess.stdin.write(controlResponse + "\n");
2819
- }
2820
- continue;
2821
- }
2822
- const permissionPromise = new Promise((resolve2) => {
2823
- pendingPermissions.set(requestId, { resolve: resolve2, toolName, input: toolInput });
2824
- });
2825
- const currentRequests = { ...sessionService._agentState?.requests };
2826
- sessionService.updateAgentState({
2827
- controlledByUser: false,
2828
- requests: {
2829
- ...currentRequests,
2830
- [requestId]: {
2831
- tool: toolName,
2832
- arguments: toolInput,
2833
- createdAt: Date.now()
2834
- }
2835
- }
2836
- });
2837
- permissionPromise.then((result) => {
2838
- if (claudeProcess && !claudeProcess.killed && claudeProcess.stdin) {
2839
- const controlResponse = JSON.stringify({
2840
- type: "control_response",
2841
- response: {
2842
- subtype: "success",
2843
- request_id: requestId,
2844
- response: result
2845
- }
2846
- });
2847
- logger.log(`[Session ${sessionId}] Sending control_response: ${controlResponse.slice(0, 200)}`);
2848
- claudeProcess.stdin.write(controlResponse + "\n");
2849
- }
2850
- const reqs = { ...sessionService._agentState?.requests };
2851
- delete reqs[requestId];
2852
- sessionService.updateAgentState({
2853
- controlledByUser: false,
2854
- requests: reqs,
2855
- completedRequests: {
2856
- ...sessionService._agentState?.completedRequests,
2857
- [requestId]: {
2858
- tool: toolName,
2859
- arguments: toolInput,
2860
- completedAt: Date.now(),
2861
- status: result.behavior === "allow" ? "approved" : "denied"
2862
- }
2863
- }
2864
- });
2865
- }).catch((err) => {
2866
- logger.log(`[Session ${sessionId}] Permission handler error (request ${requestId}): ${err}`);
2867
- });
2868
- } else if (msg.type === "control_cancel_request") {
2869
- const requestId = msg.request_id;
2870
- logger.log(`[Session ${sessionId}] Permission cancel: ${requestId}`);
2871
- const pending = pendingPermissions.get(requestId);
2872
- if (pending) {
2873
- pending.resolve({ behavior: "deny", message: "Cancelled" });
2874
- pendingPermissions.delete(requestId);
2875
- }
2876
- } else if (msg.type === "control_response") {
2877
- logger.log(`[Session ${sessionId}] Control response: ${JSON.stringify(msg).slice(0, 200)}`);
2878
- } else if (msg.type === "assistant" || msg.type === "result") {
2879
- if (msg.type === "assistant" && Array.isArray(msg.content)) {
2880
- for (const block of msg.content) {
2881
- if (block.type === "tool_use" && block.input?.run_in_background === true) {
2882
- backgroundTaskCount++;
2883
- const label = block.tool_name || block.name || "unknown";
2884
- backgroundTaskNames.push(label);
2885
- logger.log(`[Session ${sessionId}] Background task launched: ${label} (count=${backgroundTaskCount})`);
2886
- }
2887
- }
2888
- }
2889
- if (msg.type === "result") {
2890
- if (msg.is_error && msg.duration_api_ms === 0) {
2891
- const resultText = msg.result || "";
2892
- logger.error(`[Session ${sessionId}] Claude startup failure (no API calls made): "${resultText}"`);
2893
- const isLoginIssue = resultText.toLowerCase().includes("login") || resultText.toLowerCase().includes("logged in") || resultText.toLowerCase().includes("auth") || resultText.toLowerCase().includes("api key") || resultText.toLowerCase().includes("unauthorized");
2894
- const hint = isLoginIssue ? "\n\nRun `claude login` in your terminal on the machine running the daemon to re-authenticate." : "\n\nCheck that the Claude Code CLI is properly installed and configured.";
2895
- const displayMsg = resultText || "Claude Code failed to start without making any API calls.";
2896
- sessionService.pushMessage({
2897
- type: "assistant",
2898
- content: [{ type: "text", text: `\u26A0\uFE0F **Claude Code error:** ${displayMsg}${hint}` }]
2899
- }, "agent");
2900
- lastErrorMessagePushed = true;
2901
- }
2902
- }
2903
- if (msg.type === "result") {
2904
- if (!turnInitiatedByUser) {
2905
- logger.log(`[Session ${sessionId}] Skipping stale result from SDK-initiated turn`);
2906
- const hasBackgroundTasks = backgroundTaskCount > 0;
2907
- if (hasBackgroundTasks) {
2908
- const taskInfo = `Background tasks still running (${backgroundTaskCount}): ${backgroundTaskNames.join(", ")}`;
2909
- sessionService.pushMessage({ type: "session_event", message: taskInfo }, "session");
2910
- }
2911
- sessionService.sendKeepAlive(false);
2912
- turnInitiatedByUser = true;
2913
- continue;
2914
- }
2915
- sessionService.sendKeepAlive(false);
2916
- checkSvampConfig?.();
2917
- if (backgroundTaskCount > 0) {
2918
- const taskInfo = `Background tasks still running (${backgroundTaskCount}): ${backgroundTaskNames.join(", ")}`;
2919
- logger.log(`[Session ${sessionId}] ${taskInfo}`);
2920
- sessionService.pushMessage({ type: "session_event", message: taskInfo }, "session");
2921
- }
2922
- }
2923
- sessionService.pushMessage(msg, "agent");
2924
- if (msg.session_id) {
2925
- claudeResumeId = msg.session_id;
2926
- }
2927
- } else if (msg.type === "system" && msg.subtype === "init") {
2928
- if (!userMessagePending) {
2929
- turnInitiatedByUser = false;
2930
- logger.log(`[Session ${sessionId}] SDK-initiated turn (likely stale task_notification)`);
2931
- }
2932
- userMessagePending = false;
2933
- if (msg.session_id) {
2934
- claudeResumeId = msg.session_id;
2935
- sessionService.updateMetadata({
2936
- ...sessionMetadata,
2937
- claudeSessionId: msg.session_id
2938
- });
2939
- saveSession({
2940
- sessionId,
2941
- directory,
2942
- claudeResumeId,
2943
- permissionMode: currentPermissionMode,
2944
- metadata: sessionMetadata,
2945
- createdAt: Date.now(),
2946
- machineId
2947
- });
2948
- artifactSync.scheduleDebouncedSync(sessionId, getSessionDir(directory, sessionId), sessionMetadata, machineId);
2949
- }
2950
- sessionService.pushMessage(msg, "session");
2951
- } else if (msg.type === "system" && msg.subtype === "task_notification" && msg.status === "completed") {
2952
- backgroundTaskCount = Math.max(0, backgroundTaskCount - 1);
2953
- if (backgroundTaskNames.length > 0) {
2954
- const completed = backgroundTaskNames.shift();
2955
- logger.log(`[Session ${sessionId}] Background task completed: ${completed} (remaining=${backgroundTaskCount})`);
2956
- }
2957
- sessionService.pushMessage(msg, "agent");
2958
- } else {
2959
- sessionService.pushMessage(msg, "agent");
2960
- }
2961
- } catch {
2962
- logger.log(`[Session ${sessionId}] Claude stdout (non-JSON): ${line}`);
2963
- }
2964
- }
2965
- });
2966
- let stderrBuffer = "";
2967
- child.stderr?.on("data", (chunk) => {
2968
- const text = chunk.toString();
2969
- logger.log(`[Session ${sessionId}] Claude stderr: ${text.trim()}`);
2970
- stderrBuffer += text;
2971
- });
2972
- child.on("exit", (code, signal) => {
2973
- logger.log(`[Session ${sessionId}] Claude exited: code=${code}, signal=${signal}`);
2974
- claudeProcess = null;
2975
- for (const [id, pending] of pendingPermissions) {
2976
- pending.resolve({ behavior: "deny", message: "Claude process exited" });
2977
- }
2978
- pendingPermissions.clear();
2979
- if (code !== 0 && code !== null && !lastErrorMessagePushed) {
2980
- sessionService.pushMessage({
2981
- type: "assistant",
2982
- content: [{
2983
- type: "text",
2984
- text: `Error: Claude process exited with code ${code}${signal ? ` (signal: ${signal})` : ""}.
2985
-
2986
- This may indicate that Claude Code CLI is not properly installed or configured.`
2987
- }]
2988
- }, "agent");
2989
- }
2990
- lastErrorMessagePushed = false;
2991
- sessionService.updateMetadata({
2992
- ...sessionMetadata,
2993
- lifecycleState: claudeResumeId ? "idle" : "stopped"
2994
- });
2995
- sessionService.sendKeepAlive(false);
2996
- if (claudeResumeId && !trackedSession.stopped) {
2997
- saveSession({
2998
- sessionId,
2999
- directory,
3000
- claudeResumeId,
3001
- permissionMode: currentPermissionMode,
3002
- metadata: sessionMetadata,
3003
- createdAt: Date.now(),
3004
- machineId
3005
- });
3006
- artifactSync.syncSession(sessionId, getSessionDir(directory, sessionId), sessionMetadata, machineId).catch(() => {
3007
- });
3008
- }
3009
- });
3010
- if (initialMessage && child.stdin) {
3011
- const stdinMsg = JSON.stringify({
3012
- type: "user",
3013
- message: { role: "user", content: initialMessage }
3014
- });
3015
- child.stdin.write(stdinMsg + "\n");
3016
- }
3017
- return child;
3018
- };
3019
- const sessionService = await registerSessionService(
3020
- server,
3021
- sessionId,
3022
- sessionMetadata,
3023
- { controlledByUser: false },
3024
- {
3025
- onUserMessage: (content, meta) => {
3026
- logger.log(`[Session ${sessionId}] User message received`);
3027
- userMessagePending = true;
3028
- turnInitiatedByUser = true;
3029
- let text;
3030
- let msgMeta = meta;
3031
- try {
3032
- let parsed = typeof content === "string" ? JSON.parse(content) : content;
3033
- if (parsed?.content && typeof parsed.content === "string") {
3034
- try {
3035
- const inner = JSON.parse(parsed.content);
3036
- if (inner && typeof inner === "object") parsed = inner;
3037
- } catch {
3038
- }
3039
- }
3040
- text = parsed?.content?.text || parsed?.text || (typeof parsed === "string" ? parsed : JSON.stringify(parsed));
3041
- if (parsed?.meta) msgMeta = { ...msgMeta, ...parsed.meta };
3042
- } catch {
3043
- text = typeof content === "string" ? content : JSON.stringify(content);
3044
- }
3045
- if (msgMeta?.permissionMode) {
3046
- currentPermissionMode = msgMeta.permissionMode;
3047
- logger.log(`[Session ${sessionId}] Permission mode updated to: ${currentPermissionMode}`);
3048
- }
3049
- if (isKillingClaude) {
3050
- logger.log(`[Session ${sessionId}] Message received while restarting Claude, ignoring to prevent ghost process`);
3051
- sessionService.sendKeepAlive(false);
3052
- return;
3053
- }
3054
- if (!claudeProcess || claudeProcess.exitCode !== null) {
3055
- spawnClaude(text, msgMeta);
3056
- } else {
3057
- const stdinMsg = JSON.stringify({
3058
- type: "user",
3059
- message: { role: "user", content: text }
3060
- });
3061
- claudeProcess.stdin?.write(stdinMsg + "\n");
3062
- }
3063
- sessionService.sendKeepAlive(true);
3064
- },
3065
- onAbort: () => {
3066
- logger.log(`[Session ${sessionId}] Abort requested`);
3067
- if (claudeProcess && !claudeProcess.killed) {
3068
- claudeProcess.kill("SIGINT");
3069
- }
3070
- },
3071
- onPermissionResponse: (params) => {
3072
- logger.log(`[Session ${sessionId}] Permission response:`, JSON.stringify(params));
3073
- const requestId = params.id;
3074
- const pending = pendingPermissions.get(requestId);
3075
- if (params.mode) {
3076
- logger.log(`[Session ${sessionId}] Permission mode changed to: ${params.mode}`);
3077
- currentPermissionMode = params.mode;
3078
- }
3079
- if (params.allowTools && Array.isArray(params.allowTools)) {
3080
- for (const tool of params.allowTools) {
3081
- if (tool.startsWith("Bash(") || tool === "Bash") {
3082
- parseBashPermission2(tool);
3083
- } else {
3084
- allowedTools.add(tool);
3085
- }
3086
- }
3087
- logger.log(`[Session ${sessionId}] Updated allowed tools: ${[...allowedTools].join(", ")}`);
3088
- }
3089
- if (pending) {
3090
- pendingPermissions.delete(requestId);
3091
- if (params.approved) {
3092
- pending.resolve({
3093
- behavior: "allow",
3094
- updatedInput: pending.input || {}
3095
- });
3096
- } else {
3097
- pending.resolve({
3098
- behavior: "deny",
3099
- 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."
3100
- });
3101
- }
3102
- } else {
3103
- logger.log(`[Session ${sessionId}] No pending permission for id=${requestId}`);
3104
- }
3105
- },
3106
- onSwitchMode: async (mode) => {
3107
- logger.log(`[Session ${sessionId}] Switch mode: ${mode}`);
3108
- currentPermissionMode = mode;
3109
- if (claudeProcess && claudeProcess.exitCode === null) {
3110
- isKillingClaude = true;
3111
- await killAndWaitForExit2(claudeProcess);
3112
- isKillingClaude = false;
3113
- spawnClaude(void 0, { permissionMode: mode });
3114
- }
3115
- },
3116
- onRestartClaude: async () => {
3117
- logger.log(`[Session ${sessionId}] Restart Claude requested`);
3118
- try {
3119
- if (claudeProcess && claudeProcess.exitCode === null) {
3120
- isKillingClaude = true;
3121
- sessionService.updateMetadata({
3122
- ...sessionMetadata,
3123
- lifecycleState: "restarting"
3124
- });
3125
- await killAndWaitForExit2(claudeProcess);
3126
- isKillingClaude = false;
3127
- }
3128
- if (claudeResumeId) {
3129
- spawnClaude(void 0, { permissionMode: currentPermissionMode });
3130
- logger.log(`[Session ${sessionId}] Claude respawned with --resume ${claudeResumeId}`);
3131
- return { success: true, message: "Claude process restarted successfully." };
3132
- } else {
3133
- logger.log(`[Session ${sessionId}] No resume ID \u2014 cannot restart`);
3134
- return { success: false, message: "No session to resume. Send a message to start a new session." };
3135
- }
3136
- } catch (err) {
3137
- isKillingClaude = false;
3138
- logger.log(`[Session ${sessionId}] Restart failed: ${err.message}`);
3139
- return { success: false, message: `Restart failed: ${err.message}` };
3140
- }
3141
- },
3142
- onKillSession: () => {
3143
- logger.log(`[Session ${sessionId}] Kill session requested`);
3144
- stopSession(sessionId);
3145
- },
3146
- onBash: async (command, cwd) => {
3147
- logger.log(`[Session ${sessionId}] Bash: ${command} (cwd: ${cwd || directory})`);
3148
- const { exec } = await import('child_process');
3149
- return new Promise((resolve2) => {
3150
- exec(command, { cwd: cwd || directory, timeout: 3e4, maxBuffer: 1024 * 1024 }, (err, stdout, stderr) => {
3151
- if (err) {
3152
- resolve2({ success: false, stdout: stdout || "", stderr: stderr || err.message, exitCode: err.code ?? 1 });
3153
- } else {
3154
- resolve2({ success: true, stdout, stderr: stderr || "", exitCode: 0 });
3155
- }
3156
- });
3157
- });
3158
- },
3159
- onRipgrep: async (args, cwd) => {
3160
- const { exec } = await import('child_process');
3161
- const rgCwd = cwd || directory;
3162
- return new Promise((resolve2, reject) => {
3163
- exec(`rg ${args}`, { cwd: rgCwd, timeout: 3e4, maxBuffer: 5 * 1024 * 1024 }, (err, stdout) => {
3164
- if (err && !stdout) {
3165
- reject(new Error(err.message));
3166
- } else {
3167
- resolve2(stdout || "");
3168
- }
3169
- });
3170
- });
3171
- },
3172
- onReadFile: async (path) => {
3173
- const resolvedPath = resolve(directory, path);
3174
- if (!resolvedPath.startsWith(resolve(directory))) {
3175
- throw new Error("Path outside working directory");
3176
- }
3177
- const buffer = await fs.readFile(resolvedPath);
3178
- return buffer.toString("base64");
3179
- },
3180
- onWriteFile: async (path, content) => {
3181
- const resolvedPath = resolve(directory, path);
3182
- if (!resolvedPath.startsWith(resolve(directory))) {
3183
- throw new Error("Path outside working directory");
3184
- }
3185
- await fs.mkdir(dirname(resolvedPath), { recursive: true });
3186
- await fs.writeFile(resolvedPath, Buffer.from(content, "base64"));
3187
- },
3188
- onListDirectory: async (path) => {
3189
- const resolvedDir = resolve(directory, path || ".");
3190
- if (!resolvedDir.startsWith(resolve(directory))) {
3191
- throw new Error("Path outside working directory");
3192
- }
3193
- const entries = await fs.readdir(resolvedDir, { withFileTypes: true });
3194
- return entries.map((e) => ({ name: e.name, isDirectory: e.isDirectory() }));
3195
- },
3196
- onGetDirectoryTree: async (treePath, maxDepth) => {
3197
- async function buildTree(p, name, depth) {
3198
- try {
3199
- const stats = await fs.stat(p);
3200
- const node = {
3201
- name,
3202
- path: p,
3203
- type: stats.isDirectory() ? "directory" : "file",
3204
- size: stats.size,
3205
- modified: stats.mtime.getTime()
3206
- };
3207
- if (stats.isDirectory() && depth < maxDepth) {
3208
- const entries = await fs.readdir(p, { withFileTypes: true });
3209
- const children = [];
3210
- await Promise.all(entries.map(async (entry) => {
3211
- if (entry.isSymbolicLink()) return;
3212
- const childPath = join$1(p, entry.name);
3213
- const childNode = await buildTree(childPath, entry.name, depth + 1);
3214
- if (childNode) children.push(childNode);
3215
- }));
3216
- children.sort((a, b) => {
3217
- if (a.type === "directory" && b.type !== "directory") return -1;
3218
- if (a.type !== "directory" && b.type === "directory") return 1;
3219
- return a.name.localeCompare(b.name);
3220
- });
3221
- node.children = children;
3222
- }
3223
- return node;
3224
- } catch {
3225
- return null;
3226
- }
3227
- }
3228
- const resolvedPath = resolve(directory, treePath);
3229
- const tree = await buildTree(resolvedPath, basename(resolvedPath), 0);
3230
- return { success: !!tree, tree };
3231
- }
3232
- },
3233
- { messagesDir: getSessionDir(directory, sessionId) }
3234
- );
3235
- checkSvampConfig = createSvampConfigChecker(
3236
- directory,
3237
- sessionId,
3238
- () => sessionMetadata,
3239
- (updater) => {
3240
- sessionMetadata = updater(sessionMetadata);
3241
- sessionService.updateMetadata(sessionMetadata);
3242
- },
3243
- sessionService,
3244
- logger
3245
- );
3246
- const trackedSession = {
3247
- startedBy: "daemon",
3248
- pid: process.pid,
3249
- svampSessionId: sessionId,
3250
- hyphaService: sessionService,
3251
- checkSvampConfig,
3252
- directory,
3253
- resumeSessionId: claudeResumeId,
3254
- get childProcess() {
3255
- return claudeProcess || void 0;
3256
- }
3257
- };
3258
- pidToTrackedSession.set(process.pid + Math.floor(Math.random() * 1e5), trackedSession);
3259
- sessionService.updateMetadata({
3260
- ...sessionMetadata,
3261
- lifecycleState: "idle"
3262
- });
3263
- logger.log(`Session ${sessionId} registered on Hypha, waiting for first message to spawn Claude`);
3264
- return {
3265
- type: "success",
3266
- sessionId,
3267
- message: `Session registered on Hypha as svamp-session-${sessionId}`
3268
- };
3269
- } catch (err) {
3270
- logger.error(`Failed to spawn session:`, err);
3271
- return {
3272
- type: "error",
3273
- errorMessage: `Failed to register session service: ${err.message}`
3274
- };
3275
- }
3276
- };
3277
- const spawnAcpSession = async (sessionId, directory, agentName, options, resumeSessionId) => {
3278
- logger.log(`[ACP] Spawning ${agentName} session: ${sessionId}`);
3279
- try {
3280
- let parseBashPermission2 = function(permission) {
3281
- if (permission === "Bash") return;
3282
- const match = permission.match(/^Bash\((.+?)\)$/);
3283
- if (!match) return;
3284
- const command = match[1];
3285
- if (command.endsWith(":*")) {
3286
- allowedBashPrefixes.add(command.slice(0, -2));
3287
- } else {
3288
- allowedBashLiterals.add(command);
3289
- }
3290
- }, shouldAutoAllow2 = function(toolName, toolInput) {
3291
- if (toolName === "Bash") {
3292
- const inputObj = toolInput;
3293
- if (inputObj?.command) {
3294
- if (allowedBashLiterals.has(inputObj.command)) return true;
3295
- for (const prefix of allowedBashPrefixes) {
3296
- if (inputObj.command.startsWith(prefix)) return true;
3297
- }
3298
- }
3299
- } else if (allowedTools.has(toolName)) {
3300
- return true;
3301
- }
3302
- if (currentPermissionMode === "bypassPermissions" || currentPermissionMode === "yolo") return true;
3303
- if ((currentPermissionMode === "acceptEdits" || currentPermissionMode === "safe-yolo") && EDIT_TOOLS.has(toolName)) return true;
3304
- return false;
3305
- };
3306
- var parseBashPermission = parseBashPermission2, shouldAutoAllow = shouldAutoAllow2;
3307
- let sessionMetadata = {
3308
- path: directory,
3309
- host: os.hostname(),
3310
- version: "0.1.0",
3311
- machineId,
3312
- homeDir: os.homedir(),
3313
- svampHomeDir: SVAMP_HOME,
3314
- svampLibDir: join$1(__dirname$1, ".."),
3315
- svampToolsDir: join$1(__dirname$1, "..", "tools"),
3316
- startedFromDaemon: true,
3317
- startedBy: "daemon",
3318
- lifecycleState: "starting",
3319
- flavor: agentName
3320
- };
3321
- let currentPermissionMode = "default";
3322
- const allowedTools = /* @__PURE__ */ new Set();
3323
- const allowedBashLiterals = /* @__PURE__ */ new Set();
3324
- const allowedBashPrefixes = /* @__PURE__ */ new Set();
3325
- const EDIT_TOOLS = /* @__PURE__ */ new Set(["Edit", "MultiEdit", "Write", "NotebookEdit"]);
3326
- const sessionService = await registerSessionService(
3327
- server,
3328
- sessionId,
3329
- sessionMetadata,
3330
- { controlledByUser: false },
3331
- {
3332
- onUserMessage: (content, meta) => {
3333
- logger.log(`[ACP Session ${sessionId}] User message received`);
3334
- let text;
3335
- let msgMeta = meta;
3336
- try {
3337
- let parsed = typeof content === "string" ? JSON.parse(content) : content;
3338
- if (parsed?.content && typeof parsed.content === "string") {
3339
- try {
3340
- const inner = JSON.parse(parsed.content);
3341
- if (inner && typeof inner === "object") parsed = inner;
3342
- } catch {
3343
- }
3344
- }
3345
- text = parsed?.content?.text || parsed?.text || (typeof parsed === "string" ? parsed : JSON.stringify(parsed));
3346
- if (parsed?.meta) msgMeta = { ...msgMeta, ...parsed.meta };
3347
- } catch {
3348
- text = typeof content === "string" ? content : JSON.stringify(content);
3349
- }
3350
- if (msgMeta?.permissionMode) {
3351
- currentPermissionMode = msgMeta.permissionMode;
3352
- }
3353
- acpBackend.sendPrompt(sessionId, text).catch((err) => {
3354
- logger.error(`[ACP Session ${sessionId}] Error sending prompt:`, err);
3355
- });
3356
- },
3357
- onAbort: () => {
3358
- logger.log(`[ACP Session ${sessionId}] Abort requested`);
3359
- acpBackend.cancel(sessionId).catch(() => {
3360
- });
3361
- },
3362
- onPermissionResponse: (params) => {
3363
- logger.log(`[ACP Session ${sessionId}] Permission response:`, JSON.stringify(params));
3364
- const requestId = params.id;
3365
- if (params.mode) currentPermissionMode = params.mode;
3366
- if (params.allowTools && Array.isArray(params.allowTools)) {
3367
- for (const tool of params.allowTools) {
3368
- if (tool.startsWith("Bash(") || tool === "Bash") {
3369
- parseBashPermission2(tool);
3370
- } else {
3371
- allowedTools.add(tool);
3372
- }
3373
- }
3374
- }
3375
- permissionHandler.resolvePermission(requestId, params.approved);
3376
- },
3377
- onSwitchMode: (mode) => {
3378
- logger.log(`[ACP Session ${sessionId}] Switch mode: ${mode}`);
3379
- currentPermissionMode = mode;
3380
- },
3381
- onRestartClaude: async () => {
3382
- logger.log(`[ACP Session ${sessionId}] Restart agent requested`);
3383
- return { success: false, message: "Restart is not supported for this agent type." };
3384
- },
3385
- onKillSession: () => {
3386
- logger.log(`[ACP Session ${sessionId}] Kill session requested`);
3387
- stopSession(sessionId);
3388
- },
3389
- onBash: async (command, cwd) => {
3390
- const { exec } = await import('child_process');
3391
- return new Promise((resolve2) => {
3392
- exec(command, { cwd: cwd || directory, timeout: 3e4, maxBuffer: 1024 * 1024 }, (err, stdout, stderr) => {
3393
- if (err) {
3394
- resolve2({ success: false, stdout: stdout || "", stderr: stderr || err.message, exitCode: err.code ?? 1 });
3395
- } else {
3396
- resolve2({ success: true, stdout, stderr: stderr || "", exitCode: 0 });
3397
- }
3398
- });
3399
- });
3400
- },
3401
- onRipgrep: async (args, cwd) => {
3402
- const { exec } = await import('child_process');
3403
- const rgCwd = cwd || directory;
3404
- return new Promise((resolve2, reject) => {
3405
- exec(`rg ${args}`, { cwd: rgCwd, timeout: 3e4, maxBuffer: 5 * 1024 * 1024 }, (err, stdout) => {
3406
- if (err && !stdout) {
3407
- reject(new Error(err.message));
3408
- } else {
3409
- resolve2(stdout || "");
3410
- }
3411
- });
3412
- });
3413
- },
3414
- onReadFile: async (path) => {
3415
- const resolvedPath = resolve(directory, path);
3416
- if (!resolvedPath.startsWith(resolve(directory))) {
3417
- throw new Error("Path outside working directory");
3418
- }
3419
- const buffer = await fs.readFile(resolvedPath);
3420
- return buffer.toString("base64");
3421
- },
3422
- onWriteFile: async (path, content) => {
3423
- const resolvedPath = resolve(directory, path);
3424
- if (!resolvedPath.startsWith(resolve(directory))) {
3425
- throw new Error("Path outside working directory");
3426
- }
3427
- await fs.mkdir(dirname(resolvedPath), { recursive: true });
3428
- await fs.writeFile(resolvedPath, Buffer.from(content, "base64"));
3429
- },
3430
- onListDirectory: async (path) => {
3431
- const resolvedDir = resolve(directory, path || ".");
3432
- if (!resolvedDir.startsWith(resolve(directory))) {
3433
- throw new Error("Path outside working directory");
3434
- }
3435
- const entries = await fs.readdir(resolvedDir, { withFileTypes: true });
3436
- return entries.map((e) => ({ name: e.name, isDirectory: e.isDirectory() }));
3437
- },
3438
- onGetDirectoryTree: async (treePath, maxDepth) => {
3439
- async function buildTree(p, name, depth) {
3440
- try {
3441
- const stats = await fs.stat(p);
3442
- const node = {
3443
- name,
3444
- path: p,
3445
- type: stats.isDirectory() ? "directory" : "file",
3446
- size: stats.size,
3447
- modified: stats.mtime.getTime()
3448
- };
3449
- if (stats.isDirectory() && depth < maxDepth) {
3450
- const entries = await fs.readdir(p, { withFileTypes: true });
3451
- const children = [];
3452
- await Promise.all(entries.map(async (entry) => {
3453
- if (entry.isSymbolicLink()) return;
3454
- const childPath = join$1(p, entry.name);
3455
- const childNode = await buildTree(childPath, entry.name, depth + 1);
3456
- if (childNode) children.push(childNode);
3457
- }));
3458
- children.sort((a, b) => {
3459
- if (a.type === "directory" && b.type !== "directory") return -1;
3460
- if (a.type !== "directory" && b.type === "directory") return 1;
3461
- return a.name.localeCompare(b.name);
3462
- });
3463
- node.children = children;
3464
- }
3465
- return node;
3466
- } catch {
3467
- return null;
3468
- }
3469
- }
3470
- const resolvedPath = resolve(directory, treePath);
3471
- const tree = await buildTree(resolvedPath, basename(resolvedPath), 0);
3472
- return { success: !!tree, tree };
3473
- }
3474
- },
3475
- { messagesDir: getSessionDir(directory, sessionId) }
3476
- );
3477
- const checkSvampConfig = createSvampConfigChecker(
3478
- directory,
3479
- sessionId,
3480
- () => sessionMetadata,
3481
- (updater) => {
3482
- sessionMetadata = updater(sessionMetadata);
3483
- sessionService.updateMetadata(sessionMetadata);
3484
- },
3485
- sessionService,
3486
- logger
3487
- );
3488
- const transportHandler = agentName === "gemini" ? new GeminiTransport() : new DefaultTransport(agentName);
3489
- const permissionHandler = new HyphaPermissionHandler(shouldAutoAllow2, logger.log);
3490
- const acpConfig = KNOWN_ACP_AGENTS[agentName];
3491
- const acpBackend = new AcpBackend({
3492
- agentName,
3493
- cwd: directory,
3494
- command: acpConfig.command,
3495
- args: acpConfig.args,
3496
- env: options.environmentVariables,
3497
- permissionHandler,
3498
- transportHandler,
3499
- log: logger.log
3500
- });
3501
- bridgeAcpToSession(
3502
- acpBackend,
3503
- sessionService,
3504
- () => sessionMetadata,
3505
- (updater) => {
3506
- sessionMetadata = updater(sessionMetadata);
3507
- sessionService.updateMetadata(sessionMetadata);
3508
- },
3509
- logger.log,
3510
- checkSvampConfig
3511
- );
3512
- const trackedSession = {
3513
- startedBy: "daemon",
3514
- pid: process.pid,
3515
- svampSessionId: sessionId,
3516
- hyphaService: sessionService,
3517
- checkSvampConfig,
3518
- directory,
3519
- resumeSessionId,
3520
- get childProcess() {
3521
- return acpBackend.getProcess() || void 0;
3522
- }
3523
- };
3524
- pidToTrackedSession.set(process.pid + Math.floor(Math.random() * 1e5), trackedSession);
3525
- logger.log(`[ACP Session ${sessionId}] Starting ${agentName} backend...`);
3526
- acpBackend.startSession().then(() => {
3527
- logger.log(`[ACP Session ${sessionId}] ${agentName} backend started, waiting for first message`);
3528
- }).catch((err) => {
3529
- logger.error(`[ACP Session ${sessionId}] Failed to start ${agentName}:`, err);
3530
- sessionService.pushMessage({
3531
- type: "assistant",
3532
- content: [{
3533
- type: "text",
3534
- text: `Error: Failed to start ${agentName} agent: ${err.message}
3535
-
3536
- Please ensure the ${agentName} CLI is installed.`
3537
- }]
3538
- }, "agent");
3539
- sessionService.sendKeepAlive(false);
3540
- });
3541
- return {
3542
- type: "success",
3543
- sessionId,
3544
- message: `ACP session (${agentName}) registered as svamp-session-${sessionId}`
3545
- };
3546
- } catch (err) {
3547
- logger.error(`[ACP] Failed to spawn ${agentName} session:`, err);
3548
- return {
3549
- type: "error",
3550
- errorMessage: `Failed to spawn ${agentName} session: ${err.message}`
3551
- };
3552
- }
3553
- };
3554
- const stopSession = (sessionId) => {
3555
- logger.log(`Stopping session: ${sessionId}`);
3556
- for (const [pid, session] of pidToTrackedSession) {
3557
- if (session.svampSessionId === sessionId) {
3558
- session.stopped = true;
3559
- session.hyphaService?.disconnect().catch(() => {
3560
- });
3561
- if (session.childProcess) {
3562
- try {
3563
- session.childProcess.kill("SIGTERM");
3564
- } catch {
3565
- }
3566
- }
3567
- pidToTrackedSession.delete(pid);
3568
- deletePersistedSession(sessionId);
3569
- logger.log(`Session ${sessionId} stopped`);
3570
- return true;
3571
- }
3572
- }
3573
- logger.log(`Session ${sessionId} not found`);
3574
- return false;
3575
- };
3576
- const defaultHomeDir = existsSync$1("/data") ? "/data" : os.homedir();
3577
- const machineMetadata = {
3578
- host: os.hostname(),
3579
- platform: os.platform(),
3580
- svampVersion: "0.1.0 (hypha)",
3581
- homeDir: defaultHomeDir,
3582
- svampHomeDir: SVAMP_HOME,
3583
- svampLibDir: join$1(__dirname$1, ".."),
3584
- displayName: process.env.SVAMP_DISPLAY_NAME || void 0
3585
- };
3586
- const initialDaemonState = {
3587
- status: "running",
3588
- pid: process.pid,
3589
- startedAt: Date.now()
3590
- };
3591
- const machineService = await registerMachineService(
3592
- server,
3593
- machineId,
3594
- machineMetadata,
3595
- initialDaemonState,
3596
- {
3597
- spawnSession,
3598
- stopSession,
3599
- requestShutdown: () => requestShutdown("hypha-app"),
3600
- getTrackedSessions: getCurrentChildren
3601
- }
3602
- );
3603
- logger.log(`Machine service registered: svamp-machine-${machineId}`);
3604
- const artifactSync = new SessionArtifactSync(server, logger.log);
3605
- const debugService = await registerDebugService(server, machineId, {
3606
- machineId,
3607
- getTrackedSessions: getCurrentChildren,
3608
- getSessionService: (sessionId) => {
3609
- for (const [, session] of pidToTrackedSession) {
3610
- if (session.svampSessionId === sessionId) {
3611
- return session.hyphaService;
3612
- }
3613
- }
3614
- return null;
3615
- },
3616
- getArtifactSync: () => artifactSync,
3617
- getSessionsDir: () => SVAMP_HOME
3618
- // Legacy; debug service uses session index now
3619
- });
3620
- logger.log(`Debug service registered: svamp-debug-${machineId}`);
3621
- const persistedSessions = loadPersistedSessions();
3622
- if (persistedSessions.length > 0) {
3623
- logger.log(`Restoring ${persistedSessions.length} persisted session(s)...`);
3624
- for (const persisted of persistedSessions) {
3625
- try {
3626
- const isOrphaned = persisted.machineId && persisted.machineId !== machineId;
3627
- if (isOrphaned) {
3628
- logger.log(`Session ${persisted.sessionId} is from a different machine (${persisted.machineId} vs ${machineId}), marking as orphaned`);
3629
- }
3630
- const result = await spawnSession({
3631
- directory: persisted.directory,
3632
- sessionId: persisted.sessionId,
3633
- resumeSessionId: persisted.claudeResumeId
3634
- });
3635
- if (result.type === "success") {
3636
- logger.log(`Restored session ${persisted.sessionId} (resume=${persisted.claudeResumeId})`);
3637
- if (isOrphaned) {
3638
- for (const [, tracked] of pidToTrackedSession) {
3639
- if (tracked.svampSessionId === persisted.sessionId && tracked.hyphaService) {
3640
- tracked.hyphaService.updateMetadata({
3641
- ...persisted.metadata || {},
3642
- isOrphaned: true,
3643
- originalMachineId: persisted.machineId
3644
- });
3645
- break;
3646
- }
3647
- }
3648
- }
3649
- } else {
3650
- logger.log(`Failed to restore session ${persisted.sessionId}: ${result.type}`);
3651
- }
3652
- } catch (err) {
3653
- logger.error(`Error restoring session ${persisted.sessionId}:`, err.message);
3654
- }
3655
- }
3656
- }
3657
- (async () => {
3658
- try {
3659
- await artifactSync.init();
3660
- logger.log(`[ARTIFACT SYNC] Ready (upload-only, remote sessions stay in artifact store)`);
3661
- } catch (err) {
3662
- logger.log(`[ARTIFACT SYNC] Background init failed: ${err.message}`);
3663
- }
3664
- })();
3665
- let appToken;
3666
- try {
3667
- appToken = await server.generateToken({});
3668
- logger.log(`App connection token generated`);
3669
- } catch (err) {
3670
- logger.log("Could not generate token (server may not support it):", err);
3671
- }
3672
- const supervised = process.env.SVAMP_SUPERVISED === "1";
3673
- const localState = {
3674
- pid: process.pid,
3675
- startTime: (/* @__PURE__ */ new Date()).toISOString(),
3676
- version: DAEMON_VERSION,
3677
- hyphaServerUrl,
3678
- workspace: server.config.workspace,
3679
- machineId,
3680
- supervised
3681
- };
3682
- writeDaemonStateFile(localState);
3683
- console.log("Svamp daemon started successfully!");
3684
- console.log(` Machine ID: ${machineId}`);
3685
- console.log(` Hypha server: ${hyphaServerUrl}`);
3686
- console.log(` Workspace: ${server.config.workspace}`);
3687
- if (appToken) {
3688
- console.log(` App token: ${appToken}`);
3689
- }
3690
- console.log(` Service: svamp-machine-${machineId}`);
3691
- console.log(` Log file: ${logger.logFilePath}`);
3692
- let consecutiveHeartbeatFailures = 0;
3693
- const MAX_HEARTBEAT_FAILURES = 10;
3694
- const heartbeatInterval = setInterval(async () => {
3695
- try {
3696
- const state = readDaemonStateFile();
3697
- if (state && state.pid === process.pid) {
3698
- state.lastHeartbeat = (/* @__PURE__ */ new Date()).toISOString();
3699
- writeDaemonStateFile(state);
3700
- }
3701
- } catch {
3702
- }
3703
- try {
3704
- const installedVersion = readPackageVersion();
3705
- if (installedVersion !== "unknown" && installedVersion !== DAEMON_VERSION) {
3706
- logger.log(`svamp-cli version changed on disk: ${DAEMON_VERSION} \u2192 ${installedVersion}. Self-restarting...`);
3707
- const supervised2 = process.env.SVAMP_SUPERVISED === "1";
3708
- if (!supervised2) {
3709
- const { spawn: spawnSelf } = await import('child_process');
3710
- spawnSelf(process.argv[0], process.argv.slice(1), {
3711
- detached: true,
3712
- stdio: "ignore",
3713
- env: process.env
3714
- }).unref();
3715
- await new Promise((r) => setTimeout(r, 500));
3716
- }
3717
- requestShutdown("version-update", `Updated ${DAEMON_VERSION} \u2192 ${installedVersion}`);
3718
- return;
3719
- }
3720
- } catch {
3721
- }
3722
- for (const [key, session] of pidToTrackedSession) {
3723
- const child = session.childProcess;
3724
- if (child && child.pid) {
3725
- try {
3726
- process.kill(child.pid, 0);
3727
- } catch {
3728
- logger.log(`Removing stale session (child PID ${child.pid} dead): ${session.svampSessionId}`);
3729
- session.hyphaService?.disconnect().catch(() => {
3730
- });
3731
- pidToTrackedSession.delete(key);
3732
- }
3733
- }
3734
- }
3735
- const serverAny = server;
3736
- const rpcReconnecting = serverAny._connection?._reconnecting === true;
3737
- if (rpcReconnecting && !isReconnecting) {
3738
- isReconnecting = true;
3739
- logger.log("Detected hypha-rpc reconnection in progress");
3740
- }
3741
- if (isReconnecting) {
3742
- consecutiveHeartbeatFailures++;
3743
- logger.log(`Heartbeat skipped (reconnecting), failures=${consecutiveHeartbeatFailures}/${MAX_HEARTBEAT_FAILURES}`);
3744
- if (consecutiveHeartbeatFailures >= MAX_HEARTBEAT_FAILURES) {
3745
- logger.log("Too many consecutive heartbeat failures during reconnection. Shutting down.");
3746
- requestShutdown("heartbeat-timeout", "Reconnection taking too long");
3747
- }
3748
- return;
3749
- }
3750
- try {
3751
- await Promise.race([
3752
- server.echo("ping"),
3753
- new Promise((_, reject) => setTimeout(() => reject(new Error("Heartbeat ping timed out after 30s")), 3e4))
3754
- ]);
3755
- if (consecutiveHeartbeatFailures > 0) {
3756
- logger.log(`Heartbeat recovered after ${consecutiveHeartbeatFailures} failures`);
3757
- }
3758
- consecutiveHeartbeatFailures = 0;
3759
- isReconnecting = false;
3760
- } catch (err) {
3761
- consecutiveHeartbeatFailures++;
3762
- logger.log(`Hypha keep-alive ping failed (${consecutiveHeartbeatFailures}/${MAX_HEARTBEAT_FAILURES}): ${err.message}`);
3763
- if (!isReconnecting) {
3764
- isReconnecting = true;
3765
- logger.log("Entering reconnection state \u2014 hypha-rpc will attempt to reconnect");
3766
- }
3767
- if (consecutiveHeartbeatFailures >= MAX_HEARTBEAT_FAILURES) {
3768
- logger.log(`Heartbeat failed ${MAX_HEARTBEAT_FAILURES} consecutive times. Shutting down.`);
3769
- requestShutdown("heartbeat-timeout", err.message);
3770
- }
3771
- }
3772
- }, 6e4);
3773
- const cleanup = async (source) => {
3774
- logger.log(`Cleaning up (source: ${source})...`);
3775
- clearInterval(heartbeatInterval);
3776
- if (unhandledRejectionResetTimer) clearTimeout(unhandledRejectionResetTimer);
3777
- machineService.updateDaemonState({
3778
- ...initialDaemonState,
3779
- status: "shutting-down",
3780
- shutdownRequestedAt: Date.now(),
3781
- shutdownSource: source
3782
- });
3783
- await new Promise((r) => setTimeout(r, 200));
3784
- for (const [pid, session] of pidToTrackedSession) {
3785
- session.hyphaService?.disconnect().catch(() => {
3786
- });
3787
- if (session.childProcess) {
3788
- try {
3789
- session.childProcess.kill("SIGTERM");
3790
- } catch {
3791
- }
3792
- }
3793
- }
3794
- try {
3795
- const index = loadSessionIndex();
3796
- for (const [sessionId, entry] of Object.entries(index)) {
3797
- const filePath = getSessionFilePath(entry.directory, sessionId);
3798
- if (existsSync$1(filePath)) {
3799
- const data = JSON.parse(readFileSync$1(filePath, "utf-8"));
3800
- writeFileSync$1(filePath, JSON.stringify({ ...data, stopped: true }, null, 2), "utf-8");
3801
- }
3802
- }
3803
- } catch {
3804
- }
3805
- try {
3806
- await machineService.disconnect();
3807
- } catch {
3808
- }
3809
- try {
3810
- await debugService.disconnect();
3811
- } catch {
3812
- }
3813
- artifactSync.destroy();
3814
- try {
3815
- await server.disconnect();
3816
- } catch {
3817
- }
3818
- cleanupDaemonStateFile();
3819
- logger.log("Cleanup complete");
3820
- };
3821
- const shutdownReq = await resolvesWhenShutdownRequested;
3822
- await cleanup(shutdownReq.source);
3823
- if (process.env.SVAMP_SUPERVISED === "1" && shutdownReq.source === "version-update") {
3824
- process.exit(1);
3825
- }
3826
- process.exit(0);
3827
- } catch (error) {
3828
- logger.error("Fatal error:", error);
3829
- cleanupDaemonStateFile();
3830
- if (server) {
3831
- try {
3832
- await server.disconnect();
3833
- } catch {
3834
- }
3835
- }
3836
- process.exit(1);
3837
- }
3838
- }
3839
- async function stopDaemon() {
3840
- const state = readDaemonStateFile();
3841
- if (!state) {
3842
- console.log("No daemon running");
3843
- return;
3844
- }
3845
- try {
3846
- process.kill(state.pid, 0);
3847
- process.kill(state.pid, "SIGTERM");
3848
- console.log(`Sent SIGTERM to daemon PID ${state.pid}`);
3849
- for (let i = 0; i < 30; i++) {
3850
- await new Promise((r) => setTimeout(r, 100));
3851
- try {
3852
- process.kill(state.pid, 0);
3853
- } catch {
3854
- console.log("Daemon stopped");
3855
- cleanupDaemonStateFile();
3856
- return;
3857
- }
3858
- }
3859
- console.log("Daemon did not stop in time, sending SIGKILL");
3860
- process.kill(state.pid, "SIGKILL");
3861
- } catch {
3862
- console.log("Daemon is not running (stale state file)");
3863
- }
3864
- cleanupDaemonStateFile();
3865
- }
3866
- function daemonStatus() {
3867
- const state = readDaemonStateFile();
3868
- if (!state) {
3869
- const plistPath = join$1(os.homedir(), "Library", "LaunchAgents", "io.hypha.svamp.daemon.plist");
3870
- if (existsSync$1(plistPath)) {
3871
- console.log("Status: Not running (launchd service installed \u2014 may be starting)");
3872
- } else {
3873
- console.log("Status: Not running");
3874
- }
3875
- return;
3876
- }
3877
- const alive = isDaemonAlive();
3878
- console.log(`Status: ${alive ? "Running" : "Dead (stale state)"}`);
3879
- console.log(` PID: ${state.pid}`);
3880
- console.log(` Started: ${state.startTime}`);
3881
- console.log(` Version: ${state.version || "unknown"}`);
3882
- console.log(` Hypha server: ${state.hyphaServerUrl}`);
3883
- if (state.workspace) {
3884
- console.log(` Workspace: ${state.workspace}`);
3885
- }
3886
- if (state.lastHeartbeat) {
3887
- console.log(` Last heartbeat: ${state.lastHeartbeat}`);
3888
- }
3889
- if (state.supervised) {
3890
- console.log(` Managed by: supervisor (auto-restart on crash enabled)`);
3891
- }
3892
- if (!alive) {
3893
- cleanupDaemonStateFile();
3894
- }
3895
- }
3896
-
3897
- export { DefaultTransport$1 as D, GeminiTransport$1 as G, registerSessionService as a, stopDaemon as b, acpBackend as c, daemonStatus as d, acpAgentConfig as e, registerMachineService as r, startDaemon as s };