@hashgraphonline/standards-sdk 0.1.146-chore-jsr-improvements.canary.46c0c0f.91 → 0.1.146-chore-jsr-improvements.canary.01d3174.92

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 (138) hide show
  1. package/dist/cjs/services/registry-broker/client/base-client.d.ts +14 -1
  2. package/dist/cjs/services/registry-broker/client/base-client.d.ts.map +1 -1
  3. package/dist/cjs/services/registry-broker/client/search-helpers.d.ts +16 -0
  4. package/dist/cjs/services/registry-broker/client/search-helpers.d.ts.map +1 -0
  5. package/dist/cjs/services/registry-broker/client/search.d.ts +5 -18
  6. package/dist/cjs/services/registry-broker/client/search.d.ts.map +1 -1
  7. package/dist/cjs/standards-sdk.cjs +1 -1
  8. package/dist/cjs/standards-sdk.cjs.map +1 -1
  9. package/dist/es/services/registry-broker/client/base-client.d.ts +14 -1
  10. package/dist/es/services/registry-broker/client/base-client.d.ts.map +1 -1
  11. package/dist/es/services/registry-broker/client/search-helpers.d.ts +16 -0
  12. package/dist/es/services/registry-broker/client/search-helpers.d.ts.map +1 -0
  13. package/dist/es/services/registry-broker/client/search.d.ts +5 -18
  14. package/dist/es/services/registry-broker/client/search.d.ts.map +1 -1
  15. package/dist/es/standards-sdk.es.js +9 -10
  16. package/dist/es/standards-sdk.es.js.map +1 -1
  17. package/dist/es/standards-sdk.es101.js +1 -1
  18. package/dist/es/standards-sdk.es103.js +1 -1
  19. package/dist/es/standards-sdk.es109.js +2 -3
  20. package/dist/es/standards-sdk.es109.js.map +1 -1
  21. package/dist/es/standards-sdk.es11.js +1 -1
  22. package/dist/es/standards-sdk.es110.js +5 -5
  23. package/dist/es/standards-sdk.es12.js +1 -1
  24. package/dist/es/standards-sdk.es120.js +1 -1
  25. package/dist/es/standards-sdk.es121.js +1 -1
  26. package/dist/es/standards-sdk.es122.js +5 -5
  27. package/dist/es/standards-sdk.es124.js +1 -1
  28. package/dist/es/standards-sdk.es125.js +1 -1
  29. package/dist/es/standards-sdk.es127.js +3 -3
  30. package/dist/es/standards-sdk.es128.js +61 -164
  31. package/dist/es/standards-sdk.es128.js.map +1 -1
  32. package/dist/es/standards-sdk.es129.js +102 -85
  33. package/dist/es/standards-sdk.es129.js.map +1 -1
  34. package/dist/es/standards-sdk.es130.js +222 -96
  35. package/dist/es/standards-sdk.es130.js.map +1 -1
  36. package/dist/es/standards-sdk.es131.js +153 -220
  37. package/dist/es/standards-sdk.es131.js.map +1 -1
  38. package/dist/es/standards-sdk.es132.js +104 -162
  39. package/dist/es/standards-sdk.es132.js.map +1 -1
  40. package/dist/es/standards-sdk.es133.js +296 -92
  41. package/dist/es/standards-sdk.es133.js.map +1 -1
  42. package/dist/es/standards-sdk.es134.js +587 -288
  43. package/dist/es/standards-sdk.es134.js.map +1 -1
  44. package/dist/es/standards-sdk.es135.js +14 -461
  45. package/dist/es/standards-sdk.es135.js.map +1 -1
  46. package/dist/es/standards-sdk.es136.js +79 -15
  47. package/dist/es/standards-sdk.es136.js.map +1 -1
  48. package/dist/es/standards-sdk.es137.js +77 -71
  49. package/dist/es/standards-sdk.es137.js.map +1 -1
  50. package/dist/es/standards-sdk.es138.js +53 -80
  51. package/dist/es/standards-sdk.es138.js.map +1 -1
  52. package/dist/es/standards-sdk.es139.js +152 -53
  53. package/dist/es/standards-sdk.es139.js.map +1 -1
  54. package/dist/es/standards-sdk.es140.js +7 -159
  55. package/dist/es/standards-sdk.es140.js.map +1 -1
  56. package/dist/es/standards-sdk.es141.js +86 -7
  57. package/dist/es/standards-sdk.es141.js.map +1 -1
  58. package/dist/es/standards-sdk.es142.js +43 -64
  59. package/dist/es/standards-sdk.es142.js.map +1 -1
  60. package/dist/es/standards-sdk.es143.js +30 -65
  61. package/dist/es/standards-sdk.es143.js.map +1 -1
  62. package/dist/es/standards-sdk.es144.js +34 -30
  63. package/dist/es/standards-sdk.es144.js.map +1 -1
  64. package/dist/es/standards-sdk.es145.js +28 -34
  65. package/dist/es/standards-sdk.es145.js.map +1 -1
  66. package/dist/es/standards-sdk.es146.js +138 -28
  67. package/dist/es/standards-sdk.es146.js.map +1 -1
  68. package/dist/es/standards-sdk.es147.js +37 -133
  69. package/dist/es/standards-sdk.es147.js.map +1 -1
  70. package/dist/es/standards-sdk.es148.js +15 -40
  71. package/dist/es/standards-sdk.es148.js.map +1 -1
  72. package/dist/es/standards-sdk.es149.js +12269 -939
  73. package/dist/es/standards-sdk.es149.js.map +1 -1
  74. package/dist/es/standards-sdk.es150.js +939 -12269
  75. package/dist/es/standards-sdk.es150.js.map +1 -1
  76. package/dist/es/standards-sdk.es151.js +54 -15
  77. package/dist/es/standards-sdk.es151.js.map +1 -1
  78. package/dist/es/standards-sdk.es152.js +76 -48
  79. package/dist/es/standards-sdk.es152.js.map +1 -1
  80. package/dist/es/standards-sdk.es153.js +160 -72
  81. package/dist/es/standards-sdk.es153.js.map +1 -1
  82. package/dist/es/standards-sdk.es154.js +289 -139
  83. package/dist/es/standards-sdk.es154.js.map +1 -1
  84. package/dist/es/standards-sdk.es155.js +298 -274
  85. package/dist/es/standards-sdk.es155.js.map +1 -1
  86. package/dist/es/standards-sdk.es156.js +369 -262
  87. package/dist/es/standards-sdk.es156.js.map +1 -1
  88. package/dist/es/standards-sdk.es157.js +194 -316
  89. package/dist/es/standards-sdk.es157.js.map +1 -1
  90. package/dist/es/standards-sdk.es158.js +64 -319
  91. package/dist/es/standards-sdk.es158.js.map +1 -1
  92. package/dist/es/standards-sdk.es159.js +231 -68
  93. package/dist/es/standards-sdk.es159.js.map +1 -1
  94. package/dist/es/standards-sdk.es16.js +2 -3
  95. package/dist/es/standards-sdk.es16.js.map +1 -1
  96. package/dist/es/standards-sdk.es160.js +223 -218
  97. package/dist/es/standards-sdk.es160.js.map +1 -1
  98. package/dist/es/standards-sdk.es18.js +5 -6
  99. package/dist/es/standards-sdk.es18.js.map +1 -1
  100. package/dist/es/standards-sdk.es19.js +3 -4
  101. package/dist/es/standards-sdk.es19.js.map +1 -1
  102. package/dist/es/standards-sdk.es22.js +1 -1
  103. package/dist/es/standards-sdk.es27.js +5 -6
  104. package/dist/es/standards-sdk.es27.js.map +1 -1
  105. package/dist/es/standards-sdk.es30.js +1 -1
  106. package/dist/es/standards-sdk.es31.js +1 -1
  107. package/dist/es/standards-sdk.es35.js +2 -3
  108. package/dist/es/standards-sdk.es35.js.map +1 -1
  109. package/dist/es/standards-sdk.es36.js +3 -3
  110. package/dist/es/standards-sdk.es37.js +1 -1
  111. package/dist/es/standards-sdk.es4.js +1 -1
  112. package/dist/es/standards-sdk.es53.js +1 -1
  113. package/dist/es/standards-sdk.es56.js +1 -1
  114. package/dist/es/standards-sdk.es58.js +1 -1
  115. package/dist/es/standards-sdk.es59.js +1 -1
  116. package/dist/es/standards-sdk.es60.js +3 -4
  117. package/dist/es/standards-sdk.es60.js.map +1 -1
  118. package/dist/es/standards-sdk.es62.js +1 -1
  119. package/dist/es/standards-sdk.es64.js +1 -1
  120. package/dist/es/standards-sdk.es65.js +2 -2
  121. package/dist/es/standards-sdk.es68.js +2 -2
  122. package/dist/es/standards-sdk.es69.js +1 -1
  123. package/dist/es/standards-sdk.es7.js +1 -1
  124. package/dist/es/standards-sdk.es71.js +1 -1
  125. package/dist/es/standards-sdk.es76.js +1 -1
  126. package/dist/es/standards-sdk.es77.js +2 -3
  127. package/dist/es/standards-sdk.es77.js.map +1 -1
  128. package/dist/es/standards-sdk.es78.js +1 -1
  129. package/dist/es/standards-sdk.es81.js +1 -1
  130. package/dist/es/standards-sdk.es83.js +1 -1
  131. package/dist/es/standards-sdk.es87.js +3 -3
  132. package/dist/es/standards-sdk.es91.js +1 -1
  133. package/dist/es/standards-sdk.es92.js +1 -1
  134. package/dist/es/standards-sdk.es97.js +1 -1
  135. package/dist/es/standards-sdk.es99.js +1 -1
  136. package/package.json +1 -1
  137. package/dist/es/standards-sdk.es161.js +0 -247
  138. package/dist/es/standards-sdk.es161.js.map +0 -1
@@ -1,329 +1,628 @@
1
- import { createSessionResponseSchema, chatHistoryCompactionResponseSchema, sessionEncryptionStatusResponseSchema, encryptionHandshakeResponseSchema, sendMessageResponseSchema } from "./standards-sdk.es149.js";
2
- import { RegistryBrokerClient } from "./standards-sdk.es135.js";
3
- import { serialiseAuthConfig, toJsonObject } from "./standards-sdk.es160.js";
4
- import { EncryptionUnavailableError, EncryptedChatManager } from "./standards-sdk.es161.js";
5
- const encryptedManagers = /* @__PURE__ */ new WeakMap();
6
- const chatApis = /* @__PURE__ */ new WeakMap();
7
- function getEncryptedChatManager(client) {
8
- const existing = encryptedManagers.get(client);
9
- if (existing) {
10
- return existing;
11
- }
12
- const created = new EncryptedChatManager(client);
13
- encryptedManagers.set(client, created);
14
- return created;
15
- }
16
- Object.defineProperty(RegistryBrokerClient.prototype, "chat", {
17
- get() {
18
- const existing = chatApis.get(this);
19
- if (existing) {
20
- return existing;
21
- }
22
- const encryptedManager = getEncryptedChatManager(this);
23
- const api = {
24
- start: (options) => this.startChat(options),
25
- createSession: (payload) => this.createSession(payload),
26
- sendMessage: (payload) => this.sendMessage(payload),
27
- endSession: (sessionId) => this.endSession(sessionId),
28
- getHistory: (sessionId, options) => this.fetchHistorySnapshot(sessionId, options),
29
- compactHistory: (payload) => this.compactHistory(payload),
30
- getEncryptionStatus: (sessionId) => this.fetchEncryptionStatus(sessionId),
31
- submitEncryptionHandshake: (sessionId, payload) => this.postEncryptionHandshake(sessionId, payload),
32
- startConversation: (options) => this.startConversation(options),
33
- acceptConversation: (options) => this.acceptConversation(options),
34
- createEncryptedSession: (options) => encryptedManager.startSession(options),
35
- acceptEncryptedSession: (options) => encryptedManager.acceptSession(options)
1
+ import { Buffer } from "buffer";
2
+ import { randomBytes, createHash, createCipheriv, createDecipheriv } from "crypto";
3
+ import { secp256k1 } from "@noble/curves/secp256k1.js";
4
+ import { ZodError } from "zod";
5
+ import { agentFeedbackResponseSchema, agentFeedbackIndexResponseSchema, agentFeedbackEntriesIndexResponseSchema, agentFeedbackEligibilityResponseSchema, agentFeedbackSubmissionResponseSchema, searchResponseSchema, statsResponseSchema, registriesResponseSchema, additionalRegistryCatalogResponseSchema, popularResponseSchema, protocolsResponseSchema, detectProtocolResponseSchema, registrySearchByNamespaceSchema, vectorSearchResponseSchema, searchStatusResponseSchema, websocketStatsResponseSchema, metricsSummaryResponseSchema, searchFacetsResponseSchema } from "./standards-sdk.es150.js";
6
+ import { DEFAULT_BASE_URL, normaliseBaseUrl, normaliseHeaderName, isBrowserRuntime, DEFAULT_USER_AGENT, JSON_CONTENT_TYPE, createAbortError, isJsonObject, DEFAULT_HISTORY_TOP_UP_HBAR, buildSearchQuery } from "./standards-sdk.es159.js";
7
+ import { RegistryBrokerError, RegistryBrokerParseError } from "./standards-sdk.es135.js";
8
+ class RegistryBrokerClient {
9
+ constructor(options = {}) {
10
+ this.encryptionBootstrapPromise = null;
11
+ const {
12
+ baseUrl = DEFAULT_BASE_URL,
13
+ fetchImplementation,
14
+ defaultHeaders,
15
+ apiKey,
16
+ ledgerApiKey,
17
+ registrationAutoTopUp,
18
+ historyAutoTopUp,
19
+ encryption
20
+ } = options;
21
+ this.baseUrl = normaliseBaseUrl(baseUrl);
22
+ this.fetchImpl = fetchImplementation ?? fetch;
23
+ this.defaultHeaders = {
24
+ ...defaultHeaders ?? {}
36
25
  };
37
- chatApis.set(this, api);
38
- return api;
26
+ Object.entries(this.defaultHeaders).forEach(([key, value]) => {
27
+ const headerName = normaliseHeaderName(key);
28
+ if (headerName !== key) {
29
+ delete this.defaultHeaders[key];
30
+ this.defaultHeaders[headerName] = value;
31
+ }
32
+ });
33
+ if (apiKey) {
34
+ this.defaultHeaders["x-api-key"] = apiKey;
35
+ }
36
+ if (ledgerApiKey) {
37
+ this.defaultHeaders["x-ledger-api-key"] = ledgerApiKey;
38
+ }
39
+ this.registrationAutoTopUp = registrationAutoTopUp;
40
+ this.historyAutoTopUp = historyAutoTopUp;
41
+ this.encryptionOptions = encryption;
42
+ if (this.encryptionOptions) {
43
+ this.encryptionBootstrapPromise = this.initializeEncryptionBootstrap(
44
+ this.encryptionOptions
45
+ );
46
+ }
39
47
  }
40
- });
41
- RegistryBrokerClient.prototype.createSession = async function(payload, allowHistoryAutoTopUp = true) {
42
- const body = {};
43
- if ("uaid" in payload && payload.uaid) {
44
- body.uaid = payload.uaid;
48
+ static async initializeAgent(options) {
49
+ const { uaid, ensureEncryptionKey = true, ...clientOptions } = options;
50
+ const client = new RegistryBrokerClient(clientOptions);
51
+ let encryption = null;
52
+ if (ensureEncryptionKey) {
53
+ const ensureOptions = typeof ensureEncryptionKey === "object" ? ensureEncryptionKey : { generateIfMissing: true };
54
+ encryption = await client.encryption.ensureAgentKey({
55
+ uaid,
56
+ ...ensureOptions
57
+ });
58
+ }
59
+ return { client, encryption };
45
60
  }
46
- if ("agentUrl" in payload && payload.agentUrl) {
47
- body.agentUrl = payload.agentUrl;
61
+ setApiKey(apiKey) {
62
+ this.setDefaultHeader("x-api-key", apiKey);
48
63
  }
49
- if (payload.auth) {
50
- body.auth = serialiseAuthConfig(payload.auth);
64
+ setLedgerApiKey(apiKey) {
65
+ this.setDefaultHeader("x-ledger-api-key", apiKey);
51
66
  }
52
- if (payload.historyTtlSeconds !== void 0) {
53
- body.historyTtlSeconds = payload.historyTtlSeconds;
67
+ setDefaultHeader(name, value) {
68
+ if (!name || name.trim().length === 0) {
69
+ return;
70
+ }
71
+ const headerName = normaliseHeaderName(name);
72
+ if (!value || value.trim().length === 0) {
73
+ delete this.defaultHeaders[headerName];
74
+ return;
75
+ }
76
+ this.defaultHeaders[headerName] = value.trim();
54
77
  }
55
- if (payload.encryptionRequested !== void 0) {
56
- body.encryptionRequested = payload.encryptionRequested;
78
+ getDefaultHeaders() {
79
+ return { ...this.defaultHeaders };
57
80
  }
58
- if (payload.senderUaid) {
59
- body.senderUaid = payload.senderUaid;
81
+ async encryptionReady() {
82
+ if (!this.encryptionBootstrapPromise) {
83
+ return;
84
+ }
85
+ await this.encryptionBootstrapPromise;
60
86
  }
61
- try {
62
- const raw = await this.requestJson("/chat/session", {
63
- method: "POST",
64
- body,
65
- headers: { "content-type": "application/json" }
87
+ buildUrl(path) {
88
+ const normalisedPath = path.startsWith("/") ? path : `/${path}`;
89
+ return `${this.baseUrl}${normalisedPath}`;
90
+ }
91
+ async request(path, config) {
92
+ const headers = new Headers();
93
+ Object.entries(this.defaultHeaders).forEach(([key, value]) => {
94
+ headers.set(key, value);
66
95
  });
96
+ if (config.headers) {
97
+ Object.entries(config.headers).forEach(([key, value]) => {
98
+ headers.set(key, value);
99
+ });
100
+ }
101
+ if (!headers.has("accept")) {
102
+ headers.set("accept", "application/json");
103
+ }
104
+ if (!headers.has("user-agent") && !isBrowserRuntime()) {
105
+ headers.set("user-agent", DEFAULT_USER_AGENT);
106
+ }
107
+ const init = {
108
+ method: config.method ?? "GET",
109
+ headers
110
+ };
111
+ if (config.body !== void 0) {
112
+ init.body = JSON.stringify(config.body);
113
+ if (!headers.has("content-type")) {
114
+ headers.set("content-type", "application/json");
115
+ }
116
+ }
117
+ const response = await this.fetchImpl(this.buildUrl(path), init);
118
+ if (response.ok) {
119
+ return response;
120
+ }
121
+ const errorBody = await this.extractErrorBody(response);
122
+ throw new RegistryBrokerError("Registry broker request failed", {
123
+ status: response.status,
124
+ statusText: response.statusText,
125
+ body: errorBody
126
+ });
127
+ }
128
+ async requestJson(path, config) {
129
+ const response = await this.request(path, config);
130
+ const contentType = response.headers?.get("content-type") ?? "";
131
+ if (!JSON_CONTENT_TYPE.test(contentType)) {
132
+ const body = await response.text();
133
+ throw new RegistryBrokerParseError(
134
+ "Expected JSON response from registry broker",
135
+ body
136
+ );
137
+ }
138
+ return await response.json();
139
+ }
140
+ async getAgentFeedback(uaid, options = {}) {
141
+ const normalized = uaid.trim();
142
+ if (!normalized) {
143
+ throw new Error("uaid is required");
144
+ }
145
+ const query = options.includeRevoked === true ? "?includeRevoked=true" : "";
146
+ const raw = await this.requestJson(
147
+ `/agents/${encodeURIComponent(normalized)}/feedback${query}`,
148
+ { method: "GET" }
149
+ );
67
150
  return this.parseWithSchema(
68
151
  raw,
69
- createSessionResponseSchema,
70
- "chat session response"
152
+ agentFeedbackResponseSchema,
153
+ "agent feedback response"
71
154
  );
72
- } catch (error) {
73
- const maybeError = error instanceof Error ? error : null;
74
- if (allowHistoryAutoTopUp && this.shouldAutoTopUpHistory(payload, maybeError)) {
75
- await this.executeHistoryAutoTopUp("chat.session");
76
- return this.createSession(payload, false);
77
- }
78
- throw error;
79
155
  }
80
- };
81
- RegistryBrokerClient.prototype.startChat = async function(options) {
82
- if ("uaid" in options && options.uaid) {
83
- return this.startConversation({
84
- uaid: options.uaid,
85
- senderUaid: options.senderUaid,
86
- historyTtlSeconds: options.historyTtlSeconds,
87
- auth: options.auth,
88
- encryption: options.encryption,
89
- onSessionCreated: options.onSessionCreated
156
+ async listAgentFeedbackIndex(options = {}) {
157
+ const params = new URLSearchParams();
158
+ if (typeof options.page === "number" && Number.isFinite(options.page)) {
159
+ params.set("page", String(Math.trunc(options.page)));
160
+ }
161
+ if (typeof options.limit === "number" && Number.isFinite(options.limit)) {
162
+ params.set("limit", String(Math.trunc(options.limit)));
163
+ }
164
+ if (options.registries?.length) {
165
+ params.set("registry", options.registries.join(","));
166
+ }
167
+ const suffix = params.size > 0 ? `?${params.toString()}` : "";
168
+ const raw = await this.requestJson(`/agents/feedback${suffix}`, {
169
+ method: "GET"
90
170
  });
171
+ return this.parseWithSchema(
172
+ raw,
173
+ agentFeedbackIndexResponseSchema,
174
+ "agent feedback index response"
175
+ );
91
176
  }
92
- if ("agentUrl" in options && options.agentUrl) {
93
- const session = await this.createSession({
94
- agentUrl: options.agentUrl,
95
- auth: options.auth,
96
- historyTtlSeconds: options.historyTtlSeconds,
97
- senderUaid: options.senderUaid
98
- });
99
- options.onSessionCreated?.(session.sessionId);
100
- return this.createPlaintextConversationHandle(
101
- session.sessionId,
102
- session.encryption ?? null,
103
- options.auth,
104
- { agentUrl: options.agentUrl, uaid: options.uaid }
177
+ async listAgentFeedbackEntriesIndex(options = {}) {
178
+ const params = new URLSearchParams();
179
+ if (typeof options.page === "number" && Number.isFinite(options.page)) {
180
+ params.set("page", String(Math.trunc(options.page)));
181
+ }
182
+ if (typeof options.limit === "number" && Number.isFinite(options.limit)) {
183
+ params.set("limit", String(Math.trunc(options.limit)));
184
+ }
185
+ if (options.registries?.length) {
186
+ params.set("registry", options.registries.join(","));
187
+ }
188
+ const suffix = params.size > 0 ? `?${params.toString()}` : "";
189
+ const raw = await this.requestJson(
190
+ `/agents/feedback/entries${suffix}`,
191
+ { method: "GET" }
192
+ );
193
+ return this.parseWithSchema(
194
+ raw,
195
+ agentFeedbackEntriesIndexResponseSchema,
196
+ "agent feedback entries index response"
105
197
  );
106
198
  }
107
- throw new Error("startChat requires either uaid or agentUrl");
108
- };
109
- RegistryBrokerClient.prototype.startConversation = async function(options) {
110
- const preference = options.encryption?.preference ?? "preferred";
111
- const requestEncryption = preference !== "disabled";
112
- if (!requestEncryption) {
113
- const session = await this.createSession({
114
- uaid: options.uaid,
115
- auth: options.auth,
116
- historyTtlSeconds: options.historyTtlSeconds,
117
- senderUaid: options.senderUaid,
118
- encryptionRequested: false
119
- });
120
- options.onSessionCreated?.(session.sessionId);
121
- return this.createPlaintextConversationHandle(
122
- session.sessionId,
123
- session.encryption ?? null,
124
- options.auth,
125
- { uaid: options.uaid }
199
+ async checkAgentFeedbackEligibility(uaid, payload) {
200
+ const normalized = uaid.trim();
201
+ if (!normalized) {
202
+ throw new Error("uaid is required");
203
+ }
204
+ const raw = await this.requestJson(
205
+ `/agents/${encodeURIComponent(normalized)}/feedback/eligibility`,
206
+ {
207
+ method: "POST",
208
+ body: payload,
209
+ headers: { "content-type": "application/json" }
210
+ }
211
+ );
212
+ return this.parseWithSchema(
213
+ raw,
214
+ agentFeedbackEligibilityResponseSchema,
215
+ "agent feedback eligibility response"
126
216
  );
127
217
  }
128
- try {
129
- const encryptedManager = getEncryptedChatManager(this);
130
- const handle = await encryptedManager.startSession({
131
- uaid: options.uaid,
132
- senderUaid: options.senderUaid,
133
- historyTtlSeconds: options.historyTtlSeconds,
134
- handshakeTimeoutMs: options.encryption?.handshakeTimeoutMs,
135
- pollIntervalMs: options.encryption?.pollIntervalMs,
136
- onSessionCreated: (sessionId) => {
137
- options.onSessionCreated?.(sessionId);
138
- },
139
- auth: options.auth
140
- });
141
- return handle;
142
- } catch (error) {
143
- if (error instanceof EncryptionUnavailableError) {
144
- if (preference === "required") {
145
- throw error;
218
+ async submitAgentFeedback(uaid, payload) {
219
+ const normalized = uaid.trim();
220
+ if (!normalized) {
221
+ throw new Error("uaid is required");
222
+ }
223
+ const raw = await this.requestJson(
224
+ `/agents/${encodeURIComponent(normalized)}/feedback`,
225
+ {
226
+ method: "POST",
227
+ body: payload,
228
+ headers: { "content-type": "application/json" }
146
229
  }
147
- return this.createPlaintextConversationHandle(
148
- error.sessionId,
149
- error.summary ?? null,
150
- options.auth,
151
- { uaid: options.uaid }
230
+ );
231
+ return this.parseWithSchema(
232
+ raw,
233
+ agentFeedbackSubmissionResponseSchema,
234
+ "agent feedback submission response"
235
+ );
236
+ }
237
+ async extractErrorBody(response) {
238
+ const contentType = response.headers?.get("content-type") ?? "";
239
+ if (JSON_CONTENT_TYPE.test(contentType)) {
240
+ try {
241
+ return await response.json();
242
+ } catch (error) {
243
+ return { parseError: String(error) };
244
+ }
245
+ }
246
+ try {
247
+ return await response.text();
248
+ } catch (error) {
249
+ return { parseError: String(error) };
250
+ }
251
+ }
252
+ parseWithSchema(value, schema, context) {
253
+ try {
254
+ return schema.parse(value);
255
+ } catch (error) {
256
+ throw new RegistryBrokerParseError(
257
+ `Failed to parse ${context}`,
258
+ error instanceof ZodError || error instanceof Error ? error : String(error),
259
+ value
152
260
  );
153
261
  }
154
- throw error;
155
262
  }
156
- };
157
- RegistryBrokerClient.prototype.acceptConversation = async function(options) {
158
- const preference = options.encryption?.preference ?? "preferred";
159
- if (preference === "disabled") {
160
- return this.createPlaintextConversationHandle(options.sessionId, null);
161
- }
162
- try {
163
- const encryptedManager = getEncryptedChatManager(this);
164
- const handle = await encryptedManager.acceptSession({
165
- sessionId: options.sessionId,
166
- responderUaid: options.responderUaid,
167
- handshakeTimeoutMs: options.encryption?.handshakeTimeoutMs,
168
- pollIntervalMs: options.encryption?.pollIntervalMs
263
+ async delay(ms, signal) {
264
+ if (ms <= 0) {
265
+ if (signal?.aborted) {
266
+ throw createAbortError();
267
+ }
268
+ return;
269
+ }
270
+ await new Promise((resolve, reject) => {
271
+ const timer = setTimeout(() => {
272
+ if (signal) {
273
+ signal.removeEventListener("abort", onAbort);
274
+ }
275
+ resolve();
276
+ }, ms);
277
+ const onAbort = () => {
278
+ clearTimeout(timer);
279
+ signal?.removeEventListener("abort", onAbort);
280
+ reject(createAbortError());
281
+ };
282
+ if (signal) {
283
+ if (signal.aborted) {
284
+ clearTimeout(timer);
285
+ reject(createAbortError());
286
+ return;
287
+ }
288
+ signal.addEventListener("abort", onAbort, { once: true });
289
+ }
169
290
  });
170
- return handle;
171
- } catch (error) {
172
- if (error instanceof EncryptionUnavailableError && preference !== "required") {
173
- return this.createPlaintextConversationHandle(
174
- options.sessionId,
175
- null,
176
- void 0,
177
- { uaid: options.responderUaid }
178
- );
291
+ }
292
+ assertNodeRuntime(feature) {
293
+ if (typeof process === "undefined" || !process.versions?.node) {
294
+ throw new Error(`${feature} is only available in Node.js environments`);
179
295
  }
180
- throw error;
181
296
  }
182
- };
183
- RegistryBrokerClient.prototype.createPlaintextConversationHandle = function(sessionId, summary, defaultAuth, context) {
184
- const uaid = context?.uaid?.trim();
185
- const agentUrl = context?.agentUrl?.trim();
186
- return {
187
- sessionId,
188
- mode: "plaintext",
189
- summary: summary ?? null,
190
- send: async (options) => {
191
- const plaintext = options.plaintext;
192
- if (!plaintext || plaintext.trim().length === 0) {
193
- throw new Error("plaintext is required for chat messages");
297
+ createEphemeralKeyPair() {
298
+ this.assertNodeRuntime("generateEphemeralKeyPair");
299
+ const privateKeyBytes = randomBytes(32);
300
+ const publicKey = secp256k1.getPublicKey(privateKeyBytes, true);
301
+ return {
302
+ privateKey: Buffer.from(privateKeyBytes).toString("hex"),
303
+ publicKey: Buffer.from(publicKey).toString("hex")
304
+ };
305
+ }
306
+ deriveSharedSecret(options) {
307
+ this.assertNodeRuntime("deriveSharedSecret");
308
+ const privateKey = this.hexToBuffer(options.privateKey);
309
+ const peerPublicKey = this.hexToBuffer(options.peerPublicKey);
310
+ const shared = secp256k1.getSharedSecret(privateKey, peerPublicKey, true);
311
+ return createHash("sha256").update(Buffer.from(shared)).digest();
312
+ }
313
+ buildCipherEnvelope(options) {
314
+ this.assertNodeRuntime("encryptCipherEnvelope");
315
+ const sharedSecret = this.normalizeSharedSecret(options.sharedSecret);
316
+ const iv = randomBytes(12);
317
+ const cipher = createCipheriv("aes-256-gcm", sharedSecret, iv);
318
+ const aadSource = options.associatedData ?? options.sessionId;
319
+ const associatedDataEncoded = aadSource ? Buffer.from(aadSource, "utf8").toString("base64") : void 0;
320
+ if (aadSource) {
321
+ cipher.setAAD(Buffer.from(aadSource, "utf8"));
322
+ }
323
+ const ciphertext = Buffer.concat([
324
+ cipher.update(Buffer.from(options.plaintext, "utf8")),
325
+ cipher.final()
326
+ ]);
327
+ const tag = cipher.getAuthTag();
328
+ const payload = Buffer.concat([ciphertext, tag]);
329
+ return {
330
+ algorithm: "aes-256-gcm",
331
+ ciphertext: payload.toString("base64"),
332
+ nonce: iv.toString("base64"),
333
+ associatedData: associatedDataEncoded,
334
+ keyLocator: {
335
+ sessionId: options.sessionId,
336
+ revision: options.revision ?? 1
337
+ },
338
+ recipients: options.recipients.map((recipient) => ({
339
+ ...recipient,
340
+ encryptedShare: ""
341
+ }))
342
+ };
343
+ }
344
+ openCipherEnvelope(options) {
345
+ this.assertNodeRuntime("decryptCipherEnvelope");
346
+ const sharedSecret = this.normalizeSharedSecret(options.sharedSecret);
347
+ const payload = Buffer.from(options.envelope.ciphertext, "base64");
348
+ const nonce = Buffer.from(options.envelope.nonce, "base64");
349
+ const ciphertext = payload.slice(0, payload.length - 16);
350
+ const tag = payload.slice(payload.length - 16);
351
+ const decipher = createDecipheriv("aes-256-gcm", sharedSecret, nonce);
352
+ if (options.envelope.associatedData) {
353
+ decipher.setAAD(Buffer.from(options.envelope.associatedData, "base64"));
354
+ }
355
+ decipher.setAuthTag(tag);
356
+ const plaintext = Buffer.concat([
357
+ decipher.update(ciphertext),
358
+ decipher.final()
359
+ ]);
360
+ return plaintext.toString(options.encoding ?? "utf8");
361
+ }
362
+ normalizeSharedSecret(input) {
363
+ if (Buffer.isBuffer(input)) {
364
+ return Buffer.from(input);
365
+ }
366
+ if (input instanceof Uint8Array) {
367
+ return Buffer.from(input);
368
+ }
369
+ if (typeof input === "string") {
370
+ return this.bufferFromString(input);
371
+ }
372
+ throw new Error("Unsupported shared secret input");
373
+ }
374
+ bufferFromString(value) {
375
+ const trimmed = value.trim();
376
+ if (!trimmed) {
377
+ throw new Error("sharedSecret string cannot be empty");
378
+ }
379
+ const normalized = trimmed.startsWith("0x") ? trimmed.slice(2) : trimmed;
380
+ if (/^[0-9a-fA-F]+$/.test(normalized) && normalized.length % 2 === 0) {
381
+ return Buffer.from(normalized, "hex");
382
+ }
383
+ return Buffer.from(trimmed, "base64");
384
+ }
385
+ hexToBuffer(value) {
386
+ const normalized = value.startsWith("0x") ? value.slice(2) : value;
387
+ if (!/^[0-9a-fA-F]+$/.test(normalized) || normalized.length % 2 !== 0) {
388
+ throw new Error("Expected hex-encoded value");
389
+ }
390
+ return Buffer.from(normalized, "hex");
391
+ }
392
+ extractInsufficientCreditsDetails(error) {
393
+ if (!(error instanceof RegistryBrokerError) || error.status !== 402) {
394
+ return null;
395
+ }
396
+ const body = error.body;
397
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
398
+ return null;
399
+ }
400
+ const maybeShortfall = body["shortfallCredits"];
401
+ if (typeof maybeShortfall !== "number" || maybeShortfall <= 0) {
402
+ return null;
403
+ }
404
+ return { shortfallCredits: maybeShortfall };
405
+ }
406
+ extractErrorMessage(body) {
407
+ if (typeof body === "string") {
408
+ return body;
409
+ }
410
+ if (isJsonObject(body) && typeof body.error === "string") {
411
+ return body.error;
412
+ }
413
+ if (isJsonObject(body) && typeof body.message === "string") {
414
+ return body.message;
415
+ }
416
+ return void 0;
417
+ }
418
+ shouldAutoTopUpHistory(payload, error) {
419
+ if (!this.historyAutoTopUp || payload.historyTtlSeconds === void 0) {
420
+ return false;
421
+ }
422
+ if (!(error instanceof RegistryBrokerError)) {
423
+ return false;
424
+ }
425
+ if (error.status !== 402) {
426
+ return false;
427
+ }
428
+ const message = this.extractErrorMessage(error.body);
429
+ if (!message) {
430
+ return true;
431
+ }
432
+ const normalised = message.toLowerCase();
433
+ return normalised.includes("history") || normalised.includes("chat history");
434
+ }
435
+ async executeHistoryAutoTopUp(reason) {
436
+ if (!this.historyAutoTopUp) {
437
+ return;
438
+ }
439
+ const hbarAmount = this.historyAutoTopUp.hbarAmount && this.historyAutoTopUp.hbarAmount > 0 ? this.historyAutoTopUp.hbarAmount : DEFAULT_HISTORY_TOP_UP_HBAR;
440
+ await this.purchaseCreditsWithHbar({
441
+ accountId: this.historyAutoTopUp.accountId,
442
+ privateKey: this.historyAutoTopUp.privateKey,
443
+ hbarAmount,
444
+ memo: this.historyAutoTopUp.memo ?? "registry-broker-client:chat-history-topup",
445
+ metadata: {
446
+ purpose: "chat-history",
447
+ reason
194
448
  }
195
- const message = options.message ?? plaintext;
196
- return this.sendMessage({
197
- sessionId,
198
- message,
199
- streaming: options.streaming,
200
- auth: options.auth ?? defaultAuth,
201
- uaid,
202
- agentUrl
203
- });
204
- },
205
- decryptHistoryEntry: (entry) => entry.content
206
- };
207
- };
208
- RegistryBrokerClient.prototype.compactHistory = async function(payload) {
209
- if (!payload.sessionId || payload.sessionId.trim().length === 0) {
210
- throw new Error("sessionId is required to compact chat history");
449
+ });
211
450
  }
212
- const body = {};
213
- if (typeof payload.preserveEntries === "number" && Number.isFinite(payload.preserveEntries) && payload.preserveEntries >= 0) {
214
- body.preserveEntries = Math.floor(payload.preserveEntries);
451
+ initializeEncryptionBootstrap(options) {
452
+ return this.bootstrapEncryptionOptions(options).then(() => void 0);
215
453
  }
216
- const raw = await this.requestJson(
217
- `/chat/session/${encodeURIComponent(payload.sessionId)}/compact`,
218
- {
219
- method: "POST",
220
- headers: { "content-type": "application/json" },
221
- body
222
- }
223
- );
224
- return this.parseWithSchema(
225
- raw,
226
- chatHistoryCompactionResponseSchema,
227
- "chat history compaction response"
228
- );
229
- };
230
- RegistryBrokerClient.prototype.fetchEncryptionStatus = async function(sessionId) {
231
- if (!sessionId || sessionId.trim().length === 0) {
232
- throw new Error("sessionId is required for encryption status");
454
+ bootstrapEncryptionOptions(_options) {
455
+ return Promise.resolve(null);
233
456
  }
234
- const raw = await this.requestJson(
235
- `/chat/session/${encodeURIComponent(sessionId)}/encryption`,
236
- {
457
+ async search(params = {}) {
458
+ const query = buildSearchQuery(params);
459
+ const raw = await this.requestJson(`/search${query}`, {
237
460
  method: "GET"
238
- }
239
- );
240
- return this.parseWithSchema(
241
- raw,
242
- sessionEncryptionStatusResponseSchema,
243
- "session encryption status response"
244
- );
245
- };
246
- RegistryBrokerClient.prototype.postEncryptionHandshake = async function(sessionId, payload) {
247
- if (!sessionId || sessionId.trim().length === 0) {
248
- throw new Error("sessionId is required for encryption handshake");
461
+ });
462
+ return this.parseWithSchema(raw, searchResponseSchema, "search response");
249
463
  }
250
- const raw = await this.requestJson(
251
- `/chat/session/${encodeURIComponent(sessionId)}/encryption-handshake`,
252
- {
253
- method: "POST",
254
- headers: { "content-type": "application/json" },
255
- body: {
256
- role: payload.role,
257
- keyType: payload.keyType,
258
- ephemeralPublicKey: payload.ephemeralPublicKey,
259
- longTermPublicKey: payload.longTermPublicKey,
260
- signature: payload.signature,
261
- uaid: payload.uaid,
262
- userId: payload.userId,
263
- ledgerAccountId: payload.ledgerAccountId,
264
- metadata: payload.metadata
464
+ async stats() {
465
+ const raw = await this.requestJson("/stats", { method: "GET" });
466
+ return this.parseWithSchema(raw, statsResponseSchema, "stats response");
467
+ }
468
+ async registries() {
469
+ const raw = await this.requestJson("/registries", {
470
+ method: "GET"
471
+ });
472
+ return this.parseWithSchema(
473
+ raw,
474
+ registriesResponseSchema,
475
+ "registries response"
476
+ );
477
+ }
478
+ async getAdditionalRegistries() {
479
+ const raw = await this.requestJson(
480
+ "/register/additional-registries",
481
+ {
482
+ method: "GET"
265
483
  }
484
+ );
485
+ return this.parseWithSchema(
486
+ raw,
487
+ additionalRegistryCatalogResponseSchema,
488
+ "additional registry catalog response"
489
+ );
490
+ }
491
+ async popularSearches() {
492
+ const raw = await this.requestJson("/popular", {
493
+ method: "GET"
494
+ });
495
+ return this.parseWithSchema(
496
+ raw,
497
+ popularResponseSchema,
498
+ "popular searches response"
499
+ );
500
+ }
501
+ async listProtocols() {
502
+ const raw = await this.requestJson("/protocols", {
503
+ method: "GET"
504
+ });
505
+ return this.parseWithSchema(
506
+ raw,
507
+ protocolsResponseSchema,
508
+ "protocols response"
509
+ );
510
+ }
511
+ async detectProtocol(message) {
512
+ const raw = await this.requestJson("/detect-protocol", {
513
+ method: "POST",
514
+ body: { message },
515
+ headers: { "content-type": "application/json" }
516
+ });
517
+ return this.parseWithSchema(
518
+ raw,
519
+ detectProtocolResponseSchema,
520
+ "detect protocol response"
521
+ );
522
+ }
523
+ async registrySearchByNamespace(registry, query) {
524
+ const params = new URLSearchParams();
525
+ if (query) {
526
+ params.set("q", query);
266
527
  }
267
- );
268
- const response = this.parseWithSchema(
269
- raw,
270
- encryptionHandshakeResponseSchema,
271
- "encryption handshake response"
272
- );
273
- return response.handshake;
274
- };
275
- RegistryBrokerClient.prototype.sendMessage = async function(payload) {
276
- const body = {
277
- message: payload.message
278
- };
279
- if (payload.streaming !== void 0) {
280
- body.streaming = payload.streaming;
281
- }
282
- if (payload.auth) {
283
- body.auth = serialiseAuthConfig(payload.auth);
284
- }
285
- if ("uaid" in payload) {
286
- body.uaid = payload.uaid;
287
- }
288
- if ("sessionId" in payload && payload.sessionId) {
289
- body.sessionId = payload.sessionId;
290
- }
291
- if ("agentUrl" in payload && payload.agentUrl) {
292
- body.agentUrl = payload.agentUrl;
293
- }
294
- let cipherEnvelope = payload.cipherEnvelope ?? null;
295
- if (payload.encryption) {
296
- const sessionIdForEncryption = payload.encryption.sessionId ?? (typeof body.sessionId === "string" ? body.sessionId : void 0);
297
- if (!sessionIdForEncryption) {
298
- throw new Error(
299
- "sessionId is required when using encrypted chat payloads"
528
+ const suffix = params.size > 0 ? `?${params.toString()}` : "";
529
+ const raw = await this.requestJson(
530
+ `/registries/${encodeURIComponent(registry)}/search${suffix}`,
531
+ {
532
+ method: "GET"
533
+ }
534
+ );
535
+ return this.parseWithSchema(
536
+ raw,
537
+ registrySearchByNamespaceSchema,
538
+ "registry search response"
539
+ );
540
+ }
541
+ async vectorSearch(request) {
542
+ try {
543
+ const raw = await this.requestJson("/search", {
544
+ method: "POST",
545
+ body: request,
546
+ headers: { "content-type": "application/json" }
547
+ });
548
+ return this.parseWithSchema(
549
+ raw,
550
+ vectorSearchResponseSchema,
551
+ "vector search response"
300
552
  );
553
+ } catch (error) {
554
+ if (error instanceof RegistryBrokerError && error.status === 501) {
555
+ const fallbackParams = { q: request.query };
556
+ if (request.limit) fallbackParams.limit = request.limit;
557
+ if (request.filter?.registry) fallbackParams.registry = request.filter.registry;
558
+ if (request.filter?.protocols?.length) fallbackParams.protocols = [...request.filter.protocols];
559
+ const fallback = await this.search(fallbackParams);
560
+ return {
561
+ hits: fallback.hits.map((agent) => ({ agent, score: 0, highlights: {} })),
562
+ total: fallback.total,
563
+ took: 0,
564
+ totalAvailable: fallback.total,
565
+ visible: fallback.hits.length,
566
+ limited: fallback.total > fallback.limit,
567
+ credits_used: 0
568
+ };
569
+ }
570
+ throw error;
301
571
  }
302
- if (!payload.encryption.recipients?.length) {
303
- throw new Error("recipients are required for encrypted chat payloads");
572
+ }
573
+ async searchStatus() {
574
+ const raw = await this.requestJson("/search/status", {
575
+ method: "GET"
576
+ });
577
+ return this.parseWithSchema(
578
+ raw,
579
+ searchStatusResponseSchema,
580
+ "search status response"
581
+ );
582
+ }
583
+ async websocketStats() {
584
+ const raw = await this.requestJson("/websocket/stats", {
585
+ method: "GET"
586
+ });
587
+ return this.parseWithSchema(
588
+ raw,
589
+ websocketStatsResponseSchema,
590
+ "websocket stats response"
591
+ );
592
+ }
593
+ async metricsSummary() {
594
+ const raw = await this.requestJson("/metrics", {
595
+ method: "GET"
596
+ });
597
+ return this.parseWithSchema(
598
+ raw,
599
+ metricsSummaryResponseSchema,
600
+ "metrics summary response"
601
+ );
602
+ }
603
+ async facets(adapter) {
604
+ const params = new URLSearchParams();
605
+ if (adapter) {
606
+ params.set("adapter", adapter);
304
607
  }
305
- cipherEnvelope = this.encryption.encryptCipherEnvelope({
306
- ...payload.encryption,
307
- sessionId: sessionIdForEncryption
608
+ const suffix = params.size > 0 ? `?${params.toString()}` : "";
609
+ const raw = await this.requestJson(`/search/facets${suffix}`, {
610
+ method: "GET"
308
611
  });
612
+ return this.parseWithSchema(
613
+ raw,
614
+ searchFacetsResponseSchema,
615
+ "search facets response"
616
+ );
309
617
  }
310
- if (cipherEnvelope) {
311
- body.cipherEnvelope = toJsonObject(cipherEnvelope);
312
- }
313
- const raw = await this.requestJson("/chat/message", {
314
- method: "POST",
315
- body,
316
- headers: { "content-type": "application/json" }
317
- });
318
- return this.parseWithSchema(
319
- raw,
320
- sendMessageResponseSchema,
321
- "chat message response"
322
- );
323
- };
324
- RegistryBrokerClient.prototype.endSession = async function(sessionId) {
325
- await this.request(`/chat/session/${encodeURIComponent(sessionId)}`, {
326
- method: "DELETE"
327
- });
618
+ }
619
+ const isPendingRegisterAgentResponse = (response) => response.status === "pending";
620
+ const isPartialRegisterAgentResponse = (response) => response.status === "partial" && response.success === false;
621
+ const isSuccessRegisterAgentResponse = (response) => response.success === true && response.status !== "pending";
622
+ export {
623
+ RegistryBrokerClient,
624
+ isPartialRegisterAgentResponse,
625
+ isPendingRegisterAgentResponse,
626
+ isSuccessRegisterAgentResponse
328
627
  };
329
628
  //# sourceMappingURL=standards-sdk.es134.js.map