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