@conto_finance/create-conto-agent 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,11 @@
1
+ import {
2
+ ensureContoDirGitignored,
3
+ ensureEnvLocalGitignored,
4
+ loadProjectEnv,
5
+ saveGlobalConfig,
6
+ writeEnvLocal,
7
+ writeSandboxSetupEnv
8
+ } from "./chunk-RQ4PUBL7.js";
1
9
  import {
2
10
  isJsonMode,
3
11
  printBanner,
@@ -8,21 +16,12 @@ import {
8
16
  printPending,
9
17
  printSuccess,
10
18
  printWarning
11
- } from "./chunk-K4LBO234.js";
12
- import {
13
- ensureContoDirGitignored,
14
- ensureEnvLocalGitignored,
15
- loadProjectEnv,
16
- saveGlobalConfig,
17
- writeContoConfig,
18
- writeEnvLocal,
19
- writeSandboxSetupEnv
20
- } from "./chunk-XWUWB3FT.js";
19
+ } from "./chunk-DT5NOLBD.js";
21
20
 
22
21
  // package.json
23
22
  var package_default = {
24
23
  name: "@conto_finance/create-conto-agent",
25
- version: "0.5.0",
24
+ version: "0.6.0",
26
25
  description: "Set up an AI agent with Conto spending controls",
27
26
  bin: {
28
27
  "create-conto-agent": "bin/create-conto-agent.js",
@@ -358,9 +357,9 @@ function getChainChoices(chains) {
358
357
  }));
359
358
  }
360
359
  function chainHint(chain) {
361
- if (chain.testnet) return `Testnet \u2014 free ${chain.currency}, no real funds`;
362
- if (chain.chainId === "4217") return "Mainnet \u2014 real USDC.e and real settlement";
363
- return `${chain.chainType} \u2014 ${chain.currency}`;
360
+ if (chain.testnet) return `Testnet: free ${chain.currency}, no real funds`;
361
+ if (chain.chainId === "4217") return "Mainnet: real USDC.e and real settlement";
362
+ return `${chain.chainType}: ${chain.currency}`;
364
363
  }
365
364
 
366
365
  // src/lib/auth.ts
@@ -405,7 +404,7 @@ async function parseCallbackPayload(req) {
405
404
  returnedState: params.get("state")
406
405
  };
407
406
  }
408
- async function browserAuth(baseUrl) {
407
+ async function browserAuth(baseUrl, onAuthUrl) {
409
408
  return new Promise((resolve, reject) => {
410
409
  const state = randomBytes(16).toString("hex");
411
410
  const timeout = setTimeout(
@@ -472,6 +471,7 @@ async function browserAuth(baseUrl) {
472
471
  }
473
472
  const callbackUrl = `http://127.0.0.1:${address.port}/callback`;
474
473
  const authUrl = `${baseUrl}/cli-auth?callback=${encodeURIComponent(callbackUrl)}&state=${encodeURIComponent(state)}`;
474
+ onAuthUrl?.(authUrl);
475
475
  open(authUrl).catch(() => {
476
476
  });
477
477
  });
@@ -511,8 +511,181 @@ function getErrorHtml(error) {
511
511
  </html>`;
512
512
  }
513
513
 
514
+ // src/lib/http-json.ts
515
+ var HttpTransportError = class extends Error {
516
+ constructor(failure, code, message) {
517
+ super(message);
518
+ this.failure = failure;
519
+ this.code = code;
520
+ this.name = "HttpTransportError";
521
+ }
522
+ failure;
523
+ code;
524
+ };
525
+ var NOT_SENT_CODES = /* @__PURE__ */ new Set([
526
+ "ECONNREFUSED",
527
+ "ENOTFOUND",
528
+ "EAI_AGAIN",
529
+ "EHOSTUNREACH",
530
+ "ENETUNREACH",
531
+ "ERR_INVALID_URL",
532
+ "CERT_HAS_EXPIRED",
533
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
534
+ "SELF_SIGNED_CERT_IN_CHAIN",
535
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
536
+ "ERR_TLS_CERT_ALTNAME_INVALID"
537
+ ]);
538
+ var SECRET_PATTERNS = [
539
+ [/conto_claim_[A-Za-z0-9]+/g, "conto_claim_[redacted]"],
540
+ [/conto_agent_[A-Za-z0-9]+/g, "conto_agent_[redacted]"],
541
+ [/conto_setup_[A-Za-z0-9]+/g, "conto_setup_[redacted]"],
542
+ [/conto_[A-Fa-f0-9]{16,}/g, "conto_[redacted]"],
543
+ [/(Bearer\s+)\S+/gi, "$1[redacted]"]
544
+ ];
545
+ function redactSecrets(text2) {
546
+ let result = text2;
547
+ for (const [pattern, replacement] of SECRET_PATTERNS) {
548
+ result = result.replace(pattern, replacement);
549
+ }
550
+ return result;
551
+ }
552
+ function isLoopbackHost(hostname) {
553
+ return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]";
554
+ }
555
+ function parseSecureBaseUrl(baseUrl) {
556
+ let parsed;
557
+ try {
558
+ parsed = new URL(baseUrl);
559
+ } catch {
560
+ throw new Error(`Invalid base URL: ${baseUrl}`);
561
+ }
562
+ if (parsed.protocol !== "https:" && !(parsed.protocol === "http:" && isLoopbackHost(parsed.hostname))) {
563
+ throw new Error("Base URL must use https (except for localhost)");
564
+ }
565
+ if (parsed.username || parsed.password) {
566
+ throw new Error("Base URL must not contain credentials");
567
+ }
568
+ return parsed;
569
+ }
570
+ function normalizeBaseUrl(baseUrl) {
571
+ const parsed = new URL(baseUrl);
572
+ const pathname = parsed.pathname.replace(/\/+$/, "");
573
+ return `${parsed.origin}${pathname}`;
574
+ }
575
+ function apiUrl(baseUrl, apiPath) {
576
+ return new URL(`${normalizeBaseUrl(baseUrl)}${apiPath}`);
577
+ }
578
+ function errorCode(error) {
579
+ const cause = error?.cause;
580
+ return typeof cause?.code === "string" ? cause.code : void 0;
581
+ }
582
+ function classifyFetchError(error, callerSignal) {
583
+ const name = error?.name;
584
+ if (callerSignal?.aborted) {
585
+ return new HttpTransportError("aborted", "ABORTED", "The request was cancelled.");
586
+ }
587
+ if (name === "TimeoutError" || name === "AbortError") {
588
+ return new HttpTransportError(
589
+ "unknown",
590
+ "TIMEOUT",
591
+ "The server did not respond in time. The request may still have been processed."
592
+ );
593
+ }
594
+ const code = errorCode(error);
595
+ if (code && NOT_SENT_CODES.has(code)) {
596
+ return new HttpTransportError("not_sent", code, `Could not connect to the server (${code}).`);
597
+ }
598
+ return new HttpTransportError(
599
+ "unknown",
600
+ code || "NETWORK_ERROR",
601
+ `The connection failed${code ? ` (${code})` : ""} before a response arrived. The request may still have been processed.`
602
+ );
603
+ }
604
+ async function requestJson(input) {
605
+ const headers = {
606
+ Accept: "application/json",
607
+ "User-Agent": `create-conto-agent/${CLI_PACKAGE_VERSION}`,
608
+ ...input.headers
609
+ };
610
+ if (input.body !== void 0) headers["Content-Type"] = "application/json";
611
+ if (input.bearer) headers.Authorization = `Bearer ${input.bearer}`;
612
+ const timeoutSignal = AbortSignal.timeout(input.timeoutMs);
613
+ const signal = input.signal ? AbortSignal.any([input.signal, timeoutSignal]) : timeoutSignal;
614
+ let response;
615
+ try {
616
+ response = await fetch(input.url.href, {
617
+ method: input.method,
618
+ headers,
619
+ body: input.body === void 0 ? void 0 : JSON.stringify(input.body),
620
+ redirect: "manual",
621
+ signal
622
+ });
623
+ } catch (error) {
624
+ throw classifyFetchError(error, input.signal);
625
+ }
626
+ if (response.status >= 300 && response.status < 400) {
627
+ await response.body?.cancel().catch(() => void 0);
628
+ throw new HttpTransportError(
629
+ "not_sent",
630
+ "REDIRECT_REFUSED",
631
+ `The server answered with a redirect (HTTP ${response.status}). Credentials are never sent to a redirect target. Check the base URL.`
632
+ );
633
+ }
634
+ const contentType = response.headers.get("content-type") || "";
635
+ if (!contentType.includes("application/json")) {
636
+ await response.body?.cancel().catch(() => void 0);
637
+ return { status: response.status, headers: response.headers, data: void 0, isJson: false };
638
+ }
639
+ try {
640
+ const data = await response.json();
641
+ return { status: response.status, headers: response.headers, data, isJson: true };
642
+ } catch (error) {
643
+ if (input.signal?.aborted) throw classifyFetchError(error, input.signal);
644
+ return { status: response.status, headers: response.headers, data: void 0, isJson: false };
645
+ }
646
+ }
647
+ function retryAfterSeconds(headers, body) {
648
+ const header = headers.get("retry-after");
649
+ if (header) {
650
+ const seconds = Number(header);
651
+ if (Number.isFinite(seconds) && seconds >= 0) return Math.ceil(seconds);
652
+ const date = Date.parse(header);
653
+ if (Number.isFinite(date)) return Math.max(0, Math.ceil((date - Date.now()) / 1e3));
654
+ }
655
+ const hint = body?.retryAfterSeconds;
656
+ if (typeof hint === "number" && Number.isFinite(hint) && hint >= 0) return Math.ceil(hint);
657
+ return void 0;
658
+ }
659
+ function responseErrorMessage(response, fallback) {
660
+ const body = response.data;
661
+ const text2 = typeof body?.error === "string" ? body.error : typeof body?.message === "string" ? body.message : fallback;
662
+ return redactSecrets(text2);
663
+ }
664
+ function responseErrorCode(response, fallback) {
665
+ const code = response.data?.code;
666
+ return typeof code === "string" && /^[A-Z0-9_]{1,64}$/.test(code) ? code : fallback;
667
+ }
668
+
514
669
  // src/lib/api-client.ts
515
- var REQUEST_TIMEOUT_MS = 3e4;
670
+ var REQUEST_TIMEOUT_MS = Number(process.env.CONTO_REQUEST_TIMEOUT_MS) || 3e4;
671
+ var NOTHING_SENT_CODES = /* @__PURE__ */ new Set([
672
+ "EXECUTION_UNAVAILABLE",
673
+ "PAYMENTS_PAUSED",
674
+ "LIVE_PAYMENTS_PAUSED",
675
+ "LIVE_PAYMENT_CAP_EXCEEDED",
676
+ "LIVE_PAYMENT_CAP_UNSUPPORTED_ASSET",
677
+ "LIVE_PAYMENT_CAP_MISCONFIGURED"
678
+ ]);
679
+ var IN_FLIGHT_CODES = /* @__PURE__ */ new Set(["NEEDS_RECONCILIATION", "PAYMENT_PROCESSING"]);
680
+ function paymentCallError(message, code, status, outcomeUnknown, body) {
681
+ return Object.assign(new Error(message), {
682
+ code,
683
+ status,
684
+ outcomeUnknown,
685
+ body,
686
+ details: body?.details
687
+ });
688
+ }
516
689
  function assertSecureBaseUrl(baseUrl) {
517
690
  let parsed;
518
691
  try {
@@ -539,7 +712,7 @@ var ApiClient = class {
539
712
  const authType = options?.auth || "sdk";
540
713
  const token = authType === "org" ? this.orgApiKey : this.apiKey;
541
714
  const headers = {
542
- "Content-Type": "application/json",
715
+ ...options?.body instanceof FormData ? {} : { "Content-Type": "application/json" },
543
716
  "User-Agent": `create-conto-agent/${CLI_PACKAGE_VERSION}`
544
717
  };
545
718
  if (token) {
@@ -551,7 +724,7 @@ var ApiClient = class {
551
724
  const response = await fetch(url, {
552
725
  method,
553
726
  headers,
554
- body: options?.body ? JSON.stringify(options.body) : void 0,
727
+ body: options?.body instanceof FormData ? options.body : options?.body ? JSON.stringify(options.body) : void 0,
555
728
  signal: controller.signal
556
729
  });
557
730
  const contentType = response.headers.get("content-type") || "";
@@ -569,6 +742,7 @@ var ApiClient = class {
569
742
  error.code = data.code || "API_ERROR";
570
743
  error.status = response.status;
571
744
  error.body = data;
745
+ error.details = data.details;
572
746
  throw error;
573
747
  }
574
748
  return data;
@@ -586,6 +760,66 @@ var ApiClient = class {
586
760
  clearTimeout(timeoutId);
587
761
  }
588
762
  }
763
+ /**
764
+ * POST a payment call through requestJson, which refuses redirects and says
765
+ * whether a failed call may have reached the server.
766
+ */
767
+ async paymentPost(path3, body) {
768
+ let response;
769
+ try {
770
+ response = await requestJson({
771
+ url: apiUrl(this.baseUrl, path3),
772
+ method: "POST",
773
+ bearer: this.apiKey,
774
+ body,
775
+ timeoutMs: REQUEST_TIMEOUT_MS
776
+ });
777
+ } catch (err) {
778
+ if (err instanceof HttpTransportError) {
779
+ throw paymentCallError(err.message, err.code, 0, err.failure !== "not_sent");
780
+ }
781
+ throw err;
782
+ }
783
+ if (!response.isJson) {
784
+ throw response.status === 404 ? paymentCallError(`API endpoint not found: ${path3}`, "NOT_FOUND", 404, false) : paymentCallError(
785
+ `API returned non-JSON response (${response.status})`,
786
+ "INVALID_RESPONSE",
787
+ response.status,
788
+ true
789
+ );
790
+ }
791
+ if (response.status >= 400) {
792
+ const code = responseErrorCode(response, "API_ERROR");
793
+ throw paymentCallError(
794
+ responseErrorMessage(response, `API request failed: ${response.status}`),
795
+ code,
796
+ response.status,
797
+ IN_FLIGHT_CODES.has(code) || response.status >= 500 && !NOTHING_SENT_CODES.has(code),
798
+ response.data
799
+ );
800
+ }
801
+ return response.data;
802
+ }
803
+ async spendingDownload(path3, owner = false) {
804
+ const token = owner ? this.orgApiKey : this.apiKey;
805
+ const response = await fetch(
806
+ `${this.baseUrl}/api/${owner ? "spending" : path3.startsWith("purchases") ? "sdk/spending" : "sdk"}/${path3}`,
807
+ {
808
+ headers: { Authorization: `Bearer ${token}` },
809
+ signal: AbortSignal.timeout(3e4),
810
+ redirect: "error"
811
+ }
812
+ );
813
+ if (!response.ok) throw new Error(`Export failed (${response.status}). No file was saved.`);
814
+ return new Uint8Array(await response.arrayBuffer());
815
+ }
816
+ spending(method, path3, body, owner = false) {
817
+ return this.request(
818
+ method,
819
+ `/api/${owner ? "spending" : path3.startsWith("purchases") ? "sdk/spending" : "sdk"}/${path3}`,
820
+ { body, auth: owner ? "org" : "sdk" }
821
+ );
822
+ }
589
823
  async getTestReport(options) {
590
824
  const query = new URLSearchParams({ allowed: options.allowed, denied: options.denied });
591
825
  if (options.review) query.set("review", options.review);
@@ -687,29 +921,29 @@ var ApiClient = class {
687
921
  walletId: w.walletId,
688
922
  walletName: w.name,
689
923
  daily: {
690
- limit: w.limits?.daily ?? 0,
924
+ limit: w.limits?.daily ?? null,
691
925
  spent: w.spent?.today ?? 0,
692
- remaining: w.remaining?.daily ?? 0
926
+ remaining: w.remaining?.daily ?? null
693
927
  },
694
- weekly: w.limits?.weekly ? {
695
- limit: w.limits.weekly,
928
+ weekly: {
929
+ limit: w.limits?.weekly ?? null,
696
930
  spent: w.spent?.thisWeek ?? 0,
697
- remaining: w.remaining?.weekly ?? 0
698
- } : void 0,
699
- monthly: w.limits?.monthly ? {
700
- limit: w.limits.monthly,
931
+ remaining: w.remaining?.weekly ?? null
932
+ },
933
+ monthly: {
934
+ limit: w.limits?.monthly ?? null,
701
935
  spent: w.spent?.thisMonth ?? 0,
702
- remaining: w.remaining?.monthly ?? 0
703
- } : void 0,
704
- perTransaction: w.limits?.perTransaction ?? 0
936
+ remaining: w.remaining?.monthly ?? null
937
+ },
938
+ perTransaction: w.limits?.perTransaction ?? null
705
939
  }))
706
940
  };
707
941
  }
708
942
  async requestPayment(params) {
709
- return this.request("POST", "/api/sdk/payments/request", { body: params });
943
+ return this.paymentPost("/api/sdk/payments/request", params);
710
944
  }
711
945
  async executePayment(requestId) {
712
- return this.request("POST", `/api/sdk/payments/${encodeURIComponent(requestId)}/execute`, { body: {} });
946
+ return this.paymentPost(`/api/sdk/payments/${encodeURIComponent(requestId)}/execute`, {});
713
947
  }
714
948
  async getPaymentStatus(requestId) {
715
949
  return this.request("GET", `/api/sdk/payments/${encodeURIComponent(requestId)}`);
@@ -982,161 +1216,6 @@ function reviewAccessFor(baseUrl, orgApiKey) {
982
1216
  };
983
1217
  }
984
1218
 
985
- // src/lib/http-json.ts
986
- var HttpTransportError = class extends Error {
987
- constructor(failure, code, message) {
988
- super(message);
989
- this.failure = failure;
990
- this.code = code;
991
- this.name = "HttpTransportError";
992
- }
993
- failure;
994
- code;
995
- };
996
- var NOT_SENT_CODES = /* @__PURE__ */ new Set([
997
- "ECONNREFUSED",
998
- "ENOTFOUND",
999
- "EAI_AGAIN",
1000
- "EHOSTUNREACH",
1001
- "ENETUNREACH",
1002
- "ERR_INVALID_URL",
1003
- "CERT_HAS_EXPIRED",
1004
- "DEPTH_ZERO_SELF_SIGNED_CERT",
1005
- "SELF_SIGNED_CERT_IN_CHAIN",
1006
- "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
1007
- "ERR_TLS_CERT_ALTNAME_INVALID"
1008
- ]);
1009
- var SECRET_PATTERNS = [
1010
- [/conto_claim_[A-Za-z0-9]+/g, "conto_claim_[redacted]"],
1011
- [/conto_agent_[A-Za-z0-9]+/g, "conto_agent_[redacted]"],
1012
- [/conto_setup_[A-Za-z0-9]+/g, "conto_setup_[redacted]"],
1013
- [/conto_[A-Fa-f0-9]{16,}/g, "conto_[redacted]"],
1014
- [/(Bearer\s+)\S+/gi, "$1[redacted]"]
1015
- ];
1016
- function redactSecrets(text2) {
1017
- let result = text2;
1018
- for (const [pattern, replacement] of SECRET_PATTERNS) {
1019
- result = result.replace(pattern, replacement);
1020
- }
1021
- return result;
1022
- }
1023
- function isLoopbackHost(hostname) {
1024
- return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]";
1025
- }
1026
- function parseSecureBaseUrl(baseUrl) {
1027
- let parsed;
1028
- try {
1029
- parsed = new URL(baseUrl);
1030
- } catch {
1031
- throw new Error(`Invalid base URL: ${baseUrl}`);
1032
- }
1033
- if (parsed.protocol !== "https:" && !(parsed.protocol === "http:" && isLoopbackHost(parsed.hostname))) {
1034
- throw new Error("Base URL must use https (except for localhost)");
1035
- }
1036
- if (parsed.username || parsed.password) {
1037
- throw new Error("Base URL must not contain credentials");
1038
- }
1039
- return parsed;
1040
- }
1041
- function normalizeBaseUrl(baseUrl) {
1042
- const parsed = new URL(baseUrl);
1043
- const pathname = parsed.pathname.replace(/\/+$/, "");
1044
- return `${parsed.origin}${pathname}`;
1045
- }
1046
- function apiUrl(baseUrl, apiPath) {
1047
- return new URL(`${normalizeBaseUrl(baseUrl)}${apiPath}`);
1048
- }
1049
- function errorCode(error) {
1050
- const cause = error?.cause;
1051
- return typeof cause?.code === "string" ? cause.code : void 0;
1052
- }
1053
- function classifyFetchError(error, callerSignal) {
1054
- const name = error?.name;
1055
- if (callerSignal?.aborted) {
1056
- return new HttpTransportError("aborted", "ABORTED", "The request was cancelled.");
1057
- }
1058
- if (name === "TimeoutError" || name === "AbortError") {
1059
- return new HttpTransportError(
1060
- "unknown",
1061
- "TIMEOUT",
1062
- "The server did not respond in time. The request may still have been processed."
1063
- );
1064
- }
1065
- const code = errorCode(error);
1066
- if (code && NOT_SENT_CODES.has(code)) {
1067
- return new HttpTransportError("not_sent", code, `Could not connect to the server (${code}).`);
1068
- }
1069
- return new HttpTransportError(
1070
- "unknown",
1071
- code || "NETWORK_ERROR",
1072
- `The connection failed${code ? ` (${code})` : ""} before a response arrived. The request may still have been processed.`
1073
- );
1074
- }
1075
- async function requestJson(input) {
1076
- const headers = {
1077
- Accept: "application/json",
1078
- "User-Agent": `create-conto-agent/${CLI_PACKAGE_VERSION}`,
1079
- ...input.headers
1080
- };
1081
- if (input.body !== void 0) headers["Content-Type"] = "application/json";
1082
- if (input.bearer) headers.Authorization = `Bearer ${input.bearer}`;
1083
- const timeoutSignal = AbortSignal.timeout(input.timeoutMs);
1084
- const signal = input.signal ? AbortSignal.any([input.signal, timeoutSignal]) : timeoutSignal;
1085
- let response;
1086
- try {
1087
- response = await fetch(input.url, {
1088
- method: input.method,
1089
- headers,
1090
- body: input.body === void 0 ? void 0 : JSON.stringify(input.body),
1091
- redirect: "manual",
1092
- signal
1093
- });
1094
- } catch (error) {
1095
- throw classifyFetchError(error, input.signal);
1096
- }
1097
- if (response.status >= 300 && response.status < 400) {
1098
- await response.body?.cancel().catch(() => void 0);
1099
- throw new HttpTransportError(
1100
- "not_sent",
1101
- "REDIRECT_REFUSED",
1102
- `The server answered with a redirect (HTTP ${response.status}). Credentials are never sent to a redirect target. Check the base URL.`
1103
- );
1104
- }
1105
- const contentType = response.headers.get("content-type") || "";
1106
- if (!contentType.includes("application/json")) {
1107
- await response.body?.cancel().catch(() => void 0);
1108
- return { status: response.status, headers: response.headers, data: void 0, isJson: false };
1109
- }
1110
- try {
1111
- const data = await response.json();
1112
- return { status: response.status, headers: response.headers, data, isJson: true };
1113
- } catch (error) {
1114
- if (input.signal?.aborted) throw classifyFetchError(error, input.signal);
1115
- return { status: response.status, headers: response.headers, data: void 0, isJson: false };
1116
- }
1117
- }
1118
- function retryAfterSeconds(headers, body) {
1119
- const header = headers.get("retry-after");
1120
- if (header) {
1121
- const seconds = Number(header);
1122
- if (Number.isFinite(seconds) && seconds >= 0) return Math.ceil(seconds);
1123
- const date = Date.parse(header);
1124
- if (Number.isFinite(date)) return Math.max(0, Math.ceil((date - Date.now()) / 1e3));
1125
- }
1126
- const hint = body?.retryAfterSeconds;
1127
- if (typeof hint === "number" && Number.isFinite(hint) && hint >= 0) return Math.ceil(hint);
1128
- return void 0;
1129
- }
1130
- function responseErrorMessage(response, fallback) {
1131
- const body = response.data;
1132
- const text2 = typeof body?.error === "string" ? body.error : typeof body?.message === "string" ? body.message : fallback;
1133
- return redactSecrets(text2);
1134
- }
1135
- function responseErrorCode(response, fallback) {
1136
- const code = response.data?.code;
1137
- return typeof code === "string" && /^[A-Z0-9_]{1,64}$/.test(code) ? code : fallback;
1138
- }
1139
-
1140
1219
  // src/lib/project-state.ts
1141
1220
  import fs from "fs";
1142
1221
  import path from "path";
@@ -2606,30 +2685,33 @@ async function runOrganizationInit(options) {
2606
2685
  }
2607
2686
  const { wallet, agent, sdkKey } = provisioned.resources;
2608
2687
  writeOrganizationEnvLocal(cwd, { sdkKey: sdkKey.key, baseUrl, agent, wallet, chain });
2609
- writeContoConfig(cwd, {
2610
- agent: {
2611
- id: agent.id,
2612
- name: agent.name,
2613
- type: agentType
2614
- },
2615
- network: {
2616
- chain: selectedChainId,
2617
- chainId: chain.chainId,
2618
- rpcUrl: chain.rpcUrl,
2619
- explorerUrl: chain.explorerUrl,
2620
- currency: chain.currency,
2621
- testnet: chain.testnet
2622
- },
2623
- wallet: {
2624
- id: wallet.id,
2625
- address: wallet.address,
2626
- custodyMode: wallet.custodyMode
2688
+ const keptFiles = await writeProjectFiles(
2689
+ cwd,
2690
+ {
2691
+ agent: {
2692
+ id: agent.id,
2693
+ name: agent.name,
2694
+ type: agentType
2695
+ },
2696
+ network: {
2697
+ chain: selectedChainId,
2698
+ chainId: chain.chainId,
2699
+ rpcUrl: chain.rpcUrl,
2700
+ explorerUrl: chain.explorerUrl,
2701
+ currency: chain.currency,
2702
+ testnet: chain.testnet
2703
+ },
2704
+ wallet: {
2705
+ id: wallet.id,
2706
+ address: wallet.address,
2707
+ custodyMode: wallet.custodyMode
2708
+ },
2709
+ server: {
2710
+ baseUrl
2711
+ }
2627
2712
  },
2628
- server: {
2629
- baseUrl
2630
- }
2631
- });
2632
- writeExampleFile(cwd);
2713
+ options
2714
+ );
2633
2715
  saveGlobalConfig({
2634
2716
  agent: { id: agent.id, name: agent.name, type: agentType },
2635
2717
  network: {
@@ -2667,9 +2749,10 @@ async function runOrganizationInit(options) {
2667
2749
  }
2668
2750
  }
2669
2751
  const cli = cliResolves ? "npx conto" : "npx @conto_finance/create-conto-agent";
2752
+ const exampleKept = keptFiles.includes("example.mjs");
2670
2753
  const nextSteps = [
2671
2754
  `${cli} doctor`,
2672
- "node example.mjs",
2755
+ ...exampleKept ? [] : ["node example.mjs"],
2673
2756
  `${cli} pay <address> <amount>`,
2674
2757
  `${cli} mcp`
2675
2758
  ];
@@ -2690,7 +2773,8 @@ async function runOrganizationInit(options) {
2690
2773
  storedIn: ".env.local",
2691
2774
  sdkKeyEnv: "CONTO_API_KEY"
2692
2775
  },
2693
- files: [".env.local", ".gitignore", "conto.config.json", "example.mjs"],
2776
+ files: PROJECT_FILES.filter((file) => !keptFiles.includes(file)),
2777
+ ...keptFiles.length > 0 ? { keptFiles } : {},
2694
2778
  ...resumeFrom ? { resumed: true } : {},
2695
2779
  ...discarded ? { discardedSetup: discarded } : {},
2696
2780
  nextSteps
@@ -2700,9 +2784,14 @@ async function runOrganizationInit(options) {
2700
2784
  console.log("");
2701
2785
  console.log(chalk2.green.bold(" Your agent is ready!") + " Files written:\n");
2702
2786
  console.log(` ${chalk2.bold(".env.local")} - SDK key + config`);
2703
- console.log(` ${chalk2.bold("conto.config.json")} - Agent metadata`);
2704
- console.log(` ${chalk2.bold("example.mjs")} - Runnable payment example`);
2787
+ if (!keptFiles.includes("conto.config.json")) {
2788
+ console.log(` ${chalk2.bold("conto.config.json")} - Agent metadata`);
2789
+ }
2790
+ if (!exampleKept) {
2791
+ console.log(` ${chalk2.bold("example.mjs")} - Runnable payment example`);
2792
+ }
2705
2793
  console.log("");
2794
+ printKeptFiles(keptFiles);
2706
2795
  console.log(
2707
2796
  ` ${chalk2.dim("Wallet:")} ${wallet.address} (${chain.name}${chain.testnet ? " testnet" : ""}, ${wallet.custodyMode ?? "MANAGED"} custody)`
2708
2797
  );
@@ -2717,7 +2806,9 @@ async function runOrganizationInit(options) {
2717
2806
  ` ${step++}. Fund your wallet with ${chain.currency} ${chalk2.dim("\u2192")} ${wallet.address}`
2718
2807
  );
2719
2808
  }
2720
- console.log(` ${step++}. Run the example: ${chalk2.cyan("node example.mjs")}`);
2809
+ if (!exampleKept) {
2810
+ console.log(` ${step++}. Run the example: ${chalk2.cyan("node example.mjs")}`);
2811
+ }
2721
2812
  console.log(` ${step++}. Make a payment: ${chalk2.cyan(`${cli} pay <address> <amount>`)}`);
2722
2813
  console.log(` ${step++}. Connect Claude: ${chalk2.cyan(`${cli} mcp`)}`);
2723
2814
  if (!cliResolves) {
@@ -2909,6 +3000,7 @@ async function runSandboxInit(options) {
2909
3000
  "",
2910
3001
  "# Sandbox (shown once, keep private)",
2911
3002
  ["CONTO_SANDBOX_API_KEY", sandbox.credentials.apiKey],
3003
+ ["CONTO_SANDBOX_MODE", "test"],
2912
3004
  ["CONTO_SANDBOX_EXPIRES_AT", sandbox.expiresAt]
2913
3005
  ]);
2914
3006
  const setupKeyFile = sandbox.credentials.setupKey ? (ensureContoDirGitignored(cwd), writeSandboxSetupEnv(cwd, [
@@ -2922,34 +3014,38 @@ async function runSandboxInit(options) {
2922
3014
  ["CONTO_WALLET_ID", sandbox.wallet.id],
2923
3015
  ["CONTO_SANDBOX_EXPIRES_AT", sandbox.expiresAt]
2924
3016
  ])) : null;
2925
- writeContoConfig(cwd, {
2926
- agent: {
2927
- id: sandbox.agent.id,
2928
- name: sandbox.agent.name,
2929
- type: options.type || "CUSTOM"
2930
- },
2931
- network: {
2932
- chain: sandbox.wallet.chainId,
2933
- chainId: sandbox.wallet.chainId,
2934
- rpcUrl: chain?.rpcUrl || "",
2935
- explorerUrl: chain?.explorerUrl || "",
2936
- currency: chain?.currency || sandbox.wallet.currency,
2937
- testnet: true
2938
- },
2939
- wallet: {
2940
- id: sandbox.wallet.id,
2941
- address: sandbox.wallet.address,
2942
- custodyMode: sandbox.wallet.custodyMode
2943
- },
2944
- server: {
2945
- baseUrl
3017
+ const keptFiles = await writeProjectFiles(
3018
+ cwd,
3019
+ {
3020
+ agent: {
3021
+ id: sandbox.agent.id,
3022
+ name: sandbox.agent.name,
3023
+ type: options.type || "CUSTOM"
3024
+ },
3025
+ network: {
3026
+ chain: sandbox.wallet.chainId,
3027
+ chainId: sandbox.wallet.chainId,
3028
+ rpcUrl: chain?.rpcUrl || "",
3029
+ explorerUrl: chain?.explorerUrl || "",
3030
+ currency: chain?.currency || sandbox.wallet.currency,
3031
+ testnet: true
3032
+ },
3033
+ wallet: {
3034
+ id: sandbox.wallet.id,
3035
+ address: sandbox.wallet.address,
3036
+ custodyMode: sandbox.wallet.custodyMode
3037
+ },
3038
+ server: {
3039
+ baseUrl
3040
+ },
3041
+ sandbox: {
3042
+ mode: "test",
3043
+ expiresAt: sandbox.expiresAt
3044
+ }
2946
3045
  },
2947
- sandbox: {
2948
- mode: "test",
2949
- expiresAt: sandbox.expiresAt
2950
- }
2951
- });
2952
- writeExampleFile(cwd);
3046
+ options
3047
+ );
3048
+ const exampleKept = keptFiles.includes("example.mjs");
2953
3049
  saveGlobalConfig({
2954
3050
  agent: {
2955
3051
  id: sandbox.agent.id,
@@ -3000,20 +3096,17 @@ async function runSandboxInit(options) {
3000
3096
  ...setupKeyFile ? { setupKeyStoredIn: setupKeyFile, setupKeyEnv: "CONTO_SANDBOX_SETUP_KEY" } : {}
3001
3097
  },
3002
3098
  files: [
3003
- ".env.local",
3004
- ".gitignore",
3005
- "conto.config.json",
3006
- "example.mjs",
3099
+ ...PROJECT_FILES.filter((file) => !keptFiles.includes(file)),
3007
3100
  ...setupKeyFile ? [setupKeyFile] : []
3008
3101
  ],
3102
+ ...keptFiles.length > 0 ? { keptFiles } : {},
3009
3103
  claim: {
3010
3104
  command: `${cli} sandbox claim --json`,
3011
3105
  credentialEnv: "CONTO_SANDBOX_API_KEY",
3012
3106
  ...sandbox.claim ? { method: sandbox.claim.method, endpoint: sandbox.claim.endpoint } : {}
3013
3107
  },
3014
3108
  nextSteps: [
3015
- "node example.mjs",
3016
- "node example.mjs --resume REQUEST_ID",
3109
+ ...exampleKept ? [] : ["node example.mjs", "node example.mjs --resume REQUEST_ID"],
3017
3110
  `${cli} doctor`,
3018
3111
  `${cli} pay 0x742d35Cc6634C0532925a3b844Bc454e4438f44e 1 --purpose test`,
3019
3112
  `${cli} sandbox claim --json`
@@ -3024,14 +3117,19 @@ async function runSandboxInit(options) {
3024
3117
  console.log("");
3025
3118
  console.log(chalk2.green.bold(" Sandbox agent ready!") + " Files written:\n");
3026
3119
  console.log(` ${chalk2.bold(".env.local")} - SDK key + config (shown once)`);
3027
- console.log(` ${chalk2.bold("conto.config.json")} - Agent metadata`);
3028
- console.log(` ${chalk2.bold("example.mjs")} - Runnable payment example`);
3120
+ if (!keptFiles.includes("conto.config.json")) {
3121
+ console.log(` ${chalk2.bold("conto.config.json")} - Agent metadata`);
3122
+ }
3123
+ if (!exampleKept) {
3124
+ console.log(` ${chalk2.bold("example.mjs")} - Runnable payment example`);
3125
+ }
3029
3126
  if (setupKeyFile) {
3030
3127
  console.log(
3031
3128
  ` ${chalk2.bold(setupKeyFile)} - Setup key for policies and limits (keep out of the agent runtime)`
3032
3129
  );
3033
3130
  }
3034
3131
  console.log("");
3132
+ printKeptFiles(keptFiles);
3035
3133
  console.log(
3036
3134
  ` ${chalk2.dim("Wallet:")} ${sandbox.wallet.address} (${chain?.name || sandbox.wallet.chainId}, test mode)`
3037
3135
  );
@@ -3044,10 +3142,14 @@ async function runSandboxInit(options) {
3044
3142
  console.log(` ${chalk2.dim("Expires:")} ${sandbox.expiresAt}`);
3045
3143
  console.log("");
3046
3144
  console.log(chalk2.bold(" Next steps:"));
3047
- console.log(` 1. Run the example: ${chalk2.cyan("node example.mjs")}`);
3048
- console.log(` 2. Continue it: ${chalk2.cyan("node example.mjs --resume REQUEST_ID")}`);
3049
- console.log(" Replace REQUEST_ID with the ID printed by the example.");
3050
- console.log(` 3. Verify setup: ${chalk2.cyan(`${cli} doctor`)}`);
3145
+ if (exampleKept) {
3146
+ console.log(` 1. Verify setup: ${chalk2.cyan(`${cli} doctor`)}`);
3147
+ } else {
3148
+ console.log(` 1. Run the example: ${chalk2.cyan("node example.mjs")}`);
3149
+ console.log(` 2. Continue it: ${chalk2.cyan("node example.mjs --resume REQUEST_ID")}`);
3150
+ console.log(" Replace REQUEST_ID with the ID printed by the example.");
3151
+ console.log(` 3. Verify setup: ${chalk2.cyan(`${cli} doctor`)}`);
3152
+ }
3051
3153
  console.log("");
3052
3154
  printInfo(
3053
3155
  "Sandbox test payments exercise policy checks, receipts, and spend tracking without an onchain transfer."
@@ -3099,8 +3201,58 @@ function installCliLocally(cwd, agentName) {
3099
3201
  }
3100
3202
  return "failed";
3101
3203
  }
3102
- function writeExampleFile(dir) {
3103
- const content = `// Conto quickstart example, generated by create-conto-agent.
3204
+ var PROJECT_FILES = [".env.local", ".gitignore", "conto.config.json", "example.mjs"];
3205
+ async function writeUnlessKept(filePath, content, options) {
3206
+ let file;
3207
+ try {
3208
+ file = await fs2.promises.open(filePath, fs2.constants.O_RDWR | fs2.constants.O_CREAT);
3209
+ } catch (err) {
3210
+ const code = err.code;
3211
+ if (code === "EACCES" || code === "EPERM") return false;
3212
+ throw err;
3213
+ }
3214
+ try {
3215
+ const current = await file.readFile("utf8");
3216
+ if (current === content) return true;
3217
+ if (current !== "" && !options.overwrite) {
3218
+ const canAsk = Boolean(process.stdin.isTTY && process.stdout.isTTY) && !isJsonMode();
3219
+ if (!canAsk) return false;
3220
+ const replace = await p.confirm({
3221
+ message: `${path2.basename(filePath)} already exists. Replace it?`,
3222
+ initialValue: false
3223
+ });
3224
+ if (p.isCancel(replace) || !replace) return false;
3225
+ }
3226
+ await file.truncate(0);
3227
+ await file.write(content, 0, "utf8");
3228
+ return true;
3229
+ } finally {
3230
+ await file.close();
3231
+ }
3232
+ }
3233
+ async function writeProjectFiles(dir, config, options) {
3234
+ const kept = [];
3235
+ if (!await writeUnlessKept(
3236
+ path2.join(dir, "conto.config.json"),
3237
+ JSON.stringify(config, null, 2) + "\n",
3238
+ options
3239
+ )) {
3240
+ kept.push("conto.config.json");
3241
+ }
3242
+ if (!await writeUnlessKept(path2.join(dir, "example.mjs"), exampleFileContent(), options)) {
3243
+ kept.push("example.mjs");
3244
+ }
3245
+ return kept;
3246
+ }
3247
+ function printKeptFiles(keptFiles) {
3248
+ if (keptFiles.length === 0) return;
3249
+ printWarning(
3250
+ `Kept your existing ${keptFiles.join(" and ")}. Run init again with --overwrite to replace ${keptFiles.length === 1 ? "it" : "them"}.`
3251
+ );
3252
+ console.log("");
3253
+ }
3254
+ function exampleFileContent() {
3255
+ return `// Conto quickstart example, generated by create-conto-agent.
3104
3256
  //
3105
3257
  // Usage:
3106
3258
  // node example.mjs Check setup and request a test payment (no funds move)
@@ -3234,11 +3386,20 @@ main().catch((err) => {
3234
3386
  process.exit(1);
3235
3387
  });
3236
3388
  `;
3237
- fs2.writeFileSync(path2.join(dir, "example.mjs"), content);
3238
3389
  }
3239
3390
 
3240
3391
  export {
3241
3392
  CLI_PACKAGE_VERSION,
3393
+ HttpTransportError,
3394
+ redactSecrets,
3395
+ parseSecureBaseUrl,
3396
+ normalizeBaseUrl,
3397
+ apiUrl,
3398
+ requestJson,
3399
+ retryAfterSeconds,
3400
+ responseErrorMessage,
3401
+ responseErrorCode,
3402
+ NOTHING_SENT_CODES,
3242
3403
  ApiClient,
3243
3404
  createApiClient,
3244
3405
  fetchChains,
@@ -3251,15 +3412,6 @@ export {
3251
3412
  directOrReview,
3252
3413
  reportReview,
3253
3414
  browserAuth,
3254
- HttpTransportError,
3255
- redactSecrets,
3256
- parseSecureBaseUrl,
3257
- normalizeBaseUrl,
3258
- apiUrl,
3259
- requestJson,
3260
- retryAfterSeconds,
3261
- responseErrorMessage,
3262
- responseErrorCode,
3263
3415
  projectStateFile,
3264
3416
  readProjectStateFile,
3265
3417
  writeProjectStateFile,