@conto_finance/create-conto-agent 0.4.7 → 0.5.1

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,26 +1,27 @@
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,
4
12
  printError,
5
13
  printInfo,
6
14
  printJson,
15
+ printKeyValue,
16
+ printPending,
7
17
  printSuccess,
8
18
  printWarning
9
- } from "./chunk-K4LBO234.js";
10
- import {
11
- ensureContoDirGitignored,
12
- ensureEnvLocalGitignored,
13
- loadProjectEnv,
14
- saveGlobalConfig,
15
- writeContoConfig,
16
- writeEnvLocal,
17
- writeSandboxSetupEnv
18
- } from "./chunk-XWUWB3FT.js";
19
+ } from "./chunk-DT5NOLBD.js";
19
20
 
20
21
  // package.json
21
22
  var package_default = {
22
23
  name: "@conto_finance/create-conto-agent",
23
- version: "0.4.7",
24
+ version: "0.5.1",
24
25
  description: "Set up an AI agent with Conto spending controls",
25
26
  bin: {
26
27
  "create-conto-agent": "bin/create-conto-agent.js",
@@ -90,9 +91,156 @@ var package_default = {
90
91
  // src/lib/package-version.ts
91
92
  var CLI_PACKAGE_VERSION = package_default.version || "0.0.0";
92
93
 
94
+ // src/lib/owner-review.ts
95
+ import chalk from "chalk";
96
+ var REVIEW_EXIT_CODES_HELP = `
97
+ Changes that loosen controls go to owner review:
98
+ the command prints a review link, opens it when it can, and waits.
99
+
100
+ Exit codes:
101
+ 0 applied, or nothing needed to change
102
+ 1 request failed, or the change could not be applied
103
+ 3 the reviewer declined the change
104
+ 4 still waiting for review (--no-wait, or the wait timed out)
105
+ 5 the review expired
106
+ `;
107
+ var EXIT_DECLINED = 3;
108
+ var EXIT_PENDING = 4;
109
+ var EXIT_EXPIRED = 5;
110
+ var POLL_INTERVAL_MS = Number(process.env.CONTO_REVIEW_POLL_MS) || 3e3;
111
+ var DEFAULT_WAIT_SECONDS = 300;
112
+ var MAX_WAIT_SECONDS = 900;
113
+ var TIGHTEN_ONLY_CODES = /* @__PURE__ */ new Set([
114
+ "TIGHTEN_ONLY_ROUTE",
115
+ "AGENT_KEY_TIGHTEN_ONLY",
116
+ "WALLET_DELEGATION_REQUIRED",
117
+ "COUNTERPARTY_CHANGE_NOT_ALLOWED"
118
+ ]);
119
+ function isTightenOnlyRefusal(err) {
120
+ const error = err;
121
+ return error?.status === 403 && TIGHTEN_ONLY_CODES.has(error.code ?? "");
122
+ }
123
+ function interactive() {
124
+ return Boolean(process.stdout.isTTY) && !isJsonMode();
125
+ }
126
+ function waitSeconds(wait) {
127
+ if (wait === false) return 0;
128
+ if (typeof wait === "string" && wait.trim() !== "") {
129
+ const parsed = Number(wait);
130
+ if (!Number.isFinite(parsed) || parsed < 0) {
131
+ throw new Error("--wait takes a number of seconds");
132
+ }
133
+ return Math.min(Math.round(parsed), MAX_WAIT_SECONDS);
134
+ }
135
+ if (wait === true) return DEFAULT_WAIT_SECONDS;
136
+ return interactive() ? DEFAULT_WAIT_SECONDS : 0;
137
+ }
138
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
139
+ function exitCodeFor(status) {
140
+ switch (status) {
141
+ case "APPLIED":
142
+ case "NO_CHANGE":
143
+ return 0;
144
+ case "REJECTED":
145
+ return EXIT_DECLINED;
146
+ case "EXPIRED":
147
+ return EXIT_EXPIRED;
148
+ case "PENDING_REVIEW":
149
+ case "READY_TO_CLAIM":
150
+ case "APPLYING":
151
+ return EXIT_PENDING;
152
+ default:
153
+ return 1;
154
+ }
155
+ }
156
+ async function openReviewPage(url) {
157
+ try {
158
+ const open2 = (await import("open")).default;
159
+ await open2(url);
160
+ } catch {
161
+ }
162
+ }
163
+ async function followChange(api, change, options = {}) {
164
+ let current = change;
165
+ const seconds = waitSeconds(options.wait);
166
+ if (current.status === "PENDING_REVIEW" && current.reviewUrl && !isJsonMode()) {
167
+ printPending("This change needs an owner or admin to confirm it.");
168
+ printKeyValue("Review", current.reviewUrl);
169
+ if (options.open ?? interactive()) await openReviewPage(current.reviewUrl);
170
+ }
171
+ const deadline = Date.now() + seconds * 1e3;
172
+ while ((current.status === "PENDING_REVIEW" || current.status === "APPLYING") && Date.now() < deadline) {
173
+ await sleep(POLL_INTERVAL_MS);
174
+ current = await api.getOwnerAction(current.changeId);
175
+ }
176
+ if (current.status === "READY_TO_CLAIM") {
177
+ const claimed = await api.claimOwnerAction(current.changeId);
178
+ return {
179
+ change: claimed.change,
180
+ sdkKey: claimed.sdkKey,
181
+ exitCode: exitCodeFor(claimed.change.status)
182
+ };
183
+ }
184
+ return { change: current, exitCode: exitCodeFor(current.status) };
185
+ }
186
+ async function proposeForReview(api, action, input, options = {}) {
187
+ const proposed = await api.proposeOwnerAction(action, input, CLI_PACKAGE_VERSION);
188
+ if (!proposed.proposed) {
189
+ const reason = proposed.result;
190
+ const error = new Error(reason.message || "The change could not be proposed.");
191
+ error.code = reason.status === "no_op" ? "NO_CHANGE" : "NOT_PROPOSED";
192
+ error.recovery = reason.recovery;
193
+ throw error;
194
+ }
195
+ return followChange(api, proposed.change, options);
196
+ }
197
+ async function directOrReview(api, direct, proposal, options = {}) {
198
+ try {
199
+ return { direct: await direct() };
200
+ } catch (err) {
201
+ if (!isTightenOnlyRefusal(err)) throw err;
202
+ const { action, input } = await proposal();
203
+ return { review: await proposeForReview(api, action, input, options) };
204
+ }
205
+ }
206
+ function reportReview(outcome, appliedMessage) {
207
+ const { change, sdkKey, exitCode } = outcome;
208
+ process.exitCode = exitCode;
209
+ if (isJsonMode()) {
210
+ printJson({
211
+ changeId: change.changeId,
212
+ status: change.status,
213
+ nextAction: change.nextAction,
214
+ message: change.message,
215
+ ...change.reviewUrl ? { reviewUrl: change.reviewUrl } : {},
216
+ ...change.result ? { result: change.result } : {},
217
+ ...sdkKey ? { sdkKey } : {}
218
+ });
219
+ return;
220
+ }
221
+ if (change.status === "APPLIED") {
222
+ printSuccess(appliedMessage);
223
+ } else if (change.status === "NO_CHANGE") {
224
+ printInfo(change.result?.message ?? change.message);
225
+ } else if (change.status === "PENDING_REVIEW") {
226
+ printPending("Still waiting for review. Nothing has changed yet.");
227
+ printInfo(`Check later with: conto changes status ${change.changeId}`);
228
+ } else if (change.status === "REJECTED") {
229
+ printWarning(change.message);
230
+ } else {
231
+ printError(change.result?.message ?? change.message);
232
+ if (change.result?.recovery) console.log(chalk.dim(` ${change.result.recovery}`));
233
+ }
234
+ if (sdkKey) {
235
+ console.log("");
236
+ printKeyValue("SDK key", sdkKey.key);
237
+ printWarning("This key is shown once. Store it now, for example as CONTO_API_KEY in .env.");
238
+ }
239
+ }
240
+
93
241
  // src/commands/init.ts
94
242
  import * as p from "@clack/prompts";
95
- import chalk from "chalk";
243
+ import chalk2 from "chalk";
96
244
  import fs2 from "fs";
97
245
  import path2 from "path";
98
246
  import { spawnSync } from "child_process";
@@ -209,9 +357,9 @@ function getChainChoices(chains) {
209
357
  }));
210
358
  }
211
359
  function chainHint(chain) {
212
- if (chain.testnet) return `Testnet \u2014 free ${chain.currency}, no real funds`;
213
- if (chain.chainId === "4217") return "Mainnet \u2014 real USDC.e and real settlement";
214
- 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}`;
215
363
  }
216
364
 
217
365
  // src/lib/auth.ts
@@ -256,7 +404,7 @@ async function parseCallbackPayload(req) {
256
404
  returnedState: params.get("state")
257
405
  };
258
406
  }
259
- async function browserAuth(baseUrl) {
407
+ async function browserAuth(baseUrl, onAuthUrl) {
260
408
  return new Promise((resolve, reject) => {
261
409
  const state = randomBytes(16).toString("hex");
262
410
  const timeout = setTimeout(
@@ -323,6 +471,7 @@ async function browserAuth(baseUrl) {
323
471
  }
324
472
  const callbackUrl = `http://127.0.0.1:${address.port}/callback`;
325
473
  const authUrl = `${baseUrl}/cli-auth?callback=${encodeURIComponent(callbackUrl)}&state=${encodeURIComponent(state)}`;
474
+ onAuthUrl?.(authUrl);
326
475
  open(authUrl).catch(() => {
327
476
  });
328
477
  });
@@ -464,7 +613,7 @@ async function requestJson(input) {
464
613
  const signal = input.signal ? AbortSignal.any([input.signal, timeoutSignal]) : timeoutSignal;
465
614
  let response;
466
615
  try {
467
- response = await fetch(input.url, {
616
+ response = await fetch(input.url.href, {
468
617
  method: input.method,
469
618
  headers,
470
619
  body: input.body === void 0 ? void 0 : JSON.stringify(input.body),
@@ -517,6 +666,556 @@ function responseErrorCode(response, fallback) {
517
666
  return typeof code === "string" && /^[A-Z0-9_]{1,64}$/.test(code) ? code : fallback;
518
667
  }
519
668
 
669
+ // src/lib/api-client.ts
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
+ }
689
+ function assertSecureBaseUrl(baseUrl) {
690
+ let parsed;
691
+ try {
692
+ parsed = new URL(baseUrl);
693
+ } catch {
694
+ throw new Error(`Invalid base URL: ${baseUrl}`);
695
+ }
696
+ if (parsed.protocol !== "https:" && parsed.hostname !== "localhost" && parsed.hostname !== "127.0.0.1") {
697
+ throw new Error("baseUrl must use https (except for localhost)");
698
+ }
699
+ }
700
+ var ApiClient = class {
701
+ baseUrl;
702
+ apiKey;
703
+ orgApiKey;
704
+ constructor(options) {
705
+ this.baseUrl = options.baseUrl.replace(/\/$/, "");
706
+ assertSecureBaseUrl(this.baseUrl);
707
+ this.apiKey = options.apiKey;
708
+ this.orgApiKey = options.orgApiKey;
709
+ }
710
+ async request(method, path3, options) {
711
+ const url = `${this.baseUrl}${path3}`;
712
+ const authType = options?.auth || "sdk";
713
+ const token = authType === "org" ? this.orgApiKey : this.apiKey;
714
+ const headers = {
715
+ ...options?.body instanceof FormData ? {} : { "Content-Type": "application/json" },
716
+ "User-Agent": `create-conto-agent/${CLI_PACKAGE_VERSION}`
717
+ };
718
+ if (token) {
719
+ headers["Authorization"] = `Bearer ${token}`;
720
+ }
721
+ const controller = new AbortController();
722
+ const timeoutId = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
723
+ try {
724
+ const response = await fetch(url, {
725
+ method,
726
+ headers,
727
+ body: options?.body instanceof FormData ? options.body : options?.body ? JSON.stringify(options.body) : void 0,
728
+ signal: controller.signal
729
+ });
730
+ const contentType = response.headers.get("content-type") || "";
731
+ if (!contentType.includes("application/json")) {
732
+ const error = new Error(
733
+ response.status === 404 ? `API endpoint not found: ${path3}` : `API returned non-JSON response (${response.status})`
734
+ );
735
+ error.code = response.status === 404 ? "NOT_FOUND" : "INVALID_RESPONSE";
736
+ error.status = response.status;
737
+ throw error;
738
+ }
739
+ const data = await response.json();
740
+ if (!response.ok) {
741
+ const error = new Error(data.error || `API request failed: ${response.status}`);
742
+ error.code = data.code || "API_ERROR";
743
+ error.status = response.status;
744
+ error.body = data;
745
+ error.details = data.details;
746
+ throw error;
747
+ }
748
+ return data;
749
+ } catch (err) {
750
+ if (err instanceof Error && err.name === "AbortError") {
751
+ const error = new Error(
752
+ `Request timed out after ${REQUEST_TIMEOUT_MS / 1e3}s`
753
+ );
754
+ error.code = "TIMEOUT";
755
+ error.status = 0;
756
+ throw error;
757
+ }
758
+ throw err;
759
+ } finally {
760
+ clearTimeout(timeoutId);
761
+ }
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
+ }
823
+ async getTestReport(options) {
824
+ const query = new URLSearchParams({ allowed: options.allowed, denied: options.denied });
825
+ if (options.review) query.set("review", options.review);
826
+ if (options.reviewOutcome) query.set("reviewOutcome", options.reviewOutcome);
827
+ return this.request("GET", `/api/sdk/test-report?${query}`);
828
+ }
829
+ // ── Org-level Admin APIs (used during init) ──
830
+ async createWallet(params) {
831
+ return this.request("POST", "/api/wallets", { body: params, auth: "org" });
832
+ }
833
+ async createAgent(params) {
834
+ return this.request("POST", "/api/agents", { body: params, auth: "org" });
835
+ }
836
+ async linkWalletToAgent(agentId, params) {
837
+ return this.request("POST", `/api/agents/${encodeURIComponent(agentId)}/wallets`, {
838
+ body: params,
839
+ auth: "org"
840
+ });
841
+ }
842
+ async createPolicy(params) {
843
+ return this.request("POST", "/api/policies", { body: params, auth: "org" });
844
+ }
845
+ async updatePolicy(policyId, params) {
846
+ return this.request("PATCH", `/api/policies/${encodeURIComponent(policyId)}`, { body: params, auth: "org" });
847
+ }
848
+ async deletePolicy(policyId) {
849
+ return this.request("DELETE", `/api/policies/${encodeURIComponent(policyId)}`, { auth: "org" });
850
+ }
851
+ async addPolicyRule(policyId, rule) {
852
+ return this.request(
853
+ "POST",
854
+ `/api/policies/${encodeURIComponent(policyId)}/rules`,
855
+ {
856
+ body: rule,
857
+ auth: "org"
858
+ }
859
+ );
860
+ }
861
+ async deletePolicyRule(policyId, ruleId) {
862
+ return this.request(
863
+ "DELETE",
864
+ `/api/policies/${encodeURIComponent(policyId)}/rules/${encodeURIComponent(ruleId)}`,
865
+ { auth: "org" }
866
+ );
867
+ }
868
+ async listOrgPolicies() {
869
+ return this.request("GET", "/api/policies", { auth: "org" });
870
+ }
871
+ async assignPolicyToAgent(agentId, policyId) {
872
+ return this.request("POST", `/api/agents/${encodeURIComponent(agentId)}/policies`, {
873
+ body: { policyId },
874
+ auth: "org"
875
+ });
876
+ }
877
+ async unassignPolicyFromAgent(agentId, policyId) {
878
+ return this.request(
879
+ "DELETE",
880
+ `/api/agents/${encodeURIComponent(agentId)}/policies?policyId=${encodeURIComponent(policyId)}`,
881
+ {
882
+ auth: "org"
883
+ }
884
+ );
885
+ }
886
+ async createSdkKey(agentId, params) {
887
+ return this.request("POST", `/api/agents/${encodeURIComponent(agentId)}/sdk-keys`, {
888
+ body: params,
889
+ auth: "org"
890
+ });
891
+ }
892
+ async fundWallet(walletId) {
893
+ return this.request("POST", `/api/wallets/${encodeURIComponent(walletId)}/faucet`, { auth: "org" });
894
+ }
895
+ // ── SDK Agent APIs (used by CLI commands) ──
896
+ async getSetup() {
897
+ return this.request("GET", "/api/sdk/setup");
898
+ }
899
+ async getAgentInfo() {
900
+ const data = await this.request("GET", "/api/sdk/agents/me");
901
+ return {
902
+ agent: {
903
+ id: data.id,
904
+ name: data.name,
905
+ agentType: data.agentType,
906
+ status: data.status,
907
+ createdAt: data.createdAt
908
+ },
909
+ organization: { name: data.organizationId },
910
+ walletCount: data.summary?.walletCount ?? 0,
911
+ summary: data.summary
912
+ };
913
+ }
914
+ async getWallets() {
915
+ return this.request("GET", "/api/sdk/wallets");
916
+ }
917
+ async getSpendingLimits() {
918
+ const data = await this.request("GET", "/api/sdk/spending-limits");
919
+ return {
920
+ limits: (data.wallets || []).map((w) => ({
921
+ walletId: w.walletId,
922
+ walletName: w.name,
923
+ daily: {
924
+ limit: w.limits?.daily ?? null,
925
+ spent: w.spent?.today ?? 0,
926
+ remaining: w.remaining?.daily ?? null
927
+ },
928
+ weekly: {
929
+ limit: w.limits?.weekly ?? null,
930
+ spent: w.spent?.thisWeek ?? 0,
931
+ remaining: w.remaining?.weekly ?? null
932
+ },
933
+ monthly: {
934
+ limit: w.limits?.monthly ?? null,
935
+ spent: w.spent?.thisMonth ?? 0,
936
+ remaining: w.remaining?.monthly ?? null
937
+ },
938
+ perTransaction: w.limits?.perTransaction ?? null
939
+ }))
940
+ };
941
+ }
942
+ async requestPayment(params) {
943
+ return this.paymentPost("/api/sdk/payments/request", params);
944
+ }
945
+ async executePayment(requestId) {
946
+ return this.paymentPost(`/api/sdk/payments/${encodeURIComponent(requestId)}/execute`, {});
947
+ }
948
+ async getPaymentStatus(requestId) {
949
+ return this.request("GET", `/api/sdk/payments/${encodeURIComponent(requestId)}`);
950
+ }
951
+ async getTransactions(params) {
952
+ const query = new URLSearchParams();
953
+ if (params?.limit) query.set("limit", String(params.limit));
954
+ if (params?.status) query.set("status", params.status);
955
+ const qs = query.toString() ? `?${query.toString()}` : "";
956
+ return this.request("GET", `/api/sdk/transactions${qs}`);
957
+ }
958
+ async getTransaction(id) {
959
+ return this.request("GET", `/api/sdk/transactions/${encodeURIComponent(id)}`);
960
+ }
961
+ async getPolicies() {
962
+ return this.request("GET", "/api/sdk/policies");
963
+ }
964
+ async getAlerts(params) {
965
+ const query = new URLSearchParams();
966
+ if (params?.status) query.set("status", params.status);
967
+ const qs = query.toString() ? `?${query.toString()}` : "";
968
+ return this.request("GET", `/api/sdk/alerts${qs}`);
969
+ }
970
+ async getAnalytics() {
971
+ return this.request("GET", "/api/sdk/analytics");
972
+ }
973
+ };
974
+ function createApiClient(options) {
975
+ return new ApiClient(options);
976
+ }
977
+
978
+ // src/lib/owner-client.ts
979
+ var enc = encodeURIComponent;
980
+ var OwnerApiClient = class extends ApiClient {
981
+ // ── Agents ──
982
+ listAgents() {
983
+ return this.request("GET", "/api/agents?limit=100", {
984
+ auth: "org"
985
+ });
986
+ }
987
+ getAgent(agentId) {
988
+ return this.request("GET", `/api/agents/${enc(agentId)}`, {
989
+ auth: "org"
990
+ });
991
+ }
992
+ updateAgentStatus(agentId, status) {
993
+ return this.request("PATCH", `/api/agents/${enc(agentId)}`, {
994
+ body: { status },
995
+ auth: "org"
996
+ });
997
+ }
998
+ freezeAgent(agentId, body) {
999
+ return this.request("POST", `/api/agents/${enc(agentId)}/freeze`, {
1000
+ body,
1001
+ auth: "org"
1002
+ });
1003
+ }
1004
+ unfreezeAgent(agentId, body) {
1005
+ return this.request("POST", `/api/agents/${enc(agentId)}/unfreeze`, {
1006
+ body,
1007
+ auth: "org"
1008
+ });
1009
+ }
1010
+ deleteAgent(agentId) {
1011
+ return this.request("DELETE", `/api/agents/${enc(agentId)}`, {
1012
+ auth: "org"
1013
+ });
1014
+ }
1015
+ listSdkKeys(agentId) {
1016
+ return this.request("GET", `/api/agents/${enc(agentId)}/sdk-keys`, {
1017
+ auth: "org"
1018
+ });
1019
+ }
1020
+ revokeSdkKey(agentId, keyId) {
1021
+ return this.request(
1022
+ "DELETE",
1023
+ `/api/agents/${enc(agentId)}/sdk-keys?keyId=${enc(keyId)}`,
1024
+ { auth: "org" }
1025
+ );
1026
+ }
1027
+ createSdkKeyDirect(agentId, name) {
1028
+ return this.request(
1029
+ "POST",
1030
+ `/api/agents/${enc(agentId)}/sdk-keys`,
1031
+ { body: { name }, auth: "org" }
1032
+ );
1033
+ }
1034
+ // ── Wallet controls ──
1035
+ updateWallet(walletId, status) {
1036
+ return this.request("PATCH", `/api/wallets/${enc(walletId)}`, {
1037
+ body: { status },
1038
+ auth: "org"
1039
+ });
1040
+ }
1041
+ linkWallet(agentId, body) {
1042
+ return this.request("POST", `/api/agents/${enc(agentId)}/wallets`, {
1043
+ body,
1044
+ auth: "org"
1045
+ });
1046
+ }
1047
+ updateWalletLink(agentId, walletId, body) {
1048
+ return this.request(
1049
+ "PATCH",
1050
+ `/api/agents/${enc(agentId)}/wallets/${enc(walletId)}`,
1051
+ { body, auth: "org" }
1052
+ );
1053
+ }
1054
+ unlinkWallet(agentId, walletId) {
1055
+ return this.request(
1056
+ "DELETE",
1057
+ `/api/agents/${enc(agentId)}/wallets/${enc(walletId)}`,
1058
+ { auth: "org" }
1059
+ );
1060
+ }
1061
+ // ── Payees ──
1062
+ listCounterparties() {
1063
+ return this.request(
1064
+ "GET",
1065
+ "/api/counterparties?limit=100",
1066
+ { auth: "org" }
1067
+ );
1068
+ }
1069
+ getCounterparty(id) {
1070
+ return this.request(
1071
+ "GET",
1072
+ `/api/counterparties/${enc(id)}`,
1073
+ { auth: "org" }
1074
+ );
1075
+ }
1076
+ createCounterparty(body) {
1077
+ return this.request("POST", "/api/counterparties", { body, auth: "org" });
1078
+ }
1079
+ updateCounterparty(id, body) {
1080
+ return this.request("PATCH", `/api/counterparties/${enc(id)}`, {
1081
+ body,
1082
+ auth: "org"
1083
+ });
1084
+ }
1085
+ // ── Event delivery ──
1086
+ listChannels() {
1087
+ return this.request("GET", "/api/notification-channels", {
1088
+ auth: "org"
1089
+ });
1090
+ }
1091
+ createChannel(body) {
1092
+ return this.request("POST", "/api/notification-channels", {
1093
+ body,
1094
+ auth: "org"
1095
+ });
1096
+ }
1097
+ testChannel(channelId) {
1098
+ return this.request(
1099
+ "POST",
1100
+ `/api/notification-channels/${enc(channelId)}/test`,
1101
+ { auth: "org" }
1102
+ );
1103
+ }
1104
+ deleteChannel(channelId) {
1105
+ return this.request(
1106
+ "DELETE",
1107
+ `/api/notification-channels/${enc(channelId)}`,
1108
+ { auth: "org" }
1109
+ );
1110
+ }
1111
+ // ── Policy history and testing ──
1112
+ getPolicy(policyId) {
1113
+ return this.request("GET", `/api/policies/${enc(policyId)}`, { auth: "org" });
1114
+ }
1115
+ listPolicyRules(policyId) {
1116
+ return this.request(
1117
+ "GET",
1118
+ `/api/policies/${enc(policyId)}/rules`,
1119
+ { auth: "org" }
1120
+ );
1121
+ }
1122
+ listPolicyVersions(policyId) {
1123
+ return this.request("GET", `/api/policies/${enc(policyId)}/versions`, { auth: "org" });
1124
+ }
1125
+ getPolicyVersion(policyId, version) {
1126
+ return this.request("GET", `/api/policies/${enc(policyId)}/versions/${version}`, { auth: "org" });
1127
+ }
1128
+ rollbackPolicyDirect(policyId, version) {
1129
+ return this.request(
1130
+ "POST",
1131
+ `/api/policies/${enc(policyId)}/versions/${version}/rollback`,
1132
+ { body: {}, auth: "org" }
1133
+ );
1134
+ }
1135
+ simulatePolicy(body) {
1136
+ return this.request("POST", "/api/policies/simulate", { body, auth: "org" });
1137
+ }
1138
+ // ── Alerts (agent key) ──
1139
+ updateAlert(alertId, action) {
1140
+ return this.request("POST", `/api/sdk/alerts/${enc(alertId)}`, {
1141
+ body: { action }
1142
+ });
1143
+ }
1144
+ // ── Owner review ──
1145
+ proposeOwnerAction(action, input, version) {
1146
+ return this.request("POST", "/api/owner-actions", {
1147
+ body: { action, input, client: { name: "conto-cli", version } },
1148
+ auth: "org"
1149
+ });
1150
+ }
1151
+ getOwnerAction(changeId) {
1152
+ return this.request("GET", `/api/owner-actions/${enc(changeId)}`, {
1153
+ auth: "org"
1154
+ });
1155
+ }
1156
+ claimOwnerAction(changeId) {
1157
+ return this.request("POST", `/api/owner-actions/${enc(changeId)}/claim`, {
1158
+ auth: "org"
1159
+ });
1160
+ }
1161
+ };
1162
+ function createOwnerClient(options) {
1163
+ return new OwnerApiClient(options);
1164
+ }
1165
+
1166
+ // src/lib/init-review-access.ts
1167
+ var TERMINAL_RETRY = /* @__PURE__ */ new Set(["EXPIRED", "STALE", "FAILED"]);
1168
+ function toResult(outcome) {
1169
+ const { change, sdkKey } = outcome;
1170
+ if (change.status === "APPLIED" && sdkKey) {
1171
+ return { kind: "applied", sdkKey: { key: sdkKey.key, keyId: sdkKey.keyId } };
1172
+ }
1173
+ if (change.status === "PENDING_REVIEW" || change.status === "APPLYING") {
1174
+ return { kind: "pending", changeId: change.changeId, reviewUrl: change.reviewUrl };
1175
+ }
1176
+ if (change.status === "APPLIED") {
1177
+ return {
1178
+ kind: "failed",
1179
+ code: "KEY_NOT_RECEIVED",
1180
+ message: "The key was created but this terminal did not receive it. Revoke it in the dashboard and run setup again."
1181
+ };
1182
+ }
1183
+ if (change.status === "REJECTED") {
1184
+ return { kind: "failed", code: "REVIEW_DECLINED", message: change.message };
1185
+ }
1186
+ return {
1187
+ kind: "failed",
1188
+ code: `REVIEW_${change.status}`,
1189
+ message: change.result?.message ?? change.message
1190
+ };
1191
+ }
1192
+ function reviewAccessFor(baseUrl, orgApiKey) {
1193
+ const api = createOwnerClient({ baseUrl, orgApiKey });
1194
+ const interactive2 = Boolean(process.stdout.isTTY) && !isJsonMode();
1195
+ const options = { wait: interactive2, open: interactive2 };
1196
+ return async (params) => {
1197
+ if (params.changeId) {
1198
+ const earlier = await api.getOwnerAction(params.changeId);
1199
+ if (!TERMINAL_RETRY.has(earlier.status)) {
1200
+ return toResult(await followChange(api, earlier, options));
1201
+ }
1202
+ }
1203
+ const outcome = await proposeForReview(
1204
+ api,
1205
+ "setup_agent_access",
1206
+ {
1207
+ agent_id: params.agentId,
1208
+ wallet_id: params.walletId,
1209
+ spend_limit_per_tx: params.perTransactionLimit,
1210
+ spend_limit_daily: params.dailyLimit,
1211
+ key_name: params.keyName
1212
+ },
1213
+ options
1214
+ );
1215
+ return toResult(outcome);
1216
+ };
1217
+ }
1218
+
520
1219
  // src/lib/project-state.ts
521
1220
  import fs from "fs";
522
1221
  import path from "path";
@@ -696,6 +1395,7 @@ function hasServerSideEffects(checkpoint) {
696
1395
  // src/lib/init-provisioning.ts
697
1396
  var RECONCILE_WAIT_SECONDS = 300;
698
1397
  var iso = (ms = Date.now()) => new Date(ms).toISOString();
1398
+ var TIGHTEN_ONLY_CODE = "TIGHTEN_ONLY_ROUTE";
699
1399
  async function provisionOrganization(input) {
700
1400
  const { checkpoint, client, ui, chain } = input;
701
1401
  const steps = checkpoint.steps;
@@ -979,7 +1679,10 @@ async function provisionOrganization(input) {
979
1679
  }
980
1680
  }
981
1681
  const agent = resources.agent;
982
- if (steps.walletLink.status === "done") {
1682
+ let reviewedAccess = Boolean(input.reviewAccess) && steps.walletLink.status === "action_required" && (Boolean(steps.walletLink.ownerChangeId) || steps.walletLink.error?.code === TIGHTEN_ONLY_CODE);
1683
+ if (reviewedAccess) {
1684
+ ui.info("The wallet link and SDK key are waiting for owner review.");
1685
+ } else if (steps.walletLink.status === "done") {
983
1686
  if (input.resuming) {
984
1687
  const links = await client.listWalletLinks(agent.id);
985
1688
  if (!links.ok) return verifyFailed("walletLink", links.failure);
@@ -1034,13 +1737,23 @@ async function provisionOrganization(input) {
1034
1737
  spendLimitDaily: request.dailyLimit,
1035
1738
  spendLimitPerTx: request.perTransactionLimit
1036
1739
  });
1037
- if (!result.ok) {
1740
+ if (!result.ok && result.outcome === "not_created" && result.failure.code === TIGHTEN_ONLY_CODE && input.reviewAccess) {
1741
+ ui.stop("Wallet link needs owner review");
1742
+ steps.walletLink = {
1743
+ status: "action_required",
1744
+ attemptedAt: steps.walletLink.attemptedAt,
1745
+ error: result.failure
1746
+ };
1747
+ persist();
1748
+ reviewedAccess = true;
1749
+ } else if (!result.ok) {
1038
1750
  ui.stop("Wallet linking failed");
1039
1751
  return createFailed("walletLink", result);
1752
+ } else {
1753
+ complete("walletLink", { id: result.value.id });
1754
+ ui.stop("Wallet linked");
1755
+ ui.success(`Wallet linked ($${request.dailyLimit}/day limit)`);
1040
1756
  }
1041
- complete("walletLink", { id: result.value.id });
1042
- ui.stop("Wallet linked");
1043
- ui.success(`Wallet linked ($${request.dailyLimit}/day limit)`);
1044
1757
  }
1045
1758
  }
1046
1759
  if (steps.policy.status === "done") {
@@ -1142,6 +1855,62 @@ async function provisionOrganization(input) {
1142
1855
  }
1143
1856
  return "none";
1144
1857
  };
1858
+ if (reviewedAccess && input.reviewAccess && steps.sdkKey.status !== "done") {
1859
+ ui.start("Waiting for an owner to confirm the wallet link and SDK key...");
1860
+ begin("sdkKey");
1861
+ const review = await input.reviewAccess({
1862
+ agentId: agent.id,
1863
+ walletId: wallet.id,
1864
+ dailyLimit: request.dailyLimit,
1865
+ perTransactionLimit: request.perTransactionLimit,
1866
+ keyName: request.sdkKeyName,
1867
+ changeId: steps.walletLink.ownerChangeId
1868
+ });
1869
+ if (review.kind === "pending") {
1870
+ ui.stop("Still waiting for owner review");
1871
+ steps.walletLink = { ...steps.walletLink, ownerChangeId: review.changeId };
1872
+ steps.sdkKey = { ...steps.sdkKey, status: "pending" };
1873
+ return stopped({
1874
+ status: "owner_action_required",
1875
+ step: "walletLink",
1876
+ code: "OWNER_REVIEW_REQUIRED",
1877
+ message: "An owner or admin must confirm the wallet link and SDK key.",
1878
+ ownerAction: {
1879
+ action: "Confirm the change on the review page, then resume setup to collect the key.",
1880
+ dashboardUrl: review.reviewUrl ?? `${input.baseUrl}/approvals/review/changes/${review.changeId}`
1881
+ }
1882
+ });
1883
+ }
1884
+ if (review.kind === "failed") {
1885
+ ui.stop("Owner review did not complete");
1886
+ steps.walletLink = { ...steps.walletLink, ownerChangeId: void 0 };
1887
+ steps.sdkKey = { ...steps.sdkKey, status: "failed" };
1888
+ return stopped({
1889
+ status: "failed",
1890
+ step: "walletLink",
1891
+ code: review.code,
1892
+ message: review.message
1893
+ });
1894
+ }
1895
+ let storedIn;
1896
+ try {
1897
+ storedIn = input.storeSdkKey(review.sdkKey.key, wallet, agent);
1898
+ } catch {
1899
+ ui.stop("SDK key could not be saved");
1900
+ steps.sdkKey = {
1901
+ status: "action_required",
1902
+ id: review.sdkKey.keyId,
1903
+ attemptedAt: steps.sdkKey.attemptedAt
1904
+ };
1905
+ return stopped(rotationAction([{ id: review.sdkKey.keyId }]));
1906
+ }
1907
+ complete("walletLink", { ownerChangeId: steps.walletLink.ownerChangeId });
1908
+ complete("sdkKey", { id: review.sdkKey.keyId, secretStoredIn: storedIn });
1909
+ ui.stop("Owner confirmed the wallet link and SDK key");
1910
+ ui.success(`Wallet linked ($${request.dailyLimit}/day limit) and SDK key created`);
1911
+ resources.sdkKey = { key: review.sdkKey.key, scopes: review.sdkKey.scopes };
1912
+ return { kind: "complete", resources: { wallet, agent, sdkKey: resources.sdkKey } };
1913
+ }
1145
1914
  if (steps.sdkKey.status === "done" && input.resuming) {
1146
1915
  const stored = await adoptStoredKey();
1147
1916
  if (typeof stored === "object") return stopped(stored);
@@ -1234,7 +2003,7 @@ function reconcileAction(step) {
1234
2003
  }
1235
2004
 
1236
2005
  // src/lib/setup-resources-client.ts
1237
- var REQUEST_TIMEOUT_MS = 3e4;
2006
+ var REQUEST_TIMEOUT_MS2 = 3e4;
1238
2007
  function isRecord(value) {
1239
2008
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
1240
2009
  }
@@ -1343,7 +2112,7 @@ var SetupResourcesClient = class {
1343
2112
  bearer,
1344
2113
  body,
1345
2114
  headers,
1346
- timeoutMs: REQUEST_TIMEOUT_MS
2115
+ timeoutMs: REQUEST_TIMEOUT_MS2
1347
2116
  });
1348
2117
  }
1349
2118
  async create(path3, body, label, parse, headers) {
@@ -1634,7 +2403,7 @@ function organizationBindingProblem(checkpoint, credential) {
1634
2403
  }
1635
2404
  async function runOrganizationInit(options) {
1636
2405
  const cwd = process.cwd();
1637
- const interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY);
2406
+ const interactive2 = Boolean(process.stdin.isTTY && process.stdout.isTTY);
1638
2407
  const providedOrgApiKey = options.apiKey || process.env.CONTO_ORG_API_KEY;
1639
2408
  if (options.resume && options.restart) {
1640
2409
  refuse("Use --resume or --restart, not both.", { code: "INVALID_OPTIONS" });
@@ -1676,7 +2445,7 @@ async function runOrganizationInit(options) {
1676
2445
  }
1677
2446
  discarded = { operationId: partial?.operationId, resources: recordedResources(partial) };
1678
2447
  }
1679
- if (!interactive && !providedOrgApiKey) {
2448
+ if (!interactive2 && !providedOrgApiKey) {
1680
2449
  failInit(
1681
2450
  [
1682
2451
  resumeFrom ? "Resuming setup without an interactive terminal needs an organization API key." : "create-conto-agent needs an interactive terminal for the setup wizard.",
@@ -1728,7 +2497,7 @@ async function runOrganizationInit(options) {
1728
2497
  `Resuming the setup started ${resumeFrom?.createdAt} for agent "${resumed.agentName}".`
1729
2498
  );
1730
2499
  }
1731
- const agentName = options.name || resumed?.agentName || (interactive ? await p.text({
2500
+ const agentName = options.name || resumed?.agentName || (interactive2 ? await p.text({
1732
2501
  message: "Agent name",
1733
2502
  placeholder: "my-procurement-bot",
1734
2503
  validate: (v) => (v ?? "").length < 2 ? "Name must be at least 2 characters" : void 0
@@ -1737,7 +2506,7 @@ async function runOrganizationInit(options) {
1737
2506
  p.cancel("Setup cancelled.");
1738
2507
  process.exit(0);
1739
2508
  }
1740
- const agentType = options.type || resumed?.agentType || (interactive ? await p.select({
2509
+ const agentType = options.type || resumed?.agentType || (interactive2 ? await p.select({
1741
2510
  message: "Agent type",
1742
2511
  options: [
1743
2512
  { value: "ANTHROPIC_CLAUDE", label: "Claude" },
@@ -1750,7 +2519,7 @@ async function runOrganizationInit(options) {
1750
2519
  p.cancel("Setup cancelled.");
1751
2520
  process.exit(0);
1752
2521
  }
1753
- const dailyLimit = options.limit || resumed?.dailyLimit || (interactive ? await p.text({
2522
+ const dailyLimit = options.limit || resumed?.dailyLimit || (interactive2 ? await p.text({
1754
2523
  message: "Daily spending limit (USD)",
1755
2524
  placeholder: "500",
1756
2525
  initialValue: "500",
@@ -1769,7 +2538,7 @@ async function runOrganizationInit(options) {
1769
2538
  const { chains: availableChains, defaultChainId } = await fetchChains(baseUrl);
1770
2539
  s0.stop(`Found ${Object.keys(availableChains).length} networks`);
1771
2540
  const chainChoices = getChainChoices(availableChains);
1772
- const selectedChain = options.chain || resumed?.chainId || process.env.CONTO_CHAIN_ID || (interactive ? await p.select({
2541
+ const selectedChain = options.chain || resumed?.chainId || process.env.CONTO_CHAIN_ID || (interactive2 ? await p.select({
1773
2542
  message: "Network",
1774
2543
  options: chainChoices,
1775
2544
  initialValue: defaultChainId
@@ -1786,7 +2555,7 @@ async function runOrganizationInit(options) {
1786
2555
  });
1787
2556
  }
1788
2557
  if (!chain.testnet && !options.confirmMainnet && !resumed?.mainnetConfirmed) {
1789
- if (!interactive) {
2558
+ if (!interactive2) {
1790
2559
  failInit(
1791
2560
  `Chain ${chain.chainId} (${chain.name}) is a mainnet and can move real funds. Re-run with --confirm-mainnet after reviewing the network and limits.`,
1792
2561
  { chainId: chain.chainId, requiresConfirmation: "--confirm-mainnet" }
@@ -1901,7 +2670,8 @@ async function runOrganizationInit(options) {
1901
2670
  ui,
1902
2671
  persist: () => saveCheckpoint(cwd, checkpoint),
1903
2672
  storeSdkKey: (sdkKey2, wallet2, agent2) => writeOrganizationEnvLocal(cwd, { sdkKey: sdkKey2, baseUrl, agent: agent2, wallet: wallet2, chain }),
1904
- storedSdkKey: (agentId) => storedSdkKeyFor(cwd, baseUrl, agentId)
2673
+ storedSdkKey: (agentId) => storedSdkKeyFor(cwd, baseUrl, agentId),
2674
+ reviewAccess: reviewAccessFor(baseUrl, orgApiKey)
1905
2675
  });
1906
2676
  if (provisioned.kind === "stopped") {
1907
2677
  reportStoppedSetup({
@@ -1915,30 +2685,33 @@ async function runOrganizationInit(options) {
1915
2685
  }
1916
2686
  const { wallet, agent, sdkKey } = provisioned.resources;
1917
2687
  writeOrganizationEnvLocal(cwd, { sdkKey: sdkKey.key, baseUrl, agent, wallet, chain });
1918
- writeContoConfig(cwd, {
1919
- agent: {
1920
- id: agent.id,
1921
- name: agent.name,
1922
- type: agentType
1923
- },
1924
- network: {
1925
- chain: selectedChainId,
1926
- chainId: chain.chainId,
1927
- rpcUrl: chain.rpcUrl,
1928
- explorerUrl: chain.explorerUrl,
1929
- currency: chain.currency,
1930
- testnet: chain.testnet
1931
- },
1932
- wallet: {
1933
- id: wallet.id,
1934
- address: wallet.address,
1935
- 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
+ }
1936
2712
  },
1937
- server: {
1938
- baseUrl
1939
- }
1940
- });
1941
- writeExampleFile(cwd);
2713
+ options
2714
+ );
1942
2715
  saveGlobalConfig({
1943
2716
  agent: { id: agent.id, name: agent.name, type: agentType },
1944
2717
  network: {
@@ -1976,9 +2749,10 @@ async function runOrganizationInit(options) {
1976
2749
  }
1977
2750
  }
1978
2751
  const cli = cliResolves ? "npx conto" : "npx @conto_finance/create-conto-agent";
2752
+ const exampleKept = keptFiles.includes("example.mjs");
1979
2753
  const nextSteps = [
1980
2754
  `${cli} doctor`,
1981
- "node example.mjs",
2755
+ ...exampleKept ? [] : ["node example.mjs"],
1982
2756
  `${cli} pay <address> <amount>`,
1983
2757
  `${cli} mcp`
1984
2758
  ];
@@ -1999,7 +2773,8 @@ async function runOrganizationInit(options) {
1999
2773
  storedIn: ".env.local",
2000
2774
  sdkKeyEnv: "CONTO_API_KEY"
2001
2775
  },
2002
- files: [".env.local", ".gitignore", "conto.config.json", "example.mjs"],
2776
+ files: PROJECT_FILES.filter((file) => !keptFiles.includes(file)),
2777
+ ...keptFiles.length > 0 ? { keptFiles } : {},
2003
2778
  ...resumeFrom ? { resumed: true } : {},
2004
2779
  ...discarded ? { discardedSetup: discarded } : {},
2005
2780
  nextSteps
@@ -2007,28 +2782,35 @@ async function runOrganizationInit(options) {
2007
2782
  return;
2008
2783
  }
2009
2784
  console.log("");
2010
- console.log(chalk.green.bold(" Your agent is ready!") + " Files written:\n");
2011
- console.log(` ${chalk.bold(".env.local")} - SDK key + config`);
2012
- console.log(` ${chalk.bold("conto.config.json")} - Agent metadata`);
2013
- console.log(` ${chalk.bold("example.mjs")} - Runnable payment example`);
2785
+ console.log(chalk2.green.bold(" Your agent is ready!") + " Files written:\n");
2786
+ console.log(` ${chalk2.bold(".env.local")} - SDK key + config`);
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
+ }
2014
2793
  console.log("");
2794
+ printKeptFiles(keptFiles);
2015
2795
  console.log(
2016
- ` ${chalk.dim("Wallet:")} ${wallet.address} (${chain.name}${chain.testnet ? " testnet" : ""}, ${wallet.custodyMode ?? "MANAGED"} custody)`
2796
+ ` ${chalk2.dim("Wallet:")} ${wallet.address} (${chain.name}${chain.testnet ? " testnet" : ""}, ${wallet.custodyMode ?? "MANAGED"} custody)`
2017
2797
  );
2018
- console.log(` ${chalk.dim("Currency:")} ${chain.currency}`);
2019
- console.log(` ${chalk.dim("Explorer:")} ${chain.explorerUrl}`);
2798
+ console.log(` ${chalk2.dim("Currency:")} ${chain.currency}`);
2799
+ console.log(` ${chalk2.dim("Explorer:")} ${chain.explorerUrl}`);
2020
2800
  console.log("");
2021
- console.log(chalk.bold(" Next steps:"));
2801
+ console.log(chalk2.bold(" Next steps:"));
2022
2802
  let step = 1;
2023
- console.log(` ${step++}. Verify setup: ${chalk.cyan(`${cli} doctor`)}`);
2803
+ console.log(` ${step++}. Verify setup: ${chalk2.cyan(`${cli} doctor`)}`);
2024
2804
  if (!chain.faucetAvailable) {
2025
2805
  console.log(
2026
- ` ${step++}. Fund your wallet with ${chain.currency} ${chalk.dim("\u2192")} ${wallet.address}`
2806
+ ` ${step++}. Fund your wallet with ${chain.currency} ${chalk2.dim("\u2192")} ${wallet.address}`
2027
2807
  );
2028
2808
  }
2029
- console.log(` ${step++}. Run the example: ${chalk.cyan("node example.mjs")}`);
2030
- console.log(` ${step++}. Make a payment: ${chalk.cyan(`${cli} pay <address> <amount>`)}`);
2031
- console.log(` ${step++}. Connect Claude: ${chalk.cyan(`${cli} mcp`)}`);
2809
+ if (!exampleKept) {
2810
+ console.log(` ${step++}. Run the example: ${chalk2.cyan("node example.mjs")}`);
2811
+ }
2812
+ console.log(` ${step++}. Make a payment: ${chalk2.cyan(`${cli} pay <address> <amount>`)}`);
2813
+ console.log(` ${step++}. Connect Claude: ${chalk2.cyan(`${cli} mcp`)}`);
2032
2814
  if (!cliResolves) {
2033
2815
  printInfo(
2034
2816
  'Tip: "npx conto <command>" works after: npm install --save-dev @conto_finance/create-conto-agent'
@@ -2096,7 +2878,7 @@ function reportStoppedSetup(input) {
2096
2878
  const resources = recordedResources(checkpoint);
2097
2879
  if (completedSteps.length > 0) {
2098
2880
  console.log("");
2099
- console.log(chalk.bold(" Created and kept:"));
2881
+ console.log(chalk2.bold(" Created and kept:"));
2100
2882
  if (resources.walletId) {
2101
2883
  console.log(` Wallet ${resources.walletAddress ?? ""} (${resources.walletId})`);
2102
2884
  }
@@ -2218,6 +3000,7 @@ async function runSandboxInit(options) {
2218
3000
  "",
2219
3001
  "# Sandbox (shown once, keep private)",
2220
3002
  ["CONTO_SANDBOX_API_KEY", sandbox.credentials.apiKey],
3003
+ ["CONTO_SANDBOX_MODE", "test"],
2221
3004
  ["CONTO_SANDBOX_EXPIRES_AT", sandbox.expiresAt]
2222
3005
  ]);
2223
3006
  const setupKeyFile = sandbox.credentials.setupKey ? (ensureContoDirGitignored(cwd), writeSandboxSetupEnv(cwd, [
@@ -2231,34 +3014,38 @@ async function runSandboxInit(options) {
2231
3014
  ["CONTO_WALLET_ID", sandbox.wallet.id],
2232
3015
  ["CONTO_SANDBOX_EXPIRES_AT", sandbox.expiresAt]
2233
3016
  ])) : null;
2234
- writeContoConfig(cwd, {
2235
- agent: {
2236
- id: sandbox.agent.id,
2237
- name: sandbox.agent.name,
2238
- type: options.type || "CUSTOM"
2239
- },
2240
- network: {
2241
- chain: sandbox.wallet.chainId,
2242
- chainId: sandbox.wallet.chainId,
2243
- rpcUrl: chain?.rpcUrl || "",
2244
- explorerUrl: chain?.explorerUrl || "",
2245
- currency: chain?.currency || sandbox.wallet.currency,
2246
- testnet: true
2247
- },
2248
- wallet: {
2249
- id: sandbox.wallet.id,
2250
- address: sandbox.wallet.address,
2251
- custodyMode: sandbox.wallet.custodyMode
2252
- },
2253
- server: {
2254
- 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
+ }
2255
3045
  },
2256
- sandbox: {
2257
- mode: "test",
2258
- expiresAt: sandbox.expiresAt
2259
- }
2260
- });
2261
- writeExampleFile(cwd);
3046
+ options
3047
+ );
3048
+ const exampleKept = keptFiles.includes("example.mjs");
2262
3049
  saveGlobalConfig({
2263
3050
  agent: {
2264
3051
  id: sandbox.agent.id,
@@ -2309,20 +3096,17 @@ async function runSandboxInit(options) {
2309
3096
  ...setupKeyFile ? { setupKeyStoredIn: setupKeyFile, setupKeyEnv: "CONTO_SANDBOX_SETUP_KEY" } : {}
2310
3097
  },
2311
3098
  files: [
2312
- ".env.local",
2313
- ".gitignore",
2314
- "conto.config.json",
2315
- "example.mjs",
3099
+ ...PROJECT_FILES.filter((file) => !keptFiles.includes(file)),
2316
3100
  ...setupKeyFile ? [setupKeyFile] : []
2317
3101
  ],
3102
+ ...keptFiles.length > 0 ? { keptFiles } : {},
2318
3103
  claim: {
2319
3104
  command: `${cli} sandbox claim --json`,
2320
3105
  credentialEnv: "CONTO_SANDBOX_API_KEY",
2321
3106
  ...sandbox.claim ? { method: sandbox.claim.method, endpoint: sandbox.claim.endpoint } : {}
2322
3107
  },
2323
3108
  nextSteps: [
2324
- "node example.mjs",
2325
- "node example.mjs --resume REQUEST_ID",
3109
+ ...exampleKept ? [] : ["node example.mjs", "node example.mjs --resume REQUEST_ID"],
2326
3110
  `${cli} doctor`,
2327
3111
  `${cli} pay 0x742d35Cc6634C0532925a3b844Bc454e4438f44e 1 --purpose test`,
2328
3112
  `${cli} sandbox claim --json`
@@ -2331,32 +3115,41 @@ async function runSandboxInit(options) {
2331
3115
  return;
2332
3116
  }
2333
3117
  console.log("");
2334
- console.log(chalk.green.bold(" Sandbox agent ready!") + " Files written:\n");
2335
- console.log(` ${chalk.bold(".env.local")} - SDK key + config (shown once)`);
2336
- console.log(` ${chalk.bold("conto.config.json")} - Agent metadata`);
2337
- console.log(` ${chalk.bold("example.mjs")} - Runnable payment example`);
3118
+ console.log(chalk2.green.bold(" Sandbox agent ready!") + " Files written:\n");
3119
+ console.log(` ${chalk2.bold(".env.local")} - SDK key + config (shown once)`);
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
+ }
2338
3126
  if (setupKeyFile) {
2339
3127
  console.log(
2340
- ` ${chalk.bold(setupKeyFile)} - Setup key for policies and limits (keep out of the agent runtime)`
3128
+ ` ${chalk2.bold(setupKeyFile)} - Setup key for policies and limits (keep out of the agent runtime)`
2341
3129
  );
2342
3130
  }
2343
3131
  console.log("");
3132
+ printKeptFiles(keptFiles);
2344
3133
  console.log(
2345
- ` ${chalk.dim("Wallet:")} ${sandbox.wallet.address} (${chain?.name || sandbox.wallet.chainId}, test mode)`
3134
+ ` ${chalk2.dim("Wallet:")} ${sandbox.wallet.address} (${chain?.name || sandbox.wallet.chainId}, test mode)`
2346
3135
  );
2347
3136
  console.log(
2348
- ` ${chalk.dim("Balance:")} ${sandbox.wallet.balance} ${sandbox.wallet.currency} (test balance)`
3137
+ ` ${chalk2.dim("Balance:")} ${sandbox.wallet.balance} ${sandbox.wallet.currency} (test balance)`
2349
3138
  );
2350
3139
  console.log(
2351
- ` ${chalk.dim("Limits:")} $${sandbox.wallet.limits.perTransaction}/tx, $${sandbox.wallet.limits.daily}/day${setupKeyFile ? " (editable with the setup key)" : ""}`
3140
+ ` ${chalk2.dim("Limits:")} $${sandbox.wallet.limits.perTransaction}/tx, $${sandbox.wallet.limits.daily}/day${setupKeyFile ? " (editable with the setup key)" : ""}`
2352
3141
  );
2353
- console.log(` ${chalk.dim("Expires:")} ${sandbox.expiresAt}`);
3142
+ console.log(` ${chalk2.dim("Expires:")} ${sandbox.expiresAt}`);
2354
3143
  console.log("");
2355
- console.log(chalk.bold(" Next steps:"));
2356
- console.log(` 1. Run the example: ${chalk.cyan("node example.mjs")}`);
2357
- console.log(` 2. Continue it: ${chalk.cyan("node example.mjs --resume REQUEST_ID")}`);
2358
- console.log(" Replace REQUEST_ID with the ID printed by the example.");
2359
- console.log(` 3. Verify setup: ${chalk.cyan(`${cli} doctor`)}`);
3144
+ console.log(chalk2.bold(" Next steps:"));
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
+ }
2360
3153
  console.log("");
2361
3154
  printInfo(
2362
3155
  "Sandbox test payments exercise policy checks, receipts, and spend tracking without an onchain transfer."
@@ -2408,8 +3201,58 @@ function installCliLocally(cwd, agentName) {
2408
3201
  }
2409
3202
  return "failed";
2410
3203
  }
2411
- function writeExampleFile(dir) {
2412
- 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.
2413
3256
  //
2414
3257
  // Usage:
2415
3258
  // node example.mjs Check setup and request a test payment (no funds move)
@@ -2543,14 +3386,10 @@ main().catch((err) => {
2543
3386
  process.exit(1);
2544
3387
  });
2545
3388
  `;
2546
- fs2.writeFileSync(path2.join(dir, "example.mjs"), content);
2547
3389
  }
2548
3390
 
2549
3391
  export {
2550
3392
  CLI_PACKAGE_VERSION,
2551
- fetchChains,
2552
- getChain,
2553
- browserAuth,
2554
3393
  HttpTransportError,
2555
3394
  redactSecrets,
2556
3395
  parseSecureBaseUrl,
@@ -2560,6 +3399,19 @@ export {
2560
3399
  retryAfterSeconds,
2561
3400
  responseErrorMessage,
2562
3401
  responseErrorCode,
3402
+ NOTHING_SENT_CODES,
3403
+ ApiClient,
3404
+ createApiClient,
3405
+ fetchChains,
3406
+ getChain,
3407
+ createOwnerClient,
3408
+ REVIEW_EXIT_CODES_HELP,
3409
+ isTightenOnlyRefusal,
3410
+ followChange,
3411
+ proposeForReview,
3412
+ directOrReview,
3413
+ reportReview,
3414
+ browserAuth,
2563
3415
  projectStateFile,
2564
3416
  readProjectStateFile,
2565
3417
  writeProjectStateFile,