@hashgraphonline/standards-sdk 0.1.141-canary.12 → 0.1.141-canary.13

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 (180) hide show
  1. package/dist/cjs/hcs-21/base-client.d.ts.map +1 -1
  2. package/dist/cjs/hcs-21/index.d.ts +1 -0
  3. package/dist/cjs/hcs-21/index.d.ts.map +1 -1
  4. package/dist/cjs/hcs-21/tx.d.ts.map +1 -1
  5. package/dist/cjs/hcs-21/verify.d.ts +6 -0
  6. package/dist/cjs/hcs-21/verify.d.ts.map +1 -0
  7. package/dist/cjs/standards-sdk.cjs +1 -1
  8. package/dist/cjs/standards-sdk.cjs.map +1 -1
  9. package/dist/es/hcs-21/base-client.d.ts.map +1 -1
  10. package/dist/es/hcs-21/index.d.ts +1 -0
  11. package/dist/es/hcs-21/index.d.ts.map +1 -1
  12. package/dist/es/hcs-21/tx.d.ts.map +1 -1
  13. package/dist/es/hcs-21/verify.d.ts +6 -0
  14. package/dist/es/hcs-21/verify.d.ts.map +1 -0
  15. package/dist/es/standards-sdk.es.js +53 -48
  16. package/dist/es/standards-sdk.es.js.map +1 -1
  17. package/dist/es/standards-sdk.es10.js +2 -2
  18. package/dist/es/standards-sdk.es100.js +26 -229
  19. package/dist/es/standards-sdk.es100.js.map +1 -1
  20. package/dist/es/standards-sdk.es101.js +228 -109
  21. package/dist/es/standards-sdk.es101.js.map +1 -1
  22. package/dist/es/standards-sdk.es102.js +94 -15
  23. package/dist/es/standards-sdk.es102.js.map +1 -1
  24. package/dist/es/standards-sdk.es103.js +30 -80
  25. package/dist/es/standards-sdk.es103.js.map +1 -1
  26. package/dist/es/standards-sdk.es104.js +80 -27
  27. package/dist/es/standards-sdk.es104.js.map +1 -1
  28. package/dist/es/standards-sdk.es105.js +25 -136
  29. package/dist/es/standards-sdk.es105.js.map +1 -1
  30. package/dist/es/standards-sdk.es106.js +140 -27
  31. package/dist/es/standards-sdk.es106.js.map +1 -1
  32. package/dist/es/standards-sdk.es107.js +27 -20
  33. package/dist/es/standards-sdk.es107.js.map +1 -1
  34. package/dist/es/standards-sdk.es108.js +18 -156
  35. package/dist/es/standards-sdk.es108.js.map +1 -1
  36. package/dist/es/standards-sdk.es109.js +148 -196
  37. package/dist/es/standards-sdk.es109.js.map +1 -1
  38. package/dist/es/standards-sdk.es110.js +165 -747
  39. package/dist/es/standards-sdk.es110.js.map +1 -1
  40. package/dist/es/standards-sdk.es111.js +786 -9
  41. package/dist/es/standards-sdk.es111.js.map +1 -1
  42. package/dist/es/standards-sdk.es112.js +13 -567
  43. package/dist/es/standards-sdk.es112.js.map +1 -1
  44. package/dist/es/standards-sdk.es113.js +541 -576
  45. package/dist/es/standards-sdk.es113.js.map +1 -1
  46. package/dist/es/standards-sdk.es114.js +601 -12
  47. package/dist/es/standards-sdk.es114.js.map +1 -1
  48. package/dist/es/standards-sdk.es115.js +13 -2
  49. package/dist/es/standards-sdk.es115.js.map +1 -1
  50. package/dist/es/standards-sdk.es116.js +2 -83
  51. package/dist/es/standards-sdk.es116.js.map +1 -1
  52. package/dist/es/standards-sdk.es117.js +80 -36
  53. package/dist/es/standards-sdk.es117.js.map +1 -1
  54. package/dist/es/standards-sdk.es118.js +39 -2
  55. package/dist/es/standards-sdk.es118.js.map +1 -1
  56. package/dist/es/standards-sdk.es119.js +2 -223
  57. package/dist/es/standards-sdk.es119.js.map +1 -1
  58. package/dist/es/standards-sdk.es12.js +1 -1
  59. package/dist/es/standards-sdk.es120.js +193 -1110
  60. package/dist/es/standards-sdk.es120.js.map +1 -1
  61. package/dist/es/standards-sdk.es121.js +1059 -225
  62. package/dist/es/standards-sdk.es121.js.map +1 -1
  63. package/dist/es/standards-sdk.es122.js +303 -419
  64. package/dist/es/standards-sdk.es122.js.map +1 -1
  65. package/dist/es/standards-sdk.es123.js +418 -351
  66. package/dist/es/standards-sdk.es123.js.map +1 -1
  67. package/dist/es/standards-sdk.es124.js +348 -818
  68. package/dist/es/standards-sdk.es124.js.map +1 -1
  69. package/dist/es/standards-sdk.es125.js +804 -187
  70. package/dist/es/standards-sdk.es125.js.map +1 -1
  71. package/dist/es/standards-sdk.es126.js +153 -1512
  72. package/dist/es/standards-sdk.es126.js.map +1 -1
  73. package/dist/es/standards-sdk.es127.js +1373 -1987
  74. package/dist/es/standards-sdk.es127.js.map +1 -1
  75. package/dist/es/standards-sdk.es128.js +2174 -65
  76. package/dist/es/standards-sdk.es128.js.map +1 -1
  77. package/dist/es/standards-sdk.es129.js +64 -79
  78. package/dist/es/standards-sdk.es129.js.map +1 -1
  79. package/dist/es/standards-sdk.es13.js +1 -1
  80. package/dist/es/standards-sdk.es130.js +80 -152
  81. package/dist/es/standards-sdk.es130.js.map +1 -1
  82. package/dist/es/standards-sdk.es131.js +159 -7
  83. package/dist/es/standards-sdk.es131.js.map +1 -1
  84. package/dist/es/standards-sdk.es132.js +7 -86
  85. package/dist/es/standards-sdk.es132.js.map +1 -1
  86. package/dist/es/standards-sdk.es133.js +65 -44
  87. package/dist/es/standards-sdk.es133.js.map +1 -1
  88. package/dist/es/standards-sdk.es134.js +65 -28
  89. package/dist/es/standards-sdk.es134.js.map +1 -1
  90. package/dist/es/standards-sdk.es135.js +28 -138
  91. package/dist/es/standards-sdk.es135.js.map +1 -1
  92. package/dist/es/standards-sdk.es136.js +12265 -33
  93. package/dist/es/standards-sdk.es136.js.map +1 -1
  94. package/dist/es/standards-sdk.es137.js +746 -12254
  95. package/dist/es/standards-sdk.es137.js.map +1 -1
  96. package/dist/es/standards-sdk.es138.js +138 -766
  97. package/dist/es/standards-sdk.es138.js.map +1 -1
  98. package/dist/es/standards-sdk.es139.js +40 -15
  99. package/dist/es/standards-sdk.es139.js.map +1 -1
  100. package/dist/es/standards-sdk.es14.js +1 -1
  101. package/dist/es/standards-sdk.es141.js +1 -1
  102. package/dist/es/standards-sdk.es148.js +20 -0
  103. package/dist/es/standards-sdk.es148.js.map +1 -0
  104. package/dist/es/standards-sdk.es15.js +1 -1
  105. package/dist/es/standards-sdk.es16.js +1 -1
  106. package/dist/es/standards-sdk.es17.js +5 -5
  107. package/dist/es/standards-sdk.es19.js +12 -12
  108. package/dist/es/standards-sdk.es20.js +9 -9
  109. package/dist/es/standards-sdk.es21.js +1 -1
  110. package/dist/es/standards-sdk.es22.js +1 -1
  111. package/dist/es/standards-sdk.es23.js +1 -1
  112. package/dist/es/standards-sdk.es24.js +1 -1
  113. package/dist/es/standards-sdk.es25.js +1 -1
  114. package/dist/es/standards-sdk.es26.js +1 -1
  115. package/dist/es/standards-sdk.es27.js +1 -1
  116. package/dist/es/standards-sdk.es28.js +12 -12
  117. package/dist/es/standards-sdk.es3.js +2 -2
  118. package/dist/es/standards-sdk.es31.js +2 -2
  119. package/dist/es/standards-sdk.es32.js +4 -4
  120. package/dist/es/standards-sdk.es33.js +1 -1
  121. package/dist/es/standards-sdk.es36.js +6 -6
  122. package/dist/es/standards-sdk.es37.js +4 -4
  123. package/dist/es/standards-sdk.es38.js +2 -2
  124. package/dist/es/standards-sdk.es39.js +2 -2
  125. package/dist/es/standards-sdk.es40.js +1 -1
  126. package/dist/es/standards-sdk.es41.js +1 -1
  127. package/dist/es/standards-sdk.es42.js +2 -2
  128. package/dist/es/standards-sdk.es47.js +1 -1
  129. package/dist/es/standards-sdk.es5.js +2 -2
  130. package/dist/es/standards-sdk.es52.js +1 -1
  131. package/dist/es/standards-sdk.es54.js +1 -1
  132. package/dist/es/standards-sdk.es57.js +1 -1
  133. package/dist/es/standards-sdk.es6.js +2 -2
  134. package/dist/es/standards-sdk.es61.js +7 -7
  135. package/dist/es/standards-sdk.es65.js +2 -2
  136. package/dist/es/standards-sdk.es66.js +3 -3
  137. package/dist/es/standards-sdk.es69.js +2 -2
  138. package/dist/es/standards-sdk.es7.js +2 -2
  139. package/dist/es/standards-sdk.es70.js +3 -3
  140. package/dist/es/standards-sdk.es71.js +2 -2
  141. package/dist/es/standards-sdk.es72.js +1 -1
  142. package/dist/es/standards-sdk.es75.js +2 -2
  143. package/dist/es/standards-sdk.es77.js +2 -2
  144. package/dist/es/standards-sdk.es78.js +4 -4
  145. package/dist/es/standards-sdk.es79.js +1 -1
  146. package/dist/es/standards-sdk.es8.js +1 -1
  147. package/dist/es/standards-sdk.es82.js +10 -2
  148. package/dist/es/standards-sdk.es82.js.map +1 -1
  149. package/dist/es/standards-sdk.es83.js +5 -5
  150. package/dist/es/standards-sdk.es83.js.map +1 -1
  151. package/dist/es/standards-sdk.es84.js +4 -4
  152. package/dist/es/standards-sdk.es86.js +55 -21
  153. package/dist/es/standards-sdk.es86.js.map +1 -1
  154. package/dist/es/standards-sdk.es87.js +22 -75
  155. package/dist/es/standards-sdk.es87.js.map +1 -1
  156. package/dist/es/standards-sdk.es88.js +45 -30
  157. package/dist/es/standards-sdk.es88.js.map +1 -1
  158. package/dist/es/standards-sdk.es89.js +57 -22
  159. package/dist/es/standards-sdk.es89.js.map +1 -1
  160. package/dist/es/standards-sdk.es90.js +28 -23
  161. package/dist/es/standards-sdk.es90.js.map +1 -1
  162. package/dist/es/standards-sdk.es91.js +23 -167
  163. package/dist/es/standards-sdk.es91.js.map +1 -1
  164. package/dist/es/standards-sdk.es92.js +158 -119
  165. package/dist/es/standards-sdk.es92.js.map +1 -1
  166. package/dist/es/standards-sdk.es93.js +68 -95
  167. package/dist/es/standards-sdk.es93.js.map +1 -1
  168. package/dist/es/standards-sdk.es94.js +136 -119
  169. package/dist/es/standards-sdk.es94.js.map +1 -1
  170. package/dist/es/standards-sdk.es95.js +134 -39
  171. package/dist/es/standards-sdk.es95.js.map +1 -1
  172. package/dist/es/standards-sdk.es96.js +40 -258
  173. package/dist/es/standards-sdk.es96.js.map +1 -1
  174. package/dist/es/standards-sdk.es97.js +243 -80
  175. package/dist/es/standards-sdk.es97.js.map +1 -1
  176. package/dist/es/standards-sdk.es98.js +47 -48
  177. package/dist/es/standards-sdk.es98.js.map +1 -1
  178. package/dist/es/standards-sdk.es99.js +100 -28
  179. package/dist/es/standards-sdk.es99.js.map +1 -1
  180. package/package.json +1 -1
@@ -1,75 +1,2184 @@
1
+ import * as path from "node:path";
2
+ import { Buffer } from "node:buffer";
3
+ import { randomBytes, createHash, createCipheriv, createDecipheriv } from "node:crypto";
1
4
  import { createRequire } from "node:module";
2
- const unsupported = (method) => new Error(`${method} is not supported by the in-memory signer`);
3
- const createPrivateKeySigner = (options) => {
4
- const sdk = loadHashgraphSdk();
5
- const { AccountId, LedgerId, PrivateKey, SignerSignature } = sdk;
6
- if (!options.privateKey) {
7
- throw new Error("privateKey is required to create a ledger signer.");
8
- }
9
- if (!options.accountId) {
10
- throw new Error("accountId is required to create a ledger signer.");
11
- }
12
- const accountId = AccountId.fromString(options.accountId);
13
- const privateKey = PrivateKey.fromString(options.privateKey);
14
- const ledgerId = LedgerId.fromString(options.network);
15
- return {
16
- getLedgerId: () => ledgerId,
17
- getAccountId: () => accountId,
18
- getAccountKey: () => privateKey.publicKey,
19
- getNetwork: () => ({}),
20
- getMirrorNetwork: () => [],
21
- sign: async (messages) => Promise.all(
22
- messages.map(async (message) => {
23
- const signature = await privateKey.sign(message);
24
- return new SignerSignature({
25
- publicKey: privateKey.publicKey,
26
- signature,
27
- accountId
28
- });
29
- })
30
- ),
31
- getAccountBalance: async () => {
32
- throw unsupported("getAccountBalance");
33
- },
34
- getAccountInfo: async () => {
35
- throw unsupported("getAccountInfo");
36
- },
37
- getAccountRecords: async () => {
38
- throw unsupported("getAccountRecords");
39
- },
40
- signTransaction: async (_) => {
41
- throw unsupported("signTransaction");
42
- },
43
- checkTransaction: async (_) => {
44
- throw unsupported("checkTransaction");
45
- },
46
- populateTransaction: async (_) => {
47
- throw unsupported("populateTransaction");
48
- },
49
- call: async (_request) => {
50
- throw unsupported("call");
5
+ import { secp256k1 } from "@noble/curves/secp256k1.js";
6
+ import { canonicalizeLedgerNetwork } from "./standards-sdk.es130.js";
7
+ import axios from "axios";
8
+ import { privateKeyToAccount } from "viem/accounts";
9
+ import "viem/chains";
10
+ import { withPaymentInterceptor, decodeXPaymentResponse } from "x402-axios";
11
+ import { createSigner } from "x402/types";
12
+ import { searchResponseSchema, statsResponseSchema, registriesResponseSchema, additionalRegistryCatalogResponseSchema, popularResponseSchema, resolveResponseSchema, registerAgentResponseSchema, registrationQuoteResponseSchema, registrationProgressResponseSchema, creditPurchaseResponseSchema, x402MinimumsResponseSchema, x402CreditPurchaseResponseSchema, ledgerChallengeResponseSchema, ledgerVerifyResponseSchema, protocolsResponseSchema, detectProtocolResponseSchema, registrySearchByNamespaceSchema, vectorSearchResponseSchema, searchStatusResponseSchema, adapterDetailsResponseSchema, websocketStatsResponseSchema, metricsSummaryResponseSchema, uaidValidationResponseSchema, uaidConnectionStatusSchema, dashboardStatsResponseSchema, adaptersResponseSchema, searchFacetsResponseSchema, createSessionResponseSchema, chatHistorySnapshotResponseSchema, chatHistoryCompactionResponseSchema, sessionEncryptionStatusResponseSchema, encryptionHandshakeResponseSchema, registerEncryptionKeyResponseSchema, sendMessageResponseSchema } from "./standards-sdk.es137.js";
13
+ import { ZodError } from "zod";
14
+ import { createPrivateKeySigner } from "./standards-sdk.es129.js";
15
+ const createNodeRequire = () => {
16
+ const metaUrl = typeof import.meta !== "undefined" && typeof import.meta.url === "string" ? import.meta.url : void 0;
17
+ try {
18
+ return createRequire(metaUrl ?? `${process.cwd()}/.hol-rb-client.cjs`);
19
+ } catch {
20
+ return null;
21
+ }
22
+ };
23
+ const getFs = () => {
24
+ const loader = createNodeRequire();
25
+ if (!loader) {
26
+ return null;
27
+ }
28
+ try {
29
+ const fsModule = loader("node:fs");
30
+ if (fsModule && typeof fsModule.existsSync === "function" && typeof fsModule.readFileSync === "function" && typeof fsModule.writeFileSync === "function" && typeof fsModule.appendFileSync === "function") {
31
+ return fsModule;
51
32
  }
33
+ } catch {
34
+ }
35
+ return null;
36
+ };
37
+ const DEFAULT_USER_AGENT = "@hol-org/rb-client";
38
+ const DEFAULT_PROGRESS_INTERVAL_MS = 1500;
39
+ const DEFAULT_PROGRESS_TIMEOUT_MS = 5 * 60 * 1e3;
40
+ const createAbortError = () => typeof DOMException === "function" ? new DOMException("Aborted", "AbortError") : new Error("The operation was aborted");
41
+ const normaliseHeaderName = (name) => name.trim().toLowerCase();
42
+ const isBrowserRuntime = () => typeof window !== "undefined" && typeof window.fetch === "function";
43
+ const DEFAULT_BASE_URL = "https://hol.org/registry/api/v1";
44
+ const JSON_CONTENT_TYPE = /application\/json/i;
45
+ const DEFAULT_HISTORY_TOP_UP_HBAR = 0.25;
46
+ const MINIMUM_REGISTRATION_AUTO_TOP_UP_CREDITS = 1;
47
+ const toJsonValue = (value) => {
48
+ if (value === null) {
49
+ return null;
50
+ }
51
+ if (value instanceof Date) {
52
+ return value.toISOString();
53
+ }
54
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
55
+ return value;
56
+ }
57
+ if (Array.isArray(value)) {
58
+ return value.map((item) => item === void 0 ? null : toJsonValue(item));
59
+ }
60
+ if (typeof value === "object") {
61
+ const result = {};
62
+ Object.entries(value).forEach(
63
+ ([key, entryValue]) => {
64
+ if (entryValue !== void 0) {
65
+ result[key] = toJsonValue(entryValue);
66
+ }
67
+ }
68
+ );
69
+ return result;
70
+ }
71
+ throw new TypeError("Only JSON-compatible values are supported");
72
+ };
73
+ const isJsonObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
74
+ const toJsonObject = (value) => {
75
+ const normalised = toJsonValue(value);
76
+ if (isJsonObject(normalised)) {
77
+ return normalised;
78
+ }
79
+ throw new TypeError("Expected JSON object value");
80
+ };
81
+ const serialiseAuthConfig = (auth) => {
82
+ const authPayload = {};
83
+ if (auth.type) {
84
+ authPayload.type = auth.type;
85
+ }
86
+ if (auth.token) {
87
+ authPayload.token = auth.token;
88
+ }
89
+ if (auth.username) {
90
+ authPayload.username = auth.username;
91
+ }
92
+ if (auth.password) {
93
+ authPayload.password = auth.password;
94
+ }
95
+ if (auth.headerName) {
96
+ authPayload.headerName = auth.headerName;
97
+ }
98
+ if (auth.headerValue) {
99
+ authPayload.headerValue = auth.headerValue;
100
+ }
101
+ if (auth.headers) {
102
+ authPayload.headers = { ...auth.headers };
103
+ }
104
+ return authPayload;
105
+ };
106
+ const serialiseAgentRegistrationRequest = (payload) => {
107
+ const body = {
108
+ profile: toJsonObject(payload.profile)
52
109
  };
110
+ if (payload.endpoint !== void 0) {
111
+ body.endpoint = payload.endpoint;
112
+ }
113
+ if (payload.protocol !== void 0) {
114
+ body.protocol = payload.protocol;
115
+ }
116
+ if (payload.communicationProtocol !== void 0) {
117
+ body.communicationProtocol = payload.communicationProtocol;
118
+ }
119
+ if (payload.registry !== void 0) {
120
+ body.registry = payload.registry;
121
+ }
122
+ if (payload.additionalRegistries !== void 0) {
123
+ body.additionalRegistries = payload.additionalRegistries;
124
+ }
125
+ if (payload.metadata !== void 0) {
126
+ body.metadata = toJsonObject(payload.metadata);
127
+ }
128
+ return body;
53
129
  };
54
- let cachedSdk = null;
55
- const loadHashgraphSdk = () => {
56
- if (cachedSdk) {
57
- return cachedSdk;
130
+ const normalizeHexPrivateKey = (value) => {
131
+ const trimmed = value.trim();
132
+ if (!trimmed) {
133
+ throw new Error("evmPrivateKey is required");
58
134
  }
59
- const metaUrl = typeof import.meta !== "undefined" && typeof import.meta.url === "string" ? import.meta.url : void 0;
60
- const loader = createRequire(metaUrl ?? `${process.cwd()}/.hol-rb-client.cjs`);
135
+ return trimmed.startsWith("0x") ? trimmed : `0x${trimmed}`;
136
+ };
137
+ class RegistryBrokerError extends Error {
138
+ constructor(message, details) {
139
+ super(message);
140
+ this.status = details.status;
141
+ this.statusText = details.statusText;
142
+ this.body = details.body;
143
+ }
144
+ }
145
+ class RegistryBrokerParseError extends Error {
146
+ constructor(message, cause, rawValue) {
147
+ super(message);
148
+ this.cause = cause;
149
+ this.rawValue = rawValue;
150
+ }
151
+ }
152
+ function normaliseBaseUrl(input) {
153
+ const trimmed = input?.trim();
154
+ let baseCandidate = trimmed && trimmed.length > 0 ? trimmed : DEFAULT_BASE_URL;
61
155
  try {
62
- const resolved = loader("@hashgraph/sdk");
63
- cachedSdk = resolved;
64
- return resolved;
65
- } catch (error) {
66
- const message = "@hashgraph/sdk is required for ledger signing. Install it as a dependency to enable createPrivateKeySigner.";
67
- const err = new Error(message);
68
- err.cause = error;
69
- throw err;
156
+ const url = new URL(baseCandidate.replace(/\/+$/, ""));
157
+ const hostname = url.hostname.toLowerCase();
158
+ const ensureRegistryPrefix = () => {
159
+ if (!url.pathname.startsWith("/registry")) {
160
+ url.pathname = url.pathname === "/" ? "/registry" : `/registry${url.pathname}`;
161
+ }
162
+ };
163
+ if (hostname === "hol.org") {
164
+ ensureRegistryPrefix();
165
+ baseCandidate = url.toString();
166
+ } else if (hostname === "registry.hashgraphonline.com" || hostname === "hashgraphonline.com") {
167
+ ensureRegistryPrefix();
168
+ url.hostname = "hol.org";
169
+ baseCandidate = url.toString();
170
+ }
171
+ } catch {
70
172
  }
71
- };
173
+ const withoutTrailing = baseCandidate.replace(/\/+$/, "");
174
+ if (/\/api\/v\d+$/i.test(withoutTrailing)) {
175
+ return withoutTrailing;
176
+ }
177
+ if (/\/api$/i.test(withoutTrailing)) {
178
+ return `${withoutTrailing}/v1`;
179
+ }
180
+ return `${withoutTrailing}/api/v1`;
181
+ }
182
+ function buildSearchQuery(params) {
183
+ const query = new URLSearchParams();
184
+ const appendList = (key, values) => {
185
+ if (!values) {
186
+ return;
187
+ }
188
+ values.forEach((value) => {
189
+ if (typeof value === "string") {
190
+ const trimmed = value.trim();
191
+ if (trimmed.length > 0) {
192
+ query.append(key, trimmed);
193
+ }
194
+ }
195
+ });
196
+ };
197
+ if (params.q) {
198
+ const trimmed = params.q.trim();
199
+ if (trimmed.length > 0) {
200
+ query.set("q", trimmed);
201
+ }
202
+ }
203
+ if (typeof params.page === "number") {
204
+ query.set("page", params.page.toString());
205
+ }
206
+ if (typeof params.limit === "number") {
207
+ query.set("limit", params.limit.toString());
208
+ }
209
+ if (params.registry) {
210
+ const trimmed = params.registry.trim();
211
+ if (trimmed.length > 0) {
212
+ query.set("registry", trimmed);
213
+ }
214
+ }
215
+ appendList("registries", params.registries);
216
+ if (typeof params.minTrust === "number") {
217
+ query.set("minTrust", params.minTrust.toString());
218
+ }
219
+ appendList("capabilities", params.capabilities);
220
+ appendList("protocols", params.protocols);
221
+ appendList("adapters", params.adapters);
222
+ if (params.metadata) {
223
+ Object.entries(params.metadata).forEach(([key, values]) => {
224
+ if (!key || !Array.isArray(values) || values.length === 0) {
225
+ return;
226
+ }
227
+ const trimmedKey = key.trim();
228
+ if (trimmedKey.length === 0) {
229
+ return;
230
+ }
231
+ values.forEach((value) => {
232
+ if (value === void 0 || value === null) {
233
+ return;
234
+ }
235
+ query.append(`metadata.${trimmedKey}`, String(value));
236
+ });
237
+ });
238
+ }
239
+ if (params.type) {
240
+ const trimmedType = params.type.trim();
241
+ if (trimmedType.length > 0 && trimmedType.toLowerCase() !== "all") {
242
+ query.set("type", trimmedType);
243
+ }
244
+ }
245
+ if (params.verified === true) {
246
+ query.set("verified", "true");
247
+ }
248
+ if (params.online === true) {
249
+ query.set("online", "true");
250
+ }
251
+ if (params.sortBy) {
252
+ const trimmedSort = params.sortBy.trim();
253
+ if (trimmedSort.length > 0) {
254
+ query.set("sortBy", trimmedSort);
255
+ }
256
+ }
257
+ if (params.sortOrder) {
258
+ const lowered = params.sortOrder.toLowerCase();
259
+ if (lowered === "asc" || lowered === "desc") {
260
+ query.set("sortOrder", lowered);
261
+ }
262
+ }
263
+ const queryString = query.toString();
264
+ return queryString.length > 0 ? `?${queryString}` : "";
265
+ }
266
+ class RegistryBrokerClient {
267
+ constructor(options = {}) {
268
+ this.conversationContexts = /* @__PURE__ */ new Map();
269
+ this.request = async (path2, config) => {
270
+ const headers = new Headers();
271
+ Object.entries(this.defaultHeaders).forEach(([key, value]) => {
272
+ headers.set(key, value);
273
+ });
274
+ if (config.headers) {
275
+ Object.entries(config.headers).forEach(([key, value]) => {
276
+ headers.set(key, value);
277
+ });
278
+ }
279
+ if (!headers.has("accept")) {
280
+ headers.set("accept", "application/json");
281
+ }
282
+ if (!headers.has("user-agent") && !isBrowserRuntime()) {
283
+ headers.set("user-agent", DEFAULT_USER_AGENT);
284
+ }
285
+ const init = {
286
+ method: config.method ?? "GET",
287
+ headers
288
+ };
289
+ if (config.body !== void 0) {
290
+ init.body = JSON.stringify(config.body);
291
+ if (!headers.has("content-type")) {
292
+ headers.set("content-type", "application/json");
293
+ }
294
+ }
295
+ const response = await this.fetchImpl(this.buildUrl(path2), init);
296
+ if (response.ok) {
297
+ return response;
298
+ }
299
+ const errorBody = await this.extractErrorBody(response);
300
+ throw new RegistryBrokerError("Registry broker request failed", {
301
+ status: response.status,
302
+ statusText: response.statusText,
303
+ body: errorBody
304
+ });
305
+ };
306
+ this.baseUrl = normaliseBaseUrl(options.baseUrl);
307
+ const fetchCandidate = options.fetchImplementation ?? globalThis.fetch;
308
+ if (!fetchCandidate) {
309
+ throw new Error(
310
+ "A fetch implementation is required for RegistryBrokerClient"
311
+ );
312
+ }
313
+ this.fetchImpl = fetchCandidate;
314
+ this.defaultHeaders = {};
315
+ if (options.defaultHeaders) {
316
+ Object.entries(options.defaultHeaders).forEach(([name, value]) => {
317
+ if (typeof value === "string") {
318
+ this.setDefaultHeader(name, value);
319
+ }
320
+ });
321
+ }
322
+ if (options.apiKey && options.apiKey.trim().length > 0) {
323
+ this.setApiKey(options.apiKey);
324
+ }
325
+ if (options.ledgerApiKey && options.ledgerApiKey.trim().length > 0) {
326
+ this.setLedgerApiKey(options.ledgerApiKey);
327
+ }
328
+ this.registrationAutoTopUp = options.registrationAutoTopUp;
329
+ this.historyAutoTopUp = options.historyAutoTopUp;
330
+ this.encryptedChatManager = new EncryptedChatManager(this);
331
+ this.encryptionOptions = options.encryption;
332
+ this.encryptionBootstrapPromise = this.bootstrapEncryptionOptions(
333
+ options.encryption
334
+ );
335
+ this.chat = {
336
+ start: (options2) => this.startChat(options2),
337
+ createSession: (payload) => this.createSession(payload),
338
+ sendMessage: (payload) => this.sendMessage(payload),
339
+ endSession: (sessionId) => this.endSession(sessionId),
340
+ getHistory: (sessionId, options2) => this.fetchHistorySnapshot(sessionId, options2),
341
+ compactHistory: (payload) => this.compactHistory(payload),
342
+ getEncryptionStatus: (sessionId) => this.fetchEncryptionStatus(sessionId),
343
+ submitEncryptionHandshake: (sessionId, payload) => this.postEncryptionHandshake(sessionId, payload),
344
+ startConversation: (opts) => this.startConversation(opts),
345
+ acceptConversation: (opts) => this.acceptConversation(opts)
346
+ };
347
+ this.encryption = {
348
+ registerKey: (payload) => this.registerEncryptionKey(payload),
349
+ generateEphemeralKeyPair: () => this.createEphemeralKeyPair(),
350
+ deriveSharedSecret: (options2) => this.deriveSharedSecret(options2),
351
+ encryptCipherEnvelope: (options2) => this.buildCipherEnvelope(options2),
352
+ decryptCipherEnvelope: (options2) => this.openCipherEnvelope(options2),
353
+ ensureAgentKey: (options2) => this.ensureAgentEncryptionKey(options2)
354
+ };
355
+ this.chat.createEncryptedSession = (options2) => this.encryptedChatManager.startSession(options2);
356
+ this.chat.acceptEncryptedSession = (options2) => this.encryptedChatManager.acceptSession(options2);
357
+ }
358
+ static async initializeAgent(options) {
359
+ const { uaid, ensureEncryptionKey = true, ...clientOptions } = options;
360
+ const client = new RegistryBrokerClient(clientOptions);
361
+ let encryption = null;
362
+ if (ensureEncryptionKey) {
363
+ const ensureOptions = typeof ensureEncryptionKey === "object" ? ensureEncryptionKey : { generateIfMissing: true };
364
+ encryption = await client.encryption.ensureAgentKey({
365
+ uaid,
366
+ ...ensureOptions
367
+ });
368
+ }
369
+ return { client, encryption };
370
+ }
371
+ setApiKey(apiKey) {
372
+ this.setDefaultHeader("x-api-key", apiKey);
373
+ }
374
+ setLedgerApiKey(apiKey) {
375
+ this.setDefaultHeader("x-ledger-api-key", apiKey);
376
+ }
377
+ setDefaultHeader(name, value) {
378
+ if (!name || name.trim().length === 0) {
379
+ return;
380
+ }
381
+ const headerName = normaliseHeaderName(name);
382
+ if (!value || value.trim().length === 0) {
383
+ delete this.defaultHeaders[headerName];
384
+ return;
385
+ }
386
+ this.defaultHeaders[headerName] = value.trim();
387
+ }
388
+ getDefaultHeaders() {
389
+ return { ...this.defaultHeaders };
390
+ }
391
+ async encryptionReady() {
392
+ if (!this.encryptionBootstrapPromise) {
393
+ return;
394
+ }
395
+ await this.encryptionBootstrapPromise;
396
+ }
397
+ async search(params = {}) {
398
+ const query = buildSearchQuery(params);
399
+ const raw = await this.requestJson(`/search${query}`, {
400
+ method: "GET"
401
+ });
402
+ return this.parseWithSchema(raw, searchResponseSchema, "search response");
403
+ }
404
+ async stats() {
405
+ const raw = await this.requestJson("/stats", { method: "GET" });
406
+ return this.parseWithSchema(raw, statsResponseSchema, "stats response");
407
+ }
408
+ async registries() {
409
+ const raw = await this.requestJson("/registries", {
410
+ method: "GET"
411
+ });
412
+ return this.parseWithSchema(
413
+ raw,
414
+ registriesResponseSchema,
415
+ "registries response"
416
+ );
417
+ }
418
+ async getAdditionalRegistries() {
419
+ const raw = await this.requestJson(
420
+ "/register/additional-registries",
421
+ {
422
+ method: "GET"
423
+ }
424
+ );
425
+ return this.parseWithSchema(
426
+ raw,
427
+ additionalRegistryCatalogResponseSchema,
428
+ "additional registry catalog response"
429
+ );
430
+ }
431
+ bootstrapEncryptionOptions(options) {
432
+ if (!options?.autoRegister || options.autoRegister.enabled === false) {
433
+ return null;
434
+ }
435
+ return this.autoRegisterEncryptionKey(options.autoRegister).then(
436
+ () => void 0
437
+ );
438
+ }
439
+ async autoRegisterEncryptionKey(config) {
440
+ const identity = this.normalizeAutoRegisterIdentity(config);
441
+ if (!identity) {
442
+ throw new Error(
443
+ "Auto-registration requires uaid, ledgerAccountId, or email"
444
+ );
445
+ }
446
+ const material = await this.resolveAutoRegisterKeyMaterial(config);
447
+ if (!material) {
448
+ throw new Error(
449
+ "Unable to resolve encryption public key for auto-registration"
450
+ );
451
+ }
452
+ await this.registerEncryptionKey({
453
+ keyType: config.keyType ?? "secp256k1",
454
+ publicKey: material.publicKey,
455
+ ...identity
456
+ });
457
+ return material;
458
+ }
459
+ normalizeAutoRegisterIdentity(config) {
460
+ const identity = {};
461
+ if (config.uaid) {
462
+ identity.uaid = config.uaid;
463
+ }
464
+ if (config.ledgerAccountId) {
465
+ identity.ledgerAccountId = config.ledgerAccountId;
466
+ if (config.ledgerNetwork) {
467
+ identity.ledgerNetwork = config.ledgerNetwork;
468
+ }
469
+ }
470
+ if (config.email) {
471
+ identity.email = config.email;
472
+ }
473
+ if (identity.uaid || identity.ledgerAccountId || identity.email) {
474
+ return identity;
475
+ }
476
+ return null;
477
+ }
478
+ async resolveAutoRegisterKeyMaterial(config) {
479
+ if (config.publicKey?.trim()) {
480
+ return { publicKey: config.publicKey.trim() };
481
+ }
482
+ let privateKey = config.privateKey?.trim();
483
+ const envVar = config.envVar ?? "RB_ENCRYPTION_PRIVATE_KEY";
484
+ if (!privateKey && envVar && process?.env?.[envVar]?.trim()) {
485
+ privateKey = process.env[envVar]?.trim();
486
+ }
487
+ if (!privateKey && config.generateIfMissing) {
488
+ const pair = await this.generateEncryptionKeyPair({
489
+ keyType: config.keyType ?? "secp256k1",
490
+ envVar,
491
+ envPath: config.envPath,
492
+ overwrite: config.overwriteEnv
493
+ });
494
+ if (envVar) {
495
+ process.env[envVar] = pair.privateKey;
496
+ }
497
+ return { publicKey: pair.publicKey, privateKey: pair.privateKey };
498
+ }
499
+ if (privateKey) {
500
+ const publicKey = this.derivePublicKeyFromPrivateKey(privateKey);
501
+ return { publicKey, privateKey };
502
+ }
503
+ return null;
504
+ }
505
+ derivePublicKeyFromPrivateKey(privateKey) {
506
+ const normalized = this.hexToBuffer(privateKey);
507
+ const publicKey = secp256k1.getPublicKey(normalized, true);
508
+ return Buffer.from(publicKey).toString("hex");
509
+ }
510
+ ensureAgentEncryptionKey(options) {
511
+ return this.autoRegisterEncryptionKey({
512
+ ...options,
513
+ uaid: options.uaid,
514
+ enabled: true
515
+ });
516
+ }
517
+ async popularSearches() {
518
+ const raw = await this.requestJson("/popular", {
519
+ method: "GET"
520
+ });
521
+ return this.parseWithSchema(
522
+ raw,
523
+ popularResponseSchema,
524
+ "popular searches response"
525
+ );
526
+ }
527
+ async resolveUaid(uaid) {
528
+ const raw = await this.requestJson(
529
+ `/resolve/${encodeURIComponent(uaid)}`,
530
+ {
531
+ method: "GET"
532
+ }
533
+ );
534
+ return this.parseWithSchema(
535
+ raw,
536
+ resolveResponseSchema,
537
+ "resolve UAID response"
538
+ );
539
+ }
540
+ async performRegisterAgent(payload) {
541
+ const raw = await this.requestJson("/register", {
542
+ method: "POST",
543
+ body: serialiseAgentRegistrationRequest(payload),
544
+ headers: { "content-type": "application/json" }
545
+ });
546
+ return this.parseWithSchema(
547
+ raw,
548
+ registerAgentResponseSchema,
549
+ "register agent response"
550
+ );
551
+ }
552
+ async registerAgent(payload, options) {
553
+ const autoTopUp = options?.autoTopUp ?? this.registrationAutoTopUp;
554
+ if (!autoTopUp) {
555
+ return this.performRegisterAgent(payload);
556
+ }
557
+ await this.ensureCreditsForRegistration(payload, autoTopUp);
558
+ let retried = false;
559
+ while (true) {
560
+ try {
561
+ return await this.performRegisterAgent(payload);
562
+ } catch (error) {
563
+ const shortfall = this.extractInsufficientCreditsDetails(error);
564
+ if (shortfall && !retried) {
565
+ await this.ensureCreditsForRegistration(payload, autoTopUp);
566
+ retried = true;
567
+ continue;
568
+ }
569
+ throw error;
570
+ }
571
+ }
572
+ }
573
+ async getRegistrationQuote(payload) {
574
+ const raw = await this.requestJson("/register/quote", {
575
+ method: "POST",
576
+ body: serialiseAgentRegistrationRequest(payload),
577
+ headers: { "content-type": "application/json" }
578
+ });
579
+ return this.parseWithSchema(
580
+ raw,
581
+ registrationQuoteResponseSchema,
582
+ "registration quote response"
583
+ );
584
+ }
585
+ async updateAgent(uaid, payload) {
586
+ const raw = await this.requestJson(
587
+ `/register/${encodeURIComponent(uaid)}`,
588
+ {
589
+ method: "PUT",
590
+ body: serialiseAgentRegistrationRequest(payload),
591
+ headers: { "content-type": "application/json" }
592
+ }
593
+ );
594
+ return this.parseWithSchema(
595
+ raw,
596
+ registerAgentResponseSchema,
597
+ "update agent response"
598
+ );
599
+ }
600
+ async getRegistrationProgress(attemptId) {
601
+ const normalisedAttemptId = attemptId.trim();
602
+ if (!normalisedAttemptId) {
603
+ throw new Error("attemptId is required");
604
+ }
605
+ try {
606
+ const raw = await this.requestJson(
607
+ `/register/progress/${encodeURIComponent(normalisedAttemptId)}`,
608
+ { method: "GET" }
609
+ );
610
+ const parsed = this.parseWithSchema(
611
+ raw,
612
+ registrationProgressResponseSchema,
613
+ "registration progress response"
614
+ );
615
+ return parsed.progress;
616
+ } catch (error) {
617
+ if (error instanceof RegistryBrokerError && error.status === 404) {
618
+ return null;
619
+ }
620
+ throw error;
621
+ }
622
+ }
623
+ async waitForRegistrationCompletion(attemptId, options = {}) {
624
+ const normalisedAttemptId = attemptId.trim();
625
+ if (!normalisedAttemptId) {
626
+ throw new Error("attemptId is required");
627
+ }
628
+ const interval = Math.max(
629
+ 250,
630
+ options.intervalMs ?? DEFAULT_PROGRESS_INTERVAL_MS
631
+ );
632
+ const timeoutMs = options.timeoutMs ?? DEFAULT_PROGRESS_TIMEOUT_MS;
633
+ const throwOnFailure = options.throwOnFailure ?? true;
634
+ const signal = options.signal;
635
+ const startedAt = Date.now();
636
+ while (true) {
637
+ if (signal?.aborted) {
638
+ throw createAbortError();
639
+ }
640
+ const progress = await this.getRegistrationProgress(normalisedAttemptId);
641
+ if (progress) {
642
+ options.onProgress?.(progress);
643
+ if (progress.status === "completed") {
644
+ return progress;
645
+ }
646
+ if (progress.status === "partial" || progress.status === "failed") {
647
+ if (throwOnFailure) {
648
+ throw new RegistryBrokerError(
649
+ "Registration did not complete successfully",
650
+ {
651
+ status: 409,
652
+ statusText: progress.status,
653
+ body: progress
654
+ }
655
+ );
656
+ }
657
+ return progress;
658
+ }
659
+ }
660
+ if (Date.now() - startedAt >= timeoutMs) {
661
+ throw new Error(
662
+ `Registration progress polling timed out after ${timeoutMs}ms`
663
+ );
664
+ }
665
+ await this.delay(interval, signal);
666
+ }
667
+ }
668
+ async purchaseCreditsWithHbar(params) {
669
+ const body = {
670
+ accountId: params.accountId,
671
+ payerKey: params.privateKey,
672
+ hbarAmount: this.calculateHbarAmountParam(params.hbarAmount)
673
+ };
674
+ if (params.memo) {
675
+ body.memo = params.memo;
676
+ }
677
+ if (params.metadata) {
678
+ body.metadata = params.metadata;
679
+ }
680
+ const raw = await this.requestJson("/credits/purchase", {
681
+ method: "POST",
682
+ headers: { "content-type": "application/json" },
683
+ body
684
+ });
685
+ return this.parseWithSchema(
686
+ raw,
687
+ creditPurchaseResponseSchema,
688
+ "credit purchase response"
689
+ );
690
+ }
691
+ async getX402Minimums() {
692
+ const raw = await this.requestJson(
693
+ "/credits/purchase/x402/minimums",
694
+ { method: "GET" }
695
+ );
696
+ return this.parseWithSchema(
697
+ raw,
698
+ x402MinimumsResponseSchema,
699
+ "x402 minimums response"
700
+ );
701
+ }
702
+ async purchaseCreditsWithX402(params) {
703
+ if (!Number.isFinite(params.credits) || params.credits <= 0) {
704
+ throw new Error("credits must be a positive number");
705
+ }
706
+ if (params.usdAmount !== void 0 && (!Number.isFinite(params.usdAmount) || params.usdAmount <= 0)) {
707
+ throw new Error("usdAmount must be a positive number when provided");
708
+ }
709
+ const body = {
710
+ accountId: params.accountId,
711
+ credits: params.credits
712
+ };
713
+ if (params.usdAmount !== void 0) {
714
+ body.usdAmount = params.usdAmount;
715
+ }
716
+ if (params.description) {
717
+ body.description = params.description;
718
+ }
719
+ if (params.metadata) {
720
+ body.metadata = params.metadata;
721
+ }
722
+ const axiosClient = axios.create({
723
+ baseURL: this.baseUrl,
724
+ headers: {
725
+ ...this.getDefaultHeaders(),
726
+ "content-type": "application/json"
727
+ }
728
+ });
729
+ const paymentClient = withPaymentInterceptor(
730
+ axiosClient,
731
+ params.walletClient
732
+ );
733
+ const response = await paymentClient.post("/credits/purchase/x402", body);
734
+ const parsed = this.parseWithSchema(
735
+ response.data,
736
+ x402CreditPurchaseResponseSchema,
737
+ "x402 credit purchase response"
738
+ );
739
+ const paymentHeader = typeof response.headers["x-payment-response"] === "string" ? response.headers["x-payment-response"] : void 0;
740
+ const decodedPayment = paymentHeader !== void 0 ? decodeXPaymentResponse(paymentHeader) : void 0;
741
+ return {
742
+ ...parsed,
743
+ paymentResponseHeader: paymentHeader,
744
+ paymentResponse: decodedPayment
745
+ };
746
+ }
747
+ async buyCreditsWithX402(params) {
748
+ const network = params.network ?? "base";
749
+ const normalizedKey = normalizeHexPrivateKey(params.evmPrivateKey);
750
+ const walletClient = await createSigner(network, normalizedKey);
751
+ return this.purchaseCreditsWithX402({
752
+ accountId: params.accountId,
753
+ credits: params.credits,
754
+ usdAmount: params.usdAmount,
755
+ description: params.description,
756
+ metadata: params.metadata,
757
+ walletClient
758
+ });
759
+ }
760
+ calculateHbarAmount(creditsToPurchase, creditsPerHbar) {
761
+ if (creditsPerHbar <= 0) {
762
+ throw new Error("creditsPerHbar must be positive");
763
+ }
764
+ if (creditsToPurchase <= 0) {
765
+ throw new Error("creditsToPurchase must be positive");
766
+ }
767
+ const rawHbar = creditsToPurchase / creditsPerHbar;
768
+ const tinybars = Math.ceil(rawHbar * 1e8);
769
+ return tinybars / 1e8;
770
+ }
771
+ resolveCreditsToPurchase(shortfallCredits) {
772
+ if (!Number.isFinite(shortfallCredits) || shortfallCredits <= 0) {
773
+ return 0;
774
+ }
775
+ return Math.max(
776
+ Math.ceil(shortfallCredits),
777
+ MINIMUM_REGISTRATION_AUTO_TOP_UP_CREDITS
778
+ );
779
+ }
780
+ calculateHbarAmountParam(hbarAmount) {
781
+ const tinybars = Math.ceil(hbarAmount * 1e8);
782
+ if (tinybars <= 0) {
783
+ throw new Error("Calculated purchase amount must be positive");
784
+ }
785
+ return tinybars / 1e8;
786
+ }
787
+ shouldAutoTopUpHistory(payload, error) {
788
+ if (!this.historyAutoTopUp || payload.historyTtlSeconds === void 0) {
789
+ return false;
790
+ }
791
+ if (!(error instanceof RegistryBrokerError)) {
792
+ return false;
793
+ }
794
+ if (error.status !== 402) {
795
+ return false;
796
+ }
797
+ const message = this.extractErrorMessage(error.body);
798
+ if (!message) {
799
+ return true;
800
+ }
801
+ const normalised = message.toLowerCase();
802
+ return normalised.includes("history") || normalised.includes("chat history");
803
+ }
804
+ extractErrorMessage(body) {
805
+ if (typeof body === "string") {
806
+ return body;
807
+ }
808
+ if (isJsonObject(body) && typeof body.error === "string") {
809
+ return body.error;
810
+ }
811
+ if (isJsonObject(body) && typeof body.message === "string") {
812
+ return body.message;
813
+ }
814
+ return void 0;
815
+ }
816
+ async executeHistoryAutoTopUp(reason) {
817
+ if (!this.historyAutoTopUp) {
818
+ return;
819
+ }
820
+ const hbarAmount = this.historyAutoTopUp.hbarAmount && this.historyAutoTopUp.hbarAmount > 0 ? this.historyAutoTopUp.hbarAmount : DEFAULT_HISTORY_TOP_UP_HBAR;
821
+ await this.purchaseCreditsWithHbar({
822
+ accountId: this.historyAutoTopUp.accountId,
823
+ privateKey: this.historyAutoTopUp.privateKey,
824
+ hbarAmount,
825
+ memo: this.historyAutoTopUp.memo ?? "registry-broker-client:chat-history-topup",
826
+ metadata: {
827
+ purpose: "chat-history",
828
+ reason
829
+ }
830
+ });
831
+ }
832
+ async ensureCreditsForRegistration(payload, autoTopUp) {
833
+ const details = autoTopUp ?? null;
834
+ if (!details) {
835
+ return;
836
+ }
837
+ if (!details.accountId || !details.accountId.trim()) {
838
+ throw new Error("autoTopUp.accountId is required");
839
+ }
840
+ if (!details.privateKey || !details.privateKey.trim()) {
841
+ throw new Error("autoTopUp.privateKey is required");
842
+ }
843
+ for (let attempt = 0; attempt < 3; attempt += 1) {
844
+ const quote = await this.getRegistrationQuote(payload);
845
+ const shortfall = quote.shortfallCredits ?? 0;
846
+ if (shortfall <= 0) {
847
+ return;
848
+ }
849
+ const creditsToPurchase = this.resolveCreditsToPurchase(shortfall);
850
+ if (creditsToPurchase <= 0) {
851
+ return;
852
+ }
853
+ const creditsPerHbar = quote.creditsPerHbar ?? null;
854
+ if (!creditsPerHbar || creditsPerHbar <= 0) {
855
+ throw new Error("Unable to determine credits per HBAR for auto top-up");
856
+ }
857
+ const hbarAmount = this.calculateHbarAmount(
858
+ creditsToPurchase,
859
+ creditsPerHbar
860
+ );
861
+ await this.purchaseCreditsWithHbar({
862
+ accountId: details.accountId.trim(),
863
+ privateKey: details.privateKey.trim(),
864
+ hbarAmount,
865
+ memo: details.memo ?? "Registry Broker auto top-up",
866
+ metadata: {
867
+ shortfallCredits: shortfall,
868
+ requiredCredits: quote.requiredCredits,
869
+ purchasedCredits: creditsToPurchase
870
+ }
871
+ });
872
+ }
873
+ const finalQuote = await this.getRegistrationQuote(payload);
874
+ if ((finalQuote.shortfallCredits ?? 0) > 0) {
875
+ throw new Error("Unable to purchase sufficient credits for registration");
876
+ }
877
+ }
878
+ extractInsufficientCreditsDetails(error) {
879
+ if (!(error instanceof RegistryBrokerError) || error.status !== 402) {
880
+ return null;
881
+ }
882
+ const body = error.body;
883
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
884
+ return null;
885
+ }
886
+ const maybeShortfall = body["shortfallCredits"];
887
+ if (typeof maybeShortfall !== "number" || maybeShortfall <= 0) {
888
+ return null;
889
+ }
890
+ return { shortfallCredits: maybeShortfall };
891
+ }
892
+ async createLedgerChallenge(payload) {
893
+ const resolvedNetwork = canonicalizeLedgerNetwork(payload.network);
894
+ const network = resolvedNetwork.kind === "hedera" ? resolvedNetwork.hederaNetwork ?? resolvedNetwork.canonical : resolvedNetwork.canonical;
895
+ const raw = await this.requestJson("/auth/ledger/challenge", {
896
+ method: "POST",
897
+ headers: { "content-type": "application/json" },
898
+ body: {
899
+ accountId: payload.accountId,
900
+ network
901
+ }
902
+ });
903
+ return this.parseWithSchema(
904
+ raw,
905
+ ledgerChallengeResponseSchema,
906
+ "ledger challenge response"
907
+ );
908
+ }
909
+ async verifyLedgerChallenge(payload) {
910
+ const resolvedNetwork = canonicalizeLedgerNetwork(payload.network);
911
+ const network = resolvedNetwork.kind === "hedera" ? resolvedNetwork.hederaNetwork ?? resolvedNetwork.canonical : resolvedNetwork.canonical;
912
+ const body = {
913
+ challengeId: payload.challengeId,
914
+ accountId: payload.accountId,
915
+ network,
916
+ signature: payload.signature
917
+ };
918
+ if (payload.signatureKind) {
919
+ body.signatureKind = payload.signatureKind;
920
+ }
921
+ if (payload.publicKey) {
922
+ body.publicKey = payload.publicKey;
923
+ }
924
+ if (typeof payload.expiresInMinutes === "number") {
925
+ body.expiresInMinutes = payload.expiresInMinutes;
926
+ }
927
+ const raw = await this.requestJson("/auth/ledger/verify", {
928
+ method: "POST",
929
+ headers: { "content-type": "application/json" },
930
+ body
931
+ });
932
+ const result = this.parseWithSchema(
933
+ raw,
934
+ ledgerVerifyResponseSchema,
935
+ "ledger verification response"
936
+ );
937
+ this.setLedgerApiKey(result.key);
938
+ return result;
939
+ }
940
+ async authenticateWithLedger(options) {
941
+ const challenge = await this.createLedgerChallenge({
942
+ accountId: options.accountId,
943
+ network: options.network
944
+ });
945
+ const signed = await this.resolveLedgerAuthSignature(
946
+ challenge.message,
947
+ options
948
+ );
949
+ const verification = await this.verifyLedgerChallenge({
950
+ challengeId: challenge.challengeId,
951
+ accountId: options.accountId,
952
+ network: options.network,
953
+ signature: signed.signature,
954
+ signatureKind: signed.signatureKind,
955
+ publicKey: signed.publicKey,
956
+ expiresInMinutes: options.expiresInMinutes
957
+ });
958
+ return verification;
959
+ }
960
+ async resolveLedgerAuthSignature(message, options) {
961
+ if (typeof options.sign === "function") {
962
+ const result = await options.sign(message);
963
+ if (!result || typeof result.signature !== "string" || result.signature.length === 0) {
964
+ throw new Error("Custom ledger signer failed to produce a signature.");
965
+ }
966
+ return result;
967
+ }
968
+ if (!options.signer || typeof options.signer.sign !== "function") {
969
+ throw new Error(
970
+ "Ledger authentication requires a Hedera Signer or custom sign function."
971
+ );
972
+ }
973
+ const payload = Buffer.from(message, "utf8");
974
+ const signatures = await options.signer.sign([payload]);
975
+ const signatureEntry = signatures?.[0];
976
+ if (!signatureEntry) {
977
+ throw new Error("Signer did not return any signatures.");
978
+ }
979
+ let derivedPublicKey;
980
+ if (signatureEntry.publicKey) {
981
+ derivedPublicKey = signatureEntry.publicKey.toString();
982
+ } else if (typeof options.signer.getAccountKey === "function") {
983
+ const accountKey = await options.signer.getAccountKey();
984
+ if (accountKey && typeof accountKey.toString === "function") {
985
+ derivedPublicKey = accountKey.toString();
986
+ }
987
+ }
988
+ return {
989
+ signature: Buffer.from(signatureEntry.signature).toString("base64"),
990
+ signatureKind: "raw",
991
+ publicKey: derivedPublicKey
992
+ };
993
+ }
994
+ async authenticateWithLedgerCredentials(options) {
995
+ const {
996
+ accountId,
997
+ network,
998
+ signer,
999
+ sign,
1000
+ hederaPrivateKey,
1001
+ evmPrivateKey,
1002
+ expiresInMinutes,
1003
+ setAccountHeader = true,
1004
+ label,
1005
+ logger
1006
+ } = options;
1007
+ const resolvedNetwork = canonicalizeLedgerNetwork(network);
1008
+ const labelSuffix = label ? ` for ${label}` : "";
1009
+ const networkPayload = resolvedNetwork.canonical;
1010
+ const authOptions = {
1011
+ accountId,
1012
+ network: networkPayload,
1013
+ expiresInMinutes
1014
+ };
1015
+ if (sign) {
1016
+ authOptions.sign = sign;
1017
+ } else if (signer) {
1018
+ authOptions.signer = signer;
1019
+ } else if (hederaPrivateKey) {
1020
+ if (resolvedNetwork.kind !== "hedera" || !resolvedNetwork.hederaNetwork) {
1021
+ throw new Error(
1022
+ "hederaPrivateKey can only be used with hedera:mainnet or hedera:testnet networks."
1023
+ );
1024
+ }
1025
+ authOptions.signer = createPrivateKeySigner({
1026
+ accountId,
1027
+ privateKey: hederaPrivateKey,
1028
+ network: resolvedNetwork.hederaNetwork
1029
+ });
1030
+ } else if (evmPrivateKey) {
1031
+ if (resolvedNetwork.kind !== "evm") {
1032
+ throw new Error(
1033
+ "evmPrivateKey can only be used with CAIP-2 EVM networks (eip155:<chainId>)."
1034
+ );
1035
+ }
1036
+ const formattedKey = evmPrivateKey.startsWith("0x") ? evmPrivateKey : `0x${evmPrivateKey}`;
1037
+ const account = privateKeyToAccount(formattedKey);
1038
+ authOptions.sign = async (message) => ({
1039
+ signature: await account.signMessage({ message }),
1040
+ signatureKind: "evm",
1041
+ publicKey: account.publicKey
1042
+ });
1043
+ } else {
1044
+ throw new Error(
1045
+ "Provide a signer, sign function, hederaPrivateKey, or evmPrivateKey to authenticate with the ledger."
1046
+ );
1047
+ }
1048
+ logger?.info?.(
1049
+ `Authenticating ledger account ${accountId} (${resolvedNetwork.canonical})${labelSuffix}...`
1050
+ );
1051
+ const verification = await this.authenticateWithLedger(authOptions);
1052
+ if (setAccountHeader) {
1053
+ this.setDefaultHeader("x-account-id", verification.accountId);
1054
+ }
1055
+ logger?.info?.(
1056
+ `Ledger authentication complete${labelSuffix}. Issued key prefix: ${verification.apiKey.prefix}…${verification.apiKey.lastFour}`
1057
+ );
1058
+ return verification;
1059
+ }
1060
+ async listProtocols() {
1061
+ const raw = await this.requestJson("/protocols", {
1062
+ method: "GET"
1063
+ });
1064
+ return this.parseWithSchema(
1065
+ raw,
1066
+ protocolsResponseSchema,
1067
+ "protocols response"
1068
+ );
1069
+ }
1070
+ async detectProtocol(message) {
1071
+ const raw = await this.requestJson("/detect-protocol", {
1072
+ method: "POST",
1073
+ body: { message },
1074
+ headers: { "content-type": "application/json" }
1075
+ });
1076
+ return this.parseWithSchema(
1077
+ raw,
1078
+ detectProtocolResponseSchema,
1079
+ "detect protocol response"
1080
+ );
1081
+ }
1082
+ async registrySearchByNamespace(registry, query) {
1083
+ const params = new URLSearchParams();
1084
+ if (query) {
1085
+ params.set("q", query);
1086
+ }
1087
+ const suffix = params.size > 0 ? `?${params.toString()}` : "";
1088
+ const raw = await this.requestJson(
1089
+ `/registries/${encodeURIComponent(registry)}/search${suffix}`,
1090
+ {
1091
+ method: "GET"
1092
+ }
1093
+ );
1094
+ return this.parseWithSchema(
1095
+ raw,
1096
+ registrySearchByNamespaceSchema,
1097
+ "registry search response"
1098
+ );
1099
+ }
1100
+ async vectorSearch(request) {
1101
+ try {
1102
+ const raw = await this.requestJson("/search", {
1103
+ method: "POST",
1104
+ body: request,
1105
+ headers: { "content-type": "application/json" }
1106
+ });
1107
+ return this.parseWithSchema(
1108
+ raw,
1109
+ vectorSearchResponseSchema,
1110
+ "vector search response"
1111
+ );
1112
+ } catch (error) {
1113
+ if (error instanceof RegistryBrokerError && error.status === 501) {
1114
+ const fallback = await this.search(
1115
+ this.buildVectorFallbackSearchParams(request)
1116
+ );
1117
+ return this.convertSearchResultToVectorResponse(fallback);
1118
+ }
1119
+ throw error;
1120
+ }
1121
+ }
1122
+ async searchStatus() {
1123
+ const raw = await this.requestJson("/search/status", {
1124
+ method: "GET"
1125
+ });
1126
+ return this.parseWithSchema(
1127
+ raw,
1128
+ searchStatusResponseSchema,
1129
+ "search status response"
1130
+ );
1131
+ }
1132
+ async adaptersDetailed() {
1133
+ const raw = await this.requestJson("/adapters/details", {
1134
+ method: "GET"
1135
+ });
1136
+ return this.parseWithSchema(
1137
+ raw,
1138
+ adapterDetailsResponseSchema,
1139
+ "adapter details response"
1140
+ );
1141
+ }
1142
+ async websocketStats() {
1143
+ const raw = await this.requestJson("/websocket/stats", {
1144
+ method: "GET"
1145
+ });
1146
+ return this.parseWithSchema(
1147
+ raw,
1148
+ websocketStatsResponseSchema,
1149
+ "websocket stats response"
1150
+ );
1151
+ }
1152
+ async metricsSummary() {
1153
+ const raw = await this.requestJson("/metrics", {
1154
+ method: "GET"
1155
+ });
1156
+ return this.parseWithSchema(
1157
+ raw,
1158
+ metricsSummaryResponseSchema,
1159
+ "metrics summary response"
1160
+ );
1161
+ }
1162
+ async validateUaid(uaid) {
1163
+ const raw = await this.requestJson(
1164
+ `/uaids/validate/${encodeURIComponent(uaid)}`,
1165
+ {
1166
+ method: "GET"
1167
+ }
1168
+ );
1169
+ return this.parseWithSchema(
1170
+ raw,
1171
+ uaidValidationResponseSchema,
1172
+ "UAID validation response"
1173
+ );
1174
+ }
1175
+ async getUaidConnectionStatus(uaid) {
1176
+ const raw = await this.requestJson(
1177
+ `/uaids/connections/${encodeURIComponent(uaid)}/status`,
1178
+ {
1179
+ method: "GET"
1180
+ }
1181
+ );
1182
+ return this.parseWithSchema(
1183
+ raw,
1184
+ uaidConnectionStatusSchema,
1185
+ "UAID connection status"
1186
+ );
1187
+ }
1188
+ async closeUaidConnection(uaid) {
1189
+ await this.request(`/uaids/connections/${encodeURIComponent(uaid)}`, {
1190
+ method: "DELETE"
1191
+ });
1192
+ }
1193
+ async dashboardStats() {
1194
+ const raw = await this.requestJson("/dashboard/stats", {
1195
+ method: "GET"
1196
+ });
1197
+ return this.parseWithSchema(
1198
+ raw,
1199
+ dashboardStatsResponseSchema,
1200
+ "dashboard stats response"
1201
+ );
1202
+ }
1203
+ async adapters() {
1204
+ const raw = await this.requestJson("/adapters", {
1205
+ method: "GET"
1206
+ });
1207
+ return this.parseWithSchema(
1208
+ raw,
1209
+ adaptersResponseSchema,
1210
+ "adapters response"
1211
+ );
1212
+ }
1213
+ async facets(adapter) {
1214
+ const params = new URLSearchParams();
1215
+ if (adapter) {
1216
+ params.set("adapter", adapter);
1217
+ }
1218
+ const suffix = params.size > 0 ? `?${params.toString()}` : "";
1219
+ const raw = await this.requestJson(`/search/facets${suffix}`, {
1220
+ method: "GET"
1221
+ });
1222
+ return this.parseWithSchema(
1223
+ raw,
1224
+ searchFacetsResponseSchema,
1225
+ "search facets response"
1226
+ );
1227
+ }
1228
+ async createSession(payload, allowHistoryAutoTopUp = true) {
1229
+ const body = {};
1230
+ if ("uaid" in payload && payload.uaid) {
1231
+ body.uaid = payload.uaid;
1232
+ }
1233
+ if ("agentUrl" in payload && payload.agentUrl) {
1234
+ body.agentUrl = payload.agentUrl;
1235
+ }
1236
+ if (payload.auth) {
1237
+ body.auth = serialiseAuthConfig(payload.auth);
1238
+ }
1239
+ if (payload.historyTtlSeconds !== void 0) {
1240
+ body.historyTtlSeconds = payload.historyTtlSeconds;
1241
+ }
1242
+ if (payload.encryptionRequested !== void 0) {
1243
+ body.encryptionRequested = payload.encryptionRequested;
1244
+ }
1245
+ if (payload.senderUaid) {
1246
+ body.senderUaid = payload.senderUaid;
1247
+ }
1248
+ try {
1249
+ const raw = await this.requestJson("/chat/session", {
1250
+ method: "POST",
1251
+ body,
1252
+ headers: { "content-type": "application/json" }
1253
+ });
1254
+ return this.parseWithSchema(
1255
+ raw,
1256
+ createSessionResponseSchema,
1257
+ "chat session response"
1258
+ );
1259
+ } catch (error) {
1260
+ if (allowHistoryAutoTopUp && this.shouldAutoTopUpHistory(payload, error)) {
1261
+ await this.executeHistoryAutoTopUp("chat.session");
1262
+ return this.createSession(payload, false);
1263
+ }
1264
+ throw error;
1265
+ }
1266
+ }
1267
+ async startChat(options) {
1268
+ if ("uaid" in options && options.uaid) {
1269
+ return this.startConversation({
1270
+ uaid: options.uaid,
1271
+ senderUaid: options.senderUaid,
1272
+ historyTtlSeconds: options.historyTtlSeconds,
1273
+ auth: options.auth,
1274
+ encryption: options.encryption,
1275
+ onSessionCreated: options.onSessionCreated
1276
+ });
1277
+ }
1278
+ if ("agentUrl" in options && options.agentUrl) {
1279
+ const session = await this.createSession({
1280
+ agentUrl: options.agentUrl,
1281
+ auth: options.auth,
1282
+ historyTtlSeconds: options.historyTtlSeconds,
1283
+ senderUaid: options.senderUaid
1284
+ });
1285
+ options.onSessionCreated?.(session.sessionId);
1286
+ return this.createPlaintextConversationHandle(
1287
+ session.sessionId,
1288
+ session.encryption ?? null,
1289
+ options.auth,
1290
+ { agentUrl: options.agentUrl, uaid: options.uaid }
1291
+ );
1292
+ }
1293
+ throw new Error("startChat requires either uaid or agentUrl");
1294
+ }
1295
+ async startConversation(options) {
1296
+ const preference = options.encryption?.preference ?? "preferred";
1297
+ const requestEncryption = preference !== "disabled";
1298
+ if (!requestEncryption) {
1299
+ const session = await this.createSession({
1300
+ uaid: options.uaid,
1301
+ auth: options.auth,
1302
+ historyTtlSeconds: options.historyTtlSeconds,
1303
+ senderUaid: options.senderUaid,
1304
+ encryptionRequested: false
1305
+ });
1306
+ options.onSessionCreated?.(session.sessionId);
1307
+ return this.createPlaintextConversationHandle(
1308
+ session.sessionId,
1309
+ session.encryption ?? null,
1310
+ options.auth,
1311
+ { uaid: options.uaid }
1312
+ );
1313
+ }
1314
+ try {
1315
+ const handle = await this.encryptedChatManager.startSession({
1316
+ uaid: options.uaid,
1317
+ senderUaid: options.senderUaid,
1318
+ historyTtlSeconds: options.historyTtlSeconds,
1319
+ handshakeTimeoutMs: options.encryption?.handshakeTimeoutMs,
1320
+ pollIntervalMs: options.encryption?.pollIntervalMs,
1321
+ onSessionCreated: (sessionId) => {
1322
+ options.onSessionCreated?.(sessionId);
1323
+ },
1324
+ auth: options.auth
1325
+ });
1326
+ return handle;
1327
+ } catch (error) {
1328
+ if (error instanceof EncryptionUnavailableError) {
1329
+ if (preference === "required") {
1330
+ throw error;
1331
+ }
1332
+ return this.createPlaintextConversationHandle(
1333
+ error.sessionId,
1334
+ error.summary ?? null,
1335
+ options.auth,
1336
+ { uaid: options.uaid }
1337
+ );
1338
+ }
1339
+ throw error;
1340
+ }
1341
+ }
1342
+ async acceptConversation(options) {
1343
+ const preference = options.encryption?.preference ?? "preferred";
1344
+ if (preference === "disabled") {
1345
+ return this.createPlaintextConversationHandle(options.sessionId, null);
1346
+ }
1347
+ try {
1348
+ const handle = await this.encryptedChatManager.acceptSession({
1349
+ sessionId: options.sessionId,
1350
+ responderUaid: options.responderUaid,
1351
+ handshakeTimeoutMs: options.encryption?.handshakeTimeoutMs,
1352
+ pollIntervalMs: options.encryption?.pollIntervalMs
1353
+ });
1354
+ return handle;
1355
+ } catch (error) {
1356
+ if (error instanceof EncryptionUnavailableError && preference !== "required") {
1357
+ return this.createPlaintextConversationHandle(
1358
+ options.sessionId,
1359
+ null,
1360
+ void 0,
1361
+ { uaid: options.responderUaid }
1362
+ );
1363
+ }
1364
+ throw error;
1365
+ }
1366
+ }
1367
+ async fetchHistorySnapshot(sessionId, options) {
1368
+ if (!sessionId || sessionId.trim().length === 0) {
1369
+ throw new Error("sessionId is required to fetch chat history");
1370
+ }
1371
+ const raw = await this.requestJson(
1372
+ `/chat/session/${encodeURIComponent(sessionId)}/history`,
1373
+ {
1374
+ method: "GET"
1375
+ }
1376
+ );
1377
+ const snapshot = this.parseWithSchema(
1378
+ raw,
1379
+ chatHistorySnapshotResponseSchema,
1380
+ "chat history snapshot response"
1381
+ );
1382
+ return this.attachDecryptedHistory(sessionId, snapshot, options);
1383
+ }
1384
+ attachDecryptedHistory(sessionId, snapshot, options) {
1385
+ const shouldDecrypt = options?.decrypt !== void 0 ? options.decrypt : this.encryptionOptions?.autoDecryptHistory === true;
1386
+ if (!shouldDecrypt) {
1387
+ return snapshot;
1388
+ }
1389
+ const context = this.resolveDecryptionContext(sessionId, options);
1390
+ if (!context) {
1391
+ throw new Error(
1392
+ "Unable to decrypt chat history: encryption context unavailable"
1393
+ );
1394
+ }
1395
+ const decryptedHistory = snapshot.history.map((entry) => ({
1396
+ entry,
1397
+ plaintext: this.decryptHistoryEntryFromContext(sessionId, entry, context)
1398
+ }));
1399
+ return { ...snapshot, decryptedHistory };
1400
+ }
1401
+ registerConversationContext(context) {
1402
+ const normalized = {
1403
+ sessionId: context.sessionId,
1404
+ sharedSecret: Buffer.from(context.sharedSecret),
1405
+ identity: context.identity ? { ...context.identity } : void 0
1406
+ };
1407
+ const entries = this.conversationContexts.get(context.sessionId) ?? [];
1408
+ const existingIndex = entries.findIndex(
1409
+ (existing) => this.identitiesMatch(existing.identity, normalized.identity)
1410
+ );
1411
+ if (existingIndex >= 0) {
1412
+ entries[existingIndex] = normalized;
1413
+ } else {
1414
+ entries.push(normalized);
1415
+ }
1416
+ this.conversationContexts.set(context.sessionId, entries);
1417
+ }
1418
+ // Exposed for EncryptedChatManager to persist decryption context
1419
+ registerConversationContextForEncryption(context) {
1420
+ this.registerConversationContext(context);
1421
+ }
1422
+ resolveDecryptionContext(sessionId, options) {
1423
+ if (options?.sharedSecret) {
1424
+ return {
1425
+ sessionId,
1426
+ sharedSecret: this.normalizeSharedSecret(options.sharedSecret),
1427
+ identity: options.identity
1428
+ };
1429
+ }
1430
+ const contexts = this.conversationContexts.get(sessionId);
1431
+ if (!contexts || contexts.length === 0) {
1432
+ return null;
1433
+ }
1434
+ if (options?.identity) {
1435
+ const match = contexts.find(
1436
+ (context) => this.identitiesMatch(context.identity, options.identity)
1437
+ );
1438
+ if (match) {
1439
+ return match;
1440
+ }
1441
+ }
1442
+ return contexts[0];
1443
+ }
1444
+ decryptHistoryEntryFromContext(sessionId, entry, context) {
1445
+ const envelope = entry.cipherEnvelope;
1446
+ if (!envelope) {
1447
+ return entry.content;
1448
+ }
1449
+ const secret = Buffer.from(context.sharedSecret);
1450
+ try {
1451
+ return this.encryption.decryptCipherEnvelope({
1452
+ envelope,
1453
+ sharedSecret: secret
1454
+ });
1455
+ } catch (_error) {
1456
+ return null;
1457
+ }
1458
+ }
1459
+ identitiesMatch(a, b) {
1460
+ if (!a && !b) {
1461
+ return true;
1462
+ }
1463
+ if (!a || !b) {
1464
+ return false;
1465
+ }
1466
+ if (a.uaid && b.uaid && a.uaid.toLowerCase() === b.uaid.toLowerCase()) {
1467
+ return true;
1468
+ }
1469
+ if (a.ledgerAccountId && b.ledgerAccountId && a.ledgerAccountId.toLowerCase() === b.ledgerAccountId.toLowerCase()) {
1470
+ return true;
1471
+ }
1472
+ if (a.userId && b.userId && a.userId === b.userId) {
1473
+ return true;
1474
+ }
1475
+ if (a.email && b.email && a.email.toLowerCase() === b.email.toLowerCase()) {
1476
+ return true;
1477
+ }
1478
+ return false;
1479
+ }
1480
+ identityMatchesRecipient(recipient, identity) {
1481
+ if (identity.uaid && recipient.uaid?.toLowerCase() === identity.uaid.toLowerCase()) {
1482
+ return true;
1483
+ }
1484
+ if (identity.ledgerAccountId && recipient.ledgerAccountId?.toLowerCase() === identity.ledgerAccountId.toLowerCase()) {
1485
+ return true;
1486
+ }
1487
+ if (identity.userId && recipient.userId === identity.userId) {
1488
+ return true;
1489
+ }
1490
+ if (identity.email && recipient.email?.toLowerCase() === identity.email.toLowerCase()) {
1491
+ return true;
1492
+ }
1493
+ return false;
1494
+ }
1495
+ createPlaintextConversationHandle(sessionId, summary, defaultAuth, context) {
1496
+ const uaid = context?.uaid?.trim();
1497
+ const agentUrl = context?.agentUrl?.trim();
1498
+ return {
1499
+ sessionId,
1500
+ mode: "plaintext",
1501
+ summary: summary ?? null,
1502
+ send: async (options) => {
1503
+ const plaintext = options.plaintext;
1504
+ if (!plaintext || plaintext.trim().length === 0) {
1505
+ throw new Error("plaintext is required for chat messages");
1506
+ }
1507
+ const message = options.message ?? plaintext;
1508
+ return this.sendMessage({
1509
+ sessionId,
1510
+ message,
1511
+ streaming: options.streaming,
1512
+ auth: options.auth ?? defaultAuth,
1513
+ uaid,
1514
+ agentUrl
1515
+ });
1516
+ },
1517
+ decryptHistoryEntry: (entry) => entry.content
1518
+ };
1519
+ }
1520
+ async compactHistory(payload) {
1521
+ if (!payload.sessionId || payload.sessionId.trim().length === 0) {
1522
+ throw new Error("sessionId is required to compact chat history");
1523
+ }
1524
+ const body = {};
1525
+ if (typeof payload.preserveEntries === "number" && Number.isFinite(payload.preserveEntries) && payload.preserveEntries >= 0) {
1526
+ body.preserveEntries = Math.floor(payload.preserveEntries);
1527
+ }
1528
+ const raw = await this.requestJson(
1529
+ `/chat/session/${encodeURIComponent(payload.sessionId)}/compact`,
1530
+ {
1531
+ method: "POST",
1532
+ headers: { "content-type": "application/json" },
1533
+ body
1534
+ }
1535
+ );
1536
+ return this.parseWithSchema(
1537
+ raw,
1538
+ chatHistoryCompactionResponseSchema,
1539
+ "chat history compaction response"
1540
+ );
1541
+ }
1542
+ async fetchEncryptionStatus(sessionId) {
1543
+ if (!sessionId || sessionId.trim().length === 0) {
1544
+ throw new Error("sessionId is required for encryption status");
1545
+ }
1546
+ const raw = await this.requestJson(
1547
+ `/chat/session/${encodeURIComponent(sessionId)}/encryption`,
1548
+ {
1549
+ method: "GET"
1550
+ }
1551
+ );
1552
+ return this.parseWithSchema(
1553
+ raw,
1554
+ sessionEncryptionStatusResponseSchema,
1555
+ "session encryption status response"
1556
+ );
1557
+ }
1558
+ async postEncryptionHandshake(sessionId, payload) {
1559
+ if (!sessionId || sessionId.trim().length === 0) {
1560
+ throw new Error("sessionId is required for encryption handshake");
1561
+ }
1562
+ const raw = await this.requestJson(
1563
+ `/chat/session/${encodeURIComponent(sessionId)}/encryption-handshake`,
1564
+ {
1565
+ method: "POST",
1566
+ headers: { "content-type": "application/json" },
1567
+ body: {
1568
+ role: payload.role,
1569
+ keyType: payload.keyType,
1570
+ ephemeralPublicKey: payload.ephemeralPublicKey,
1571
+ longTermPublicKey: payload.longTermPublicKey,
1572
+ signature: payload.signature,
1573
+ uaid: payload.uaid,
1574
+ userId: payload.userId,
1575
+ ledgerAccountId: payload.ledgerAccountId,
1576
+ metadata: payload.metadata
1577
+ }
1578
+ }
1579
+ );
1580
+ const response = this.parseWithSchema(
1581
+ raw,
1582
+ encryptionHandshakeResponseSchema,
1583
+ "encryption handshake response"
1584
+ );
1585
+ return response.handshake;
1586
+ }
1587
+ async registerEncryptionKey(payload) {
1588
+ const raw = await this.requestJson("/encryption/keys", {
1589
+ method: "POST",
1590
+ headers: { "content-type": "application/json" },
1591
+ body: payload
1592
+ });
1593
+ return this.parseWithSchema(
1594
+ raw,
1595
+ registerEncryptionKeyResponseSchema,
1596
+ "register encryption key response"
1597
+ );
1598
+ }
1599
+ async sendMessage(payload) {
1600
+ const body = {
1601
+ message: payload.message
1602
+ };
1603
+ if (payload.streaming !== void 0) {
1604
+ body.streaming = payload.streaming;
1605
+ }
1606
+ if (payload.auth) {
1607
+ body.auth = serialiseAuthConfig(payload.auth);
1608
+ }
1609
+ if ("uaid" in payload) {
1610
+ body.uaid = payload.uaid;
1611
+ }
1612
+ if ("sessionId" in payload && payload.sessionId) {
1613
+ body.sessionId = payload.sessionId;
1614
+ }
1615
+ if ("agentUrl" in payload && payload.agentUrl) {
1616
+ body.agentUrl = payload.agentUrl;
1617
+ }
1618
+ let cipherEnvelope = payload.cipherEnvelope ?? null;
1619
+ if (payload.encryption) {
1620
+ const sessionIdForEncryption = payload.encryption.sessionId ?? (typeof body.sessionId === "string" ? body.sessionId : void 0);
1621
+ if (!sessionIdForEncryption) {
1622
+ throw new Error(
1623
+ "sessionId is required when using encrypted chat payloads"
1624
+ );
1625
+ }
1626
+ if (!payload.encryption.recipients?.length) {
1627
+ throw new Error("recipients are required for encrypted chat payloads");
1628
+ }
1629
+ cipherEnvelope = this.encryption.encryptCipherEnvelope({
1630
+ ...payload.encryption,
1631
+ sessionId: sessionIdForEncryption
1632
+ });
1633
+ }
1634
+ if (cipherEnvelope) {
1635
+ body.cipherEnvelope = cipherEnvelope;
1636
+ }
1637
+ delete body.encryption;
1638
+ const raw = await this.requestJson("/chat/message", {
1639
+ method: "POST",
1640
+ body,
1641
+ headers: { "content-type": "application/json" }
1642
+ });
1643
+ return this.parseWithSchema(
1644
+ raw,
1645
+ sendMessageResponseSchema,
1646
+ "chat message response"
1647
+ );
1648
+ }
1649
+ async endSession(sessionId) {
1650
+ await this.request(`/chat/session/${encodeURIComponent(sessionId)}`, {
1651
+ method: "DELETE"
1652
+ });
1653
+ }
1654
+ async generateEncryptionKeyPair(options = {}) {
1655
+ this.assertNodeRuntime("generateEncryptionKeyPair");
1656
+ const keyType = options.keyType ?? "secp256k1";
1657
+ if (keyType !== "secp256k1") {
1658
+ throw new Error("Only secp256k1 key generation is supported currently");
1659
+ }
1660
+ const privateKeyBytes = randomBytes(32);
1661
+ const privateKey = Buffer.from(privateKeyBytes).toString("hex");
1662
+ const publicKeyBytes = secp256k1.getPublicKey(privateKeyBytes, true);
1663
+ const publicKey = Buffer.from(publicKeyBytes).toString("hex");
1664
+ const envVar = options.envVar ?? "RB_ENCRYPTION_PRIVATE_KEY";
1665
+ const resolvedPath = options.envPath ? path.resolve(options.envPath) : void 0;
1666
+ if (resolvedPath) {
1667
+ const fsModule = getFs();
1668
+ if (!fsModule) {
1669
+ throw new Error(
1670
+ "File system module is not available; cannot write encryption key env file"
1671
+ );
1672
+ }
1673
+ const envLine = `${envVar}=${privateKey}`;
1674
+ if (fsModule.existsSync(resolvedPath)) {
1675
+ const content = fsModule.readFileSync(resolvedPath, "utf-8");
1676
+ const lineRegex = new RegExp(`^${envVar}=.*$`, "m");
1677
+ if (lineRegex.test(content)) {
1678
+ if (!options.overwrite) {
1679
+ throw new Error(
1680
+ `${envVar} already exists in ${resolvedPath}; set overwrite=true to replace it`
1681
+ );
1682
+ }
1683
+ const updated = content.replace(lineRegex, envLine);
1684
+ fsModule.writeFileSync(resolvedPath, updated);
1685
+ } else {
1686
+ const needsNewline = !content.endsWith("\n");
1687
+ fsModule.appendFileSync(
1688
+ resolvedPath,
1689
+ `${needsNewline ? "\n" : ""}${envLine}
1690
+ `
1691
+ );
1692
+ }
1693
+ } else {
1694
+ fsModule.writeFileSync(resolvedPath, `${envLine}
1695
+ `);
1696
+ }
1697
+ }
1698
+ return {
1699
+ privateKey,
1700
+ publicKey,
1701
+ envPath: resolvedPath,
1702
+ envVar
1703
+ };
1704
+ }
1705
+ buildUrl(path2) {
1706
+ const normalisedPath = path2.startsWith("/") ? path2 : `/${path2}`;
1707
+ return `${this.baseUrl}${normalisedPath}`;
1708
+ }
1709
+ buildVectorFallbackSearchParams(request) {
1710
+ const params = {
1711
+ q: request.query
1712
+ };
1713
+ let effectiveLimit;
1714
+ if (typeof request.limit === "number" && Number.isFinite(request.limit)) {
1715
+ effectiveLimit = request.limit;
1716
+ params.limit = request.limit;
1717
+ }
1718
+ if (typeof request.offset === "number" && Number.isFinite(request.offset) && request.offset > 0) {
1719
+ const limit = effectiveLimit && effectiveLimit > 0 ? effectiveLimit : 20;
1720
+ params.limit = limit;
1721
+ params.page = Math.floor(request.offset / limit) + 1;
1722
+ }
1723
+ if (request.filter?.registry) {
1724
+ params.registry = request.filter.registry;
1725
+ }
1726
+ if (request.filter?.protocols?.length) {
1727
+ params.protocols = [...request.filter.protocols];
1728
+ }
1729
+ if (request.filter?.adapter?.length) {
1730
+ params.adapters = [...request.filter.adapter];
1731
+ }
1732
+ if (request.filter?.capabilities?.length) {
1733
+ params.capabilities = request.filter.capabilities.map(
1734
+ (value) => typeof value === "number" ? value.toString(10) : value
1735
+ );
1736
+ }
1737
+ if (request.filter?.type) {
1738
+ params.type = request.filter.type;
1739
+ }
1740
+ return params;
1741
+ }
1742
+ convertSearchResultToVectorResponse(result) {
1743
+ const hits = result.hits.map((agent) => ({
1744
+ agent,
1745
+ score: 0,
1746
+ highlights: {}
1747
+ }));
1748
+ const total = result.total;
1749
+ const limit = result.limit;
1750
+ const page = result.page;
1751
+ const totalVisible = page * limit;
1752
+ const limited = total > totalVisible || page > 1;
1753
+ return {
1754
+ hits,
1755
+ total,
1756
+ took: 0,
1757
+ totalAvailable: total,
1758
+ visible: hits.length,
1759
+ limited,
1760
+ credits_used: 0
1761
+ };
1762
+ }
1763
+ async delay(ms, signal) {
1764
+ if (ms <= 0) {
1765
+ if (signal?.aborted) {
1766
+ throw createAbortError();
1767
+ }
1768
+ return;
1769
+ }
1770
+ await new Promise((resolve, reject) => {
1771
+ const timer = setTimeout(() => {
1772
+ if (signal) {
1773
+ signal.removeEventListener("abort", onAbort);
1774
+ }
1775
+ resolve();
1776
+ }, ms);
1777
+ const onAbort = () => {
1778
+ clearTimeout(timer);
1779
+ signal?.removeEventListener("abort", onAbort);
1780
+ reject(createAbortError());
1781
+ };
1782
+ if (signal) {
1783
+ if (signal.aborted) {
1784
+ clearTimeout(timer);
1785
+ reject(createAbortError());
1786
+ return;
1787
+ }
1788
+ signal.addEventListener("abort", onAbort, { once: true });
1789
+ }
1790
+ });
1791
+ }
1792
+ async requestJson(path2, config) {
1793
+ const response = await this.request(path2, config);
1794
+ const contentType = response.headers?.get("content-type") ?? "";
1795
+ if (!JSON_CONTENT_TYPE.test(contentType)) {
1796
+ const body = await response.text();
1797
+ throw new RegistryBrokerParseError(
1798
+ "Expected JSON response from registry broker",
1799
+ body
1800
+ );
1801
+ }
1802
+ return await response.json();
1803
+ }
1804
+ async extractErrorBody(response) {
1805
+ const contentType = response.headers?.get("content-type") ?? "";
1806
+ if (JSON_CONTENT_TYPE.test(contentType)) {
1807
+ try {
1808
+ return await response.json();
1809
+ } catch (error) {
1810
+ return { parseError: String(error) };
1811
+ }
1812
+ }
1813
+ try {
1814
+ return await response.text();
1815
+ } catch (error) {
1816
+ return { parseError: String(error) };
1817
+ }
1818
+ }
1819
+ parseWithSchema(value, schema, context) {
1820
+ try {
1821
+ return schema.parse(value);
1822
+ } catch (error) {
1823
+ throw new RegistryBrokerParseError(
1824
+ `Failed to parse ${context}`,
1825
+ error instanceof ZodError || error instanceof Error ? error : String(error),
1826
+ value
1827
+ );
1828
+ }
1829
+ }
1830
+ assertNodeRuntime(feature) {
1831
+ if (typeof process === "undefined" || !process.versions?.node) {
1832
+ throw new Error(`${feature} is only available in Node.js environments`);
1833
+ }
1834
+ }
1835
+ createEphemeralKeyPair() {
1836
+ this.assertNodeRuntime("generateEphemeralKeyPair");
1837
+ const privateKeyBytes = randomBytes(32);
1838
+ const publicKey = secp256k1.getPublicKey(privateKeyBytes, true);
1839
+ return {
1840
+ privateKey: Buffer.from(privateKeyBytes).toString("hex"),
1841
+ publicKey: Buffer.from(publicKey).toString("hex")
1842
+ };
1843
+ }
1844
+ deriveSharedSecret(options) {
1845
+ this.assertNodeRuntime("deriveSharedSecret");
1846
+ const privateKey = this.hexToBuffer(options.privateKey);
1847
+ const peerPublicKey = this.hexToBuffer(options.peerPublicKey);
1848
+ const shared = secp256k1.getSharedSecret(privateKey, peerPublicKey, true);
1849
+ return createHash("sha256").update(Buffer.from(shared)).digest();
1850
+ }
1851
+ buildCipherEnvelope(options) {
1852
+ this.assertNodeRuntime("encryptCipherEnvelope");
1853
+ const sharedSecret = this.normalizeSharedSecret(options.sharedSecret);
1854
+ const iv = randomBytes(12);
1855
+ const cipher = createCipheriv("aes-256-gcm", sharedSecret, iv);
1856
+ const aadSource = options.associatedData ?? options.sessionId;
1857
+ const associatedDataEncoded = aadSource ? Buffer.from(aadSource, "utf8").toString("base64") : void 0;
1858
+ if (aadSource) {
1859
+ cipher.setAAD(Buffer.from(aadSource, "utf8"));
1860
+ }
1861
+ const ciphertext = Buffer.concat([
1862
+ cipher.update(Buffer.from(options.plaintext, "utf8")),
1863
+ cipher.final()
1864
+ ]);
1865
+ const tag = cipher.getAuthTag();
1866
+ const payload = Buffer.concat([ciphertext, tag]);
1867
+ return {
1868
+ algorithm: "aes-256-gcm",
1869
+ ciphertext: payload.toString("base64"),
1870
+ nonce: iv.toString("base64"),
1871
+ associatedData: associatedDataEncoded,
1872
+ keyLocator: {
1873
+ sessionId: options.sessionId,
1874
+ revision: options.revision ?? 1
1875
+ },
1876
+ recipients: options.recipients.map((recipient) => ({
1877
+ ...recipient,
1878
+ encryptedShare: ""
1879
+ }))
1880
+ };
1881
+ }
1882
+ openCipherEnvelope(options) {
1883
+ this.assertNodeRuntime("decryptCipherEnvelope");
1884
+ const sharedSecret = this.normalizeSharedSecret(options.sharedSecret);
1885
+ const payload = Buffer.from(options.envelope.ciphertext, "base64");
1886
+ const nonce = Buffer.from(options.envelope.nonce, "base64");
1887
+ const ciphertext = payload.slice(0, payload.length - 16);
1888
+ const tag = payload.slice(payload.length - 16);
1889
+ const decipher = createDecipheriv("aes-256-gcm", sharedSecret, nonce);
1890
+ if (options.envelope.associatedData) {
1891
+ decipher.setAAD(Buffer.from(options.envelope.associatedData, "base64"));
1892
+ }
1893
+ decipher.setAuthTag(tag);
1894
+ const plaintext = Buffer.concat([
1895
+ decipher.update(ciphertext),
1896
+ decipher.final()
1897
+ ]);
1898
+ return plaintext.toString(options.encoding ?? "utf8");
1899
+ }
1900
+ normalizeSharedSecret(input) {
1901
+ if (Buffer.isBuffer(input)) {
1902
+ return Buffer.from(input);
1903
+ }
1904
+ if (input instanceof Uint8Array) {
1905
+ return Buffer.from(input);
1906
+ }
1907
+ if (typeof input === "string") {
1908
+ return this.bufferFromString(input);
1909
+ }
1910
+ throw new Error("Unsupported shared secret input");
1911
+ }
1912
+ bufferFromString(value) {
1913
+ const trimmed = value.trim();
1914
+ if (!trimmed) {
1915
+ throw new Error("sharedSecret string cannot be empty");
1916
+ }
1917
+ const normalized = trimmed.startsWith("0x") ? trimmed.slice(2) : trimmed;
1918
+ if (/^[0-9a-fA-F]+$/.test(normalized) && normalized.length % 2 === 0) {
1919
+ return Buffer.from(normalized, "hex");
1920
+ }
1921
+ return Buffer.from(trimmed, "base64");
1922
+ }
1923
+ hexToBuffer(value) {
1924
+ const normalized = value.startsWith("0x") ? value.slice(2) : value;
1925
+ if (!/^[0-9a-fA-F]+$/.test(normalized) || normalized.length % 2 !== 0) {
1926
+ throw new Error("Expected hex-encoded value");
1927
+ }
1928
+ return Buffer.from(normalized, "hex");
1929
+ }
1930
+ }
1931
+ const isPendingRegisterAgentResponse = (response) => response.status === "pending";
1932
+ const isPartialRegisterAgentResponse = (response) => response.status === "partial" && response.success === false;
1933
+ const isSuccessRegisterAgentResponse = (response) => response.success === true && response.status !== "pending";
1934
+ class EncryptedChatManager {
1935
+ constructor(client) {
1936
+ this.client = client;
1937
+ }
1938
+ registerConversationContext(context) {
1939
+ this.client.registerConversationContextForEncryption(context);
1940
+ }
1941
+ async startSession(options) {
1942
+ await this.client.encryptionReady();
1943
+ const session = await this.client.chat.createSession({
1944
+ uaid: options.uaid,
1945
+ senderUaid: options.senderUaid,
1946
+ encryptionRequested: true,
1947
+ historyTtlSeconds: options.historyTtlSeconds,
1948
+ auth: options.auth
1949
+ });
1950
+ options.onSessionCreated?.(session.sessionId);
1951
+ const summary = session.encryption;
1952
+ if (!summary?.enabled) {
1953
+ throw new EncryptionUnavailableError(
1954
+ session.sessionId,
1955
+ session.encryption ?? null
1956
+ );
1957
+ }
1958
+ const handle = await this.establishRequesterContext({
1959
+ sessionId: session.sessionId,
1960
+ summary,
1961
+ senderUaid: options.senderUaid,
1962
+ handshakeTimeoutMs: options.handshakeTimeoutMs,
1963
+ pollIntervalMs: options.pollIntervalMs
1964
+ });
1965
+ return handle;
1966
+ }
1967
+ async acceptSession(options) {
1968
+ await this.client.encryptionReady();
1969
+ const summary = await this.waitForEncryptionSummary(
1970
+ options.sessionId,
1971
+ options.handshakeTimeoutMs,
1972
+ options.pollIntervalMs
1973
+ );
1974
+ const handle = await this.establishResponderContext({
1975
+ sessionId: options.sessionId,
1976
+ summary,
1977
+ responderUaid: options.responderUaid,
1978
+ handshakeTimeoutMs: options.handshakeTimeoutMs,
1979
+ pollIntervalMs: options.pollIntervalMs
1980
+ });
1981
+ return handle;
1982
+ }
1983
+ async establishRequesterContext(params) {
1984
+ const keyPair = this.client.encryption.generateEphemeralKeyPair();
1985
+ await this.client.chat.submitEncryptionHandshake(params.sessionId, {
1986
+ role: "requester",
1987
+ keyType: "secp256k1",
1988
+ ephemeralPublicKey: keyPair.publicKey,
1989
+ uaid: params.senderUaid ?? params.summary.requester?.uaid ?? void 0
1990
+ });
1991
+ const { summary, record } = await this.waitForHandshakeCompletion(
1992
+ params.sessionId,
1993
+ params.handshakeTimeoutMs,
1994
+ params.pollIntervalMs
1995
+ );
1996
+ const responderKey = record.responder?.ephemeralPublicKey;
1997
+ if (!responderKey) {
1998
+ throw new Error("Responder handshake was not completed in time");
1999
+ }
2000
+ const sharedSecret = this.client.encryption.deriveSharedSecret({
2001
+ privateKey: keyPair.privateKey,
2002
+ peerPublicKey: responderKey
2003
+ }).subarray();
2004
+ const recipients = this.buildRecipients(summary);
2005
+ return this.createHandle({
2006
+ sessionId: params.sessionId,
2007
+ sharedSecret,
2008
+ summary,
2009
+ recipients,
2010
+ identity: summary.requester ?? void 0
2011
+ });
2012
+ }
2013
+ async establishResponderContext(params) {
2014
+ const keyPair = this.client.encryption.generateEphemeralKeyPair();
2015
+ await this.client.chat.submitEncryptionHandshake(params.sessionId, {
2016
+ role: "responder",
2017
+ keyType: "secp256k1",
2018
+ ephemeralPublicKey: keyPair.publicKey,
2019
+ uaid: params.responderUaid ?? params.summary.responder?.uaid ?? void 0
2020
+ });
2021
+ const { summary, record } = await this.waitForHandshakeCompletion(
2022
+ params.sessionId,
2023
+ params.handshakeTimeoutMs,
2024
+ params.pollIntervalMs
2025
+ );
2026
+ const requesterKey = record.requester?.ephemeralPublicKey;
2027
+ if (!requesterKey) {
2028
+ throw new Error("Requester handshake was not detected in time");
2029
+ }
2030
+ const sharedSecret = this.client.encryption.deriveSharedSecret({
2031
+ privateKey: keyPair.privateKey,
2032
+ peerPublicKey: requesterKey
2033
+ }).subarray();
2034
+ const recipients = this.buildRecipients(summary);
2035
+ return this.createHandle({
2036
+ sessionId: params.sessionId,
2037
+ sharedSecret,
2038
+ summary,
2039
+ recipients,
2040
+ identity: summary.responder ?? void 0
2041
+ });
2042
+ }
2043
+ async waitForHandshakeCompletion(sessionId, timeoutMs = 3e4, pollIntervalMs = 1e3) {
2044
+ const deadline = Date.now() + timeoutMs;
2045
+ while (true) {
2046
+ const status = await this.client.chat.getEncryptionStatus(sessionId);
2047
+ const summary = status.encryption;
2048
+ const record = summary?.handshake;
2049
+ if (summary && record && record.status === "complete") {
2050
+ return { summary, record };
2051
+ }
2052
+ if (Date.now() >= deadline) {
2053
+ throw new Error("Timed out waiting for encrypted handshake completion");
2054
+ }
2055
+ await this.delay(pollIntervalMs);
2056
+ }
2057
+ }
2058
+ async waitForEncryptionSummary(sessionId, _timeoutMs = 3e4, _pollIntervalMs = 1e3) {
2059
+ const status = await this.client.chat.getEncryptionStatus(sessionId);
2060
+ if (!status.encryption?.enabled) {
2061
+ throw new EncryptionUnavailableError(
2062
+ sessionId,
2063
+ status.encryption ?? null
2064
+ );
2065
+ }
2066
+ return status.encryption;
2067
+ }
2068
+ buildRecipients(summary) {
2069
+ const candidates = [summary.requester, summary.responder].filter(Boolean);
2070
+ const normalized = candidates.map((candidate) => {
2071
+ if (!candidate) {
2072
+ return null;
2073
+ }
2074
+ const recipient = {};
2075
+ if (candidate.uaid) {
2076
+ recipient.uaid = candidate.uaid;
2077
+ }
2078
+ if (candidate.ledgerAccountId) {
2079
+ recipient.ledgerAccountId = candidate.ledgerAccountId;
2080
+ }
2081
+ if (candidate.userId) {
2082
+ recipient.userId = candidate.userId;
2083
+ }
2084
+ if (candidate.email) {
2085
+ recipient.email = candidate.email;
2086
+ }
2087
+ return recipient;
2088
+ }).filter(
2089
+ (entry) => Boolean(
2090
+ entry?.uaid || entry?.ledgerAccountId || entry?.userId || entry?.email
2091
+ )
2092
+ );
2093
+ if (normalized.length > 0) {
2094
+ return normalized;
2095
+ }
2096
+ if (summary.responder?.uaid) {
2097
+ return [{ uaid: summary.responder.uaid }];
2098
+ }
2099
+ return [];
2100
+ }
2101
+ createHandle(context) {
2102
+ const sharedSecret = context.sharedSecret;
2103
+ const uaid = context.summary.requester?.uaid ?? context.summary.responder?.uaid ?? context.identity?.uaid;
2104
+ const handle = {
2105
+ sessionId: context.sessionId,
2106
+ mode: "encrypted",
2107
+ summary: context.summary,
2108
+ send: async (options) => {
2109
+ const recipients = options.recipients ?? context.recipients;
2110
+ return this.client.chat.sendMessage({
2111
+ sessionId: context.sessionId,
2112
+ message: options.message ?? "[ciphertext omitted]",
2113
+ streaming: options.streaming,
2114
+ auth: options.auth,
2115
+ uaid,
2116
+ encryption: {
2117
+ plaintext: options.plaintext,
2118
+ sharedSecret: Buffer.from(sharedSecret),
2119
+ recipients
2120
+ }
2121
+ });
2122
+ },
2123
+ decryptHistoryEntry: (entry) => this.decryptEntry(entry, context.identity, sharedSecret)
2124
+ };
2125
+ this.registerConversationContext({
2126
+ sessionId: context.sessionId,
2127
+ sharedSecret,
2128
+ identity: context.identity
2129
+ });
2130
+ return handle;
2131
+ }
2132
+ decryptEntry(entry, identity, fallbackSecret) {
2133
+ const envelope = entry.cipherEnvelope;
2134
+ if (!envelope) {
2135
+ return null;
2136
+ }
2137
+ const secret = Buffer.from(fallbackSecret);
2138
+ try {
2139
+ return this.client.encryption.decryptCipherEnvelope({
2140
+ envelope,
2141
+ sharedSecret: secret
2142
+ });
2143
+ } catch (_error) {
2144
+ return null;
2145
+ }
2146
+ }
2147
+ recipientMatches(candidate, target) {
2148
+ if (target.uaid && candidate.uaid?.toLowerCase() === target.uaid.toLowerCase()) {
2149
+ return true;
2150
+ }
2151
+ if (target.ledgerAccountId && candidate.ledgerAccountId?.toLowerCase() === target.ledgerAccountId.toLowerCase()) {
2152
+ return true;
2153
+ }
2154
+ if (target.userId && candidate.userId === target.userId) {
2155
+ return true;
2156
+ }
2157
+ if (target.email && candidate.email?.toLowerCase() === target.email.toLowerCase()) {
2158
+ return true;
2159
+ }
2160
+ return false;
2161
+ }
2162
+ async delay(ms) {
2163
+ if (ms <= 0) {
2164
+ return;
2165
+ }
2166
+ await new Promise((resolve) => setTimeout(resolve, ms));
2167
+ }
2168
+ }
2169
+ class EncryptionUnavailableError extends Error {
2170
+ constructor(sessionId, summary) {
2171
+ super("Encryption is not enabled for this session");
2172
+ this.sessionId = sessionId;
2173
+ this.summary = summary;
2174
+ }
2175
+ }
72
2176
  export {
73
- createPrivateKeySigner
2177
+ RegistryBrokerClient,
2178
+ RegistryBrokerError,
2179
+ RegistryBrokerParseError,
2180
+ isPartialRegisterAgentResponse,
2181
+ isPendingRegisterAgentResponse,
2182
+ isSuccessRegisterAgentResponse
74
2183
  };
75
2184
  //# sourceMappingURL=standards-sdk.es128.js.map