@conto_finance/create-conto-agent 0.1.1 → 0.3.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.
@@ -1,777 +0,0 @@
1
- import {
2
- printBanner,
3
- printError,
4
- printInfo,
5
- printSuccess
6
- } from "./chunk-6TRDZ4JG.js";
7
- import {
8
- saveGlobalConfig,
9
- writeContoConfig,
10
- writeEnvLocal
11
- } from "./chunk-NK52PCTE.js";
12
-
13
- // src/commands/init.ts
14
- import * as p from "@clack/prompts";
15
- import chalk from "chalk";
16
- import fs from "fs";
17
- import path from "path";
18
-
19
- // src/lib/chains.ts
20
- var FALLBACK_CHAINS = {
21
- "4217": {
22
- name: "Tempo",
23
- shortName: "Tempo",
24
- chainId: "4217",
25
- rpcUrl: "https://rpc.tempo.xyz",
26
- explorerUrl: "https://explore.tempo.xyz",
27
- explorerName: "Tempo Explorer",
28
- currency: "pathUSD",
29
- chainType: "EVM",
30
- custodyType: "SPONGE",
31
- spongeChainId: "tempo-mainnet",
32
- testnet: false,
33
- isDefault: false,
34
- faucetAvailable: false,
35
- stablecoins: [
36
- {
37
- symbol: "pathUSD",
38
- name: "Path USD",
39
- address: "0x20c0000000000000000000000000000000000000",
40
- decimals: 6
41
- }
42
- ]
43
- },
44
- "42431": {
45
- name: "Tempo Testnet",
46
- shortName: "Tempo Testnet",
47
- chainId: "42431",
48
- rpcUrl: "https://rpc.moderato.tempo.xyz",
49
- explorerUrl: "https://explore.moderato.tempo.xyz",
50
- explorerName: "Tempo Explorer",
51
- currency: "pathUSD",
52
- chainType: "EVM",
53
- custodyType: "SPONGE",
54
- spongeChainId: "tempo",
55
- testnet: true,
56
- isDefault: true,
57
- faucetAvailable: true,
58
- stablecoins: [
59
- {
60
- symbol: "pathUSD",
61
- name: "Path USD",
62
- address: "0x20c0000000000000000000000000000000000000",
63
- decimals: 6
64
- }
65
- ]
66
- }
67
- };
68
- var DEFAULT_FALLBACK_CHAIN_ID = "4217";
69
- var cachedChains = null;
70
- var cachedDefaultChainId = null;
71
- async function fetchChains(baseUrl) {
72
- if (cachedChains) {
73
- return { chains: cachedChains, defaultChainId: cachedDefaultChainId };
74
- }
75
- try {
76
- const res = await fetch(`${baseUrl.replace(/\/$/, "")}/api/chains`, {
77
- signal: AbortSignal.timeout(5e3)
78
- });
79
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
80
- const data = await res.json();
81
- const chains = {};
82
- for (const c of data.chains) {
83
- chains[c.id] = {
84
- name: c.name,
85
- shortName: c.shortName,
86
- chainId: c.id,
87
- rpcUrl: c.rpcUrl,
88
- explorerUrl: c.explorerUrl,
89
- explorerName: c.explorerName,
90
- currency: c.currency,
91
- chainType: c.type,
92
- custodyType: "SPONGE",
93
- // Default; server doesn't dictate custody
94
- spongeChainId: c.spongeChainId,
95
- testnet: c.isTestnet,
96
- isDefault: c.isDefault,
97
- faucetAvailable: c.faucetAvailable,
98
- iconUrl: c.iconUrl,
99
- stablecoins: c.stablecoins
100
- };
101
- }
102
- cachedChains = chains;
103
- cachedDefaultChainId = data.defaultChainId;
104
- return { chains, defaultChainId: data.defaultChainId };
105
- } catch {
106
- cachedChains = FALLBACK_CHAINS;
107
- cachedDefaultChainId = DEFAULT_FALLBACK_CHAIN_ID;
108
- return { chains: FALLBACK_CHAINS, defaultChainId: DEFAULT_FALLBACK_CHAIN_ID };
109
- }
110
- }
111
- function getChain(chainId) {
112
- return cachedChains?.[chainId] || FALLBACK_CHAINS[chainId];
113
- }
114
- function getChainChoices(chains) {
115
- const entries = Object.entries(chains);
116
- entries.sort(([, a], [, b]) => {
117
- if (a.chainId === "4217") return -1;
118
- if (b.chainId === "4217") return 1;
119
- if (!a.testnet && b.testnet) return -1;
120
- if (a.testnet && !b.testnet) return 1;
121
- if (a.chainId === "42431") return -1;
122
- if (b.chainId === "42431") return 1;
123
- return a.name.localeCompare(b.name);
124
- });
125
- return entries.map(([id, chain], i) => ({
126
- value: id,
127
- label: i === 0 ? `${chain.name} (recommended)` : chain.name,
128
- hint: chainHint(chain)
129
- }));
130
- }
131
- function chainHint(chain) {
132
- if (chain.chainId === "4217") return "Stablecoin-native, fast, low fees";
133
- if (chain.testnet) return `Testnet \u2014 free ${chain.currency}, no real funds`;
134
- return `${chain.chainType} \u2014 ${chain.currency}`;
135
- }
136
-
137
- // src/lib/api-client.ts
138
- var ApiClient = class {
139
- baseUrl;
140
- apiKey;
141
- orgApiKey;
142
- constructor(options) {
143
- this.baseUrl = options.baseUrl.replace(/\/$/, "");
144
- this.apiKey = options.apiKey;
145
- this.orgApiKey = options.orgApiKey;
146
- }
147
- async request(method, path2, options) {
148
- const url = `${this.baseUrl}${path2}`;
149
- const authType = options?.auth || "sdk";
150
- const token = authType === "org" ? this.orgApiKey : this.apiKey;
151
- const headers = {
152
- "Content-Type": "application/json",
153
- "User-Agent": "create-conto-agent/0.1.0"
154
- };
155
- if (token) {
156
- headers["Authorization"] = `Bearer ${token}`;
157
- }
158
- const response = await fetch(url, {
159
- method,
160
- headers,
161
- body: options?.body ? JSON.stringify(options.body) : void 0
162
- });
163
- const contentType = response.headers.get("content-type") || "";
164
- if (!contentType.includes("application/json")) {
165
- const error = new Error(
166
- response.status === 404 ? `API endpoint not found: ${path2}` : `API returned non-JSON response (${response.status})`
167
- );
168
- error.code = response.status === 404 ? "NOT_FOUND" : "INVALID_RESPONSE";
169
- error.status = response.status;
170
- throw error;
171
- }
172
- const data = await response.json();
173
- if (!response.ok) {
174
- const error = new Error(data.error || `API request failed: ${response.status}`);
175
- error.code = data.code || "API_ERROR";
176
- error.status = response.status;
177
- throw error;
178
- }
179
- return data;
180
- }
181
- // ── Org-level Admin APIs (used during init) ──
182
- async createWallet(params) {
183
- return this.request("POST", "/api/wallets", { body: params, auth: "org" });
184
- }
185
- async createAgent(params) {
186
- return this.request("POST", "/api/agents", { body: params, auth: "org" });
187
- }
188
- async linkWalletToAgent(agentId, params) {
189
- return this.request("POST", `/api/agents/${agentId}/wallets`, {
190
- body: params,
191
- auth: "org"
192
- });
193
- }
194
- async createPolicy(params) {
195
- return this.request("POST", "/api/policies", { body: params, auth: "org" });
196
- }
197
- async updatePolicy(policyId, params) {
198
- return this.request("PATCH", `/api/policies/${policyId}`, { body: params, auth: "org" });
199
- }
200
- async deletePolicy(policyId) {
201
- return this.request("DELETE", `/api/policies/${policyId}`, { auth: "org" });
202
- }
203
- async addPolicyRule(policyId, rule) {
204
- return this.request(
205
- "POST",
206
- `/api/policies/${policyId}/rules`,
207
- {
208
- body: rule,
209
- auth: "org"
210
- }
211
- );
212
- }
213
- async deletePolicyRule(policyId, ruleId) {
214
- return this.request("DELETE", `/api/policies/${policyId}/rules/${ruleId}`, { auth: "org" });
215
- }
216
- async listOrgPolicies() {
217
- return this.request("GET", "/api/policies", { auth: "org" });
218
- }
219
- async assignPolicyToAgent(agentId, policyId) {
220
- return this.request("POST", `/api/agents/${agentId}/policies`, {
221
- body: { policyId },
222
- auth: "org"
223
- });
224
- }
225
- async unassignPolicyFromAgent(agentId, policyId) {
226
- return this.request("DELETE", `/api/agents/${agentId}/policies?policyId=${policyId}`, {
227
- auth: "org"
228
- });
229
- }
230
- async createSdkKey(agentId, params) {
231
- return this.request("POST", `/api/agents/${agentId}/sdk-keys`, {
232
- body: params,
233
- auth: "org"
234
- });
235
- }
236
- async fundWallet(walletId) {
237
- return this.request("POST", `/api/wallets/${walletId}/faucet`, { auth: "org" });
238
- }
239
- async provisionWallet(walletId) {
240
- return this.request("POST", `/api/wallets/${walletId}/provision`, { auth: "org" });
241
- }
242
- // ── SDK Agent APIs (used by CLI commands) ──
243
- async getAgentInfo() {
244
- const data = await this.request("GET", "/api/sdk/agents/me");
245
- return {
246
- agent: {
247
- id: data.id,
248
- name: data.name,
249
- agentType: data.agentType,
250
- status: data.status,
251
- createdAt: data.createdAt
252
- },
253
- organization: { name: data.organizationId },
254
- walletCount: data.summary?.walletCount ?? 0,
255
- summary: data.summary
256
- };
257
- }
258
- async getWallets() {
259
- return this.request("GET", "/api/sdk/wallets");
260
- }
261
- async getSpendingLimits() {
262
- const data = await this.request("GET", "/api/sdk/spending-limits");
263
- return {
264
- limits: (data.wallets || []).map((w) => ({
265
- walletId: w.walletId,
266
- walletName: w.name,
267
- daily: {
268
- limit: w.limits?.daily ?? 0,
269
- spent: w.spent?.today ?? 0,
270
- remaining: w.remaining?.daily ?? 0
271
- },
272
- weekly: w.limits?.weekly ? {
273
- limit: w.limits.weekly,
274
- spent: w.spent?.thisWeek ?? 0,
275
- remaining: w.remaining?.weekly ?? 0
276
- } : void 0,
277
- monthly: w.limits?.monthly ? {
278
- limit: w.limits.monthly,
279
- spent: w.spent?.thisMonth ?? 0,
280
- remaining: w.remaining?.monthly ?? 0
281
- } : void 0,
282
- perTransaction: w.limits?.perTransaction ?? 0
283
- }))
284
- };
285
- }
286
- async requestPayment(params) {
287
- return this.request("POST", "/api/sdk/payments/request", { body: params });
288
- }
289
- async executePayment(requestId) {
290
- return this.request("POST", `/api/sdk/payments/${requestId}/execute`, { body: {} });
291
- }
292
- async getPaymentStatus(requestId) {
293
- return this.request("GET", `/api/sdk/payments/${requestId}`);
294
- }
295
- async getTransactions(params) {
296
- const query = new URLSearchParams();
297
- if (params?.limit) query.set("limit", String(params.limit));
298
- if (params?.status) query.set("status", params.status);
299
- const qs = query.toString() ? `?${query.toString()}` : "";
300
- return this.request("GET", `/api/sdk/transactions${qs}`);
301
- }
302
- async getTransaction(id) {
303
- return this.request("GET", `/api/sdk/transactions/${id}`);
304
- }
305
- async getPolicies() {
306
- return this.request("GET", "/api/sdk/policies");
307
- }
308
- async getAlerts(params) {
309
- const query = new URLSearchParams();
310
- if (params?.status) query.set("status", params.status);
311
- const qs = query.toString() ? `?${query.toString()}` : "";
312
- return this.request("GET", `/api/sdk/alerts${qs}`);
313
- }
314
- async getAnalytics() {
315
- return this.request("GET", "/api/sdk/analytics");
316
- }
317
- };
318
- function createApiClient(options) {
319
- return new ApiClient(options);
320
- }
321
-
322
- // src/lib/auth.ts
323
- import http from "http";
324
- import open from "open";
325
- async function browserAuth(baseUrl) {
326
- return new Promise((resolve, reject) => {
327
- const server = http.createServer((req, res) => {
328
- if (!req.url?.startsWith("/callback")) {
329
- res.writeHead(404);
330
- res.end();
331
- return;
332
- }
333
- const url = new URL(req.url, `http://localhost`);
334
- const orgApiKey = url.searchParams.get("token");
335
- const organizationName = url.searchParams.get("org") || "";
336
- const userId = url.searchParams.get("userId") || "";
337
- const error = url.searchParams.get("error");
338
- if (error) {
339
- res.writeHead(200, { "Content-Type": "text/html" });
340
- res.end(getErrorHtml(error));
341
- server.close();
342
- reject(new Error(`Authentication failed: ${error}`));
343
- return;
344
- }
345
- if (!orgApiKey) {
346
- res.writeHead(200, { "Content-Type": "text/html" });
347
- res.end(getErrorHtml("No token received"));
348
- server.close();
349
- reject(new Error("No authentication token received"));
350
- return;
351
- }
352
- res.writeHead(200, { "Content-Type": "text/html" });
353
- res.end(getSuccessHtml());
354
- server.close();
355
- resolve({ orgApiKey, organizationName, userId });
356
- });
357
- server.listen(0, "127.0.0.1", () => {
358
- const address = server.address();
359
- if (!address || typeof address === "string") {
360
- reject(new Error("Failed to start local auth server"));
361
- return;
362
- }
363
- const callbackUrl = `http://127.0.0.1:${address.port}/callback`;
364
- const authUrl = `${baseUrl}/cli-auth?callback=${encodeURIComponent(callbackUrl)}`;
365
- open(authUrl).catch(() => {
366
- });
367
- });
368
- setTimeout(
369
- () => {
370
- server.close();
371
- reject(new Error("Authentication timed out. Please try again."));
372
- },
373
- 5 * 60 * 1e3
374
- );
375
- });
376
- }
377
- function getSuccessHtml() {
378
- return `<!DOCTYPE html>
379
- <html>
380
- <head><title>Conto CLI - Authenticated</title></head>
381
- <body style="font-family: system-ui, sans-serif; display: flex; justify-content: center; align-items: center; min-height: 100vh; margin: 0; background: #0a0a0a; color: #fafafa;">
382
- <div style="text-align: center;">
383
- <h1 style="color: #22c55e;">Authenticated</h1>
384
- <p>You can close this window and return to the terminal.</p>
385
- </div>
386
- </body>
387
- </html>`;
388
- }
389
- function getErrorHtml(error) {
390
- return `<!DOCTYPE html>
391
- <html>
392
- <head><title>Conto CLI - Error</title></head>
393
- <body style="font-family: system-ui, sans-serif; display: flex; justify-content: center; align-items: center; min-height: 100vh; margin: 0; background: #0a0a0a; color: #fafafa;">
394
- <div style="text-align: center;">
395
- <h1 style="color: #ef4444;">Authentication Failed</h1>
396
- <p>${error}</p>
397
- <p>Please return to the terminal and try again.</p>
398
- </div>
399
- </body>
400
- </html>`;
401
- }
402
-
403
- // src/commands/init.ts
404
- async function runInit(options = {}) {
405
- printBanner();
406
- let baseUrl = options.baseUrl || "";
407
- if (!baseUrl) {
408
- const setupMode = await p.select({
409
- message: "Choose setup mode",
410
- options: [
411
- { value: "hosted", label: "Quick start", hint: "hosted on conto.finance" },
412
- { value: "self-hosted", label: "Self-hosted", hint: "connect to your own instance" }
413
- ]
414
- });
415
- if (p.isCancel(setupMode)) {
416
- p.cancel("Setup cancelled.");
417
- process.exit(0);
418
- }
419
- if (setupMode === "self-hosted") {
420
- const customUrl = await p.text({
421
- message: "Conto instance URL",
422
- placeholder: "https://conto.your-company.com",
423
- validate: (v) => {
424
- try {
425
- new URL(v);
426
- return void 0;
427
- } catch {
428
- return "Please enter a valid URL";
429
- }
430
- }
431
- });
432
- if (p.isCancel(customUrl)) {
433
- p.cancel("Setup cancelled.");
434
- process.exit(0);
435
- }
436
- baseUrl = customUrl;
437
- } else {
438
- baseUrl = "https://conto.finance";
439
- }
440
- }
441
- const agentName = options.name || await p.text({
442
- message: "Agent name",
443
- placeholder: "my-procurement-bot",
444
- validate: (v) => v.length < 2 ? "Name must be at least 2 characters" : void 0
445
- });
446
- if (p.isCancel(agentName)) {
447
- p.cancel("Setup cancelled.");
448
- process.exit(0);
449
- }
450
- const agentType = options.type || await p.select({
451
- message: "Agent type",
452
- options: [
453
- { value: "ANTHROPIC_CLAUDE", label: "Claude" },
454
- { value: "OPENAI_ASSISTANT", label: "OpenAI" },
455
- { value: "LANGCHAIN", label: "LangChain" },
456
- { value: "AUTOGPT", label: "AutoGPT" },
457
- { value: "CUSTOM", label: "Custom" }
458
- ]
459
- });
460
- if (p.isCancel(agentType)) {
461
- p.cancel("Setup cancelled.");
462
- process.exit(0);
463
- }
464
- const dailyLimit = options.limit || await p.text({
465
- message: "Daily spending limit (USD)",
466
- placeholder: "500",
467
- initialValue: "500",
468
- validate: (v) => {
469
- const n = Number(v);
470
- if (isNaN(n) || n <= 0) return "Enter a positive number";
471
- return void 0;
472
- }
473
- });
474
- if (p.isCancel(dailyLimit)) {
475
- p.cancel("Setup cancelled.");
476
- process.exit(0);
477
- }
478
- const s0 = p.spinner();
479
- s0.start("Fetching supported networks...");
480
- const { chains: availableChains, defaultChainId } = await fetchChains(baseUrl);
481
- s0.stop(`Found ${Object.keys(availableChains).length} networks`);
482
- const chainChoices = getChainChoices(availableChains);
483
- const selectedChain = options.chain || await p.select({
484
- message: "Network",
485
- options: chainChoices
486
- });
487
- if (p.isCancel(selectedChain)) {
488
- p.cancel("Setup cancelled.");
489
- process.exit(0);
490
- }
491
- const chain = availableChains[selectedChain] || availableChains[defaultChainId];
492
- const limit = typeof dailyLimit === "string" ? Number(dailyLimit) : dailyLimit;
493
- const s = p.spinner();
494
- s.start("Opening browser to authenticate...");
495
- let orgApiKey;
496
- let organizationName;
497
- try {
498
- const authResult = await browserAuth(baseUrl);
499
- orgApiKey = authResult.orgApiKey;
500
- organizationName = authResult.organizationName;
501
- s.stop("Authenticated");
502
- printSuccess("Account connected");
503
- } catch (err) {
504
- s.stop("Authentication failed");
505
- printError(err instanceof Error ? err.message : "Authentication failed");
506
- process.exit(1);
507
- }
508
- const api = new ApiClient({ baseUrl, orgApiKey });
509
- s.start(`Provisioning wallet on ${chain.name}...`);
510
- let wallet;
511
- try {
512
- const walletResult = await api.createWallet({
513
- name: `${agentName} Wallet`,
514
- chainType: chain.chainType,
515
- chainId: chain.chainId,
516
- custodyType: chain.custodyType
517
- });
518
- wallet = walletResult;
519
- s.stop(`Wallet provisioned on ${chain.name}`);
520
- printSuccess(`Wallet: ${wallet.address}`);
521
- } catch (err) {
522
- s.stop("Wallet creation failed");
523
- printError(err instanceof Error ? err.message : "Failed to create wallet");
524
- process.exit(1);
525
- }
526
- if (chain.faucetAvailable) {
527
- s.start("Requesting testnet funds from faucet...");
528
- try {
529
- const faucetResult = await api.fundWallet(wallet.id);
530
- s.stop("Wallet funded");
531
- printSuccess(`Funded with ${faucetResult.balance ?? 100} ${chain.currency} (testnet)`);
532
- } catch (err) {
533
- s.stop("Faucet request failed (you can fund manually)");
534
- printInfo(err instanceof Error ? err.message : "Faucet unavailable");
535
- }
536
- }
537
- s.start(`Registering agent "${agentName}"...`);
538
- let agent;
539
- try {
540
- agent = await api.createAgent({
541
- name: agentName,
542
- agentType,
543
- description: `Created via CLI quickstart`
544
- });
545
- s.stop("Agent registered");
546
- printSuccess(`Agent "${agent.name}" created`);
547
- } catch (err) {
548
- s.stop("Agent creation failed");
549
- printError(err instanceof Error ? err.message : "Failed to create agent");
550
- process.exit(1);
551
- }
552
- s.start("Linking wallet to agent...");
553
- try {
554
- await api.linkWalletToAgent(agent.id, {
555
- walletId: wallet.id,
556
- delegationType: "FULL",
557
- spendLimitDaily: limit,
558
- spendLimitPerTx: Math.min(limit, 1e3)
559
- });
560
- s.stop("Wallet linked");
561
- printSuccess(`Wallet linked ($${limit}/day limit)`);
562
- } catch (err) {
563
- s.stop("Wallet linking failed");
564
- printError(err instanceof Error ? err.message : "Failed to link wallet");
565
- process.exit(1);
566
- }
567
- s.start("Creating default spending policy...");
568
- try {
569
- const policy = await api.createPolicy({
570
- name: `${agentName} - Daily Limit`,
571
- policyType: "SPEND_LIMIT",
572
- priority: 50,
573
- isActive: true,
574
- rules: [
575
- {
576
- ruleType: "DAILY_LIMIT",
577
- operator: "LESS_THAN_OR_EQUAL",
578
- value: String(limit),
579
- action: "ALLOW"
580
- }
581
- ],
582
- agentIds: [agent.id]
583
- });
584
- s.stop("Policy created");
585
- printSuccess("Default spending policy applied");
586
- } catch (err) {
587
- s.stop("Policy creation failed (continuing without policy)");
588
- printInfo("You can create policies later in the dashboard");
589
- }
590
- s.start("Generating SDK key...");
591
- let sdkKey;
592
- try {
593
- sdkKey = await api.createSdkKey(agent.id, {
594
- name: "CLI Quickstart Key",
595
- keyType: "standard"
596
- });
597
- s.stop("SDK key generated");
598
- printSuccess("SDK key created");
599
- } catch (err) {
600
- s.stop("SDK key generation failed");
601
- printError(err instanceof Error ? err.message : "Failed to create SDK key");
602
- process.exit(1);
603
- }
604
- const cwd = process.cwd();
605
- writeEnvLocal(cwd, {
606
- "# Conto Agent Configuration": "",
607
- "# Generated by: npx create-conto-agent": "",
608
- "": "",
609
- "# SDK Authentication": "",
610
- CONTO_API_KEY: sdkKey.key,
611
- CONTO_BASE_URL: baseUrl,
612
- "# ": "",
613
- "# Agent Identity": "",
614
- CONTO_AGENT_ID: agent.id,
615
- CONTO_AGENT_NAME: agent.name,
616
- "# 2": "",
617
- [`# Network: ${chain.name}${chain.testnet ? " (testnet)" : ""}`]: "",
618
- CONTO_CHAIN_ID: chain.chainId,
619
- CONTO_CHAIN_NAME: chain.name,
620
- CONTO_RPC_URL: chain.rpcUrl,
621
- CONTO_EXPLORER_URL: chain.explorerUrl,
622
- CONTO_CURRENCY: chain.currency,
623
- "# 3": "",
624
- "# Wallet": "",
625
- CONTO_WALLET_ID: wallet.id,
626
- CONTO_WALLET_ADDRESS: wallet.address
627
- });
628
- writeContoConfig(cwd, {
629
- agent: {
630
- id: agent.id,
631
- name: agent.name,
632
- type: agentType
633
- },
634
- network: {
635
- chain: selectedChain,
636
- chainId: chain.chainId,
637
- rpcUrl: chain.rpcUrl,
638
- explorerUrl: chain.explorerUrl,
639
- currency: chain.currency,
640
- testnet: chain.testnet
641
- },
642
- wallet: {
643
- id: wallet.id,
644
- address: wallet.address,
645
- custodyType: chain.custodyType
646
- },
647
- server: {
648
- baseUrl
649
- }
650
- });
651
- writeExampleFile(cwd);
652
- saveGlobalConfig({
653
- agent: { id: agent.id, name: agent.name, type: agentType },
654
- network: {
655
- chain: selectedChain,
656
- chainId: chain.chainId,
657
- rpcUrl: chain.rpcUrl,
658
- explorerUrl: chain.explorerUrl,
659
- currency: chain.currency,
660
- testnet: chain.testnet
661
- },
662
- wallet: { id: wallet.id, address: wallet.address, custodyType: chain.custodyType },
663
- server: { baseUrl, apiKey: sdkKey.key, orgApiKey }
664
- });
665
- console.log("");
666
- console.log(chalk.green.bold(" Your agent is ready!") + " Files written:\n");
667
- console.log(` ${chalk.bold(".env.local")} \u2014 SDK key + config`);
668
- console.log(` ${chalk.bold("conto.config.json")} \u2014 Agent metadata`);
669
- console.log(` ${chalk.bold("example.ts")} \u2014 Working payment example`);
670
- console.log("");
671
- console.log(
672
- ` ${chalk.dim("Wallet:")} ${wallet.address} (${chain.name}${chain.testnet ? " testnet" : ""})`
673
- );
674
- console.log(` ${chalk.dim("Currency:")} ${chain.currency}`);
675
- console.log(` ${chalk.dim("Explorer:")} ${chain.explorerUrl}`);
676
- console.log("");
677
- console.log(chalk.bold(" Next steps:"));
678
- if (chain.faucetAvailable) {
679
- console.log(` 1. Run the example: ${chalk.cyan("npx tsx example.ts")}`);
680
- console.log(` 2. Check status: ${chalk.cyan("npx conto status")}`);
681
- console.log(` 3. Make a payment: ${chalk.cyan("npx conto pay <address> <amount>")}`);
682
- } else {
683
- console.log(
684
- ` 1. Fund your wallet with ${chain.currency} ${chalk.dim("\u2192")} ${wallet.address}`
685
- );
686
- console.log(` 2. Run the example: ${chalk.cyan("npx tsx example.ts")}`);
687
- console.log(` 3. Check status: ${chalk.cyan("npx conto status")}`);
688
- }
689
- console.log("");
690
- }
691
- function writeExampleFile(dir) {
692
- const content = `// Load .env.local (Node 20+ built-in, no dependencies needed)
693
- import { readFileSync } from 'fs';
694
- try {
695
- const envFile = readFileSync('.env.local', 'utf-8');
696
- for (const line of envFile.split('\\n')) {
697
- const match = line.match(/^([A-Z_]+)=(.*)$/);
698
- if (match) process.env[match[1]] = match[2];
699
- }
700
- } catch {}
701
-
702
- // Using the Conto SDK for programmatic payment control
703
- // Docs: https://docs.conto.finance
704
-
705
- async function main() {
706
- const apiKey = process.env.CONTO_API_KEY;
707
- const baseUrl = process.env.CONTO_BASE_URL || 'https://conto.finance';
708
-
709
- if (!apiKey) {
710
- console.error('Missing CONTO_API_KEY in .env.local');
711
- process.exit(1);
712
- }
713
-
714
- console.log('Checking agent status...\\n');
715
-
716
- // Get agent info
717
- const infoRes = await fetch(\`\${baseUrl}/api/sdk/agents/me\`, {
718
- headers: { Authorization: \`Bearer \${apiKey}\` },
719
- });
720
- const info = await infoRes.json();
721
- console.log(\`Agent: \${info.name || 'Unknown'}\`);
722
- console.log(\`Status: \${info.status || 'Unknown'}\\n\`);
723
-
724
- // Get wallet balances
725
- const walletsRes = await fetch(\`\${baseUrl}/api/sdk/wallets\`, {
726
- headers: { Authorization: \`Bearer \${apiKey}\` },
727
- });
728
- const { wallets } = await walletsRes.json();
729
- for (const w of wallets || []) {
730
- console.log(\`Wallet: \${w.address}\`);
731
- console.log(\` Balance: \${w.balance}\`);
732
- console.log(\` Daily: \${w.spent?.today || 0}/\${w.limits?.daily || 'unlimited'}\\n\`);
733
- }
734
-
735
- // Request a test payment (policy engine evaluates spending rules)
736
- console.log('Requesting test payment...\\n');
737
- const payRes = await fetch(\`\${baseUrl}/api/sdk/payments/request\`, {
738
- method: 'POST',
739
- headers: {
740
- Authorization: \`Bearer \${apiKey}\`,
741
- 'Content-Type': 'application/json',
742
- },
743
- body: JSON.stringify({
744
- amount: 0.01,
745
- recipientAddress: '0x0000000000000000000000000000000000000001',
746
- purpose: 'Test payment from CLI quickstart',
747
- category: 'TESTING',
748
- }),
749
- });
750
- const request = await payRes.json();
751
-
752
- console.log(\`Policy decision: \${request.status}\`);
753
- console.log(\`Reasons: \${(request.reasons || []).join(', ')}\`);
754
-
755
- if (request.status === 'APPROVED') {
756
- console.log(\`\\nPayment approved! Request ID: \${request.requestId}\`);
757
- console.log('To execute: call POST /api/sdk/payments/{requestId}/execute');
758
- } else if (request.status === 'DENIED') {
759
- const violations = (request.violations || []).map((v: any) => v.message).join(', ');
760
- console.log(\`\\nPayment denied: \${violations}\`);
761
- } else {
762
- console.log('\\nPayment requires manual approval (check dashboard)');
763
- }
764
- }
765
-
766
- main().catch(console.error);
767
- `;
768
- fs.writeFileSync(path.join(dir, "example.ts"), content);
769
- }
770
-
771
- export {
772
- createApiClient,
773
- fetchChains,
774
- getChain,
775
- browserAuth,
776
- runInit
777
- };