@conto_finance/create-conto-agent 0.3.1 → 0.4.3

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.
@@ -8,16 +8,17 @@ import {
8
8
  printWarning
9
9
  } from "./chunk-K4LBO234.js";
10
10
  import {
11
+ ensureEnvLocalGitignored,
11
12
  saveGlobalConfig,
12
13
  writeContoConfig,
13
14
  writeEnvLocal
14
- } from "./chunk-WMVGNUSL.js";
15
+ } from "./chunk-2U2MPMMD.js";
15
16
 
16
17
  // package.json
17
18
  var package_default = {
18
19
  name: "@conto_finance/create-conto-agent",
19
- version: "0.3.1",
20
- description: "CLI quickstart for Conto \u2014 Agentic Payments Control Center",
20
+ version: "0.4.3",
21
+ description: "Set up an AI agent with Conto spending controls",
21
22
  bin: {
22
23
  "create-conto-agent": "bin/create-conto-agent.js",
23
24
  conto: "bin/conto.js"
@@ -26,13 +27,21 @@ var package_default = {
26
27
  type: "module",
27
28
  files: [
28
29
  "dist",
29
- "bin"
30
+ "bin",
31
+ "README.md",
32
+ "CHANGELOG.md"
30
33
  ],
34
+ publishConfig: {
35
+ access: "public"
36
+ },
31
37
  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",
38
+ build: "tsup src/index.ts src/cli.ts src/lib/rule-values.ts --format esm --dts --clean",
39
+ dev: "tsup src/index.ts src/cli.ts src/lib/rule-values.ts --format esm --dts --watch",
34
40
  lint: "tsc --noEmit",
35
- test: "npm run build && node --test test/*.test.mjs"
41
+ test: "npm run lint && npm run test:contract",
42
+ "test:contract": "npm run build && node --test test/*.test.mjs",
43
+ "verify:release": "node scripts/verify-release.mjs",
44
+ prepublishOnly: "npm run verify:release && npm test"
36
45
  },
37
46
  engines: {
38
47
  node: ">=20.19.0"
@@ -51,12 +60,12 @@ var package_default = {
51
60
  license: "MIT",
52
61
  repository: {
53
62
  type: "git",
54
- url: "https://github.com/kwattana/conto.git",
63
+ url: "https://github.com/conto-finance/conto.git",
55
64
  directory: "packages/cli"
56
65
  },
57
- homepage: "https://conto.finance",
66
+ homepage: "https://conto.finance/docs/cli/quickstart",
58
67
  bugs: {
59
- url: "https://github.com/kwattana/conto/issues"
68
+ email: "support@conto.finance"
60
69
  },
61
70
  dependencies: {
62
71
  "@clack/prompts": "^0.9.1",
@@ -96,7 +105,6 @@ var FALLBACK_CHAINS = {
96
105
  explorerName: "Tempo Explorer",
97
106
  currency: "USDC.e",
98
107
  chainType: "EVM",
99
- spongeChainId: "tempo-mainnet",
100
108
  testnet: false,
101
109
  isDefault: false,
102
110
  faucetAvailable: false,
@@ -118,7 +126,6 @@ var FALLBACK_CHAINS = {
118
126
  explorerName: "Tempo Explorer",
119
127
  currency: "pathUSD",
120
128
  chainType: "EVM",
121
- spongeChainId: "tempo",
122
129
  testnet: true,
123
130
  isDefault: true,
124
131
  faucetAvailable: true,
@@ -132,9 +139,17 @@ var FALLBACK_CHAINS = {
132
139
  ]
133
140
  }
134
141
  };
135
- var DEFAULT_FALLBACK_CHAIN_ID = "4217";
142
+ var DEFAULT_EVALUATION_CHAIN_ID = "42431";
143
+ var DEFAULT_FALLBACK_CHAIN_ID = DEFAULT_EVALUATION_CHAIN_ID;
136
144
  var cachedChains = null;
137
145
  var cachedDefaultChainId = null;
146
+ function getEvaluationDefaultChainId(chains, serverDefaultChainId) {
147
+ if (chains[DEFAULT_EVALUATION_CHAIN_ID]?.testnet) return DEFAULT_EVALUATION_CHAIN_ID;
148
+ if (serverDefaultChainId && chains[serverDefaultChainId]?.testnet) return serverDefaultChainId;
149
+ const firstTestnet = Object.values(chains).find((chain) => chain.testnet);
150
+ if (firstTestnet) return firstTestnet.chainId;
151
+ return serverDefaultChainId && chains[serverDefaultChainId] ? serverDefaultChainId : Object.keys(chains)[0];
152
+ }
138
153
  async function fetchChains(baseUrl) {
139
154
  if (cachedChains) {
140
155
  return { chains: cachedChains, defaultChainId: cachedDefaultChainId };
@@ -156,7 +171,6 @@ async function fetchChains(baseUrl) {
156
171
  explorerName: c.explorerName,
157
172
  currency: c.currency,
158
173
  chainType: c.type,
159
- spongeChainId: c.spongeChainId,
160
174
  testnet: c.isTestnet,
161
175
  isDefault: c.isDefault,
162
176
  faucetAvailable: c.faucetAvailable,
@@ -165,8 +179,8 @@ async function fetchChains(baseUrl) {
165
179
  };
166
180
  }
167
181
  cachedChains = chains;
168
- cachedDefaultChainId = data.defaultChainId;
169
- return { chains, defaultChainId: data.defaultChainId };
182
+ cachedDefaultChainId = getEvaluationDefaultChainId(chains, data.defaultChainId);
183
+ return { chains, defaultChainId: cachedDefaultChainId };
170
184
  } catch {
171
185
  cachedChains = FALLBACK_CHAINS;
172
186
  cachedDefaultChainId = DEFAULT_FALLBACK_CHAIN_ID;
@@ -179,33 +193,44 @@ function getChain(chainId) {
179
193
  function getChainChoices(chains) {
180
194
  const entries = Object.entries(chains);
181
195
  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;
196
+ if (a.chainId === DEFAULT_EVALUATION_CHAIN_ID) return -1;
197
+ if (b.chainId === DEFAULT_EVALUATION_CHAIN_ID) return 1;
198
+ if (a.testnet && !b.testnet) return -1;
199
+ if (!a.testnet && b.testnet) return 1;
188
200
  return a.name.localeCompare(b.name);
189
201
  });
190
- return entries.map(([id, chain], i) => ({
202
+ return entries.map(([id, chain]) => ({
191
203
  value: id,
192
- label: i === 0 ? `${chain.name} (recommended)` : chain.name,
204
+ label: chain.chainId === DEFAULT_EVALUATION_CHAIN_ID ? `${chain.name} (recommended for evaluation)` : chain.name,
193
205
  hint: chainHint(chain)
194
206
  }));
195
207
  }
196
208
  function chainHint(chain) {
197
- if (chain.chainId === "4217") return "Stablecoin-native, fast, low fees";
198
209
  if (chain.testnet) return `Testnet \u2014 free ${chain.currency}, no real funds`;
210
+ if (chain.chainId === "4217") return "Mainnet \u2014 real USDC.e and real settlement";
199
211
  return `${chain.chainType} \u2014 ${chain.currency}`;
200
212
  }
201
213
 
202
214
  // src/lib/api-client.ts
215
+ var REQUEST_TIMEOUT_MS = 3e4;
216
+ function assertSecureBaseUrl(baseUrl) {
217
+ let parsed;
218
+ try {
219
+ parsed = new URL(baseUrl);
220
+ } catch {
221
+ throw new Error(`Invalid base URL: ${baseUrl}`);
222
+ }
223
+ if (parsed.protocol !== "https:" && parsed.hostname !== "localhost" && parsed.hostname !== "127.0.0.1") {
224
+ throw new Error("baseUrl must use https (except for localhost)");
225
+ }
226
+ }
203
227
  var ApiClient = class {
204
228
  baseUrl;
205
229
  apiKey;
206
230
  orgApiKey;
207
231
  constructor(options) {
208
232
  this.baseUrl = options.baseUrl.replace(/\/$/, "");
233
+ assertSecureBaseUrl(this.baseUrl);
209
234
  this.apiKey = options.apiKey;
210
235
  this.orgApiKey = options.orgApiKey;
211
236
  }
@@ -220,28 +245,45 @@ var ApiClient = class {
220
245
  if (token) {
221
246
  headers["Authorization"] = `Bearer ${token}`;
222
247
  }
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;
248
+ const controller = new AbortController();
249
+ const timeoutId = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
250
+ try {
251
+ const response = await fetch(url, {
252
+ method,
253
+ headers,
254
+ body: options?.body ? JSON.stringify(options.body) : void 0,
255
+ signal: controller.signal
256
+ });
257
+ const contentType = response.headers.get("content-type") || "";
258
+ if (!contentType.includes("application/json")) {
259
+ const error = new Error(
260
+ response.status === 404 ? `API endpoint not found: ${path2}` : `API returned non-JSON response (${response.status})`
261
+ );
262
+ error.code = response.status === 404 ? "NOT_FOUND" : "INVALID_RESPONSE";
263
+ error.status = response.status;
264
+ throw error;
265
+ }
266
+ const data = await response.json();
267
+ if (!response.ok) {
268
+ const error = new Error(data.error || `API request failed: ${response.status}`);
269
+ error.code = data.code || "API_ERROR";
270
+ error.status = response.status;
271
+ throw error;
272
+ }
273
+ return data;
274
+ } catch (err) {
275
+ if (err instanceof Error && err.name === "AbortError") {
276
+ const error = new Error(
277
+ `Request timed out after ${REQUEST_TIMEOUT_MS / 1e3}s`
278
+ );
279
+ error.code = "TIMEOUT";
280
+ error.status = 0;
281
+ throw error;
282
+ }
283
+ throw err;
284
+ } finally {
285
+ clearTimeout(timeoutId);
243
286
  }
244
- return data;
245
287
  }
246
288
  // ── Org-level Admin APIs (used during init) ──
247
289
  async createWallet(params) {
@@ -251,7 +293,7 @@ var ApiClient = class {
251
293
  return this.request("POST", "/api/agents", { body: params, auth: "org" });
252
294
  }
253
295
  async linkWalletToAgent(agentId, params) {
254
- return this.request("POST", `/api/agents/${agentId}/wallets`, {
296
+ return this.request("POST", `/api/agents/${encodeURIComponent(agentId)}/wallets`, {
255
297
  body: params,
256
298
  auth: "org"
257
299
  });
@@ -260,15 +302,15 @@ var ApiClient = class {
260
302
  return this.request("POST", "/api/policies", { body: params, auth: "org" });
261
303
  }
262
304
  async updatePolicy(policyId, params) {
263
- return this.request("PATCH", `/api/policies/${policyId}`, { body: params, auth: "org" });
305
+ return this.request("PATCH", `/api/policies/${encodeURIComponent(policyId)}`, { body: params, auth: "org" });
264
306
  }
265
307
  async deletePolicy(policyId) {
266
- return this.request("DELETE", `/api/policies/${policyId}`, { auth: "org" });
308
+ return this.request("DELETE", `/api/policies/${encodeURIComponent(policyId)}`, { auth: "org" });
267
309
  }
268
310
  async addPolicyRule(policyId, rule) {
269
311
  return this.request(
270
312
  "POST",
271
- `/api/policies/${policyId}/rules`,
313
+ `/api/policies/${encodeURIComponent(policyId)}/rules`,
272
314
  {
273
315
  body: rule,
274
316
  auth: "org"
@@ -276,36 +318,40 @@ var ApiClient = class {
276
318
  );
277
319
  }
278
320
  async deletePolicyRule(policyId, ruleId) {
279
- return this.request("DELETE", `/api/policies/${policyId}/rules/${ruleId}`, { auth: "org" });
321
+ return this.request(
322
+ "DELETE",
323
+ `/api/policies/${encodeURIComponent(policyId)}/rules/${encodeURIComponent(ruleId)}`,
324
+ { auth: "org" }
325
+ );
280
326
  }
281
327
  async listOrgPolicies() {
282
328
  return this.request("GET", "/api/policies", { auth: "org" });
283
329
  }
284
330
  async assignPolicyToAgent(agentId, policyId) {
285
- return this.request("POST", `/api/agents/${agentId}/policies`, {
331
+ return this.request("POST", `/api/agents/${encodeURIComponent(agentId)}/policies`, {
286
332
  body: { policyId },
287
333
  auth: "org"
288
334
  });
289
335
  }
290
336
  async unassignPolicyFromAgent(agentId, policyId) {
291
- return this.request("DELETE", `/api/agents/${agentId}/policies?policyId=${policyId}`, {
292
- auth: "org"
293
- });
337
+ return this.request(
338
+ "DELETE",
339
+ `/api/agents/${encodeURIComponent(agentId)}/policies?policyId=${encodeURIComponent(policyId)}`,
340
+ {
341
+ auth: "org"
342
+ }
343
+ );
294
344
  }
295
345
  async createSdkKey(agentId, params) {
296
- return this.request("POST", `/api/agents/${agentId}/sdk-keys`, {
346
+ return this.request("POST", `/api/agents/${encodeURIComponent(agentId)}/sdk-keys`, {
297
347
  body: params,
298
348
  auth: "org"
299
349
  });
300
350
  }
301
351
  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" });
352
+ return this.request("POST", `/api/wallets/${encodeURIComponent(walletId)}/faucet`, { auth: "org" });
306
353
  }
307
354
  // ── SDK Agent APIs (used by CLI commands) ──
308
- /** GET /api/sdk/setup: full diagnostic snapshot for the authenticated key. */
309
355
  async getSetup() {
310
356
  return this.request("GET", "/api/sdk/setup");
311
357
  }
@@ -356,10 +402,10 @@ var ApiClient = class {
356
402
  return this.request("POST", "/api/sdk/payments/request", { body: params });
357
403
  }
358
404
  async executePayment(requestId) {
359
- return this.request("POST", `/api/sdk/payments/${requestId}/execute`, { body: {} });
405
+ return this.request("POST", `/api/sdk/payments/${encodeURIComponent(requestId)}/execute`, { body: {} });
360
406
  }
361
407
  async getPaymentStatus(requestId) {
362
- return this.request("GET", `/api/sdk/payments/${requestId}`);
408
+ return this.request("GET", `/api/sdk/payments/${encodeURIComponent(requestId)}`);
363
409
  }
364
410
  async getTransactions(params) {
365
411
  const query = new URLSearchParams();
@@ -369,7 +415,7 @@ var ApiClient = class {
369
415
  return this.request("GET", `/api/sdk/transactions${qs}`);
370
416
  }
371
417
  async getTransaction(id) {
372
- return this.request("GET", `/api/sdk/transactions/${id}`);
418
+ return this.request("GET", `/api/sdk/transactions/${encodeURIComponent(id)}`);
373
419
  }
374
420
  async getPolicies() {
375
421
  return this.request("GET", "/api/sdk/policies");
@@ -414,14 +460,18 @@ async function readRequestBody(req) {
414
460
  async function parseCallbackPayload(req) {
415
461
  const url = new URL(req.url || "/", "http://127.0.0.1");
416
462
  let params = url.searchParams;
417
- if (req.method === "POST") {
463
+ const isPost = req.method === "POST";
464
+ if (isPost) {
418
465
  const rawBody = await readRequestBody(req);
419
466
  params = new URLSearchParams(rawBody);
420
467
  }
421
468
  return {
422
- orgApiKey: params.get("token"),
469
+ // The org API key is a secret. Accept it only from the POST body so it
470
+ // never transits a GET query string (query strings leak into browser
471
+ // history, proxy logs, and Referer headers). Ignore any ?token= on GET.
472
+ orgApiKey: isPost ? params.get("token") : null,
423
473
  organizationName: params.get("org") || "",
424
- userId: params.get("userId") || "",
474
+ expiresAt: params.get("expiresAt") || "",
425
475
  error: params.get("error"),
426
476
  returnedState: params.get("state")
427
477
  };
@@ -449,7 +499,7 @@ async function browserAuth(baseUrl) {
449
499
  res.end(getErrorHtml("Unsupported callback method"));
450
500
  return;
451
501
  }
452
- const { orgApiKey, organizationName, userId, error, returnedState } = await parseCallbackPayload(req);
502
+ const { orgApiKey, organizationName, expiresAt, error, returnedState } = await parseCallbackPayload(req);
453
503
  if (returnedState !== state) {
454
504
  res.writeHead(400, { "Content-Type": "text/html" });
455
505
  res.end(getErrorHtml("Invalid authentication state"));
@@ -475,7 +525,7 @@ async function browserAuth(baseUrl) {
475
525
  res.end(getSuccessHtml());
476
526
  clearTimeout(timeout);
477
527
  server.close();
478
- resolve({ orgApiKey, organizationName, userId });
528
+ resolve({ orgApiKey, organizationName, expiresAt });
479
529
  })().catch((error) => {
480
530
  res.writeHead(500, { "Content-Type": "text/html" });
481
531
  res.end(getErrorHtml("Authentication callback failed"));
@@ -536,26 +586,44 @@ function getErrorHtml(error) {
536
586
  var HEADLESS_DEFAULT_NAME = "conto-agent";
537
587
  var HEADLESS_DEFAULT_TYPE = "CUSTOM";
538
588
  var HEADLESS_DEFAULT_LIMIT = 500;
589
+ function failInit(message, details = {}) {
590
+ if (isJsonMode()) {
591
+ printJson({ ok: false, error: message, ...details });
592
+ } else {
593
+ printError(message);
594
+ }
595
+ process.exit(1);
596
+ }
597
+ function initSpinner() {
598
+ if (!isJsonMode()) return p.spinner();
599
+ return {
600
+ start() {
601
+ },
602
+ stop() {
603
+ },
604
+ message() {
605
+ }
606
+ };
607
+ }
539
608
  async function runInit(options = {}) {
540
609
  if (options.sandbox) {
541
610
  await runSandboxInit(options);
542
611
  return;
543
612
  }
544
613
  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)"
614
+ const providedOrgApiKey = options.apiKey || process.env.CONTO_ORG_API_KEY;
615
+ if (!interactive && !providedOrgApiKey) {
616
+ failInit(
617
+ [
618
+ "create-conto-agent needs an interactive terminal for the setup wizard.",
619
+ "Headless options: --sandbox, or --api-key <org-api-key>.",
620
+ "Add --json for machine-readable output."
621
+ ].join(" "),
622
+ { headlessOptions: ["--sandbox", "--api-key <org-api-key>"] }
550
623
  );
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
624
  }
557
625
  printBanner();
558
- const baseUrl = options.baseUrl || "https://conto.finance";
626
+ const baseUrl = options.baseUrl || process.env.CONTO_BASE_URL || "https://conto.finance";
559
627
  const agentName = options.name || (interactive ? await p.text({
560
628
  message: "Agent name",
561
629
  placeholder: "my-procurement-bot",
@@ -570,7 +638,6 @@ async function runInit(options = {}) {
570
638
  options: [
571
639
  { value: "ANTHROPIC_CLAUDE", label: "Claude" },
572
640
  { value: "OPENAI_ASSISTANT", label: "OpenAI" },
573
- { value: "LANGCHAIN", label: "LangChain" },
574
641
  { value: "AUTOGPT", label: "AutoGPT" },
575
642
  { value: "CUSTOM", label: "Custom" }
576
643
  ]
@@ -593,85 +660,79 @@ async function runInit(options = {}) {
593
660
  p.cancel("Setup cancelled.");
594
661
  process.exit(0);
595
662
  }
596
- const s0 = p.spinner();
663
+ const s0 = initSpinner();
597
664
  s0.start("Fetching supported networks...");
598
665
  const { chains: availableChains, defaultChainId } = await fetchChains(baseUrl);
599
666
  s0.stop(`Found ${Object.keys(availableChains).length} networks`);
600
667
  const chainChoices = getChainChoices(availableChains);
601
- const selectedChain = options.chain || (interactive ? await p.select({
668
+ const selectedChain = options.chain || process.env.CONTO_CHAIN_ID || (interactive ? await p.select({
602
669
  message: "Network",
603
- options: chainChoices
670
+ options: chainChoices,
671
+ initialValue: defaultChainId
604
672
  }) : defaultChainId);
605
673
  if (p.isCancel(selectedChain)) {
606
674
  p.cancel("Setup cancelled.");
607
675
  process.exit(0);
608
676
  }
609
- const chain = availableChains[selectedChain] || availableChains[defaultChainId];
677
+ const selectedChainId = String(selectedChain);
678
+ const chain = availableChains[selectedChainId];
679
+ if (!chain) {
680
+ failInit(`Unknown chain "${selectedChainId}". Choose a chain ID returned by /api/chains.`, {
681
+ availableChainIds: Object.keys(availableChains)
682
+ });
683
+ }
684
+ if (!chain.testnet && !options.confirmMainnet) {
685
+ if (!interactive) {
686
+ failInit(
687
+ `Chain ${chain.chainId} (${chain.name}) is a mainnet and can move real funds. Re-run with --confirm-mainnet after reviewing the network and limits.`,
688
+ { chainId: chain.chainId, requiresConfirmation: "--confirm-mainnet" }
689
+ );
690
+ }
691
+ const confirmed = await p.confirm({
692
+ message: `${chain.name} is a real-money network. Continue with mainnet provisioning?`,
693
+ initialValue: false
694
+ });
695
+ if (p.isCancel(confirmed) || !confirmed) {
696
+ p.cancel("Setup cancelled before any mainnet resources were created.");
697
+ process.exit(0);
698
+ }
699
+ }
610
700
  const limit = typeof dailyLimit === "string" ? Number(dailyLimit) : dailyLimit;
611
- const s = p.spinner();
701
+ const s = initSpinner();
612
702
  let orgApiKey;
613
- if (options.apiKey) {
614
- orgApiKey = options.apiKey;
703
+ let orgApiKeyExpiresAt;
704
+ if (providedOrgApiKey) {
705
+ orgApiKey = providedOrgApiKey;
615
706
  printSuccess("Using provided organization API key");
616
707
  } else {
617
708
  s.start("Opening browser to authenticate...");
618
709
  try {
619
710
  const authResult = await browserAuth(baseUrl);
620
711
  orgApiKey = authResult.orgApiKey;
712
+ orgApiKeyExpiresAt = authResult.expiresAt || void 0;
621
713
  s.stop("Authenticated");
622
714
  printSuccess("Account connected");
623
715
  } catch (err) {
624
716
  s.stop("Authentication failed");
625
- printError(err instanceof Error ? err.message : "Authentication failed");
626
- process.exit(1);
717
+ failInit(err instanceof Error ? err.message : "Authentication failed");
627
718
  }
628
719
  }
629
720
  const api = new ApiClient({ baseUrl, orgApiKey });
630
- s.start(`Provisioning wallet on ${chain.name}...`);
721
+ s.start(`Creating wallet on ${chain.name}...`);
631
722
  let wallet;
632
723
  try {
633
724
  wallet = await api.createWallet({
634
725
  name: `${agentName} Wallet`,
635
726
  chainType: chain.chainType,
636
- chainId: chain.chainId
727
+ chainId: chain.chainId,
728
+ custodyMode: "MANAGED"
637
729
  });
638
730
  } 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
- }
731
+ s.stop("Wallet creation failed");
732
+ failInit(err instanceof Error ? err.message : "Failed to create wallet");
674
733
  }
734
+ s.stop(`Wallet created on ${chain.name}`);
735
+ printSuccess(`Wallet: ${wallet.address} (${wallet.custodyMode} custody)`);
675
736
  if (chain.faucetAvailable) {
676
737
  s.start("Requesting testnet funds from faucet...");
677
738
  try {
@@ -687,20 +748,21 @@ async function runInit(options = {}) {
687
748
  printInfo(err instanceof Error ? err.message : "Faucet unavailable");
688
749
  }
689
750
  }
751
+ const agentEnvironment = chain.testnet ? "DEV" : "PROD";
690
752
  s.start(`Registering agent "${agentName}"...`);
691
753
  let agent;
692
754
  try {
693
755
  agent = await api.createAgent({
694
756
  name: agentName,
695
757
  agentType,
696
- description: `Created via CLI quickstart`
758
+ description: `Created via CLI quickstart`,
759
+ environment: agentEnvironment
697
760
  });
698
761
  s.stop("Agent registered");
699
- printSuccess(`Agent "${agent.name}" created`);
762
+ printSuccess(`Agent "${agent.name}" created (${agent.environment ?? agentEnvironment})`);
700
763
  } catch (err) {
701
764
  s.stop("Agent creation failed");
702
- printError(err instanceof Error ? err.message : "Failed to create agent");
703
- process.exit(1);
765
+ failInit(err instanceof Error ? err.message : "Failed to create agent");
704
766
  }
705
767
  s.start("Linking wallet to agent...");
706
768
  try {
@@ -714,8 +776,7 @@ async function runInit(options = {}) {
714
776
  printSuccess(`Wallet linked ($${limit}/day limit)`);
715
777
  } catch (err) {
716
778
  s.stop("Wallet linking failed");
717
- printError(err instanceof Error ? err.message : "Failed to link wallet");
718
- process.exit(1);
779
+ failInit(err instanceof Error ? err.message : "Failed to link wallet");
719
780
  }
720
781
  s.start("Creating default spending policy...");
721
782
  try {
@@ -727,7 +788,10 @@ async function runInit(options = {}) {
727
788
  rules: [
728
789
  {
729
790
  ruleType: "DAILY_LIMIT",
730
- operator: "LESS_THAN_OR_EQUAL",
791
+ // Canonical operator accepted by the strict enum at POST /api/policies
792
+ // (src/lib/schemas/common.ts ruleOperatorSchema). The `LESS_THAN_OR_EQUAL`
793
+ // alias is rejected there (400), which the catch below would silently swallow.
794
+ operator: "LTE",
731
795
  value: String(limit),
732
796
  action: "ALLOW"
733
797
  }
@@ -757,13 +821,13 @@ async function runInit(options = {}) {
757
821
  }
758
822
  } catch (err) {
759
823
  s.stop("SDK key generation failed");
760
- printError(err instanceof Error ? err.message : "Failed to create SDK key");
761
- process.exit(1);
824
+ failInit(err instanceof Error ? err.message : "Failed to create SDK key");
762
825
  }
763
826
  const cwd = process.cwd();
827
+ ensureEnvLocalGitignored(cwd);
764
828
  writeEnvLocal(cwd, [
765
829
  "# Conto Agent Configuration",
766
- "# Generated by: npx create-conto-agent",
830
+ "# Generated by: npx @conto_finance/create-conto-agent",
767
831
  "",
768
832
  "# SDK Authentication",
769
833
  ["CONTO_API_KEY", sdkKey.key],
@@ -791,7 +855,7 @@ async function runInit(options = {}) {
791
855
  type: agentType
792
856
  },
793
857
  network: {
794
- chain: selectedChain,
858
+ chain: selectedChainId,
795
859
  chainId: chain.chainId,
796
860
  rpcUrl: chain.rpcUrl,
797
861
  explorerUrl: chain.explorerUrl,
@@ -801,7 +865,7 @@ async function runInit(options = {}) {
801
865
  wallet: {
802
866
  id: wallet.id,
803
867
  address: wallet.address,
804
- custodyType: wallet.custodyType
868
+ custodyMode: wallet.custodyMode
805
869
  },
806
870
  server: {
807
871
  baseUrl
@@ -811,15 +875,15 @@ async function runInit(options = {}) {
811
875
  saveGlobalConfig({
812
876
  agent: { id: agent.id, name: agent.name, type: agentType },
813
877
  network: {
814
- chain: selectedChain,
878
+ chain: selectedChainId,
815
879
  chainId: chain.chainId,
816
880
  rpcUrl: chain.rpcUrl,
817
881
  explorerUrl: chain.explorerUrl,
818
882
  currency: chain.currency,
819
883
  testnet: chain.testnet
820
884
  },
821
- wallet: { id: wallet.id, address: wallet.address, custodyType: wallet.custodyType },
822
- server: { baseUrl, apiKey: sdkKey.key, orgApiKey }
885
+ wallet: { id: wallet.id, address: wallet.address, custodyMode: wallet.custodyMode },
886
+ server: { baseUrl, apiKey: sdkKey.key, orgApiKey, orgApiKeyExpiresAt }
823
887
  });
824
888
  let cliResolves = false;
825
889
  if (hasLocalCliBin(cwd)) {
@@ -839,19 +903,47 @@ async function runInit(options = {}) {
839
903
  s.stop("CLI install failed (continuing)");
840
904
  }
841
905
  }
906
+ const cli = cliResolves ? "npx conto" : "npx @conto_finance/create-conto-agent";
907
+ const nextSteps = [
908
+ `${cli} doctor`,
909
+ "node example.mjs",
910
+ `${cli} pay <address> <amount>`,
911
+ `${cli} mcp`
912
+ ];
913
+ if (isJsonMode()) {
914
+ printJson({
915
+ ok: true,
916
+ mode: "organization",
917
+ baseUrl,
918
+ agent,
919
+ wallet,
920
+ network: {
921
+ chainId: chain.chainId,
922
+ name: chain.name,
923
+ currency: chain.currency,
924
+ testnet: chain.testnet
925
+ },
926
+ credentials: {
927
+ storedIn: ".env.local",
928
+ sdkKeyEnv: "CONTO_API_KEY"
929
+ },
930
+ files: [".env.local", ".gitignore", "conto.config.json", "example.mjs"],
931
+ nextSteps
932
+ });
933
+ return;
934
+ }
842
935
  console.log("");
843
936
  console.log(chalk.green.bold(" Your agent is ready!") + " Files written:\n");
844
937
  console.log(` ${chalk.bold(".env.local")} - SDK key + config`);
845
938
  console.log(` ${chalk.bold("conto.config.json")} - Agent metadata`);
846
- console.log(` ${chalk.bold("example.ts")} - Runnable payment example`);
939
+ console.log(` ${chalk.bold("example.mjs")} - Runnable payment example`);
847
940
  console.log("");
848
941
  console.log(
849
- ` ${chalk.dim("Wallet:")} ${wallet.address} (${chain.name}${chain.testnet ? " testnet" : ""}, ${wallet.custodyType} custody)`
942
+ ` ${chalk.dim("Wallet:")} ${wallet.address} (${chain.name}${chain.testnet ? " testnet" : ""}, ${wallet.custodyMode} custody)`
850
943
  );
851
944
  console.log(` ${chalk.dim("Currency:")} ${chain.currency}`);
852
945
  console.log(` ${chalk.dim("Explorer:")} ${chain.explorerUrl}`);
853
946
  console.log("");
854
- const cli = cliResolves ? "npx conto" : "npx @conto_finance/create-conto-agent";
855
947
  console.log(chalk.bold(" Next steps:"));
856
948
  let step = 1;
857
949
  console.log(` ${step++}. Verify setup: ${chalk.cyan(`${cli} doctor`)}`);
@@ -860,7 +952,7 @@ async function runInit(options = {}) {
860
952
  ` ${step++}. Fund your wallet with ${chain.currency} ${chalk.dim("\u2192")} ${wallet.address}`
861
953
  );
862
954
  }
863
- console.log(` ${step++}. Run the example: ${chalk.cyan("npx tsx example.ts")}`);
955
+ console.log(` ${step++}. Run the example: ${chalk.cyan("node example.mjs")}`);
864
956
  console.log(` ${step++}. Make a payment: ${chalk.cyan(`${cli} pay <address> <amount>`)}`);
865
957
  console.log(` ${step++}. Connect Claude: ${chalk.cyan(`${cli} mcp`)}`);
866
958
  if (!cliResolves) {
@@ -920,9 +1012,10 @@ async function runSandboxInit(options) {
920
1012
  chain = void 0;
921
1013
  }
922
1014
  const cwd = process.cwd();
1015
+ ensureEnvLocalGitignored(cwd);
923
1016
  writeEnvLocal(cwd, [
924
1017
  "# Conto Agent Configuration (anonymous test-mode sandbox)",
925
- "# Generated by: npx create-conto-agent --sandbox",
1018
+ "# Generated by: npx @conto_finance/create-conto-agent --sandbox",
926
1019
  "",
927
1020
  "# SDK Authentication",
928
1021
  ["CONTO_API_KEY", sandbox.credentials.sdkKey],
@@ -947,8 +1040,7 @@ async function runSandboxInit(options) {
947
1040
  "",
948
1041
  "# Sandbox (shown once, keep private)",
949
1042
  ["CONTO_SANDBOX_API_KEY", sandbox.credentials.apiKey],
950
- ["CONTO_SANDBOX_EXPIRES_AT", sandbox.expiresAt],
951
- ["CONTO_SANDBOX_EXECUTION", "simulated"]
1043
+ ["CONTO_SANDBOX_EXPIRES_AT", sandbox.expiresAt]
952
1044
  ]);
953
1045
  writeContoConfig(cwd, {
954
1046
  agent: {
@@ -967,15 +1059,14 @@ async function runSandboxInit(options) {
967
1059
  wallet: {
968
1060
  id: sandbox.wallet.id,
969
1061
  address: sandbox.wallet.address,
970
- custodyType: sandbox.wallet.custodyType
1062
+ custodyMode: sandbox.wallet.custodyMode
971
1063
  },
972
1064
  server: {
973
1065
  baseUrl
974
1066
  },
975
1067
  sandbox: {
976
1068
  mode: "test",
977
- expiresAt: sandbox.expiresAt,
978
- execution: "simulated"
1069
+ expiresAt: sandbox.expiresAt
979
1070
  }
980
1071
  });
981
1072
  writeExampleFile(cwd);
@@ -996,7 +1087,7 @@ async function runSandboxInit(options) {
996
1087
  wallet: {
997
1088
  id: sandbox.wallet.id,
998
1089
  address: sandbox.wallet.address,
999
- custodyType: sandbox.wallet.custodyType
1090
+ custodyMode: sandbox.wallet.custodyMode
1000
1091
  },
1001
1092
  server: {
1002
1093
  baseUrl,
@@ -1005,8 +1096,7 @@ async function runSandboxInit(options) {
1005
1096
  },
1006
1097
  sandbox: {
1007
1098
  mode: "test",
1008
- expiresAt: sandbox.expiresAt,
1009
- execution: "simulated"
1099
+ expiresAt: sandbox.expiresAt
1010
1100
  }
1011
1101
  });
1012
1102
  let cliResolves = hasLocalCliBin(cwd);
@@ -1020,16 +1110,23 @@ async function runSandboxInit(options) {
1020
1110
  mode: "sandbox",
1021
1111
  baseUrl,
1022
1112
  expiresAt: sandbox.expiresAt,
1023
- execution: "simulated",
1024
1113
  organization: sandbox.organization,
1025
1114
  agent: sandbox.agent,
1026
1115
  wallet: sandbox.wallet,
1027
- credentials: { ...sandbox.credentials, shownOnce: true },
1028
- files: [".env.local", "conto.config.json", "example.ts"],
1029
- claim: sandbox.claim ?? null,
1116
+ credentials: {
1117
+ storedIn: ".env.local",
1118
+ sdkKeyEnv: "CONTO_API_KEY",
1119
+ sandboxApiKeyEnv: "CONTO_SANDBOX_API_KEY"
1120
+ },
1121
+ files: [".env.local", ".gitignore", "conto.config.json", "example.mjs"],
1122
+ claim: sandbox.claim ? {
1123
+ method: sandbox.claim.method,
1124
+ endpoint: sandbox.claim.endpoint,
1125
+ credentialEnv: "CONTO_SANDBOX_API_KEY"
1126
+ } : null,
1030
1127
  nextSteps: [
1031
- "npx tsx example.ts",
1032
- "npx tsx example.ts --execute",
1128
+ "node example.mjs",
1129
+ "node example.mjs --execute",
1033
1130
  `${cli} doctor`,
1034
1131
  `${cli} pay 0x742d35Cc6634C0532925a3b844Bc454e4438f44e 1 --purpose test`
1035
1132
  ]
@@ -1040,13 +1137,13 @@ async function runSandboxInit(options) {
1040
1137
  console.log(chalk.green.bold(" Sandbox agent ready!") + " Files written:\n");
1041
1138
  console.log(` ${chalk.bold(".env.local")} - SDK key + config (shown once)`);
1042
1139
  console.log(` ${chalk.bold("conto.config.json")} - Agent metadata`);
1043
- console.log(` ${chalk.bold("example.ts")} - Runnable payment example`);
1140
+ console.log(` ${chalk.bold("example.mjs")} - Runnable payment example`);
1044
1141
  console.log("");
1045
1142
  console.log(
1046
1143
  ` ${chalk.dim("Wallet:")} ${sandbox.wallet.address} (${chain?.name || sandbox.wallet.chainId}, test mode)`
1047
1144
  );
1048
1145
  console.log(
1049
- ` ${chalk.dim("Balance:")} ${sandbox.wallet.balance} ${sandbox.wallet.currency} (simulated)`
1146
+ ` ${chalk.dim("Balance:")} ${sandbox.wallet.balance} ${sandbox.wallet.currency} (test balance)`
1050
1147
  );
1051
1148
  console.log(
1052
1149
  ` ${chalk.dim("Limits:")} $${sandbox.wallet.limits.perTransaction}/tx, $${sandbox.wallet.limits.daily}/day`
@@ -1054,12 +1151,12 @@ async function runSandboxInit(options) {
1054
1151
  console.log(` ${chalk.dim("Expires:")} ${sandbox.expiresAt}`);
1055
1152
  console.log("");
1056
1153
  console.log(chalk.bold(" Next steps:"));
1057
- console.log(` 1. Run the example: ${chalk.cyan("npx tsx example.ts")}`);
1058
- console.log(` 2. Execute it: ${chalk.cyan("npx tsx example.ts --execute")}`);
1154
+ console.log(` 1. Run the example: ${chalk.cyan("node example.mjs")}`);
1155
+ console.log(` 2. Execute it: ${chalk.cyan("node example.mjs --execute")}`);
1059
1156
  console.log(` 3. Verify setup: ${chalk.cyan(`${cli} doctor`)}`);
1060
1157
  console.log("");
1061
1158
  printInfo(
1062
- "Sandbox payments execute in simulated mode: policy checks, receipts, and spend tracking are real; no onchain transfer happens."
1159
+ "Sandbox test payments exercise policy checks, receipts, and spend tracking without an onchain transfer."
1063
1160
  );
1064
1161
  printInfo("To keep this sandbox, sign in at conto.finance and claim it before it expires.");
1065
1162
  console.log("");
@@ -1112,13 +1209,15 @@ function writeExampleFile(dir) {
1112
1209
  const content = `// Conto quickstart example, generated by create-conto-agent.
1113
1210
  //
1114
1211
  // Usage:
1115
- // npx tsx example.ts Check setup and request a test payment (no funds move)
1116
- // npx tsx example.ts --execute Also execute the payment if it is approved
1212
+ // node example.mjs Check setup and request a test payment (no funds move)
1213
+ // node example.mjs --execute Also execute the payment if it is approved
1117
1214
  //
1118
1215
  // Reads CONTO_API_KEY and CONTO_BASE_URL from .env.local in this directory.
1119
1216
  // Docs: https://conto.finance/docs
1120
1217
 
1121
1218
  import { readFileSync } from 'fs';
1219
+ import { randomUUID } from 'node:crypto';
1220
+ let lastRequestId;
1122
1221
  try {
1123
1222
  for (const line of readFileSync('.env.local', 'utf-8').split('\\n')) {
1124
1223
  const match = line.match(/^([A-Z_][A-Z0-9_]*)=(.*)$/);
@@ -1128,20 +1227,23 @@ try {
1128
1227
 
1129
1228
  const BASE_URL = process.env.CONTO_BASE_URL || 'https://conto.finance';
1130
1229
  const API_KEY = process.env.CONTO_API_KEY;
1230
+ const IS_SANDBOX = Boolean(process.env.CONTO_SANDBOX_EXPIRES_AT);
1131
1231
  const EXECUTE = process.argv.includes('--execute');
1132
1232
 
1133
1233
  if (!API_KEY) {
1134
- console.error('Missing CONTO_API_KEY in .env.local. Run: npx create-conto-agent');
1234
+ console.error('Missing CONTO_API_KEY in .env.local. Run: npx @conto_finance/create-conto-agent');
1135
1235
  process.exit(1);
1136
1236
  }
1137
1237
 
1138
- async function api(method: string, path: string, body?: unknown) {
1238
+ async function api(method, path, body) {
1139
1239
  const res = await fetch(\`\${BASE_URL}\${path}\`, {
1140
1240
  method,
1141
1241
  headers: { Authorization: \`Bearer \${API_KEY}\`, 'Content-Type': 'application/json' },
1142
1242
  body: body ? JSON.stringify(body) : undefined,
1143
1243
  });
1144
1244
  const data = await res.json();
1245
+ if (data.requestId) lastRequestId = data.requestId;
1246
+ if (!res.ok && data.actionUrl) console.error('Complete action:', data.actionUrl);
1145
1247
  if (!res.ok) throw new Error(data.error || \`\${method} \${path} failed (\${res.status})\`);
1146
1248
  return data;
1147
1249
  }
@@ -1155,27 +1257,32 @@ async function main() {
1155
1257
  console.log(\`Wallet: \${w.address}\`);
1156
1258
  console.log(\` Chain: \${w.chainName} (\${w.chainId})\${w.isTestnet ? ' testnet' : ''}\`);
1157
1259
  const executionLabel =
1158
- w.executionMode === 'managed'
1159
- ? 'managed execution'
1160
- : w.executionMode === 'simulated'
1161
- ? 'simulated execution'
1162
- : w.executionMode === 'manual'
1163
- ? 'manual execution'
1164
- : '';
1165
- console.log(\` Custody: \${w.custodyType}\${executionLabel ? \` (\${executionLabel})\` : ''}\`);
1260
+ IS_SANDBOX
1261
+ ? 'sandbox test mode'
1262
+ : w.custodyMode === 'MANAGED'
1263
+ ? 'managed execution'
1264
+ : 'external execution';
1265
+ console.log(\` Custody: \${w.custodyMode}\${executionLabel ? \` (\${executionLabel})\` : ''}\`);
1166
1266
  console.log(\` Balance: \${w.balance} \${w.currency}\`);
1167
1267
  console.log(\` Daily: \${w.spent?.today ?? 0} / \${w.limits?.daily ?? 'unlimited'}\\n\`);
1168
1268
  }
1169
1269
 
1270
+ const wallet = (setup.wallets || []).find((w) => String(w.chainId) === '42431');
1271
+ if (!wallet) throw new Error('This example requires a Tempo Testnet wallet (42431).');
1272
+
1170
1273
  // 2. Request a payment. The policy engine evaluates it and returns
1171
1274
  // APPROVED, DENIED, or REQUIRES_APPROVAL. No funds move on request.
1172
1275
  console.log('Requesting a $0.01 test payment...');
1173
1276
  const request = await api('POST', '/api/sdk/payments/request', {
1174
1277
  amount: 0.01,
1278
+ walletId: wallet.id,
1279
+ idempotencyKey: randomUUID(),
1175
1280
  recipientAddress: '0x0000000000000000000000000000000000000001',
1176
1281
  purpose: 'Test payment from CLI quickstart',
1177
1282
  category: 'TESTING',
1178
1283
  });
1284
+ lastRequestId = request.requestId;
1285
+ console.log('Request ID:', lastRequestId);
1179
1286
  console.log(\`Policy decision: \${request.status}\`);
1180
1287
  if (request.reasons?.length) console.log(\`Reasons: \${request.reasons.join(', ')}\`);
1181
1288
 
@@ -1196,21 +1303,25 @@ async function main() {
1196
1303
  // quickstart includes the payments:execute scope.
1197
1304
  if (!EXECUTE) {
1198
1305
  console.log(\`\\nApproved (request \${request.requestId}). No funds moved.\`);
1199
- console.log('Re-run with --execute to send it, or use: npx conto pay <address> <amount>');
1306
+ console.log('Re-run with --execute to send it, or use: npx @conto_finance/create-conto-agent pay <address> <amount>');
1200
1307
  return;
1201
1308
  }
1202
1309
  const result = await api('POST', \`/api/sdk/payments/\${request.requestId}/execute\`);
1203
- console.log(\`\\nPayment sent\${result.simulated ? ' (simulated, no onchain transfer)' : ''}.\`);
1204
- console.log(\`TX hash: \${result.txHash}\`);
1205
- console.log(\`Explorer: \${result.explorerUrl}\`);
1310
+ console.log(IS_SANDBOX ? '\\nPayment recorded in sandbox test mode.' : '\\nPayment sent.');
1311
+ console.log('Status:', result.status);
1312
+ console.log('Settlement mode:', result.receipt?.settlementMode);
1313
+ if (result.receipt?.txHash) console.log('TX hash:', result.receipt.txHash);
1314
+ if (result.receipt?.explorerUrl) console.log('Explorer:', result.receipt.explorerUrl);
1315
+ console.log('Check settlement with GET /api/sdk/payments/' + lastRequestId);
1206
1316
  }
1207
1317
 
1208
1318
  main().catch((err) => {
1209
1319
  console.error(err instanceof Error ? err.message : err);
1320
+ if (lastRequestId) console.error('Do not repeat execution. Check GET /api/sdk/payments/' + lastRequestId);
1210
1321
  process.exit(1);
1211
1322
  });
1212
1323
  `;
1213
- fs.writeFileSync(path.join(dir, "example.ts"), content);
1324
+ fs.writeFileSync(path.join(dir, "example.mjs"), content);
1214
1325
  }
1215
1326
 
1216
1327
  export {