@agentxv2/sdk 0.3.0 → 0.4.0

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 (107) hide show
  1. package/README.md +25 -16
  2. package/dist/core.d.mts +64 -0
  3. package/dist/core.d.ts +64 -0
  4. package/dist/core.js +275 -0
  5. package/dist/core.js.map +1 -0
  6. package/dist/core.mjs +240 -0
  7. package/dist/core.mjs.map +1 -0
  8. package/dist/{agent/agent-runner.d.ts → index-DhXVi_ub.d.ts} +94 -10
  9. package/dist/index-eQO4iaOr.d.mts +208 -0
  10. package/dist/index.d.mts +269 -0
  11. package/dist/index.d.ts +269 -10
  12. package/dist/index.js +2416 -31
  13. package/dist/index.js.map +1 -1
  14. package/dist/index.mjs +2363 -0
  15. package/dist/index.mjs.map +1 -0
  16. package/dist/react.d.mts +3 -0
  17. package/dist/react.d.ts +3 -0
  18. package/dist/react.js +755 -0
  19. package/dist/react.js.map +1 -0
  20. package/dist/react.mjs +735 -0
  21. package/dist/react.mjs.map +1 -0
  22. package/dist/{core/types.d.ts → types-2aHUvS4M.d.mts} +34 -33
  23. package/dist/types-2aHUvS4M.d.ts +297 -0
  24. package/package.json +12 -11
  25. package/dist/a2a/a2a.d.ts +0 -37
  26. package/dist/a2a/a2a.d.ts.map +0 -1
  27. package/dist/a2a/a2a.js +0 -252
  28. package/dist/a2a/a2a.js.map +0 -1
  29. package/dist/a2a/index.d.ts +0 -4
  30. package/dist/a2a/index.d.ts.map +0 -1
  31. package/dist/a2a/index.js +0 -4
  32. package/dist/a2a/index.js.map +0 -1
  33. package/dist/agent/agent-runner.d.ts.map +0 -1
  34. package/dist/agent/agent-runner.js +0 -249
  35. package/dist/agent/agent-runner.js.map +0 -1
  36. package/dist/agent/index.d.ts +0 -3
  37. package/dist/agent/index.d.ts.map +0 -1
  38. package/dist/agent/index.js +0 -3
  39. package/dist/agent/index.js.map +0 -1
  40. package/dist/config/config.d.ts +0 -31
  41. package/dist/config/config.d.ts.map +0 -1
  42. package/dist/config/config.js +0 -95
  43. package/dist/config/config.js.map +0 -1
  44. package/dist/config/index.d.ts +0 -4
  45. package/dist/config/index.d.ts.map +0 -1
  46. package/dist/config/index.js +0 -4
  47. package/dist/config/index.js.map +0 -1
  48. package/dist/core/crypto.d.ts +0 -62
  49. package/dist/core/crypto.d.ts.map +0 -1
  50. package/dist/core/crypto.js +0 -291
  51. package/dist/core/crypto.js.map +0 -1
  52. package/dist/core/index.d.ts +0 -3
  53. package/dist/core/index.d.ts.map +0 -1
  54. package/dist/core/index.js +0 -4
  55. package/dist/core/index.js.map +0 -1
  56. package/dist/core/types.d.ts.map +0 -1
  57. package/dist/core/types.js +0 -30
  58. package/dist/core/types.js.map +0 -1
  59. package/dist/index.d.ts.map +0 -1
  60. package/dist/mcp/connector.d.ts +0 -43
  61. package/dist/mcp/connector.d.ts.map +0 -1
  62. package/dist/mcp/connector.js +0 -79
  63. package/dist/mcp/connector.js.map +0 -1
  64. package/dist/mcp/index.d.ts +0 -4
  65. package/dist/mcp/index.d.ts.map +0 -1
  66. package/dist/mcp/index.js +0 -4
  67. package/dist/mcp/index.js.map +0 -1
  68. package/dist/react/index.d.ts +0 -4
  69. package/dist/react/index.d.ts.map +0 -1
  70. package/dist/react/index.js +0 -3
  71. package/dist/react/index.js.map +0 -1
  72. package/dist/react/useAgentRunner.d.ts +0 -16
  73. package/dist/react/useAgentRunner.d.ts.map +0 -1
  74. package/dist/react/useAgentRunner.js +0 -204
  75. package/dist/react/useAgentRunner.js.map +0 -1
  76. package/dist/registry/agent-registry.d.ts +0 -52
  77. package/dist/registry/agent-registry.d.ts.map +0 -1
  78. package/dist/registry/agent-registry.js +0 -221
  79. package/dist/registry/agent-registry.js.map +0 -1
  80. package/dist/registry/index.d.ts +0 -7
  81. package/dist/registry/index.d.ts.map +0 -1
  82. package/dist/registry/index.js +0 -6
  83. package/dist/registry/index.js.map +0 -1
  84. package/dist/registry/ipfs-fetcher.d.ts +0 -39
  85. package/dist/registry/ipfs-fetcher.d.ts.map +0 -1
  86. package/dist/registry/ipfs-fetcher.js +0 -139
  87. package/dist/registry/ipfs-fetcher.js.map +0 -1
  88. package/dist/reputation/index.d.ts +0 -4
  89. package/dist/reputation/index.d.ts.map +0 -1
  90. package/dist/reputation/index.js +0 -4
  91. package/dist/reputation/index.js.map +0 -1
  92. package/dist/reputation/reputation.d.ts +0 -26
  93. package/dist/reputation/reputation.d.ts.map +0 -1
  94. package/dist/reputation/reputation.js +0 -113
  95. package/dist/reputation/reputation.js.map +0 -1
  96. package/dist/subscription/agent-x402.d.ts +0 -33
  97. package/dist/subscription/agent-x402.d.ts.map +0 -1
  98. package/dist/subscription/agent-x402.js +0 -144
  99. package/dist/subscription/agent-x402.js.map +0 -1
  100. package/dist/subscription/index.d.ts +0 -6
  101. package/dist/subscription/index.d.ts.map +0 -1
  102. package/dist/subscription/index.js +0 -5
  103. package/dist/subscription/index.js.map +0 -1
  104. package/dist/subscription/subscription.d.ts +0 -67
  105. package/dist/subscription/subscription.d.ts.map +0 -1
  106. package/dist/subscription/subscription.js +0 -346
  107. package/dist/subscription/subscription.js.map +0 -1
package/dist/index.mjs ADDED
@@ -0,0 +1,2363 @@
1
+ var __getOwnPropNames = Object.getOwnPropertyNames;
2
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
3
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
4
+ }) : x)(function(x) {
5
+ if (typeof require !== "undefined") return require.apply(this, arguments);
6
+ throw Error('Dynamic require of "' + x + '" is not supported');
7
+ });
8
+ var __esm = (fn, res) => function __init() {
9
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
+ };
11
+
12
+ // node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/_esm/utils/data/isHex.js
13
+ function isHex(value, { strict = true } = {}) {
14
+ if (!value)
15
+ return false;
16
+ if (typeof value !== "string")
17
+ return false;
18
+ return strict ? /^0x[0-9a-fA-F]*$/.test(value) : value.startsWith("0x");
19
+ }
20
+ var init_isHex = __esm({
21
+ "node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/_esm/utils/data/isHex.js"() {
22
+ "use strict";
23
+ }
24
+ });
25
+
26
+ // node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/_esm/utils/data/size.js
27
+ function size(value) {
28
+ if (isHex(value, { strict: false }))
29
+ return Math.ceil((value.length - 2) / 2);
30
+ return value.length;
31
+ }
32
+ var init_size = __esm({
33
+ "node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/_esm/utils/data/size.js"() {
34
+ "use strict";
35
+ init_isHex();
36
+ }
37
+ });
38
+
39
+ // node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/_esm/errors/version.js
40
+ var version;
41
+ var init_version = __esm({
42
+ "node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/_esm/errors/version.js"() {
43
+ "use strict";
44
+ version = "2.55.0";
45
+ }
46
+ });
47
+
48
+ // node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/_esm/errors/base.js
49
+ function walk(err, fn) {
50
+ if (fn?.(err))
51
+ return err;
52
+ if (err && typeof err === "object" && "cause" in err && err.cause !== void 0)
53
+ return walk(err.cause, fn);
54
+ return fn ? null : err;
55
+ }
56
+ var errorConfig, BaseError;
57
+ var init_base = __esm({
58
+ "node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/_esm/errors/base.js"() {
59
+ "use strict";
60
+ init_version();
61
+ errorConfig = {
62
+ getDocsUrl: ({ docsBaseUrl, docsPath = "", docsSlug }) => docsPath ? `${docsBaseUrl ?? "https://viem.sh"}${docsPath}${docsSlug ? `#${docsSlug}` : ""}` : void 0,
63
+ version: `viem@${version}`
64
+ };
65
+ BaseError = class _BaseError extends Error {
66
+ constructor(shortMessage, args = {}) {
67
+ const details = (() => {
68
+ if (args.cause instanceof _BaseError)
69
+ return args.cause.details;
70
+ if (args.cause?.message)
71
+ return args.cause.message;
72
+ return args.details;
73
+ })();
74
+ const docsPath = (() => {
75
+ if (args.cause instanceof _BaseError)
76
+ return args.cause.docsPath || args.docsPath;
77
+ return args.docsPath;
78
+ })();
79
+ const docsUrl = errorConfig.getDocsUrl?.({ ...args, docsPath });
80
+ const message = [
81
+ shortMessage || "An error occurred.",
82
+ "",
83
+ ...args.metaMessages ? [...args.metaMessages, ""] : [],
84
+ ...docsUrl ? [`Docs: ${docsUrl}`] : [],
85
+ ...details ? [`Details: ${details}`] : [],
86
+ ...errorConfig.version ? [`Version: ${errorConfig.version}`] : []
87
+ ].join("\n");
88
+ super(message, args.cause ? { cause: args.cause } : void 0);
89
+ Object.defineProperty(this, "details", {
90
+ enumerable: true,
91
+ configurable: true,
92
+ writable: true,
93
+ value: void 0
94
+ });
95
+ Object.defineProperty(this, "docsPath", {
96
+ enumerable: true,
97
+ configurable: true,
98
+ writable: true,
99
+ value: void 0
100
+ });
101
+ Object.defineProperty(this, "metaMessages", {
102
+ enumerable: true,
103
+ configurable: true,
104
+ writable: true,
105
+ value: void 0
106
+ });
107
+ Object.defineProperty(this, "shortMessage", {
108
+ enumerable: true,
109
+ configurable: true,
110
+ writable: true,
111
+ value: void 0
112
+ });
113
+ Object.defineProperty(this, "version", {
114
+ enumerable: true,
115
+ configurable: true,
116
+ writable: true,
117
+ value: void 0
118
+ });
119
+ Object.defineProperty(this, "name", {
120
+ enumerable: true,
121
+ configurable: true,
122
+ writable: true,
123
+ value: "BaseError"
124
+ });
125
+ this.details = details;
126
+ this.docsPath = docsPath;
127
+ this.metaMessages = args.metaMessages;
128
+ this.name = args.name ?? this.name;
129
+ this.shortMessage = shortMessage;
130
+ this.version = version;
131
+ }
132
+ walk(fn) {
133
+ return walk(this, fn);
134
+ }
135
+ };
136
+ }
137
+ });
138
+
139
+ // node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/_esm/errors/data.js
140
+ var SizeExceedsPaddingSizeError;
141
+ var init_data = __esm({
142
+ "node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/_esm/errors/data.js"() {
143
+ "use strict";
144
+ init_base();
145
+ SizeExceedsPaddingSizeError = class extends BaseError {
146
+ constructor({ size: size2, targetSize, type }) {
147
+ super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (${size2}) exceeds padding size (${targetSize}).`, { name: "SizeExceedsPaddingSizeError" });
148
+ }
149
+ };
150
+ }
151
+ });
152
+
153
+ // node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/_esm/utils/data/pad.js
154
+ function pad(hexOrBytes, { dir, size: size2 = 32 } = {}) {
155
+ if (typeof hexOrBytes === "string")
156
+ return padHex(hexOrBytes, { dir, size: size2 });
157
+ return padBytes(hexOrBytes, { dir, size: size2 });
158
+ }
159
+ function padHex(hex_, { dir, size: size2 = 32 } = {}) {
160
+ if (size2 === null)
161
+ return hex_;
162
+ const hex = hex_.replace("0x", "");
163
+ if (hex.length > size2 * 2)
164
+ throw new SizeExceedsPaddingSizeError({
165
+ size: Math.ceil(hex.length / 2),
166
+ targetSize: size2,
167
+ type: "hex"
168
+ });
169
+ return `0x${hex[dir === "right" ? "padEnd" : "padStart"](size2 * 2, "0")}`;
170
+ }
171
+ function padBytes(bytes, { dir, size: size2 = 32 } = {}) {
172
+ if (size2 === null)
173
+ return bytes;
174
+ if (bytes.length > size2)
175
+ throw new SizeExceedsPaddingSizeError({
176
+ size: bytes.length,
177
+ targetSize: size2,
178
+ type: "bytes"
179
+ });
180
+ const paddedBytes = new Uint8Array(size2);
181
+ for (let i = 0; i < size2; i++) {
182
+ const padEnd = dir === "right";
183
+ paddedBytes[padEnd ? i : size2 - i - 1] = bytes[padEnd ? i : bytes.length - i - 1];
184
+ }
185
+ return paddedBytes;
186
+ }
187
+ var init_pad = __esm({
188
+ "node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/_esm/utils/data/pad.js"() {
189
+ "use strict";
190
+ init_data();
191
+ }
192
+ });
193
+
194
+ // node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/_esm/errors/encoding.js
195
+ var SizeOverflowError;
196
+ var init_encoding = __esm({
197
+ "node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/_esm/errors/encoding.js"() {
198
+ "use strict";
199
+ init_base();
200
+ SizeOverflowError = class extends BaseError {
201
+ constructor({ givenSize, maxSize }) {
202
+ super(`Size cannot exceed ${maxSize} bytes. Given size: ${givenSize} bytes.`, { name: "SizeOverflowError" });
203
+ }
204
+ };
205
+ }
206
+ });
207
+
208
+ // node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/_esm/utils/data/trim.js
209
+ function trim(hexOrBytes, { dir = "left" } = {}) {
210
+ let data = typeof hexOrBytes === "string" ? hexOrBytes.replace("0x", "") : hexOrBytes;
211
+ let sliceLength = 0;
212
+ for (let i = 0; i < data.length - 1; i++) {
213
+ if (data[dir === "left" ? i : data.length - i - 1].toString() === "0")
214
+ sliceLength++;
215
+ else
216
+ break;
217
+ }
218
+ data = dir === "left" ? data.slice(sliceLength) : data.slice(0, data.length - sliceLength);
219
+ if (typeof hexOrBytes === "string") {
220
+ if (data.length === 1 && dir === "right")
221
+ data = `${data}0`;
222
+ return `0x${data.length % 2 === 1 ? `0${data}` : data}`;
223
+ }
224
+ return data;
225
+ }
226
+ var init_trim = __esm({
227
+ "node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/_esm/utils/data/trim.js"() {
228
+ "use strict";
229
+ }
230
+ });
231
+
232
+ // node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/_esm/utils/encoding/fromHex.js
233
+ function assertSize(hexOrBytes, { size: size2 }) {
234
+ if (size(hexOrBytes) > size2)
235
+ throw new SizeOverflowError({
236
+ givenSize: size(hexOrBytes),
237
+ maxSize: size2
238
+ });
239
+ }
240
+ function hexToString(hex, opts = {}) {
241
+ let bytes = hexToBytes2(hex);
242
+ if (opts.size) {
243
+ assertSize(bytes, { size: opts.size });
244
+ bytes = trim(bytes, { dir: "right" });
245
+ }
246
+ return new TextDecoder().decode(bytes);
247
+ }
248
+ var init_fromHex = __esm({
249
+ "node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/_esm/utils/encoding/fromHex.js"() {
250
+ "use strict";
251
+ init_encoding();
252
+ init_size();
253
+ init_trim();
254
+ init_toBytes();
255
+ }
256
+ });
257
+
258
+ // node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/_esm/utils/encoding/toHex.js
259
+ function bytesToHex2(value, opts = {}) {
260
+ let string = "";
261
+ for (let i = 0; i < value.length; i++) {
262
+ string += hexes[value[i]];
263
+ }
264
+ const hex = `0x${string}`;
265
+ if (typeof opts.size === "number") {
266
+ assertSize(hex, { size: opts.size });
267
+ return pad(hex, { dir: "right", size: opts.size });
268
+ }
269
+ return hex;
270
+ }
271
+ function stringToHex(value_, opts = {}) {
272
+ const value = encoder.encode(value_);
273
+ return bytesToHex2(value, opts);
274
+ }
275
+ var hexes, encoder;
276
+ var init_toHex = __esm({
277
+ "node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/_esm/utils/encoding/toHex.js"() {
278
+ "use strict";
279
+ init_pad();
280
+ init_fromHex();
281
+ hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_v, i) => i.toString(16).padStart(2, "0"));
282
+ encoder = /* @__PURE__ */ new TextEncoder();
283
+ }
284
+ });
285
+
286
+ // node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/_esm/utils/encoding/toBytes.js
287
+ function charCodeToBase16(char) {
288
+ if (char >= charCodeMap.zero && char <= charCodeMap.nine)
289
+ return char - charCodeMap.zero;
290
+ if (char >= charCodeMap.A && char <= charCodeMap.F)
291
+ return char - (charCodeMap.A - 10);
292
+ if (char >= charCodeMap.a && char <= charCodeMap.f)
293
+ return char - (charCodeMap.a - 10);
294
+ return void 0;
295
+ }
296
+ function hexToBytes2(hex_, opts = {}) {
297
+ let hex = hex_;
298
+ if (opts.size) {
299
+ assertSize(hex, { size: opts.size });
300
+ hex = pad(hex, { dir: "right", size: opts.size });
301
+ }
302
+ let hexString = hex.slice(2);
303
+ if (hexString.length % 2)
304
+ hexString = `0${hexString}`;
305
+ const length = hexString.length / 2;
306
+ const bytes = new Uint8Array(length);
307
+ for (let index = 0, j = 0; index < length; index++) {
308
+ const nibbleLeft = charCodeToBase16(hexString.charCodeAt(j++));
309
+ const nibbleRight = charCodeToBase16(hexString.charCodeAt(j++));
310
+ if (nibbleLeft === void 0 || nibbleRight === void 0) {
311
+ throw new BaseError(`Invalid byte sequence ("${hexString[j - 2]}${hexString[j - 1]}" in "${hexString}").`);
312
+ }
313
+ bytes[index] = nibbleLeft * 16 + nibbleRight;
314
+ }
315
+ return bytes;
316
+ }
317
+ var charCodeMap;
318
+ var init_toBytes = __esm({
319
+ "node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/_esm/utils/encoding/toBytes.js"() {
320
+ "use strict";
321
+ init_base();
322
+ init_pad();
323
+ init_fromHex();
324
+ charCodeMap = {
325
+ zero: 48,
326
+ nine: 57,
327
+ A: 65,
328
+ F: 70,
329
+ a: 97,
330
+ f: 102
331
+ };
332
+ }
333
+ });
334
+
335
+ // src/core/types.ts
336
+ var AgentXErrorCode = /* @__PURE__ */ ((AgentXErrorCode2) => {
337
+ AgentXErrorCode2["NOT_SUBSCRIBED"] = "NOT_SUBSCRIBED";
338
+ AgentXErrorCode2["SUBSCRIPTION_EXPIRED"] = "SUBSCRIPTION_EXPIRED";
339
+ AgentXErrorCode2["DECRYPTION_FAILED"] = "DECRYPTION_FAILED";
340
+ AgentXErrorCode2["IPFS_FETCH_FAILED"] = "IPFS_FETCH_FAILED";
341
+ AgentXErrorCode2["AGENT_NOT_FOUND"] = "AGENT_NOT_FOUND";
342
+ AgentXErrorCode2["INVALID_SCHEMA"] = "INVALID_SCHEMA";
343
+ AgentXErrorCode2["TX_FAILED"] = "TX_FAILED";
344
+ AgentXErrorCode2["WALLET_NOT_CONNECTED"] = "WALLET_NOT_CONNECTED";
345
+ return AgentXErrorCode2;
346
+ })(AgentXErrorCode || {});
347
+ var AgentXError = class extends Error {
348
+ code;
349
+ /** If NOT_SUBSCRIBED, carry enough info for wallet/X402 auto-payment */
350
+ paymentInfo;
351
+ constructor(code, message) {
352
+ super(message);
353
+ this.code = code;
354
+ this.name = "AgentXError";
355
+ }
356
+ };
357
+
358
+ // src/core/crypto.ts
359
+ import { gcm } from "@noble/ciphers/aes.js";
360
+ import { secp256k1 } from "@noble/curves/secp256k1.js";
361
+ import { sha256 } from "@noble/hashes/sha2.js";
362
+ import { hkdf } from "@noble/hashes/hkdf.js";
363
+ import { hmac } from "@noble/hashes/hmac.js";
364
+ import { bytesToHex, hexToBytes } from "@noble/ciphers/utils.js";
365
+ function randomBytes(length) {
366
+ if (typeof crypto !== "undefined" && crypto.getRandomValues) {
367
+ const buf = new Uint8Array(length);
368
+ crypto.getRandomValues(buf);
369
+ return buf;
370
+ }
371
+ const nodeCrypto = __require("crypto");
372
+ return new Uint8Array(nodeCrypto.randomBytes(length));
373
+ }
374
+ var AES_KEY_SIZE = 32;
375
+ var IV_SIZE = 12;
376
+ var TAG_SIZE = 16;
377
+ function toBase64(bytes) {
378
+ if (typeof Buffer !== "undefined") return Buffer.from(bytes).toString("base64");
379
+ let binary = "";
380
+ for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
381
+ return btoa(binary);
382
+ }
383
+ function fromBase64(b64) {
384
+ if (typeof Buffer !== "undefined") return new Uint8Array(Buffer.from(b64, "base64"));
385
+ const binary = atob(b64);
386
+ const bytes = new Uint8Array(binary.length);
387
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
388
+ return bytes;
389
+ }
390
+ function aesEncrypt(plaintext, keyHex) {
391
+ const key = hexToBytes(keyHex);
392
+ const iv = randomBytes(IV_SIZE);
393
+ const plainBytes = new TextEncoder().encode(plaintext);
394
+ const cipher = gcm(key, iv);
395
+ const encrypted = cipher.encrypt(plainBytes);
396
+ const ciphertext = encrypted.subarray(0, -TAG_SIZE);
397
+ const authTag = encrypted.subarray(-TAG_SIZE);
398
+ const combined = new Uint8Array(IV_SIZE + ciphertext.length + TAG_SIZE);
399
+ combined.set(iv, 0);
400
+ combined.set(ciphertext, IV_SIZE);
401
+ combined.set(authTag, IV_SIZE + ciphertext.length);
402
+ return toBase64(combined);
403
+ }
404
+ function aesDecrypt(encryptedBase64, keyHex) {
405
+ const key = hexToBytes(keyHex);
406
+ const combined = fromBase64(encryptedBase64);
407
+ const iv = combined.subarray(0, IV_SIZE);
408
+ const ciphertext = combined.subarray(IV_SIZE, -TAG_SIZE);
409
+ const authTag = combined.subarray(-TAG_SIZE);
410
+ const cipher = gcm(key, iv);
411
+ const ciphertextWithTag = new Uint8Array(ciphertext.length + TAG_SIZE);
412
+ ciphertextWithTag.set(ciphertext, 0);
413
+ ciphertextWithTag.set(authTag, ciphertext.length);
414
+ const decrypted = cipher.decrypt(ciphertextWithTag);
415
+ return new TextDecoder().decode(decrypted);
416
+ }
417
+ function generateAesKey() {
418
+ return bytesToHex(randomBytes(AES_KEY_SIZE));
419
+ }
420
+ function eciesEncode(ephemeralPub, iv, ciphertext, mac) {
421
+ const out = new Uint8Array(33 + 16 + ciphertext.length + 32);
422
+ out.set(ephemeralPub, 0);
423
+ out.set(iv, 33);
424
+ out.set(ciphertext, 33 + 16);
425
+ out.set(mac, 33 + 16 + ciphertext.length);
426
+ return bytesToHex(out);
427
+ }
428
+ function eciesDecode(dataHex) {
429
+ const d = hexToBytes(dataHex);
430
+ return {
431
+ ephemeralPub: d.subarray(0, 33),
432
+ iv: d.subarray(33, 49),
433
+ ciphertext: d.subarray(49, -32),
434
+ mac: d.subarray(-32)
435
+ };
436
+ }
437
+ function aesCtrEncrypt(key, ctrBytes, data) {
438
+ const blockSize = 16;
439
+ const cipher = gcm(key, ctrBytes);
440
+ const result = new Uint8Array(data.length);
441
+ const counter = new Uint8Array(blockSize);
442
+ counter.set(ctrBytes);
443
+ for (let i = 0; i < data.length; i += blockSize) {
444
+ const keystream = gcm(key, counter).encrypt(new Uint8Array(blockSize));
445
+ for (let j = 0; j < blockSize && i + j < data.length; j++) {
446
+ result[i + j] = keystream[j] ^ data[i + j];
447
+ }
448
+ for (let j = blockSize - 1; j >= 0; j--) {
449
+ const val = counter[j];
450
+ if (val !== void 0) {
451
+ counter[j] = val + 1 & 255;
452
+ if (counter[j] !== 0) break;
453
+ }
454
+ }
455
+ }
456
+ return result;
457
+ }
458
+ function eciesEncrypt(dataHex, publicKey) {
459
+ const ephPriv = randomBytes(32);
460
+ const ephPub = secp256k1.getPublicKey(ephPriv, true);
461
+ let recipientPub;
462
+ if (publicKey.startsWith("04") && publicKey.length === 130) {
463
+ recipientPub = hexToBytes(publicKey);
464
+ } else if (publicKey.startsWith("02") || publicKey.startsWith("03")) {
465
+ recipientPub = hexToBytes(publicKey);
466
+ } else {
467
+ throw new Error("Invalid public key format: expected hex with 02/03/04 prefix");
468
+ }
469
+ const shared = secp256k1.getSharedSecret(ephPriv, recipientPub);
470
+ const sharedX = shared.subarray(1, 33);
471
+ const sharedKey = sha256(sharedX);
472
+ const hkdfOut = hkdf(sha256, sharedKey, void 0, void 0, 64);
473
+ const encKey = hkdfOut.subarray(0, 32);
474
+ const macKey = hkdfOut.subarray(32, 64);
475
+ const iv = randomBytes(16);
476
+ const plaintext = hexToBytes(dataHex);
477
+ const ciphertext = aesCtrEncrypt(encKey, iv, plaintext);
478
+ const macInput = new Uint8Array(33 + 16 + ciphertext.length);
479
+ macInput.set(ephPub, 0);
480
+ macInput.set(iv, 33);
481
+ macInput.set(ciphertext, 33 + 16);
482
+ const mac = hmac(sha256, macKey, macInput);
483
+ return eciesEncode(ephPub, iv, ciphertext, mac);
484
+ }
485
+ function eciesDecrypt(dataHex, privateKey) {
486
+ const { ephemeralPub, iv, ciphertext, mac } = eciesDecode(dataHex);
487
+ const privBytes = hexToBytes(privateKey);
488
+ const shared = secp256k1.getSharedSecret(privBytes, ephemeralPub);
489
+ const sharedX = shared.subarray(1, 33);
490
+ const sharedKey = sha256(sharedX);
491
+ const hkdfOut = hkdf(sha256, sharedKey, void 0, void 0, 64);
492
+ const encKey = hkdfOut.subarray(0, 32);
493
+ const macKey = hkdfOut.subarray(32, 64);
494
+ const macInput = new Uint8Array(33 + 16 + ciphertext.length);
495
+ macInput.set(ephemeralPub, 0);
496
+ macInput.set(iv, 33);
497
+ macInput.set(ciphertext, 33 + 16);
498
+ const expectedMac = hmac(sha256, macKey, macInput);
499
+ if (!constantTimeEqual(mac, expectedMac)) {
500
+ throw new Error("ECIES decryption failed: MAC mismatch");
501
+ }
502
+ const plaintext = aesCtrEncrypt(encKey, iv, ciphertext);
503
+ return bytesToHex(plaintext);
504
+ }
505
+ function constantTimeEqual(a, b) {
506
+ if (a.length !== b.length) return false;
507
+ let diff = 0;
508
+ for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
509
+ return diff === 0;
510
+ }
511
+ function encryptPayload(payload, keyHex) {
512
+ const key = keyHex ?? generateAesKey();
513
+ return {
514
+ encrypted: true,
515
+ algorithm: "AES-256-GCM",
516
+ data: aesEncrypt(JSON.stringify(payload), key)
517
+ };
518
+ }
519
+ function decryptPayload(encrypted, keyHex) {
520
+ if (encrypted.algorithm !== "AES-256-GCM") {
521
+ throw new Error(`Unsupported algorithm: ${encrypted.algorithm}`);
522
+ }
523
+ return JSON.parse(aesDecrypt(encrypted.data, keyHex));
524
+ }
525
+ function packAgentForPublish(agent, publicKey, aesKeyHex) {
526
+ const key = aesKeyHex ?? generateAesKey();
527
+ const eciesEncryptedKeyHex = eciesEncrypt(key, publicKey);
528
+ return {
529
+ encryptedCid: "",
530
+ // filled after IPFS upload
531
+ publicCid: "",
532
+ // filled after IPFS upload
533
+ aesKeyHex: key,
534
+ eciesEncryptedKeyHex
535
+ };
536
+ }
537
+ function unpackAgent(encryptedPayload, eciesEncryptedKey, privateKey) {
538
+ const aesKeyHex = eciesDecrypt(eciesEncryptedKey, privateKey);
539
+ return decryptPayload(encryptedPayload, aesKeyHex);
540
+ }
541
+ function generateKeyPair() {
542
+ const priv = randomBytes(32);
543
+ const pub = secp256k1.getPublicKey(priv, false);
544
+ return { privateKey: bytesToHex(priv), publicKey: bytesToHex(pub) };
545
+ }
546
+ function getPublicKey(privateKey) {
547
+ return bytesToHex(secp256k1.getPublicKey(hexToBytes(privateKey), false));
548
+ }
549
+
550
+ // src/registry/ipfs-fetcher.ts
551
+ var IPFSFetcher = class {
552
+ gateway;
553
+ fallbackGateways;
554
+ timeoutMs;
555
+ cache = /* @__PURE__ */ new Map();
556
+ maxCache;
557
+ pending = /* @__PURE__ */ new Map();
558
+ failed = /* @__PURE__ */ new Set();
559
+ constructor(config = {}) {
560
+ this.gateway = config.gateway ?? "ipfs.io";
561
+ this.fallbackGateways = config.fallbackGateways ?? [
562
+ "gateway.pinata.cloud",
563
+ "dweb.link",
564
+ "cf-ipfs.com"
565
+ ];
566
+ this.timeoutMs = config.timeoutMs ?? 1e4;
567
+ this.maxCache = config.maxCache ?? 200;
568
+ }
569
+ // ── Public API ──────────────────────────────────────────────────────────
570
+ /** Fetch JSON from a single IPFS CID. */
571
+ async fetchJSON(cid) {
572
+ const cached = this.cache.get(cid);
573
+ if (cached) return cached.data;
574
+ if (this.failed.has(cid)) throw new Error(`CID ${cid} previously failed`);
575
+ const pending = this.pending.get(cid);
576
+ if (pending) return pending;
577
+ const promise = this._doFetch(cid);
578
+ this.pending.set(cid, promise);
579
+ try {
580
+ const data = await promise;
581
+ this._cacheSet(cid, data);
582
+ return data;
583
+ } catch (e) {
584
+ this.failed.add(cid);
585
+ throw e;
586
+ } finally {
587
+ this.pending.delete(cid);
588
+ }
589
+ }
590
+ /** Fetch encrypted agent payload (validates algorithm). */
591
+ async fetchEncryptedPayload(cid) {
592
+ const raw = await this.fetchJSON(cid);
593
+ if (!raw.encrypted || raw.algorithm !== "AES-256-GCM" || typeof raw.data !== "string") {
594
+ throw new Error(`Invalid EncryptedPayload at CID ${cid}`);
595
+ }
596
+ return raw;
597
+ }
598
+ /** Batch fetch multiple CIDs with concurrency control. */
599
+ async fetchBatch(cids, concurrency = 5) {
600
+ const results = /* @__PURE__ */ new Map();
601
+ const unique = [...new Set(cids)].filter((c) => this.isValidCID(c));
602
+ for (let i = 0; i < unique.length; i += concurrency) {
603
+ const batch = unique.slice(i, i + concurrency);
604
+ const settled = await Promise.allSettled(
605
+ batch.map((cid) => this.fetchJSON(cid))
606
+ );
607
+ settled.forEach((r, j) => {
608
+ if (r.status === "fulfilled") results.set(batch[j], r.value);
609
+ });
610
+ if (i + concurrency < unique.length) {
611
+ await new Promise((r) => setTimeout(r, 200));
612
+ }
613
+ }
614
+ return results;
615
+ }
616
+ /** Check if a string looks like a valid IPFS CID. */
617
+ isValidCID(cid) {
618
+ return /^(Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[a-z2-7]{58,}|[A-Za-z0-9+/]{46,})$/.test(cid);
619
+ }
620
+ /** Clear cache (optionally for a specific CID). */
621
+ clearCache(cid) {
622
+ if (cid) {
623
+ this.cache.delete(cid);
624
+ } else {
625
+ this.cache.clear();
626
+ }
627
+ this.failed.clear();
628
+ }
629
+ /** Number of cached entries. */
630
+ get cacheSize() {
631
+ return this.cache.size;
632
+ }
633
+ // ── Internal ─────────────────────────────────────────────────────────────
634
+ async _doFetch(cid) {
635
+ if (!this.isValidCID(cid)) throw new Error(`Invalid CID: ${cid}`);
636
+ try {
637
+ return await this._fetchFrom(cid, this.gateway, this.timeoutMs);
638
+ } catch {
639
+ }
640
+ for (const gw of this.fallbackGateways) {
641
+ try {
642
+ return await this._fetchFrom(cid, gw, this.timeoutMs);
643
+ } catch {
644
+ }
645
+ }
646
+ throw new Error(`All IPFS gateways failed for CID ${cid}`);
647
+ }
648
+ async _fetchFrom(cid, gateway, timeoutMs) {
649
+ const url = `https://${gateway}/ipfs/${cid}`;
650
+ const res = await fetch(url, {
651
+ headers: { Accept: "application/json" },
652
+ signal: AbortSignal.timeout(timeoutMs)
653
+ });
654
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
655
+ return await res.json();
656
+ }
657
+ _cacheSet(cid, data) {
658
+ this.cache.set(cid, { data, timestamp: Date.now() });
659
+ if (this.cache.size > this.maxCache) {
660
+ const oldest = [...this.cache.entries()].sort(
661
+ (a, b) => a[1].timestamp - b[1].timestamp
662
+ )[0];
663
+ if (oldest) this.cache.delete(oldest[0]);
664
+ }
665
+ }
666
+ };
667
+ var defaultIPFSFetcher = new IPFSFetcher();
668
+
669
+ // src/agent/agent-runner.ts
670
+ var AgentRunner = class {
671
+ reader;
672
+ wallet;
673
+ ipfs;
674
+ constructor(config) {
675
+ this.reader = config.reader;
676
+ this.wallet = config.wallet;
677
+ this.ipfs = config.ipfsFetcher ?? new IPFSFetcher({
678
+ fallbackGateways: config.ipfsGateways ?? [
679
+ "gateway.pinata.cloud",
680
+ "dweb.link",
681
+ "cf-ipfs.com"
682
+ ]
683
+ });
684
+ }
685
+ // ── Primary API: useAgent ────────────────────────────────────────────────
686
+ /**
687
+ * Load and decrypt an Agent, returning a run context ready to inject
688
+ * into any LLM conversation.
689
+ *
690
+ * Steps:
691
+ * 1. Verify on-chain subscription (frontend check)
692
+ * 2. Fetch metadata → get encryptedPayloadCid + eciesEncryptedKey
693
+ * 3. IPFS fetch encrypted payload
694
+ * 4. ECIES decrypt AES key (using wallet private key)
695
+ * 5. AES-256-GCM decrypt payload → { prompt, skills, mcp }
696
+ * 6. Build RunnableSkill wrappers (Open: local stub, Closed: MCP remote)
697
+ */
698
+ async useAgent(agentId) {
699
+ const address = await this.wallet.getAddress();
700
+ const isActive = await this.reader.hasActiveSubscription(address, agentId);
701
+ if (!isActive) {
702
+ const err = new AgentXError(
703
+ "NOT_SUBSCRIBED" /* NOT_SUBSCRIBED */,
704
+ `No active subscription for Agent #${agentId}. Check error.paymentInfo for auto-subscribe via wallet/X402.`
705
+ );
706
+ err.paymentInfo = {
707
+ agentId
708
+ };
709
+ throw err;
710
+ }
711
+ const attrs = await this.reader.getAttributes(agentId);
712
+ const encryptedPayloadCid = attrs.encryptedPayloadCid;
713
+ const eciesEncryptedKey = attrs.eciesEncryptedKey;
714
+ if (!encryptedPayloadCid || !eciesEncryptedKey) {
715
+ throw new AgentXError(
716
+ "AGENT_NOT_FOUND" /* AGENT_NOT_FOUND */,
717
+ `Agent #${agentId} metadata incomplete \u2014 missing encryptedPayloadCid or eciesEncryptedKey`
718
+ );
719
+ }
720
+ let encryptedPayload;
721
+ try {
722
+ encryptedPayload = await this.ipfs.fetchEncryptedPayload(encryptedPayloadCid);
723
+ } catch (e) {
724
+ throw new AgentXError(
725
+ "IPFS_FETCH_FAILED" /* IPFS_FETCH_FAILED */,
726
+ `Failed to fetch encrypted payload for agent #${agentId}: ${e}`
727
+ );
728
+ }
729
+ let privatePayload;
730
+ try {
731
+ const privKey = await this._getPrivateKey();
732
+ privatePayload = unpackAgent(encryptedPayload, eciesEncryptedKey, privKey);
733
+ } catch (e) {
734
+ throw new AgentXError(
735
+ "DECRYPTION_FAILED" /* DECRYPTION_FAILED */,
736
+ `Failed to decrypt agent #${agentId}: ${e}`
737
+ );
738
+ }
739
+ const skills = privatePayload.skills.map((s) => this._wrapSkill(s));
740
+ return {
741
+ agentId,
742
+ prompt: privatePayload.prompt,
743
+ skills,
744
+ mcp: {
745
+ type: privatePayload.mcp.type,
746
+ url: privatePayload.mcp.url,
747
+ toolFilter: privatePayload.mcp.toolFilter
748
+ },
749
+ subscriptionExpiry: 0
750
+ };
751
+ }
752
+ // ── Publishing ───────────────────────────────────────────────────────────
753
+ /**
754
+ * Pack an AgentPayload for publishing (encryption only, no IPFS upload).
755
+ * Caller is responsible for IPFS upload and on-chain registration.
756
+ */
757
+ packForPublish(payload, publicKey) {
758
+ const key = generateAesKey();
759
+ return {
760
+ encryptedCid: "",
761
+ publicCid: "",
762
+ aesKeyHex: key,
763
+ eciesEncryptedKeyHex: eciesEncrypt(key, publicKey)
764
+ };
765
+ }
766
+ // ── Internals ────────────────────────────────────────────────────────────
767
+ /** Wrap a SkillDef into a RunnableSkill with execute(). */
768
+ _wrapSkill(skill) {
769
+ let mode = "open";
770
+ let executeFn;
771
+ if (skill.execution) {
772
+ if (skill.execution.type === "mcp") {
773
+ mode = "mcp";
774
+ const endpoint = skill.execution.endpoint ?? "";
775
+ const toolName = skill.execution.toolName ?? skill.name;
776
+ executeFn = async (input) => {
777
+ return this._executeMCPTool(endpoint, toolName, input);
778
+ };
779
+ } else if (skill.execution.type === "a2a") {
780
+ mode = "a2a";
781
+ executeFn = async (input) => {
782
+ return this._executeA2ASkill(skill, input);
783
+ };
784
+ } else {
785
+ throw new AgentXError(
786
+ "INVALID_SCHEMA" /* INVALID_SCHEMA */,
787
+ `Unknown execution type "${skill.execution.type}" for skill "${skill.name}"`
788
+ );
789
+ }
790
+ } else {
791
+ executeFn = async () => {
792
+ throw new AgentXError(
793
+ "INVALID_SCHEMA" /* INVALID_SCHEMA */,
794
+ `Open skill "${skill.name}" has no local executor. Implement execute() or switch to execution.type = "mcp" or "a2a".`
795
+ );
796
+ };
797
+ }
798
+ return {
799
+ name: skill.name,
800
+ description: skill.description,
801
+ inputSchema: skill.inputSchema,
802
+ outputSchema: skill.outputSchema,
803
+ mode,
804
+ execute: executeFn,
805
+ /** If A2A, carry delegation metadata so the LLM can see it */
806
+ a2aTargetAgentId: skill.execution?.type === "a2a" ? skill.execution.targetAgentId : void 0
807
+ };
808
+ }
809
+ /** Call a tool on the publisher's MCP server (Closed skill). */
810
+ async _executeMCPTool(endpoint, toolName, params) {
811
+ const address = await this.wallet.getAddress();
812
+ const timestamp = Math.floor(Date.now() / 1e3);
813
+ const message = `agentx:mcp:${toolName}:${timestamp}`;
814
+ const signature = await this.wallet.signMessage(message);
815
+ const res = await fetch(endpoint, {
816
+ method: "POST",
817
+ headers: {
818
+ "Content-Type": "application/json",
819
+ "X-Subscriber-Address": address,
820
+ "X-Signature": signature,
821
+ "X-Timestamp": String(timestamp)
822
+ },
823
+ body: JSON.stringify({
824
+ method: "tools/call",
825
+ params: {
826
+ name: toolName,
827
+ arguments: params
828
+ }
829
+ })
830
+ });
831
+ if (!res.ok) {
832
+ const text = await res.text();
833
+ if (res.status === 403) {
834
+ throw new AgentXError(
835
+ "SUBSCRIPTION_EXPIRED" /* SUBSCRIPTION_EXPIRED */,
836
+ `MCP server rejected request: subscription may have expired. ${text}`
837
+ );
838
+ }
839
+ throw new AgentXError(
840
+ "TX_FAILED" /* TX_FAILED */,
841
+ `MCP tool "${toolName}" failed (HTTP ${res.status}): ${text}`
842
+ );
843
+ }
844
+ const data = await res.json();
845
+ const content = data.content?.[0];
846
+ if (content?.type === "text" && content.text) {
847
+ try {
848
+ return JSON.parse(content.text);
849
+ } catch {
850
+ return content.text;
851
+ }
852
+ }
853
+ return data;
854
+ }
855
+ /**
856
+ * Execute an A2A skill — delegate to another AgentX Agent.
857
+ *
858
+ * Standard Interface:
859
+ * Input: { task, ...taskSpecificParams }
860
+ * Output: { agentId, prompt, skills[] }
861
+ *
862
+ * The caller (LLM) receives the sub-Agent's prompt + skill list.
863
+ * The LLM then decides how to use the sub-Agent — typically by
864
+ * injecting the sub-Agent's system prompt and calling its skills.
865
+ */
866
+ async _executeA2ASkill(skill, input) {
867
+ const exec = skill.execution;
868
+ if (!exec || exec.type !== "a2a") {
869
+ throw new AgentXError(
870
+ "INVALID_SCHEMA" /* INVALID_SCHEMA */,
871
+ `Skill "${skill.name}" is not an A2A delegation skill`
872
+ );
873
+ }
874
+ const targetAgentId = exec.targetAgentId;
875
+ let subContext;
876
+ try {
877
+ subContext = await this.useAgent(targetAgentId);
878
+ } catch (e) {
879
+ throw new AgentXError(
880
+ "AGENT_NOT_FOUND" /* AGENT_NOT_FOUND */,
881
+ `A2A delegation failed: cannot load Agent #${targetAgentId}. ${e}`
882
+ );
883
+ }
884
+ if (exec.skillFilter && exec.skillFilter.length > 0) {
885
+ const filterSet = new Set(exec.skillFilter);
886
+ subContext = {
887
+ ...subContext,
888
+ skills: subContext.skills.filter((s) => filterSet.has(s.name))
889
+ };
890
+ }
891
+ if (exec.promptOverride) {
892
+ subContext = { ...subContext, prompt: exec.promptOverride };
893
+ }
894
+ return {
895
+ agentId: targetAgentId,
896
+ prompt: subContext.prompt,
897
+ skills: subContext.skills.map((s) => ({
898
+ name: s.name,
899
+ description: s.description,
900
+ inputSchema: s.inputSchema
901
+ })),
902
+ // Pass the caller's input to the sub-agent's context
903
+ callerInput: input
904
+ };
905
+ }
906
+ async _getPrivateKey() {
907
+ if (this.wallet.getPrivateKey) return this.wallet.getPrivateKey();
908
+ throw new AgentXError(
909
+ "WALLET_NOT_CONNECTED" /* WALLET_NOT_CONNECTED */,
910
+ "Wallet must support getPrivateKey() for ECIES decryption."
911
+ );
912
+ }
913
+ };
914
+
915
+ // node_modules/.pnpm/viem@2.55.0_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@5.0.10_zod@4.4.3/node_modules/viem/_esm/index.js
916
+ init_fromHex();
917
+ init_toHex();
918
+
919
+ // src/registry/agent-registry.ts
920
+ var IDENTITY_REGISTRY_ABI = {
921
+ // Register
922
+ register: {
923
+ inputs: [],
924
+ name: "register",
925
+ outputs: [{ name: "agentId", type: "uint256" }],
926
+ stateMutability: "payable",
927
+ type: "function"
928
+ },
929
+ registerWithTokenURI: {
930
+ inputs: [{ name: "tokenURI", type: "string" }],
931
+ name: "register",
932
+ outputs: [{ name: "agentId", type: "uint256" }],
933
+ stateMutability: "payable",
934
+ type: "function"
935
+ },
936
+ registerWithMetadata: {
937
+ inputs: [
938
+ { name: "tokenURI", type: "string" },
939
+ {
940
+ name: "metadata",
941
+ type: "tuple[]",
942
+ components: [
943
+ { name: "key", type: "string" },
944
+ { name: "value", type: "bytes" }
945
+ ]
946
+ }
947
+ ],
948
+ name: "registerWithMetadata",
949
+ outputs: [{ name: "agentId", type: "uint256" }],
950
+ stateMutability: "payable",
951
+ type: "function"
952
+ },
953
+ // Queries
954
+ getAgentsByOwner: {
955
+ inputs: [{ name: "owner", type: "address" }],
956
+ name: "getAgentsByOwner",
957
+ outputs: [{ name: "", type: "uint256[]" }],
958
+ stateMutability: "view",
959
+ type: "function"
960
+ },
961
+ getCurrentAgentId: {
962
+ inputs: [],
963
+ name: "getCurrentAgentId",
964
+ outputs: [{ name: "", type: "uint256" }],
965
+ stateMutability: "view",
966
+ type: "function"
967
+ },
968
+ agentExists: {
969
+ inputs: [{ name: "agentId", type: "uint256" }],
970
+ name: "agentExists",
971
+ outputs: [{ name: "", type: "bool" }],
972
+ stateMutability: "view",
973
+ type: "function"
974
+ },
975
+ tokenURI: {
976
+ inputs: [{ name: "tokenId", type: "uint256" }],
977
+ name: "tokenURI",
978
+ outputs: [{ name: "", type: "string" }],
979
+ stateMutability: "view",
980
+ type: "function"
981
+ },
982
+ getAgentMetadata: {
983
+ inputs: [{ name: "agentId", type: "uint256" }],
984
+ name: "getAgentMetadata",
985
+ outputs: [{ name: "", type: "tuple[]", components: [{ name: "key", type: "string" }, { name: "value", type: "bytes" }] }],
986
+ stateMutability: "view",
987
+ type: "function"
988
+ }
989
+ };
990
+ var AgentRegistry = class {
991
+ address;
992
+ publicClient;
993
+ walletClient;
994
+ constructor(config) {
995
+ this.address = config.contractAddress;
996
+ this.publicClient = config.publicClient;
997
+ this.walletClient = config.walletClient;
998
+ }
999
+ // ── Write: Register Agent ───────────────────────────────────────────────
1000
+ /**
1001
+ * Register a new Agent NFT on-chain.
1002
+ *
1003
+ * @param tokenURI IPFS URI of the public metadata (ipfs://...)
1004
+ * @param metadata Key-value metadata (encryptedPayloadCid, eciesEncryptedKey, etc.)
1005
+ * @param valueWei Optional: native currency to send with registration
1006
+ * @returns { agentId: number, txHash: Hash }
1007
+ */
1008
+ async register(tokenURI, metadata, valueWei) {
1009
+ const [account] = await this.walletClient.getAddresses();
1010
+ if (!account) throw new Error("Wallet not connected");
1011
+ const encodedMetadata = metadata.map((m) => ({
1012
+ key: m.key,
1013
+ value: stringToHex(m.value)
1014
+ }));
1015
+ const { request } = await this.publicClient.simulateContract({
1016
+ account,
1017
+ address: this.address,
1018
+ abi: [IDENTITY_REGISTRY_ABI.registerWithMetadata],
1019
+ functionName: "registerWithMetadata",
1020
+ args: [tokenURI, encodedMetadata],
1021
+ value: valueWei
1022
+ });
1023
+ const hash = await this.walletClient.writeContract(request);
1024
+ const receipt = await this.publicClient.waitForTransactionReceipt({ hash });
1025
+ const agentId = this._parseAgentIdFromReceipt(receipt);
1026
+ return { agentId, txHash: hash };
1027
+ }
1028
+ /**
1029
+ * Simple register — just a tokenURI, no extra metadata.
1030
+ */
1031
+ async registerSimple(tokenURI, valueWei) {
1032
+ const [account] = await this.walletClient.getAddresses();
1033
+ if (!account) throw new Error("Wallet not connected");
1034
+ const abi = tokenURI ? [IDENTITY_REGISTRY_ABI.registerWithTokenURI] : [IDENTITY_REGISTRY_ABI.register];
1035
+ const args = tokenURI ? [tokenURI] : [];
1036
+ const { request } = await this.publicClient.simulateContract({
1037
+ account,
1038
+ address: this.address,
1039
+ abi,
1040
+ functionName: "register",
1041
+ args,
1042
+ value: valueWei
1043
+ });
1044
+ const hash = await this.walletClient.writeContract(request);
1045
+ const receipt = await this.publicClient.waitForTransactionReceipt({ hash });
1046
+ const agentId = this._parseAgentIdFromReceipt(receipt);
1047
+ return { agentId, txHash: hash };
1048
+ }
1049
+ // ── Read: Query ──────────────────────────────────────────────────────────
1050
+ /** Get all agent IDs owned by an address. */
1051
+ async getAgentsByOwner(owner) {
1052
+ const result = await this.publicClient.readContract({
1053
+ address: this.address,
1054
+ abi: [IDENTITY_REGISTRY_ABI.getAgentsByOwner],
1055
+ functionName: "getAgentsByOwner",
1056
+ args: [owner]
1057
+ });
1058
+ return result.map(Number);
1059
+ }
1060
+ /** Get the current total agent count. */
1061
+ async getCurrentAgentId() {
1062
+ const result = await this.publicClient.readContract({
1063
+ address: this.address,
1064
+ abi: [IDENTITY_REGISTRY_ABI.getCurrentAgentId],
1065
+ functionName: "getCurrentAgentId"
1066
+ });
1067
+ return Number(result);
1068
+ }
1069
+ /** Check if an agent exists. */
1070
+ async agentExists(agentId) {
1071
+ const result = await this.publicClient.readContract({
1072
+ address: this.address,
1073
+ abi: [IDENTITY_REGISTRY_ABI.agentExists],
1074
+ functionName: "agentExists",
1075
+ args: [BigInt(agentId)]
1076
+ });
1077
+ return result;
1078
+ }
1079
+ /** Get the tokenURI for an agent. */
1080
+ async tokenURI(agentId) {
1081
+ const result = await this.publicClient.readContract({
1082
+ address: this.address,
1083
+ abi: [IDENTITY_REGISTRY_ABI.tokenURI],
1084
+ functionName: "tokenURI",
1085
+ args: [BigInt(agentId)]
1086
+ });
1087
+ return result;
1088
+ }
1089
+ /** Get all metadata attributes for an agent as key-value pairs. */
1090
+ async getAttributes(agentId) {
1091
+ const result = await this.publicClient.readContract({
1092
+ address: this.address,
1093
+ abi: [IDENTITY_REGISTRY_ABI.getAgentMetadata],
1094
+ functionName: "getAgentMetadata",
1095
+ args: [BigInt(agentId)]
1096
+ });
1097
+ const attrs = {};
1098
+ for (const item of result) {
1099
+ attrs[item.key] = hexToString(item.value);
1100
+ }
1101
+ return attrs;
1102
+ }
1103
+ // ── Helpers ──────────────────────────────────────────────────────────────
1104
+ /** Extract tokenId from the Transfer event in the receipt. */
1105
+ _parseAgentIdFromReceipt(receipt) {
1106
+ for (const log of receipt.logs) {
1107
+ const transferTopic = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef";
1108
+ if (log.topics[0] === transferTopic && log.topics.length >= 4) {
1109
+ return Number(BigInt(log.topics[3]));
1110
+ }
1111
+ }
1112
+ throw new Error("Could not parse agentId from Transfer event in receipt");
1113
+ }
1114
+ };
1115
+ function cidFromURI(uri) {
1116
+ return uri.replace(/^ipfs:\/\//, "");
1117
+ }
1118
+
1119
+ // src/registry/index.ts
1120
+ var REGISTRY_VERSION = "0.1.0";
1121
+
1122
+ // src/subscription/subscription.ts
1123
+ var SUBSCRIPTION_ABI_V2 = {
1124
+ // Admin
1125
+ platformFeeBps: {
1126
+ inputs: [],
1127
+ name: "platformFeeBps",
1128
+ outputs: [{ name: "", type: "uint256" }],
1129
+ stateMutability: "view",
1130
+ type: "function"
1131
+ },
1132
+ tokenWhitelist: {
1133
+ inputs: [{ name: "token", type: "address" }],
1134
+ name: "tokenWhitelist",
1135
+ outputs: [{ name: "", type: "bool" }],
1136
+ stateMutability: "view",
1137
+ type: "function"
1138
+ },
1139
+ // Plans
1140
+ createPlan: {
1141
+ inputs: [
1142
+ { name: "agentId", type: "uint256" },
1143
+ { name: "price", type: "uint256" },
1144
+ { name: "period", type: "string" },
1145
+ { name: "payToken", type: "address" },
1146
+ { name: "trialDays", type: "uint256" }
1147
+ ],
1148
+ name: "createPlan",
1149
+ outputs: [{ name: "planId", type: "uint256" }],
1150
+ stateMutability: "nonpayable",
1151
+ type: "function"
1152
+ },
1153
+ getPlan: {
1154
+ inputs: [{ name: "planId", type: "uint256" }],
1155
+ name: "getPlan",
1156
+ outputs: [
1157
+ { name: "planId", type: "uint256" },
1158
+ { name: "agentId", type: "uint256" },
1159
+ { name: "creator", type: "address" },
1160
+ { name: "price", type: "uint256" },
1161
+ { name: "period", type: "string" },
1162
+ { name: "active", type: "bool" },
1163
+ { name: "payToken", type: "address" },
1164
+ { name: "trialDays", type: "uint256" }
1165
+ ],
1166
+ stateMutability: "view",
1167
+ type: "function"
1168
+ },
1169
+ // Subscribe
1170
+ subscribe: {
1171
+ inputs: [{ name: "planId", type: "uint256" }],
1172
+ name: "subscribe",
1173
+ outputs: [{ name: "subscriptionId", type: "uint256" }],
1174
+ stateMutability: "payable",
1175
+ type: "function"
1176
+ },
1177
+ // Trial / Release
1178
+ releaseFunds: {
1179
+ inputs: [{ name: "subscriptionId", type: "uint256" }],
1180
+ name: "releaseFunds",
1181
+ outputs: [],
1182
+ stateMutability: "nonpayable",
1183
+ type: "function"
1184
+ },
1185
+ cancelSubscription: {
1186
+ inputs: [{ name: "subscriptionId", type: "uint256" }],
1187
+ name: "cancelSubscription",
1188
+ outputs: [],
1189
+ stateMutability: "nonpayable",
1190
+ type: "function"
1191
+ },
1192
+ // Queries
1193
+ getSubscription: {
1194
+ inputs: [
1195
+ { name: "subscriber", type: "address" },
1196
+ { name: "agentId", type: "uint256" }
1197
+ ],
1198
+ name: "getSubscription",
1199
+ outputs: [
1200
+ { name: "subscriptionId", type: "uint256" },
1201
+ { name: "subscriber", type: "address" },
1202
+ { name: "agentId", type: "uint256" },
1203
+ { name: "status", type: "uint8" },
1204
+ { name: "startedAt", type: "uint256" },
1205
+ { name: "expiresAt", type: "uint256" },
1206
+ { name: "period", type: "string" }
1207
+ ],
1208
+ stateMutability: "view",
1209
+ type: "function"
1210
+ },
1211
+ hasActiveSubscription: {
1212
+ inputs: [
1213
+ { name: "subscriber", type: "address" },
1214
+ { name: "agentId", type: "uint256" }
1215
+ ],
1216
+ name: "hasActiveSubscription",
1217
+ outputs: [{ name: "", type: "bool" }],
1218
+ stateMutability: "view",
1219
+ type: "function"
1220
+ },
1221
+ getUserSubscriptions: {
1222
+ inputs: [{ name: "user", type: "address" }],
1223
+ name: "getUserSubscriptions",
1224
+ outputs: [{ name: "", type: "uint256[]" }],
1225
+ stateMutability: "view",
1226
+ type: "function"
1227
+ },
1228
+ getSubscriptionDetail: {
1229
+ inputs: [{ name: "subscriptionId", type: "uint256" }],
1230
+ name: "getSubscriptionDetail",
1231
+ outputs: [
1232
+ { name: "subscriptionId", type: "uint256" },
1233
+ { name: "subscriber", type: "address" },
1234
+ { name: "agentId", type: "uint256" },
1235
+ { name: "status", type: "uint8" },
1236
+ { name: "startedAt", type: "uint256" },
1237
+ { name: "expiresAt", type: "uint256" },
1238
+ { name: "period", type: "string" },
1239
+ { name: "payToken", type: "address" },
1240
+ { name: "amountPaid", type: "uint256" },
1241
+ { name: "trialActive", type: "bool" },
1242
+ { name: "trialEndsAt", type: "uint256" },
1243
+ { name: "fundsReleased", type: "bool" }
1244
+ ],
1245
+ stateMutability: "view",
1246
+ type: "function"
1247
+ }
1248
+ };
1249
+ var ERC20_ABI = {
1250
+ approve: {
1251
+ inputs: [
1252
+ { name: "spender", type: "address" },
1253
+ { name: "amount", type: "uint256" }
1254
+ ],
1255
+ name: "approve",
1256
+ outputs: [{ name: "", type: "bool" }],
1257
+ stateMutability: "nonpayable",
1258
+ type: "function"
1259
+ },
1260
+ allowance: {
1261
+ inputs: [
1262
+ { name: "owner", type: "address" },
1263
+ { name: "spender", type: "address" }
1264
+ ],
1265
+ name: "allowance",
1266
+ outputs: [{ name: "", type: "uint256" }],
1267
+ stateMutability: "view",
1268
+ type: "function"
1269
+ }
1270
+ };
1271
+ var SubscriptionManager = class {
1272
+ address;
1273
+ publicClient;
1274
+ walletClient;
1275
+ constructor(config) {
1276
+ this.address = config.contractAddress;
1277
+ this.publicClient = config.publicClient;
1278
+ this.walletClient = config.walletClient;
1279
+ }
1280
+ // ── Config Read ──────────────────────────────────────────────────────────
1281
+ /** Get current platform fee in basis points (e.g. 250 = 2.5%). */
1282
+ async getPlatformFeeBps() {
1283
+ const result = await this.publicClient.readContract({
1284
+ address: this.address,
1285
+ abi: [SUBSCRIPTION_ABI_V2.platformFeeBps],
1286
+ functionName: "platformFeeBps"
1287
+ });
1288
+ return Number(result);
1289
+ }
1290
+ /** Check if a token is whitelisted for payments. */
1291
+ async isTokenWhitelisted(token) {
1292
+ const result = await this.publicClient.readContract({
1293
+ address: this.address,
1294
+ abi: [SUBSCRIPTION_ABI_V2.tokenWhitelist],
1295
+ functionName: "tokenWhitelist",
1296
+ args: [token]
1297
+ });
1298
+ return result;
1299
+ }
1300
+ // ── Plans ────────────────────────────────────────────────────────────────
1301
+ /** Get full plan details with v2 fields. */
1302
+ async getPlan(planId) {
1303
+ const result = await this.publicClient.readContract({
1304
+ address: this.address,
1305
+ abi: [SUBSCRIPTION_ABI_V2.getPlan],
1306
+ functionName: "getPlan",
1307
+ args: [BigInt(planId)]
1308
+ });
1309
+ const [pid, aid, creator, price, period, active, payToken, trialDays] = result;
1310
+ return {
1311
+ planId: Number(pid),
1312
+ agentId: Number(aid),
1313
+ creator,
1314
+ price,
1315
+ period,
1316
+ active,
1317
+ payToken,
1318
+ trialDays: Number(trialDays)
1319
+ };
1320
+ }
1321
+ // ── Subscribe ────────────────────────────────────────────────────────────
1322
+ /**
1323
+ * Subscribe to a plan.
1324
+ * For ETH plans: pass valueWei = plan.price.
1325
+ * For ERC20 plans: auto-detects from plan.payToken, calls approve + subscribe.
1326
+ * User must have approved this contract for plan.price tokens.
1327
+ */
1328
+ async subscribe(planId, opts) {
1329
+ const [account] = await this.walletClient.getAddresses();
1330
+ if (!account) throw new Error("Wallet not connected");
1331
+ const plan = await this.getPlan(planId);
1332
+ if (!plan.active) throw new Error("Plan not active");
1333
+ if (plan.payToken === "0x0000000000000000000000000000000000000000") {
1334
+ const value = opts?.valueWei ?? plan.price;
1335
+ const { request } = await this.publicClient.simulateContract({
1336
+ account,
1337
+ address: this.address,
1338
+ abi: [SUBSCRIPTION_ABI_V2.subscribe],
1339
+ functionName: "subscribe",
1340
+ args: [BigInt(planId)],
1341
+ value
1342
+ });
1343
+ const hash = await this.walletClient.writeContract(request);
1344
+ return { subscriptionId: 0, txHash: hash };
1345
+ } else {
1346
+ if (opts?.approveTokenFirst !== false) {
1347
+ const allowance = await this.publicClient.readContract({
1348
+ address: plan.payToken,
1349
+ abi: [ERC20_ABI.allowance],
1350
+ functionName: "allowance",
1351
+ args: [account, this.address]
1352
+ });
1353
+ if (allowance < plan.price) {
1354
+ const { request: approveReq } = await this.publicClient.simulateContract({
1355
+ account,
1356
+ address: plan.payToken,
1357
+ abi: [ERC20_ABI.approve],
1358
+ functionName: "approve",
1359
+ args: [this.address, plan.price]
1360
+ });
1361
+ await this.walletClient.writeContract(approveReq);
1362
+ }
1363
+ }
1364
+ const { request } = await this.publicClient.simulateContract({
1365
+ account,
1366
+ address: this.address,
1367
+ abi: [SUBSCRIPTION_ABI_V2.subscribe],
1368
+ functionName: "subscribe",
1369
+ args: [BigInt(planId)]
1370
+ });
1371
+ const hash = await this.walletClient.writeContract(request);
1372
+ return { subscriptionId: 0, txHash: hash };
1373
+ }
1374
+ }
1375
+ /** Release escrowed funds to creator after trial window ends. */
1376
+ async releaseFunds(subscriptionId) {
1377
+ const [account] = await this.walletClient.getAddresses();
1378
+ if (!account) throw new Error("Wallet not connected");
1379
+ const { request } = await this.publicClient.simulateContract({
1380
+ account,
1381
+ address: this.address,
1382
+ abi: [SUBSCRIPTION_ABI_V2.releaseFunds],
1383
+ functionName: "releaseFunds",
1384
+ args: [BigInt(subscriptionId)]
1385
+ });
1386
+ return this.walletClient.writeContract(request);
1387
+ }
1388
+ /** Cancel subscription (trial refund if within window). */
1389
+ async cancel(subscriptionId) {
1390
+ const [account] = await this.walletClient.getAddresses();
1391
+ if (!account) throw new Error("Wallet not connected");
1392
+ const { request } = await this.publicClient.simulateContract({
1393
+ account,
1394
+ address: this.address,
1395
+ abi: [SUBSCRIPTION_ABI_V2.cancelSubscription],
1396
+ functionName: "cancelSubscription",
1397
+ args: [BigInt(subscriptionId)]
1398
+ });
1399
+ return this.walletClient.writeContract(request);
1400
+ }
1401
+ // ── Read ─────────────────────────────────────────────────────────────────
1402
+ async hasActiveSubscription(subscriber, agentId) {
1403
+ const result = await this.publicClient.readContract({
1404
+ address: this.address,
1405
+ abi: [SUBSCRIPTION_ABI_V2.hasActiveSubscription],
1406
+ functionName: "hasActiveSubscription",
1407
+ args: [subscriber, BigInt(agentId)]
1408
+ });
1409
+ return result;
1410
+ }
1411
+ async getSubscription(subscriber, agentId) {
1412
+ const result = await this.publicClient.readContract({
1413
+ address: this.address,
1414
+ abi: [SUBSCRIPTION_ABI_V2.getSubscription],
1415
+ functionName: "getSubscription",
1416
+ args: [subscriber, BigInt(agentId)]
1417
+ });
1418
+ const [subId, sub, aId, status, started, expires, period] = result;
1419
+ if (Number(subId) === 0) return null;
1420
+ return {
1421
+ subscriptionId: Number(subId),
1422
+ subscriber: sub,
1423
+ agentId: Number(aId),
1424
+ status: ["active", "expired", "cancelled", "pending"][status],
1425
+ startedAt: Number(started),
1426
+ expiresAt: Number(expires),
1427
+ period
1428
+ };
1429
+ }
1430
+ /** Get full subscription detail with v2 fields (trial, payToken, fundsReleased). */
1431
+ async getSubscriptionDetail(subscriptionId) {
1432
+ const result = await this.publicClient.readContract({
1433
+ address: this.address,
1434
+ abi: [SUBSCRIPTION_ABI_V2.getSubscriptionDetail],
1435
+ functionName: "getSubscriptionDetail",
1436
+ args: [BigInt(subscriptionId)]
1437
+ });
1438
+ const [
1439
+ sid,
1440
+ sub,
1441
+ aId,
1442
+ status,
1443
+ started,
1444
+ expires,
1445
+ period,
1446
+ payToken,
1447
+ amountPaid,
1448
+ trialActive,
1449
+ trialEndsAt,
1450
+ fundsReleased
1451
+ ] = result;
1452
+ return {
1453
+ subscriptionId: Number(sid),
1454
+ subscriber: sub,
1455
+ agentId: Number(aId),
1456
+ status,
1457
+ startedAt: Number(started),
1458
+ expiresAt: Number(expires),
1459
+ period,
1460
+ payToken,
1461
+ amountPaid,
1462
+ trialActive,
1463
+ trialEndsAt: Number(trialEndsAt),
1464
+ fundsReleased
1465
+ };
1466
+ }
1467
+ async getUserSubscriptions(user) {
1468
+ const result = await this.publicClient.readContract({
1469
+ address: this.address,
1470
+ abi: [SUBSCRIPTION_ABI_V2.getUserSubscriptions],
1471
+ functionName: "getUserSubscriptions",
1472
+ args: [user]
1473
+ });
1474
+ return result.map(Number);
1475
+ }
1476
+ };
1477
+ async function guardSubscription(manager, user, agentId) {
1478
+ const active = await manager.hasActiveSubscription(user, agentId);
1479
+ if (!active) {
1480
+ throw new Error(
1481
+ `No active subscription for agent #${agentId}. Address ${user} must purchase a subscription first.`
1482
+ );
1483
+ }
1484
+ const sub = await manager.getSubscription(user, agentId);
1485
+ if (!sub) throw new Error(`Subscription not found for agent #${agentId}`);
1486
+ return sub;
1487
+ }
1488
+
1489
+ // src/subscription/agent-x402.ts
1490
+ var getPlanAbi = {
1491
+ inputs: [{ name: "planId", type: "uint256" }],
1492
+ name: "getPlan",
1493
+ outputs: [
1494
+ { name: "planId", type: "uint256" },
1495
+ { name: "agentId", type: "uint256" },
1496
+ { name: "creator", type: "address" },
1497
+ { name: "price", type: "uint256" },
1498
+ { name: "period", type: "string" },
1499
+ { name: "active", type: "bool" },
1500
+ { name: "payToken", type: "address" },
1501
+ { name: "trialDays", type: "uint256" }
1502
+ ],
1503
+ stateMutability: "view",
1504
+ type: "function"
1505
+ };
1506
+ var subscribeAbi = {
1507
+ inputs: [{ name: "planId", type: "uint256" }],
1508
+ name: "subscribe",
1509
+ outputs: [{ name: "subscriptionId", type: "uint256" }],
1510
+ stateMutability: "payable",
1511
+ type: "function"
1512
+ };
1513
+ var hasActiveSubAbi = {
1514
+ inputs: [
1515
+ { name: "subscriber", type: "address" },
1516
+ { name: "agentId", type: "uint256" }
1517
+ ],
1518
+ name: "hasActiveSubscription",
1519
+ outputs: [{ name: "", type: "bool" }],
1520
+ stateMutability: "view",
1521
+ type: "function"
1522
+ };
1523
+ var AgentX402 = class {
1524
+ constructor(config) {
1525
+ this.config = config;
1526
+ }
1527
+ config;
1528
+ /**
1529
+ * Require active subscription — or throw with auto-pay info.
1530
+ *
1531
+ * Usage:
1532
+ * await x402.requireSubscription(agentId, address, { planIds: [1,2,3] })
1533
+ *
1534
+ * On success, returns silently.
1535
+ * On failure, throws AgentXError with paymentInfo populated
1536
+ * so the caller can auto-pay via wallet/X402.
1537
+ */
1538
+ async requireSubscription(agentId, address, opts) {
1539
+ const { publicClient, subscriptionManagerAddress } = this.config;
1540
+ const isActive = await publicClient.readContract({
1541
+ address: subscriptionManagerAddress,
1542
+ abi: [hasActiveSubAbi],
1543
+ functionName: "hasActiveSubscription",
1544
+ args: [address, BigInt(agentId)]
1545
+ });
1546
+ if (isActive) return;
1547
+ const plans = [];
1548
+ if (opts?.planIds && opts.planIds.length > 0) {
1549
+ for (const planId of opts.planIds) {
1550
+ try {
1551
+ const plan = await publicClient.readContract({
1552
+ address: subscriptionManagerAddress,
1553
+ abi: [getPlanAbi],
1554
+ functionName: "getPlan",
1555
+ args: [BigInt(planId)]
1556
+ });
1557
+ const planAgentId = Number(plan[1]);
1558
+ const planActive = plan[5];
1559
+ if (planActive && planAgentId === agentId) {
1560
+ plans.push({
1561
+ planId: Number(plan[0]),
1562
+ price: plan[3],
1563
+ period: plan[4],
1564
+ payToken: plan[6],
1565
+ trialDays: Number(plan[7])
1566
+ });
1567
+ }
1568
+ } catch {
1569
+ }
1570
+ }
1571
+ }
1572
+ const err = new AgentXError(
1573
+ "NOT_SUBSCRIBED" /* NOT_SUBSCRIBED */,
1574
+ `No active subscription for Agent #${agentId}. Use error.paymentInfo for auto-subscribe via X402/wallet.`
1575
+ );
1576
+ err.paymentInfo = {
1577
+ agentId,
1578
+ plans: plans.length > 0 ? plans : void 0
1579
+ };
1580
+ throw err;
1581
+ }
1582
+ /**
1583
+ * Subscribe to a plan + wait for receipt.
1584
+ * Returns subscriptionId from the Subscribed event.
1585
+ *
1586
+ * NOTE: For ERC20 plans, the caller must approve token spending
1587
+ * BEFORE calling this method. Use X402 SDK or wagmi's useWriteContract
1588
+ * for the approve step.
1589
+ */
1590
+ async subscribeAndWait(planId, price, payToken) {
1591
+ const { publicClient, walletClient, subscriptionManagerAddress } = this.config;
1592
+ const isETH = payToken === "0x0000000000000000000000000000000000000000";
1593
+ const { request } = await publicClient.simulateContract({
1594
+ address: subscriptionManagerAddress,
1595
+ abi: [subscribeAbi],
1596
+ functionName: "subscribe",
1597
+ args: [BigInt(planId)],
1598
+ account: walletClient.account?.address,
1599
+ value: isETH ? price : 0n
1600
+ });
1601
+ const hash = await walletClient.writeContract(request);
1602
+ const receipt = await publicClient.waitForTransactionReceipt({ hash });
1603
+ const subIdHex = receipt.logs[0]?.topics?.[1];
1604
+ if (!subIdHex || subIdHex === "0x") {
1605
+ throw new Error("Failed to parse subscriptionId from Subscribed event");
1606
+ }
1607
+ return Number(BigInt(subIdHex));
1608
+ }
1609
+ };
1610
+
1611
+ // src/subscription/index.ts
1612
+ var SUBSCRIPTION_VERSION = "0.2.0";
1613
+
1614
+ // src/a2a/a2a.ts
1615
+ var A2A_ABI = {
1616
+ createAgentCard: {
1617
+ inputs: [
1618
+ { name: "agentId", type: "uint256" },
1619
+ { name: "name", type: "string" },
1620
+ { name: "description", type: "string" },
1621
+ { name: "version", type: "string" },
1622
+ { name: "capabilities", type: "string[]" },
1623
+ { name: "supportedTasks", type: "string[]" },
1624
+ { name: "communicationProtocol", type: "string" },
1625
+ { name: "authenticationMethod", type: "string" },
1626
+ { name: "cardURI", type: "string" }
1627
+ ],
1628
+ name: "createAgentCard",
1629
+ outputs: [{ name: "cardId", type: "uint256" }],
1630
+ stateMutability: "nonpayable",
1631
+ type: "function"
1632
+ },
1633
+ getAgentCard: {
1634
+ inputs: [{ name: "agentId", type: "uint256" }],
1635
+ name: "getAgentCard",
1636
+ outputs: [
1637
+ { name: "cardId", type: "uint256" },
1638
+ { name: "agentId", type: "uint256" },
1639
+ { name: "name", type: "string" },
1640
+ { name: "description", type: "string" },
1641
+ { name: "version", type: "string" },
1642
+ { name: "capabilities", type: "string[]" },
1643
+ { name: "supportedTasks", type: "string[]" },
1644
+ { name: "communicationProtocol", type: "string" },
1645
+ { name: "authenticationMethod", type: "string" },
1646
+ { name: "cardURI", type: "string" },
1647
+ { name: "isActive", type: "bool" }
1648
+ ],
1649
+ stateMutability: "view",
1650
+ type: "function"
1651
+ },
1652
+ registerSkill: {
1653
+ inputs: [
1654
+ { name: "name", type: "string" },
1655
+ { name: "description", type: "string" },
1656
+ { name: "inputSchema", type: "string" },
1657
+ { name: "outputSchema", type: "string" },
1658
+ { name: "requiredCapabilities", type: "string[]" },
1659
+ { name: "complexity", type: "uint256" }
1660
+ ],
1661
+ name: "registerSkill",
1662
+ outputs: [{ name: "skillId", type: "uint256" }],
1663
+ stateMutability: "nonpayable",
1664
+ type: "function"
1665
+ },
1666
+ addAgentSkill: {
1667
+ inputs: [
1668
+ { name: "agentId", type: "uint256" },
1669
+ { name: "skillId", type: "uint256" },
1670
+ { name: "skillEndpoint", type: "string" },
1671
+ { name: "version", type: "string" },
1672
+ { name: "price", type: "uint256" },
1673
+ { name: "priceToken", type: "address" }
1674
+ ],
1675
+ name: "addAgentSkill",
1676
+ outputs: [],
1677
+ stateMutability: "nonpayable",
1678
+ type: "function"
1679
+ },
1680
+ createTask: {
1681
+ inputs: [
1682
+ { name: "agentId", type: "uint256" },
1683
+ { name: "taskType", type: "string" },
1684
+ { name: "inputData", type: "string" }
1685
+ ],
1686
+ name: "createTask",
1687
+ outputs: [{ name: "taskId", type: "uint256" }],
1688
+ stateMutability: "nonpayable",
1689
+ type: "function"
1690
+ },
1691
+ completeTask: {
1692
+ inputs: [
1693
+ { name: "taskId", type: "uint256" },
1694
+ { name: "outputData", type: "string" }
1695
+ ],
1696
+ name: "completeTask",
1697
+ outputs: [],
1698
+ stateMutability: "nonpayable",
1699
+ type: "function"
1700
+ },
1701
+ getTask: {
1702
+ inputs: [{ name: "taskId", type: "uint256" }],
1703
+ name: "getTask",
1704
+ outputs: [
1705
+ { name: "taskId", type: "uint256" },
1706
+ { name: "agentId", type: "uint256" },
1707
+ { name: "taskType", type: "string" },
1708
+ { name: "inputData", type: "string" },
1709
+ { name: "outputData", type: "string" },
1710
+ { name: "status", type: "uint256" },
1711
+ { name: "clientAddress", type: "address" },
1712
+ { name: "createdAt", type: "uint256" },
1713
+ { name: "completedAt", type: "uint256" }
1714
+ ],
1715
+ stateMutability: "view",
1716
+ type: "function"
1717
+ },
1718
+ getUserTasks: {
1719
+ inputs: [{ name: "user", type: "address" }],
1720
+ name: "getUserTasks",
1721
+ outputs: [{ name: "", type: "uint256[]" }],
1722
+ stateMutability: "view",
1723
+ type: "function"
1724
+ }
1725
+ };
1726
+ var A2AProtocol = class {
1727
+ address;
1728
+ publicClient;
1729
+ walletClient;
1730
+ constructor(config) {
1731
+ this.address = config.contractAddress;
1732
+ this.publicClient = config.publicClient;
1733
+ this.walletClient = config.walletClient;
1734
+ }
1735
+ get account() {
1736
+ return this.walletClient.getAddresses().then((a) => {
1737
+ if (!a[0]) throw new Error("Wallet not connected");
1738
+ return a[0];
1739
+ });
1740
+ }
1741
+ // ── Agent Card ──────────────────────────────────────────────────────────
1742
+ async createAgentCard(agentId, card) {
1743
+ const acct = await this.account;
1744
+ const { request } = await this.publicClient.simulateContract({
1745
+ account: acct,
1746
+ address: this.address,
1747
+ abi: [A2A_ABI.createAgentCard],
1748
+ functionName: "createAgentCard",
1749
+ args: [
1750
+ BigInt(agentId),
1751
+ card.name,
1752
+ card.description,
1753
+ card.version,
1754
+ card.capabilities,
1755
+ card.supportedTasks,
1756
+ card.commProtocol ?? "a2a",
1757
+ card.authMethod ?? "ecdsa",
1758
+ card.cardURI ?? ""
1759
+ ]
1760
+ });
1761
+ const hash = await this.walletClient.writeContract(request);
1762
+ const receipt = await this.publicClient.waitForTransactionReceipt({ hash });
1763
+ const cardId = this._parseUintFromLog(receipt, "AgentCardCreated");
1764
+ return { cardId, txHash: hash };
1765
+ }
1766
+ async getAgentCard(agentId) {
1767
+ const r = await this.publicClient.readContract({
1768
+ address: this.address,
1769
+ abi: [A2A_ABI.getAgentCard],
1770
+ functionName: "getAgentCard",
1771
+ args: [BigInt(agentId)]
1772
+ });
1773
+ const [, aId, name, , , capabilities, supportedTasks, , , , isActive] = r;
1774
+ if (!isActive) return null;
1775
+ return {
1776
+ agentId: Number(aId),
1777
+ name,
1778
+ capabilities,
1779
+ supportedTasks,
1780
+ endpoint: "",
1781
+ publicKey: ""
1782
+ };
1783
+ }
1784
+ // ── Task ────────────────────────────────────────────────────────────────
1785
+ async createTask(agentId, taskType, input) {
1786
+ const acct = await this.account;
1787
+ const inputStr = JSON.stringify(input);
1788
+ const { request } = await this.publicClient.simulateContract({
1789
+ account: acct,
1790
+ address: this.address,
1791
+ abi: [A2A_ABI.createTask],
1792
+ functionName: "createTask",
1793
+ args: [BigInt(agentId), taskType, inputStr]
1794
+ });
1795
+ const hash = await this.walletClient.writeContract(request);
1796
+ const receipt = await this.publicClient.waitForTransactionReceipt({ hash });
1797
+ const taskId = this._parseUintFromLog(receipt, "TaskCreated");
1798
+ return { taskId, txHash: hash };
1799
+ }
1800
+ async completeTask(taskId, output) {
1801
+ const acct = await this.account;
1802
+ const outputStr = typeof output === "string" ? output : JSON.stringify(output);
1803
+ const { request } = await this.publicClient.simulateContract({
1804
+ account: acct,
1805
+ address: this.address,
1806
+ abi: [A2A_ABI.completeTask],
1807
+ functionName: "completeTask",
1808
+ args: [BigInt(taskId), outputStr]
1809
+ });
1810
+ return this.walletClient.writeContract(request);
1811
+ }
1812
+ async getTask(taskId) {
1813
+ const r = await this.publicClient.readContract({
1814
+ address: this.address,
1815
+ abi: [A2A_ABI.getTask],
1816
+ functionName: "getTask",
1817
+ args: [BigInt(taskId)]
1818
+ });
1819
+ const [, aId, taskType, inputData, outputData, status, client, createdAt, completedAt] = r;
1820
+ const statusMap = ["created", "accepted", "in_progress", "completed", "failed"];
1821
+ return {
1822
+ taskId,
1823
+ creator: client,
1824
+ targetAgentId: Number(aId),
1825
+ taskType,
1826
+ input: inputData,
1827
+ status: statusMap[Number(status)] ?? "created",
1828
+ result: outputData,
1829
+ createdAt: Number(createdAt),
1830
+ completedAt: completedAt > 0n ? Number(completedAt) : void 0
1831
+ };
1832
+ }
1833
+ async getUserTasks(user) {
1834
+ const r = await this.publicClient.readContract({
1835
+ address: this.address,
1836
+ abi: [A2A_ABI.getUserTasks],
1837
+ functionName: "getUserTasks",
1838
+ args: [user]
1839
+ });
1840
+ return r.map(Number);
1841
+ }
1842
+ // ── Helpers ─────────────────────────────────────────────────────────────
1843
+ _parseUintFromLog(receipt, _eventName) {
1844
+ for (const log of receipt.logs) {
1845
+ if (log.topics.length >= 2) {
1846
+ try {
1847
+ return Number(BigInt(log.topics[1]));
1848
+ } catch {
1849
+ }
1850
+ }
1851
+ if (log.data && log.data !== "0x") {
1852
+ try {
1853
+ return Number(BigInt(log.data));
1854
+ } catch {
1855
+ }
1856
+ }
1857
+ }
1858
+ return 0;
1859
+ }
1860
+ };
1861
+
1862
+ // src/a2a/index.ts
1863
+ var A2A_VERSION = "0.1.0";
1864
+
1865
+ // src/mcp/connector.ts
1866
+ var MCPConnector = class _MCPConnector {
1867
+ config;
1868
+ constructor(config) {
1869
+ this.config = { timeoutMs: 3e4, transport: "http", ...config };
1870
+ }
1871
+ /** Create from an Agent's McpConnection. */
1872
+ static fromAgent(mcp, opts) {
1873
+ return new _MCPConnector({
1874
+ url: mcp.url ?? "",
1875
+ transport: mcp.type === "sse" ? "sse" : "http",
1876
+ authHeader: mcp.authHeader,
1877
+ ...opts
1878
+ });
1879
+ }
1880
+ // ── Tool Discovery ───────────────────────────────────────────────────────
1881
+ /** List available tools from the MCP server. */
1882
+ async listTools() {
1883
+ const res = await this._request("tools/list", {});
1884
+ return res.tools ?? [];
1885
+ }
1886
+ // ── Tool Execution ───────────────────────────────────────────────────────
1887
+ /** Call a tool on the MCP server. */
1888
+ async callTool(name, args = {}) {
1889
+ return this._request("tools/call", { name, arguments: args });
1890
+ }
1891
+ // ── Resources (optional) ─────────────────────────────────────────────────
1892
+ async listResources() {
1893
+ const res = await this._request("resources/list", {});
1894
+ return res.resources ?? [];
1895
+ }
1896
+ async readResource(uri) {
1897
+ return this._request("resources/read", { uri });
1898
+ }
1899
+ // ── Internal ─────────────────────────────────────────────────────────────
1900
+ async _request(method, params) {
1901
+ const headers = {
1902
+ "Content-Type": "application/json"
1903
+ };
1904
+ if (this.config.authHeader) {
1905
+ headers["Authorization"] = this.config.authHeader;
1906
+ }
1907
+ if (this.config.subscriberAddress) {
1908
+ headers["X-Subscriber-Address"] = this.config.subscriberAddress;
1909
+ }
1910
+ if (this.config.signature) {
1911
+ headers["X-Signature"] = this.config.signature;
1912
+ }
1913
+ if (this.config.timestamp) {
1914
+ headers["X-Timestamp"] = String(this.config.timestamp);
1915
+ }
1916
+ const res = await fetch(this.config.url, {
1917
+ method: "POST",
1918
+ headers,
1919
+ body: JSON.stringify({
1920
+ jsonrpc: "2.0",
1921
+ id: Date.now(),
1922
+ method,
1923
+ params
1924
+ }),
1925
+ signal: AbortSignal.timeout(this.config.timeoutMs ?? 3e4)
1926
+ });
1927
+ if (!res.ok) {
1928
+ throw new Error(`MCP request failed: HTTP ${res.status}`);
1929
+ }
1930
+ const data = await res.json();
1931
+ if (data.error) {
1932
+ throw new Error(`MCP error: ${data.error.message}`);
1933
+ }
1934
+ return data.result ?? {};
1935
+ }
1936
+ };
1937
+
1938
+ // src/mcp/index.ts
1939
+ var MCP_VERSION = "0.1.0";
1940
+
1941
+ // src/reputation/reputation.ts
1942
+ var REPUTATION_ABI = {
1943
+ rateAgent: {
1944
+ inputs: [
1945
+ { name: "agentId", type: "uint256" },
1946
+ { name: "rating", type: "uint8" },
1947
+ { name: "comment", type: "string" }
1948
+ ],
1949
+ name: "rateAgent",
1950
+ outputs: [],
1951
+ stateMutability: "nonpayable",
1952
+ type: "function"
1953
+ },
1954
+ getRating: {
1955
+ inputs: [{ name: "agentId", type: "uint256" }],
1956
+ name: "getRating",
1957
+ outputs: [
1958
+ { name: "averageRating", type: "uint256" },
1959
+ { name: "totalRatings", type: "uint256" }
1960
+ ],
1961
+ stateMutability: "view",
1962
+ type: "function"
1963
+ },
1964
+ getReviews: {
1965
+ inputs: [{ name: "agentId", type: "uint256" }],
1966
+ name: "getReviews",
1967
+ outputs: [
1968
+ {
1969
+ name: "",
1970
+ type: "tuple[]",
1971
+ components: [
1972
+ { name: "reviewer", type: "address" },
1973
+ { name: "rating", type: "uint8" },
1974
+ { name: "comment", type: "string" },
1975
+ { name: "timestamp", type: "uint256" }
1976
+ ]
1977
+ }
1978
+ ],
1979
+ stateMutability: "view",
1980
+ type: "function"
1981
+ }
1982
+ };
1983
+ var ReputationRegistry = class {
1984
+ address;
1985
+ publicClient;
1986
+ walletClient;
1987
+ constructor(config) {
1988
+ this.address = config.contractAddress;
1989
+ this.publicClient = config.publicClient;
1990
+ this.walletClient = config.walletClient;
1991
+ }
1992
+ get account() {
1993
+ return this.walletClient.getAddresses().then((a) => {
1994
+ if (!a[0]) throw new Error("Wallet not connected");
1995
+ return a[0];
1996
+ });
1997
+ }
1998
+ /** Submit a rating (1-5) with optional comment. */
1999
+ async rate(agentId, rating, comment = "") {
2000
+ if (rating < 1 || rating > 5) throw new Error("Rating must be 1-5");
2001
+ const acct = await this.account;
2002
+ const { request } = await this.publicClient.simulateContract({
2003
+ account: acct,
2004
+ address: this.address,
2005
+ abi: [REPUTATION_ABI.rateAgent],
2006
+ functionName: "rateAgent",
2007
+ args: [BigInt(agentId), rating, comment]
2008
+ });
2009
+ return this.walletClient.writeContract(request);
2010
+ }
2011
+ /** Get average rating and total count. */
2012
+ async getRating(agentId) {
2013
+ const r = await this.publicClient.readContract({
2014
+ address: this.address,
2015
+ abi: [REPUTATION_ABI.getRating],
2016
+ functionName: "getRating",
2017
+ args: [BigInt(agentId)]
2018
+ });
2019
+ const [avg, total] = r;
2020
+ return { averageRating: Number(avg), totalRatings: Number(total) };
2021
+ }
2022
+ /** Get all reviews for an agent. */
2023
+ async getReviews(agentId) {
2024
+ const r = await this.publicClient.readContract({
2025
+ address: this.address,
2026
+ abi: [REPUTATION_ABI.getReviews],
2027
+ functionName: "getReviews",
2028
+ args: [BigInt(agentId)]
2029
+ });
2030
+ return r.map((x) => ({
2031
+ reviewer: x.reviewer,
2032
+ rating: x.rating,
2033
+ comment: x.comment,
2034
+ timestamp: Number(x.timestamp)
2035
+ }));
2036
+ }
2037
+ /** Get full reputation summary. */
2038
+ async getReputation(agentId) {
2039
+ const [rating, reviews] = await Promise.all([
2040
+ this.getRating(agentId),
2041
+ this.getReviews(agentId)
2042
+ ]);
2043
+ return { agentId, ...rating, reviews };
2044
+ }
2045
+ };
2046
+
2047
+ // src/reputation/index.ts
2048
+ var REPUTATION_VERSION = "0.1.0";
2049
+
2050
+ // src/config/config.ts
2051
+ var CONFIG_ABI = {
2052
+ setConfig: {
2053
+ inputs: [{ name: "key", type: "string" }, { name: "value", type: "bytes" }],
2054
+ name: "setConfig",
2055
+ outputs: [],
2056
+ stateMutability: "nonpayable",
2057
+ type: "function"
2058
+ },
2059
+ getConfig: {
2060
+ inputs: [{ name: "key", type: "string" }],
2061
+ name: "getConfig",
2062
+ outputs: [{ name: "", type: "bytes" }],
2063
+ stateMutability: "view",
2064
+ type: "function"
2065
+ },
2066
+ getAllConfig: {
2067
+ inputs: [],
2068
+ name: "getAllConfig",
2069
+ outputs: [{ name: "", type: "tuple[]", components: [{ name: "key", type: "string" }, { name: "value", type: "bytes" }] }],
2070
+ stateMutability: "view",
2071
+ type: "function"
2072
+ }
2073
+ };
2074
+ var KNOWN_CHAINS = {
2075
+ // Sepolia Testnet
2076
+ // v3 (deployed 2026-07-13): platformFee=250bps(2.5%), ReentrancyGuard, audit fixes
2077
+ 11155111: {
2078
+ chainId: 11155111,
2079
+ contracts: {
2080
+ identityRegistry: "0xe94ad380d3F8d08a7590eda0C84f354a93F96e5F",
2081
+ subscriptionManager: "0xC15fE80b9d800abb72121F353a6ae6d6E9077E63",
2082
+ paymentGateway: "0x0000000000000000000000000000000000000000",
2083
+ a2aProtocolRegistry: "0x0000000000000000000000000000000000000000",
2084
+ reputationRegistry: "0x0000000000000000000000000000000000000000",
2085
+ configurationRegistry: "0x0000000000000000000000000000000000000000"
2086
+ },
2087
+ ipfsGateways: ["ipfs.io", "gateway.pinata.cloud", "dweb.link", "cf-ipfs.com"]
2088
+ },
2089
+ // OxaChain L1 Mainnet
2090
+ // Chain ID 19505, Clique PoA, Shanghai+Cancun, gas token T0x
2091
+ // Deployer: 0x8E869A0624fF9e766Df71b5B08897d00E4d260ba
2092
+ // RPC: http://43.156.99.215:18545
2093
+ // Explorer: http://43.156.99.215:18400
2094
+ 19505: {
2095
+ chainId: 19505,
2096
+ contracts: {
2097
+ identityRegistry: "0x0292af212Ce34bbCd95BbC69F4F8c9f7ae123902",
2098
+ subscriptionManager: "0x37BA9DdfE66Aa86f920a34Ae0ae268342151E249",
2099
+ paymentGateway: "0x0000000000000000000000000000000000000000",
2100
+ a2aProtocolRegistry: "0x0000000000000000000000000000000000000000",
2101
+ reputationRegistry: "0x0000000000000000000000000000000000000000",
2102
+ configurationRegistry: "0x0000000000000000000000000000000000000000"
2103
+ },
2104
+ ipfsGateways: ["ipfs.io", "gateway.pinata.cloud", "dweb.link", "cf-ipfs.com"],
2105
+ rpcUrl: "http://43.156.99.215:18545"
2106
+ }
2107
+ };
2108
+ var ConfigurationRegistry = class {
2109
+ address;
2110
+ publicClient;
2111
+ walletClient;
2112
+ constructor(opts) {
2113
+ this.address = opts.contractAddress;
2114
+ this.publicClient = opts.publicClient;
2115
+ this.walletClient = opts.walletClient;
2116
+ }
2117
+ get account() {
2118
+ return this.walletClient.getAddresses().then((a) => {
2119
+ if (!a[0]) throw new Error("Wallet not connected");
2120
+ return a[0];
2121
+ });
2122
+ }
2123
+ async set(key, value) {
2124
+ const acct = await this.account;
2125
+ const { request } = await this.publicClient.simulateContract({
2126
+ account: acct,
2127
+ address: this.address,
2128
+ abi: [CONFIG_ABI.setConfig],
2129
+ functionName: "setConfig",
2130
+ args: [key, stringToHex(value)]
2131
+ });
2132
+ return this.walletClient.writeContract(request);
2133
+ }
2134
+ async get(key) {
2135
+ const r = await this.publicClient.readContract({
2136
+ address: this.address,
2137
+ abi: [CONFIG_ABI.getConfig],
2138
+ functionName: "getConfig",
2139
+ args: [key]
2140
+ });
2141
+ return hexToString(r);
2142
+ }
2143
+ async getAll() {
2144
+ const r = await this.publicClient.readContract({
2145
+ address: this.address,
2146
+ abi: [CONFIG_ABI.getAllConfig],
2147
+ functionName: "getAllConfig"
2148
+ });
2149
+ const map = {};
2150
+ for (const { key, value } of r) {
2151
+ map[key] = hexToString(value);
2152
+ }
2153
+ return map;
2154
+ }
2155
+ };
2156
+
2157
+ // src/config/index.ts
2158
+ var CONFIG_VERSION = "0.1.0";
2159
+
2160
+ // src/react/useAgentRunner.ts
2161
+ import { useState, useEffect, useRef } from "react";
2162
+ import { usePublicClient, useWalletClient } from "wagmi";
2163
+ var IDENTITY_REGISTRY_ABI2 = [
2164
+ // getAgentMetadata returns MetadataEntry[] with key+value strings
2165
+ {
2166
+ name: "getAgentMetadata",
2167
+ type: "function",
2168
+ stateMutability: "view",
2169
+ inputs: [{ name: "agentId", type: "uint256" }],
2170
+ outputs: [
2171
+ {
2172
+ name: "",
2173
+ type: "tuple[]",
2174
+ components: [
2175
+ { name: "key", type: "string" },
2176
+ { name: "value", type: "bytes" }
2177
+ ]
2178
+ }
2179
+ ]
2180
+ }
2181
+ ];
2182
+ var SUBSCRIPTION_MANAGER_ABI = [
2183
+ {
2184
+ name: "hasActiveSubscription",
2185
+ type: "function",
2186
+ stateMutability: "view",
2187
+ inputs: [
2188
+ { name: "subscriber", type: "address" },
2189
+ { name: "agentId", type: "uint256" }
2190
+ ],
2191
+ outputs: [{ name: "", type: "bool" }]
2192
+ }
2193
+ ];
2194
+ var ViemOnChainReader = class {
2195
+ constructor(publicClient, chainConfig) {
2196
+ this.publicClient = publicClient;
2197
+ this.chainConfig = chainConfig;
2198
+ }
2199
+ publicClient;
2200
+ chainConfig;
2201
+ async getTokenURI(_agentId) {
2202
+ return "";
2203
+ }
2204
+ async getAttributes(agentId) {
2205
+ if (!this.publicClient) throw new Error("Public client not available");
2206
+ const entries = await this.publicClient.readContract({
2207
+ address: this.chainConfig.contracts.identityRegistry,
2208
+ abi: IDENTITY_REGISTRY_ABI2,
2209
+ functionName: "getAgentMetadata",
2210
+ args: [BigInt(agentId)]
2211
+ });
2212
+ const attrs = {};
2213
+ for (const entry of entries) {
2214
+ const hexStr = entry.value;
2215
+ if (hexStr && hexStr !== "0x") {
2216
+ attrs[entry.key] = hexToStringUTF8(hexStr);
2217
+ } else {
2218
+ attrs[entry.key] = "";
2219
+ }
2220
+ }
2221
+ return attrs;
2222
+ }
2223
+ async hasActiveSubscription(address, agentId) {
2224
+ if (!this.publicClient) return false;
2225
+ try {
2226
+ return await this.publicClient.readContract({
2227
+ address: this.chainConfig.contracts.subscriptionManager,
2228
+ abi: SUBSCRIPTION_MANAGER_ABI,
2229
+ functionName: "hasActiveSubscription",
2230
+ args: [address, BigInt(agentId)]
2231
+ });
2232
+ } catch {
2233
+ return false;
2234
+ }
2235
+ }
2236
+ };
2237
+ function hexToStringUTF8(hex) {
2238
+ if (!hex.startsWith("0x")) return hex;
2239
+ const hexClean = hex.slice(2);
2240
+ if (hexClean.length === 0) return "";
2241
+ try {
2242
+ const bytes = new Uint8Array(hexClean.length / 2);
2243
+ for (let i = 0; i < bytes.length; i++) {
2244
+ bytes[i] = parseInt(hexClean.substring(i * 2, i * 2 + 2), 16);
2245
+ }
2246
+ return new TextDecoder().decode(bytes);
2247
+ } catch {
2248
+ return hex;
2249
+ }
2250
+ }
2251
+ function useAgentRunner(config) {
2252
+ const { agentId, chainConfig: chainConfigOverride, ipfsGateways } = config;
2253
+ const publicClient = usePublicClient();
2254
+ const { data: walletClient } = useWalletClient();
2255
+ const [ctx, setCtx] = useState(null);
2256
+ const [isLoading, setIsLoading] = useState(false);
2257
+ const [error, setError] = useState(null);
2258
+ const [refetchKey, setRefetchKey] = useState(0);
2259
+ const runnerRef = useRef(null);
2260
+ const mountedRef = useRef(true);
2261
+ useEffect(() => {
2262
+ mountedRef.current = true;
2263
+ return () => {
2264
+ mountedRef.current = false;
2265
+ };
2266
+ }, []);
2267
+ useEffect(() => {
2268
+ if (!publicClient || !walletClient) {
2269
+ setError(new Error("Wallet not connected"));
2270
+ return;
2271
+ }
2272
+ const chainConfig = chainConfigOverride ?? (publicClient.chain?.id ? KNOWN_CHAINS[publicClient.chain.id] : void 0);
2273
+ if (!chainConfig) {
2274
+ setError(new Error(`Chain ${publicClient.chain?.id} not supported`));
2275
+ return;
2276
+ }
2277
+ const reader = new ViemOnChainReader(publicClient, chainConfig);
2278
+ const signer = {
2279
+ async signMessage(message) {
2280
+ if (!walletClient.account) throw new Error("Wallet not connected");
2281
+ return walletClient.signMessage({ account: walletClient.account, message });
2282
+ },
2283
+ async getAddress() {
2284
+ if (!walletClient.account) throw new Error("Wallet not connected");
2285
+ return walletClient.account.address;
2286
+ },
2287
+ async getPrivateKey() {
2288
+ throw new Error(
2289
+ 'Private key not available via wagmi. Use window.ethereum.request({ method: "eth_private_key" }) or inject getPrivateKey via custom WalletSigner.'
2290
+ );
2291
+ }
2292
+ };
2293
+ const ipfsFetcher = new IPFSFetcher({
2294
+ fallbackGateways: ipfsGateways ?? chainConfig.ipfsGateways ?? [
2295
+ "gateway.pinata.cloud",
2296
+ "dweb.link",
2297
+ "cf-ipfs.com"
2298
+ ]
2299
+ });
2300
+ runnerRef.current = new AgentRunner({
2301
+ reader,
2302
+ wallet: signer,
2303
+ ipfsFetcher
2304
+ });
2305
+ setIsLoading(true);
2306
+ setError(null);
2307
+ runnerRef.current.useAgent(agentId).then((result) => {
2308
+ if (mountedRef.current) {
2309
+ setCtx(result);
2310
+ setIsLoading(false);
2311
+ }
2312
+ }).catch((err) => {
2313
+ if (mountedRef.current) {
2314
+ setError(err instanceof Error ? err : new Error(String(err)));
2315
+ setIsLoading(false);
2316
+ }
2317
+ });
2318
+ return () => {
2319
+ mountedRef.current = false;
2320
+ };
2321
+ }, [agentId, publicClient?.chain?.id, publicClient, walletClient, refetchKey]);
2322
+ const refetch = () => setRefetchKey((k) => k + 1);
2323
+ return { ctx, isLoading, error, refetch };
2324
+ }
2325
+ export {
2326
+ A2AProtocol,
2327
+ A2A_VERSION,
2328
+ AgentRegistry,
2329
+ AgentRunner,
2330
+ AgentX402,
2331
+ AgentXError,
2332
+ AgentXErrorCode,
2333
+ CONFIG_VERSION,
2334
+ ConfigurationRegistry,
2335
+ IPFSFetcher,
2336
+ KNOWN_CHAINS,
2337
+ MCPConnector,
2338
+ MCP_VERSION,
2339
+ REGISTRY_VERSION,
2340
+ REPUTATION_VERSION,
2341
+ ReputationRegistry,
2342
+ SUBSCRIPTION_VERSION,
2343
+ SubscriptionManager,
2344
+ aesDecrypt,
2345
+ aesEncrypt,
2346
+ bytesToHex,
2347
+ cidFromURI,
2348
+ decryptPayload,
2349
+ defaultIPFSFetcher,
2350
+ eciesDecrypt,
2351
+ eciesEncrypt,
2352
+ encryptPayload,
2353
+ generateAesKey,
2354
+ generateKeyPair,
2355
+ getPublicKey,
2356
+ guardSubscription,
2357
+ hexToBytes,
2358
+ packAgentForPublish,
2359
+ randomBytes,
2360
+ unpackAgent,
2361
+ useAgentRunner
2362
+ };
2363
+ //# sourceMappingURL=index.mjs.map