@elizaos/plugin-elizacloud 2.0.3-beta.5 → 2.0.3-beta.6

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.
@@ -20,8 +20,907 @@ var __require = /* @__PURE__ */ createRequire(import.meta.url);
20
20
  import { normalizeCloudSiteUrl, resolveCloudApiBaseUrl } from "@elizaos/shared";
21
21
  var init_base_url = () => {};
22
22
 
23
- // src/cloud/x402-payment-handler.ts
23
+ // src/cloud/validate-url.ts
24
+ import dns from "node:dns";
25
+ import net from "node:net";
26
+ import { promisify } from "node:util";
27
+ function normalizeHostLike(value) {
28
+ return value.trim().toLowerCase().replace(/^\[|\]$/g, "");
29
+ }
30
+ function decodeIpv6MappedHex(mapped) {
31
+ const parts = mapped.split(":");
32
+ if (parts.length < 1 || parts.length > 2)
33
+ return null;
34
+ const parsed = parts.map((part) => {
35
+ if (!/^[0-9a-f]{1,4}$/i.test(part))
36
+ return Number.NaN;
37
+ return Number.parseInt(part, 16);
38
+ });
39
+ if (parsed.some((value) => !Number.isFinite(value)))
40
+ return null;
41
+ const [hi, lo] = parsed.length === 1 ? [0, parsed[0]] : parsed;
42
+ const octets = [hi >> 8, hi & 255, lo >> 8, lo & 255];
43
+ return octets.join(".");
44
+ }
45
+ function canonicalizeIpv6(ip) {
46
+ try {
47
+ return new URL(`http://[${ip}]/`).hostname.replace(/^\[|\]$/g, "");
48
+ } catch {
49
+ return null;
50
+ }
51
+ }
52
+ function normalizeIpForPolicy(ip) {
53
+ const base = normalizeHostLike(ip).split("%")[0];
54
+ if (!base)
55
+ return base;
56
+ let normalized = base;
57
+ if (net.isIP(normalized) === 6) {
58
+ normalized = canonicalizeIpv6(normalized) ?? normalized;
59
+ }
60
+ let mapped = null;
61
+ if (normalized.startsWith("::ffff:")) {
62
+ mapped = normalized.slice("::ffff:".length);
63
+ } else if (normalized.startsWith("0:0:0:0:0:ffff:")) {
64
+ mapped = normalized.slice("0:0:0:0:0:ffff:".length);
65
+ }
66
+ if (!mapped)
67
+ return normalized;
68
+ if (net.isIP(mapped) === 4)
69
+ return mapped;
70
+ return decodeIpv6MappedHex(mapped) ?? normalized;
71
+ }
72
+ function cidrV4(base, prefix) {
73
+ const parsed = parseIpv4ToInt(base);
74
+ if (parsed === null) {
75
+ throw new Error(`Invalid CIDR base IPv4 address: ${base}`);
76
+ }
77
+ const shift = 32 - prefix;
78
+ const mask = shift === 32 ? 0 : 4294967295 << shift >>> 0;
79
+ return { base: parsed & mask, mask };
80
+ }
81
+ function parseIpv4ToInt(ip) {
82
+ const parts = ip.split(".");
83
+ if (parts.length !== 4)
84
+ return null;
85
+ let value = 0;
86
+ for (const part of parts) {
87
+ if (!/^\d{1,3}$/.test(part))
88
+ return null;
89
+ const octet = Number.parseInt(part, 10);
90
+ if (!Number.isInteger(octet) || octet < 0 || octet > 255)
91
+ return null;
92
+ value = value << 8 | octet;
93
+ }
94
+ return value >>> 0;
95
+ }
96
+ function isBlockedIpv4(ip) {
97
+ const asInt = parseIpv4ToInt(ip);
98
+ if (asInt === null)
99
+ return true;
100
+ return BLOCKED_IPV4_CIDRS.some((cidr) => (asInt & cidr.mask) === cidr.base);
101
+ }
102
+ function isBlockedIpv6(ip) {
103
+ const normalized = ip.toLowerCase();
104
+ return normalized === "::" || normalized === "::1" || /^fe[89ab][0-9a-f]:/.test(normalized) || /^f[cd][0-9a-f]{2}:/i.test(normalized) || normalized.startsWith("ff");
105
+ }
106
+ function isBlockedIp(ip) {
107
+ const normalized = normalizeIpForPolicy(ip);
108
+ const family = net.isIP(normalized);
109
+ if (family === 4)
110
+ return isBlockedIpv4(normalized);
111
+ if (family === 6)
112
+ return isBlockedIpv6(normalized);
113
+ return false;
114
+ }
115
+ async function validateCloudBaseUrl(rawUrl) {
116
+ let parsed;
117
+ try {
118
+ parsed = new URL(rawUrl);
119
+ } catch {
120
+ return `Invalid cloud base URL: "${rawUrl}"`;
121
+ }
122
+ if (parsed.protocol !== "https:") {
123
+ return `Cloud base URL must use HTTPS, got "${parsed.protocol}" in "${rawUrl}"`;
124
+ }
125
+ const hostname = normalizeHostLike(parsed.hostname);
126
+ if (!hostname) {
127
+ return `Invalid cloud base URL: "${rawUrl}"`;
128
+ }
129
+ if (hostname === "localhost" || hostname.endsWith(".localhost") || hostname.endsWith(".local")) {
130
+ return `Cloud base URL "${rawUrl}" points to a blocked local hostname.`;
131
+ }
132
+ const elizaDev = process.env.ELIZA_DEV?.trim().toLowerCase();
133
+ if (true) {
134
+ return null;
135
+ }
136
+ if (isBlockedIp(hostname)) {
137
+ return `Cloud base URL "${rawUrl}" points to a blocked address.`;
138
+ }
139
+ try {
140
+ const results = await dnsLookupAll(hostname, { all: true });
141
+ const addresses = Array.isArray(results) ? results : [results];
142
+ for (const entry of addresses) {
143
+ const ip = typeof entry === "string" ? entry : entry.address;
144
+ if (isBlockedIp(ip)) {
145
+ return `Cloud base URL "${rawUrl}" resolves to ${ip}, ` + "which is a blocked internal/metadata address.";
146
+ }
147
+ }
148
+ } catch {
149
+ return `Cloud base URL "${rawUrl}" could not be resolved via DNS.`;
150
+ }
151
+ return null;
152
+ }
153
+ var dnsLookupAll, BLOCKED_IPV4_CIDRS;
154
+ var init_validate_url = __esm(() => {
155
+ dnsLookupAll = promisify(dns.lookup);
156
+ BLOCKED_IPV4_CIDRS = [
157
+ cidrV4("0.0.0.0", 8),
158
+ cidrV4("10.0.0.0", 8),
159
+ cidrV4("172.16.0.0", 12),
160
+ cidrV4("192.168.0.0", 16),
161
+ cidrV4("100.64.0.0", 10),
162
+ cidrV4("127.0.0.0", 8),
163
+ cidrV4("169.254.0.0", 16),
164
+ cidrV4("192.0.0.0", 24),
165
+ cidrV4("198.18.0.0", 15),
166
+ cidrV4("192.0.2.0", 24),
167
+ cidrV4("198.51.100.0", 24),
168
+ cidrV4("203.0.113.0", 24),
169
+ cidrV4("224.0.0.0", 4),
170
+ cidrV4("240.0.0.0", 4)
171
+ ];
172
+ });
173
+
174
+ // src/cloud/auth-service-types.ts
175
+ function isCloudAuthApiKeyService(value) {
176
+ return value !== null && value !== undefined && typeof value.isAuthenticated === "function";
177
+ }
178
+ function normalizeCloudApiKey(value) {
179
+ if (typeof value !== "string")
180
+ return null;
181
+ const trimmed = value.trim();
182
+ if (!trimmed || trimmed.toUpperCase() === "[REDACTED]")
183
+ return null;
184
+ return trimmed;
185
+ }
186
+
187
+ // src/cloud/auth.ts
188
+ init_base_url();
189
+ init_validate_url();
190
+ import crypto2 from "node:crypto";
24
191
  import { logger } from "@elizaos/core";
192
+ var DEFAULT_CLOUD_REQUEST_TIMEOUT_MS = 1e4;
193
+ function isRedirectResponse(response) {
194
+ return response.status >= 300 && response.status < 400;
195
+ }
196
+ function isTimeoutError(err) {
197
+ if (!(err instanceof Error))
198
+ return false;
199
+ if (err.name === "TimeoutError" || err.name === "AbortError")
200
+ return true;
201
+ const msg = err.message.toLowerCase();
202
+ return msg.includes("timed out") || msg.includes("timeout");
203
+ }
204
+ async function fetchWithTimeout(input, init, timeoutMs) {
205
+ return fetch(input, {
206
+ ...init,
207
+ redirect: "manual",
208
+ signal: AbortSignal.timeout(timeoutMs)
209
+ });
210
+ }
211
+ async function cloudLogin(options = {}) {
212
+ const baseUrl = normalizeCloudSiteUrl(options.baseUrl);
213
+ const urlError = await validateCloudBaseUrl(baseUrl);
214
+ if (urlError) {
215
+ throw new Error(urlError);
216
+ }
217
+ const timeoutMs = options.timeoutMs ?? 300000;
218
+ const requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_CLOUD_REQUEST_TIMEOUT_MS;
219
+ const pollIntervalMs = options.pollIntervalMs ?? 2000;
220
+ const sessionId = crypto2.randomUUID();
221
+ logger.info("[cloud-auth] Creating auth session...");
222
+ let createResponse;
223
+ try {
224
+ createResponse = await fetchWithTimeout(`${baseUrl}/api/auth/cli-session`, {
225
+ method: "POST",
226
+ headers: { "Content-Type": "application/json" },
227
+ body: JSON.stringify({ sessionId })
228
+ }, requestTimeoutMs);
229
+ } catch (err) {
230
+ if (isTimeoutError(err)) {
231
+ throw new Error(`Cloud login request timed out while creating session (>${requestTimeoutMs}ms).`);
232
+ }
233
+ throw new Error(`Failed to create auth session: ${String(err)}`);
234
+ }
235
+ if (!createResponse.ok) {
236
+ if (isRedirectResponse(createResponse)) {
237
+ throw new Error("Cloud login request was redirected; redirects are not allowed.");
238
+ }
239
+ const errorText = await createResponse.text();
240
+ throw new Error(`Failed to create auth session (HTTP ${createResponse.status}): ${errorText}`);
241
+ }
242
+ const browserUrl = `${baseUrl}/auth/cli-login?session=${encodeURIComponent(sessionId)}`;
243
+ logger.info(`[cloud-auth] Browser URL: ${browserUrl}`);
244
+ options.onBrowserUrl?.(browserUrl);
245
+ const deadline = Date.now() + timeoutMs;
246
+ while (Date.now() < deadline) {
247
+ const remainingBeforeSleep = deadline - Date.now();
248
+ if (remainingBeforeSleep <= 0)
249
+ break;
250
+ await new Promise((resolve) => setTimeout(resolve, Math.min(pollIntervalMs, remainingBeforeSleep)));
251
+ const remaining = deadline - Date.now();
252
+ if (remaining <= 0)
253
+ break;
254
+ let pollResponse;
255
+ try {
256
+ pollResponse = await fetchWithTimeout(`${baseUrl}/api/auth/cli-session/${encodeURIComponent(sessionId)}`, {}, Math.min(requestTimeoutMs, remaining));
257
+ } catch (err) {
258
+ if (isTimeoutError(err)) {
259
+ if (remaining <= requestTimeoutMs) {
260
+ break;
261
+ }
262
+ throw new Error(`Cloud login polling request timed out (>${Math.min(requestTimeoutMs, remaining)}ms).`);
263
+ }
264
+ throw new Error(`Cloud login polling failed: ${String(err)}`);
265
+ }
266
+ if (!pollResponse.ok) {
267
+ if (isRedirectResponse(pollResponse)) {
268
+ throw new Error("Cloud login polling request was redirected; redirects are not allowed.");
269
+ }
270
+ if (pollResponse.status === 404) {
271
+ throw new Error("Auth session expired or not found. Please try again.");
272
+ }
273
+ options.onPollStatus?.("error");
274
+ continue;
275
+ }
276
+ const data = await pollResponse.json();
277
+ options.onPollStatus?.(data.status);
278
+ if (data.status === "authenticated" && data.apiKey) {
279
+ logger.info("[cloud-auth] Authentication complete");
280
+ return {
281
+ apiKey: data.apiKey,
282
+ keyPrefix: data.keyPrefix ?? "",
283
+ expiresAt: data.expiresAt ?? null
284
+ };
285
+ }
286
+ if (data.status === "authenticated" && !data.apiKey) {
287
+ throw new Error("Auth session was completed but the API key was already retrieved. Please try logging in again.");
288
+ }
289
+ }
290
+ throw new Error(`Cloud login timed out. The browser login was not completed within ${Math.round(timeoutMs / 1000)} seconds.`);
291
+ }
292
+
293
+ // src/cloud/bridge-client.ts
294
+ init_base_url();
295
+
296
+ class CloudBridgeError extends Error {
297
+ status;
298
+ body;
299
+ constructor(message, status, body) {
300
+ super(message);
301
+ this.status = status;
302
+ this.body = body;
303
+ this.name = "CloudBridgeError";
304
+ }
305
+ }
306
+
307
+ class SignatureInvalidError extends CloudBridgeError {
308
+ constructor(message, body) {
309
+ super(message, 401, body);
310
+ this.name = "SignatureInvalidError";
311
+ }
312
+ }
313
+
314
+ class NonceReplayError extends CloudBridgeError {
315
+ constructor(message, body) {
316
+ super(message, 409, body);
317
+ this.name = "NonceReplayError";
318
+ }
319
+ }
320
+
321
+ class SessionExpiredError extends CloudBridgeError {
322
+ constructor(message, body) {
323
+ super(message, 410, body);
324
+ this.name = "SessionExpiredError";
325
+ }
326
+ }
327
+
328
+ class CloudUnavailableError extends CloudBridgeError {
329
+ constructor(message, status, body) {
330
+ super(message, status, body);
331
+ this.name = "CloudUnavailableError";
332
+ }
333
+ }
334
+ function formatApiErrorBody(text) {
335
+ if (!text)
336
+ return null;
337
+ try {
338
+ const parsed = JSON.parse(text);
339
+ const baseError = typeof parsed.error === "string" && parsed.error.trim().length > 0 ? parsed.error.trim() : null;
340
+ const details = Array.isArray(parsed.details) ? parsed.details.map((detail) => typeof detail?.message === "string" ? detail.message.trim() : "").filter((message) => message.length > 0) : [];
341
+ if (baseError && details.length > 0) {
342
+ return `${baseError}: ${details.join("; ")}`;
343
+ }
344
+ if (baseError)
345
+ return baseError;
346
+ } catch {}
347
+ return text.slice(0, 200) || null;
348
+ }
349
+ function isRedirectResponse2(response) {
350
+ return response.status >= 300 && response.status < 400;
351
+ }
352
+ function normalizeChainAddress(addresses, chain) {
353
+ const value = addresses?.[chain];
354
+ if (typeof value !== "string")
355
+ return null;
356
+ const trimmed = value.trim();
357
+ return trimmed.length > 0 ? trimmed : null;
358
+ }
359
+ function looksLikeChainAddress(address, chain) {
360
+ if (chain === "evm") {
361
+ return /^0x[a-fA-F0-9]{40}$/.test(address);
362
+ }
363
+ return /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(address);
364
+ }
365
+ function resolveRequestedWalletAddress(data, chain) {
366
+ const explicit = normalizeChainAddress(data.walletAddresses, chain);
367
+ if (explicit)
368
+ return explicit;
369
+ if (typeof data.walletAddress !== "string")
370
+ return null;
371
+ const trimmed = data.walletAddress.trim();
372
+ if (!trimmed)
373
+ return null;
374
+ return looksLikeChainAddress(trimmed, chain) ? trimmed : null;
375
+ }
376
+
377
+ class ElizaCloudClient {
378
+ baseUrl;
379
+ apiKey;
380
+ constructor(baseUrl, apiKey) {
381
+ this.baseUrl = normalizeCloudSiteUrl(baseUrl);
382
+ this.apiKey = apiKey;
383
+ }
384
+ async listAgents() {
385
+ const res = await this.request("GET", "/api/v1/eliza/agents");
386
+ return res.data ?? [];
387
+ }
388
+ async createAgent(params) {
389
+ const res = await this.request("POST", "/api/v1/eliza/agents", params);
390
+ if (!res.success || !res.data)
391
+ throw new Error(res.error ?? "Failed to create cloud agent");
392
+ return res.data;
393
+ }
394
+ async getAgent(agentId) {
395
+ const res = await this.request("GET", `/api/v1/eliza/agents/${agentId}`);
396
+ if (!res.success || !res.data)
397
+ throw new Error(res.error ?? "Agent not found");
398
+ return res.data;
399
+ }
400
+ async deleteAgent(agentId) {
401
+ const res = await this.request("DELETE", `/api/v1/eliza/agents/${agentId}`);
402
+ if (!res.success)
403
+ throw new Error(res.error ?? "Failed to delete agent");
404
+ }
405
+ async provision(agentId) {
406
+ const res = await this.request("POST", `/api/v1/eliza/agents/${agentId}/provision`);
407
+ if (!res.success || !res.data)
408
+ throw new Error(res.error ?? "Failed to provision sandbox");
409
+ return res.data;
410
+ }
411
+ async sendMessage(agentId, text, roomId = "web-chat", channelType = "DM") {
412
+ const url = `${this.baseUrl}/api/v1/eliza/agents/${agentId}/bridge`;
413
+ const response = await fetch(url, {
414
+ method: "POST",
415
+ headers: { "Content-Type": "application/json", "X-Api-Key": this.apiKey },
416
+ body: JSON.stringify({
417
+ jsonrpc: "2.0",
418
+ id: crypto.randomUUID(),
419
+ method: "message.send",
420
+ params: { text, roomId, channelType }
421
+ }),
422
+ redirect: "manual",
423
+ signal: AbortSignal.timeout(60000)
424
+ });
425
+ if (isRedirectResponse2(response)) {
426
+ throw new Error("Bridge request was redirected; redirects are not allowed");
427
+ }
428
+ if (!response.ok) {
429
+ const errorText = await response.text().catch(() => "");
430
+ throw new Error(`Bridge request failed: HTTP ${response.status} ${errorText.slice(0, 200)}`);
431
+ }
432
+ const rpc = await response.json();
433
+ if (rpc.error)
434
+ throw new Error(rpc.error.message);
435
+ return rpc.result?.text ?? "(no response)";
436
+ }
437
+ async* sendMessageStream(agentId, text, roomId = "web-chat", channelType = "DM") {
438
+ const url = `${this.baseUrl}/api/v1/eliza/agents/${agentId}/stream`;
439
+ const response = await fetch(url, {
440
+ method: "POST",
441
+ headers: { "Content-Type": "application/json", "X-Api-Key": this.apiKey },
442
+ body: JSON.stringify({
443
+ jsonrpc: "2.0",
444
+ id: crypto.randomUUID(),
445
+ method: "message.send",
446
+ params: { text, roomId, channelType }
447
+ }),
448
+ redirect: "manual"
449
+ });
450
+ if (isRedirectResponse2(response)) {
451
+ throw new Error("Stream request was redirected; redirects are not allowed");
452
+ }
453
+ if (!response.ok || !response.body) {
454
+ throw new Error(`Stream request failed: HTTP ${response.status}`);
455
+ }
456
+ const reader = response.body.getReader();
457
+ const decoder = new TextDecoder;
458
+ let buffer = "";
459
+ for (;; ) {
460
+ const { done, value } = await reader.read();
461
+ if (done)
462
+ break;
463
+ buffer += decoder.decode(value, { stream: true });
464
+ const parts = buffer.split(`
465
+
466
+ `);
467
+ buffer = parts.pop() ?? "";
468
+ for (const part of parts) {
469
+ if (!part.trim())
470
+ continue;
471
+ let eventType = "message";
472
+ let eventData = "";
473
+ for (const line of part.split(`
474
+ `)) {
475
+ if (line.startsWith("event: "))
476
+ eventType = line.slice(7).trim();
477
+ else if (line.startsWith("data: "))
478
+ eventData += (eventData ? `
479
+ ` : "") + line.slice(6);
480
+ }
481
+ if (eventData) {
482
+ let data;
483
+ try {
484
+ data = JSON.parse(eventData);
485
+ } catch {
486
+ continue;
487
+ }
488
+ yield { type: eventType, data };
489
+ }
490
+ }
491
+ }
492
+ }
493
+ async snapshot(agentId) {
494
+ const res = await this.request("POST", `/api/v1/eliza/agents/${agentId}/snapshot`);
495
+ if (!res.success || !res.data)
496
+ throw new Error(res.error ?? "Snapshot failed");
497
+ return res.data;
498
+ }
499
+ async listBackups(agentId) {
500
+ const res = await this.request("GET", `/api/v1/eliza/agents/${agentId}/backups`);
501
+ return res.data ?? [];
502
+ }
503
+ async restore(agentId, backupId) {
504
+ const res = await this.request("POST", `/api/v1/eliza/agents/${agentId}/restore`, backupId ? { backupId } : {});
505
+ if (!res.success)
506
+ throw new Error(res.error ?? "Restore failed");
507
+ }
508
+ async heartbeat(agentId) {
509
+ const url = `${this.baseUrl}/api/v1/eliza/agents/${agentId}/bridge`;
510
+ try {
511
+ const response = await fetch(url, {
512
+ method: "POST",
513
+ headers: {
514
+ "Content-Type": "application/json",
515
+ "X-Api-Key": this.apiKey
516
+ },
517
+ body: JSON.stringify({ jsonrpc: "2.0", method: "heartbeat" }),
518
+ redirect: "manual",
519
+ signal: AbortSignal.timeout(1e4)
520
+ });
521
+ if (isRedirectResponse2(response))
522
+ return false;
523
+ return response.ok;
524
+ } catch {
525
+ return false;
526
+ }
527
+ }
528
+ async getAgentWallet(agentId, chain) {
529
+ const res = await this.request("GET", `/api/v1/eliza/agents/${encodeURIComponent(agentId)}/wallet?chain=${encodeURIComponent(chain)}`);
530
+ if (!res.success || !res.data) {
531
+ throw new CloudBridgeError(res.error ?? "Failed to fetch agent wallet");
532
+ }
533
+ const data = res.data;
534
+ const walletAddress = resolveRequestedWalletAddress(data, chain);
535
+ if (!walletAddress || !data.walletProvider) {
536
+ throw new CloudBridgeError(`Agent has no cloud ${chain} wallet provisioned`);
537
+ }
538
+ return {
539
+ agentWalletId: data.agentId ?? agentId,
540
+ walletAddress,
541
+ walletProvider: data.walletProvider,
542
+ chainType: chain,
543
+ balance: data.balance ?? undefined
544
+ };
545
+ }
546
+ async provisionWallet(input) {
547
+ const res = await this.request("POST", "/api/v1/user/wallets/provision", input);
548
+ if (!res.success || !res.data) {
549
+ throw new CloudBridgeError(res.error ?? "Failed to provision wallet");
550
+ }
551
+ return {
552
+ walletId: res.data.id,
553
+ address: res.data.address,
554
+ chainType: res.data.chainType,
555
+ provider: res.data.provider ?? "privy"
556
+ };
557
+ }
558
+ async executeRpc(envelope) {
559
+ const { correlationId, ...body } = envelope;
560
+ const headers = {
561
+ "Content-Type": "application/json"
562
+ };
563
+ if (correlationId) {
564
+ headers["X-Correlation-Id"] = correlationId;
565
+ }
566
+ let response;
567
+ try {
568
+ response = await fetch(`${this.baseUrl}/api/v1/user/wallets/rpc`, {
569
+ method: "POST",
570
+ headers,
571
+ body: JSON.stringify(body),
572
+ redirect: "manual",
573
+ signal: AbortSignal.timeout(60000)
574
+ });
575
+ } catch (err) {
576
+ throw new CloudUnavailableError(`Cloud RPC network error: ${err.message}`, 0);
577
+ }
578
+ if (isRedirectResponse2(response)) {
579
+ throw new CloudBridgeError("Cloud RPC request was redirected; redirects are not allowed", response.status);
580
+ }
581
+ const text = await response.text().catch(() => "");
582
+ if (response.ok) {
583
+ try {
584
+ const parsed = JSON.parse(text);
585
+ if (!parsed.success || parsed.data === undefined) {
586
+ throw new CloudBridgeError(parsed.error ?? "Cloud RPC returned no data", response.status, text);
587
+ }
588
+ return parsed.data;
589
+ } catch (err) {
590
+ if (err instanceof CloudBridgeError)
591
+ throw err;
592
+ throw new CloudBridgeError(`Cloud RPC returned malformed JSON: ${err.message}`, response.status, text);
593
+ }
594
+ }
595
+ let errMessage = `HTTP ${response.status}`;
596
+ try {
597
+ const parsed = JSON.parse(text);
598
+ if (parsed.error)
599
+ errMessage = parsed.error;
600
+ } catch {
601
+ if (text)
602
+ errMessage = text.slice(0, 200);
603
+ }
604
+ if (response.status === 401) {
605
+ throw new SignatureInvalidError(errMessage, text);
606
+ }
607
+ if (response.status === 409) {
608
+ throw new NonceReplayError(errMessage, text);
609
+ }
610
+ if (response.status === 410) {
611
+ throw new SessionExpiredError(errMessage, text);
612
+ }
613
+ if (response.status >= 500) {
614
+ throw new CloudUnavailableError(errMessage, response.status, text);
615
+ }
616
+ throw new CloudBridgeError(errMessage, response.status, text);
617
+ }
618
+ async request(method, path, body) {
619
+ const headers = { "X-Api-Key": this.apiKey };
620
+ if (body !== undefined)
621
+ headers["Content-Type"] = "application/json";
622
+ const response = await fetch(`${this.baseUrl}${path}`, {
623
+ method,
624
+ headers,
625
+ body: body !== undefined ? JSON.stringify(body) : undefined,
626
+ redirect: "manual",
627
+ signal: AbortSignal.timeout(30000)
628
+ });
629
+ if (isRedirectResponse2(response)) {
630
+ return {
631
+ success: false,
632
+ error: "Cloud API request was redirected; redirects are not allowed"
633
+ };
634
+ }
635
+ if (!response.ok) {
636
+ const text = await response.text().catch(() => "");
637
+ return {
638
+ success: false,
639
+ error: formatApiErrorBody(text) ?? `HTTP ${response.status}`
640
+ };
641
+ }
642
+ return await response.json();
643
+ }
644
+ }
645
+
646
+ // src/cloud/backup.ts
647
+ import { logger as logger2 } from "@elizaos/core";
648
+
649
+ class BackupScheduler {
650
+ client;
651
+ agentId;
652
+ intervalMs;
653
+ timer = null;
654
+ running = false;
655
+ constructor(client, agentId, intervalMs = 60000) {
656
+ this.client = client;
657
+ this.agentId = agentId;
658
+ this.intervalMs = intervalMs;
659
+ }
660
+ start() {
661
+ if (this.timer)
662
+ return;
663
+ this.running = true;
664
+ this.timer = setInterval(() => {
665
+ this.client.snapshot(this.agentId).catch((err) => {
666
+ logger2.warn(`[cloud-backup] Auto-backup failed: ${String(err)}`);
667
+ });
668
+ }, this.intervalMs);
669
+ }
670
+ stop() {
671
+ if (this.timer) {
672
+ clearInterval(this.timer);
673
+ this.timer = null;
674
+ }
675
+ this.running = false;
676
+ }
677
+ isRunning() {
678
+ return this.running;
679
+ }
680
+ async finalSnapshot() {
681
+ await this.client.snapshot(this.agentId).catch((err) => {
682
+ logger2.warn(`[cloud-backup] Final snapshot failed: ${String(err)}`);
683
+ });
684
+ }
685
+ }
686
+
687
+ // src/cloud/cloud-proxy.ts
688
+ class CloudRuntimeProxy {
689
+ client;
690
+ agentId;
691
+ _agentName;
692
+ constructor(client, agentId, _agentName) {
693
+ this.client = client;
694
+ this.agentId = agentId;
695
+ this._agentName = _agentName;
696
+ }
697
+ get agentName() {
698
+ return this._agentName;
699
+ }
700
+ async handleChatMessage(text, roomId = "web-chat", channelType = "DM") {
701
+ return this.client.sendMessage(this.agentId, text, roomId, channelType);
702
+ }
703
+ async* handleChatMessageStream(text, roomId = "web-chat", channelType = "DM") {
704
+ for await (const event of this.client.sendMessageStream(this.agentId, text, roomId, channelType)) {
705
+ if (event.type === "chunk" && typeof event.data.text === "string") {
706
+ yield event.data.text;
707
+ }
708
+ }
709
+ }
710
+ async getStatus() {
711
+ const agent = await this.client.getAgent(this.agentId);
712
+ return { state: agent.status, agentName: agent.agentName };
713
+ }
714
+ async isAlive() {
715
+ return this.client.heartbeat(this.agentId).catch(() => false);
716
+ }
717
+ }
718
+
719
+ // src/cloud/reconnect.ts
720
+ import { logger as logger3 } from "@elizaos/core";
721
+
722
+ class ConnectionMonitor {
723
+ client;
724
+ agentId;
725
+ callbacks;
726
+ heartbeatIntervalMs;
727
+ maxFailures;
728
+ timer = null;
729
+ consecutiveFailures = 0;
730
+ reconnecting = false;
731
+ constructor(client, agentId, callbacks, heartbeatIntervalMs = 30000, maxFailures = 3) {
732
+ this.client = client;
733
+ this.agentId = agentId;
734
+ this.callbacks = callbacks;
735
+ this.heartbeatIntervalMs = heartbeatIntervalMs;
736
+ this.maxFailures = maxFailures;
737
+ }
738
+ start() {
739
+ if (this.timer)
740
+ return;
741
+ logger3.info(`[cloud-monitor] Starting connection monitor (interval: ${this.heartbeatIntervalMs}ms, maxFailures: ${this.maxFailures})`);
742
+ this.consecutiveFailures = 0;
743
+ this.timer = setInterval(() => {
744
+ this.tick();
745
+ }, this.heartbeatIntervalMs);
746
+ }
747
+ stop() {
748
+ if (this.timer) {
749
+ clearInterval(this.timer);
750
+ this.timer = null;
751
+ }
752
+ this.consecutiveFailures = 0;
753
+ this.reconnecting = false;
754
+ logger3.info("[cloud-monitor] Connection monitor stopped");
755
+ }
756
+ isMonitoring() {
757
+ return this.timer !== null;
758
+ }
759
+ async tick() {
760
+ if (this.reconnecting)
761
+ return;
762
+ const alive = await this.client.heartbeat(this.agentId).catch(() => false);
763
+ if (alive) {
764
+ if (this.consecutiveFailures > 0) {
765
+ this.consecutiveFailures = 0;
766
+ this.callbacks.onStatusChange?.("connected");
767
+ }
768
+ return;
769
+ }
770
+ this.consecutiveFailures++;
771
+ logger3.warn(`[cloud-monitor] Heartbeat failed (${this.consecutiveFailures}/${this.maxFailures})`);
772
+ if (this.consecutiveFailures >= this.maxFailures) {
773
+ this.callbacks.onDisconnect();
774
+ await this.attemptReconnect();
775
+ }
776
+ }
777
+ async attemptReconnect() {
778
+ this.reconnecting = true;
779
+ this.callbacks.onStatusChange?.("reconnecting");
780
+ let delay = 3000;
781
+ for (let attempt = 1;attempt <= 10; attempt++) {
782
+ logger3.info(`[cloud-monitor] Reconnect attempt ${attempt}/10...`);
783
+ const ok = await this.client.provision(this.agentId).then(() => true).catch(() => false);
784
+ if (ok) {
785
+ logger3.info("[cloud-monitor] Reconnection successful");
786
+ this.consecutiveFailures = 0;
787
+ this.reconnecting = false;
788
+ this.callbacks.onStatusChange?.("connected");
789
+ this.callbacks.onReconnect();
790
+ return;
791
+ }
792
+ await new Promise((r) => setTimeout(r, delay));
793
+ delay = Math.min(delay * 2, 60000);
794
+ }
795
+ logger3.error("[cloud-monitor] Failed to reconnect after 10 attempts");
796
+ this.reconnecting = false;
797
+ this.callbacks.onStatusChange?.("disconnected");
798
+ }
799
+ }
800
+
801
+ // src/cloud/cloud-manager.ts
802
+ import { logger as logger4 } from "@elizaos/core";
803
+ init_base_url();
804
+ init_validate_url();
805
+
806
+ class CloudManager {
807
+ cloudConfig;
808
+ callbacks;
809
+ client = null;
810
+ proxy = null;
811
+ backupScheduler = null;
812
+ connectionMonitor = null;
813
+ status = "disconnected";
814
+ activeAgentId = null;
815
+ constructor(cloudConfig, callbacks = {}) {
816
+ this.cloudConfig = cloudConfig;
817
+ this.callbacks = callbacks;
818
+ }
819
+ async init() {
820
+ const rawUrl = normalizeCloudSiteUrl(this.cloudConfig.baseUrl);
821
+ const apiKey = this.cloudConfig.apiKey;
822
+ if (!apiKey)
823
+ throw new Error("Cloud API key is not configured. Run cloud login first.");
824
+ const urlError = await validateCloudBaseUrl(rawUrl);
825
+ if (urlError) {
826
+ throw new Error(urlError);
827
+ }
828
+ this.client = new ElizaCloudClient(rawUrl, apiKey);
829
+ logger4.info(`[cloud-manager] Client initialised (baseUrl=${rawUrl})`);
830
+ }
831
+ async connect(agentId) {
832
+ if (!this.client)
833
+ await this.init();
834
+ if (!this.client)
835
+ throw new Error("Cloud client failed to initialise");
836
+ this.setStatus("connecting");
837
+ this.activeAgentId = agentId;
838
+ try {
839
+ await this.client.provision(agentId);
840
+ const agent = await this.client.getAgent(agentId);
841
+ this.proxy = new CloudRuntimeProxy(this.client, agentId, agent.agentName);
842
+ this.backupScheduler = new BackupScheduler(this.client, agentId, this.cloudConfig.backup?.autoBackupIntervalMs ?? 60000);
843
+ this.backupScheduler.start();
844
+ this.connectionMonitor = new ConnectionMonitor(this.client, agentId, {
845
+ onDisconnect: () => this.setStatus("reconnecting"),
846
+ onReconnect: () => this.setStatus("connected"),
847
+ onStatusChange: (s) => {
848
+ if (s === "connected")
849
+ this.setStatus("connected");
850
+ else if (s === "reconnecting")
851
+ this.setStatus("reconnecting");
852
+ else
853
+ this.setStatus("error");
854
+ }
855
+ }, this.cloudConfig.bridge?.heartbeatIntervalMs ?? 30000);
856
+ this.connectionMonitor.start();
857
+ this.setStatus("connected");
858
+ logger4.info(`[cloud-manager] Connected to cloud agent (agentId=${agentId}, agentName=${agent.agentName})`);
859
+ return this.proxy;
860
+ } catch (err) {
861
+ this.setStatus("error");
862
+ if (this.backupScheduler) {
863
+ this.backupScheduler.stop();
864
+ this.backupScheduler = null;
865
+ }
866
+ if (this.connectionMonitor) {
867
+ this.connectionMonitor.stop();
868
+ this.connectionMonitor = null;
869
+ }
870
+ this.proxy = null;
871
+ this.activeAgentId = null;
872
+ this.setStatus("disconnected");
873
+ throw err;
874
+ }
875
+ }
876
+ async disconnect() {
877
+ if (this.backupScheduler) {
878
+ await this.backupScheduler.finalSnapshot();
879
+ this.backupScheduler.stop();
880
+ this.backupScheduler = null;
881
+ }
882
+ if (this.connectionMonitor) {
883
+ this.connectionMonitor.stop();
884
+ this.connectionMonitor = null;
885
+ }
886
+ this.proxy = null;
887
+ this.activeAgentId = null;
888
+ this.setStatus("disconnected");
889
+ }
890
+ async replaceApiKey(apiKey) {
891
+ await this.disconnect();
892
+ this.cloudConfig = {
893
+ ...this.cloudConfig,
894
+ apiKey
895
+ };
896
+ this.client = null;
897
+ await this.init();
898
+ }
899
+ getProxy() {
900
+ return this.proxy;
901
+ }
902
+ getClient() {
903
+ return this.client;
904
+ }
905
+ getActiveAgentId() {
906
+ return this.activeAgentId;
907
+ }
908
+ getStatus() {
909
+ return this.status;
910
+ }
911
+ isEnabled() {
912
+ return Boolean(this.cloudConfig.enabled && this.cloudConfig.apiKey);
913
+ }
914
+ setStatus(status) {
915
+ if (this.status === status)
916
+ return;
917
+ this.status = status;
918
+ this.callbacks.onStatusChange?.(status);
919
+ }
920
+ }
921
+
922
+ // src/cloud/x402-payment-handler.ts
923
+ import { logger as logger5 } from "@elizaos/core";
25
924
  function readString(value) {
26
925
  if (typeof value !== "string")
27
926
  return null;
@@ -104,7 +1003,7 @@ async function requestPayment(runtime, requirements) {
104
1003
  throw new Error("[x402] requestPayment called with no requirements — adapter bug");
105
1004
  }
106
1005
  const preferred = requirements[0];
107
- logger.warn({
1006
+ logger5.warn({
108
1007
  boundary: "elizacloud",
109
1008
  integration: "x402",
110
1009
  asset: preferred.asset,
@@ -116,7 +1015,7 @@ async function requestPayment(runtime, requirements) {
116
1015
  }
117
1016
 
118
1017
  // src/cloud/duffel-client.ts
119
- import { logger as logger2 } from "@elizaos/core";
1018
+ import { logger as logger6 } from "@elizaos/core";
120
1019
  class DuffelConfigError extends Error {
121
1020
  code = "DUFFEL_NOT_CONFIGURED";
122
1021
  constructor(message) {
@@ -297,7 +1196,7 @@ async function duffelFetch(args) {
297
1196
  });
298
1197
  } catch (error) {
299
1198
  const msg = error instanceof Error ? error.message : String(error);
300
- logger2.error({
1199
+ logger6.error({
301
1200
  boundary: "elizacloud",
302
1201
  integration: "duffel",
303
1202
  operation,
@@ -309,7 +1208,7 @@ async function duffelFetch(args) {
309
1208
  }
310
1209
  if (response.status === 402 && isCloud) {
311
1210
  const requirements = await parseX402Response(response);
312
- logger2.warn({
1211
+ logger6.warn({
313
1212
  boundary: "elizacloud",
314
1213
  integration: "duffel",
315
1214
  operation,
@@ -326,7 +1225,7 @@ async function duffelFetch(args) {
326
1225
  if (!response.ok) {
327
1226
  const errorBody = await response.text().catch(() => "");
328
1227
  const errorMsg = errorBody || `HTTP ${response.status}`;
329
- logger2.warn({
1228
+ logger6.warn({
330
1229
  boundary: "elizacloud",
331
1230
  integration: "duffel",
332
1231
  operation,
@@ -367,7 +1266,7 @@ async function searchFlights(request, config) {
367
1266
  cabin_class: "economy"
368
1267
  }
369
1268
  };
370
- logger2.info({
1269
+ logger6.info({
371
1270
  boundary: "elizacloud",
372
1271
  integration: "duffel",
373
1272
  origin: request.origin,
@@ -382,7 +1281,7 @@ async function searchFlights(request, config) {
382
1281
  operation: "offer_request"
383
1282
  });
384
1283
  const offers = responseData.data.offers.map(mapOffer);
385
- logger2.info({
1284
+ logger6.info({
386
1285
  boundary: "elizacloud",
387
1286
  integration: "duffel",
388
1287
  offerRequestId: responseData.data.id,
@@ -867,19 +1766,23 @@ class PaypalManagedClient {
867
1766
  return readPaypalJson(response);
868
1767
  }
869
1768
  }
1769
+
1770
+ // src/cloud/index.ts
1771
+ init_base_url();
1772
+ init_validate_url();
870
1773
  export {
871
1774
  validateCloudBaseUrl,
872
1775
  searchFlights,
873
1776
  resolveLifeOpsScheduleSyncSiteUrl,
874
1777
  resolveLifeOpsScheduleSyncConfig,
875
1778
  resolveEnvElizaCloudManagedClientConfig,
876
- resolveCloudApiBaseUrl2 as resolveCloudApiBaseUrl,
1779
+ resolveCloudApiBaseUrl,
877
1780
  requestPayment,
878
1781
  readDuffelConfigFromEnv,
879
1782
  parseX402Response,
880
1783
  normalizeLifeOpsScheduleSyncSecret,
881
1784
  normalizeElizaCloudApiKey,
882
- normalizeCloudSiteUrl2 as normalizeCloudSiteUrl,
1785
+ normalizeCloudSiteUrl,
883
1786
  normalizeCloudApiKey,
884
1787
  isCloudAuthApiKeyService,
885
1788
  getOrder,
@@ -905,4 +1808,4 @@ export {
905
1808
  BackupScheduler
906
1809
  };
907
1810
 
908
- //# debugId=EB90B659DB4BC34E64756E2164756E21
1811
+ //# debugId=399B25FA0312702564756E2164756E21