@conto_finance/create-conto-agent 0.1.2 → 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.
@@ -0,0 +1,1209 @@
1
+ import {
2
+ isJsonMode,
3
+ printBanner,
4
+ printError,
5
+ printInfo,
6
+ printJson,
7
+ printSuccess,
8
+ printWarning
9
+ } from "./chunk-K4LBO234.js";
10
+ import {
11
+ saveGlobalConfig,
12
+ writeContoConfig,
13
+ writeEnvLocal
14
+ } from "./chunk-OS5PZNRM.js";
15
+
16
+ // package.json
17
+ var package_default = {
18
+ name: "@conto_finance/create-conto-agent",
19
+ version: "0.3.0",
20
+ description: "CLI quickstart for Conto \u2014 Agentic Payments Control Center",
21
+ bin: {
22
+ "create-conto-agent": "bin/create-conto-agent.js",
23
+ conto: "bin/conto.js"
24
+ },
25
+ main: "./dist/index.js",
26
+ type: "module",
27
+ files: [
28
+ "dist",
29
+ "bin"
30
+ ],
31
+ scripts: {
32
+ build: "tsup src/index.ts src/cli.ts --format esm --dts --clean",
33
+ dev: "tsup src/index.ts src/cli.ts --format esm --dts --watch",
34
+ lint: "tsc --noEmit",
35
+ test: "npm run build && node --test test/*.test.mjs"
36
+ },
37
+ engines: {
38
+ node: ">=18"
39
+ },
40
+ keywords: [
41
+ "conto",
42
+ "ai",
43
+ "agent",
44
+ "payments",
45
+ "cli",
46
+ "quickstart",
47
+ "tempo",
48
+ "blockchain"
49
+ ],
50
+ author: "Conto",
51
+ license: "MIT",
52
+ repository: {
53
+ type: "git",
54
+ url: "https://github.com/kwattana/conto.git",
55
+ directory: "packages/cli"
56
+ },
57
+ homepage: "https://conto.finance",
58
+ bugs: {
59
+ url: "https://github.com/kwattana/conto/issues"
60
+ },
61
+ dependencies: {
62
+ "@clack/prompts": "^0.9.1",
63
+ chalk: "^5.4.1",
64
+ "cli-table3": "^0.6.5",
65
+ commander: "^13.1.0",
66
+ open: "^10.1.0"
67
+ },
68
+ overrides: {
69
+ esbuild: "0.28.1"
70
+ },
71
+ devDependencies: {
72
+ "@types/node": "^22.19.18",
73
+ tsup: "^8.5.1",
74
+ typescript: "^5.9.3"
75
+ }
76
+ };
77
+
78
+ // src/lib/package-version.ts
79
+ var CLI_PACKAGE_VERSION = package_default.version || "0.0.0";
80
+
81
+ // src/commands/init.ts
82
+ import * as p from "@clack/prompts";
83
+ import chalk from "chalk";
84
+ import fs from "fs";
85
+ import path from "path";
86
+ import { spawnSync } from "child_process";
87
+
88
+ // src/lib/chains.ts
89
+ var FALLBACK_CHAINS = {
90
+ "4217": {
91
+ name: "Tempo",
92
+ shortName: "Tempo",
93
+ chainId: "4217",
94
+ rpcUrl: "https://rpc.tempo.xyz",
95
+ explorerUrl: "https://explore.tempo.xyz",
96
+ explorerName: "Tempo Explorer",
97
+ currency: "USDC.e",
98
+ chainType: "EVM",
99
+ spongeChainId: "tempo-mainnet",
100
+ testnet: false,
101
+ isDefault: false,
102
+ faucetAvailable: false,
103
+ stablecoins: [
104
+ {
105
+ symbol: "USDC.e",
106
+ name: "Bridged USDC",
107
+ address: "0x20c000000000000000000000b9537d11c60e8b50",
108
+ decimals: 6
109
+ }
110
+ ]
111
+ },
112
+ "42431": {
113
+ name: "Tempo Testnet",
114
+ shortName: "Tempo Testnet",
115
+ chainId: "42431",
116
+ rpcUrl: "https://rpc.moderato.tempo.xyz",
117
+ explorerUrl: "https://explore.moderato.tempo.xyz",
118
+ explorerName: "Tempo Explorer",
119
+ currency: "pathUSD",
120
+ chainType: "EVM",
121
+ spongeChainId: "tempo",
122
+ testnet: true,
123
+ isDefault: true,
124
+ faucetAvailable: true,
125
+ stablecoins: [
126
+ {
127
+ symbol: "pathUSD",
128
+ name: "Path USD",
129
+ address: "0x20c0000000000000000000000000000000000000",
130
+ decimals: 6
131
+ }
132
+ ]
133
+ }
134
+ };
135
+ var DEFAULT_FALLBACK_CHAIN_ID = "4217";
136
+ var cachedChains = null;
137
+ var cachedDefaultChainId = null;
138
+ async function fetchChains(baseUrl) {
139
+ if (cachedChains) {
140
+ return { chains: cachedChains, defaultChainId: cachedDefaultChainId };
141
+ }
142
+ try {
143
+ const res = await fetch(`${baseUrl.replace(/\/$/, "")}/api/chains`, {
144
+ signal: AbortSignal.timeout(5e3)
145
+ });
146
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
147
+ const data = await res.json();
148
+ const chains = {};
149
+ for (const c of data.chains) {
150
+ chains[c.id] = {
151
+ name: c.name,
152
+ shortName: c.shortName,
153
+ chainId: c.id,
154
+ rpcUrl: c.rpcUrl,
155
+ explorerUrl: c.explorerUrl,
156
+ explorerName: c.explorerName,
157
+ currency: c.currency,
158
+ chainType: c.type,
159
+ spongeChainId: c.spongeChainId,
160
+ testnet: c.isTestnet,
161
+ isDefault: c.isDefault,
162
+ faucetAvailable: c.faucetAvailable,
163
+ iconUrl: c.iconUrl,
164
+ stablecoins: c.stablecoins
165
+ };
166
+ }
167
+ cachedChains = chains;
168
+ cachedDefaultChainId = data.defaultChainId;
169
+ return { chains, defaultChainId: data.defaultChainId };
170
+ } catch {
171
+ cachedChains = FALLBACK_CHAINS;
172
+ cachedDefaultChainId = DEFAULT_FALLBACK_CHAIN_ID;
173
+ return { chains: FALLBACK_CHAINS, defaultChainId: DEFAULT_FALLBACK_CHAIN_ID };
174
+ }
175
+ }
176
+ function getChain(chainId) {
177
+ return cachedChains?.[chainId] || FALLBACK_CHAINS[chainId];
178
+ }
179
+ function getChainChoices(chains) {
180
+ const entries = Object.entries(chains);
181
+ entries.sort(([, a], [, b]) => {
182
+ if (a.chainId === "4217") return -1;
183
+ if (b.chainId === "4217") return 1;
184
+ if (!a.testnet && b.testnet) return -1;
185
+ if (a.testnet && !b.testnet) return 1;
186
+ if (a.chainId === "42431") return -1;
187
+ if (b.chainId === "42431") return 1;
188
+ return a.name.localeCompare(b.name);
189
+ });
190
+ return entries.map(([id, chain], i) => ({
191
+ value: id,
192
+ label: i === 0 ? `${chain.name} (recommended)` : chain.name,
193
+ hint: chainHint(chain)
194
+ }));
195
+ }
196
+ function chainHint(chain) {
197
+ if (chain.chainId === "4217") return "Stablecoin-native, fast, low fees";
198
+ if (chain.testnet) return `Testnet \u2014 free ${chain.currency}, no real funds`;
199
+ return `${chain.chainType} \u2014 ${chain.currency}`;
200
+ }
201
+
202
+ // src/lib/api-client.ts
203
+ var ApiClient = class {
204
+ baseUrl;
205
+ apiKey;
206
+ orgApiKey;
207
+ constructor(options) {
208
+ this.baseUrl = options.baseUrl.replace(/\/$/, "");
209
+ this.apiKey = options.apiKey;
210
+ this.orgApiKey = options.orgApiKey;
211
+ }
212
+ async request(method, path2, options) {
213
+ const url = `${this.baseUrl}${path2}`;
214
+ const authType = options?.auth || "sdk";
215
+ const token = authType === "org" ? this.orgApiKey : this.apiKey;
216
+ const headers = {
217
+ "Content-Type": "application/json",
218
+ "User-Agent": `create-conto-agent/${CLI_PACKAGE_VERSION}`
219
+ };
220
+ if (token) {
221
+ headers["Authorization"] = `Bearer ${token}`;
222
+ }
223
+ const response = await fetch(url, {
224
+ method,
225
+ headers,
226
+ body: options?.body ? JSON.stringify(options.body) : void 0
227
+ });
228
+ const contentType = response.headers.get("content-type") || "";
229
+ if (!contentType.includes("application/json")) {
230
+ const error = new Error(
231
+ response.status === 404 ? `API endpoint not found: ${path2}` : `API returned non-JSON response (${response.status})`
232
+ );
233
+ error.code = response.status === 404 ? "NOT_FOUND" : "INVALID_RESPONSE";
234
+ error.status = response.status;
235
+ throw error;
236
+ }
237
+ const data = await response.json();
238
+ if (!response.ok) {
239
+ const error = new Error(data.error || `API request failed: ${response.status}`);
240
+ error.code = data.code || "API_ERROR";
241
+ error.status = response.status;
242
+ throw error;
243
+ }
244
+ return data;
245
+ }
246
+ // ── Org-level Admin APIs (used during init) ──
247
+ async createWallet(params) {
248
+ return this.request("POST", "/api/wallets", { body: params, auth: "org" });
249
+ }
250
+ async createAgent(params) {
251
+ return this.request("POST", "/api/agents", { body: params, auth: "org" });
252
+ }
253
+ async linkWalletToAgent(agentId, params) {
254
+ return this.request("POST", `/api/agents/${agentId}/wallets`, {
255
+ body: params,
256
+ auth: "org"
257
+ });
258
+ }
259
+ async createPolicy(params) {
260
+ return this.request("POST", "/api/policies", { body: params, auth: "org" });
261
+ }
262
+ async updatePolicy(policyId, params) {
263
+ return this.request("PATCH", `/api/policies/${policyId}`, { body: params, auth: "org" });
264
+ }
265
+ async deletePolicy(policyId) {
266
+ return this.request("DELETE", `/api/policies/${policyId}`, { auth: "org" });
267
+ }
268
+ async addPolicyRule(policyId, rule) {
269
+ return this.request(
270
+ "POST",
271
+ `/api/policies/${policyId}/rules`,
272
+ {
273
+ body: rule,
274
+ auth: "org"
275
+ }
276
+ );
277
+ }
278
+ async deletePolicyRule(policyId, ruleId) {
279
+ return this.request("DELETE", `/api/policies/${policyId}/rules/${ruleId}`, { auth: "org" });
280
+ }
281
+ async listOrgPolicies() {
282
+ return this.request("GET", "/api/policies", { auth: "org" });
283
+ }
284
+ async assignPolicyToAgent(agentId, policyId) {
285
+ return this.request("POST", `/api/agents/${agentId}/policies`, {
286
+ body: { policyId },
287
+ auth: "org"
288
+ });
289
+ }
290
+ async unassignPolicyFromAgent(agentId, policyId) {
291
+ return this.request("DELETE", `/api/agents/${agentId}/policies?policyId=${policyId}`, {
292
+ auth: "org"
293
+ });
294
+ }
295
+ async createSdkKey(agentId, params) {
296
+ return this.request("POST", `/api/agents/${agentId}/sdk-keys`, {
297
+ body: params,
298
+ auth: "org"
299
+ });
300
+ }
301
+ async fundWallet(walletId) {
302
+ return this.request("POST", `/api/wallets/${walletId}/faucet`, { auth: "org" });
303
+ }
304
+ async provisionWallet(walletId) {
305
+ return this.request("POST", `/api/wallets/${walletId}/provision`, { auth: "org" });
306
+ }
307
+ // ── SDK Agent APIs (used by CLI commands) ──
308
+ /** GET /api/sdk/setup: full diagnostic snapshot for the authenticated key. */
309
+ async getSetup() {
310
+ return this.request("GET", "/api/sdk/setup");
311
+ }
312
+ async getAgentInfo() {
313
+ const data = await this.request("GET", "/api/sdk/agents/me");
314
+ return {
315
+ agent: {
316
+ id: data.id,
317
+ name: data.name,
318
+ agentType: data.agentType,
319
+ status: data.status,
320
+ createdAt: data.createdAt
321
+ },
322
+ organization: { name: data.organizationId },
323
+ walletCount: data.summary?.walletCount ?? 0,
324
+ summary: data.summary
325
+ };
326
+ }
327
+ async getWallets() {
328
+ return this.request("GET", "/api/sdk/wallets");
329
+ }
330
+ async getSpendingLimits() {
331
+ const data = await this.request("GET", "/api/sdk/spending-limits");
332
+ return {
333
+ limits: (data.wallets || []).map((w) => ({
334
+ walletId: w.walletId,
335
+ walletName: w.name,
336
+ daily: {
337
+ limit: w.limits?.daily ?? 0,
338
+ spent: w.spent?.today ?? 0,
339
+ remaining: w.remaining?.daily ?? 0
340
+ },
341
+ weekly: w.limits?.weekly ? {
342
+ limit: w.limits.weekly,
343
+ spent: w.spent?.thisWeek ?? 0,
344
+ remaining: w.remaining?.weekly ?? 0
345
+ } : void 0,
346
+ monthly: w.limits?.monthly ? {
347
+ limit: w.limits.monthly,
348
+ spent: w.spent?.thisMonth ?? 0,
349
+ remaining: w.remaining?.monthly ?? 0
350
+ } : void 0,
351
+ perTransaction: w.limits?.perTransaction ?? 0
352
+ }))
353
+ };
354
+ }
355
+ async requestPayment(params) {
356
+ return this.request("POST", "/api/sdk/payments/request", { body: params });
357
+ }
358
+ async executePayment(requestId) {
359
+ return this.request("POST", `/api/sdk/payments/${requestId}/execute`, { body: {} });
360
+ }
361
+ async getPaymentStatus(requestId) {
362
+ return this.request("GET", `/api/sdk/payments/${requestId}`);
363
+ }
364
+ async getTransactions(params) {
365
+ const query = new URLSearchParams();
366
+ if (params?.limit) query.set("limit", String(params.limit));
367
+ if (params?.status) query.set("status", params.status);
368
+ const qs = query.toString() ? `?${query.toString()}` : "";
369
+ return this.request("GET", `/api/sdk/transactions${qs}`);
370
+ }
371
+ async getTransaction(id) {
372
+ return this.request("GET", `/api/sdk/transactions/${id}`);
373
+ }
374
+ async getPolicies() {
375
+ return this.request("GET", "/api/sdk/policies");
376
+ }
377
+ async getAlerts(params) {
378
+ const query = new URLSearchParams();
379
+ if (params?.status) query.set("status", params.status);
380
+ const qs = query.toString() ? `?${query.toString()}` : "";
381
+ return this.request("GET", `/api/sdk/alerts${qs}`);
382
+ }
383
+ async getAnalytics() {
384
+ return this.request("GET", "/api/sdk/analytics");
385
+ }
386
+ };
387
+ function createApiClient(options) {
388
+ return new ApiClient(options);
389
+ }
390
+
391
+ // src/lib/auth.ts
392
+ import http from "http";
393
+ import { randomBytes } from "crypto";
394
+ import open from "open";
395
+ var CALLBACK_BODY_LIMIT_BYTES = 16 * 1024;
396
+ async function readRequestBody(req) {
397
+ return new Promise((resolve, reject) => {
398
+ let totalBytes = 0;
399
+ let body = "";
400
+ req.setEncoding("utf8");
401
+ req.on("data", (chunk) => {
402
+ totalBytes += Buffer.byteLength(chunk);
403
+ if (totalBytes > CALLBACK_BODY_LIMIT_BYTES) {
404
+ reject(new Error("Callback payload too large"));
405
+ req.destroy();
406
+ return;
407
+ }
408
+ body += chunk;
409
+ });
410
+ req.on("end", () => resolve(body));
411
+ req.on("error", reject);
412
+ });
413
+ }
414
+ async function parseCallbackPayload(req) {
415
+ const url = new URL(req.url || "/", "http://127.0.0.1");
416
+ let params = url.searchParams;
417
+ if (req.method === "POST") {
418
+ const rawBody = await readRequestBody(req);
419
+ params = new URLSearchParams(rawBody);
420
+ }
421
+ return {
422
+ orgApiKey: params.get("token"),
423
+ organizationName: params.get("org") || "",
424
+ userId: params.get("userId") || "",
425
+ error: params.get("error"),
426
+ returnedState: params.get("state")
427
+ };
428
+ }
429
+ async function browserAuth(baseUrl) {
430
+ return new Promise((resolve, reject) => {
431
+ const state = randomBytes(16).toString("hex");
432
+ const timeout = setTimeout(
433
+ () => {
434
+ server.close();
435
+ reject(new Error("Authentication timed out. Please try again."));
436
+ },
437
+ 5 * 60 * 1e3
438
+ );
439
+ const server = http.createServer((req, res) => {
440
+ void (async () => {
441
+ const url = new URL(req.url || "/", "http://127.0.0.1");
442
+ if (url.pathname !== "/callback") {
443
+ res.writeHead(404);
444
+ res.end();
445
+ return;
446
+ }
447
+ if (req.method !== "GET" && req.method !== "POST") {
448
+ res.writeHead(405, { "Content-Type": "text/html" });
449
+ res.end(getErrorHtml("Unsupported callback method"));
450
+ return;
451
+ }
452
+ const { orgApiKey, organizationName, userId, error, returnedState } = await parseCallbackPayload(req);
453
+ if (returnedState !== state) {
454
+ res.writeHead(400, { "Content-Type": "text/html" });
455
+ res.end(getErrorHtml("Invalid authentication state"));
456
+ return;
457
+ }
458
+ if (error) {
459
+ res.writeHead(200, { "Content-Type": "text/html" });
460
+ res.end(getErrorHtml(error));
461
+ clearTimeout(timeout);
462
+ server.close();
463
+ reject(new Error(`Authentication failed: ${error}`));
464
+ return;
465
+ }
466
+ if (!orgApiKey) {
467
+ res.writeHead(200, { "Content-Type": "text/html" });
468
+ res.end(getErrorHtml("No token received"));
469
+ clearTimeout(timeout);
470
+ server.close();
471
+ reject(new Error("No authentication token received"));
472
+ return;
473
+ }
474
+ res.writeHead(200, { "Content-Type": "text/html" });
475
+ res.end(getSuccessHtml());
476
+ clearTimeout(timeout);
477
+ server.close();
478
+ resolve({ orgApiKey, organizationName, userId });
479
+ })().catch((error) => {
480
+ res.writeHead(500, { "Content-Type": "text/html" });
481
+ res.end(getErrorHtml("Authentication callback failed"));
482
+ clearTimeout(timeout);
483
+ server.close();
484
+ reject(error instanceof Error ? error : new Error(String(error)));
485
+ });
486
+ });
487
+ server.listen(0, "127.0.0.1", () => {
488
+ const address = server.address();
489
+ if (!address || typeof address === "string") {
490
+ clearTimeout(timeout);
491
+ reject(new Error("Failed to start local auth server"));
492
+ return;
493
+ }
494
+ const callbackUrl = `http://127.0.0.1:${address.port}/callback`;
495
+ const authUrl = `${baseUrl}/cli-auth?callback=${encodeURIComponent(callbackUrl)}&state=${encodeURIComponent(state)}`;
496
+ open(authUrl).catch(() => {
497
+ });
498
+ });
499
+ });
500
+ }
501
+ function getSuccessHtml() {
502
+ return `<!DOCTYPE html>
503
+ <html>
504
+ <head><title>Conto CLI - Authenticated</title></head>
505
+ <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;">
506
+ <script>
507
+ if (window.location.search || window.location.hash) {
508
+ window.history.replaceState(null, '', window.location.pathname);
509
+ }
510
+ </script>
511
+ <div style="text-align: center;">
512
+ <h1 style="color: #22c55e;">Authenticated</h1>
513
+ <p>You can close this window and return to the terminal.</p>
514
+ </div>
515
+ </body>
516
+ </html>`;
517
+ }
518
+ function escapeHtml(str) {
519
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
520
+ }
521
+ function getErrorHtml(error) {
522
+ return `<!DOCTYPE html>
523
+ <html>
524
+ <head><title>Conto CLI - Error</title></head>
525
+ <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;">
526
+ <div style="text-align: center;">
527
+ <h1 style="color: #ef4444;">Authentication Failed</h1>
528
+ <p>${escapeHtml(error)}</p>
529
+ <p>Please return to the terminal and try again.</p>
530
+ </div>
531
+ </body>
532
+ </html>`;
533
+ }
534
+
535
+ // src/commands/init.ts
536
+ var HEADLESS_DEFAULT_NAME = "conto-agent";
537
+ var HEADLESS_DEFAULT_TYPE = "CUSTOM";
538
+ var HEADLESS_DEFAULT_LIMIT = 500;
539
+ async function runInit(options = {}) {
540
+ if (options.sandbox) {
541
+ await runSandboxInit(options);
542
+ return;
543
+ }
544
+ const interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY);
545
+ if (!interactive && !options.apiKey) {
546
+ console.error("create-conto-agent needs an interactive terminal for the setup wizard.");
547
+ console.error("Headless options:");
548
+ console.error(
549
+ " --sandbox create an anonymous test-mode sandbox (no account, expires in 7 days)"
550
+ );
551
+ console.error(
552
+ " --api-key <org-api-key> use an existing Conto organization API key (skips browser auth)"
553
+ );
554
+ console.error("Add --json for machine-readable output.");
555
+ process.exit(1);
556
+ }
557
+ printBanner();
558
+ const baseUrl = options.baseUrl || "https://conto.finance";
559
+ const agentName = options.name || (interactive ? await p.text({
560
+ message: "Agent name",
561
+ placeholder: "my-procurement-bot",
562
+ validate: (v) => v.length < 2 ? "Name must be at least 2 characters" : void 0
563
+ }) : HEADLESS_DEFAULT_NAME);
564
+ if (p.isCancel(agentName)) {
565
+ p.cancel("Setup cancelled.");
566
+ process.exit(0);
567
+ }
568
+ const agentType = options.type || (interactive ? await p.select({
569
+ message: "Agent type",
570
+ options: [
571
+ { value: "ANTHROPIC_CLAUDE", label: "Claude" },
572
+ { value: "OPENAI_ASSISTANT", label: "OpenAI" },
573
+ { value: "LANGCHAIN", label: "LangChain" },
574
+ { value: "AUTOGPT", label: "AutoGPT" },
575
+ { value: "CUSTOM", label: "Custom" }
576
+ ]
577
+ }) : HEADLESS_DEFAULT_TYPE);
578
+ if (p.isCancel(agentType)) {
579
+ p.cancel("Setup cancelled.");
580
+ process.exit(0);
581
+ }
582
+ const dailyLimit = options.limit || (interactive ? await p.text({
583
+ message: "Daily spending limit (USD)",
584
+ placeholder: "500",
585
+ initialValue: "500",
586
+ validate: (v) => {
587
+ const n = Number(v);
588
+ if (isNaN(n) || n <= 0) return "Enter a positive number";
589
+ return void 0;
590
+ }
591
+ }) : HEADLESS_DEFAULT_LIMIT);
592
+ if (p.isCancel(dailyLimit)) {
593
+ p.cancel("Setup cancelled.");
594
+ process.exit(0);
595
+ }
596
+ const s0 = p.spinner();
597
+ s0.start("Fetching supported networks...");
598
+ const { chains: availableChains, defaultChainId } = await fetchChains(baseUrl);
599
+ s0.stop(`Found ${Object.keys(availableChains).length} networks`);
600
+ const chainChoices = getChainChoices(availableChains);
601
+ const selectedChain = options.chain || (interactive ? await p.select({
602
+ message: "Network",
603
+ options: chainChoices
604
+ }) : defaultChainId);
605
+ if (p.isCancel(selectedChain)) {
606
+ p.cancel("Setup cancelled.");
607
+ process.exit(0);
608
+ }
609
+ const chain = availableChains[selectedChain] || availableChains[defaultChainId];
610
+ const limit = typeof dailyLimit === "string" ? Number(dailyLimit) : dailyLimit;
611
+ const s = p.spinner();
612
+ let orgApiKey;
613
+ if (options.apiKey) {
614
+ orgApiKey = options.apiKey;
615
+ printSuccess("Using provided organization API key");
616
+ } else {
617
+ s.start("Opening browser to authenticate...");
618
+ try {
619
+ const authResult = await browserAuth(baseUrl);
620
+ orgApiKey = authResult.orgApiKey;
621
+ s.stop("Authenticated");
622
+ printSuccess("Account connected");
623
+ } catch (err) {
624
+ s.stop("Authentication failed");
625
+ printError(err instanceof Error ? err.message : "Authentication failed");
626
+ process.exit(1);
627
+ }
628
+ }
629
+ const api = new ApiClient({ baseUrl, orgApiKey });
630
+ s.start(`Provisioning wallet on ${chain.name}...`);
631
+ let wallet;
632
+ try {
633
+ wallet = await api.createWallet({
634
+ name: `${agentName} Wallet`,
635
+ chainType: chain.chainType,
636
+ chainId: chain.chainId
637
+ });
638
+ } catch (err) {
639
+ const status = err.status;
640
+ if (status === 503) {
641
+ try {
642
+ wallet = await api.createWallet({
643
+ name: `${agentName} Wallet`,
644
+ chainType: chain.chainType,
645
+ chainId: chain.chainId,
646
+ custodyType: "SPONGE"
647
+ });
648
+ } catch (retryErr) {
649
+ s.stop("Wallet creation failed");
650
+ printError(retryErr instanceof Error ? retryErr.message : "Failed to create wallet");
651
+ process.exit(1);
652
+ }
653
+ } else {
654
+ s.stop("Wallet creation failed");
655
+ printError(err instanceof Error ? err.message : "Failed to create wallet");
656
+ process.exit(1);
657
+ }
658
+ }
659
+ s.stop(`Wallet provisioned on ${chain.name}`);
660
+ printSuccess(`Wallet: ${wallet.address} (${wallet.custodyType} custody)`);
661
+ if (wallet.custodyType === "SPONGE") {
662
+ s.start("Linking wallet to custody provider...");
663
+ try {
664
+ const provisioned = await api.provisionWallet(wallet.id);
665
+ if (provisioned.wallet?.address) {
666
+ wallet.address = provisioned.wallet.address;
667
+ }
668
+ s.stop("Custody provider linked");
669
+ } catch (err) {
670
+ s.stop("Custody provisioning incomplete");
671
+ printWarning(err instanceof Error ? err.message : "Custody provider not configured");
672
+ printInfo('Payments may run in simulated mode. Run "conto doctor" after setup for details.');
673
+ }
674
+ }
675
+ if (chain.faucetAvailable) {
676
+ s.start("Requesting testnet funds from faucet...");
677
+ try {
678
+ const faucetResult = await api.fundWallet(wallet.id);
679
+ s.stop("Faucet request sent");
680
+ if (typeof faucetResult.updatedBalance === "number") {
681
+ printSuccess(`Wallet balance: ${faucetResult.updatedBalance} ${chain.currency} (testnet)`);
682
+ } else {
683
+ printSuccess(faucetResult.message || `Testnet ${chain.currency} requested`);
684
+ }
685
+ } catch (err) {
686
+ s.stop("Faucet request failed (you can fund manually)");
687
+ printInfo(err instanceof Error ? err.message : "Faucet unavailable");
688
+ }
689
+ }
690
+ s.start(`Registering agent "${agentName}"...`);
691
+ let agent;
692
+ try {
693
+ agent = await api.createAgent({
694
+ name: agentName,
695
+ agentType,
696
+ description: `Created via CLI quickstart`
697
+ });
698
+ s.stop("Agent registered");
699
+ printSuccess(`Agent "${agent.name}" created`);
700
+ } catch (err) {
701
+ s.stop("Agent creation failed");
702
+ printError(err instanceof Error ? err.message : "Failed to create agent");
703
+ process.exit(1);
704
+ }
705
+ s.start("Linking wallet to agent...");
706
+ try {
707
+ await api.linkWalletToAgent(agent.id, {
708
+ walletId: wallet.id,
709
+ delegationType: "FULL",
710
+ spendLimitDaily: limit,
711
+ spendLimitPerTx: Math.min(limit, 1e3)
712
+ });
713
+ s.stop("Wallet linked");
714
+ printSuccess(`Wallet linked ($${limit}/day limit)`);
715
+ } catch (err) {
716
+ s.stop("Wallet linking failed");
717
+ printError(err instanceof Error ? err.message : "Failed to link wallet");
718
+ process.exit(1);
719
+ }
720
+ s.start("Creating default spending policy...");
721
+ try {
722
+ await api.createPolicy({
723
+ name: `${agentName} - Daily Limit`,
724
+ policyType: "SPEND_LIMIT",
725
+ priority: 50,
726
+ isActive: true,
727
+ rules: [
728
+ {
729
+ ruleType: "DAILY_LIMIT",
730
+ operator: "LESS_THAN_OR_EQUAL",
731
+ value: String(limit),
732
+ action: "ALLOW"
733
+ }
734
+ ],
735
+ agentIds: [agent.id]
736
+ });
737
+ s.stop("Policy created");
738
+ printSuccess("Default spending policy applied");
739
+ } catch (err) {
740
+ s.stop("Policy creation failed (continuing without policy)");
741
+ printInfo("You can create policies later in the dashboard");
742
+ }
743
+ s.start("Generating SDK key...");
744
+ let sdkKey;
745
+ try {
746
+ sdkKey = await api.createSdkKey(agent.id, {
747
+ name: "CLI Quickstart Key",
748
+ keyType: "standard"
749
+ });
750
+ s.stop("SDK key generated");
751
+ if (sdkKey.scopes && !sdkKey.scopes.includes("payments:execute")) {
752
+ printWarning(
753
+ 'SDK key is missing payments:execute, so "conto pay" will not be able to execute'
754
+ );
755
+ } else {
756
+ printSuccess("SDK key created (standard preset, includes payments:execute)");
757
+ }
758
+ } catch (err) {
759
+ s.stop("SDK key generation failed");
760
+ printError(err instanceof Error ? err.message : "Failed to create SDK key");
761
+ process.exit(1);
762
+ }
763
+ const cwd = process.cwd();
764
+ writeEnvLocal(cwd, [
765
+ "# Conto Agent Configuration",
766
+ "# Generated by: npx create-conto-agent",
767
+ "",
768
+ "# SDK Authentication",
769
+ ["CONTO_API_KEY", sdkKey.key],
770
+ ["CONTO_BASE_URL", baseUrl],
771
+ "",
772
+ "# Agent Identity",
773
+ ["CONTO_AGENT_ID", agent.id],
774
+ ["CONTO_AGENT_NAME", agent.name],
775
+ "",
776
+ `# Network: ${chain.name}${chain.testnet ? " (testnet)" : ""}`,
777
+ ["CONTO_CHAIN_ID", chain.chainId],
778
+ ["CONTO_CHAIN_NAME", chain.name],
779
+ ["CONTO_RPC_URL", chain.rpcUrl],
780
+ ["CONTO_EXPLORER_URL", chain.explorerUrl],
781
+ ["CONTO_CURRENCY", chain.currency],
782
+ "",
783
+ "# Wallet",
784
+ ["CONTO_WALLET_ID", wallet.id],
785
+ ["CONTO_WALLET_ADDRESS", wallet.address]
786
+ ]);
787
+ writeContoConfig(cwd, {
788
+ agent: {
789
+ id: agent.id,
790
+ name: agent.name,
791
+ type: agentType
792
+ },
793
+ network: {
794
+ chain: selectedChain,
795
+ chainId: chain.chainId,
796
+ rpcUrl: chain.rpcUrl,
797
+ explorerUrl: chain.explorerUrl,
798
+ currency: chain.currency,
799
+ testnet: chain.testnet
800
+ },
801
+ wallet: {
802
+ id: wallet.id,
803
+ address: wallet.address,
804
+ custodyType: wallet.custodyType
805
+ },
806
+ server: {
807
+ baseUrl
808
+ }
809
+ });
810
+ writeExampleFile(cwd);
811
+ saveGlobalConfig({
812
+ agent: { id: agent.id, name: agent.name, type: agentType },
813
+ network: {
814
+ chain: selectedChain,
815
+ chainId: chain.chainId,
816
+ rpcUrl: chain.rpcUrl,
817
+ explorerUrl: chain.explorerUrl,
818
+ currency: chain.currency,
819
+ testnet: chain.testnet
820
+ },
821
+ wallet: { id: wallet.id, address: wallet.address, custodyType: wallet.custodyType },
822
+ server: { baseUrl, apiKey: sdkKey.key, orgApiKey }
823
+ });
824
+ let cliResolves = false;
825
+ if (hasLocalCliBin(cwd)) {
826
+ cliResolves = true;
827
+ } else if (options.install !== false) {
828
+ s.start("Installing conto CLI into this project...");
829
+ const outcome = installCliLocally(cwd, agent.name);
830
+ if (outcome === "installed") {
831
+ s.stop("CLI installed (devDependency)");
832
+ cliResolves = true;
833
+ } else if (outcome === "unsupported-pm") {
834
+ s.stop("Skipped CLI install (non-npm lockfile found)");
835
+ printInfo(
836
+ "Install it with your package manager: add @conto_finance/create-conto-agent as a dev dependency."
837
+ );
838
+ } else {
839
+ s.stop("CLI install failed (continuing)");
840
+ }
841
+ }
842
+ console.log("");
843
+ console.log(chalk.green.bold(" Your agent is ready!") + " Files written:\n");
844
+ console.log(` ${chalk.bold(".env.local")} - SDK key + config`);
845
+ console.log(` ${chalk.bold("conto.config.json")} - Agent metadata`);
846
+ console.log(` ${chalk.bold("example.ts")} - Runnable payment example`);
847
+ console.log("");
848
+ console.log(
849
+ ` ${chalk.dim("Wallet:")} ${wallet.address} (${chain.name}${chain.testnet ? " testnet" : ""}, ${wallet.custodyType} custody)`
850
+ );
851
+ console.log(` ${chalk.dim("Currency:")} ${chain.currency}`);
852
+ console.log(` ${chalk.dim("Explorer:")} ${chain.explorerUrl}`);
853
+ console.log("");
854
+ const cli = cliResolves ? "npx conto" : "npx @conto_finance/create-conto-agent";
855
+ console.log(chalk.bold(" Next steps:"));
856
+ let step = 1;
857
+ console.log(` ${step++}. Verify setup: ${chalk.cyan(`${cli} doctor`)}`);
858
+ if (!chain.faucetAvailable) {
859
+ console.log(
860
+ ` ${step++}. Fund your wallet with ${chain.currency} ${chalk.dim("\u2192")} ${wallet.address}`
861
+ );
862
+ }
863
+ console.log(` ${step++}. Run the example: ${chalk.cyan("npx tsx example.ts")}`);
864
+ console.log(` ${step++}. Make a payment: ${chalk.cyan(`${cli} pay <address> <amount>`)}`);
865
+ console.log(` ${step++}. Connect Claude: ${chalk.cyan(`${cli} mcp`)}`);
866
+ if (!cliResolves) {
867
+ printInfo(
868
+ 'Tip: "npx conto <command>" works after: npm install --save-dev @conto_finance/create-conto-agent'
869
+ );
870
+ }
871
+ console.log("");
872
+ }
873
+ async function runSandboxInit(options) {
874
+ printBanner();
875
+ const baseUrl = options.baseUrl || "https://conto.finance";
876
+ const failure = (message) => {
877
+ if (isJsonMode()) {
878
+ printJson({ ok: false, mode: "sandbox", error: message });
879
+ } else {
880
+ printError(message);
881
+ }
882
+ process.exit(1);
883
+ };
884
+ printInfo(`Creating an anonymous sandbox on ${baseUrl}...`);
885
+ let response;
886
+ try {
887
+ response = await fetch(`${baseUrl}/api/agents/sandbox`, {
888
+ method: "POST",
889
+ headers: { "Content-Type": "application/json" },
890
+ body: JSON.stringify({
891
+ name: options.name || "Sandbox Agent",
892
+ agentType: options.type || "CUSTOM",
893
+ description: "Created via create-conto-agent --sandbox"
894
+ })
895
+ });
896
+ } catch (err) {
897
+ return failure(
898
+ `Could not reach ${baseUrl}: ${err instanceof Error ? err.message : "network error"}`
899
+ );
900
+ }
901
+ const body = await response.json().catch(() => ({}));
902
+ if (response.status === 429) {
903
+ const retryAfter = response.headers.get("retry-after");
904
+ return failure(
905
+ `Sandbox signup is rate limited for this IP.${retryAfter ? ` Retry after ${retryAfter}s.` : ""}`
906
+ );
907
+ }
908
+ if (!response.ok) {
909
+ return failure(
910
+ typeof body.error === "string" ? body.error : `Sandbox signup failed (${response.status})`
911
+ );
912
+ }
913
+ const sandbox = body;
914
+ printSuccess(`Sandbox created (expires ${sandbox.expiresAt})`);
915
+ let chain;
916
+ try {
917
+ const { chains } = await fetchChains(baseUrl);
918
+ chain = chains[sandbox.wallet.chainId];
919
+ } catch {
920
+ chain = void 0;
921
+ }
922
+ const cwd = process.cwd();
923
+ writeEnvLocal(cwd, [
924
+ "# Conto Agent Configuration (anonymous test-mode sandbox)",
925
+ "# Generated by: npx create-conto-agent --sandbox",
926
+ "",
927
+ "# SDK Authentication",
928
+ ["CONTO_API_KEY", sandbox.credentials.sdkKey],
929
+ ["CONTO_BASE_URL", baseUrl],
930
+ "",
931
+ "# Agent Identity",
932
+ ["CONTO_AGENT_ID", sandbox.agent.id],
933
+ ["CONTO_AGENT_NAME", sandbox.agent.name],
934
+ "",
935
+ `# Network: ${chain?.name || sandbox.wallet.chainId} (testnet)`,
936
+ ["CONTO_CHAIN_ID", sandbox.wallet.chainId],
937
+ ...chain ? [
938
+ ["CONTO_CHAIN_NAME", chain.name],
939
+ ["CONTO_RPC_URL", chain.rpcUrl],
940
+ ["CONTO_EXPLORER_URL", chain.explorerUrl],
941
+ ["CONTO_CURRENCY", chain.currency]
942
+ ] : [["CONTO_CURRENCY", sandbox.wallet.currency]],
943
+ "",
944
+ "# Wallet",
945
+ ["CONTO_WALLET_ID", sandbox.wallet.id],
946
+ ["CONTO_WALLET_ADDRESS", sandbox.wallet.address],
947
+ "",
948
+ "# Sandbox (shown once, keep private)",
949
+ ["CONTO_SANDBOX_API_KEY", sandbox.credentials.apiKey],
950
+ ["CONTO_SANDBOX_EXPIRES_AT", sandbox.expiresAt]
951
+ ]);
952
+ writeContoConfig(cwd, {
953
+ agent: {
954
+ id: sandbox.agent.id,
955
+ name: sandbox.agent.name,
956
+ type: options.type || "CUSTOM"
957
+ },
958
+ network: {
959
+ chain: sandbox.wallet.chainId,
960
+ chainId: sandbox.wallet.chainId,
961
+ rpcUrl: chain?.rpcUrl || "",
962
+ explorerUrl: chain?.explorerUrl || "",
963
+ currency: chain?.currency || sandbox.wallet.currency,
964
+ testnet: true
965
+ },
966
+ wallet: {
967
+ id: sandbox.wallet.id,
968
+ address: sandbox.wallet.address,
969
+ custodyType: sandbox.wallet.custodyType
970
+ },
971
+ server: {
972
+ baseUrl
973
+ },
974
+ sandbox: {
975
+ mode: "test",
976
+ expiresAt: sandbox.expiresAt,
977
+ execution: "simulated"
978
+ }
979
+ });
980
+ writeExampleFile(cwd);
981
+ saveGlobalConfig({
982
+ agent: {
983
+ id: sandbox.agent.id,
984
+ name: sandbox.agent.name,
985
+ type: options.type || "CUSTOM"
986
+ },
987
+ network: {
988
+ chain: sandbox.wallet.chainId,
989
+ chainId: sandbox.wallet.chainId,
990
+ rpcUrl: chain?.rpcUrl || "",
991
+ explorerUrl: chain?.explorerUrl || "",
992
+ currency: chain?.currency || sandbox.wallet.currency,
993
+ testnet: true
994
+ },
995
+ wallet: {
996
+ id: sandbox.wallet.id,
997
+ address: sandbox.wallet.address,
998
+ custodyType: sandbox.wallet.custodyType
999
+ },
1000
+ server: {
1001
+ baseUrl,
1002
+ apiKey: sandbox.credentials.sdkKey,
1003
+ orgApiKey: sandbox.credentials.apiKey
1004
+ }
1005
+ });
1006
+ let cliResolves = hasLocalCliBin(cwd);
1007
+ if (!cliResolves && options.install !== false) {
1008
+ cliResolves = installCliLocally(cwd, sandbox.agent.name) === "installed";
1009
+ }
1010
+ const cli = cliResolves ? "npx conto" : "npx @conto_finance/create-conto-agent";
1011
+ if (isJsonMode()) {
1012
+ printJson({
1013
+ ok: true,
1014
+ mode: "sandbox",
1015
+ baseUrl,
1016
+ expiresAt: sandbox.expiresAt,
1017
+ execution: "simulated",
1018
+ organization: sandbox.organization,
1019
+ agent: sandbox.agent,
1020
+ wallet: sandbox.wallet,
1021
+ credentials: { ...sandbox.credentials, shownOnce: true },
1022
+ files: [".env.local", "conto.config.json", "example.ts"],
1023
+ claim: sandbox.claim ?? null,
1024
+ nextSteps: [
1025
+ "npx tsx example.ts",
1026
+ "npx tsx example.ts --execute",
1027
+ `${cli} doctor`,
1028
+ `${cli} pay 0x742d35Cc6634C0532925a3b844Bc454e4438f44e 1 --purpose test`
1029
+ ]
1030
+ });
1031
+ return;
1032
+ }
1033
+ console.log("");
1034
+ console.log(chalk.green.bold(" Sandbox agent ready!") + " Files written:\n");
1035
+ console.log(` ${chalk.bold(".env.local")} - SDK key + config (shown once)`);
1036
+ console.log(` ${chalk.bold("conto.config.json")} - Agent metadata`);
1037
+ console.log(` ${chalk.bold("example.ts")} - Runnable payment example`);
1038
+ console.log("");
1039
+ console.log(
1040
+ ` ${chalk.dim("Wallet:")} ${sandbox.wallet.address} (${chain?.name || sandbox.wallet.chainId}, test mode)`
1041
+ );
1042
+ console.log(
1043
+ ` ${chalk.dim("Balance:")} ${sandbox.wallet.balance} ${sandbox.wallet.currency} (simulated)`
1044
+ );
1045
+ console.log(
1046
+ ` ${chalk.dim("Limits:")} $${sandbox.wallet.limits.perTransaction}/tx, $${sandbox.wallet.limits.daily}/day`
1047
+ );
1048
+ console.log(` ${chalk.dim("Expires:")} ${sandbox.expiresAt}`);
1049
+ console.log("");
1050
+ console.log(chalk.bold(" Next steps:"));
1051
+ console.log(` 1. Run the example: ${chalk.cyan("npx tsx example.ts")}`);
1052
+ console.log(` 2. Execute it: ${chalk.cyan("npx tsx example.ts --execute")}`);
1053
+ console.log(` 3. Verify setup: ${chalk.cyan(`${cli} doctor`)}`);
1054
+ console.log("");
1055
+ printInfo(
1056
+ "Sandbox payments execute in simulated mode: policy checks, receipts, and spend tracking are real; no onchain transfer happens."
1057
+ );
1058
+ printInfo("To keep this sandbox, sign in at conto.finance and claim it before it expires.");
1059
+ console.log("");
1060
+ }
1061
+ function hasLocalCliBin(cwd) {
1062
+ return fs.existsSync(path.join(cwd, "node_modules", ".bin", "conto"));
1063
+ }
1064
+ function installCliLocally(cwd, agentName) {
1065
+ const foreignLockfiles = ["yarn.lock", "pnpm-lock.yaml", "bun.lockb", "bun.lock"];
1066
+ if (foreignLockfiles.some((f) => fs.existsSync(path.join(cwd, f)))) {
1067
+ return "unsupported-pm";
1068
+ }
1069
+ const pkgJsonPath = path.join(cwd, "package.json");
1070
+ const createdPkgJson = !fs.existsSync(pkgJsonPath);
1071
+ if (createdPkgJson) {
1072
+ const slug = agentName.toLowerCase().replace(/[^a-z0-9-_]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40) || "conto-agent";
1073
+ fs.writeFileSync(
1074
+ pkgJsonPath,
1075
+ JSON.stringify({ name: slug, version: "0.1.0", private: true, type: "module" }, null, 2) + "\n"
1076
+ );
1077
+ }
1078
+ const result = spawnSync(
1079
+ process.platform === "win32" ? "npm.cmd" : "npm",
1080
+ [
1081
+ "install",
1082
+ "--save-dev",
1083
+ "--no-fund",
1084
+ "--no-audit",
1085
+ `@conto_finance/create-conto-agent@^${CLI_PACKAGE_VERSION}`
1086
+ ],
1087
+ {
1088
+ cwd,
1089
+ stdio: "ignore",
1090
+ timeout: 18e4,
1091
+ shell: process.platform === "win32"
1092
+ }
1093
+ );
1094
+ if (result.status === 0) {
1095
+ return "installed";
1096
+ }
1097
+ if (createdPkgJson) {
1098
+ try {
1099
+ fs.unlinkSync(pkgJsonPath);
1100
+ } catch {
1101
+ }
1102
+ }
1103
+ return "failed";
1104
+ }
1105
+ function writeExampleFile(dir) {
1106
+ const content = `// Conto quickstart example, generated by create-conto-agent.
1107
+ //
1108
+ // Usage:
1109
+ // npx tsx example.ts Check setup and request a test payment (no funds move)
1110
+ // npx tsx example.ts --execute Also execute the payment if it is approved
1111
+ //
1112
+ // Reads CONTO_API_KEY and CONTO_BASE_URL from .env.local in this directory.
1113
+ // Docs: https://conto.finance/docs
1114
+
1115
+ import { readFileSync } from 'fs';
1116
+ try {
1117
+ for (const line of readFileSync('.env.local', 'utf-8').split('\\n')) {
1118
+ const match = line.match(/^([A-Z_][A-Z0-9_]*)=(.*)$/);
1119
+ if (match && !process.env[match[1]]) process.env[match[1]] = match[2];
1120
+ }
1121
+ } catch {}
1122
+
1123
+ const BASE_URL = process.env.CONTO_BASE_URL || 'https://conto.finance';
1124
+ const API_KEY = process.env.CONTO_API_KEY;
1125
+ const EXECUTE = process.argv.includes('--execute');
1126
+
1127
+ if (!API_KEY) {
1128
+ console.error('Missing CONTO_API_KEY in .env.local. Run: npx create-conto-agent');
1129
+ process.exit(1);
1130
+ }
1131
+
1132
+ async function api(method: string, path: string, body?: unknown) {
1133
+ const res = await fetch(\`\${BASE_URL}\${path}\`, {
1134
+ method,
1135
+ headers: { Authorization: \`Bearer \${API_KEY}\`, 'Content-Type': 'application/json' },
1136
+ body: body ? JSON.stringify(body) : undefined,
1137
+ });
1138
+ const data = await res.json();
1139
+ if (!res.ok) throw new Error(data.error || \`\${method} \${path} failed (\${res.status})\`);
1140
+ return data;
1141
+ }
1142
+
1143
+ async function main() {
1144
+ // 1. Setup snapshot: agent, key scopes, wallets. Same data as "conto doctor".
1145
+ const setup = await api('GET', '/api/sdk/setup');
1146
+ console.log(\`Agent: \${setup.agent.name} (\${setup.agent.status})\`);
1147
+ console.log(\`Scopes: \${(setup.scopes || []).join(', ')}\\n\`);
1148
+ for (const w of setup.wallets || []) {
1149
+ console.log(\`Wallet: \${w.address}\`);
1150
+ console.log(\` Chain: \${w.chainName} (\${w.chainId})\${w.isTestnet ? ' testnet' : ''}\`);
1151
+ console.log(\` Custody: \${w.custodyType}\${w.executionMode ? \` ( execution)\` : ''}\`);
1152
+ console.log(\` Balance: \${w.balance} \${w.currency}\`);
1153
+ console.log(\` Daily: \${w.spent?.today ?? 0} / \${w.limits?.daily ?? 'unlimited'}\\n\`);
1154
+ }
1155
+
1156
+ // 2. Request a payment. The policy engine evaluates it and returns
1157
+ // APPROVED, DENIED, or REQUIRES_APPROVAL. No funds move on request.
1158
+ console.log('Requesting a $0.01 test payment...');
1159
+ const request = await api('POST', '/api/sdk/payments/request', {
1160
+ amount: 0.01,
1161
+ recipientAddress: '0x0000000000000000000000000000000000000001',
1162
+ purpose: 'Test payment from CLI quickstart',
1163
+ category: 'TESTING',
1164
+ });
1165
+ console.log(\`Policy decision: \${request.status}\`);
1166
+ if (request.reasons?.length) console.log(\`Reasons: \${request.reasons.join(', ')}\`);
1167
+
1168
+ if (request.status === 'DENIED') {
1169
+ for (const v of request.violations || []) console.log(\` - \${v.message}\`);
1170
+ return;
1171
+ }
1172
+ if (request.status === 'REQUIRES_APPROVAL') {
1173
+ console.log('Approve it in the Conto dashboard, then execute it from there or via the API.');
1174
+ return;
1175
+ }
1176
+ if (request.status !== 'APPROVED') {
1177
+ console.log(\`Stopped at status \${request.status}. Check the dashboard for next steps.\`);
1178
+ return;
1179
+ }
1180
+
1181
+ // 3. Execute the approved request. The standard SDK key created by the
1182
+ // quickstart includes the payments:execute scope.
1183
+ if (!EXECUTE) {
1184
+ console.log(\`\\nApproved (request \${request.requestId}). No funds moved.\`);
1185
+ console.log('Re-run with --execute to send it, or use: npx conto pay <address> <amount>');
1186
+ return;
1187
+ }
1188
+ const result = await api('POST', \`/api/sdk/payments/\${request.requestId}/execute\`);
1189
+ console.log(\`\\nPayment sent\${result.simulated ? ' (simulated, no onchain transfer)' : ''}.\`);
1190
+ console.log(\`TX hash: \${result.txHash}\`);
1191
+ console.log(\`Explorer: \${result.explorerUrl}\`);
1192
+ }
1193
+
1194
+ main().catch((err) => {
1195
+ console.error(err instanceof Error ? err.message : err);
1196
+ process.exit(1);
1197
+ });
1198
+ `;
1199
+ fs.writeFileSync(path.join(dir, "example.ts"), content);
1200
+ }
1201
+
1202
+ export {
1203
+ CLI_PACKAGE_VERSION,
1204
+ createApiClient,
1205
+ fetchChains,
1206
+ getChain,
1207
+ browserAuth,
1208
+ runInit
1209
+ };