@arcdot/agent 0.1.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.
package/dist/index.js ADDED
@@ -0,0 +1,633 @@
1
+ // src/constants.ts
2
+ var ARC_CHAIN_ID = 5042;
3
+ var ARC_RPC_URL_DEFAULT = "https://rpc.mainnet.arc.io";
4
+ var ARC_EXPLORER = "https://explorer.arc.io";
5
+ var GATEWAY_FEE_WEI_DEFAULT = 10000000000000000n;
6
+
7
+ // src/wallet/store.ts
8
+ import { mkdirSync, readFileSync, writeFileSync, existsSync, chmodSync } from "fs";
9
+ import { homedir } from "os";
10
+ import { join } from "path";
11
+ import { generatePrivateKey, privateKeyToAccount } from "viem/accounts";
12
+ function walletDir() {
13
+ return process.env.ARCDOT_HOME?.trim() || join(homedir(), ".arcdot");
14
+ }
15
+ function walletPath() {
16
+ return join(walletDir(), "wallet.json");
17
+ }
18
+ function isHexKey(key) {
19
+ return /^0x[a-fA-F0-9]{64}$/.test(key);
20
+ }
21
+ function resolvePrivateKey() {
22
+ const fromEnv = process.env.ARCDOT_PRIVATE_KEY?.trim() || process.env.AGENT_PRIVATE_KEY?.trim();
23
+ if (fromEnv) {
24
+ if (!isHexKey(fromEnv)) {
25
+ throw new Error(
26
+ "ARCDOT_PRIVATE_KEY / AGENT_PRIVATE_KEY must be a 0x-prefixed 32-byte hex key."
27
+ );
28
+ }
29
+ return fromEnv;
30
+ }
31
+ const stored = loadWallet();
32
+ if (!stored) {
33
+ throw new Error(
34
+ "No agent wallet found. Run: npx @arcdot/agent wallet create"
35
+ );
36
+ }
37
+ return stored.privateKey;
38
+ }
39
+ function loadWallet() {
40
+ const path = walletPath();
41
+ if (!existsSync(path)) return null;
42
+ const raw = JSON.parse(readFileSync(path, "utf8"));
43
+ if (!raw.address || !isHexKey(raw.privateKey)) {
44
+ throw new Error(`Corrupt wallet file at ${path}`);
45
+ }
46
+ return raw;
47
+ }
48
+ function createWallet(opts) {
49
+ const path = walletPath();
50
+ if (existsSync(path) && !opts?.force) {
51
+ throw new Error(
52
+ `Wallet already exists at ${path}. Pass --force to overwrite, or use wallet address.`
53
+ );
54
+ }
55
+ mkdirSync(walletDir(), { recursive: true });
56
+ const privateKey = generatePrivateKey();
57
+ const account = privateKeyToAccount(privateKey);
58
+ const wallet = {
59
+ address: account.address,
60
+ privateKey,
61
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
62
+ };
63
+ writeFileSync(path, JSON.stringify(wallet, null, 2) + "\n", {
64
+ encoding: "utf8",
65
+ mode: 384
66
+ });
67
+ try {
68
+ chmodSync(path, 384);
69
+ } catch {
70
+ }
71
+ return wallet;
72
+ }
73
+ function walletAccountFromKey(privateKey) {
74
+ return privateKeyToAccount(privateKey);
75
+ }
76
+
77
+ // src/settle/pay.ts
78
+ import {
79
+ createPublicClient,
80
+ createWalletClient,
81
+ formatEther,
82
+ http
83
+ } from "viem";
84
+ import { privateKeyToAccount as privateKeyToAccount2 } from "viem/accounts";
85
+
86
+ // src/arc/chain.ts
87
+ import { defineChain } from "viem";
88
+ function resolveRpcUrl(override) {
89
+ return override || process.env.ARC_RPC_URL || process.env.NEXT_PUBLIC_ARC_RPC_URL || ARC_RPC_URL_DEFAULT;
90
+ }
91
+ function arcMainnet(rpcUrl) {
92
+ return defineChain({
93
+ id: ARC_CHAIN_ID,
94
+ name: "Arc",
95
+ nativeCurrency: { name: "USDC", symbol: "USDC", decimals: 18 },
96
+ rpcUrls: {
97
+ default: { http: [resolveRpcUrl(rpcUrl)] }
98
+ },
99
+ blockExplorers: {
100
+ default: { name: "Arc Explorer", url: ARC_EXPLORER }
101
+ }
102
+ });
103
+ }
104
+ var promptGatewayAbi = [
105
+ {
106
+ type: "function",
107
+ name: "depositPayment",
108
+ stateMutability: "payable",
109
+ inputs: [
110
+ { name: "paymentId", type: "bytes32" },
111
+ { name: "seller", type: "address" }
112
+ ],
113
+ outputs: []
114
+ },
115
+ {
116
+ type: "function",
117
+ name: "minFee",
118
+ stateMutability: "view",
119
+ inputs: [],
120
+ outputs: [{ name: "", type: "uint256" }]
121
+ }
122
+ ];
123
+
124
+ // src/auth/challenge.ts
125
+ import { keccak256, stringToBytes } from "viem";
126
+ function hashGatewayInput(input) {
127
+ return keccak256(stringToBytes(JSON.stringify(input ?? null)));
128
+ }
129
+ function buildAuthChallenge(msg) {
130
+ return [
131
+ "arcdot.gateway",
132
+ `chainId:${msg.chainId}`,
133
+ `gateway:${msg.gateway.toLowerCase()}`,
134
+ `txHash:${msg.txHash.toLowerCase()}`,
135
+ `feeWei:${msg.feeWei}`,
136
+ `service:${msg.service}`,
137
+ `inputHash:${msg.inputHash.toLowerCase()}`,
138
+ `issuedAt:${msg.issuedAt}`,
139
+ `expiresAt:${msg.expiresAt}`
140
+ ].join("\n");
141
+ }
142
+ function buildGatewayAuthMessage(params) {
143
+ return {
144
+ domain: "arcdot.gateway",
145
+ chainId: ARC_CHAIN_ID,
146
+ gateway: params.gateway,
147
+ txHash: params.txHash,
148
+ feeWei: params.feeWei.toString(),
149
+ service: params.service,
150
+ inputHash: hashGatewayInput(params.input),
151
+ issuedAt: params.issuedAt,
152
+ expiresAt: params.expiresAt
153
+ };
154
+ }
155
+
156
+ // src/settle/paymentId.ts
157
+ import { encodeAbiParameters, keccak256 as keccak2562 } from "viem";
158
+ function makePaymentId(params) {
159
+ return keccak2562(
160
+ encodeAbiParameters(
161
+ [
162
+ { type: "address" },
163
+ { type: "string" },
164
+ { type: "uint256" }
165
+ ],
166
+ [params.payer, params.service, BigInt(params.nonce)]
167
+ )
168
+ );
169
+ }
170
+
171
+ // src/settle/pay.ts
172
+ async function settlePayment(params) {
173
+ const account = privateKeyToAccount2(params.privateKey);
174
+ const chain = arcMainnet(params.rpcUrl);
175
+ const rpcUrl = resolveRpcUrl(params.rpcUrl);
176
+ const publicClient = createPublicClient({
177
+ chain,
178
+ transport: http(rpcUrl)
179
+ });
180
+ const walletClient = createWalletClient({
181
+ account,
182
+ chain,
183
+ transport: http(rpcUrl)
184
+ });
185
+ const paymentId = makePaymentId({
186
+ payer: account.address,
187
+ service: params.service,
188
+ nonce: Date.now()
189
+ });
190
+ const txHash = await walletClient.writeContract({
191
+ address: params.gateway,
192
+ abi: promptGatewayAbi,
193
+ functionName: "depositPayment",
194
+ args: [paymentId, params.seller],
195
+ value: params.feeWei,
196
+ chain,
197
+ account
198
+ });
199
+ await publicClient.waitForTransactionReceipt({ hash: txHash });
200
+ const now = Math.floor(Date.now() / 1e3);
201
+ const authMessage = buildGatewayAuthMessage({
202
+ gateway: params.gateway,
203
+ txHash,
204
+ feeWei: params.feeWei,
205
+ service: params.service,
206
+ input: params.input,
207
+ issuedAt: now,
208
+ expiresAt: now + 120
209
+ });
210
+ const signature = await walletClient.signMessage({
211
+ account,
212
+ message: buildAuthChallenge(authMessage)
213
+ });
214
+ return {
215
+ paymentId,
216
+ feeWei: params.feeWei,
217
+ proof: {
218
+ txHash,
219
+ address: account.address,
220
+ signature,
221
+ issuedAt: now,
222
+ expiresAt: now + 120
223
+ }
224
+ };
225
+ }
226
+ async function getNativeBalance(address, rpcUrl) {
227
+ const publicClient = createPublicClient({
228
+ chain: arcMainnet(rpcUrl),
229
+ transport: http(resolveRpcUrl(rpcUrl))
230
+ });
231
+ const wei = await publicClient.getBalance({ address });
232
+ return { wei, formatted: formatEther(wei) };
233
+ }
234
+
235
+ // src/client/paymentParse.ts
236
+ function isGateway402Body(value) {
237
+ if (!value || typeof value !== "object") return false;
238
+ const v = value;
239
+ if (v.ok !== false || v.status !== 402) return false;
240
+ const err = v.error;
241
+ if (!err || typeof err !== "object") return false;
242
+ return Boolean(err.payment);
243
+ }
244
+ function parsePaymentRequired(body) {
245
+ if (!isGateway402Body(body)) return null;
246
+ const payment = body.error.payment;
247
+ if (!payment?.gateway || !payment.feeWei) return null;
248
+ return payment;
249
+ }
250
+ function parseMcpPaymentNeeded(toolResult) {
251
+ const text = extractMcpText(toolResult);
252
+ if (!text) return null;
253
+ let parsed;
254
+ try {
255
+ parsed = JSON.parse(text);
256
+ } catch {
257
+ return null;
258
+ }
259
+ if (!parsed || typeof parsed !== "object") return null;
260
+ const obj = parsed;
261
+ const err = obj.error;
262
+ if (obj.status === 402 || err?.code === "PAYMENT_REQUIRED") {
263
+ const payment = err?.payment;
264
+ if (!payment?.gateway || !payment.feeWei) return null;
265
+ const slug = err?.service?.slug || (typeof obj.service === "string" ? obj.service : "") || "";
266
+ return { payment, serviceSlug: slug, raw: parsed };
267
+ }
268
+ return null;
269
+ }
270
+ function extractMcpText(toolResult) {
271
+ if (!toolResult || typeof toolResult !== "object") return null;
272
+ const r = toolResult;
273
+ if (Array.isArray(r.content)) {
274
+ const texts = r.content.filter((c) => c?.type === "text" && typeof c.text === "string").map((c) => c.text);
275
+ if (texts.length) return texts.join("\n");
276
+ }
277
+ if (typeof toolResult.text === "string") {
278
+ return toolResult.text;
279
+ }
280
+ return null;
281
+ }
282
+ function paymentDepositArgs(payment) {
283
+ if (!payment.seller) {
284
+ throw new Error("Payment instructions missing seller address");
285
+ }
286
+ return {
287
+ feeWei: BigInt(payment.feeWei),
288
+ seller: payment.seller,
289
+ gateway: payment.gateway
290
+ };
291
+ }
292
+
293
+ // src/client/gateway.ts
294
+ async function fetchService(origin, slug) {
295
+ const res = await fetch(new URL(`/api/services/${slug}`, origin));
296
+ const json = await res.json();
297
+ if (!res.ok || !json.service) {
298
+ throw new Error(json.error || `Service not found: ${slug}`);
299
+ }
300
+ const sellerRaw = json.service.seller || json.service.owner_address;
301
+ if (!sellerRaw || !/^0x[a-fA-F0-9]{40}$/.test(sellerRaw)) {
302
+ throw new Error("Service is missing a valid seller address");
303
+ }
304
+ return {
305
+ slug: json.service.slug,
306
+ price_wei: json.service.price_wei,
307
+ seller: sellerRaw,
308
+ title: json.service.title
309
+ };
310
+ }
311
+ async function resolveGateway(origin, override) {
312
+ if (override && override.length === 42) return override;
313
+ if (process.env.ARCDOT_GATEWAY?.startsWith("0x")) {
314
+ return process.env.ARCDOT_GATEWAY;
315
+ }
316
+ const res = await fetch(new URL("/api/services", origin));
317
+ const json = await res.json();
318
+ if (json.gateway && json.gateway.length === 42) {
319
+ return json.gateway;
320
+ }
321
+ throw new Error(
322
+ "Gateway address not configured on host. Set ARCDOT_GATEWAY or deploy PromptGateway."
323
+ );
324
+ }
325
+ async function postGatewayPaid(params) {
326
+ const body = {
327
+ service: params.service,
328
+ input: params.input,
329
+ clientRequestId: params.clientRequestId,
330
+ auth: {
331
+ issuedAt: params.proof.issuedAt,
332
+ expiresAt: params.proof.expiresAt
333
+ }
334
+ };
335
+ const res = await fetch(new URL("/api/gateway", params.origin), {
336
+ method: "POST",
337
+ headers: {
338
+ "Content-Type": "application/json",
339
+ "X-Arc-Tx-Hash": params.proof.txHash,
340
+ "X-Arc-Address": params.proof.address,
341
+ "X-Arc-Signature": params.proof.signature
342
+ },
343
+ body: JSON.stringify(body)
344
+ });
345
+ const json = await res.json();
346
+ if (res.status === 200 && json?.ok === true) {
347
+ return { ok: true, status: 200, body: json };
348
+ }
349
+ return { ok: false, status: res.status, body: json };
350
+ }
351
+ async function unlockWithAutoSettle(params) {
352
+ const privateKey = params.privateKey ?? resolvePrivateKey();
353
+ const origin = params.origin.replace(/\/$/, "");
354
+ const probe = await fetch(new URL("/api/gateway", origin), {
355
+ method: "POST",
356
+ headers: { "Content-Type": "application/json" },
357
+ body: JSON.stringify({
358
+ service: params.service,
359
+ input: params.input,
360
+ clientRequestId: params.clientRequestId
361
+ })
362
+ });
363
+ const probeJson = await probe.json();
364
+ if (probe.status === 200 && probeJson?.ok === true) {
365
+ return {
366
+ gateway: { ok: true, status: 200, body: probeJson },
367
+ settled: false
368
+ };
369
+ }
370
+ const payment = parsePaymentRequired(probeJson);
371
+ const service = await fetchService(origin, params.service);
372
+ const gatewayAddr = params.gateway || (payment ? payment.gateway : await resolveGateway(origin));
373
+ let feeWei = BigInt(service.price_wei);
374
+ let seller = service.seller;
375
+ if (payment) {
376
+ const args = paymentDepositArgs(payment);
377
+ feeWei = args.feeWei;
378
+ seller = args.seller;
379
+ }
380
+ if (feeWei <= 0n) feeWei = GATEWAY_FEE_WEI_DEFAULT;
381
+ const settled = await settlePayment({
382
+ privateKey,
383
+ gateway: gatewayAddr,
384
+ seller,
385
+ service: params.service,
386
+ feeWei,
387
+ input: params.input,
388
+ rpcUrl: params.rpcUrl
389
+ });
390
+ const gateway = await postGatewayPaid({
391
+ origin,
392
+ service: params.service,
393
+ input: params.input,
394
+ proof: settled.proof,
395
+ feeWei: settled.feeWei,
396
+ clientRequestId: params.clientRequestId
397
+ });
398
+ return {
399
+ gateway,
400
+ txHash: settled.proof.txHash,
401
+ paymentId: settled.paymentId,
402
+ settled: true
403
+ };
404
+ }
405
+
406
+ // src/mcp/toolNames.ts
407
+ function toolNameForSlug(slug) {
408
+ return `arcdot_${slug.replace(/-/g, "_")}`;
409
+ }
410
+ function slugFromToolName(name) {
411
+ if (!name.startsWith("arcdot_")) return null;
412
+ if (name === "arcdot_catalog" || name === "arcdot_health") return null;
413
+ return name.slice("arcdot_".length).replace(/_/g, "-");
414
+ }
415
+
416
+ // src/client/mcp.ts
417
+ async function mcpRpc(origin, method, params, id = 1) {
418
+ const endpoint = new URL("/api/mcp", origin.replace(/\/$/, ""));
419
+ const res = await fetch(endpoint, {
420
+ method: "POST",
421
+ headers: { "Content-Type": "application/json" },
422
+ body: JSON.stringify({
423
+ jsonrpc: "2.0",
424
+ id,
425
+ method,
426
+ params: params ?? {}
427
+ })
428
+ });
429
+ return await res.json();
430
+ }
431
+ async function callMcpToolWithAutoSettle(params) {
432
+ const origin = params.origin.replace(/\/$/, "");
433
+ const args = { ...params.arguments ?? {} };
434
+ const first = await mcpRpc(origin, "tools/call", {
435
+ name: params.name,
436
+ arguments: args
437
+ });
438
+ if (first.error) return first;
439
+ const needed = parseMcpPaymentNeeded(first.result);
440
+ if (!needed) return first;
441
+ const privateKey = params.privateKey ?? resolvePrivateKey();
442
+ const deposit = paymentDepositArgs(needed.payment);
443
+ const slug = needed.serviceSlug || slugFromToolName(params.name) || String(args.service ?? "");
444
+ if (!slug) {
445
+ throw new Error(
446
+ `Cannot settle: missing service slug for tool ${params.name}`
447
+ );
448
+ }
449
+ const input = {
450
+ prompt: typeof args.prompt === "string" ? args.prompt : JSON.stringify(args)
451
+ };
452
+ const gateway = params.gateway || deposit.gateway || await resolveGateway(origin);
453
+ const settled = await settlePayment({
454
+ privateKey,
455
+ gateway,
456
+ seller: deposit.seller,
457
+ service: slug,
458
+ feeWei: deposit.feeWei,
459
+ input,
460
+ rpcUrl: params.rpcUrl
461
+ });
462
+ const retryArgs = {
463
+ ...args,
464
+ payment: {
465
+ txHash: settled.proof.txHash,
466
+ address: settled.proof.address,
467
+ signature: settled.proof.signature,
468
+ issuedAt: settled.proof.issuedAt,
469
+ expiresAt: settled.proof.expiresAt
470
+ }
471
+ };
472
+ return mcpRpc(origin, "tools/call", {
473
+ name: params.name,
474
+ arguments: retryArgs
475
+ }, 2);
476
+ }
477
+
478
+ // src/createAgent.ts
479
+ async function createArcdotAgent(options) {
480
+ const origin = options.origin.replace(/\/$/, "");
481
+ const privateKey = options.privateKey ?? resolvePrivateKey();
482
+ return {
483
+ origin,
484
+ async unlock(params) {
485
+ return unlockWithAutoSettle({
486
+ origin,
487
+ service: params.service,
488
+ input: params.input,
489
+ privateKey,
490
+ rpcUrl: options.rpcUrl,
491
+ gateway: options.gateway,
492
+ clientRequestId: params.clientRequestId
493
+ });
494
+ },
495
+ async callMcpTool(name, args) {
496
+ const res = await callMcpToolWithAutoSettle({
497
+ origin,
498
+ name,
499
+ arguments: args,
500
+ privateKey,
501
+ rpcUrl: options.rpcUrl,
502
+ gateway: options.gateway
503
+ });
504
+ if (res.error) {
505
+ throw new Error(res.error.message);
506
+ }
507
+ return res.result;
508
+ },
509
+ async listMcpTools() {
510
+ const res = await mcpRpc(origin, "tools/list");
511
+ if (res.error) throw new Error(res.error.message);
512
+ return res.result;
513
+ }
514
+ };
515
+ }
516
+
517
+ // src/mcp/proxy.ts
518
+ import { createInterface } from "readline";
519
+ function write(msg) {
520
+ process.stdout.write(JSON.stringify(msg) + "\n");
521
+ }
522
+ function ok(id, result) {
523
+ write({ jsonrpc: "2.0", id: id ?? null, result });
524
+ }
525
+ function fail(id, code, message) {
526
+ write({
527
+ jsonrpc: "2.0",
528
+ id: id ?? null,
529
+ error: { code, message }
530
+ });
531
+ }
532
+ async function runMcpProxy(origin) {
533
+ const base = origin.replace(/\/$/, "");
534
+ const rl = createInterface({ input: process.stdin, crlfDelay: Infinity });
535
+ console.error(`[arcdot] MCP proxy \u2192 ${base}/api/mcp`);
536
+ for await (const line of rl) {
537
+ const trimmed = line.trim();
538
+ if (!trimmed) continue;
539
+ let msg;
540
+ try {
541
+ msg = JSON.parse(trimmed);
542
+ } catch {
543
+ fail(null, -32700, "Parse error");
544
+ continue;
545
+ }
546
+ const id = msg.id;
547
+ const method = msg.method;
548
+ if (method === "notifications/initialized" || id === void 0) {
549
+ if (method && method.startsWith("notifications/")) continue;
550
+ }
551
+ try {
552
+ if (method === "initialize") {
553
+ const remote = await mcpRpc(base, "initialize", msg.params);
554
+ if (remote.error) {
555
+ fail(id, remote.error.code, remote.error.message);
556
+ } else {
557
+ const result = remote.result;
558
+ ok(id, result ?? {
559
+ protocolVersion: "2024-11-05",
560
+ capabilities: { tools: {} },
561
+ serverInfo: { name: "arcdot-proxy", version: "0.1.0" }
562
+ });
563
+ }
564
+ continue;
565
+ }
566
+ if (method === "ping") {
567
+ ok(id, {});
568
+ continue;
569
+ }
570
+ if (method === "tools/list") {
571
+ const remote = await mcpRpc(base, "tools/list", msg.params);
572
+ if (remote.error) fail(id, remote.error.code, remote.error.message);
573
+ else ok(id, remote.result);
574
+ continue;
575
+ }
576
+ if (method === "tools/call") {
577
+ const p = msg.params;
578
+ if (!p?.name) {
579
+ fail(id, -32602, "tools/call requires params.name");
580
+ continue;
581
+ }
582
+ const remote = await callMcpToolWithAutoSettle({
583
+ origin: base,
584
+ name: p.name,
585
+ arguments: p.arguments
586
+ });
587
+ if (remote.error) fail(id, remote.error.code, remote.error.message);
588
+ else ok(id, remote.result);
589
+ continue;
590
+ }
591
+ if (method) {
592
+ const remote = await mcpRpc(base, method, msg.params);
593
+ if (remote.error) fail(id, remote.error.code, remote.error.message);
594
+ else ok(id, remote.result);
595
+ continue;
596
+ }
597
+ fail(id, -32600, "Invalid Request");
598
+ } catch (err) {
599
+ fail(
600
+ id,
601
+ -32e3,
602
+ err instanceof Error ? err.message : "Proxy error"
603
+ );
604
+ }
605
+ }
606
+ }
607
+ export {
608
+ ARC_CHAIN_ID,
609
+ ARC_RPC_URL_DEFAULT,
610
+ GATEWAY_FEE_WEI_DEFAULT,
611
+ callMcpToolWithAutoSettle,
612
+ createArcdotAgent,
613
+ createWallet,
614
+ fetchService,
615
+ getNativeBalance,
616
+ isGateway402Body,
617
+ loadWallet,
618
+ makePaymentId,
619
+ mcpRpc,
620
+ parseMcpPaymentNeeded,
621
+ parsePaymentRequired,
622
+ paymentDepositArgs,
623
+ resolveGateway,
624
+ resolvePrivateKey,
625
+ runMcpProxy,
626
+ settlePayment,
627
+ slugFromToolName,
628
+ toolNameForSlug,
629
+ unlockWithAutoSettle,
630
+ walletAccountFromKey,
631
+ walletPath
632
+ };
633
+ //# sourceMappingURL=index.js.map