svamp-cli 0.2.190 → 0.2.192

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,379 @@
1
+ import { existsSync, readFileSync, mkdirSync, writeFileSync, renameSync } from 'node:fs';
2
+ import { join, dirname } from 'node:path';
3
+ import os from 'node:os';
4
+ import { requireNotSandboxed } from './sandboxDetect-DNTcbgWD.mjs';
5
+ import { x as shortId } from './run-DZLwKdGH.mjs';
6
+ import 'os';
7
+ import 'fs/promises';
8
+ import 'fs';
9
+ import 'path';
10
+ import 'url';
11
+ import 'child_process';
12
+ import 'crypto';
13
+ import 'node:crypto';
14
+ import 'node:child_process';
15
+ import 'util';
16
+ import 'node:events';
17
+ import '@agentclientprotocol/sdk';
18
+ import '@modelcontextprotocol/sdk/client/index.js';
19
+ import '@modelcontextprotocol/sdk/client/stdio.js';
20
+ import '@modelcontextprotocol/sdk/types.js';
21
+ import 'zod';
22
+ import 'node:fs/promises';
23
+ import 'node:util';
24
+
25
+ const SVAMP_HOME = process.env.SVAMP_HOME || join(os.homedir(), ".svamp");
26
+ function getConfigPath(sessionId) {
27
+ const cwd = process.cwd();
28
+ return join(cwd, ".svamp", sessionId, "config.json");
29
+ }
30
+ function readConfig(configPath) {
31
+ try {
32
+ if (existsSync(configPath)) return JSON.parse(readFileSync(configPath, "utf-8"));
33
+ } catch {
34
+ }
35
+ return {};
36
+ }
37
+ function writeConfig(configPath, config) {
38
+ mkdirSync(dirname(configPath), { recursive: true });
39
+ const tmp = configPath + ".tmp";
40
+ writeFileSync(tmp, JSON.stringify(config, null, 2));
41
+ renameSync(tmp, configPath);
42
+ }
43
+ async function connectAndEmit(event) {
44
+ const ENV_FILE = join(SVAMP_HOME, ".env");
45
+ if (existsSync(ENV_FILE)) {
46
+ const lines = readFileSync(ENV_FILE, "utf-8").split("\n");
47
+ for (const line of lines) {
48
+ const m = line.match(/^([A-Z_]+)=(.*)/);
49
+ if (m && !process.env[m[1]]) process.env[m[1]] = m[2].replace(/^["']|["']$/g, "");
50
+ }
51
+ }
52
+ const serverUrl = process.env.HYPHA_SERVER_URL;
53
+ const token = process.env.HYPHA_TOKEN;
54
+ if (!serverUrl || !token) {
55
+ console.error('No Hypha credentials. Run "svamp login" first.');
56
+ process.exit(1);
57
+ }
58
+ const origLog = console.log;
59
+ const origWarn = console.warn;
60
+ const origInfo = console.info;
61
+ console.log = () => {
62
+ };
63
+ console.warn = () => {
64
+ };
65
+ console.info = () => {
66
+ };
67
+ let server;
68
+ try {
69
+ const mod = await import('hypha-rpc');
70
+ const connectToServer = mod.connectToServer || mod.default?.connectToServer;
71
+ server = await connectToServer({ server_url: serverUrl, token, name: "svamp-agent-emit" });
72
+ } catch (err) {
73
+ console.log = origLog;
74
+ console.warn = origWarn;
75
+ console.info = origInfo;
76
+ console.error(`Failed to connect to Hypha: ${err.message}`);
77
+ process.exit(1);
78
+ }
79
+ console.log = origLog;
80
+ console.warn = origWarn;
81
+ console.info = origInfo;
82
+ await server.emit({ ...event, to: "*" });
83
+ await server.disconnect();
84
+ }
85
+ async function sessionSetTitle(title) {
86
+ const sessionId = process.env.SVAMP_SESSION_ID;
87
+ if (!sessionId) {
88
+ console.error("SVAMP_SESSION_ID not set. This command must be run inside a Svamp session.");
89
+ process.exit(1);
90
+ }
91
+ const configPath = getConfigPath(sessionId);
92
+ const config = readConfig(configPath);
93
+ config.title = title.trim();
94
+ writeConfig(configPath, config);
95
+ console.log(`Session title set: "${title.trim()}"`);
96
+ }
97
+ async function sessionSetProjectDescription(description) {
98
+ const dir = process.cwd();
99
+ const { projectName, writeProjectInfo, sanitizeDescription, projectInfoPath } = await import('./run-DZLwKdGH.mjs').then(function (n) { return n.a5; });
100
+ const desc = sanitizeDescription(description, 240);
101
+ if (!desc) {
102
+ console.error("Project description is empty.");
103
+ process.exit(1);
104
+ }
105
+ const name = projectName(dir);
106
+ writeProjectInfo(dir, { name, description: desc, source: "manual", updatedAt: Date.now() });
107
+ console.log(`Project description set for "${name}": "${desc}"`);
108
+ console.log(`Shared across all sessions in this project (${projectInfoPath(dir)}).`);
109
+ }
110
+ async function sessionSetLink(url, label) {
111
+ const sessionId = process.env.SVAMP_SESSION_ID;
112
+ if (!sessionId) {
113
+ console.error("SVAMP_SESSION_ID not set. This command must be run inside a Svamp session.");
114
+ process.exit(1);
115
+ }
116
+ const resolvedLabel = label?.trim() || (() => {
117
+ try {
118
+ return new URL(url).hostname;
119
+ } catch {
120
+ return "View";
121
+ }
122
+ })();
123
+ const configPath = getConfigPath(sessionId);
124
+ const config = readConfig(configPath);
125
+ config.session_link = { url: url.trim(), label: resolvedLabel };
126
+ writeConfig(configPath, config);
127
+ console.log(`Session link set: "${resolvedLabel}" \u2192 ${url.trim()}`);
128
+ }
129
+ async function sessionNotify(message, level = "info") {
130
+ requireNotSandboxed("session notify");
131
+ const sessionId = process.env.SVAMP_SESSION_ID;
132
+ if (!sessionId) {
133
+ console.error("SVAMP_SESSION_ID not set. This command must be run inside a Svamp session.");
134
+ process.exit(1);
135
+ }
136
+ await connectAndEmit({
137
+ type: "svamp:session-notify",
138
+ data: { sessionId, message, level, timestamp: Date.now() }
139
+ });
140
+ console.log(`Notification sent [${level}]: ${message}`);
141
+ }
142
+ async function sessionBroadcast(action, args) {
143
+ requireNotSandboxed("session broadcast");
144
+ const sessionId = process.env.SVAMP_SESSION_ID;
145
+ if (!sessionId) {
146
+ console.error("SVAMP_SESSION_ID not set. This command must be run inside a Svamp session.");
147
+ process.exit(1);
148
+ }
149
+ let payload = { action };
150
+ if (action === "open-canvas") {
151
+ const url = args[0];
152
+ if (!url) {
153
+ console.error("Usage: svamp session broadcast open-canvas <url> [label]");
154
+ process.exit(1);
155
+ }
156
+ const label = args[1] || (() => {
157
+ try {
158
+ return new URL(url).hostname;
159
+ } catch {
160
+ return "View";
161
+ }
162
+ })();
163
+ payload = { action, url, label };
164
+ } else if (action === "close-canvas") ; else if (action === "toast") {
165
+ const message = args[0];
166
+ if (!message) {
167
+ console.error("Usage: svamp session broadcast toast <message>");
168
+ process.exit(1);
169
+ }
170
+ payload = { action, message };
171
+ } else {
172
+ console.error(`Unknown broadcast action: ${action}`);
173
+ console.error("Available actions: open-canvas, close-canvas, toast");
174
+ process.exit(1);
175
+ }
176
+ await connectAndEmit({
177
+ type: "svamp:session-broadcast",
178
+ data: { sessionId, ...payload }
179
+ });
180
+ console.log(`Broadcast sent: ${action}`);
181
+ }
182
+ async function connectToMachineService() {
183
+ const { connectAndGetMachine } = await import('./commands-CkxVt5V0.mjs');
184
+ return connectAndGetMachine();
185
+ }
186
+ function buildInboxMessage(args) {
187
+ return {
188
+ messageId: shortId(),
189
+ body: args.body,
190
+ timestamp: Date.now(),
191
+ read: false,
192
+ from: `agent:${args.fromSessionId}`,
193
+ fromSession: args.fromSessionId,
194
+ to: args.to,
195
+ subject: args.subject,
196
+ urgency: args.urgency || "normal",
197
+ ...args.replyTo ? { replyTo: args.replyTo } : {},
198
+ ...args.threadId ? { threadId: args.threadId } : {}
199
+ };
200
+ }
201
+ async function inboxSendCore(resolve, args) {
202
+ const { machine, fullId } = await resolve(args.target);
203
+ const message = buildInboxMessage({
204
+ fromSessionId: args.fromSessionId,
205
+ to: fullId,
206
+ body: args.body,
207
+ subject: args.subject,
208
+ urgency: args.urgency
209
+ });
210
+ const result = await machine.sessionRPC(fullId, "sendInboxMessage", { message });
211
+ return { targetId: fullId, messageId: result.messageId, message };
212
+ }
213
+ async function inboxReplyCore(localMachine, resolve, args) {
214
+ const result = await localMachine.sessionRPC(args.sessionId, "getInbox", {});
215
+ const original = (result.messages || []).find(
216
+ (m) => m.messageId === args.messageId || m.messageId.startsWith(args.messageId)
217
+ );
218
+ if (!original) return { kind: "not-found" };
219
+ let channelDelivered = false;
220
+ if (original.channelId && original.correlationId) {
221
+ const rr = await localMachine.sessionRPC(args.sessionId, "channelReply", {
222
+ params: { channel: original.channelId, correlationId: original.correlationId, to: original.from, body: args.body }
223
+ });
224
+ if (rr?.error) {
225
+ if (!original.fromSession) return { kind: "channel-error", error: rr.error };
226
+ } else channelDelivered = true;
227
+ }
228
+ if (original.fromSession) {
229
+ try {
230
+ const { machine, fullId } = await resolve(original.fromSession);
231
+ const reply = buildInboxMessage({
232
+ fromSessionId: args.sessionId,
233
+ to: fullId,
234
+ body: args.body,
235
+ subject: original.subject ? `Re: ${original.subject}` : void 0,
236
+ replyTo: original.messageId,
237
+ threadId: original.threadId || original.messageId
238
+ });
239
+ const sendResult = await machine.sessionRPC(fullId, "sendInboxMessage", { message: reply });
240
+ return { kind: "sent", targetId: fullId, messageId: sendResult.messageId, message: reply };
241
+ } catch (err) {
242
+ if (channelDelivered) return { kind: "channel", from: original.from, channelId: original.channelId, correlationId: original.correlationId };
243
+ throw err;
244
+ }
245
+ }
246
+ if (channelDelivered) return { kind: "channel", from: original.from, channelId: original.channelId, correlationId: original.correlationId };
247
+ return { kind: "no-from-session" };
248
+ }
249
+ async function inboxSend(targetSessionId, opts) {
250
+ requireNotSandboxed("inbox send");
251
+ const sessionId = process.env.SVAMP_SESSION_ID;
252
+ if (!sessionId) {
253
+ console.error("SVAMP_SESSION_ID not set. This command must be run inside a Svamp session.");
254
+ process.exit(1);
255
+ }
256
+ const body = opts?.body || "";
257
+ if (!body) {
258
+ console.error("Message body is required.");
259
+ process.exit(1);
260
+ }
261
+ const { connectAndResolveSession } = await import('./commands-CkxVt5V0.mjs');
262
+ let server;
263
+ try {
264
+ const { targetId, messageId } = await inboxSendCore(
265
+ async (target) => {
266
+ const r = await connectAndResolveSession(target);
267
+ server = r.server;
268
+ return { machine: r.machine, fullId: r.fullId };
269
+ },
270
+ { fromSessionId: sessionId, target: targetSessionId, body, subject: opts?.subject, urgency: opts?.urgency }
271
+ );
272
+ console.log(`Inbox message sent to ${targetId.slice(0, 8)} (id: ${messageId.slice(0, 8)})`);
273
+ } finally {
274
+ if (server) await server.disconnect();
275
+ }
276
+ }
277
+ async function inboxList(opts) {
278
+ requireNotSandboxed("inbox list");
279
+ const sessionId = process.env.SVAMP_SESSION_ID;
280
+ if (!sessionId) {
281
+ console.error("SVAMP_SESSION_ID not set. This command must be run inside a Svamp session.");
282
+ process.exit(1);
283
+ }
284
+ const { server, machine } = await connectToMachineService();
285
+ try {
286
+ const result = await machine.sessionRPC(sessionId, "getInbox", { opts: { unread: opts?.unread, limit: opts?.limit } });
287
+ const messages = result.messages;
288
+ if (opts?.json) {
289
+ console.log(JSON.stringify({ messages }, null, 2));
290
+ return;
291
+ }
292
+ if (messages.length === 0) {
293
+ console.log("Inbox is empty.");
294
+ return;
295
+ }
296
+ for (const msg of messages) {
297
+ const status = msg.read ? " " : "\u25CF";
298
+ const from = msg.from ? ` from ${msg.from}` : "";
299
+ const subject = msg.subject ? ` \u2014 ${msg.subject}` : "";
300
+ const urgencyTag = msg.urgency === "urgent" ? " [URGENT]" : "";
301
+ const preview = msg.body.length > 100 ? msg.body.slice(0, 97) + "..." : msg.body;
302
+ console.log(`${status} ${msg.messageId.slice(0, 8)}${urgencyTag}${from}${subject}: ${preview}`);
303
+ }
304
+ } finally {
305
+ await server.disconnect();
306
+ }
307
+ }
308
+ async function inboxReply(messageId, body) {
309
+ requireNotSandboxed("inbox reply");
310
+ const sessionId = process.env.SVAMP_SESSION_ID;
311
+ if (!sessionId) {
312
+ console.error("SVAMP_SESSION_ID not set. This command must be run inside a Svamp session.");
313
+ process.exit(1);
314
+ }
315
+ const { connectAndResolveSession } = await import('./commands-CkxVt5V0.mjs');
316
+ const { server: localServer, machine: localMachine } = await connectToMachineService();
317
+ let localDisconnected = false;
318
+ const disconnectLocal = async () => {
319
+ if (!localDisconnected) {
320
+ localDisconnected = true;
321
+ try {
322
+ await localServer.disconnect();
323
+ } catch {
324
+ }
325
+ }
326
+ };
327
+ let senderServer;
328
+ try {
329
+ const res = await inboxReplyCore(
330
+ localMachine,
331
+ async (target) => {
332
+ await disconnectLocal();
333
+ const r = await connectAndResolveSession(target);
334
+ senderServer = r.server;
335
+ return { machine: r.machine, fullId: r.fullId };
336
+ },
337
+ { sessionId, messageId, body }
338
+ );
339
+ switch (res.kind) {
340
+ case "not-found":
341
+ console.error(`Message ${messageId} not found in inbox.`);
342
+ process.exit(1);
343
+ break;
344
+ case "no-from-session":
345
+ console.error("Cannot reply: original message has no fromSession (and not a channel message).");
346
+ process.exit(1);
347
+ break;
348
+ case "channel-error":
349
+ console.error(`Channel reply failed: ${res.error}`);
350
+ process.exit(1);
351
+ break;
352
+ case "channel":
353
+ console.log(`Reply queued to "${res.from}" on channel ${res.channelId} (correlation ${res.correlationId}).`);
354
+ break;
355
+ case "sent":
356
+ console.log(`Reply sent to ${res.targetId.slice(0, 8)} (id: ${res.messageId.slice(0, 8)})`);
357
+ break;
358
+ }
359
+ } finally {
360
+ await disconnectLocal();
361
+ if (senderServer) {
362
+ try {
363
+ await senderServer.disconnect();
364
+ } catch {
365
+ }
366
+ }
367
+ }
368
+ }
369
+ async function machineNotify(message, level = "info") {
370
+ requireNotSandboxed("machine notify");
371
+ const machineId = process.env.SVAMP_MACHINE_ID;
372
+ await connectAndEmit({
373
+ type: "svamp:machine-notify",
374
+ data: { machineId, message, level, timestamp: Date.now() }
375
+ });
376
+ console.log(`Machine notification sent [${level}]: ${message}`);
377
+ }
378
+
379
+ export { buildInboxMessage, inboxList, inboxReply, inboxReplyCore, inboxSend, inboxSendCore, machineNotify, sessionBroadcast, sessionNotify, sessionSetLink, sessionSetProjectDescription, sessionSetTitle };
@@ -0,0 +1,83 @@
1
+ import { M as resolveModel } from './run-DZLwKdGH.mjs';
2
+ import 'os';
3
+ import 'fs/promises';
4
+ import 'fs';
5
+ import 'path';
6
+ import 'url';
7
+ import 'child_process';
8
+ import 'crypto';
9
+ import 'node:crypto';
10
+ import 'node:fs';
11
+ import 'node:child_process';
12
+ import 'util';
13
+ import 'node:path';
14
+ import 'node:events';
15
+ import 'node:os';
16
+ import '@agentclientprotocol/sdk';
17
+ import '@modelcontextprotocol/sdk/client/index.js';
18
+ import '@modelcontextprotocol/sdk/client/stdio.js';
19
+ import '@modelcontextprotocol/sdk/types.js';
20
+ import 'zod';
21
+ import 'node:fs/promises';
22
+ import 'node:util';
23
+
24
+ function buildWiseAgentEnvUpdates(action) {
25
+ switch (action.kind) {
26
+ case "use-openai":
27
+ return { WISE_AGENT_PROVIDER: "openai", ...action.key ? { WISE_AGENT_API_KEY: action.key } : {} };
28
+ case "use-hypha-proxy":
29
+ return { WISE_AGENT_PROVIDER: "hypha-proxy", ...action.url ? { SVAMP_HYPHA_PROXY_URL: action.url } : {} };
30
+ case "use-claude-haiku":
31
+ return { WISE_AGENT_PROVIDER: "claude-haiku", WISE_AGENT_MODEL: void 0, ...action.url ? { SVAMP_HYPHA_PROXY_URL: action.url } : {} };
32
+ case "set":
33
+ return { WISE_AGENT_PROVIDER: "openai", WISE_AGENT_BASE_URL: action.url, WISE_AGENT_API_KEY: action.key };
34
+ case "set-key":
35
+ return { WISE_AGENT_API_KEY: action.key };
36
+ case "set-model":
37
+ return { WISE_AGENT_MODEL: action.model };
38
+ case "set-base-url":
39
+ return { WISE_AGENT_BASE_URL: action.url };
40
+ }
41
+ }
42
+ function redactKey(key) {
43
+ if (!key) return "(none)";
44
+ if (key.length <= 12) return "***";
45
+ return `${key.slice(0, 8)}\u2026${key.slice(-4)}`;
46
+ }
47
+ function describeWiseAgentAuth(env) {
48
+ const r = resolveModel(void 0, env);
49
+ return {
50
+ provider: r.provider,
51
+ model: r.model,
52
+ baseUrl: r.baseUrl || "(unset)",
53
+ keyRedacted: redactKey(r.apiKey)
54
+ };
55
+ }
56
+ function parseWiseAgentAuthArgs(args) {
57
+ const [sub, ...rest] = args;
58
+ if (!sub || sub === "status") return null;
59
+ switch (sub) {
60
+ case "use-openai":
61
+ return { kind: "use-openai", key: rest[0] };
62
+ case "use-hypha-proxy":
63
+ return { kind: "use-hypha-proxy", url: rest[0] };
64
+ case "use-claude-haiku":
65
+ return { kind: "use-claude-haiku", url: rest[0] };
66
+ case "set":
67
+ if (!rest[0] || !rest[1]) throw new Error("Usage: svamp wise-agent auth set <BASE_URL> <KEY>");
68
+ return { kind: "set", url: rest[0], key: rest[1] };
69
+ case "set-key":
70
+ if (!rest[0]) throw new Error("Usage: svamp wise-agent auth set-key <KEY>");
71
+ return { kind: "set-key", key: rest[0] };
72
+ case "set-model":
73
+ if (!rest[0]) throw new Error("Usage: svamp wise-agent auth set-model <model>");
74
+ return { kind: "set-model", model: rest[0] };
75
+ case "set-base-url":
76
+ if (!rest[0]) throw new Error("Usage: svamp wise-agent auth set-base-url <url>");
77
+ return { kind: "set-base-url", url: rest[0] };
78
+ default:
79
+ throw new Error(`Unknown wise-agent auth command "${sub}". Try: status | use-openai [KEY] | use-hypha-proxy [URL] | use-claude-haiku [URL] | set <URL> <KEY> | set-key <KEY> | set-model <m> | set-base-url <url>`);
80
+ }
81
+ }
82
+
83
+ export { buildWiseAgentEnvUpdates, describeWiseAgentAuth, parseWiseAgentAuthArgs, redactKey };