@conto_finance/create-conto-agent 0.4.4 → 0.4.6

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