@hol-org/rb-client 0.1.171 → 0.1.173

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 (5) hide show
  1. package/dist/index.cjs +2065 -1815
  2. package/dist/index.d.cts +17827 -114
  3. package/dist/index.d.ts +17827 -114
  4. package/dist/index.js +2050 -1816
  5. package/package.json +3 -2
package/dist/index.cjs CHANGED
@@ -37,21 +37,30 @@ __export(src_exports, {
37
37
  buildPaymentApproveMessage: () => buildPaymentApproveMessage,
38
38
  buildPaymentDeclineMessage: () => buildPaymentDeclineMessage,
39
39
  canonicalizeLedgerNetwork: () => canonicalizeLedgerNetwork,
40
+ closeUaidConnection: () => closeUaidConnection,
40
41
  createPrivateKeySigner: () => createPrivateKeySigner,
41
42
  createPrivateKeySignerAsync: () => createPrivateKeySignerAsync,
43
+ dashboardStats: () => dashboardStats,
44
+ getRegistrationProgress: () => getRegistrationProgress,
45
+ getRegistrationQuote: () => getRegistrationQuote,
46
+ getUaidConnectionStatus: () => getUaidConnectionStatus,
42
47
  isHolChatOp: () => isHolChatOp,
43
48
  isPartialRegisterAgentResponse: () => isPartialRegisterAgentResponse,
44
49
  isPendingRegisterAgentResponse: () => isPendingRegisterAgentResponse,
45
50
  isSuccessRegisterAgentResponse: () => isSuccessRegisterAgentResponse,
46
- parseHolChatOps: () => parseHolChatOps
51
+ parseHolChatOps: () => parseHolChatOps,
52
+ registerAgent: () => registerAgent,
53
+ resolveUaid: () => resolveUaid,
54
+ updateAgent: () => updateAgent,
55
+ validateUaid: () => validateUaid,
56
+ waitForRegistrationCompletion: () => waitForRegistrationCompletion
47
57
  });
48
58
  module.exports = __toCommonJS(src_exports);
49
59
 
50
- // ../../src/services/registry-broker/client/encryption.ts
51
- var path = __toESM(require("path"), 1);
52
- var import_buffer = require("buffer");
53
- var import_crypto = require("crypto");
54
- var import_secp256k1 = require("@noble/curves/secp256k1.js");
60
+ // ../../src/services/registry-broker/client/base-client.ts
61
+ var import_buffer4 = require("buffer");
62
+ var import_secp256k12 = require("@noble/curves/secp256k1.js");
63
+ var import_zod3 = require("zod");
55
64
 
56
65
  // ../../src/services/registry-broker/schemas.ts
57
66
  var import_zod2 = require("zod");
@@ -288,6 +297,13 @@ var metadataFacetSchema = import_zod2.z.record(
288
297
  jsonValueSchema
289
298
  ])
290
299
  ).optional();
300
+ var searchHitMetadataSchema = import_zod2.z.object({
301
+ delegationRoles: jsonValueSchema.optional(),
302
+ delegationTaskTags: jsonValueSchema.optional(),
303
+ delegationProtocols: jsonValueSchema.optional(),
304
+ delegationSummary: jsonValueSchema.optional(),
305
+ delegationSignals: jsonValueSchema.optional()
306
+ }).passthrough();
291
307
  var searchHitSchema = import_zod2.z.object({
292
308
  id: import_zod2.z.string(),
293
309
  uaid: import_zod2.z.string(),
@@ -296,7 +312,7 @@ var searchHitSchema = import_zod2.z.object({
296
312
  description: import_zod2.z.string().optional(),
297
313
  capabilities: import_zod2.z.array(capabilityValueSchema),
298
314
  endpoints: import_zod2.z.union([import_zod2.z.record(jsonValueSchema), import_zod2.z.array(import_zod2.z.string())]).optional(),
299
- metadata: import_zod2.z.record(jsonValueSchema).optional(),
315
+ metadata: searchHitMetadataSchema.optional(),
300
316
  metadataFacet: metadataFacetSchema,
301
317
  profile: agentProfileSchema.optional(),
302
318
  protocols: import_zod2.z.array(import_zod2.z.string()).optional(),
@@ -340,6 +356,62 @@ var popularResponseSchema = import_zod2.z.object({
340
356
  var resolveResponseSchema = import_zod2.z.object({
341
357
  agent: searchHitSchema
342
358
  });
359
+ var delegationPlanCandidateSchema = import_zod2.z.object({
360
+ uaid: import_zod2.z.string(),
361
+ label: import_zod2.z.string(),
362
+ registry: import_zod2.z.string().optional(),
363
+ agent: searchHitSchema,
364
+ score: import_zod2.z.number(),
365
+ matchedQueries: import_zod2.z.array(import_zod2.z.string()).optional(),
366
+ matchedRoles: import_zod2.z.array(import_zod2.z.string()).optional(),
367
+ matchedProtocols: import_zod2.z.array(import_zod2.z.string()).optional(),
368
+ matchedSurfaces: import_zod2.z.array(import_zod2.z.string()).optional(),
369
+ matchedLanguages: import_zod2.z.array(import_zod2.z.string()).optional(),
370
+ matchedArtifacts: import_zod2.z.array(import_zod2.z.string()).optional(),
371
+ matchedTaskTags: import_zod2.z.array(import_zod2.z.string()).optional(),
372
+ reasons: import_zod2.z.array(import_zod2.z.string()).optional(),
373
+ suggestedMessage: import_zod2.z.string().optional(),
374
+ trustScore: import_zod2.z.number().optional(),
375
+ verified: import_zod2.z.boolean().optional(),
376
+ communicationSupported: import_zod2.z.boolean().optional(),
377
+ availability: import_zod2.z.boolean().optional(),
378
+ explanation: import_zod2.z.string().optional()
379
+ }).passthrough();
380
+ var delegationOpportunitySchema = import_zod2.z.object({
381
+ id: import_zod2.z.string(),
382
+ title: import_zod2.z.string(),
383
+ reason: import_zod2.z.string(),
384
+ role: import_zod2.z.string(),
385
+ type: import_zod2.z.enum(["ai-agents", "mcp-servers"]),
386
+ suggestedMode: import_zod2.z.enum(["best-match", "fallback", "parallel"]),
387
+ searchQueries: import_zod2.z.array(import_zod2.z.string()),
388
+ protocols: import_zod2.z.array(import_zod2.z.string()).optional(),
389
+ surfaces: import_zod2.z.array(import_zod2.z.string()).optional(),
390
+ languages: import_zod2.z.array(import_zod2.z.string()).optional(),
391
+ artifacts: import_zod2.z.array(import_zod2.z.string()).optional(),
392
+ candidates: import_zod2.z.array(delegationPlanCandidateSchema)
393
+ }).passthrough();
394
+ var delegationRecommendationSchema = import_zod2.z.object({
395
+ action: import_zod2.z.enum(["delegate-now", "review-shortlist", "handle-locally"]),
396
+ confidence: import_zod2.z.number(),
397
+ reason: import_zod2.z.string(),
398
+ opportunityId: import_zod2.z.string().optional(),
399
+ candidate: delegationPlanCandidateSchema.optional()
400
+ }).passthrough();
401
+ var delegationPlanResponseSchema = import_zod2.z.object({
402
+ task: import_zod2.z.string(),
403
+ context: import_zod2.z.string().optional(),
404
+ summary: import_zod2.z.string().optional(),
405
+ intents: import_zod2.z.array(import_zod2.z.string()),
406
+ protocols: import_zod2.z.array(import_zod2.z.string()),
407
+ surfaces: import_zod2.z.array(import_zod2.z.string()),
408
+ languages: import_zod2.z.array(import_zod2.z.string()).optional(),
409
+ artifacts: import_zod2.z.array(import_zod2.z.string()).optional(),
410
+ shouldDelegate: import_zod2.z.boolean(),
411
+ localFirstReason: import_zod2.z.string().optional(),
412
+ recommendation: delegationRecommendationSchema.optional(),
413
+ opportunities: import_zod2.z.array(delegationOpportunitySchema)
414
+ }).passthrough();
343
415
  var agentFeedbackSummarySchema = import_zod2.z.object({
344
416
  averageScore: import_zod2.z.number(),
345
417
  totalFeedbacks: import_zod2.z.number(),
@@ -1568,285 +1640,171 @@ var skillVerificationDomainProofVerifyResponseSchema = import_zod2.z.object({
1568
1640
  signal: skillVerificationDomainProofSignalSchema
1569
1641
  }).passthrough();
1570
1642
 
1571
- // ../../src/utils/is-browser.ts
1572
- var isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined";
1573
-
1574
- // ../../src/utils/dynamic-import.ts
1575
- var nodeRequire;
1576
- function isModuleNotFound(specifier, error) {
1577
- if (!error || typeof error !== "object") {
1643
+ // ../../src/services/registry-broker/client/chat-history.ts
1644
+ var import_buffer = require("buffer");
1645
+ function identitiesMatch(a, b) {
1646
+ if (!a && !b) {
1647
+ return true;
1648
+ }
1649
+ if (!a || !b) {
1578
1650
  return false;
1579
1651
  }
1580
- const code = Reflect.get(error, "code");
1581
- const message = Reflect.get(error, "message");
1582
- const messageText = typeof message === "string" ? message : "";
1583
- if (typeof code === "string" && code.includes("MODULE_NOT_FOUND")) {
1584
- return messageText.includes(specifier);
1652
+ if (a.uaid && b.uaid && a.uaid.toLowerCase() === b.uaid.toLowerCase()) {
1653
+ return true;
1585
1654
  }
1586
- if (messageText) {
1587
- const lowered = messageText.toLowerCase();
1588
- if (lowered.includes("cannot find module") || lowered.includes("module not found") || lowered.includes("cannot find package")) {
1589
- return lowered.includes(specifier.toLowerCase());
1590
- }
1655
+ if (a.ledgerAccountId && b.ledgerAccountId && a.ledgerAccountId.toLowerCase() === b.ledgerAccountId.toLowerCase()) {
1656
+ return true;
1657
+ }
1658
+ if (a.userId && b.userId && a.userId === b.userId) {
1659
+ return true;
1660
+ }
1661
+ if (a.email && b.email && a.email.toLowerCase() === b.email.toLowerCase()) {
1662
+ return true;
1591
1663
  }
1592
1664
  return false;
1593
1665
  }
1594
- async function resolveNodeRequire() {
1595
- if (nodeRequire !== void 0) {
1596
- return nodeRequire;
1666
+ async function fetchHistorySnapshot(conversationContexts, client, sessionId, options) {
1667
+ if (!sessionId || sessionId.trim().length === 0) {
1668
+ throw new Error("sessionId is required to fetch chat history");
1597
1669
  }
1598
- if (isBrowser) {
1599
- nodeRequire = null;
1600
- return nodeRequire;
1670
+ const raw = await client.requestJson(
1671
+ `/chat/session/${encodeURIComponent(sessionId)}/history`,
1672
+ {
1673
+ method: "GET"
1674
+ }
1675
+ );
1676
+ const snapshot = client.parseWithSchema(
1677
+ raw,
1678
+ chatHistorySnapshotResponseSchema,
1679
+ "chat history snapshot response"
1680
+ );
1681
+ return attachDecryptedHistory(
1682
+ conversationContexts,
1683
+ client,
1684
+ sessionId,
1685
+ snapshot,
1686
+ options
1687
+ );
1688
+ }
1689
+ function attachDecryptedHistory(conversationContexts, client, sessionId, snapshot, options) {
1690
+ const shouldDecrypt = options?.decrypt !== void 0 ? options.decrypt : client.encryptionOptions?.autoDecryptHistory === true;
1691
+ if (!shouldDecrypt) {
1692
+ return snapshot;
1601
1693
  }
1602
- try {
1603
- const globalObject = typeof global !== "undefined" ? global : globalThis;
1604
- const req = globalObject.process?.mainModule?.require ?? globalObject.require;
1605
- nodeRequire = typeof req === "function" && typeof req.resolve === "function" ? req : null;
1606
- } catch {
1607
- nodeRequire = null;
1694
+ const requiresContext = snapshot.history.some(
1695
+ (entry) => Boolean(entry.cipherEnvelope)
1696
+ );
1697
+ if (!requiresContext) {
1698
+ return {
1699
+ ...snapshot,
1700
+ decryptedHistory: snapshot.history.map((entry) => ({
1701
+ entry,
1702
+ plaintext: entry.content
1703
+ }))
1704
+ };
1608
1705
  }
1609
- return nodeRequire;
1706
+ const context = resolveDecryptionContext(
1707
+ conversationContexts,
1708
+ client,
1709
+ sessionId,
1710
+ options
1711
+ );
1712
+ if (!context) {
1713
+ throw new Error(
1714
+ "Unable to decrypt chat history: encryption context unavailable"
1715
+ );
1716
+ }
1717
+ const decryptedHistory = snapshot.history.map((entry) => ({
1718
+ entry,
1719
+ plaintext: decryptHistoryEntryFromContext(client, entry, context)
1720
+ }));
1721
+ return { ...snapshot, decryptedHistory };
1610
1722
  }
1611
- async function dynamicImport(specifier) {
1612
- try {
1613
- return await import(specifier);
1614
- } catch (error) {
1615
- if (isModuleNotFound(specifier, error)) {
1616
- return null;
1617
- }
1618
- throw error;
1723
+ function registerConversationContextForEncryption(conversationContexts, context) {
1724
+ const normalized = {
1725
+ sessionId: context.sessionId,
1726
+ sharedSecret: import_buffer.Buffer.from(context.sharedSecret),
1727
+ identity: context.identity ? { ...context.identity } : void 0
1728
+ };
1729
+ const entries = conversationContexts.get(context.sessionId) ?? [];
1730
+ const existingIndex = entries.findIndex(
1731
+ (existing) => identitiesMatch(existing.identity, normalized.identity)
1732
+ );
1733
+ if (existingIndex >= 0) {
1734
+ entries[existingIndex] = normalized;
1735
+ } else {
1736
+ entries.push(normalized);
1619
1737
  }
1738
+ conversationContexts.set(context.sessionId, entries);
1620
1739
  }
1621
- async function optionalImport(specifier, options = {}) {
1622
- if (isBrowser) {
1623
- return dynamicImport(specifier);
1740
+ function resolveDecryptionContext(conversationContexts, client, sessionId, options) {
1741
+ if (options?.sharedSecret) {
1742
+ return {
1743
+ sessionId,
1744
+ sharedSecret: client.normalizeSharedSecret(options.sharedSecret),
1745
+ identity: options.identity
1746
+ };
1624
1747
  }
1625
- if (!options.preferImport) {
1626
- const requireFn = await resolveNodeRequire();
1627
- if (requireFn) {
1628
- try {
1629
- return requireFn(specifier);
1630
- } catch (error) {
1631
- if (!isModuleNotFound(specifier, error)) {
1632
- throw error;
1633
- }
1634
- }
1748
+ const contexts = conversationContexts.get(sessionId);
1749
+ if (!contexts || contexts.length === 0) {
1750
+ return null;
1751
+ }
1752
+ if (options?.identity) {
1753
+ const match = contexts.find(
1754
+ (context) => identitiesMatch(context.identity, options.identity)
1755
+ );
1756
+ if (match) {
1757
+ return match;
1635
1758
  }
1636
1759
  }
1637
- return dynamicImport(specifier);
1760
+ return contexts[0];
1638
1761
  }
1639
- function optionalImportSync(specifier) {
1640
- if (isBrowser) {
1641
- return null;
1762
+ function decryptHistoryEntryFromContext(client, entry, context) {
1763
+ const envelope = entry.cipherEnvelope;
1764
+ if (!envelope) {
1765
+ return entry.content;
1642
1766
  }
1767
+ const secret = import_buffer.Buffer.from(context.sharedSecret);
1643
1768
  try {
1644
- const globalObject = typeof global !== "undefined" ? global : globalThis;
1645
- const req = globalObject.process?.mainModule?.require ?? globalObject.require;
1646
- if (typeof req === "function" && typeof req.resolve === "function") {
1647
- return req(specifier);
1648
- }
1649
- } catch (error) {
1650
- if (!isModuleNotFound(specifier, error)) {
1651
- throw error;
1652
- }
1769
+ return client.encryption.decryptCipherEnvelope({
1770
+ envelope,
1771
+ sharedSecret: secret
1772
+ });
1773
+ } catch (_error) {
1774
+ return null;
1653
1775
  }
1654
- return null;
1655
1776
  }
1656
1777
 
1657
- // ../../src/services/registry-broker/client/encryption.ts
1658
- var getFs = async () => {
1659
- const fsModule = await optionalImport("node:fs");
1660
- if (fsModule && typeof fsModule.existsSync === "function" && typeof fsModule.readFileSync === "function" && typeof fsModule.writeFileSync === "function" && typeof fsModule.appendFileSync === "function") {
1661
- return fsModule;
1778
+ // ../../src/services/registry-broker/client/utils.ts
1779
+ var DEFAULT_USER_AGENT = "@hol-org/rb-client";
1780
+ var DEFAULT_PROGRESS_INTERVAL_MS = 1500;
1781
+ var DEFAULT_PROGRESS_TIMEOUT_MS = 5 * 60 * 1e3;
1782
+ var DEFAULT_BASE_URL = "https://hol.org/registry/api/v1";
1783
+ var JSON_CONTENT_TYPE = /application\/json/i;
1784
+ var DEFAULT_HISTORY_TOP_UP_HBAR = 0.25;
1785
+ var MINIMUM_REGISTRATION_AUTO_TOP_UP_CREDITS = 1;
1786
+ var stripTrailingSlashes = (value) => {
1787
+ let end = value.length;
1788
+ while (end > 0 && value.charCodeAt(end - 1) === 47) {
1789
+ end -= 1;
1662
1790
  }
1663
- return null;
1791
+ return end === value.length ? value : value.slice(0, end);
1664
1792
  };
1665
- async function registerEncryptionKey(client, payload) {
1666
- const raw = await client.requestJson("/encryption/keys", {
1667
- method: "POST",
1668
- headers: { "content-type": "application/json" },
1669
- body: payload
1670
- });
1671
- return client.parseWithSchema(
1672
- raw,
1673
- registerEncryptionKeyResponseSchema,
1674
- "register encryption key response"
1675
- );
1676
- }
1677
- function normalizeAutoRegisterIdentity(config) {
1678
- const identity = {};
1679
- if (config.uaid) {
1680
- identity.uaid = config.uaid;
1793
+ var createAbortError = () => typeof DOMException === "function" ? new DOMException("Aborted", "AbortError") : new Error("The operation was aborted");
1794
+ var normaliseHeaderName = (name) => name.trim().toLowerCase();
1795
+ var isBrowserRuntime = () => typeof window !== "undefined" && typeof window.fetch === "function";
1796
+ var toJsonValue = (value) => {
1797
+ if (value === null) {
1798
+ return null;
1681
1799
  }
1682
- if (config.ledgerAccountId) {
1683
- identity.ledgerAccountId = config.ledgerAccountId;
1684
- if (config.ledgerNetwork) {
1685
- identity.ledgerNetwork = config.ledgerNetwork;
1686
- }
1800
+ if (value instanceof Date) {
1801
+ return value.toISOString();
1687
1802
  }
1688
- if (config.email) {
1689
- identity.email = config.email;
1803
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
1804
+ return value;
1690
1805
  }
1691
- if (identity.uaid || identity.ledgerAccountId || identity.email) {
1692
- return identity;
1693
- }
1694
- return null;
1695
- }
1696
- function derivePublicKeyFromPrivateKey(client, privateKey) {
1697
- const normalized = client.hexToBuffer(privateKey);
1698
- const publicKey = import_secp256k1.secp256k1.getPublicKey(normalized, true);
1699
- return import_buffer.Buffer.from(publicKey).toString("hex");
1700
- }
1701
- async function resolveAutoRegisterKeyMaterial(client, config) {
1702
- if (config.publicKey?.trim()) {
1703
- return { publicKey: config.publicKey.trim() };
1704
- }
1705
- let privateKey = config.privateKey?.trim();
1706
- const envVar = config.envVar ?? "RB_ENCRYPTION_PRIVATE_KEY";
1707
- if (!privateKey && envVar && process?.env?.[envVar]?.trim()) {
1708
- privateKey = process.env[envVar]?.trim();
1709
- }
1710
- if (!privateKey && config.generateIfMissing) {
1711
- const pair = await client.generateEncryptionKeyPair({
1712
- keyType: config.keyType ?? "secp256k1",
1713
- envVar,
1714
- envPath: config.envPath,
1715
- overwrite: config.overwriteEnv
1716
- });
1717
- return { publicKey: pair.publicKey, privateKey: pair.privateKey };
1718
- }
1719
- if (privateKey) {
1720
- const publicKey = derivePublicKeyFromPrivateKey(client, privateKey);
1721
- return { publicKey, privateKey };
1722
- }
1723
- return null;
1724
- }
1725
- async function autoRegisterEncryptionKey(client, config) {
1726
- const identity = normalizeAutoRegisterIdentity(config);
1727
- if (!identity) {
1728
- throw new Error(
1729
- "Auto-registration requires uaid, ledgerAccountId, or email"
1730
- );
1731
- }
1732
- const material = await resolveAutoRegisterKeyMaterial(client, config);
1733
- if (!material) {
1734
- throw new Error(
1735
- "Unable to resolve encryption public key for auto-registration"
1736
- );
1737
- }
1738
- await registerEncryptionKey(client, {
1739
- keyType: config.keyType ?? "secp256k1",
1740
- publicKey: material.publicKey,
1741
- ...identity
1742
- });
1743
- return material;
1744
- }
1745
- async function ensureAgentEncryptionKey(client, options) {
1746
- return autoRegisterEncryptionKey(client, {
1747
- ...options,
1748
- uaid: options.uaid,
1749
- enabled: true
1750
- });
1751
- }
1752
- function createEncryptionApi(client) {
1753
- return {
1754
- registerKey: (payload) => registerEncryptionKey(client, payload),
1755
- generateEphemeralKeyPair: () => client.createEphemeralKeyPair(),
1756
- deriveSharedSecret: (options) => client.deriveSharedSecret(options),
1757
- encryptCipherEnvelope: (options) => client.buildCipherEnvelope(options),
1758
- decryptCipherEnvelope: (options) => client.openCipherEnvelope(options),
1759
- ensureAgentKey: (options) => ensureAgentEncryptionKey(client, options)
1760
- };
1761
- }
1762
- async function bootstrapEncryptionOptions(client, options) {
1763
- if (!options?.autoRegister || options.autoRegister.enabled === false) {
1764
- return null;
1765
- }
1766
- return autoRegisterEncryptionKey(client, options.autoRegister);
1767
- }
1768
- async function generateEncryptionKeyPair(client, options = {}) {
1769
- client.assertNodeRuntime("generateEncryptionKeyPair");
1770
- const keyType = options.keyType ?? "secp256k1";
1771
- if (keyType !== "secp256k1") {
1772
- throw new Error("Only secp256k1 key generation is supported currently");
1773
- }
1774
- const privateKeyBytes = (0, import_crypto.randomBytes)(32);
1775
- const privateKey = import_buffer.Buffer.from(privateKeyBytes).toString("hex");
1776
- const publicKeyBytes = import_secp256k1.secp256k1.getPublicKey(privateKeyBytes, true);
1777
- const publicKey = import_buffer.Buffer.from(publicKeyBytes).toString("hex");
1778
- const envVar = options.envVar ?? "RB_ENCRYPTION_PRIVATE_KEY";
1779
- const resolvedPath = options.envPath ? path.resolve(options.envPath) : void 0;
1780
- if (resolvedPath) {
1781
- const fsModule = await getFs();
1782
- if (!fsModule) {
1783
- throw new Error(
1784
- "File system module is not available; cannot write encryption key env file"
1785
- );
1786
- }
1787
- const envLine = `${envVar}=${privateKey}`;
1788
- if (fsModule.existsSync(resolvedPath)) {
1789
- const content = fsModule.readFileSync(resolvedPath, "utf-8");
1790
- const lineRegex = new RegExp(`^${envVar}=.*$`, "m");
1791
- if (lineRegex.test(content)) {
1792
- if (!options.overwrite) {
1793
- throw new Error(
1794
- `${envVar} already exists in ${resolvedPath}; set overwrite=true to replace it`
1795
- );
1796
- }
1797
- const updated = content.replace(lineRegex, envLine);
1798
- fsModule.writeFileSync(resolvedPath, updated);
1799
- } else {
1800
- const needsNewline = !content.endsWith("\n");
1801
- fsModule.appendFileSync(
1802
- resolvedPath,
1803
- `${needsNewline ? "\n" : ""}${envLine}
1804
- `
1805
- );
1806
- }
1807
- } else {
1808
- fsModule.writeFileSync(resolvedPath, `${envLine}
1809
- `);
1810
- }
1811
- }
1812
- return {
1813
- privateKey,
1814
- publicKey,
1815
- envPath: resolvedPath,
1816
- envVar
1817
- };
1818
- }
1819
-
1820
- // ../../src/services/registry-broker/client/utils.ts
1821
- var DEFAULT_USER_AGENT = "@hol-org/rb-client";
1822
- var DEFAULT_PROGRESS_INTERVAL_MS = 1500;
1823
- var DEFAULT_PROGRESS_TIMEOUT_MS = 5 * 60 * 1e3;
1824
- var DEFAULT_BASE_URL = "https://hol.org/registry/api/v1";
1825
- var JSON_CONTENT_TYPE = /application\/json/i;
1826
- var DEFAULT_HISTORY_TOP_UP_HBAR = 0.25;
1827
- var MINIMUM_REGISTRATION_AUTO_TOP_UP_CREDITS = 1;
1828
- var stripTrailingSlashes = (value) => {
1829
- let end = value.length;
1830
- while (end > 0 && value.charCodeAt(end - 1) === 47) {
1831
- end -= 1;
1832
- }
1833
- return end === value.length ? value : value.slice(0, end);
1834
- };
1835
- var createAbortError = () => typeof DOMException === "function" ? new DOMException("Aborted", "AbortError") : new Error("The operation was aborted");
1836
- var normaliseHeaderName = (name) => name.trim().toLowerCase();
1837
- var isBrowserRuntime = () => typeof window !== "undefined" && typeof window.fetch === "function";
1838
- var toJsonValue = (value) => {
1839
- if (value === null) {
1840
- return null;
1841
- }
1842
- if (value instanceof Date) {
1843
- return value.toISOString();
1844
- }
1845
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
1846
- return value;
1847
- }
1848
- if (Array.isArray(value)) {
1849
- return value.map((item) => item === void 0 ? null : toJsonValue(item));
1806
+ if (Array.isArray(value)) {
1807
+ return value.map((item) => item === void 0 ? null : toJsonValue(item));
1850
1808
  }
1851
1809
  if (typeof value === "object") {
1852
1810
  const result = {};
@@ -2040,1818 +1998,2091 @@ function buildSearchQuery(params) {
2040
1998
  return queryString.length > 0 ? `?${queryString}` : "";
2041
1999
  }
2042
2000
 
2043
- // ../../src/services/registry-broker/client/errors.ts
2044
- var RegistryBrokerError = class extends Error {
2045
- constructor(message, details) {
2046
- super(message);
2047
- this.status = details.status;
2048
- this.statusText = details.statusText;
2049
- this.body = details.body;
2050
- }
2051
- };
2052
- var RegistryBrokerParseError = class extends Error {
2053
- constructor(message, cause, rawValue) {
2054
- super(message);
2055
- this.cause = cause;
2056
- this.rawValue = rawValue;
2001
+ // ../../src/services/registry-broker/client/encrypted-chat-manager.ts
2002
+ var EncryptionUnavailableError = class extends Error {
2003
+ constructor(sessionId, summary) {
2004
+ super("Encryption is not enabled for this session");
2005
+ this.sessionId = sessionId;
2006
+ this.summary = summary;
2057
2007
  }
2058
2008
  };
2059
-
2060
- // ../../src/services/registry-broker/client/search.ts
2061
- function buildVectorFallbackSearchParams(request) {
2062
- const params = {
2063
- q: request.query
2064
- };
2065
- let effectiveLimit;
2066
- if (typeof request.limit === "number" && Number.isFinite(request.limit)) {
2067
- effectiveLimit = request.limit;
2068
- params.limit = request.limit;
2069
- }
2070
- if (typeof request.offset === "number" && Number.isFinite(request.offset) && request.offset > 0) {
2071
- const limit = effectiveLimit && effectiveLimit > 0 ? effectiveLimit : 20;
2072
- params.limit = limit;
2073
- params.page = Math.floor(request.offset / limit) + 1;
2074
- }
2075
- if (request.filter?.registry) {
2076
- params.registry = request.filter.registry;
2009
+ var EncryptedChatManager = class {
2010
+ constructor(client) {
2011
+ this.client = client;
2077
2012
  }
2078
- if (request.filter?.protocols?.length) {
2079
- params.protocols = [...request.filter.protocols];
2013
+ registerConversationContext(context) {
2014
+ this.client.registerConversationContextForEncryption(context);
2080
2015
  }
2081
- if (request.filter?.adapter?.length) {
2082
- params.adapters = [...request.filter.adapter];
2016
+ async startSession(options) {
2017
+ await this.client.encryptionReady();
2018
+ const session = await this.client.chat.createSession({
2019
+ uaid: options.uaid,
2020
+ senderUaid: options.senderUaid,
2021
+ encryptionRequested: true,
2022
+ historyTtlSeconds: options.historyTtlSeconds,
2023
+ auth: options.auth
2024
+ });
2025
+ options.onSessionCreated?.(session.sessionId);
2026
+ const summary = session.encryption;
2027
+ if (!summary?.enabled) {
2028
+ throw new EncryptionUnavailableError(
2029
+ session.sessionId,
2030
+ session.encryption ?? null
2031
+ );
2032
+ }
2033
+ const handle = await this.establishRequesterContext({
2034
+ sessionId: session.sessionId,
2035
+ summary,
2036
+ senderUaid: options.senderUaid,
2037
+ handshakeTimeoutMs: options.handshakeTimeoutMs,
2038
+ pollIntervalMs: options.pollIntervalMs
2039
+ });
2040
+ return handle;
2083
2041
  }
2084
- if (request.filter?.capabilities?.length) {
2085
- params.capabilities = request.filter.capabilities.map(
2086
- (value) => typeof value === "number" ? value.toString(10) : value
2042
+ async acceptSession(options) {
2043
+ await this.client.encryptionReady();
2044
+ const summary = await this.waitForEncryptionSummary(
2045
+ options.sessionId,
2046
+ options.handshakeTimeoutMs,
2047
+ options.pollIntervalMs
2087
2048
  );
2049
+ const handle = await this.establishResponderContext({
2050
+ sessionId: options.sessionId,
2051
+ summary,
2052
+ responderUaid: options.responderUaid,
2053
+ handshakeTimeoutMs: options.handshakeTimeoutMs,
2054
+ pollIntervalMs: options.pollIntervalMs
2055
+ });
2056
+ return handle;
2088
2057
  }
2089
- if (request.filter?.type) {
2090
- params.type = request.filter.type;
2091
- }
2092
- return params;
2093
- }
2094
- function convertSearchResultToVectorResponse(result) {
2095
- const hits = result.hits.map((agent) => ({
2096
- agent,
2097
- score: 0,
2098
- highlights: {}
2099
- }));
2100
- const total = result.total;
2101
- const limit = result.limit;
2102
- const page = result.page;
2103
- const totalVisible = page * limit;
2104
- const limited = total > totalVisible || page > 1;
2105
- return {
2106
- hits,
2107
- total,
2108
- took: 0,
2109
- totalAvailable: total,
2110
- visible: hits.length,
2111
- limited,
2112
- credits_used: 0
2113
- };
2114
- }
2115
- async function search(client, params = {}) {
2116
- const query = buildSearchQuery(params);
2117
- const raw = await client.requestJson(`/search${query}`, {
2118
- method: "GET"
2119
- });
2120
- return client.parseWithSchema(raw, searchResponseSchema, "search response");
2121
- }
2122
- async function stats(client) {
2123
- const raw = await client.requestJson("/stats", { method: "GET" });
2124
- return client.parseWithSchema(raw, statsResponseSchema, "stats response");
2125
- }
2126
- async function registries(client) {
2127
- const raw = await client.requestJson("/registries", {
2128
- method: "GET"
2129
- });
2130
- return client.parseWithSchema(
2131
- raw,
2132
- registriesResponseSchema,
2133
- "registries response"
2134
- );
2135
- }
2136
- async function getAdditionalRegistries(client) {
2137
- const raw = await client.requestJson(
2138
- "/register/additional-registries",
2139
- {
2140
- method: "GET"
2058
+ async establishRequesterContext(params) {
2059
+ const keyPair = this.client.encryption.generateEphemeralKeyPair();
2060
+ await this.client.chat.submitEncryptionHandshake(params.sessionId, {
2061
+ role: "requester",
2062
+ keyType: "secp256k1",
2063
+ ephemeralPublicKey: keyPair.publicKey,
2064
+ uaid: params.senderUaid ?? params.summary.requester?.uaid ?? void 0
2065
+ });
2066
+ const { summary, record } = await this.waitForHandshakeCompletion(
2067
+ params.sessionId,
2068
+ params.handshakeTimeoutMs,
2069
+ params.pollIntervalMs
2070
+ );
2071
+ const responderKey = record.responder?.ephemeralPublicKey;
2072
+ if (!responderKey) {
2073
+ throw new Error("Responder handshake was not completed in time");
2141
2074
  }
2142
- );
2143
- return client.parseWithSchema(
2144
- raw,
2145
- additionalRegistryCatalogResponseSchema,
2146
- "additional registry catalog response"
2147
- );
2148
- }
2149
- async function popularSearches(client) {
2150
- const raw = await client.requestJson("/popular", {
2151
- method: "GET"
2152
- });
2153
- return client.parseWithSchema(
2154
- raw,
2155
- popularResponseSchema,
2156
- "popular searches response"
2157
- );
2158
- }
2159
- async function listProtocols(client) {
2160
- const raw = await client.requestJson("/protocols", {
2161
- method: "GET"
2162
- });
2163
- return client.parseWithSchema(
2164
- raw,
2165
- protocolsResponseSchema,
2166
- "protocols response"
2167
- );
2168
- }
2169
- async function detectProtocol(client, message) {
2170
- const raw = await client.requestJson("/detect-protocol", {
2171
- method: "POST",
2172
- body: { message },
2173
- headers: { "content-type": "application/json" }
2174
- });
2175
- return client.parseWithSchema(
2176
- raw,
2177
- detectProtocolResponseSchema,
2178
- "detect protocol response"
2179
- );
2075
+ const sharedSecret = this.client.encryption.deriveSharedSecret({
2076
+ privateKey: keyPair.privateKey,
2077
+ peerPublicKey: responderKey
2078
+ }).subarray();
2079
+ const recipients = this.buildRecipients(summary);
2080
+ return this.createHandle({
2081
+ sessionId: params.sessionId,
2082
+ sharedSecret,
2083
+ summary,
2084
+ recipients,
2085
+ identity: summary.requester ?? void 0
2086
+ });
2087
+ }
2088
+ async establishResponderContext(params) {
2089
+ const keyPair = this.client.encryption.generateEphemeralKeyPair();
2090
+ await this.client.chat.submitEncryptionHandshake(params.sessionId, {
2091
+ role: "responder",
2092
+ keyType: "secp256k1",
2093
+ ephemeralPublicKey: keyPair.publicKey,
2094
+ uaid: params.responderUaid ?? params.summary.responder?.uaid ?? void 0
2095
+ });
2096
+ const { summary, record } = await this.waitForHandshakeCompletion(
2097
+ params.sessionId,
2098
+ params.handshakeTimeoutMs,
2099
+ params.pollIntervalMs
2100
+ );
2101
+ const requesterKey = record.requester?.ephemeralPublicKey;
2102
+ if (!requesterKey) {
2103
+ throw new Error("Requester handshake was not detected in time");
2104
+ }
2105
+ const sharedSecret = this.client.encryption.deriveSharedSecret({
2106
+ privateKey: keyPair.privateKey,
2107
+ peerPublicKey: requesterKey
2108
+ }).subarray();
2109
+ const recipients = this.buildRecipients(summary);
2110
+ return this.createHandle({
2111
+ sessionId: params.sessionId,
2112
+ sharedSecret,
2113
+ summary,
2114
+ recipients,
2115
+ identity: summary.responder ?? void 0
2116
+ });
2117
+ }
2118
+ async waitForHandshakeCompletion(sessionId, timeoutMs = 3e4, pollIntervalMs = 1e3) {
2119
+ const deadline = Date.now() + timeoutMs;
2120
+ while (true) {
2121
+ const status = await this.client.chat.getEncryptionStatus(sessionId);
2122
+ const summary = status.encryption;
2123
+ const record = summary?.handshake;
2124
+ if (summary && record && record.status === "complete") {
2125
+ return { summary, record };
2126
+ }
2127
+ if (Date.now() >= deadline) {
2128
+ throw new Error("Timed out waiting for encrypted handshake completion");
2129
+ }
2130
+ await this.delay(pollIntervalMs);
2131
+ }
2132
+ }
2133
+ async waitForEncryptionSummary(sessionId, _timeoutMs = 3e4, _pollIntervalMs = 1e3) {
2134
+ const status = await this.client.chat.getEncryptionStatus(sessionId);
2135
+ if (!status.encryption?.enabled) {
2136
+ throw new EncryptionUnavailableError(
2137
+ sessionId,
2138
+ status.encryption ?? null
2139
+ );
2140
+ }
2141
+ return status.encryption;
2142
+ }
2143
+ buildRecipients(summary) {
2144
+ const candidates = [summary.requester, summary.responder].filter(Boolean);
2145
+ const normalized = candidates.map((candidate) => {
2146
+ if (!candidate) {
2147
+ return null;
2148
+ }
2149
+ const recipient = {};
2150
+ if (candidate.uaid) {
2151
+ recipient.uaid = candidate.uaid;
2152
+ }
2153
+ if (candidate.ledgerAccountId) {
2154
+ recipient.ledgerAccountId = candidate.ledgerAccountId;
2155
+ }
2156
+ if (candidate.userId) {
2157
+ recipient.userId = candidate.userId;
2158
+ }
2159
+ if (candidate.email) {
2160
+ recipient.email = candidate.email;
2161
+ }
2162
+ return recipient;
2163
+ }).filter(
2164
+ (entry) => Boolean(
2165
+ entry?.uaid || entry?.ledgerAccountId || entry?.userId || entry?.email
2166
+ )
2167
+ );
2168
+ if (normalized.length > 0) {
2169
+ return normalized;
2170
+ }
2171
+ if (summary.responder?.uaid) {
2172
+ return [{ uaid: summary.responder.uaid }];
2173
+ }
2174
+ return [];
2175
+ }
2176
+ createHandle(context) {
2177
+ const sharedSecret = context.sharedSecret;
2178
+ const uaid = context.summary.requester?.uaid ?? context.summary.responder?.uaid ?? context.identity?.uaid;
2179
+ const decryptHistoryEntry = (entry) => this.decryptEntry(entry, context.identity, sharedSecret);
2180
+ const fetchHistory = async (options) => {
2181
+ const snapshot = await this.client.fetchHistorySnapshot(
2182
+ context.sessionId,
2183
+ options
2184
+ );
2185
+ if (snapshot.decryptedHistory) {
2186
+ return snapshot.decryptedHistory;
2187
+ }
2188
+ return snapshot.history.map((entry) => ({
2189
+ entry,
2190
+ plaintext: decryptHistoryEntry(entry)
2191
+ }));
2192
+ };
2193
+ const handle = {
2194
+ sessionId: context.sessionId,
2195
+ mode: "encrypted",
2196
+ summary: context.summary,
2197
+ send: async (options) => {
2198
+ const recipients = options.recipients ?? context.recipients;
2199
+ return this.client.chat.sendMessage({
2200
+ sessionId: context.sessionId,
2201
+ message: options.message ?? "[ciphertext omitted]",
2202
+ streaming: options.streaming,
2203
+ auth: options.auth,
2204
+ uaid,
2205
+ encryption: {
2206
+ plaintext: options.plaintext,
2207
+ sharedSecret: Buffer.from(sharedSecret),
2208
+ recipients
2209
+ }
2210
+ });
2211
+ },
2212
+ decryptHistoryEntry,
2213
+ fetchHistory
2214
+ };
2215
+ this.registerConversationContext({
2216
+ sessionId: context.sessionId,
2217
+ sharedSecret,
2218
+ identity: context.identity
2219
+ });
2220
+ return handle;
2221
+ }
2222
+ decryptEntry(entry, identity, fallbackSecret) {
2223
+ const envelope = entry.cipherEnvelope;
2224
+ if (!envelope) {
2225
+ return null;
2226
+ }
2227
+ const secret = Buffer.from(fallbackSecret);
2228
+ try {
2229
+ return this.client.encryption.decryptCipherEnvelope({
2230
+ envelope,
2231
+ sharedSecret: secret
2232
+ });
2233
+ } catch (_error) {
2234
+ return null;
2235
+ }
2236
+ }
2237
+ recipientMatches(candidate, target) {
2238
+ if (target.uaid && candidate.uaid?.toLowerCase() === target.uaid.toLowerCase()) {
2239
+ return true;
2240
+ }
2241
+ if (target.ledgerAccountId && candidate.ledgerAccountId?.toLowerCase() === target.ledgerAccountId.toLowerCase()) {
2242
+ return true;
2243
+ }
2244
+ if (target.userId && candidate.userId === target.userId) {
2245
+ return true;
2246
+ }
2247
+ if (target.email && candidate.email?.toLowerCase() === target.email.toLowerCase()) {
2248
+ return true;
2249
+ }
2250
+ return false;
2251
+ }
2252
+ async delay(ms) {
2253
+ if (ms <= 0) {
2254
+ return;
2255
+ }
2256
+ await new Promise((resolve) => setTimeout(resolve, ms));
2257
+ }
2258
+ };
2259
+
2260
+ // ../../src/services/registry-broker/client/chat.ts
2261
+ function createChatApi(client, encryptedManager) {
2262
+ return {
2263
+ start: (options) => client.startChat(options),
2264
+ createSession: (payload) => client.createSession(payload),
2265
+ sendMessage: (payload) => client.sendMessage(payload),
2266
+ endSession: (sessionId) => client.endSession(sessionId),
2267
+ getHistory: (sessionId, options) => client.fetchHistorySnapshot(sessionId, options),
2268
+ compactHistory: (payload) => client.compactHistory(payload),
2269
+ getEncryptionStatus: (sessionId) => client.fetchEncryptionStatus(sessionId),
2270
+ submitEncryptionHandshake: (sessionId, payload) => client.postEncryptionHandshake(sessionId, payload),
2271
+ startConversation: (options) => client.startConversation(options),
2272
+ acceptConversation: (options) => client.acceptConversation(options),
2273
+ createEncryptedSession: (options) => encryptedManager.startSession(options),
2274
+ acceptEncryptedSession: (options) => encryptedManager.acceptSession(options)
2275
+ };
2180
2276
  }
2181
- async function registrySearchByNamespace(client, registry, query) {
2182
- const params = new URLSearchParams();
2183
- if (query) {
2184
- params.set("q", query);
2277
+ async function createSession(client, payload, allowHistoryAutoTopUp = true) {
2278
+ const body = {};
2279
+ if ("uaid" in payload && payload.uaid) {
2280
+ body.uaid = payload.uaid;
2281
+ }
2282
+ if ("agentUrl" in payload && payload.agentUrl) {
2283
+ body.agentUrl = payload.agentUrl;
2284
+ }
2285
+ if (payload.auth) {
2286
+ body.auth = serialiseAuthConfig(payload.auth);
2287
+ }
2288
+ if (payload.historyTtlSeconds !== void 0) {
2289
+ body.historyTtlSeconds = payload.historyTtlSeconds;
2290
+ }
2291
+ if (payload.encryptionRequested !== void 0) {
2292
+ body.encryptionRequested = payload.encryptionRequested;
2293
+ }
2294
+ if (payload.senderUaid) {
2295
+ body.senderUaid = payload.senderUaid;
2185
2296
  }
2186
- const suffix = params.size > 0 ? `?${params.toString()}` : "";
2187
- const raw = await client.requestJson(
2188
- `/registries/${encodeURIComponent(registry)}/search${suffix}`,
2189
- {
2190
- method: "GET"
2191
- }
2192
- );
2193
- return client.parseWithSchema(
2194
- raw,
2195
- registrySearchByNamespaceSchema,
2196
- "registry search response"
2197
- );
2198
- }
2199
- async function vectorSearch(client, request) {
2200
2297
  try {
2201
- const raw = await client.requestJson("/search", {
2298
+ const raw = await client.requestJson("/chat/session", {
2202
2299
  method: "POST",
2203
- body: request,
2300
+ body,
2204
2301
  headers: { "content-type": "application/json" }
2205
2302
  });
2206
2303
  return client.parseWithSchema(
2207
2304
  raw,
2208
- vectorSearchResponseSchema,
2209
- "vector search response"
2305
+ createSessionResponseSchema,
2306
+ "chat session response"
2210
2307
  );
2211
2308
  } catch (error) {
2212
- if (error instanceof RegistryBrokerError && error.status === 501) {
2213
- const fallback = await search(
2214
- client,
2215
- buildVectorFallbackSearchParams(request)
2216
- );
2217
- return convertSearchResultToVectorResponse(fallback);
2309
+ const maybeError = error instanceof Error ? error : null;
2310
+ if (allowHistoryAutoTopUp && client.shouldAutoTopUpHistory(payload, maybeError)) {
2311
+ await client.executeHistoryAutoTopUp("chat.session");
2312
+ return createSession(client, payload, false);
2218
2313
  }
2219
2314
  throw error;
2220
2315
  }
2221
2316
  }
2222
- async function searchStatus(client) {
2223
- const raw = await client.requestJson("/search/status", {
2224
- method: "GET"
2225
- });
2226
- return client.parseWithSchema(
2227
- raw,
2228
- searchStatusResponseSchema,
2229
- "search status response"
2230
- );
2231
- }
2232
- async function websocketStats(client) {
2233
- const raw = await client.requestJson("/websocket/stats", {
2234
- method: "GET"
2235
- });
2236
- return client.parseWithSchema(
2237
- raw,
2238
- websocketStatsResponseSchema,
2239
- "websocket stats response"
2240
- );
2241
- }
2242
- async function metricsSummary(client) {
2243
- const raw = await client.requestJson("/metrics", {
2244
- method: "GET"
2245
- });
2246
- return client.parseWithSchema(
2247
- raw,
2248
- metricsSummaryResponseSchema,
2249
- "metrics summary response"
2250
- );
2251
- }
2252
- async function facets(client, adapter) {
2253
- const params = new URLSearchParams();
2254
- if (adapter) {
2255
- params.set("adapter", adapter);
2317
+ async function startChat(client, encryptedManager, options) {
2318
+ if ("uaid" in options && options.uaid) {
2319
+ return startConversation(client, encryptedManager, {
2320
+ uaid: options.uaid,
2321
+ senderUaid: options.senderUaid,
2322
+ historyTtlSeconds: options.historyTtlSeconds,
2323
+ auth: options.auth,
2324
+ encryption: options.encryption,
2325
+ onSessionCreated: options.onSessionCreated
2326
+ });
2256
2327
  }
2257
- const suffix = params.size > 0 ? `?${params.toString()}` : "";
2258
- const raw = await client.requestJson(`/search/facets${suffix}`, {
2259
- method: "GET"
2260
- });
2261
- return client.parseWithSchema(
2262
- raw,
2263
- searchFacetsResponseSchema,
2264
- "search facets response"
2265
- );
2266
- }
2267
-
2268
- // ../../src/services/registry-broker/client/adapters.ts
2269
- async function adapters(client) {
2270
- const raw = await client.requestJson("/adapters", {
2271
- method: "GET"
2272
- });
2273
- return client.parseWithSchema(
2274
- raw,
2275
- adaptersResponseSchema,
2276
- "adapters response"
2277
- );
2278
- }
2279
- async function adaptersDetailed(client) {
2280
- const raw = await client.requestJson("/adapters/details", {
2281
- method: "GET"
2282
- });
2283
- return client.parseWithSchema(
2284
- raw,
2285
- adapterDetailsResponseSchema,
2286
- "adapter details response"
2287
- );
2288
- }
2289
- async function adapterRegistryCategories(client) {
2290
- const raw = await client.requestJson(
2291
- "/adapters/registry/categories",
2292
- {
2293
- method: "GET"
2294
- }
2295
- );
2296
- return client.parseWithSchema(
2297
- raw,
2298
- adapterRegistryCategoriesResponseSchema,
2299
- "adapter registry categories response"
2300
- );
2328
+ if ("agentUrl" in options && options.agentUrl) {
2329
+ const session = await createSession(client, {
2330
+ agentUrl: options.agentUrl,
2331
+ auth: options.auth,
2332
+ historyTtlSeconds: options.historyTtlSeconds,
2333
+ senderUaid: options.senderUaid
2334
+ });
2335
+ options.onSessionCreated?.(session.sessionId);
2336
+ return createPlaintextConversationHandle(
2337
+ client,
2338
+ session.sessionId,
2339
+ session.encryption ?? null,
2340
+ options.auth,
2341
+ { agentUrl: options.agentUrl, uaid: options.uaid }
2342
+ );
2343
+ }
2344
+ throw new Error("startChat requires either uaid or agentUrl");
2301
2345
  }
2302
- async function adapterRegistryAdapters(client, filters = {}) {
2303
- const params = new URLSearchParams();
2304
- if (filters.category) {
2305
- params.set("category", filters.category);
2346
+ async function startConversation(client, encryptedManager, options) {
2347
+ const preference = options.encryption?.preference ?? "preferred";
2348
+ const requestEncryption = preference !== "disabled";
2349
+ if (!requestEncryption) {
2350
+ const session = await createSession(client, {
2351
+ uaid: options.uaid,
2352
+ auth: options.auth,
2353
+ historyTtlSeconds: options.historyTtlSeconds,
2354
+ senderUaid: options.senderUaid,
2355
+ encryptionRequested: false
2356
+ });
2357
+ options.onSessionCreated?.(session.sessionId);
2358
+ return createPlaintextConversationHandle(
2359
+ client,
2360
+ session.sessionId,
2361
+ session.encryption ?? null,
2362
+ options.auth,
2363
+ { uaid: options.uaid }
2364
+ );
2306
2365
  }
2307
- if (filters.entity) {
2308
- params.set("entity", filters.entity);
2366
+ try {
2367
+ const handle = await encryptedManager.startSession({
2368
+ uaid: options.uaid,
2369
+ senderUaid: options.senderUaid,
2370
+ historyTtlSeconds: options.historyTtlSeconds,
2371
+ handshakeTimeoutMs: options.encryption?.handshakeTimeoutMs,
2372
+ pollIntervalMs: options.encryption?.pollIntervalMs,
2373
+ onSessionCreated: (sessionId) => {
2374
+ options.onSessionCreated?.(sessionId);
2375
+ },
2376
+ auth: options.auth
2377
+ });
2378
+ return handle;
2379
+ } catch (error) {
2380
+ if (error instanceof EncryptionUnavailableError) {
2381
+ if (preference === "required") {
2382
+ throw error;
2383
+ }
2384
+ return createPlaintextConversationHandle(
2385
+ client,
2386
+ error.sessionId,
2387
+ error.summary ?? null,
2388
+ options.auth,
2389
+ { uaid: options.uaid }
2390
+ );
2391
+ }
2392
+ throw error;
2309
2393
  }
2310
- if (filters.keywords?.length) {
2311
- params.set("keywords", filters.keywords.join(","));
2394
+ }
2395
+ async function acceptConversation(client, encryptedManager, options) {
2396
+ const preference = options.encryption?.preference ?? "preferred";
2397
+ if (preference === "disabled") {
2398
+ return createPlaintextConversationHandle(client, options.sessionId, null);
2312
2399
  }
2313
- if (filters.query) {
2314
- params.set("query", filters.query);
2400
+ try {
2401
+ const handle = await encryptedManager.acceptSession({
2402
+ sessionId: options.sessionId,
2403
+ responderUaid: options.responderUaid,
2404
+ handshakeTimeoutMs: options.encryption?.handshakeTimeoutMs,
2405
+ pollIntervalMs: options.encryption?.pollIntervalMs
2406
+ });
2407
+ return handle;
2408
+ } catch (error) {
2409
+ if (error instanceof EncryptionUnavailableError && preference !== "required") {
2410
+ return createPlaintextConversationHandle(
2411
+ client,
2412
+ options.sessionId,
2413
+ null,
2414
+ void 0,
2415
+ { uaid: options.responderUaid }
2416
+ );
2417
+ }
2418
+ throw error;
2315
2419
  }
2316
- if (typeof filters.limit === "number") {
2317
- params.set("limit", String(filters.limit));
2420
+ }
2421
+ function createPlaintextConversationHandle(client, sessionId, summary, defaultAuth, context) {
2422
+ const uaid = context?.uaid?.trim();
2423
+ const agentUrl = context?.agentUrl?.trim();
2424
+ const fetchHistory = async (options) => {
2425
+ const snapshot = await client.fetchHistorySnapshot(sessionId, options);
2426
+ if (snapshot.decryptedHistory) {
2427
+ return snapshot.decryptedHistory;
2428
+ }
2429
+ return snapshot.history.map((entry) => ({
2430
+ entry,
2431
+ plaintext: entry.content
2432
+ }));
2433
+ };
2434
+ return {
2435
+ sessionId,
2436
+ mode: "plaintext",
2437
+ summary: summary ?? null,
2438
+ send: async (options) => {
2439
+ const plaintext = options.plaintext;
2440
+ if (!plaintext || plaintext.trim().length === 0) {
2441
+ throw new Error("plaintext is required for chat messages");
2442
+ }
2443
+ const message = options.message ?? plaintext;
2444
+ return sendMessage(client, {
2445
+ sessionId,
2446
+ message,
2447
+ streaming: options.streaming,
2448
+ auth: options.auth ?? defaultAuth,
2449
+ uaid,
2450
+ agentUrl
2451
+ });
2452
+ },
2453
+ decryptHistoryEntry: (entry) => entry.content,
2454
+ fetchHistory
2455
+ };
2456
+ }
2457
+ async function compactHistory(client, payload) {
2458
+ if (!payload.sessionId || payload.sessionId.trim().length === 0) {
2459
+ throw new Error("sessionId is required to compact chat history");
2318
2460
  }
2319
- if (typeof filters.offset === "number") {
2320
- params.set("offset", String(filters.offset));
2461
+ const body = {};
2462
+ if (typeof payload.preserveEntries === "number" && Number.isFinite(payload.preserveEntries) && payload.preserveEntries >= 0) {
2463
+ body.preserveEntries = Math.floor(payload.preserveEntries);
2321
2464
  }
2322
- const suffix = params.size > 0 ? `?${params.toString()}` : "";
2323
- const raw = await client.requestJson(
2324
- `/adapters/registry/adapters${suffix}`,
2325
- {
2326
- method: "GET"
2327
- }
2328
- );
2329
- return client.parseWithSchema(
2330
- raw,
2331
- adapterRegistryAdaptersResponseSchema,
2332
- "adapter registry adapters response"
2333
- );
2334
- }
2335
- async function createAdapterRegistryCategory(client, payload) {
2336
2465
  const raw = await client.requestJson(
2337
- "/adapters/registry/categories",
2466
+ `/chat/session/${encodeURIComponent(payload.sessionId)}/compact`,
2338
2467
  {
2339
2468
  method: "POST",
2340
2469
  headers: { "content-type": "application/json" },
2341
- body: toJsonObject(payload)
2470
+ body
2342
2471
  }
2343
2472
  );
2344
- const parsed = client.parseWithSchema(
2473
+ return client.parseWithSchema(
2345
2474
  raw,
2346
- adapterRegistryCreateCategoryResponseSchema,
2347
- "adapter registry create category response"
2475
+ chatHistoryCompactionResponseSchema,
2476
+ "chat history compaction response"
2348
2477
  );
2349
- return parsed.category;
2350
2478
  }
2351
- async function submitAdapterRegistryAdapter(client, payload) {
2479
+ async function fetchEncryptionStatus(client, sessionId) {
2480
+ if (!sessionId || sessionId.trim().length === 0) {
2481
+ throw new Error("sessionId is required for encryption status");
2482
+ }
2352
2483
  const raw = await client.requestJson(
2353
- "/adapters/registry/adapters",
2484
+ `/chat/session/${encodeURIComponent(sessionId)}/encryption`,
2354
2485
  {
2355
- method: "POST",
2356
- headers: { "content-type": "application/json" },
2357
- body: toJsonObject(payload)
2486
+ method: "GET"
2358
2487
  }
2359
2488
  );
2360
2489
  return client.parseWithSchema(
2361
2490
  raw,
2362
- adapterRegistrySubmitAdapterAcceptedResponseSchema,
2363
- "adapter registry submit adapter response"
2491
+ sessionEncryptionStatusResponseSchema,
2492
+ "session encryption status response"
2364
2493
  );
2365
2494
  }
2366
- async function adapterRegistrySubmissionStatus(client, submissionId) {
2495
+ async function postEncryptionHandshake(client, sessionId, payload) {
2496
+ if (!sessionId || sessionId.trim().length === 0) {
2497
+ throw new Error("sessionId is required for encryption handshake");
2498
+ }
2367
2499
  const raw = await client.requestJson(
2368
- `/adapters/registry/submissions/${encodeURIComponent(submissionId)}`,
2500
+ `/chat/session/${encodeURIComponent(sessionId)}/encryption-handshake`,
2369
2501
  {
2370
- method: "GET"
2502
+ method: "POST",
2503
+ headers: { "content-type": "application/json" },
2504
+ body: {
2505
+ role: payload.role,
2506
+ keyType: payload.keyType,
2507
+ ephemeralPublicKey: payload.ephemeralPublicKey,
2508
+ longTermPublicKey: payload.longTermPublicKey,
2509
+ signature: payload.signature,
2510
+ uaid: payload.uaid,
2511
+ userId: payload.userId,
2512
+ ledgerAccountId: payload.ledgerAccountId,
2513
+ metadata: payload.metadata
2514
+ }
2371
2515
  }
2372
2516
  );
2373
- return client.parseWithSchema(
2517
+ const response = client.parseWithSchema(
2374
2518
  raw,
2375
- adapterRegistrySubmissionStatusResponseSchema,
2376
- "adapter registry submission status response"
2519
+ encryptionHandshakeResponseSchema,
2520
+ "encryption handshake response"
2377
2521
  );
2522
+ return response.handshake;
2378
2523
  }
2379
-
2380
- // ../../src/services/registry-broker/client/credits.ts
2381
- async function loadX402Dependencies(client) {
2382
- const [{ default: axios }, x402Axios, x402Types] = await Promise.all([
2383
- import("axios"),
2384
- optionalImport("x402-axios"),
2385
- optionalImport("x402/types")
2386
- ]);
2387
- if (!x402Axios || !x402Types) {
2388
- throw new Error(
2389
- "x402-axios and x402/types are required for X402 flows. Install them to enable ledger payments."
2390
- );
2391
- }
2392
- const withPaymentInterceptor = x402Axios.withPaymentInterceptor;
2393
- const decodePaymentResponse = x402Axios.decodeXPaymentResponse;
2394
- const createX402Signer = x402Types.createSigner;
2395
- const createPaymentClient = (walletClient) => {
2396
- const axiosClient = axios.create({
2397
- baseURL: client.baseUrl,
2398
- headers: {
2399
- ...client.getDefaultHeaders(),
2400
- "content-type": "application/json"
2401
- }
2402
- });
2403
- const paymentClient = withPaymentInterceptor(axiosClient, walletClient);
2404
- return paymentClient;
2405
- };
2406
- return { createPaymentClient, decodePaymentResponse, createX402Signer };
2407
- }
2408
- function calculateHbarAmountParam(hbarAmount) {
2409
- const tinybars = Math.ceil(hbarAmount * 1e8);
2410
- if (tinybars <= 0) {
2411
- throw new Error("Calculated purchase amount must be positive");
2412
- }
2413
- return tinybars / 1e8;
2414
- }
2415
- async function purchaseCreditsWithHbar(client, params) {
2524
+ async function sendMessage(client, payload) {
2416
2525
  const body = {
2417
- accountId: params.accountId,
2418
- payerKey: params.privateKey,
2419
- hbarAmount: calculateHbarAmountParam(params.hbarAmount)
2526
+ message: payload.message
2420
2527
  };
2421
- if (params.memo) {
2422
- body.memo = params.memo;
2528
+ if (payload.streaming !== void 0) {
2529
+ body.streaming = payload.streaming;
2423
2530
  }
2424
- if (params.metadata) {
2425
- body.metadata = params.metadata;
2531
+ if (payload.auth) {
2532
+ body.auth = serialiseAuthConfig(payload.auth);
2426
2533
  }
2427
- const raw = await client.requestJson("/credits/purchase", {
2428
- method: "POST",
2429
- headers: { "content-type": "application/json" },
2430
- body
2431
- });
2432
- return client.parseWithSchema(
2433
- raw,
2434
- creditPurchaseResponseSchema,
2435
- "credit purchase response"
2436
- );
2437
- }
2438
- async function getX402Minimums(client) {
2439
- const raw = await client.requestJson(
2440
- "/credits/purchase/x402/minimums",
2441
- { method: "GET" }
2442
- );
2443
- return client.parseWithSchema(
2444
- raw,
2445
- x402MinimumsResponseSchema,
2446
- "x402 minimums response"
2447
- );
2448
- }
2449
- async function purchaseCreditsWithX402(client, params) {
2450
- const { createPaymentClient, decodePaymentResponse } = await loadX402Dependencies(client);
2451
- if (!Number.isFinite(params.credits) || params.credits <= 0) {
2452
- throw new Error("credits must be a positive number");
2534
+ if ("uaid" in payload) {
2535
+ body.uaid = payload.uaid;
2453
2536
  }
2454
- if (params.usdAmount !== void 0 && (!Number.isFinite(params.usdAmount) || params.usdAmount <= 0)) {
2455
- throw new Error("usdAmount must be a positive number when provided");
2537
+ if ("sessionId" in payload && payload.sessionId) {
2538
+ body.sessionId = payload.sessionId;
2456
2539
  }
2457
- const body = {
2458
- accountId: params.accountId,
2459
- credits: params.credits
2460
- };
2461
- if (params.usdAmount !== void 0) {
2462
- body.usdAmount = params.usdAmount;
2540
+ if ("agentUrl" in payload && payload.agentUrl) {
2541
+ body.agentUrl = payload.agentUrl;
2463
2542
  }
2464
- if (params.description) {
2465
- body.description = params.description;
2543
+ let cipherEnvelope = payload.cipherEnvelope ?? null;
2544
+ if (payload.encryption) {
2545
+ const sessionIdForEncryption = payload.encryption.sessionId ?? (typeof body.sessionId === "string" ? body.sessionId : void 0);
2546
+ if (!sessionIdForEncryption) {
2547
+ throw new Error(
2548
+ "sessionId is required when using encrypted chat payloads"
2549
+ );
2550
+ }
2551
+ if (!payload.encryption.recipients?.length) {
2552
+ throw new Error("recipients are required for encrypted chat payloads");
2553
+ }
2554
+ cipherEnvelope = client.encryption.encryptCipherEnvelope({
2555
+ ...payload.encryption,
2556
+ sessionId: sessionIdForEncryption
2557
+ });
2466
2558
  }
2467
- if (params.metadata) {
2468
- body.metadata = params.metadata;
2559
+ if (cipherEnvelope) {
2560
+ body.cipherEnvelope = toJsonObject(cipherEnvelope);
2469
2561
  }
2470
- const paymentClient = createPaymentClient(params.walletClient);
2471
- const response = await paymentClient.post("/credits/purchase/x402", body);
2472
- const parsed = client.parseWithSchema(
2473
- response.data,
2474
- x402CreditPurchaseResponseSchema,
2475
- "x402 credit purchase response"
2476
- );
2477
- const responseHeaders = response.headers ?? {};
2478
- const paymentHeader = typeof responseHeaders["x-payment-response"] === "string" ? responseHeaders["x-payment-response"] : void 0;
2479
- const decodedPayment = paymentHeader !== void 0 ? decodePaymentResponse(paymentHeader) : void 0;
2480
- return {
2481
- ...parsed,
2482
- paymentResponseHeader: paymentHeader,
2483
- paymentResponse: decodedPayment
2484
- };
2485
- }
2486
- async function buyCreditsWithX402(client, params) {
2487
- const network = params.network ?? "base";
2488
- const { createX402Signer } = await loadX402Dependencies(client);
2489
- const normalizedKey = normalizeHexPrivateKey(params.evmPrivateKey);
2490
- const walletClient = await createX402Signer(network, normalizedKey);
2491
- return purchaseCreditsWithX402(client, {
2492
- accountId: params.accountId,
2493
- credits: params.credits,
2494
- usdAmount: params.usdAmount,
2495
- description: params.description,
2496
- metadata: params.metadata,
2497
- walletClient
2498
- });
2499
- }
2500
-
2501
- // ../../src/services/registry-broker/client/agents.ts
2502
- async function resolveUaid(client, uaid) {
2503
- const raw = await client.requestJson(
2504
- `/resolve/${encodeURIComponent(uaid)}`,
2505
- {
2506
- method: "GET"
2507
- }
2508
- );
2509
- return client.parseWithSchema(
2510
- raw,
2511
- resolveResponseSchema,
2512
- "resolve UAID response"
2513
- );
2514
- }
2515
- async function getRegistrationQuote(client, payload) {
2516
- const raw = await client.requestJson("/register/quote", {
2562
+ const raw = await client.requestJson("/chat/message", {
2517
2563
  method: "POST",
2518
- body: serialiseAgentRegistrationRequest(payload),
2564
+ body,
2519
2565
  headers: { "content-type": "application/json" }
2520
2566
  });
2521
2567
  return client.parseWithSchema(
2522
2568
  raw,
2523
- registrationQuoteResponseSchema,
2524
- "registration quote response"
2569
+ sendMessageResponseSchema,
2570
+ "chat message response"
2525
2571
  );
2526
2572
  }
2527
- async function updateAgent(client, uaid, payload) {
2528
- const raw = await client.requestJson(
2529
- `/register/${encodeURIComponent(uaid)}`,
2530
- {
2531
- method: "PUT",
2532
- body: serialiseAgentRegistrationRequest(payload),
2533
- headers: { "content-type": "application/json" }
2573
+ async function endSession(client, sessionId) {
2574
+ await client.request(`/chat/session/${encodeURIComponent(sessionId)}`, {
2575
+ method: "DELETE"
2576
+ });
2577
+ }
2578
+
2579
+ // ../../src/services/registry-broker/client/encryption.ts
2580
+ var import_buffer2 = require("buffer");
2581
+ var import_secp256k1 = require("@noble/curves/secp256k1.js");
2582
+
2583
+ // ../../src/utils/is-browser.ts
2584
+ var isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined";
2585
+
2586
+ // ../../src/utils/dynamic-import.ts
2587
+ var import_meta = {};
2588
+ var nodeRequire;
2589
+ var isNodeRuntime = () => typeof process !== "undefined" && Boolean(process.versions?.node);
2590
+ function getNodeRequireSync() {
2591
+ try {
2592
+ const moduleNamespace = process.getBuiltinModule?.("module");
2593
+ if (typeof moduleNamespace?.createRequire === "function") {
2594
+ const requireFromModule = moduleNamespace.createRequire(import_meta.url);
2595
+ if (typeof requireFromModule.resolve === "function") {
2596
+ return requireFromModule;
2597
+ }
2598
+ }
2599
+ const globalObject = typeof global !== "undefined" ? global : globalThis;
2600
+ const runtimeRequire = globalObject.process?.mainModule?.require ?? globalObject.require ?? Function('return typeof require === "function" ? require : undefined;')();
2601
+ if (typeof runtimeRequire === "function" && typeof runtimeRequire.resolve === "function") {
2602
+ return runtimeRequire;
2603
+ }
2604
+ } catch {
2605
+ return null;
2606
+ }
2607
+ return null;
2608
+ }
2609
+ function isModuleNotFound(specifier, error) {
2610
+ if (!error || typeof error !== "object") {
2611
+ return false;
2612
+ }
2613
+ const code = Reflect.get(error, "code");
2614
+ const message = Reflect.get(error, "message");
2615
+ const messageText = typeof message === "string" ? message : "";
2616
+ if (typeof code === "string" && code.includes("MODULE_NOT_FOUND")) {
2617
+ return messageText.includes(specifier);
2618
+ }
2619
+ if (messageText) {
2620
+ const lowered = messageText.toLowerCase();
2621
+ if (lowered.includes("cannot find module") || lowered.includes("module not found") || lowered.includes("cannot find package")) {
2622
+ return lowered.includes(specifier.toLowerCase());
2534
2623
  }
2535
- );
2536
- return client.parseWithSchema(
2537
- raw,
2538
- registerAgentResponseSchema,
2539
- "update agent response"
2540
- );
2624
+ }
2625
+ return false;
2541
2626
  }
2542
- async function getRegistrationProgress(client, attemptId) {
2543
- const normalisedAttemptId = attemptId.trim();
2544
- if (!normalisedAttemptId) {
2545
- throw new Error("attemptId is required");
2627
+ async function resolveNodeRequire() {
2628
+ if (nodeRequire !== void 0) {
2629
+ return nodeRequire;
2630
+ }
2631
+ if (isBrowser && !isNodeRuntime()) {
2632
+ nodeRequire = null;
2633
+ return nodeRequire;
2546
2634
  }
2547
2635
  try {
2548
- const raw = await client.requestJson(
2549
- `/register/progress/${encodeURIComponent(normalisedAttemptId)}`,
2550
- { method: "GET" }
2551
- );
2552
- const parsed = client.parseWithSchema(
2553
- raw,
2554
- registrationProgressResponseSchema,
2555
- "registration progress response"
2636
+ nodeRequire = getNodeRequireSync();
2637
+ } catch {
2638
+ nodeRequire = null;
2639
+ }
2640
+ return nodeRequire;
2641
+ }
2642
+ async function dynamicImport(specifier) {
2643
+ try {
2644
+ return await import(
2645
+ /* webpackIgnore: true */
2646
+ specifier
2556
2647
  );
2557
- return parsed.progress;
2558
2648
  } catch (error) {
2559
- if (error instanceof RegistryBrokerError && error.status === 404) {
2649
+ if (isModuleNotFound(specifier, error)) {
2560
2650
  return null;
2561
2651
  }
2562
2652
  throw error;
2563
2653
  }
2564
2654
  }
2565
- async function waitForRegistrationCompletion(client, attemptId, options = {}) {
2566
- const normalisedAttemptId = attemptId.trim();
2567
- if (!normalisedAttemptId) {
2568
- throw new Error("attemptId is required");
2655
+ async function optionalImport(specifier, options = {}) {
2656
+ if (isBrowser && !isNodeRuntime()) {
2657
+ return dynamicImport(specifier);
2569
2658
  }
2570
- const interval = Math.max(
2571
- 250,
2572
- options.intervalMs ?? DEFAULT_PROGRESS_INTERVAL_MS
2573
- );
2574
- const timeoutMs = options.timeoutMs ?? DEFAULT_PROGRESS_TIMEOUT_MS;
2575
- const throwOnFailure = options.throwOnFailure ?? true;
2576
- const signal = options.signal;
2577
- const startedAt = Date.now();
2578
- while (true) {
2579
- if (signal?.aborted) {
2580
- throw createAbortError();
2581
- }
2582
- const progress = await client.getRegistrationProgress(normalisedAttemptId);
2583
- if (progress) {
2584
- options.onProgress?.(progress);
2585
- if (progress.status === "completed") {
2586
- return progress;
2587
- }
2588
- if (progress.status === "partial" || progress.status === "failed") {
2589
- if (throwOnFailure) {
2590
- throw new RegistryBrokerError(
2591
- "Registration did not complete successfully",
2592
- {
2593
- status: 409,
2594
- statusText: progress.status,
2595
- body: progress
2596
- }
2597
- );
2659
+ if (!options.preferImport) {
2660
+ const requireFn = await resolveNodeRequire();
2661
+ if (requireFn) {
2662
+ try {
2663
+ return requireFn(specifier);
2664
+ } catch (error) {
2665
+ if (!isModuleNotFound(specifier, error)) {
2666
+ throw error;
2598
2667
  }
2599
- return progress;
2600
2668
  }
2601
2669
  }
2602
- if (Date.now() - startedAt >= timeoutMs) {
2603
- throw new Error(
2604
- `Registration progress polling timed out after ${timeoutMs}ms`
2605
- );
2606
- }
2607
- await client.delay(interval, signal);
2608
2670
  }
2671
+ return dynamicImport(specifier);
2609
2672
  }
2610
- async function validateUaid(client, uaid) {
2611
- const raw = await client.requestJson(
2612
- `/uaids/validate/${encodeURIComponent(uaid)}`,
2613
- {
2614
- method: "GET"
2673
+ function optionalImportSync(specifier) {
2674
+ if (isBrowser && !isNodeRuntime()) {
2675
+ return null;
2676
+ }
2677
+ try {
2678
+ const requireFn = getNodeRequireSync();
2679
+ if (requireFn) {
2680
+ return requireFn(specifier);
2615
2681
  }
2616
- );
2617
- return client.parseWithSchema(
2618
- raw,
2619
- uaidValidationResponseSchema,
2620
- "UAID validation response"
2621
- );
2622
- }
2623
- async function getUaidConnectionStatus(client, uaid) {
2624
- const raw = await client.requestJson(
2625
- `/uaids/connections/${encodeURIComponent(uaid)}/status`,
2626
- {
2627
- method: "GET"
2682
+ } catch (error) {
2683
+ if (!isModuleNotFound(specifier, error)) {
2684
+ throw error;
2628
2685
  }
2629
- );
2630
- return client.parseWithSchema(
2631
- raw,
2632
- uaidConnectionStatusSchema,
2633
- "UAID connection status"
2634
- );
2635
- }
2636
- async function closeUaidConnection(client, uaid) {
2637
- await client.request(`/uaids/connections/${encodeURIComponent(uaid)}`, {
2638
- method: "DELETE"
2639
- });
2640
- }
2641
- async function dashboardStats(client) {
2642
- const raw = await client.requestJson("/dashboard/stats", {
2643
- method: "GET"
2644
- });
2645
- return client.parseWithSchema(
2646
- raw,
2647
- dashboardStatsResponseSchema,
2648
- "dashboard stats response"
2649
- );
2686
+ }
2687
+ return null;
2650
2688
  }
2651
2689
 
2652
- // ../../src/services/registry-broker/client/ledger-auth.ts
2653
- var import_buffer2 = require("buffer");
2654
-
2655
- // ../../src/services/registry-broker/ledger-network.ts
2656
- var normalise = (value) => value.trim().toLowerCase();
2657
- var HEDERA_NETWORK_ALIASES = /* @__PURE__ */ new Map([
2658
- ["hedera:mainnet", { canonical: "hedera:mainnet", hederaNetwork: "mainnet" }],
2659
- ["mainnet", { canonical: "hedera:mainnet", hederaNetwork: "mainnet" }],
2660
- ["hedera-mainnet", { canonical: "hedera:mainnet", hederaNetwork: "mainnet" }],
2661
- ["hedera_mainnet", { canonical: "hedera:mainnet", hederaNetwork: "mainnet" }],
2662
- ["hedera:testnet", { canonical: "hedera:testnet", hederaNetwork: "testnet" }],
2663
- ["testnet", { canonical: "hedera:testnet", hederaNetwork: "testnet" }],
2664
- ["hedera-testnet", { canonical: "hedera:testnet", hederaNetwork: "testnet" }],
2665
- ["hedera_testnet", { canonical: "hedera:testnet", hederaNetwork: "testnet" }]
2666
- ]);
2667
- var EVM_NETWORK_CHAIN_IDS = {
2668
- abstract: 2741,
2669
- "abstract-testnet": 11124,
2670
- base: 8453,
2671
- "base-sepolia": 84532,
2672
- avalanche: 43114,
2673
- "avalanche-fuji": 43113,
2674
- iotex: 4689,
2675
- sei: 1329,
2676
- "sei-testnet": 1328,
2677
- polygon: 137,
2678
- "polygon-amoy": 80002,
2679
- peaq: 3338
2680
- };
2681
- var CHAIN_ID_TO_ALIAS = new Map(
2682
- Object.entries(EVM_NETWORK_CHAIN_IDS).map(([alias, id]) => [id, alias])
2683
- );
2684
- var parseChainId = (value) => {
2685
- if (/^eip155:\d+$/i.test(value)) {
2686
- return Number.parseInt(value.split(":")[1], 10);
2687
- }
2688
- if (/^\d+$/.test(value)) {
2689
- return Number.parseInt(value, 10);
2690
+ // ../../src/services/registry-broker/client/encryption.ts
2691
+ var getFs = async () => {
2692
+ const fsModule = await optionalImport("node:fs") ?? await optionalImport("fs");
2693
+ if (fsModule && typeof fsModule.existsSync === "function" && typeof fsModule.readFileSync === "function" && typeof fsModule.writeFileSync === "function" && typeof fsModule.appendFileSync === "function") {
2694
+ return fsModule;
2690
2695
  }
2691
- return void 0;
2696
+ return null;
2692
2697
  };
2693
- var normaliseEvmNetwork = (value) => {
2694
- const trimmed = normalise(value);
2695
- let chainId = parseChainId(trimmed);
2696
- let alias;
2697
- if (chainId === void 0) {
2698
- const mapped = EVM_NETWORK_CHAIN_IDS[trimmed];
2699
- if (mapped !== void 0) {
2700
- chainId = mapped;
2701
- alias = trimmed;
2702
- }
2703
- } else if (CHAIN_ID_TO_ALIAS.has(chainId)) {
2704
- alias = CHAIN_ID_TO_ALIAS.get(chainId);
2698
+ var getNodePath = async () => {
2699
+ const pathModule = await optionalImport("node:path") ?? await optionalImport("path");
2700
+ if (pathModule && typeof pathModule.resolve === "function") {
2701
+ return pathModule;
2705
2702
  }
2706
- if (chainId === void 0) {
2707
- throw new Error(
2708
- 'Unsupported EVM ledger network. Provide an alias like "base-sepolia" or a canonical eip155:<chainId> string.'
2709
- );
2703
+ return null;
2704
+ };
2705
+ var getNodeCrypto = async () => {
2706
+ const cryptoModule = await optionalImport("node:crypto") ?? await optionalImport("crypto");
2707
+ if (cryptoModule && typeof cryptoModule.randomBytes === "function") {
2708
+ return cryptoModule;
2710
2709
  }
2711
- return {
2712
- canonical: `eip155:${chainId}`,
2713
- kind: "evm",
2714
- chainId,
2715
- legacyName: alias
2716
- };
2710
+ return null;
2717
2711
  };
2718
- var normaliseHederaNetwork = (value) => {
2719
- const trimmed = normalise(value);
2720
- const mapping = HEDERA_NETWORK_ALIASES.get(trimmed);
2721
- if (!mapping) {
2722
- throw new Error(
2723
- 'Unsupported Hedera network. Use hedera:mainnet or hedera:testnet (legacy "mainnet"/"testnet" also accepted).'
2724
- );
2712
+ async function registerEncryptionKey(client, payload) {
2713
+ const raw = await client.requestJson("/encryption/keys", {
2714
+ method: "POST",
2715
+ headers: { "content-type": "application/json" },
2716
+ body: payload
2717
+ });
2718
+ return client.parseWithSchema(
2719
+ raw,
2720
+ registerEncryptionKeyResponseSchema,
2721
+ "register encryption key response"
2722
+ );
2723
+ }
2724
+ function normalizeAutoRegisterIdentity(config) {
2725
+ const identity = {};
2726
+ if (config.uaid) {
2727
+ identity.uaid = config.uaid;
2725
2728
  }
2726
- return {
2727
- canonical: mapping.canonical,
2728
- kind: "hedera",
2729
- hederaNetwork: mapping.hederaNetwork
2730
- };
2731
- };
2732
- var canonicalizeLedgerNetwork = (network) => {
2733
- if (typeof network !== "string" || network.trim().length === 0) {
2734
- throw new Error("Ledger network is required.");
2729
+ if (config.ledgerAccountId) {
2730
+ identity.ledgerAccountId = config.ledgerAccountId;
2731
+ if (config.ledgerNetwork) {
2732
+ identity.ledgerNetwork = config.ledgerNetwork;
2733
+ }
2735
2734
  }
2736
- const trimmed = normalise(network);
2737
- if (trimmed.startsWith("hedera:") || trimmed.includes("hedera-") || trimmed.includes("hedera_") || trimmed === "mainnet" || trimmed === "testnet") {
2738
- return normaliseHederaNetwork(trimmed);
2735
+ if (config.email) {
2736
+ identity.email = config.email;
2739
2737
  }
2740
- return normaliseEvmNetwork(trimmed);
2741
- };
2742
-
2743
- // ../../src/services/registry-broker/private-key-signer.ts
2744
- var unsupported = (method) => new Error(`${method} is not supported by the in-memory signer`);
2745
- var cachedSdk = null;
2746
- var loadHashgraphSdk = () => {
2747
- if (cachedSdk) {
2748
- return cachedSdk;
2738
+ if (identity.uaid || identity.ledgerAccountId || identity.email) {
2739
+ return identity;
2749
2740
  }
2750
- const resolved = optionalImportSync("@hashgraph/sdk");
2751
- if (resolved) {
2752
- cachedSdk = resolved;
2753
- return resolved;
2741
+ return null;
2742
+ }
2743
+ function derivePublicKeyFromPrivateKey(client, privateKey) {
2744
+ const normalized = client.hexToBuffer(privateKey);
2745
+ const publicKey = import_secp256k1.secp256k1.getPublicKey(normalized, true);
2746
+ return import_buffer2.Buffer.from(publicKey).toString("hex");
2747
+ }
2748
+ async function resolveAutoRegisterKeyMaterial(client, config) {
2749
+ if (config.publicKey?.trim()) {
2750
+ return { publicKey: config.publicKey.trim() };
2754
2751
  }
2755
- const message = "@hashgraph/sdk is required for ledger signing. Install it as a dependency to enable createPrivateKeySigner.";
2756
- throw new Error(message);
2757
- };
2758
- var loadHashgraphSdkAsync = async () => {
2759
- if (cachedSdk) {
2760
- return cachedSdk;
2752
+ let privateKey = config.privateKey?.trim();
2753
+ const envVar = config.envVar ?? "RB_ENCRYPTION_PRIVATE_KEY";
2754
+ if (!privateKey && envVar && process?.env?.[envVar]?.trim()) {
2755
+ privateKey = process.env[envVar]?.trim();
2761
2756
  }
2762
- const resolved = await optionalImport("@hashgraph/sdk");
2763
- if (resolved) {
2764
- cachedSdk = resolved;
2765
- return resolved;
2757
+ if (!privateKey && config.generateIfMissing) {
2758
+ const pair = await client.generateEncryptionKeyPair({
2759
+ keyType: config.keyType ?? "secp256k1",
2760
+ envVar,
2761
+ envPath: config.envPath,
2762
+ overwrite: config.overwriteEnv
2763
+ });
2764
+ return { publicKey: pair.publicKey, privateKey: pair.privateKey };
2766
2765
  }
2767
- const message = "@hashgraph/sdk is required for ledger signing. Install it as a dependency to enable createPrivateKeySigner.";
2768
- throw new Error(message);
2769
- };
2770
- var buildSigner = (sdk, options) => {
2771
- const { AccountId, LedgerId, PrivateKey, SignerSignature } = sdk;
2772
- if (!options.privateKey) {
2773
- throw new Error("privateKey is required to create a ledger signer.");
2766
+ if (privateKey) {
2767
+ const publicKey = derivePublicKeyFromPrivateKey(client, privateKey);
2768
+ return { publicKey, privateKey };
2774
2769
  }
2775
- if (!options.accountId) {
2776
- throw new Error("accountId is required to create a ledger signer.");
2770
+ return null;
2771
+ }
2772
+ async function autoRegisterEncryptionKey(client, config) {
2773
+ const identity = normalizeAutoRegisterIdentity(config);
2774
+ if (!identity) {
2775
+ throw new Error(
2776
+ "Auto-registration requires uaid, ledgerAccountId, or email"
2777
+ );
2777
2778
  }
2778
- const accountId = AccountId.fromString(options.accountId);
2779
- const privateKey = PrivateKey.fromString(options.privateKey);
2780
- const ledgerId = LedgerId.fromString(options.network);
2779
+ const material = await resolveAutoRegisterKeyMaterial(client, config);
2780
+ if (!material) {
2781
+ throw new Error(
2782
+ "Unable to resolve encryption public key for auto-registration"
2783
+ );
2784
+ }
2785
+ await registerEncryptionKey(client, {
2786
+ keyType: config.keyType ?? "secp256k1",
2787
+ publicKey: material.publicKey,
2788
+ ...identity
2789
+ });
2790
+ return material;
2791
+ }
2792
+ async function ensureAgentEncryptionKey(client, options) {
2793
+ return autoRegisterEncryptionKey(client, {
2794
+ ...options,
2795
+ uaid: options.uaid,
2796
+ enabled: true
2797
+ });
2798
+ }
2799
+ function createEncryptionApi(client) {
2781
2800
  return {
2782
- getLedgerId: () => ledgerId,
2783
- getAccountId: () => accountId,
2784
- getAccountKey: () => privateKey.publicKey,
2785
- getNetwork: () => ({}),
2786
- getMirrorNetwork: () => [],
2787
- sign: async (messages) => Promise.all(
2788
- messages.map(async (message) => {
2789
- const signature = await privateKey.sign(message);
2790
- return new SignerSignature({
2791
- publicKey: privateKey.publicKey,
2792
- signature,
2793
- accountId
2794
- });
2795
- })
2796
- ),
2797
- getAccountBalance: async () => {
2798
- throw unsupported("getAccountBalance");
2799
- },
2800
- getAccountInfo: async () => {
2801
- throw unsupported("getAccountInfo");
2802
- },
2803
- getAccountRecords: async () => {
2804
- throw unsupported("getAccountRecords");
2805
- },
2806
- signTransaction: async (_) => {
2807
- throw unsupported("signTransaction");
2808
- },
2809
- checkTransaction: async (_) => {
2810
- throw unsupported("checkTransaction");
2811
- },
2812
- populateTransaction: async (_) => {
2813
- throw unsupported("populateTransaction");
2814
- },
2815
- call: async (_request) => {
2816
- throw unsupported("call");
2817
- }
2801
+ registerKey: (payload) => registerEncryptionKey(client, payload),
2802
+ generateEphemeralKeyPair: () => client.createEphemeralKeyPair(),
2803
+ deriveSharedSecret: (options) => client.deriveSharedSecret(options),
2804
+ encryptCipherEnvelope: (options) => client.buildCipherEnvelope(options),
2805
+ decryptCipherEnvelope: (options) => client.openCipherEnvelope(options),
2806
+ ensureAgentKey: (options) => ensureAgentEncryptionKey(client, options)
2818
2807
  };
2819
- };
2820
- var createPrivateKeySigner = (options) => buildSigner(loadHashgraphSdk(), options);
2821
- var createPrivateKeySignerAsync = async (options) => buildSigner(await loadHashgraphSdkAsync(), options);
2822
-
2823
- // ../../src/services/registry-broker/client/ledger-auth.ts
2824
- async function loadViemAccount(privateKey) {
2825
- try {
2826
- const viem = await import("viem/accounts");
2827
- return viem.privateKeyToAccount(privateKey);
2828
- } catch (error) {
2829
- const err = new Error(
2830
- 'EVM ledger authentication requires the optional dependency "viem". Install it to use evmPrivateKey flows.'
2831
- );
2832
- err.cause = error;
2833
- throw err;
2808
+ }
2809
+ async function bootstrapEncryptionOptions(client, options) {
2810
+ if (!options?.autoRegister || options.autoRegister.enabled === false) {
2811
+ return null;
2834
2812
  }
2813
+ return autoRegisterEncryptionKey(client, options.autoRegister);
2835
2814
  }
2836
- async function resolveLedgerAuthSignature(message, options) {
2837
- if (typeof options.sign === "function") {
2838
- const result = await options.sign(message);
2839
- if (!result || typeof result.signature !== "string" || result.signature.length === 0) {
2840
- throw new Error("Custom ledger signer failed to produce a signature.");
2841
- }
2842
- return result;
2815
+ async function generateEncryptionKeyPair(client, options = {}) {
2816
+ client.assertNodeRuntime("generateEncryptionKeyPair");
2817
+ const keyType = options.keyType ?? "secp256k1";
2818
+ if (keyType !== "secp256k1") {
2819
+ throw new Error("Only secp256k1 key generation is supported currently");
2843
2820
  }
2844
- if (!options.signer || typeof options.signer.sign !== "function") {
2821
+ const cryptoModule = await getNodeCrypto();
2822
+ if (!cryptoModule) {
2845
2823
  throw new Error(
2846
- "Ledger authentication requires a Hedera Signer or custom sign function."
2824
+ "Node.js crypto module is not available; cannot generate encryption key pair"
2847
2825
  );
2848
2826
  }
2849
- const payload = import_buffer2.Buffer.from(message, "utf8");
2850
- const signatures = await options.signer.sign([payload]);
2851
- const signatureEntry = signatures?.[0];
2852
- if (!signatureEntry) {
2853
- throw new Error("Signer did not return any signatures.");
2827
+ const privateKeyBytes = cryptoModule.randomBytes(32);
2828
+ const privateKey = import_buffer2.Buffer.from(privateKeyBytes).toString("hex");
2829
+ const publicKeyBytes = import_secp256k1.secp256k1.getPublicKey(privateKeyBytes, true);
2830
+ const publicKey = import_buffer2.Buffer.from(publicKeyBytes).toString("hex");
2831
+ const envVar = options.envVar ?? "RB_ENCRYPTION_PRIVATE_KEY";
2832
+ const pathModule = options.envPath ? await getNodePath() : null;
2833
+ const resolvedPath = options.envPath && pathModule ? pathModule.resolve(options.envPath) : void 0;
2834
+ if (options.envPath && !resolvedPath) {
2835
+ throw new Error(
2836
+ "Node.js path module is not available; cannot resolve encryption key env path"
2837
+ );
2854
2838
  }
2855
- let derivedPublicKey;
2856
- if (signatureEntry.publicKey) {
2857
- derivedPublicKey = signatureEntry.publicKey.toString();
2858
- } else if (typeof options.signer.getAccountKey === "function") {
2859
- const accountKey = await options.signer.getAccountKey();
2860
- if (accountKey && typeof accountKey.toString === "function") {
2861
- derivedPublicKey = accountKey.toString();
2839
+ if (resolvedPath) {
2840
+ const fsModule = await getFs();
2841
+ if (!fsModule) {
2842
+ throw new Error(
2843
+ "File system module is not available; cannot write encryption key env file"
2844
+ );
2845
+ }
2846
+ const envLine = `${envVar}=${privateKey}`;
2847
+ if (fsModule.existsSync(resolvedPath)) {
2848
+ const content = fsModule.readFileSync(resolvedPath, "utf-8");
2849
+ const lineRegex = new RegExp(`^${envVar}=.*$`, "m");
2850
+ if (lineRegex.test(content)) {
2851
+ if (!options.overwrite) {
2852
+ throw new Error(
2853
+ `${envVar} already exists in ${resolvedPath}; set overwrite=true to replace it`
2854
+ );
2855
+ }
2856
+ const updated = content.replace(lineRegex, envLine);
2857
+ fsModule.writeFileSync(resolvedPath, updated);
2858
+ } else {
2859
+ const needsNewline = !content.endsWith("\n");
2860
+ fsModule.appendFileSync(
2861
+ resolvedPath,
2862
+ `${needsNewline ? "\n" : ""}${envLine}
2863
+ `
2864
+ );
2865
+ }
2866
+ } else {
2867
+ fsModule.writeFileSync(resolvedPath, `${envLine}
2868
+ `);
2862
2869
  }
2863
2870
  }
2864
2871
  return {
2865
- signature: import_buffer2.Buffer.from(signatureEntry.signature).toString("base64"),
2866
- signatureKind: "raw",
2867
- publicKey: derivedPublicKey
2872
+ privateKey,
2873
+ publicKey,
2874
+ envPath: resolvedPath,
2875
+ envVar
2868
2876
  };
2869
2877
  }
2870
- async function createLedgerChallenge(client, payload) {
2871
- const resolvedNetwork = canonicalizeLedgerNetwork(payload.network);
2872
- const network = resolvedNetwork.kind === "hedera" ? resolvedNetwork.hederaNetwork ?? resolvedNetwork.canonical : resolvedNetwork.canonical;
2873
- const raw = await client.requestJson("/auth/ledger/challenge", {
2874
- method: "POST",
2875
- headers: { "content-type": "application/json" },
2876
- body: {
2877
- accountId: payload.accountId,
2878
- network
2878
+
2879
+ // ../../src/services/registry-broker/client/adapters.ts
2880
+ async function adapters(client) {
2881
+ const raw = await client.requestJson("/adapters", {
2882
+ method: "GET"
2883
+ });
2884
+ return client.parseWithSchema(
2885
+ raw,
2886
+ adaptersResponseSchema,
2887
+ "adapters response"
2888
+ );
2889
+ }
2890
+ async function adaptersDetailed(client) {
2891
+ const raw = await client.requestJson("/adapters/details", {
2892
+ method: "GET"
2893
+ });
2894
+ return client.parseWithSchema(
2895
+ raw,
2896
+ adapterDetailsResponseSchema,
2897
+ "adapter details response"
2898
+ );
2899
+ }
2900
+ async function adapterRegistryCategories(client) {
2901
+ const raw = await client.requestJson(
2902
+ "/adapters/registry/categories",
2903
+ {
2904
+ method: "GET"
2879
2905
  }
2880
- });
2906
+ );
2881
2907
  return client.parseWithSchema(
2882
2908
  raw,
2883
- ledgerChallengeResponseSchema,
2884
- "ledger challenge response"
2909
+ adapterRegistryCategoriesResponseSchema,
2910
+ "adapter registry categories response"
2885
2911
  );
2886
2912
  }
2887
- async function verifyLedgerChallenge(client, payload) {
2888
- const resolvedNetwork = canonicalizeLedgerNetwork(payload.network);
2889
- const network = resolvedNetwork.kind === "hedera" ? resolvedNetwork.hederaNetwork ?? resolvedNetwork.canonical : resolvedNetwork.canonical;
2890
- const body = {
2891
- challengeId: payload.challengeId,
2892
- accountId: payload.accountId,
2893
- network,
2894
- signature: payload.signature
2895
- };
2896
- if (payload.signatureKind) {
2897
- body.signatureKind = payload.signatureKind;
2913
+ async function adapterRegistryAdapters(client, filters = {}) {
2914
+ const params = new URLSearchParams();
2915
+ if (filters.category) {
2916
+ params.set("category", filters.category);
2898
2917
  }
2899
- if (payload.publicKey) {
2900
- body.publicKey = payload.publicKey;
2918
+ if (filters.entity) {
2919
+ params.set("entity", filters.entity);
2901
2920
  }
2902
- if (typeof payload.expiresInMinutes === "number") {
2903
- body.expiresInMinutes = payload.expiresInMinutes;
2921
+ if (filters.keywords?.length) {
2922
+ params.set("keywords", filters.keywords.join(","));
2904
2923
  }
2905
- const raw = await client.requestJson("/auth/ledger/verify", {
2906
- method: "POST",
2907
- headers: { "content-type": "application/json" },
2908
- body
2909
- });
2910
- const result = client.parseWithSchema(
2924
+ if (filters.query) {
2925
+ params.set("query", filters.query);
2926
+ }
2927
+ if (typeof filters.limit === "number") {
2928
+ params.set("limit", String(filters.limit));
2929
+ }
2930
+ if (typeof filters.offset === "number") {
2931
+ params.set("offset", String(filters.offset));
2932
+ }
2933
+ const suffix = params.size > 0 ? `?${params.toString()}` : "";
2934
+ const raw = await client.requestJson(
2935
+ `/adapters/registry/adapters${suffix}`,
2936
+ {
2937
+ method: "GET"
2938
+ }
2939
+ );
2940
+ return client.parseWithSchema(
2911
2941
  raw,
2912
- ledgerVerifyResponseSchema,
2913
- "ledger verification response"
2942
+ adapterRegistryAdaptersResponseSchema,
2943
+ "adapter registry adapters response"
2914
2944
  );
2915
- client.setLedgerApiKey(result.key);
2916
- return result;
2917
2945
  }
2918
- async function authenticateWithLedger(client, options) {
2919
- const challenge = await client.createLedgerChallenge({
2920
- accountId: options.accountId,
2921
- network: options.network
2922
- });
2923
- const signed = await resolveLedgerAuthSignature(challenge.message, options);
2924
- const verification = await client.verifyLedgerChallenge({
2925
- challengeId: challenge.challengeId,
2926
- accountId: options.accountId,
2927
- network: options.network,
2928
- signature: signed.signature,
2929
- signatureKind: signed.signatureKind,
2930
- publicKey: signed.publicKey,
2931
- expiresInMinutes: options.expiresInMinutes
2932
- });
2933
- return verification;
2946
+ async function createAdapterRegistryCategory(client, payload) {
2947
+ const raw = await client.requestJson(
2948
+ "/adapters/registry/categories",
2949
+ {
2950
+ method: "POST",
2951
+ headers: { "content-type": "application/json" },
2952
+ body: toJsonObject(payload)
2953
+ }
2954
+ );
2955
+ const parsed = client.parseWithSchema(
2956
+ raw,
2957
+ adapterRegistryCreateCategoryResponseSchema,
2958
+ "adapter registry create category response"
2959
+ );
2960
+ return parsed.category;
2934
2961
  }
2935
- async function authenticateWithLedgerCredentials(client, options) {
2936
- const {
2937
- accountId,
2938
- network,
2939
- signer,
2940
- sign,
2941
- hederaPrivateKey,
2942
- evmPrivateKey,
2943
- expiresInMinutes,
2944
- setAccountHeader = true,
2945
- label,
2946
- logger
2947
- } = options;
2948
- const resolvedNetwork = canonicalizeLedgerNetwork(network);
2949
- const labelSuffix = label ? ` for ${label}` : "";
2950
- const networkPayload = resolvedNetwork.canonical;
2951
- const authOptions = {
2952
- accountId,
2953
- network: networkPayload,
2954
- expiresInMinutes
2955
- };
2956
- if (sign) {
2957
- authOptions.sign = sign;
2958
- } else if (signer) {
2959
- authOptions.signer = signer;
2960
- } else if (hederaPrivateKey) {
2961
- if (resolvedNetwork.kind !== "hedera" || !resolvedNetwork.hederaNetwork) {
2962
- throw new Error(
2963
- "hederaPrivateKey can only be used with hedera:mainnet or hedera:testnet networks."
2964
- );
2962
+ async function submitAdapterRegistryAdapter(client, payload) {
2963
+ const raw = await client.requestJson(
2964
+ "/adapters/registry/adapters",
2965
+ {
2966
+ method: "POST",
2967
+ headers: { "content-type": "application/json" },
2968
+ body: toJsonObject(payload)
2965
2969
  }
2966
- authOptions.signer = await createPrivateKeySignerAsync({
2967
- accountId,
2968
- privateKey: hederaPrivateKey,
2969
- network: resolvedNetwork.hederaNetwork
2970
- });
2971
- } else if (evmPrivateKey) {
2972
- if (resolvedNetwork.kind !== "evm") {
2973
- throw new Error(
2974
- "evmPrivateKey can only be used with CAIP-2 EVM networks (eip155:<chainId>)."
2975
- );
2970
+ );
2971
+ return client.parseWithSchema(
2972
+ raw,
2973
+ adapterRegistrySubmitAdapterAcceptedResponseSchema,
2974
+ "adapter registry submit adapter response"
2975
+ );
2976
+ }
2977
+ async function adapterRegistrySubmissionStatus(client, submissionId) {
2978
+ const raw = await client.requestJson(
2979
+ `/adapters/registry/submissions/${encodeURIComponent(submissionId)}`,
2980
+ {
2981
+ method: "GET"
2976
2982
  }
2977
- const formattedKey = evmPrivateKey.startsWith("0x") ? evmPrivateKey : `0x${evmPrivateKey}`;
2978
- const account = await loadViemAccount(formattedKey);
2979
- authOptions.sign = async (message) => ({
2980
- signature: await account.signMessage({ message }),
2981
- signatureKind: "evm",
2982
- publicKey: account.publicKey
2983
- });
2984
- } else {
2985
- throw new Error(
2986
- "Provide a signer, sign function, hederaPrivateKey, or evmPrivateKey to authenticate with the ledger."
2987
- );
2988
- }
2989
- logger?.info?.(
2990
- `Authenticating ledger account ${accountId} (${resolvedNetwork.canonical})${labelSuffix}...`
2991
2983
  );
2992
- const verification = await client.authenticateWithLedger(authOptions);
2993
- if (setAccountHeader) {
2994
- client.setDefaultHeader("x-account-id", verification.accountId);
2995
- }
2996
- logger?.info?.(
2997
- `Ledger authentication complete${labelSuffix}. Issued key prefix: ${verification.apiKey.prefix}\u2026${verification.apiKey.lastFour}`
2984
+ return client.parseWithSchema(
2985
+ raw,
2986
+ adapterRegistrySubmissionStatusResponseSchema,
2987
+ "adapter registry submission status response"
2998
2988
  );
2999
- return verification;
3000
2989
  }
3001
2990
 
3002
- // ../../src/services/registry-broker/client/chat-history.ts
3003
- var import_buffer3 = require("buffer");
3004
- function identitiesMatch(a, b) {
3005
- if (!a && !b) {
3006
- return true;
3007
- }
3008
- if (!a || !b) {
3009
- return false;
3010
- }
3011
- if (a.uaid && b.uaid && a.uaid.toLowerCase() === b.uaid.toLowerCase()) {
3012
- return true;
2991
+ // ../../src/services/registry-broker/client/credits.ts
2992
+ async function loadX402Dependencies(client) {
2993
+ const [{ default: axios }, x402Axios, x402Types] = await Promise.all([
2994
+ import("axios"),
2995
+ optionalImport("x402-axios"),
2996
+ optionalImport("x402/types")
2997
+ ]);
2998
+ if (!x402Axios || !x402Types) {
2999
+ throw new Error(
3000
+ "x402-axios and x402/types are required for X402 flows. Install them to enable ledger payments."
3001
+ );
3013
3002
  }
3014
- if (a.ledgerAccountId && b.ledgerAccountId && a.ledgerAccountId.toLowerCase() === b.ledgerAccountId.toLowerCase()) {
3015
- return true;
3003
+ const withPaymentInterceptor = x402Axios.withPaymentInterceptor;
3004
+ const decodePaymentResponse = x402Axios.decodeXPaymentResponse;
3005
+ const createX402Signer = x402Types.createSigner;
3006
+ const createPaymentClient = (walletClient) => {
3007
+ const axiosClient = axios.create({
3008
+ baseURL: client.baseUrl,
3009
+ headers: {
3010
+ ...client.getDefaultHeaders(),
3011
+ "content-type": "application/json"
3012
+ }
3013
+ });
3014
+ const paymentClient = withPaymentInterceptor(axiosClient, walletClient);
3015
+ return paymentClient;
3016
+ };
3017
+ return { createPaymentClient, decodePaymentResponse, createX402Signer };
3018
+ }
3019
+ function calculateHbarAmountParam(hbarAmount) {
3020
+ const tinybars = Math.ceil(hbarAmount * 1e8);
3021
+ if (tinybars <= 0) {
3022
+ throw new Error("Calculated purchase amount must be positive");
3016
3023
  }
3017
- if (a.userId && b.userId && a.userId === b.userId) {
3018
- return true;
3024
+ return tinybars / 1e8;
3025
+ }
3026
+ async function purchaseCreditsWithHbar(client, params) {
3027
+ const body = {
3028
+ accountId: params.accountId,
3029
+ payerKey: params.privateKey,
3030
+ hbarAmount: calculateHbarAmountParam(params.hbarAmount)
3031
+ };
3032
+ if (params.memo) {
3033
+ body.memo = params.memo;
3019
3034
  }
3020
- if (a.email && b.email && a.email.toLowerCase() === b.email.toLowerCase()) {
3021
- return true;
3035
+ if (params.metadata) {
3036
+ body.metadata = params.metadata;
3022
3037
  }
3023
- return false;
3038
+ const raw = await client.requestJson("/credits/purchase", {
3039
+ method: "POST",
3040
+ headers: { "content-type": "application/json" },
3041
+ body
3042
+ });
3043
+ return client.parseWithSchema(
3044
+ raw,
3045
+ creditPurchaseResponseSchema,
3046
+ "credit purchase response"
3047
+ );
3024
3048
  }
3025
- async function fetchHistorySnapshot(conversationContexts, client, sessionId, options) {
3026
- if (!sessionId || sessionId.trim().length === 0) {
3027
- throw new Error("sessionId is required to fetch chat history");
3028
- }
3049
+ async function getX402Minimums(client) {
3029
3050
  const raw = await client.requestJson(
3030
- `/chat/session/${encodeURIComponent(sessionId)}/history`,
3031
- {
3032
- method: "GET"
3033
- }
3051
+ "/credits/purchase/x402/minimums",
3052
+ { method: "GET" }
3034
3053
  );
3035
- const snapshot = client.parseWithSchema(
3054
+ return client.parseWithSchema(
3036
3055
  raw,
3037
- chatHistorySnapshotResponseSchema,
3038
- "chat history snapshot response"
3039
- );
3040
- return attachDecryptedHistory(
3041
- conversationContexts,
3042
- client,
3043
- sessionId,
3044
- snapshot,
3045
- options
3056
+ x402MinimumsResponseSchema,
3057
+ "x402 minimums response"
3046
3058
  );
3047
3059
  }
3048
- function attachDecryptedHistory(conversationContexts, client, sessionId, snapshot, options) {
3049
- const shouldDecrypt = options?.decrypt !== void 0 ? options.decrypt : client.encryptionOptions?.autoDecryptHistory === true;
3050
- if (!shouldDecrypt) {
3051
- return snapshot;
3052
- }
3053
- const requiresContext = snapshot.history.some(
3054
- (entry) => Boolean(entry.cipherEnvelope)
3055
- );
3056
- if (!requiresContext) {
3057
- return {
3058
- ...snapshot,
3059
- decryptedHistory: snapshot.history.map((entry) => ({
3060
- entry,
3061
- plaintext: entry.content
3062
- }))
3063
- };
3060
+ async function purchaseCreditsWithX402(client, params) {
3061
+ const { createPaymentClient, decodePaymentResponse } = await loadX402Dependencies(client);
3062
+ if (!Number.isFinite(params.credits) || params.credits <= 0) {
3063
+ throw new Error("credits must be a positive number");
3064
3064
  }
3065
- const context = resolveDecryptionContext(
3066
- conversationContexts,
3067
- client,
3068
- sessionId,
3069
- options
3070
- );
3071
- if (!context) {
3072
- throw new Error(
3073
- "Unable to decrypt chat history: encryption context unavailable"
3074
- );
3065
+ if (params.usdAmount !== void 0 && (!Number.isFinite(params.usdAmount) || params.usdAmount <= 0)) {
3066
+ throw new Error("usdAmount must be a positive number when provided");
3075
3067
  }
3076
- const decryptedHistory = snapshot.history.map((entry) => ({
3077
- entry,
3078
- plaintext: decryptHistoryEntryFromContext(client, entry, context)
3079
- }));
3080
- return { ...snapshot, decryptedHistory };
3081
- }
3082
- function registerConversationContextForEncryption(conversationContexts, context) {
3083
- const normalized = {
3084
- sessionId: context.sessionId,
3085
- sharedSecret: import_buffer3.Buffer.from(context.sharedSecret),
3086
- identity: context.identity ? { ...context.identity } : void 0
3068
+ const body = {
3069
+ accountId: params.accountId,
3070
+ credits: params.credits
3087
3071
  };
3088
- const entries = conversationContexts.get(context.sessionId) ?? [];
3089
- const existingIndex = entries.findIndex(
3090
- (existing) => identitiesMatch(existing.identity, normalized.identity)
3091
- );
3092
- if (existingIndex >= 0) {
3093
- entries[existingIndex] = normalized;
3094
- } else {
3095
- entries.push(normalized);
3096
- }
3097
- conversationContexts.set(context.sessionId, entries);
3098
- }
3099
- function resolveDecryptionContext(conversationContexts, client, sessionId, options) {
3100
- if (options?.sharedSecret) {
3101
- return {
3102
- sessionId,
3103
- sharedSecret: client.normalizeSharedSecret(options.sharedSecret),
3104
- identity: options.identity
3105
- };
3072
+ if (params.usdAmount !== void 0) {
3073
+ body.usdAmount = params.usdAmount;
3106
3074
  }
3107
- const contexts = conversationContexts.get(sessionId);
3108
- if (!contexts || contexts.length === 0) {
3109
- return null;
3075
+ if (params.description) {
3076
+ body.description = params.description;
3110
3077
  }
3111
- if (options?.identity) {
3112
- const match = contexts.find(
3113
- (context) => identitiesMatch(context.identity, options.identity)
3114
- );
3115
- if (match) {
3116
- return match;
3117
- }
3078
+ if (params.metadata) {
3079
+ body.metadata = params.metadata;
3118
3080
  }
3119
- return contexts[0];
3081
+ const paymentClient = createPaymentClient(params.walletClient);
3082
+ const response = await paymentClient.post("/credits/purchase/x402", body);
3083
+ const parsed = client.parseWithSchema(
3084
+ response.data,
3085
+ x402CreditPurchaseResponseSchema,
3086
+ "x402 credit purchase response"
3087
+ );
3088
+ const responseHeaders = response.headers ?? {};
3089
+ const paymentHeader = typeof responseHeaders["x-payment-response"] === "string" ? responseHeaders["x-payment-response"] : void 0;
3090
+ const decodedPayment = paymentHeader !== void 0 ? decodePaymentResponse(paymentHeader) : void 0;
3091
+ return {
3092
+ ...parsed,
3093
+ paymentResponseHeader: paymentHeader,
3094
+ paymentResponse: decodedPayment
3095
+ };
3120
3096
  }
3121
- function decryptHistoryEntryFromContext(client, entry, context) {
3122
- const envelope = entry.cipherEnvelope;
3123
- if (!envelope) {
3124
- return entry.content;
3125
- }
3126
- const secret = import_buffer3.Buffer.from(context.sharedSecret);
3127
- try {
3128
- return client.encryption.decryptCipherEnvelope({
3129
- envelope,
3130
- sharedSecret: secret
3131
- });
3132
- } catch (_error) {
3133
- return null;
3134
- }
3097
+ async function buyCreditsWithX402(client, params) {
3098
+ const network = params.network ?? "base";
3099
+ const { createX402Signer } = await loadX402Dependencies(client);
3100
+ const normalizedKey = normalizeHexPrivateKey(params.evmPrivateKey);
3101
+ const walletClient = await createX402Signer(network, normalizedKey);
3102
+ return purchaseCreditsWithX402(client, {
3103
+ accountId: params.accountId,
3104
+ credits: params.credits,
3105
+ usdAmount: params.usdAmount,
3106
+ description: params.description,
3107
+ metadata: params.metadata,
3108
+ walletClient
3109
+ });
3135
3110
  }
3136
3111
 
3137
- // ../../src/services/registry-broker/client/encrypted-chat-manager.ts
3138
- var EncryptionUnavailableError = class extends Error {
3139
- constructor(sessionId, summary) {
3140
- super("Encryption is not enabled for this session");
3141
- this.sessionId = sessionId;
3142
- this.summary = summary;
3112
+ // ../../src/services/registry-broker/client/errors.ts
3113
+ var RegistryBrokerError = class extends Error {
3114
+ constructor(message, details) {
3115
+ super(message);
3116
+ this.status = details.status;
3117
+ this.statusText = details.statusText;
3118
+ this.body = details.body;
3143
3119
  }
3144
3120
  };
3145
- var EncryptedChatManager = class {
3146
- constructor(client) {
3147
- this.client = client;
3121
+ var RegistryBrokerParseError = class extends Error {
3122
+ constructor(message, cause, rawValue) {
3123
+ super(message);
3124
+ this.cause = cause;
3125
+ this.rawValue = rawValue;
3148
3126
  }
3149
- registerConversationContext(context) {
3150
- this.client.registerConversationContextForEncryption(context);
3127
+ };
3128
+
3129
+ // ../../src/services/registry-broker/client/agents.ts
3130
+ async function performRegisterAgent(client, payload) {
3131
+ const raw = await client.requestJson("/register", {
3132
+ method: "POST",
3133
+ body: serialiseAgentRegistrationRequest(payload),
3134
+ headers: { "content-type": "application/json" }
3135
+ });
3136
+ return client.parseWithSchema(
3137
+ raw,
3138
+ registerAgentResponseSchema,
3139
+ "register agent response"
3140
+ );
3141
+ }
3142
+ function calculateHbarAmount(creditsToPurchase, creditsPerHbar) {
3143
+ if (creditsPerHbar <= 0) {
3144
+ throw new Error("creditsPerHbar must be positive");
3151
3145
  }
3152
- async startSession(options) {
3153
- await this.client.encryptionReady();
3154
- const session = await this.client.chat.createSession({
3155
- uaid: options.uaid,
3156
- senderUaid: options.senderUaid,
3157
- encryptionRequested: true,
3158
- historyTtlSeconds: options.historyTtlSeconds,
3159
- auth: options.auth
3160
- });
3161
- options.onSessionCreated?.(session.sessionId);
3162
- const summary = session.encryption;
3163
- if (!summary?.enabled) {
3164
- throw new EncryptionUnavailableError(
3165
- session.sessionId,
3166
- session.encryption ?? null
3167
- );
3168
- }
3169
- const handle = await this.establishRequesterContext({
3170
- sessionId: session.sessionId,
3171
- summary,
3172
- senderUaid: options.senderUaid,
3173
- handshakeTimeoutMs: options.handshakeTimeoutMs,
3174
- pollIntervalMs: options.pollIntervalMs
3175
- });
3176
- return handle;
3146
+ if (creditsToPurchase <= 0) {
3147
+ throw new Error("creditsToPurchase must be positive");
3177
3148
  }
3178
- async acceptSession(options) {
3179
- await this.client.encryptionReady();
3180
- const summary = await this.waitForEncryptionSummary(
3181
- options.sessionId,
3182
- options.handshakeTimeoutMs,
3183
- options.pollIntervalMs
3184
- );
3185
- const handle = await this.establishResponderContext({
3186
- sessionId: options.sessionId,
3187
- summary,
3188
- responderUaid: options.responderUaid,
3189
- handshakeTimeoutMs: options.handshakeTimeoutMs,
3190
- pollIntervalMs: options.pollIntervalMs
3191
- });
3192
- return handle;
3149
+ const rawHbar = creditsToPurchase / creditsPerHbar;
3150
+ const tinybars = Math.ceil(rawHbar * 1e8);
3151
+ return tinybars / 1e8;
3152
+ }
3153
+ function resolveCreditsToPurchase(shortfallCredits) {
3154
+ if (!Number.isFinite(shortfallCredits) || shortfallCredits <= 0) {
3155
+ return 0;
3193
3156
  }
3194
- async establishRequesterContext(params) {
3195
- const keyPair = this.client.encryption.generateEphemeralKeyPair();
3196
- await this.client.chat.submitEncryptionHandshake(params.sessionId, {
3197
- role: "requester",
3198
- keyType: "secp256k1",
3199
- ephemeralPublicKey: keyPair.publicKey,
3200
- uaid: params.senderUaid ?? params.summary.requester?.uaid ?? void 0
3201
- });
3202
- const { summary, record } = await this.waitForHandshakeCompletion(
3203
- params.sessionId,
3204
- params.handshakeTimeoutMs,
3205
- params.pollIntervalMs
3206
- );
3207
- const responderKey = record.responder?.ephemeralPublicKey;
3208
- if (!responderKey) {
3209
- throw new Error("Responder handshake was not completed in time");
3210
- }
3211
- const sharedSecret = this.client.encryption.deriveSharedSecret({
3212
- privateKey: keyPair.privateKey,
3213
- peerPublicKey: responderKey
3214
- }).subarray();
3215
- const recipients = this.buildRecipients(summary);
3216
- return this.createHandle({
3217
- sessionId: params.sessionId,
3218
- sharedSecret,
3219
- summary,
3220
- recipients,
3221
- identity: summary.requester ?? void 0
3222
- });
3157
+ return Math.max(
3158
+ Math.ceil(shortfallCredits),
3159
+ MINIMUM_REGISTRATION_AUTO_TOP_UP_CREDITS
3160
+ );
3161
+ }
3162
+ async function ensureCreditsForRegistration(client, payload, autoTopUp) {
3163
+ const details = autoTopUp ?? null;
3164
+ if (!details) {
3165
+ return;
3223
3166
  }
3224
- async establishResponderContext(params) {
3225
- const keyPair = this.client.encryption.generateEphemeralKeyPair();
3226
- await this.client.chat.submitEncryptionHandshake(params.sessionId, {
3227
- role: "responder",
3228
- keyType: "secp256k1",
3229
- ephemeralPublicKey: keyPair.publicKey,
3230
- uaid: params.responderUaid ?? params.summary.responder?.uaid ?? void 0
3231
- });
3232
- const { summary, record } = await this.waitForHandshakeCompletion(
3233
- params.sessionId,
3234
- params.handshakeTimeoutMs,
3235
- params.pollIntervalMs
3236
- );
3237
- const requesterKey = record.requester?.ephemeralPublicKey;
3238
- if (!requesterKey) {
3239
- throw new Error("Requester handshake was not detected in time");
3167
+ if (!details.accountId || !details.accountId.trim()) {
3168
+ throw new Error("autoTopUp.accountId is required");
3169
+ }
3170
+ if (!details.privateKey || !details.privateKey.trim()) {
3171
+ throw new Error("autoTopUp.privateKey is required");
3172
+ }
3173
+ for (let attempt = 0; attempt < 3; attempt += 1) {
3174
+ const quote = await getRegistrationQuote(client, payload);
3175
+ const shortfall = quote.shortfallCredits ?? 0;
3176
+ if (shortfall <= 0) {
3177
+ return;
3240
3178
  }
3241
- const sharedSecret = this.client.encryption.deriveSharedSecret({
3242
- privateKey: keyPair.privateKey,
3243
- peerPublicKey: requesterKey
3244
- }).subarray();
3245
- const recipients = this.buildRecipients(summary);
3246
- return this.createHandle({
3247
- sessionId: params.sessionId,
3248
- sharedSecret,
3249
- summary,
3250
- recipients,
3251
- identity: summary.responder ?? void 0
3179
+ const creditsToPurchase = resolveCreditsToPurchase(shortfall);
3180
+ if (creditsToPurchase <= 0) {
3181
+ return;
3182
+ }
3183
+ const creditsPerHbar = quote.creditsPerHbar ?? null;
3184
+ if (!creditsPerHbar || creditsPerHbar <= 0) {
3185
+ throw new Error("Unable to determine credits per HBAR for auto top-up");
3186
+ }
3187
+ const hbarAmount = calculateHbarAmount(creditsToPurchase, creditsPerHbar);
3188
+ await purchaseCreditsWithHbar(client, {
3189
+ accountId: details.accountId.trim(),
3190
+ privateKey: details.privateKey.trim(),
3191
+ hbarAmount,
3192
+ memo: details.memo ?? "Registry Broker auto top-up",
3193
+ metadata: {
3194
+ shortfallCredits: shortfall,
3195
+ requiredCredits: quote.requiredCredits,
3196
+ purchasedCredits: creditsToPurchase
3197
+ }
3252
3198
  });
3253
3199
  }
3254
- async waitForHandshakeCompletion(sessionId, timeoutMs = 3e4, pollIntervalMs = 1e3) {
3255
- const deadline = Date.now() + timeoutMs;
3256
- while (true) {
3257
- const status = await this.client.chat.getEncryptionStatus(sessionId);
3258
- const summary = status.encryption;
3259
- const record = summary?.handshake;
3260
- if (summary && record && record.status === "complete") {
3261
- return { summary, record };
3262
- }
3263
- if (Date.now() >= deadline) {
3264
- throw new Error("Timed out waiting for encrypted handshake completion");
3200
+ const finalQuote = await getRegistrationQuote(client, payload);
3201
+ if ((finalQuote.shortfallCredits ?? 0) > 0) {
3202
+ throw new Error("Unable to purchase sufficient credits for registration");
3203
+ }
3204
+ }
3205
+ async function resolveUaid(client, uaid) {
3206
+ const raw = await client.requestJson(
3207
+ `/resolve/${encodeURIComponent(uaid)}`,
3208
+ {
3209
+ method: "GET"
3210
+ }
3211
+ );
3212
+ return client.parseWithSchema(
3213
+ raw,
3214
+ resolveResponseSchema,
3215
+ "resolve UAID response"
3216
+ );
3217
+ }
3218
+ async function registerAgent(client, payload, options) {
3219
+ const autoTopUp = options?.autoTopUp ?? client.registrationAutoTopUp;
3220
+ if (!autoTopUp) {
3221
+ return performRegisterAgent(client, payload);
3222
+ }
3223
+ await ensureCreditsForRegistration(client, payload, autoTopUp);
3224
+ let retried = false;
3225
+ while (true) {
3226
+ try {
3227
+ return await performRegisterAgent(client, payload);
3228
+ } catch (error) {
3229
+ const shortfall = client.extractInsufficientCreditsDetails(error);
3230
+ if (shortfall && !retried) {
3231
+ await ensureCreditsForRegistration(client, payload, autoTopUp);
3232
+ retried = true;
3233
+ continue;
3265
3234
  }
3266
- await this.delay(pollIntervalMs);
3235
+ throw error;
3267
3236
  }
3268
3237
  }
3269
- async waitForEncryptionSummary(sessionId, _timeoutMs = 3e4, _pollIntervalMs = 1e3) {
3270
- const status = await this.client.chat.getEncryptionStatus(sessionId);
3271
- if (!status.encryption?.enabled) {
3272
- throw new EncryptionUnavailableError(
3273
- sessionId,
3274
- status.encryption ?? null
3275
- );
3238
+ }
3239
+ async function getRegistrationQuote(client, payload) {
3240
+ const raw = await client.requestJson("/register/quote", {
3241
+ method: "POST",
3242
+ body: serialiseAgentRegistrationRequest(payload),
3243
+ headers: { "content-type": "application/json" }
3244
+ });
3245
+ return client.parseWithSchema(
3246
+ raw,
3247
+ registrationQuoteResponseSchema,
3248
+ "registration quote response"
3249
+ );
3250
+ }
3251
+ async function updateAgent(client, uaid, payload) {
3252
+ const raw = await client.requestJson(
3253
+ `/register/${encodeURIComponent(uaid)}`,
3254
+ {
3255
+ method: "PUT",
3256
+ body: serialiseAgentRegistrationRequest(payload),
3257
+ headers: { "content-type": "application/json" }
3276
3258
  }
3277
- return status.encryption;
3259
+ );
3260
+ return client.parseWithSchema(
3261
+ raw,
3262
+ registerAgentResponseSchema,
3263
+ "update agent response"
3264
+ );
3265
+ }
3266
+ async function getRegistrationProgress(client, attemptId) {
3267
+ const normalisedAttemptId = attemptId.trim();
3268
+ if (!normalisedAttemptId) {
3269
+ throw new Error("attemptId is required");
3278
3270
  }
3279
- buildRecipients(summary) {
3280
- const candidates = [summary.requester, summary.responder].filter(Boolean);
3281
- const normalized = candidates.map((candidate) => {
3282
- if (!candidate) {
3283
- return null;
3284
- }
3285
- const recipient = {};
3286
- if (candidate.uaid) {
3287
- recipient.uaid = candidate.uaid;
3288
- }
3289
- if (candidate.ledgerAccountId) {
3290
- recipient.ledgerAccountId = candidate.ledgerAccountId;
3291
- }
3292
- if (candidate.userId) {
3293
- recipient.userId = candidate.userId;
3294
- }
3295
- if (candidate.email) {
3296
- recipient.email = candidate.email;
3297
- }
3298
- return recipient;
3299
- }).filter(
3300
- (entry) => Boolean(
3301
- entry?.uaid || entry?.ledgerAccountId || entry?.userId || entry?.email
3302
- )
3271
+ try {
3272
+ const raw = await client.requestJson(
3273
+ `/register/progress/${encodeURIComponent(normalisedAttemptId)}`,
3274
+ { method: "GET" }
3303
3275
  );
3304
- if (normalized.length > 0) {
3305
- return normalized;
3306
- }
3307
- if (summary.responder?.uaid) {
3308
- return [{ uaid: summary.responder.uaid }];
3276
+ const parsed = client.parseWithSchema(
3277
+ raw,
3278
+ registrationProgressResponseSchema,
3279
+ "registration progress response"
3280
+ );
3281
+ return parsed.progress;
3282
+ } catch (error) {
3283
+ if (error instanceof RegistryBrokerError && error.status === 404) {
3284
+ return null;
3309
3285
  }
3310
- return [];
3286
+ throw error;
3311
3287
  }
3312
- createHandle(context) {
3313
- const sharedSecret = context.sharedSecret;
3314
- const uaid = context.summary.requester?.uaid ?? context.summary.responder?.uaid ?? context.identity?.uaid;
3315
- const decryptHistoryEntry = (entry) => this.decryptEntry(entry, context.identity, sharedSecret);
3316
- const fetchHistory = async (options) => {
3317
- const snapshot = await this.client.fetchHistorySnapshot(
3318
- context.sessionId,
3319
- options
3320
- );
3321
- if (snapshot.decryptedHistory) {
3322
- return snapshot.decryptedHistory;
3323
- }
3324
- return snapshot.history.map((entry) => ({
3325
- entry,
3326
- plaintext: decryptHistoryEntry(entry)
3327
- }));
3328
- };
3329
- const handle = {
3330
- sessionId: context.sessionId,
3331
- mode: "encrypted",
3332
- summary: context.summary,
3333
- send: async (options) => {
3334
- const recipients = options.recipients ?? context.recipients;
3335
- return this.client.chat.sendMessage({
3336
- sessionId: context.sessionId,
3337
- message: options.message ?? "[ciphertext omitted]",
3338
- streaming: options.streaming,
3339
- auth: options.auth,
3340
- uaid,
3341
- encryption: {
3342
- plaintext: options.plaintext,
3343
- sharedSecret: Buffer.from(sharedSecret),
3344
- recipients
3345
- }
3346
- });
3347
- },
3348
- decryptHistoryEntry,
3349
- fetchHistory
3350
- };
3351
- this.registerConversationContext({
3352
- sessionId: context.sessionId,
3353
- sharedSecret,
3354
- identity: context.identity
3355
- });
3356
- return handle;
3288
+ }
3289
+ async function waitForRegistrationCompletion(client, attemptId, options = {}) {
3290
+ const normalisedAttemptId = attemptId.trim();
3291
+ if (!normalisedAttemptId) {
3292
+ throw new Error("attemptId is required");
3357
3293
  }
3358
- decryptEntry(entry, identity, fallbackSecret) {
3359
- const envelope = entry.cipherEnvelope;
3360
- if (!envelope) {
3361
- return null;
3294
+ const interval = Math.max(
3295
+ 250,
3296
+ options.intervalMs ?? DEFAULT_PROGRESS_INTERVAL_MS
3297
+ );
3298
+ const timeoutMs = options.timeoutMs ?? DEFAULT_PROGRESS_TIMEOUT_MS;
3299
+ const throwOnFailure = options.throwOnFailure ?? true;
3300
+ const signal = options.signal;
3301
+ const startedAt = Date.now();
3302
+ while (true) {
3303
+ if (signal?.aborted) {
3304
+ throw createAbortError();
3362
3305
  }
3363
- const secret = Buffer.from(fallbackSecret);
3364
- try {
3365
- return this.client.encryption.decryptCipherEnvelope({
3366
- envelope,
3367
- sharedSecret: secret
3368
- });
3369
- } catch (_error) {
3370
- return null;
3306
+ const progress = await client.getRegistrationProgress(normalisedAttemptId);
3307
+ if (progress) {
3308
+ options.onProgress?.(progress);
3309
+ if (progress.status === "completed") {
3310
+ return progress;
3311
+ }
3312
+ if (progress.status === "partial" || progress.status === "failed") {
3313
+ if (throwOnFailure) {
3314
+ throw new RegistryBrokerError(
3315
+ "Registration did not complete successfully",
3316
+ {
3317
+ status: 409,
3318
+ statusText: progress.status,
3319
+ body: progress
3320
+ }
3321
+ );
3322
+ }
3323
+ return progress;
3324
+ }
3325
+ }
3326
+ if (Date.now() - startedAt >= timeoutMs) {
3327
+ throw new Error(
3328
+ `Registration progress polling timed out after ${timeoutMs}ms`
3329
+ );
3330
+ }
3331
+ await client.delay(interval, signal);
3332
+ }
3333
+ }
3334
+ async function validateUaid(client, uaid) {
3335
+ const raw = await client.requestJson(
3336
+ `/uaids/validate/${encodeURIComponent(uaid)}`,
3337
+ {
3338
+ method: "GET"
3371
3339
  }
3372
- }
3373
- recipientMatches(candidate, target) {
3374
- if (target.uaid && candidate.uaid?.toLowerCase() === target.uaid.toLowerCase()) {
3375
- return true;
3340
+ );
3341
+ return client.parseWithSchema(
3342
+ raw,
3343
+ uaidValidationResponseSchema,
3344
+ "UAID validation response"
3345
+ );
3346
+ }
3347
+ async function getUaidConnectionStatus(client, uaid) {
3348
+ const raw = await client.requestJson(
3349
+ `/uaids/connections/${encodeURIComponent(uaid)}/status`,
3350
+ {
3351
+ method: "GET"
3376
3352
  }
3377
- if (target.ledgerAccountId && candidate.ledgerAccountId?.toLowerCase() === target.ledgerAccountId.toLowerCase()) {
3378
- return true;
3353
+ );
3354
+ return client.parseWithSchema(
3355
+ raw,
3356
+ uaidConnectionStatusSchema,
3357
+ "UAID connection status"
3358
+ );
3359
+ }
3360
+ async function closeUaidConnection(client, uaid) {
3361
+ await client.request(`/uaids/connections/${encodeURIComponent(uaid)}`, {
3362
+ method: "DELETE"
3363
+ });
3364
+ }
3365
+ async function dashboardStats(client) {
3366
+ const raw = await client.requestJson("/dashboard/stats", {
3367
+ method: "GET"
3368
+ });
3369
+ return client.parseWithSchema(
3370
+ raw,
3371
+ dashboardStatsResponseSchema,
3372
+ "dashboard stats response"
3373
+ );
3374
+ }
3375
+
3376
+ // ../../src/services/registry-broker/client/verification.ts
3377
+ async function getVerificationStatus(client, uaid) {
3378
+ const raw = await client.requestJson(
3379
+ `/verification/status/${encodeURIComponent(uaid)}`,
3380
+ { method: "GET" }
3381
+ );
3382
+ return client.parseWithSchema(
3383
+ raw,
3384
+ verificationStatusResponseSchema,
3385
+ "verification status response"
3386
+ );
3387
+ }
3388
+ async function createVerificationChallenge(client, uaid) {
3389
+ const raw = await client.requestJson("/verification/challenge", {
3390
+ method: "POST",
3391
+ headers: { "content-type": "application/json" },
3392
+ body: { uaid }
3393
+ });
3394
+ return client.parseWithSchema(
3395
+ raw,
3396
+ verificationChallengeResponseSchema,
3397
+ "verification challenge response"
3398
+ );
3399
+ }
3400
+ async function getVerificationChallenge(client, challengeId) {
3401
+ const raw = await client.requestJson(
3402
+ `/verification/challenge/${encodeURIComponent(challengeId)}`,
3403
+ { method: "GET" }
3404
+ );
3405
+ return client.parseWithSchema(
3406
+ raw,
3407
+ verificationChallengeDetailsResponseSchema,
3408
+ "verification challenge details response"
3409
+ );
3410
+ }
3411
+ async function verifyVerificationChallenge(client, params) {
3412
+ const raw = await client.requestJson("/verification/verify", {
3413
+ method: "POST",
3414
+ headers: { "content-type": "application/json" },
3415
+ body: {
3416
+ challengeId: params.challengeId,
3417
+ method: params.method ?? "moltbook-post"
3379
3418
  }
3380
- if (target.userId && candidate.userId === target.userId) {
3381
- return true;
3419
+ });
3420
+ return client.parseWithSchema(
3421
+ raw,
3422
+ verificationVerifyResponseSchema,
3423
+ "verification verify response"
3424
+ );
3425
+ }
3426
+ async function getVerificationOwnership(client, uaid) {
3427
+ const raw = await client.requestJson(
3428
+ `/verification/ownership/${encodeURIComponent(uaid)}`,
3429
+ { method: "GET" }
3430
+ );
3431
+ return client.parseWithSchema(
3432
+ raw,
3433
+ verificationOwnershipResponseSchema,
3434
+ "verification ownership response"
3435
+ );
3436
+ }
3437
+ async function verifySenderOwnership(client, uaid) {
3438
+ const raw = await client.requestJson(
3439
+ "/verification/verify-sender",
3440
+ {
3441
+ method: "POST",
3442
+ headers: { "content-type": "application/json" },
3443
+ body: { uaid }
3382
3444
  }
3383
- if (target.email && candidate.email?.toLowerCase() === target.email.toLowerCase()) {
3384
- return true;
3445
+ );
3446
+ return client.parseWithSchema(
3447
+ raw,
3448
+ verificationVerifySenderResponseSchema,
3449
+ "verification sender response"
3450
+ );
3451
+ }
3452
+ async function verifyUaidDnsTxt(client, payload) {
3453
+ const raw = await client.requestJson("/verification/dns/verify", {
3454
+ method: "POST",
3455
+ headers: { "content-type": "application/json" },
3456
+ body: {
3457
+ uaid: payload.uaid,
3458
+ ...payload.persist !== void 0 ? { persist: payload.persist } : {}
3385
3459
  }
3386
- return false;
3460
+ });
3461
+ return client.parseWithSchema(
3462
+ raw,
3463
+ verificationDnsStatusResponseSchema,
3464
+ "verification dns verify response"
3465
+ );
3466
+ }
3467
+ async function getVerificationDnsStatus(client, uaid, query) {
3468
+ const params = new URLSearchParams();
3469
+ if (query?.refresh !== void 0) {
3470
+ params.set("refresh", String(query.refresh));
3387
3471
  }
3388
- async delay(ms) {
3389
- if (ms <= 0) {
3390
- return;
3391
- }
3392
- await new Promise((resolve2) => setTimeout(resolve2, ms));
3472
+ if (query?.persist !== void 0) {
3473
+ params.set("persist", String(query.persist));
3393
3474
  }
3394
- };
3395
-
3396
- // ../../src/services/registry-broker/client/chat.ts
3397
- function createChatApi(client, encryptedManager) {
3398
- return {
3399
- start: (options) => client.startChat(options),
3400
- createSession: (payload) => client.createSession(payload),
3401
- sendMessage: (payload) => client.sendMessage(payload),
3402
- endSession: (sessionId) => client.endSession(sessionId),
3403
- getHistory: (sessionId, options) => client.fetchHistorySnapshot(sessionId, options),
3404
- compactHistory: (payload) => client.compactHistory(payload),
3405
- getEncryptionStatus: (sessionId) => client.fetchEncryptionStatus(sessionId),
3406
- submitEncryptionHandshake: (sessionId, payload) => client.postEncryptionHandshake(sessionId, payload),
3407
- startConversation: (options) => client.startConversation(options),
3408
- acceptConversation: (options) => client.acceptConversation(options),
3409
- createEncryptedSession: (options) => encryptedManager.startSession(options),
3410
- acceptEncryptedSession: (options) => encryptedManager.acceptSession(options)
3411
- };
3475
+ const queryString = params.toString();
3476
+ const path = `/verification/dns/status/${encodeURIComponent(uaid)}${queryString ? `?${queryString}` : ""}`;
3477
+ const raw = await client.requestJson(path, {
3478
+ method: "GET"
3479
+ });
3480
+ return client.parseWithSchema(
3481
+ raw,
3482
+ verificationDnsStatusResponseSchema,
3483
+ "verification dns status response"
3484
+ );
3412
3485
  }
3413
- async function createSession(client, payload, allowHistoryAutoTopUp = true) {
3414
- const body = {};
3415
- if ("uaid" in payload && payload.uaid) {
3416
- body.uaid = payload.uaid;
3486
+ async function getRegisterStatus(client, uaid) {
3487
+ const raw = await client.requestJson(
3488
+ `/register/status/${encodeURIComponent(uaid)}`,
3489
+ { method: "GET" }
3490
+ );
3491
+ return client.parseWithSchema(
3492
+ raw,
3493
+ registerStatusResponseSchema,
3494
+ "register status response"
3495
+ );
3496
+ }
3497
+ async function registerOwnedMoltbookAgent(client, uaid, request) {
3498
+ const raw = await client.requestJson(
3499
+ `/register/${encodeURIComponent(uaid)}`,
3500
+ {
3501
+ method: "PUT",
3502
+ headers: { "content-type": "application/json" },
3503
+ body: {
3504
+ registered: request.registered ?? true,
3505
+ ...request.name ? { name: request.name } : {},
3506
+ ...request.description ? { description: request.description } : {},
3507
+ ...request.endpoint ? { endpoint: request.endpoint } : {},
3508
+ ...request.metadata ? { metadata: request.metadata } : {}
3509
+ }
3510
+ }
3511
+ );
3512
+ return client.parseWithSchema(
3513
+ raw,
3514
+ moltbookOwnerRegistrationUpdateResponseSchema,
3515
+ "moltbook owner registration update response"
3516
+ );
3517
+ }
3518
+
3519
+ // ../../src/services/registry-broker/client/ledger-auth.ts
3520
+ var import_buffer3 = require("buffer");
3521
+
3522
+ // ../../src/services/registry-broker/ledger-network.ts
3523
+ var normalise = (value) => value.trim().toLowerCase();
3524
+ var HEDERA_NETWORK_ALIASES = /* @__PURE__ */ new Map([
3525
+ ["hedera:mainnet", { canonical: "hedera:mainnet", hederaNetwork: "mainnet" }],
3526
+ ["mainnet", { canonical: "hedera:mainnet", hederaNetwork: "mainnet" }],
3527
+ ["hedera-mainnet", { canonical: "hedera:mainnet", hederaNetwork: "mainnet" }],
3528
+ ["hedera_mainnet", { canonical: "hedera:mainnet", hederaNetwork: "mainnet" }],
3529
+ ["hedera:testnet", { canonical: "hedera:testnet", hederaNetwork: "testnet" }],
3530
+ ["testnet", { canonical: "hedera:testnet", hederaNetwork: "testnet" }],
3531
+ ["hedera-testnet", { canonical: "hedera:testnet", hederaNetwork: "testnet" }],
3532
+ ["hedera_testnet", { canonical: "hedera:testnet", hederaNetwork: "testnet" }]
3533
+ ]);
3534
+ var EVM_NETWORK_CHAIN_IDS = {
3535
+ abstract: 2741,
3536
+ "abstract-testnet": 11124,
3537
+ base: 8453,
3538
+ "base-sepolia": 84532,
3539
+ avalanche: 43114,
3540
+ "avalanche-fuji": 43113,
3541
+ iotex: 4689,
3542
+ sei: 1329,
3543
+ "sei-testnet": 1328,
3544
+ polygon: 137,
3545
+ "polygon-amoy": 80002,
3546
+ peaq: 3338
3547
+ };
3548
+ var CHAIN_ID_TO_ALIAS = new Map(
3549
+ Object.entries(EVM_NETWORK_CHAIN_IDS).map(([alias, id]) => [id, alias])
3550
+ );
3551
+ var parseChainId = (value) => {
3552
+ if (/^eip155:\d+$/i.test(value)) {
3553
+ return Number.parseInt(value.split(":")[1], 10);
3417
3554
  }
3418
- if ("agentUrl" in payload && payload.agentUrl) {
3419
- body.agentUrl = payload.agentUrl;
3555
+ if (/^\d+$/.test(value)) {
3556
+ return Number.parseInt(value, 10);
3420
3557
  }
3421
- if (payload.auth) {
3422
- body.auth = serialiseAuthConfig(payload.auth);
3558
+ return void 0;
3559
+ };
3560
+ var normaliseEvmNetwork = (value) => {
3561
+ const trimmed = normalise(value);
3562
+ let chainId = parseChainId(trimmed);
3563
+ let alias;
3564
+ if (chainId === void 0) {
3565
+ const mapped = EVM_NETWORK_CHAIN_IDS[trimmed];
3566
+ if (mapped !== void 0) {
3567
+ chainId = mapped;
3568
+ alias = trimmed;
3569
+ }
3570
+ } else if (CHAIN_ID_TO_ALIAS.has(chainId)) {
3571
+ alias = CHAIN_ID_TO_ALIAS.get(chainId);
3423
3572
  }
3424
- if (payload.historyTtlSeconds !== void 0) {
3425
- body.historyTtlSeconds = payload.historyTtlSeconds;
3573
+ if (chainId === void 0) {
3574
+ throw new Error(
3575
+ 'Unsupported EVM ledger network. Provide an alias like "base-sepolia" or a canonical eip155:<chainId> string.'
3576
+ );
3426
3577
  }
3427
- if (payload.encryptionRequested !== void 0) {
3428
- body.encryptionRequested = payload.encryptionRequested;
3578
+ return {
3579
+ canonical: `eip155:${chainId}`,
3580
+ kind: "evm",
3581
+ chainId,
3582
+ legacyName: alias
3583
+ };
3584
+ };
3585
+ var normaliseHederaNetwork = (value) => {
3586
+ const trimmed = normalise(value);
3587
+ const mapping = HEDERA_NETWORK_ALIASES.get(trimmed);
3588
+ if (!mapping) {
3589
+ throw new Error(
3590
+ 'Unsupported Hedera network. Use hedera:mainnet or hedera:testnet (legacy "mainnet"/"testnet" also accepted).'
3591
+ );
3429
3592
  }
3430
- if (payload.senderUaid) {
3431
- body.senderUaid = payload.senderUaid;
3593
+ return {
3594
+ canonical: mapping.canonical,
3595
+ kind: "hedera",
3596
+ hederaNetwork: mapping.hederaNetwork
3597
+ };
3598
+ };
3599
+ var canonicalizeLedgerNetwork = (network) => {
3600
+ if (typeof network !== "string" || network.trim().length === 0) {
3601
+ throw new Error("Ledger network is required.");
3432
3602
  }
3433
- try {
3434
- const raw = await client.requestJson("/chat/session", {
3435
- method: "POST",
3436
- body,
3437
- headers: { "content-type": "application/json" }
3438
- });
3439
- return client.parseWithSchema(
3440
- raw,
3441
- createSessionResponseSchema,
3442
- "chat session response"
3443
- );
3444
- } catch (error) {
3445
- const maybeError = error instanceof Error ? error : null;
3446
- if (allowHistoryAutoTopUp && client.shouldAutoTopUpHistory(payload, maybeError)) {
3447
- await client.executeHistoryAutoTopUp("chat.session");
3448
- return createSession(client, payload, false);
3449
- }
3450
- throw error;
3603
+ const trimmed = normalise(network);
3604
+ if (trimmed.startsWith("hedera:") || trimmed.includes("hedera-") || trimmed.includes("hedera_") || trimmed === "mainnet" || trimmed === "testnet") {
3605
+ return normaliseHederaNetwork(trimmed);
3451
3606
  }
3452
- }
3453
- async function startChat(client, encryptedManager, options) {
3454
- if ("uaid" in options && options.uaid) {
3455
- return startConversation(client, encryptedManager, {
3456
- uaid: options.uaid,
3457
- senderUaid: options.senderUaid,
3458
- historyTtlSeconds: options.historyTtlSeconds,
3459
- auth: options.auth,
3460
- encryption: options.encryption,
3461
- onSessionCreated: options.onSessionCreated
3462
- });
3607
+ return normaliseEvmNetwork(trimmed);
3608
+ };
3609
+
3610
+ // ../../src/services/registry-broker/private-key-signer.ts
3611
+ var unsupported = (method) => new Error(`${method} is not supported by the in-memory signer`);
3612
+ var cachedSdk = null;
3613
+ var loadHashgraphSdk = () => {
3614
+ if (cachedSdk) {
3615
+ return cachedSdk;
3463
3616
  }
3464
- if ("agentUrl" in options && options.agentUrl) {
3465
- const session = await createSession(client, {
3466
- agentUrl: options.agentUrl,
3467
- auth: options.auth,
3468
- historyTtlSeconds: options.historyTtlSeconds,
3469
- senderUaid: options.senderUaid
3470
- });
3471
- options.onSessionCreated?.(session.sessionId);
3472
- return createPlaintextConversationHandle(
3473
- client,
3474
- session.sessionId,
3475
- session.encryption ?? null,
3476
- options.auth,
3477
- { agentUrl: options.agentUrl, uaid: options.uaid }
3478
- );
3617
+ const resolved = optionalImportSync("@hashgraph/sdk");
3618
+ if (resolved) {
3619
+ cachedSdk = resolved;
3620
+ return resolved;
3479
3621
  }
3480
- throw new Error("startChat requires either uaid or agentUrl");
3481
- }
3482
- async function startConversation(client, encryptedManager, options) {
3483
- const preference = options.encryption?.preference ?? "preferred";
3484
- const requestEncryption = preference !== "disabled";
3485
- if (!requestEncryption) {
3486
- const session = await createSession(client, {
3487
- uaid: options.uaid,
3488
- auth: options.auth,
3489
- historyTtlSeconds: options.historyTtlSeconds,
3490
- senderUaid: options.senderUaid,
3491
- encryptionRequested: false
3492
- });
3493
- options.onSessionCreated?.(session.sessionId);
3494
- return createPlaintextConversationHandle(
3495
- client,
3496
- session.sessionId,
3497
- session.encryption ?? null,
3498
- options.auth,
3499
- { uaid: options.uaid }
3500
- );
3622
+ const message = "@hashgraph/sdk is required for ledger signing. Install it as a dependency to enable createPrivateKeySigner.";
3623
+ throw new Error(message);
3624
+ };
3625
+ var loadHashgraphSdkAsync = async () => {
3626
+ if (cachedSdk) {
3627
+ return cachedSdk;
3501
3628
  }
3502
- try {
3503
- const handle = await encryptedManager.startSession({
3504
- uaid: options.uaid,
3505
- senderUaid: options.senderUaid,
3506
- historyTtlSeconds: options.historyTtlSeconds,
3507
- handshakeTimeoutMs: options.encryption?.handshakeTimeoutMs,
3508
- pollIntervalMs: options.encryption?.pollIntervalMs,
3509
- onSessionCreated: (sessionId) => {
3510
- options.onSessionCreated?.(sessionId);
3511
- },
3512
- auth: options.auth
3513
- });
3514
- return handle;
3515
- } catch (error) {
3516
- if (error instanceof EncryptionUnavailableError) {
3517
- if (preference === "required") {
3518
- throw error;
3519
- }
3520
- return createPlaintextConversationHandle(
3521
- client,
3522
- error.sessionId,
3523
- error.summary ?? null,
3524
- options.auth,
3525
- { uaid: options.uaid }
3526
- );
3527
- }
3528
- throw error;
3629
+ const resolved = await optionalImport("@hashgraph/sdk");
3630
+ if (resolved) {
3631
+ cachedSdk = resolved;
3632
+ return resolved;
3529
3633
  }
3530
- }
3531
- async function acceptConversation(client, encryptedManager, options) {
3532
- const preference = options.encryption?.preference ?? "preferred";
3533
- if (preference === "disabled") {
3534
- return createPlaintextConversationHandle(client, options.sessionId, null);
3634
+ const message = "@hashgraph/sdk is required for ledger signing. Install it as a dependency to enable createPrivateKeySigner.";
3635
+ throw new Error(message);
3636
+ };
3637
+ var buildSigner = (sdk, options) => {
3638
+ const { AccountId, LedgerId, PrivateKey, SignerSignature } = sdk;
3639
+ if (!options.privateKey) {
3640
+ throw new Error("privateKey is required to create a ledger signer.");
3535
3641
  }
3536
- try {
3537
- const handle = await encryptedManager.acceptSession({
3538
- sessionId: options.sessionId,
3539
- responderUaid: options.responderUaid,
3540
- handshakeTimeoutMs: options.encryption?.handshakeTimeoutMs,
3541
- pollIntervalMs: options.encryption?.pollIntervalMs
3542
- });
3543
- return handle;
3544
- } catch (error) {
3545
- if (error instanceof EncryptionUnavailableError && preference !== "required") {
3546
- return createPlaintextConversationHandle(
3547
- client,
3548
- options.sessionId,
3549
- null,
3550
- void 0,
3551
- { uaid: options.responderUaid }
3552
- );
3553
- }
3554
- throw error;
3642
+ if (!options.accountId) {
3643
+ throw new Error("accountId is required to create a ledger signer.");
3555
3644
  }
3556
- }
3557
- function createPlaintextConversationHandle(client, sessionId, summary, defaultAuth, context) {
3558
- const uaid = context?.uaid?.trim();
3559
- const agentUrl = context?.agentUrl?.trim();
3560
- const fetchHistory = async (options) => {
3561
- const snapshot = await client.fetchHistorySnapshot(sessionId, options);
3562
- if (snapshot.decryptedHistory) {
3563
- return snapshot.decryptedHistory;
3564
- }
3565
- return snapshot.history.map((entry) => ({
3566
- entry,
3567
- plaintext: entry.content
3568
- }));
3569
- };
3645
+ const accountId = AccountId.fromString(options.accountId);
3646
+ const privateKey = PrivateKey.fromString(options.privateKey);
3647
+ const ledgerId = LedgerId.fromString(options.network);
3570
3648
  return {
3571
- sessionId,
3572
- mode: "plaintext",
3573
- summary: summary ?? null,
3574
- send: async (options) => {
3575
- const plaintext = options.plaintext;
3576
- if (!plaintext || plaintext.trim().length === 0) {
3577
- throw new Error("plaintext is required for chat messages");
3578
- }
3579
- const message = options.message ?? plaintext;
3580
- return sendMessage(client, {
3581
- sessionId,
3582
- message,
3583
- streaming: options.streaming,
3584
- auth: options.auth ?? defaultAuth,
3585
- uaid,
3586
- agentUrl
3587
- });
3649
+ getLedgerId: () => ledgerId,
3650
+ getAccountId: () => accountId,
3651
+ getAccountKey: () => privateKey.publicKey,
3652
+ getNetwork: () => ({}),
3653
+ getMirrorNetwork: () => [],
3654
+ sign: async (messages) => Promise.all(
3655
+ messages.map(async (message) => {
3656
+ const signature = await privateKey.sign(message);
3657
+ return new SignerSignature({
3658
+ publicKey: privateKey.publicKey,
3659
+ signature,
3660
+ accountId
3661
+ });
3662
+ })
3663
+ ),
3664
+ getAccountBalance: async () => {
3665
+ throw unsupported("getAccountBalance");
3666
+ },
3667
+ getAccountInfo: async () => {
3668
+ throw unsupported("getAccountInfo");
3669
+ },
3670
+ getAccountRecords: async () => {
3671
+ throw unsupported("getAccountRecords");
3672
+ },
3673
+ signTransaction: async (_) => {
3674
+ throw unsupported("signTransaction");
3675
+ },
3676
+ checkTransaction: async (_) => {
3677
+ throw unsupported("checkTransaction");
3588
3678
  },
3589
- decryptHistoryEntry: (entry) => entry.content,
3590
- fetchHistory
3679
+ populateTransaction: async (_) => {
3680
+ throw unsupported("populateTransaction");
3681
+ },
3682
+ call: async (_request) => {
3683
+ throw unsupported("call");
3684
+ }
3591
3685
  };
3686
+ };
3687
+ var createPrivateKeySigner = (options) => buildSigner(loadHashgraphSdk(), options);
3688
+ var createPrivateKeySignerAsync = async (options) => buildSigner(await loadHashgraphSdkAsync(), options);
3689
+
3690
+ // ../../src/services/registry-broker/client/ledger-auth.ts
3691
+ async function loadViemAccount(privateKey) {
3692
+ try {
3693
+ const viem = await import("viem/accounts");
3694
+ return viem.privateKeyToAccount(privateKey);
3695
+ } catch (error) {
3696
+ const err = new Error(
3697
+ 'EVM ledger authentication requires the optional dependency "viem". Install it to use evmPrivateKey flows.'
3698
+ );
3699
+ err.cause = error;
3700
+ throw err;
3701
+ }
3592
3702
  }
3593
- async function compactHistory(client, payload) {
3594
- if (!payload.sessionId || payload.sessionId.trim().length === 0) {
3595
- throw new Error("sessionId is required to compact chat history");
3703
+ async function resolveLedgerAuthSignature(message, options) {
3704
+ if (typeof options.sign === "function") {
3705
+ const result = await options.sign(message);
3706
+ if (!result || typeof result.signature !== "string" || result.signature.length === 0) {
3707
+ throw new Error("Custom ledger signer failed to produce a signature.");
3708
+ }
3709
+ return result;
3596
3710
  }
3597
- const body = {};
3598
- if (typeof payload.preserveEntries === "number" && Number.isFinite(payload.preserveEntries) && payload.preserveEntries >= 0) {
3599
- body.preserveEntries = Math.floor(payload.preserveEntries);
3711
+ if (!options.signer || typeof options.signer.sign !== "function") {
3712
+ throw new Error(
3713
+ "Ledger authentication requires a Hedera Signer or custom sign function."
3714
+ );
3600
3715
  }
3601
- const raw = await client.requestJson(
3602
- `/chat/session/${encodeURIComponent(payload.sessionId)}/compact`,
3603
- {
3604
- method: "POST",
3605
- headers: { "content-type": "application/json" },
3606
- body
3716
+ const payload = import_buffer3.Buffer.from(message, "utf8");
3717
+ const signatures = await options.signer.sign([payload]);
3718
+ const signatureEntry = signatures?.[0];
3719
+ if (!signatureEntry) {
3720
+ throw new Error("Signer did not return any signatures.");
3721
+ }
3722
+ let derivedPublicKey;
3723
+ if (signatureEntry.publicKey) {
3724
+ derivedPublicKey = signatureEntry.publicKey.toString();
3725
+ } else if (typeof options.signer.getAccountKey === "function") {
3726
+ const accountKey = await options.signer.getAccountKey();
3727
+ if (accountKey && typeof accountKey.toString === "function") {
3728
+ derivedPublicKey = accountKey.toString();
3607
3729
  }
3608
- );
3730
+ }
3731
+ return {
3732
+ signature: import_buffer3.Buffer.from(signatureEntry.signature).toString("base64"),
3733
+ signatureKind: "raw",
3734
+ publicKey: derivedPublicKey
3735
+ };
3736
+ }
3737
+ async function createLedgerChallenge(client, payload) {
3738
+ const resolvedNetwork = canonicalizeLedgerNetwork(payload.network);
3739
+ const network = resolvedNetwork.kind === "hedera" ? resolvedNetwork.hederaNetwork ?? resolvedNetwork.canonical : resolvedNetwork.canonical;
3740
+ const raw = await client.requestJson("/auth/ledger/challenge", {
3741
+ method: "POST",
3742
+ headers: { "content-type": "application/json" },
3743
+ body: {
3744
+ accountId: payload.accountId,
3745
+ network
3746
+ }
3747
+ });
3609
3748
  return client.parseWithSchema(
3610
3749
  raw,
3611
- chatHistoryCompactionResponseSchema,
3612
- "chat history compaction response"
3750
+ ledgerChallengeResponseSchema,
3751
+ "ledger challenge response"
3613
3752
  );
3614
3753
  }
3615
- async function fetchEncryptionStatus(client, sessionId) {
3616
- if (!sessionId || sessionId.trim().length === 0) {
3617
- throw new Error("sessionId is required for encryption status");
3754
+ async function verifyLedgerChallenge(client, payload) {
3755
+ const resolvedNetwork = canonicalizeLedgerNetwork(payload.network);
3756
+ const network = resolvedNetwork.kind === "hedera" ? resolvedNetwork.hederaNetwork ?? resolvedNetwork.canonical : resolvedNetwork.canonical;
3757
+ const body = {
3758
+ challengeId: payload.challengeId,
3759
+ accountId: payload.accountId,
3760
+ network,
3761
+ signature: payload.signature
3762
+ };
3763
+ if (payload.signatureKind) {
3764
+ body.signatureKind = payload.signatureKind;
3618
3765
  }
3619
- const raw = await client.requestJson(
3620
- `/chat/session/${encodeURIComponent(sessionId)}/encryption`,
3621
- {
3622
- method: "GET"
3623
- }
3624
- );
3625
- return client.parseWithSchema(
3766
+ if (payload.publicKey) {
3767
+ body.publicKey = payload.publicKey;
3768
+ }
3769
+ if (typeof payload.expiresInMinutes === "number") {
3770
+ body.expiresInMinutes = payload.expiresInMinutes;
3771
+ }
3772
+ const raw = await client.requestJson("/auth/ledger/verify", {
3773
+ method: "POST",
3774
+ headers: { "content-type": "application/json" },
3775
+ body
3776
+ });
3777
+ const result = client.parseWithSchema(
3626
3778
  raw,
3627
- sessionEncryptionStatusResponseSchema,
3628
- "session encryption status response"
3779
+ ledgerVerifyResponseSchema,
3780
+ "ledger verification response"
3629
3781
  );
3782
+ client.setLedgerApiKey(result.key);
3783
+ return result;
3630
3784
  }
3631
- async function postEncryptionHandshake(client, sessionId, payload) {
3632
- if (!sessionId || sessionId.trim().length === 0) {
3633
- throw new Error("sessionId is required for encryption handshake");
3634
- }
3635
- const raw = await client.requestJson(
3636
- `/chat/session/${encodeURIComponent(sessionId)}/encryption-handshake`,
3637
- {
3638
- method: "POST",
3639
- headers: { "content-type": "application/json" },
3640
- body: {
3641
- role: payload.role,
3642
- keyType: payload.keyType,
3643
- ephemeralPublicKey: payload.ephemeralPublicKey,
3644
- longTermPublicKey: payload.longTermPublicKey,
3645
- signature: payload.signature,
3646
- uaid: payload.uaid,
3647
- userId: payload.userId,
3648
- ledgerAccountId: payload.ledgerAccountId,
3649
- metadata: payload.metadata
3650
- }
3785
+ async function authenticateWithLedger(client, options) {
3786
+ const challenge = await client.createLedgerChallenge({
3787
+ accountId: options.accountId,
3788
+ network: options.network
3789
+ });
3790
+ const signed = await resolveLedgerAuthSignature(challenge.message, options);
3791
+ const verification = await client.verifyLedgerChallenge({
3792
+ challengeId: challenge.challengeId,
3793
+ accountId: options.accountId,
3794
+ network: options.network,
3795
+ signature: signed.signature,
3796
+ signatureKind: signed.signatureKind,
3797
+ publicKey: signed.publicKey,
3798
+ expiresInMinutes: options.expiresInMinutes
3799
+ });
3800
+ return verification;
3801
+ }
3802
+ async function authenticateWithLedgerCredentials(client, options) {
3803
+ const {
3804
+ accountId,
3805
+ network,
3806
+ signer,
3807
+ sign,
3808
+ hederaPrivateKey,
3809
+ evmPrivateKey,
3810
+ expiresInMinutes,
3811
+ setAccountHeader = true,
3812
+ label,
3813
+ logger
3814
+ } = options;
3815
+ const resolvedNetwork = canonicalizeLedgerNetwork(network);
3816
+ const labelSuffix = label ? ` for ${label}` : "";
3817
+ const networkPayload = resolvedNetwork.canonical;
3818
+ const authOptions = {
3819
+ accountId,
3820
+ network: networkPayload,
3821
+ expiresInMinutes
3822
+ };
3823
+ if (sign) {
3824
+ authOptions.sign = sign;
3825
+ } else if (signer) {
3826
+ authOptions.signer = signer;
3827
+ } else if (hederaPrivateKey) {
3828
+ if (resolvedNetwork.kind !== "hedera" || !resolvedNetwork.hederaNetwork) {
3829
+ throw new Error(
3830
+ "hederaPrivateKey can only be used with hedera:mainnet or hedera:testnet networks."
3831
+ );
3832
+ }
3833
+ authOptions.signer = await createPrivateKeySignerAsync({
3834
+ accountId,
3835
+ privateKey: hederaPrivateKey,
3836
+ network: resolvedNetwork.hederaNetwork
3837
+ });
3838
+ } else if (evmPrivateKey) {
3839
+ if (resolvedNetwork.kind !== "evm") {
3840
+ throw new Error(
3841
+ "evmPrivateKey can only be used with CAIP-2 EVM networks (eip155:<chainId>)."
3842
+ );
3651
3843
  }
3844
+ const formattedKey = evmPrivateKey.startsWith("0x") ? evmPrivateKey : `0x${evmPrivateKey}`;
3845
+ const account = await loadViemAccount(formattedKey);
3846
+ authOptions.sign = async (message) => ({
3847
+ signature: await account.signMessage({ message }),
3848
+ signatureKind: "evm",
3849
+ publicKey: account.publicKey
3850
+ });
3851
+ } else {
3852
+ throw new Error(
3853
+ "Provide a signer, sign function, hederaPrivateKey, or evmPrivateKey to authenticate with the ledger."
3854
+ );
3855
+ }
3856
+ logger?.info?.(
3857
+ `Authenticating ledger account ${accountId} (${resolvedNetwork.canonical})${labelSuffix}...`
3652
3858
  );
3653
- const response = client.parseWithSchema(
3654
- raw,
3655
- encryptionHandshakeResponseSchema,
3656
- "encryption handshake response"
3859
+ const verification = await client.authenticateWithLedger(authOptions);
3860
+ if (setAccountHeader) {
3861
+ client.setDefaultHeader("x-account-id", verification.accountId);
3862
+ }
3863
+ logger?.info?.(
3864
+ `Ledger authentication complete${labelSuffix}. Issued key prefix: ${verification.apiKey.prefix}\u2026${verification.apiKey.lastFour}`
3657
3865
  );
3658
- return response.handshake;
3866
+ return verification;
3659
3867
  }
3660
- async function sendMessage(client, payload) {
3661
- const body = {
3662
- message: payload.message
3868
+
3869
+ // ../../src/services/registry-broker/client/search.ts
3870
+ function buildVectorFallbackSearchParams(request) {
3871
+ const params = {
3872
+ q: request.query
3663
3873
  };
3664
- if (payload.streaming !== void 0) {
3665
- body.streaming = payload.streaming;
3666
- }
3667
- if (payload.auth) {
3668
- body.auth = serialiseAuthConfig(payload.auth);
3874
+ let effectiveLimit;
3875
+ if (typeof request.limit === "number" && Number.isFinite(request.limit)) {
3876
+ effectiveLimit = request.limit;
3877
+ params.limit = request.limit;
3669
3878
  }
3670
- if ("uaid" in payload) {
3671
- body.uaid = payload.uaid;
3879
+ if (typeof request.offset === "number" && Number.isFinite(request.offset) && request.offset > 0) {
3880
+ const limit = effectiveLimit && effectiveLimit > 0 ? effectiveLimit : 20;
3881
+ params.limit = limit;
3882
+ params.page = Math.floor(request.offset / limit) + 1;
3672
3883
  }
3673
- if ("sessionId" in payload && payload.sessionId) {
3674
- body.sessionId = payload.sessionId;
3884
+ if (request.filter?.registry) {
3885
+ params.registry = request.filter.registry;
3675
3886
  }
3676
- if ("agentUrl" in payload && payload.agentUrl) {
3677
- body.agentUrl = payload.agentUrl;
3887
+ if (request.filter?.protocols?.length) {
3888
+ params.protocols = [...request.filter.protocols];
3678
3889
  }
3679
- let cipherEnvelope = payload.cipherEnvelope ?? null;
3680
- if (payload.encryption) {
3681
- const sessionIdForEncryption = payload.encryption.sessionId ?? (typeof body.sessionId === "string" ? body.sessionId : void 0);
3682
- if (!sessionIdForEncryption) {
3683
- throw new Error(
3684
- "sessionId is required when using encrypted chat payloads"
3685
- );
3686
- }
3687
- if (!payload.encryption.recipients?.length) {
3688
- throw new Error("recipients are required for encrypted chat payloads");
3689
- }
3690
- cipherEnvelope = client.encryption.encryptCipherEnvelope({
3691
- ...payload.encryption,
3692
- sessionId: sessionIdForEncryption
3693
- });
3890
+ if (request.filter?.adapter?.length) {
3891
+ params.adapters = [...request.filter.adapter];
3694
3892
  }
3695
- if (cipherEnvelope) {
3696
- body.cipherEnvelope = toJsonObject(cipherEnvelope);
3893
+ if (request.filter?.capabilities?.length) {
3894
+ params.capabilities = request.filter.capabilities.map(
3895
+ (value) => typeof value === "number" ? value.toString(10) : value
3896
+ );
3697
3897
  }
3698
- const raw = await client.requestJson("/chat/message", {
3898
+ if (request.filter?.type) {
3899
+ params.type = request.filter.type;
3900
+ }
3901
+ return params;
3902
+ }
3903
+ function convertSearchResultToVectorResponse(result) {
3904
+ const hits = result.hits.map((agent) => ({
3905
+ agent,
3906
+ score: 0,
3907
+ highlights: {}
3908
+ }));
3909
+ const total = result.total;
3910
+ const limit = result.limit;
3911
+ const page = result.page;
3912
+ const totalVisible = page * limit;
3913
+ const limited = total > totalVisible || page > 1;
3914
+ return {
3915
+ hits,
3916
+ total,
3917
+ took: 0,
3918
+ totalAvailable: total,
3919
+ visible: hits.length,
3920
+ limited,
3921
+ credits_used: 0
3922
+ };
3923
+ }
3924
+ async function search(client, params = {}) {
3925
+ const query = buildSearchQuery(params);
3926
+ const raw = await client.requestJson(`/search${query}`, {
3927
+ method: "GET"
3928
+ });
3929
+ return client.parseWithSchema(raw, searchResponseSchema, "search response");
3930
+ }
3931
+ async function delegate(client, request) {
3932
+ const raw = await client.requestJson("/delegate", {
3699
3933
  method: "POST",
3700
- body,
3934
+ body: request,
3701
3935
  headers: { "content-type": "application/json" }
3702
3936
  });
3703
3937
  return client.parseWithSchema(
3704
3938
  raw,
3705
- sendMessageResponseSchema,
3706
- "chat message response"
3939
+ delegationPlanResponseSchema,
3940
+ "delegate response"
3707
3941
  );
3708
3942
  }
3709
- async function endSession(client, sessionId) {
3710
- await client.request(`/chat/session/${encodeURIComponent(sessionId)}`, {
3711
- method: "DELETE"
3943
+ async function stats(client) {
3944
+ const raw = await client.requestJson("/stats", { method: "GET" });
3945
+ return client.parseWithSchema(raw, statsResponseSchema, "stats response");
3946
+ }
3947
+ async function registries(client) {
3948
+ const raw = await client.requestJson("/registries", {
3949
+ method: "GET"
3712
3950
  });
3951
+ return client.parseWithSchema(
3952
+ raw,
3953
+ registriesResponseSchema,
3954
+ "registries response"
3955
+ );
3713
3956
  }
3714
-
3715
- // ../../src/services/registry-broker/client/verification.ts
3716
- async function getVerificationStatus(client, uaid) {
3957
+ async function getAdditionalRegistries(client) {
3717
3958
  const raw = await client.requestJson(
3718
- `/verification/status/${encodeURIComponent(uaid)}`,
3719
- { method: "GET" }
3959
+ "/register/additional-registries",
3960
+ {
3961
+ method: "GET"
3962
+ }
3720
3963
  );
3721
3964
  return client.parseWithSchema(
3722
3965
  raw,
3723
- verificationStatusResponseSchema,
3724
- "verification status response"
3966
+ additionalRegistryCatalogResponseSchema,
3967
+ "additional registry catalog response"
3725
3968
  );
3726
3969
  }
3727
- async function createVerificationChallenge(client, uaid) {
3728
- const raw = await client.requestJson("/verification/challenge", {
3729
- method: "POST",
3730
- headers: { "content-type": "application/json" },
3731
- body: { uaid }
3970
+ async function popularSearches(client) {
3971
+ const raw = await client.requestJson("/popular", {
3972
+ method: "GET"
3732
3973
  });
3733
3974
  return client.parseWithSchema(
3734
3975
  raw,
3735
- verificationChallengeResponseSchema,
3736
- "verification challenge response"
3976
+ popularResponseSchema,
3977
+ "popular searches response"
3737
3978
  );
3738
3979
  }
3739
- async function getVerificationChallenge(client, challengeId) {
3740
- const raw = await client.requestJson(
3741
- `/verification/challenge/${encodeURIComponent(challengeId)}`,
3742
- { method: "GET" }
3743
- );
3980
+ async function listProtocols(client) {
3981
+ const raw = await client.requestJson("/protocols", {
3982
+ method: "GET"
3983
+ });
3744
3984
  return client.parseWithSchema(
3745
3985
  raw,
3746
- verificationChallengeDetailsResponseSchema,
3747
- "verification challenge details response"
3986
+ protocolsResponseSchema,
3987
+ "protocols response"
3748
3988
  );
3749
3989
  }
3750
- async function verifyVerificationChallenge(client, params) {
3751
- const raw = await client.requestJson("/verification/verify", {
3990
+ async function detectProtocol(client, message) {
3991
+ const raw = await client.requestJson("/detect-protocol", {
3752
3992
  method: "POST",
3753
- headers: { "content-type": "application/json" },
3754
- body: {
3755
- challengeId: params.challengeId,
3756
- method: params.method ?? "moltbook-post"
3757
- }
3993
+ body: { message },
3994
+ headers: { "content-type": "application/json" }
3758
3995
  });
3759
3996
  return client.parseWithSchema(
3760
3997
  raw,
3761
- verificationVerifyResponseSchema,
3762
- "verification verify response"
3763
- );
3764
- }
3765
- async function getVerificationOwnership(client, uaid) {
3766
- const raw = await client.requestJson(
3767
- `/verification/ownership/${encodeURIComponent(uaid)}`,
3768
- { method: "GET" }
3769
- );
3770
- return client.parseWithSchema(
3771
- raw,
3772
- verificationOwnershipResponseSchema,
3773
- "verification ownership response"
3998
+ detectProtocolResponseSchema,
3999
+ "detect protocol response"
3774
4000
  );
3775
4001
  }
3776
- async function verifySenderOwnership(client, uaid) {
4002
+ async function registrySearchByNamespace(client, registry, query) {
4003
+ const params = new URLSearchParams();
4004
+ if (query) {
4005
+ params.set("q", query);
4006
+ }
4007
+ const suffix = params.size > 0 ? `?${params.toString()}` : "";
3777
4008
  const raw = await client.requestJson(
3778
- "/verification/verify-sender",
4009
+ `/registries/${encodeURIComponent(registry)}/search${suffix}`,
3779
4010
  {
3780
- method: "POST",
3781
- headers: { "content-type": "application/json" },
3782
- body: { uaid }
4011
+ method: "GET"
3783
4012
  }
3784
4013
  );
3785
4014
  return client.parseWithSchema(
3786
4015
  raw,
3787
- verificationVerifySenderResponseSchema,
3788
- "verification sender response"
4016
+ registrySearchByNamespaceSchema,
4017
+ "registry search response"
3789
4018
  );
3790
4019
  }
3791
- async function verifyUaidDnsTxt(client, payload) {
3792
- const raw = await client.requestJson("/verification/dns/verify", {
3793
- method: "POST",
3794
- headers: { "content-type": "application/json" },
3795
- body: {
3796
- uaid: payload.uaid,
3797
- ...payload.persist !== void 0 ? { persist: payload.persist } : {}
4020
+ async function vectorSearch(client, request) {
4021
+ try {
4022
+ const raw = await client.requestJson("/search", {
4023
+ method: "POST",
4024
+ body: request,
4025
+ headers: { "content-type": "application/json" }
4026
+ });
4027
+ return client.parseWithSchema(
4028
+ raw,
4029
+ vectorSearchResponseSchema,
4030
+ "vector search response"
4031
+ );
4032
+ } catch (error) {
4033
+ if (error instanceof RegistryBrokerError && error.status === 501) {
4034
+ const fallback = await search(
4035
+ client,
4036
+ buildVectorFallbackSearchParams(request)
4037
+ );
4038
+ return convertSearchResultToVectorResponse(fallback);
3798
4039
  }
4040
+ throw error;
4041
+ }
4042
+ }
4043
+ async function searchStatus(client) {
4044
+ const raw = await client.requestJson("/search/status", {
4045
+ method: "GET"
3799
4046
  });
3800
4047
  return client.parseWithSchema(
3801
4048
  raw,
3802
- verificationDnsStatusResponseSchema,
3803
- "verification dns verify response"
4049
+ searchStatusResponseSchema,
4050
+ "search status response"
3804
4051
  );
3805
4052
  }
3806
- async function getVerificationDnsStatus(client, uaid, query) {
3807
- const params = new URLSearchParams();
3808
- if (query?.refresh !== void 0) {
3809
- params.set("refresh", String(query.refresh));
3810
- }
3811
- if (query?.persist !== void 0) {
3812
- params.set("persist", String(query.persist));
3813
- }
3814
- const queryString = params.toString();
3815
- const path2 = `/verification/dns/status/${encodeURIComponent(uaid)}${queryString ? `?${queryString}` : ""}`;
3816
- const raw = await client.requestJson(path2, {
4053
+ async function websocketStats(client) {
4054
+ const raw = await client.requestJson("/websocket/stats", {
3817
4055
  method: "GET"
3818
4056
  });
3819
4057
  return client.parseWithSchema(
3820
4058
  raw,
3821
- verificationDnsStatusResponseSchema,
3822
- "verification dns status response"
4059
+ websocketStatsResponseSchema,
4060
+ "websocket stats response"
3823
4061
  );
3824
4062
  }
3825
- async function getRegisterStatus(client, uaid) {
3826
- const raw = await client.requestJson(
3827
- `/register/status/${encodeURIComponent(uaid)}`,
3828
- { method: "GET" }
3829
- );
4063
+ async function metricsSummary(client) {
4064
+ const raw = await client.requestJson("/metrics", {
4065
+ method: "GET"
4066
+ });
3830
4067
  return client.parseWithSchema(
3831
4068
  raw,
3832
- registerStatusResponseSchema,
3833
- "register status response"
4069
+ metricsSummaryResponseSchema,
4070
+ "metrics summary response"
3834
4071
  );
3835
4072
  }
3836
- async function registerOwnedMoltbookAgent(client, uaid, request) {
3837
- const raw = await client.requestJson(
3838
- `/register/${encodeURIComponent(uaid)}`,
3839
- {
3840
- method: "PUT",
3841
- headers: { "content-type": "application/json" },
3842
- body: {
3843
- registered: request.registered ?? true,
3844
- ...request.name ? { name: request.name } : {},
3845
- ...request.description ? { description: request.description } : {},
3846
- ...request.endpoint ? { endpoint: request.endpoint } : {},
3847
- ...request.metadata ? { metadata: request.metadata } : {}
3848
- }
3849
- }
3850
- );
4073
+ async function facets(client, adapter) {
4074
+ const params = new URLSearchParams();
4075
+ if (adapter) {
4076
+ params.set("adapter", adapter);
4077
+ }
4078
+ const suffix = params.size > 0 ? `?${params.toString()}` : "";
4079
+ const raw = await client.requestJson(`/search/facets${suffix}`, {
4080
+ method: "GET"
4081
+ });
3851
4082
  return client.parseWithSchema(
3852
4083
  raw,
3853
- moltbookOwnerRegistrationUpdateResponseSchema,
3854
- "moltbook owner registration update response"
4084
+ searchFacetsResponseSchema,
4085
+ "search facets response"
3855
4086
  );
3856
4087
  }
3857
4088
 
@@ -4381,10 +4612,6 @@ async function verifySkillDomainProof(client, payload) {
4381
4612
  }
4382
4613
 
4383
4614
  // ../../src/services/registry-broker/client/base-client.ts
4384
- var import_buffer4 = require("buffer");
4385
- var import_crypto2 = require("crypto");
4386
- var import_secp256k12 = require("@noble/curves/secp256k1.js");
4387
- var import_zod3 = require("zod");
4388
4615
  var RegistryBrokerClient = class _RegistryBrokerClient {
4389
4616
  constructor(options = {}) {
4390
4617
  this.encryptionBootstrapPromise = null;
@@ -4501,11 +4728,11 @@ var RegistryBrokerClient = class _RegistryBrokerClient {
4501
4728
  }
4502
4729
  await this.encryptionBootstrapPromise;
4503
4730
  }
4504
- buildUrl(path2) {
4505
- const normalisedPath = path2.startsWith("/") ? path2 : `/${path2}`;
4731
+ buildUrl(path) {
4732
+ const normalisedPath = path.startsWith("/") ? path : `/${path}`;
4506
4733
  return `${this.baseUrl}${normalisedPath}`;
4507
4734
  }
4508
- async request(path2, config) {
4735
+ async request(path, config) {
4509
4736
  const headers = new Headers();
4510
4737
  Object.entries(this.defaultHeaders).forEach(([key, value]) => {
4511
4738
  headers.set(key, value);
@@ -4531,7 +4758,7 @@ var RegistryBrokerClient = class _RegistryBrokerClient {
4531
4758
  headers.set("content-type", "application/json");
4532
4759
  }
4533
4760
  }
4534
- const response = await this.fetchImpl(this.buildUrl(path2), init);
4761
+ const response = await this.fetchImpl(this.buildUrl(path), init);
4535
4762
  if (response.ok) {
4536
4763
  return response;
4537
4764
  }
@@ -4542,8 +4769,8 @@ var RegistryBrokerClient = class _RegistryBrokerClient {
4542
4769
  body: errorBody
4543
4770
  });
4544
4771
  }
4545
- async requestJson(path2, config) {
4546
- const response = await this.request(path2, config);
4772
+ async requestJson(path, config) {
4773
+ const response = await this.request(path, config);
4547
4774
  const contentType = response.headers?.get("content-type") ?? "";
4548
4775
  if (!JSON_CONTENT_TYPE.test(contentType)) {
4549
4776
  const body = await response.text();
@@ -4654,6 +4881,9 @@ var RegistryBrokerClient = class _RegistryBrokerClient {
4654
4881
  async search(params = {}) {
4655
4882
  return search(this, params);
4656
4883
  }
4884
+ async delegate(request) {
4885
+ return delegate(this, request);
4886
+ }
4657
4887
  async searchErc8004ByAgentId(params) {
4658
4888
  const chainId = Math.floor(params.chainId);
4659
4889
  if (!Number.isFinite(chainId) || chainId <= 0) {
@@ -5110,12 +5340,12 @@ var RegistryBrokerClient = class _RegistryBrokerClient {
5110
5340
  }
5111
5341
  return;
5112
5342
  }
5113
- await new Promise((resolve2, reject) => {
5343
+ await new Promise((resolve, reject) => {
5114
5344
  const timer = setTimeout(() => {
5115
5345
  if (signal) {
5116
5346
  signal.removeEventListener("abort", onAbort);
5117
5347
  }
5118
- resolve2();
5348
+ resolve();
5119
5349
  }, ms);
5120
5350
  const onAbort = () => {
5121
5351
  clearTimeout(timer);
@@ -5137,9 +5367,17 @@ var RegistryBrokerClient = class _RegistryBrokerClient {
5137
5367
  throw new Error(`${feature} is only available in Node.js environments`);
5138
5368
  }
5139
5369
  }
5370
+ getNodeCrypto(feature) {
5371
+ this.assertNodeRuntime(feature);
5372
+ const nodeCrypto = optionalImportSync("node:crypto") ?? optionalImportSync("crypto");
5373
+ if (!nodeCrypto) {
5374
+ throw new Error(`${feature} requires the Node.js crypto module`);
5375
+ }
5376
+ return nodeCrypto;
5377
+ }
5140
5378
  createEphemeralKeyPair() {
5141
- this.assertNodeRuntime("generateEphemeralKeyPair");
5142
- const privateKeyBytes = (0, import_crypto2.randomBytes)(32);
5379
+ const { randomBytes } = this.getNodeCrypto("generateEphemeralKeyPair");
5380
+ const privateKeyBytes = randomBytes(32);
5143
5381
  const publicKey = import_secp256k12.secp256k1.getPublicKey(privateKeyBytes, true);
5144
5382
  return {
5145
5383
  privateKey: import_buffer4.Buffer.from(privateKeyBytes).toString("hex"),
@@ -5147,17 +5385,19 @@ var RegistryBrokerClient = class _RegistryBrokerClient {
5147
5385
  };
5148
5386
  }
5149
5387
  deriveSharedSecret(options) {
5150
- this.assertNodeRuntime("deriveSharedSecret");
5388
+ const { createHash } = this.getNodeCrypto("deriveSharedSecret");
5151
5389
  const privateKey = this.hexToBuffer(options.privateKey);
5152
5390
  const peerPublicKey = this.hexToBuffer(options.peerPublicKey);
5153
5391
  const shared = import_secp256k12.secp256k1.getSharedSecret(privateKey, peerPublicKey, true);
5154
- return (0, import_crypto2.createHash)("sha256").update(import_buffer4.Buffer.from(shared)).digest();
5392
+ return createHash("sha256").update(import_buffer4.Buffer.from(shared)).digest();
5155
5393
  }
5156
5394
  buildCipherEnvelope(options) {
5157
- this.assertNodeRuntime("encryptCipherEnvelope");
5395
+ const { createCipheriv, randomBytes } = this.getNodeCrypto(
5396
+ "encryptCipherEnvelope"
5397
+ );
5158
5398
  const sharedSecret = this.normalizeSharedSecret(options.sharedSecret);
5159
- const iv = (0, import_crypto2.randomBytes)(12);
5160
- const cipher = (0, import_crypto2.createCipheriv)("aes-256-gcm", sharedSecret, iv);
5399
+ const iv = randomBytes(12);
5400
+ const cipher = createCipheriv("aes-256-gcm", sharedSecret, iv);
5161
5401
  const aadSource = options.associatedData ?? options.sessionId;
5162
5402
  const associatedDataEncoded = aadSource ? import_buffer4.Buffer.from(aadSource, "utf8").toString("base64") : void 0;
5163
5403
  if (aadSource) {
@@ -5185,13 +5425,13 @@ var RegistryBrokerClient = class _RegistryBrokerClient {
5185
5425
  };
5186
5426
  }
5187
5427
  openCipherEnvelope(options) {
5188
- this.assertNodeRuntime("decryptCipherEnvelope");
5428
+ const { createDecipheriv } = this.getNodeCrypto("decryptCipherEnvelope");
5189
5429
  const sharedSecret = this.normalizeSharedSecret(options.sharedSecret);
5190
5430
  const payload = import_buffer4.Buffer.from(options.envelope.ciphertext, "base64");
5191
5431
  const nonce = import_buffer4.Buffer.from(options.envelope.nonce, "base64");
5192
5432
  const ciphertext = payload.slice(0, payload.length - 16);
5193
5433
  const tag = payload.slice(payload.length - 16);
5194
- const decipher = (0, import_crypto2.createDecipheriv)("aes-256-gcm", sharedSecret, nonce);
5434
+ const decipher = createDecipheriv("aes-256-gcm", sharedSecret, nonce);
5195
5435
  if (options.envelope.associatedData) {
5196
5436
  decipher.setAAD(import_buffer4.Buffer.from(options.envelope.associatedData, "base64"));
5197
5437
  }
@@ -5367,11 +5607,21 @@ var buildJobStatusMessage = (input) => JSON.stringify({
5367
5607
  buildPaymentApproveMessage,
5368
5608
  buildPaymentDeclineMessage,
5369
5609
  canonicalizeLedgerNetwork,
5610
+ closeUaidConnection,
5370
5611
  createPrivateKeySigner,
5371
5612
  createPrivateKeySignerAsync,
5613
+ dashboardStats,
5614
+ getRegistrationProgress,
5615
+ getRegistrationQuote,
5616
+ getUaidConnectionStatus,
5372
5617
  isHolChatOp,
5373
5618
  isPartialRegisterAgentResponse,
5374
5619
  isPendingRegisterAgentResponse,
5375
5620
  isSuccessRegisterAgentResponse,
5376
- parseHolChatOps
5621
+ parseHolChatOps,
5622
+ registerAgent,
5623
+ resolveUaid,
5624
+ updateAgent,
5625
+ validateUaid,
5626
+ waitForRegistrationCompletion
5377
5627
  });