@conto_finance/create-conto-agent 0.4.6 → 0.5.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.
package/dist/cli.js CHANGED
@@ -1,23 +1,32 @@
1
1
  import {
2
+ ApiClient,
2
3
  CLI_PACKAGE_VERSION,
3
4
  HttpTransportError,
5
+ REVIEW_EXIT_CODES_HELP,
4
6
  apiUrl,
5
7
  browserAuth,
8
+ createApiClient,
9
+ createOwnerClient,
10
+ directOrReview,
6
11
  fetchChains,
7
12
  fingerprintSecret,
13
+ followChange,
8
14
  getChain,
15
+ isTightenOnlyRefusal,
9
16
  normalizeBaseUrl,
10
17
  parseSecureBaseUrl,
11
18
  projectStateFile,
19
+ proposeForReview,
12
20
  readProjectStateFile,
13
21
  redactSecrets,
22
+ reportReview,
14
23
  requestJson,
15
24
  responseErrorCode,
16
25
  responseErrorMessage,
17
26
  retryAfterSeconds,
18
27
  runInit,
19
28
  writeProjectStateFile
20
- } from "./chunk-MASQPQTP.js";
29
+ } from "./chunk-HDSRGTWB.js";
21
30
  import {
22
31
  VELOCITY_PERIODS,
23
32
  buildVelocityCountValue,
@@ -53,228 +62,43 @@ import {
53
62
  // src/cli.ts
54
63
  import { Command } from "commander";
55
64
 
56
- // src/lib/api-client.ts
57
- var REQUEST_TIMEOUT_MS = 3e4;
58
- function assertSecureBaseUrl(baseUrl) {
59
- let parsed;
65
+ // src/commands/test-report.ts
66
+ import fs from "fs";
67
+ async function testReportCommand(options) {
60
68
  try {
61
- parsed = new URL(baseUrl);
62
- } catch {
63
- throw new Error(`Invalid base URL: ${baseUrl}`);
64
- }
65
- if (parsed.protocol !== "https:" && parsed.hostname !== "localhost" && parsed.hostname !== "127.0.0.1") {
66
- throw new Error("baseUrl must use https (except for localhost)");
67
- }
68
- }
69
- var ApiClient = class {
70
- baseUrl;
71
- apiKey;
72
- orgApiKey;
73
- constructor(options) {
74
- this.baseUrl = options.baseUrl.replace(/\/$/, "");
75
- assertSecureBaseUrl(this.baseUrl);
76
- this.apiKey = options.apiKey;
77
- this.orgApiKey = options.orgApiKey;
78
- }
79
- async request(method, path2, options) {
80
- const url = `${this.baseUrl}${path2}`;
81
- const authType = options?.auth || "sdk";
82
- const token = authType === "org" ? this.orgApiKey : this.apiKey;
83
- const headers = {
84
- "Content-Type": "application/json",
85
- "User-Agent": `create-conto-agent/${CLI_PACKAGE_VERSION}`
86
- };
87
- if (token) {
88
- headers["Authorization"] = `Bearer ${token}`;
89
- }
90
- const controller = new AbortController();
91
- const timeoutId = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
69
+ const config = loadConfig();
70
+ if (!config.apiKey) throw new Error(missingSdkKeyMessage(config));
71
+ const report = await createApiClient({
72
+ baseUrl: config.baseUrl,
73
+ apiKey: config.apiKey
74
+ }).getTestReport(options);
75
+ const fd = fs.openSync(options.output, "wx", 384);
92
76
  try {
93
- const response = await fetch(url, {
94
- method,
95
- headers,
96
- body: options?.body ? JSON.stringify(options.body) : void 0,
97
- signal: controller.signal
98
- });
99
- const contentType = response.headers.get("content-type") || "";
100
- if (!contentType.includes("application/json")) {
101
- const error = new Error(
102
- response.status === 404 ? `API endpoint not found: ${path2}` : `API returned non-JSON response (${response.status})`
103
- );
104
- error.code = response.status === 404 ? "NOT_FOUND" : "INVALID_RESPONSE";
105
- error.status = response.status;
106
- throw error;
107
- }
108
- const data = await response.json();
109
- if (!response.ok) {
110
- const error = new Error(data.error || `API request failed: ${response.status}`);
111
- error.code = data.code || "API_ERROR";
112
- error.status = response.status;
113
- error.body = data;
114
- throw error;
115
- }
116
- return data;
117
- } catch (err) {
118
- if (err instanceof Error && err.name === "AbortError") {
119
- const error = new Error(
120
- `Request timed out after ${REQUEST_TIMEOUT_MS / 1e3}s`
121
- );
122
- error.code = "TIMEOUT";
123
- error.status = 0;
124
- throw error;
125
- }
126
- throw err;
127
- } finally {
128
- clearTimeout(timeoutId);
77
+ fs.writeFileSync(
78
+ fd,
79
+ JSON.stringify(
80
+ { ...report, milestones: { ...report.milestones, savedForReview: true } },
81
+ null,
82
+ 2
83
+ ) + "\n"
84
+ );
85
+ } catch (error) {
86
+ fs.closeSync(fd);
87
+ fs.unlinkSync(options.output);
88
+ throw error;
129
89
  }
130
- }
131
- // ── Org-level Admin APIs (used during init) ──
132
- async createWallet(params) {
133
- return this.request("POST", "/api/wallets", { body: params, auth: "org" });
134
- }
135
- async createAgent(params) {
136
- return this.request("POST", "/api/agents", { body: params, auth: "org" });
137
- }
138
- async linkWalletToAgent(agentId, params) {
139
- return this.request("POST", `/api/agents/${encodeURIComponent(agentId)}/wallets`, {
140
- body: params,
141
- auth: "org"
142
- });
143
- }
144
- async createPolicy(params) {
145
- return this.request("POST", "/api/policies", { body: params, auth: "org" });
146
- }
147
- async updatePolicy(policyId, params) {
148
- return this.request("PATCH", `/api/policies/${encodeURIComponent(policyId)}`, { body: params, auth: "org" });
149
- }
150
- async deletePolicy(policyId) {
151
- return this.request("DELETE", `/api/policies/${encodeURIComponent(policyId)}`, { auth: "org" });
152
- }
153
- async addPolicyRule(policyId, rule) {
154
- return this.request(
155
- "POST",
156
- `/api/policies/${encodeURIComponent(policyId)}/rules`,
157
- {
158
- body: rule,
159
- auth: "org"
160
- }
161
- );
162
- }
163
- async deletePolicyRule(policyId, ruleId) {
164
- return this.request(
165
- "DELETE",
166
- `/api/policies/${encodeURIComponent(policyId)}/rules/${encodeURIComponent(ruleId)}`,
167
- { auth: "org" }
168
- );
169
- }
170
- async listOrgPolicies() {
171
- return this.request("GET", "/api/policies", { auth: "org" });
172
- }
173
- async assignPolicyToAgent(agentId, policyId) {
174
- return this.request("POST", `/api/agents/${encodeURIComponent(agentId)}/policies`, {
175
- body: { policyId },
176
- auth: "org"
177
- });
178
- }
179
- async unassignPolicyFromAgent(agentId, policyId) {
180
- return this.request(
181
- "DELETE",
182
- `/api/agents/${encodeURIComponent(agentId)}/policies?policyId=${encodeURIComponent(policyId)}`,
183
- {
184
- auth: "org"
185
- }
186
- );
187
- }
188
- async createSdkKey(agentId, params) {
189
- return this.request("POST", `/api/agents/${encodeURIComponent(agentId)}/sdk-keys`, {
190
- body: params,
191
- auth: "org"
90
+ fs.closeSync(fd);
91
+ printJson({
92
+ savedTo: options.output,
93
+ milestones: { ...report.milestones, savedForReview: true },
94
+ reviewCoverage: report.reviewCoverage
192
95
  });
96
+ if (!report.milestones.controlsVerified || !report.milestones.evidencePrepared)
97
+ process.exitCode = 2;
98
+ } catch (error) {
99
+ printError(error instanceof Error ? error.message : "Could not save the test report.");
100
+ process.exitCode = 1;
193
101
  }
194
- async fundWallet(walletId) {
195
- return this.request("POST", `/api/wallets/${encodeURIComponent(walletId)}/faucet`, { auth: "org" });
196
- }
197
- // ── SDK Agent APIs (used by CLI commands) ──
198
- async getSetup() {
199
- return this.request("GET", "/api/sdk/setup");
200
- }
201
- async getAgentInfo() {
202
- const data = await this.request("GET", "/api/sdk/agents/me");
203
- return {
204
- agent: {
205
- id: data.id,
206
- name: data.name,
207
- agentType: data.agentType,
208
- status: data.status,
209
- createdAt: data.createdAt
210
- },
211
- organization: { name: data.organizationId },
212
- walletCount: data.summary?.walletCount ?? 0,
213
- summary: data.summary
214
- };
215
- }
216
- async getWallets() {
217
- return this.request("GET", "/api/sdk/wallets");
218
- }
219
- async getSpendingLimits() {
220
- const data = await this.request("GET", "/api/sdk/spending-limits");
221
- return {
222
- limits: (data.wallets || []).map((w) => ({
223
- walletId: w.walletId,
224
- walletName: w.name,
225
- daily: {
226
- limit: w.limits?.daily ?? 0,
227
- spent: w.spent?.today ?? 0,
228
- remaining: w.remaining?.daily ?? 0
229
- },
230
- weekly: w.limits?.weekly ? {
231
- limit: w.limits.weekly,
232
- spent: w.spent?.thisWeek ?? 0,
233
- remaining: w.remaining?.weekly ?? 0
234
- } : void 0,
235
- monthly: w.limits?.monthly ? {
236
- limit: w.limits.monthly,
237
- spent: w.spent?.thisMonth ?? 0,
238
- remaining: w.remaining?.monthly ?? 0
239
- } : void 0,
240
- perTransaction: w.limits?.perTransaction ?? 0
241
- }))
242
- };
243
- }
244
- async requestPayment(params) {
245
- return this.request("POST", "/api/sdk/payments/request", { body: params });
246
- }
247
- async executePayment(requestId) {
248
- return this.request("POST", `/api/sdk/payments/${encodeURIComponent(requestId)}/execute`, { body: {} });
249
- }
250
- async getPaymentStatus(requestId) {
251
- return this.request("GET", `/api/sdk/payments/${encodeURIComponent(requestId)}`);
252
- }
253
- async getTransactions(params) {
254
- const query = new URLSearchParams();
255
- if (params?.limit) query.set("limit", String(params.limit));
256
- if (params?.status) query.set("status", params.status);
257
- const qs = query.toString() ? `?${query.toString()}` : "";
258
- return this.request("GET", `/api/sdk/transactions${qs}`);
259
- }
260
- async getTransaction(id) {
261
- return this.request("GET", `/api/sdk/transactions/${encodeURIComponent(id)}`);
262
- }
263
- async getPolicies() {
264
- return this.request("GET", "/api/sdk/policies");
265
- }
266
- async getAlerts(params) {
267
- const query = new URLSearchParams();
268
- if (params?.status) query.set("status", params.status);
269
- const qs = query.toString() ? `?${query.toString()}` : "";
270
- return this.request("GET", `/api/sdk/alerts${qs}`);
271
- }
272
- async getAnalytics() {
273
- return this.request("GET", "/api/sdk/analytics");
274
- }
275
- };
276
- function createApiClient(options) {
277
- return new ApiClient(options);
278
102
  }
279
103
 
280
104
  // src/commands/status.ts
@@ -921,9 +745,171 @@ async function balanceCommand() {
921
745
  }
922
746
 
923
747
  // src/commands/pay.ts
748
+ import chalk3 from "chalk";
749
+
750
+ // src/lib/payment-review.ts
924
751
  import chalk2 from "chalk";
752
+ var PAYMENT_EXIT_CODES_HELP = `
753
+ Payments that need approval:
754
+ the command prints a review link, opens it when it can, waits for the
755
+ decision, and sends the payment once it is approved.
756
+
757
+ conto pay status <requestId> Check a payment waiting for approval
758
+ conto pay execute <requestId> Send a payment an approver already approved
759
+
760
+ Exit codes:
761
+ 0 sent, or already handled
762
+ 1 request failed
763
+ 3 an approver rejected the payment
764
+ 4 still waiting for approval (--no-wait, or the wait timed out)
765
+ 5 the approval expired or was cancelled
766
+ `;
767
+ var PAY_EXIT_REJECTED = 3;
768
+ var PAY_EXIT_PENDING = 4;
769
+ var PAY_EXIT_EXPIRED = 5;
770
+ var POLL_INTERVAL_MS = Number(process.env.CONTO_REVIEW_POLL_MS) || 3e3;
771
+ var DEFAULT_WAIT_SECONDS = 300;
772
+ var PaymentReviewClient = class extends ApiClient {
773
+ startReview(paymentRequestId) {
774
+ return this.request("POST", "/api/sdk/approval-reviews", {
775
+ body: { paymentRequestId, client: { name: "conto-cli", version: CLI_PACKAGE_VERSION } }
776
+ });
777
+ }
778
+ getReview(reviewSessionId) {
779
+ return this.request(
780
+ "GET",
781
+ `/api/sdk/approval-reviews/${encodeURIComponent(reviewSessionId)}`
782
+ );
783
+ }
784
+ };
785
+ function interactive() {
786
+ return Boolean(process.stdout.isTTY) && !isJsonMode();
787
+ }
788
+ function waitSeconds(wait) {
789
+ if (wait === false) return 0;
790
+ if (typeof wait === "string" && wait.trim() !== "") {
791
+ const seconds = Number(wait);
792
+ if (!Number.isFinite(seconds) || seconds < 0)
793
+ throw new Error("--wait takes a number of seconds");
794
+ return Math.min(Math.round(seconds), DEFAULT_WAIT_SECONDS);
795
+ }
796
+ if (wait === true) return DEFAULT_WAIT_SECONDS;
797
+ return interactive() ? DEFAULT_WAIT_SECONDS : 0;
798
+ }
799
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
800
+ async function followPaymentReview(api, paymentRequestId, options = {}) {
801
+ let review = await api.startReview(paymentRequestId);
802
+ if (review.nextAction.type === "START_REVIEW_AGAIN") {
803
+ review = await api.startReview(paymentRequestId);
804
+ }
805
+ if (review.state === "PENDING_REVIEW" && review.reviewUrl && !isJsonMode()) {
806
+ printPending("This payment needs an approver to confirm it.");
807
+ printKeyValue("Review", review.reviewUrl);
808
+ if (options.open ?? interactive()) {
809
+ try {
810
+ const open = (await import("open")).default;
811
+ await open(review.reviewUrl);
812
+ } catch {
813
+ }
814
+ }
815
+ }
816
+ const deadline = Date.now() + waitSeconds(options.wait) * 1e3;
817
+ while (review.nextAction.type === "WAIT_FOR_REVIEW" && Date.now() < deadline) {
818
+ await sleep(POLL_INTERVAL_MS);
819
+ review = await api.getReview(review.reviewSessionId);
820
+ }
821
+ return review;
822
+ }
823
+ function paymentReviewExitCode(review) {
824
+ if (review.state === "REJECTED") return PAY_EXIT_REJECTED;
825
+ if (review.state === "EXPIRED" || review.state === "CANCELLED") return PAY_EXIT_EXPIRED;
826
+ if (review.nextAction.type === "WAIT_FOR_REVIEW" || review.state === "CHANGED") {
827
+ return PAY_EXIT_PENDING;
828
+ }
829
+ return 0;
830
+ }
831
+ function printReviewOutcome(review, requestId) {
832
+ if (review.nextAction.type === "WAIT_FOR_REVIEW") {
833
+ printPending("Still waiting for approval. Nothing was sent.");
834
+ console.log(chalk2.dim(` Check later with: conto pay status ${requestId}`));
835
+ return;
836
+ }
837
+ console.log(chalk2.dim(` ${review.nextAction.message}`));
838
+ }
839
+
840
+ // src/commands/pay.ts
841
+ async function sendPayment(api, requestId, config) {
842
+ const result = await api.executePayment(requestId);
843
+ if (isJsonMode()) {
844
+ printJson(result);
845
+ return;
846
+ }
847
+ if (config.sandboxMode === "test") {
848
+ printSuccess("Payment recorded in sandbox test mode");
849
+ } else {
850
+ printSuccess("Payment sent!");
851
+ }
852
+ if (result.receipt?.txHash) printKeyValue("TX Hash", result.receipt?.txHash);
853
+ printKeyValue("Amount", printAmount(result.amount, result.currency));
854
+ printKeyValue("Recipient", result.recipient);
855
+ printKeyValue("Status", result.status);
856
+ printKeyValue("Request ID", requestId);
857
+ if (result.receipt?.settlementMode)
858
+ printKeyValue("Settlement mode", result.receipt.settlementMode);
859
+ if (result.receipt?.explorerUrl) printKeyValue("Explorer", result.receipt?.explorerUrl);
860
+ console.log("");
861
+ }
862
+ async function reviewAndSend(api, requestId, config, options) {
863
+ const review = await followPaymentReview(api, requestId, options);
864
+ if (review.nextAction.type === "EXECUTE_PAYMENT") {
865
+ return sendPayment(api, requestId, config);
866
+ }
867
+ process.exitCode = paymentReviewExitCode(review);
868
+ if (isJsonMode()) {
869
+ printJson({ requestId, review });
870
+ return;
871
+ }
872
+ printReviewOutcome(review, requestId);
873
+ }
874
+ function handlePayError(err) {
875
+ const code = err.code;
876
+ const message = err instanceof Error ? err.message : "Payment failed";
877
+ if (isJsonMode()) {
878
+ printJson({ error: message, code });
879
+ process.exit(1);
880
+ }
881
+ printError(message);
882
+ if (code === "INSUFFICIENT_SCOPE") {
883
+ console.log(
884
+ chalk3.dim(' This SDK key cannot execute payments. Run "conto doctor" to see its scopes,')
885
+ );
886
+ console.log(chalk3.dim(" or create a new standard SDK key (includes payments:execute)."));
887
+ } else if (code === "EXECUTION_UNAVAILABLE") {
888
+ console.log(chalk3.dim(" Try again later or contact Conto support if the issue continues."));
889
+ }
890
+ process.exit(1);
891
+ }
892
+ async function payFollowUpCommand(subcommand, requestId, options) {
893
+ const config = loadConfig();
894
+ if (!config.apiKey) {
895
+ printError(
896
+ 'Not configured. Run "npx @conto_finance/create-conto-agent" or "conto login" first.'
897
+ );
898
+ process.exit(1);
899
+ }
900
+ const api = new PaymentReviewClient({ baseUrl: config.baseUrl, apiKey: config.apiKey });
901
+ try {
902
+ if (subcommand === "execute") return await sendPayment(api, requestId, config);
903
+ return await reviewAndSend(api, requestId, config, { wait: false, open: false, ...options });
904
+ } catch (err) {
905
+ handlePayError(err);
906
+ }
907
+ }
925
908
  var DRY_RUN_NOTICE = "Dry run: nothing was sent to Conto and no policy evaluation was performed.";
926
909
  async function payCommand(address, amountStr, options) {
910
+ if (address === "status" || address === "execute") {
911
+ return payFollowUpCommand(address, amountStr, options);
912
+ }
927
913
  const config = loadConfig();
928
914
  const validation = validatePaymentRequest({
929
915
  address,
@@ -945,7 +931,7 @@ async function payCommand(address, amountStr, options) {
945
931
  });
946
932
  } else {
947
933
  for (const error of validation.errors) printError(error);
948
- console.log(chalk2.dim(`
934
+ console.log(chalk3.dim(`
949
935
  ${DRY_RUN_NOTICE}`));
950
936
  }
951
937
  process.exit(1);
@@ -969,15 +955,15 @@ async function payCommand(address, amountStr, options) {
969
955
  if (options.wallet) printKeyValue("Wallet", options.wallet);
970
956
  console.log("");
971
957
  printSuccess("Input is valid");
972
- console.log(chalk2.dim(` Would send: POST ${url}`));
973
- console.log(chalk2.dim(` ${JSON.stringify(validation.body)}`));
958
+ console.log(chalk3.dim(` Would send: POST ${url}`));
959
+ console.log(chalk3.dim(` ${JSON.stringify(validation.body)}`));
974
960
  if (!config.apiKey) {
975
961
  printWarning('No API key configured. Run "conto login" before sending payments.');
976
962
  }
977
963
  console.log("");
978
964
  printWarning(DRY_RUN_NOTICE);
979
- console.log(chalk2.dim(' Run "conto limits" to see current spend limits.'));
980
- console.log(chalk2.dim(" Run without --dry-run to submit the payment for policy evaluation."));
965
+ console.log(chalk3.dim(' Run "conto limits" to see current spend limits.'));
966
+ console.log(chalk3.dim(" Run without --dry-run to submit the payment for policy evaluation."));
981
967
  console.log("");
982
968
  return;
983
969
  }
@@ -992,7 +978,7 @@ async function payCommand(address, amountStr, options) {
992
978
  process.exit(1);
993
979
  }
994
980
  const amount = validation.body.amount;
995
- const api = createApiClient({
981
+ const api = new PaymentReviewClient({
996
982
  baseUrl: config.baseUrl,
997
983
  apiKey: config.apiKey
998
984
  });
@@ -1019,24 +1005,18 @@ async function payCommand(address, amountStr, options) {
1019
1005
  printError("Payment denied by policy");
1020
1006
  if (request.violations) {
1021
1007
  for (const v of request.violations) {
1022
- console.log(chalk2.red(` ${v.message}`));
1008
+ console.log(chalk3.red(` ${v.message}`));
1023
1009
  }
1024
1010
  }
1025
1011
  if (request.reasons.length > 0) {
1026
- console.log(chalk2.dim(`
1012
+ console.log(chalk3.dim(`
1027
1013
  Reasons: ${request.reasons.join(", ")}`));
1028
1014
  }
1029
1015
  process.exit(1);
1030
1016
  }
1031
1017
  if (request.status === "REQUIRES_APPROVAL") {
1032
- if (isJsonMode()) {
1033
- printJson(request);
1034
- return;
1035
- }
1036
- printPending("Payment requires manual approval");
1037
- printKeyValue("Request ID", request.requestId);
1038
- console.log(chalk2.dim(" Approve in the Conto dashboard to execute."));
1039
- return;
1018
+ if (!isJsonMode()) printKeyValue("Request ID", request.requestId);
1019
+ return await reviewAndSend(api, request.requestId, config, options);
1040
1020
  }
1041
1021
  if (request.status !== "APPROVED") {
1042
1022
  if (isJsonMode()) {
@@ -1046,47 +1026,14 @@ async function payCommand(address, amountStr, options) {
1046
1026
  printPending(`Payment is ${request.status}`);
1047
1027
  printKeyValue("Request ID", request.requestId);
1048
1028
  if (request.reasons.length > 0) {
1049
- console.log(chalk2.dim(` Reasons: ${request.reasons.join(", ")}`));
1029
+ console.log(chalk3.dim(` Reasons: ${request.reasons.join(", ")}`));
1050
1030
  }
1051
- console.log(chalk2.dim(" Check the Conto dashboard for next steps."));
1052
- return;
1053
- }
1054
- const result = await api.executePayment(request.requestId);
1055
- if (isJsonMode()) {
1056
- printJson(result);
1031
+ console.log(chalk3.dim(" Check the Conto dashboard for next steps."));
1057
1032
  return;
1058
1033
  }
1059
- if (config.sandboxMode === "test") {
1060
- printSuccess("Payment recorded in sandbox test mode");
1061
- } else {
1062
- printSuccess("Payment sent!");
1063
- }
1064
- if (result.receipt?.txHash) printKeyValue("TX Hash", result.receipt?.txHash);
1065
- printKeyValue("Amount", printAmount(result.amount, result.currency));
1066
- printKeyValue("Recipient", result.recipient);
1067
- printKeyValue("Status", result.status);
1068
- printKeyValue("Request ID", request.requestId);
1069
- if (result.receipt?.settlementMode)
1070
- printKeyValue("Settlement mode", result.receipt.settlementMode);
1071
- if (result.receipt?.explorerUrl) printKeyValue("Explorer", result.receipt?.explorerUrl);
1072
- console.log("");
1034
+ await sendPayment(api, request.requestId, config);
1073
1035
  } catch (err) {
1074
- const code = err.code;
1075
- const message = err instanceof Error ? err.message : "Payment failed";
1076
- if (isJsonMode()) {
1077
- printJson({ error: message, code });
1078
- process.exit(1);
1079
- }
1080
- printError(message);
1081
- if (code === "INSUFFICIENT_SCOPE") {
1082
- console.log(
1083
- chalk2.dim(' This SDK key cannot execute payments. Run "conto doctor" to see its scopes,')
1084
- );
1085
- console.log(chalk2.dim(" or create a new standard SDK key (includes payments:execute)."));
1086
- } else if (code === "EXECUTION_UNAVAILABLE") {
1087
- console.log(chalk2.dim(" Try again later or contact Conto support if the issue continues."));
1088
- }
1089
- process.exit(1);
1036
+ handlePayError(err);
1090
1037
  }
1091
1038
  }
1092
1039
 
@@ -1178,7 +1125,7 @@ async function transactionsCommand(id, options) {
1178
1125
  }
1179
1126
 
1180
1127
  // src/commands/wallets.ts
1181
- import chalk3 from "chalk";
1128
+ import chalk4 from "chalk";
1182
1129
  async function walletsCommand(subcommand, options = {}) {
1183
1130
  const config = loadConfig();
1184
1131
  if (!config.apiKey) {
@@ -1291,20 +1238,20 @@ async function walletsCommand(subcommand, options = {}) {
1291
1238
  console.log("");
1292
1239
  if (chainEntry?.faucetAvailable && config.testnet) {
1293
1240
  console.log(
1294
- chalk3.cyan(
1241
+ chalk4.cyan(
1295
1242
  ' This is a testnet wallet. Use "conto fund --faucet" to get free test tokens.'
1296
1243
  )
1297
1244
  );
1298
1245
  console.log("");
1299
1246
  } else {
1300
- console.log(` To fund your agent wallet, send ${chalk3.bold(w.currency || "USD")} to:
1247
+ console.log(` To fund your agent wallet, send ${chalk4.bold(w.currency || "USD")} to:
1301
1248
  `);
1302
- console.log(chalk3.bold(` ${w.address}`));
1249
+ console.log(chalk4.bold(` ${w.address}`));
1303
1250
  console.log("");
1304
1251
  const instructions = getFundingInstructions(w.currency || "USD", chainEntry);
1305
1252
  console.log(` How to get ${w.currency || "USD"}:`);
1306
1253
  for (const instruction of instructions) {
1307
- console.log(` ${chalk3.dim("\u2022")} ${instruction}`);
1254
+ console.log(` ${chalk4.dim("\u2022")} ${instruction}`);
1308
1255
  }
1309
1256
  console.log("");
1310
1257
  if (chainEntry) {
@@ -1356,7 +1303,7 @@ function getFundingInstructions(currency, chain) {
1356
1303
  }
1357
1304
 
1358
1305
  // src/commands/policies.ts
1359
- import chalk4 from "chalk";
1306
+ import chalk5 from "chalk";
1360
1307
  import * as p from "@clack/prompts";
1361
1308
  var POLICY_TYPES = [
1362
1309
  {
@@ -1574,7 +1521,7 @@ var ACTIONS = [
1574
1521
  hint: "Payment needs human approval if rule triggers"
1575
1522
  }
1576
1523
  ];
1577
- async function policiesCommand(subcommand = "list", idOrAmount, extra) {
1524
+ async function policiesCommand(subcommand = "list", idOrAmount, extra, reviewOptions = {}) {
1578
1525
  const config = loadConfig();
1579
1526
  if (!config.apiKey) {
1580
1527
  printError(
@@ -1582,7 +1529,7 @@ async function policiesCommand(subcommand = "list", idOrAmount, extra) {
1582
1529
  );
1583
1530
  process.exit(1);
1584
1531
  }
1585
- const api = createApiClient({
1532
+ const api = createOwnerClient({
1586
1533
  baseUrl: config.baseUrl,
1587
1534
  apiKey: config.apiKey,
1588
1535
  orgApiKey: config.orgApiKey
@@ -1600,13 +1547,13 @@ async function policiesCommand(subcommand = "list", idOrAmount, extra) {
1600
1547
  printError("Usage: conto policies update <policy-id>");
1601
1548
  process.exit(1);
1602
1549
  }
1603
- return await updatePolicy(api, idOrAmount);
1550
+ return await updatePolicy(api, idOrAmount, reviewOptions);
1604
1551
  case "delete":
1605
1552
  if (!idOrAmount) {
1606
1553
  printError("Usage: conto policies delete <policy-id>");
1607
1554
  process.exit(1);
1608
1555
  }
1609
- return await deletePolicy(api, idOrAmount);
1556
+ return await deletePolicy(api, idOrAmount, reviewOptions);
1610
1557
  case "assign":
1611
1558
  if (!idOrAmount) {
1612
1559
  printError("Usage: conto policies assign <policy-id>");
@@ -1618,7 +1565,7 @@ async function policiesCommand(subcommand = "list", idOrAmount, extra) {
1618
1565
  printError("Usage: conto policies unassign <policy-id>");
1619
1566
  process.exit(1);
1620
1567
  }
1621
- return await unassignPolicy(api, config.agentId, idOrAmount);
1568
+ return await unassignPolicy(api, config.agentId, idOrAmount, reviewOptions);
1622
1569
  case "add-rule":
1623
1570
  if (!idOrAmount) {
1624
1571
  printError("Usage: conto policies add-rule <policy-id>");
@@ -1630,7 +1577,25 @@ async function policiesCommand(subcommand = "list", idOrAmount, extra) {
1630
1577
  printError("Usage: conto policies remove-rule <policy-id> <rule-id>");
1631
1578
  process.exit(1);
1632
1579
  }
1633
- return await removeRule(api, idOrAmount, extra);
1580
+ return await removeRule(api, idOrAmount, extra, reviewOptions);
1581
+ case "versions":
1582
+ if (!idOrAmount) {
1583
+ printError("Usage: conto policies versions <policy-id>");
1584
+ process.exit(1);
1585
+ }
1586
+ return await listVersions(api, idOrAmount);
1587
+ case "rollback":
1588
+ if (!idOrAmount || !extra) {
1589
+ printError("Usage: conto policies rollback <policy-id> <version>");
1590
+ process.exit(1);
1591
+ }
1592
+ return await rollbackPolicy(api, idOrAmount, Number(extra), reviewOptions);
1593
+ case "simulate":
1594
+ if (!idOrAmount) {
1595
+ printError("Usage: conto policies simulate <policy-id>");
1596
+ process.exit(1);
1597
+ }
1598
+ return await simulatePolicy(api, idOrAmount);
1634
1599
  case "help":
1635
1600
  return printPolicyHelp();
1636
1601
  default:
@@ -1660,21 +1625,21 @@ async function listAgentPolicies(api) {
1660
1625
  }
1661
1626
  printHeader("Agent Policies");
1662
1627
  for (const policy of policies) {
1663
- const scope = policy.scope === "organization" ? chalk4.dim("[organization]") : chalk4.cyan(`[${policy.appliesVia.join("+")}]`);
1628
+ const scope = policy.scope === "organization" ? chalk5.dim("[organization]") : chalk5.cyan(`[${policy.appliesVia.join("+")}]`);
1664
1629
  console.log(
1665
1630
  `
1666
- ${chalk4.bold(policy.name)} ${scope} ${chalk4.dim(`(${policy.policyType}, priority: ${policy.priority})`)}`
1631
+ ${chalk5.bold(policy.name)} ${scope} ${chalk5.dim(`(${policy.policyType}, priority: ${policy.priority})`)}`
1667
1632
  );
1668
- console.log(` ${chalk4.dim("ID:")} ${policy.id}`);
1633
+ console.log(` ${chalk5.dim("ID:")} ${policy.id}`);
1669
1634
  console.log(
1670
- ` ${chalk4.dim("Active:")} ${policy.isActive ? chalk4.green("Yes") : chalk4.red("No")}`
1635
+ ` ${chalk5.dim("Active:")} ${policy.isActive ? chalk5.green("Yes") : chalk5.red("No")}`
1671
1636
  );
1672
1637
  if (policy.rules.length > 0) {
1673
- console.log(` ${chalk4.dim("Rules:")}`);
1638
+ console.log(` ${chalk5.dim("Rules:")}`);
1674
1639
  for (const rule of policy.rules) {
1675
1640
  const valueDisplay = formatRuleValue(rule.ruleType, rule.value);
1676
1641
  console.log(
1677
- ` ${chalk4.dim("\u2022")} ${rule.ruleType} ${rule.operator} ${valueDisplay} \u2192 ${rule.action}`
1642
+ ` ${chalk5.dim("\u2022")} ${rule.ruleType} ${rule.operator} ${valueDisplay} \u2192 ${rule.action}`
1678
1643
  );
1679
1644
  }
1680
1645
  }
@@ -1697,18 +1662,18 @@ async function listAllPolicies(api) {
1697
1662
  const scope = policy.scope === "organization" ? "organization-wide" : `${agentCount} agents`;
1698
1663
  console.log(
1699
1664
  `
1700
- ${chalk4.bold(policy.name)} ${chalk4.dim(`(${policy.policyType}, priority: ${policy.priority}, ${scope})`)}`
1665
+ ${chalk5.bold(policy.name)} ${chalk5.dim(`(${policy.policyType}, priority: ${policy.priority}, ${scope})`)}`
1701
1666
  );
1702
- console.log(` ${chalk4.dim("ID:")} ${policy.id}`);
1667
+ console.log(` ${chalk5.dim("ID:")} ${policy.id}`);
1703
1668
  console.log(
1704
- ` ${chalk4.dim("Active:")} ${policy.isActive ? chalk4.green("Yes") : chalk4.red("No")}`
1669
+ ` ${chalk5.dim("Active:")} ${policy.isActive ? chalk5.green("Yes") : chalk5.red("No")}`
1705
1670
  );
1706
1671
  if (policy.rules.length > 0) {
1707
- console.log(` ${chalk4.dim("Rules:")}`);
1672
+ console.log(` ${chalk5.dim("Rules:")}`);
1708
1673
  for (const rule of policy.rules) {
1709
1674
  const valueDisplay = formatRuleValue(rule.ruleType, rule.value);
1710
1675
  console.log(
1711
- ` ${chalk4.dim("\u2022")} [${rule.id.slice(-6)}] ${rule.ruleType} ${rule.operator} ${valueDisplay} \u2192 ${rule.action}`
1676
+ ` ${chalk5.dim("\u2022")} [${rule.id.slice(-6)}] ${rule.ruleType} ${rule.operator} ${valueDisplay} \u2192 ${rule.action}`
1712
1677
  );
1713
1678
  }
1714
1679
  }
@@ -1772,7 +1737,7 @@ async function createPolicy(api, agentId) {
1772
1737
  if (assignToAgent) printSuccess("Assigned to current agent");
1773
1738
  }
1774
1739
  }
1775
- async function updatePolicy(api, policyId) {
1740
+ async function updatePolicy(api, policyId, reviewOptions) {
1776
1741
  const name = await p.text({
1777
1742
  message: "New name (leave empty to skip)",
1778
1743
  initialValue: ""
@@ -1810,22 +1775,63 @@ async function updatePolicy(api, policyId) {
1810
1775
  printInfo("No changes to make.");
1811
1776
  return;
1812
1777
  }
1813
- const result = await api.updatePolicy(policyId, params);
1778
+ let result;
1779
+ try {
1780
+ result = await api.updatePolicy(policyId, params);
1781
+ } catch (err) {
1782
+ if (!isTightenOnlyRefusal(err)) throw err;
1783
+ return proposePolicyUpdate(api, policyId, params, reviewOptions);
1784
+ }
1814
1785
  if (isJsonMode()) {
1815
1786
  printJson(result);
1816
1787
  } else {
1817
1788
  printSuccess(`Policy "${result.name}" updated`);
1818
1789
  }
1819
1790
  }
1820
- async function deletePolicy(api, policyId) {
1821
- const confirm2 = await p.confirm({
1791
+ async function proposePolicyUpdate(api, policyId, params, reviewOptions) {
1792
+ if (params.scope !== void 0) {
1793
+ throw new Error("This key can't change a policy's scope. Change it in the dashboard.");
1794
+ }
1795
+ const proposals = [];
1796
+ if (params.name !== void 0 || params.priority !== void 0) {
1797
+ proposals.push({
1798
+ action: "update_policy",
1799
+ input: {
1800
+ policy_id: policyId,
1801
+ ...params.name !== void 0 ? { name: params.name } : {},
1802
+ ...params.priority !== void 0 ? { priority: params.priority } : {}
1803
+ },
1804
+ done: "Policy updated."
1805
+ });
1806
+ }
1807
+ if (params.isActive !== void 0) {
1808
+ proposals.push({
1809
+ action: params.isActive ? "activate_policy" : "deactivate_policy",
1810
+ input: { policy_id: policyId },
1811
+ done: params.isActive ? "Policy turned on." : "Policy turned off."
1812
+ });
1813
+ }
1814
+ for (const proposal of proposals) {
1815
+ const outcome = await proposeForReview(api, proposal.action, proposal.input, reviewOptions);
1816
+ reportReview(outcome, proposal.done);
1817
+ if (outcome.exitCode !== 0) return;
1818
+ }
1819
+ }
1820
+ async function deletePolicy(api, policyId, reviewOptions) {
1821
+ const confirm3 = await p.confirm({
1822
1822
  message: `Delete policy ${policyId}? This cannot be undone.`
1823
1823
  });
1824
- if (p.isCancel(confirm2) || !confirm2) {
1824
+ if (p.isCancel(confirm3) || !confirm3) {
1825
1825
  printInfo("Cancelled.");
1826
1826
  return;
1827
1827
  }
1828
- await api.deletePolicy(policyId);
1828
+ const result = await directOrReview(
1829
+ api,
1830
+ () => api.deletePolicy(policyId),
1831
+ async () => ({ action: "delete_policy", input: { policy_id: policyId } }),
1832
+ reviewOptions
1833
+ );
1834
+ if ("review" in result) return reportReview(result.review, `Policy ${policyId} deleted`);
1829
1835
  printSuccess(`Policy ${policyId} deleted`);
1830
1836
  }
1831
1837
  async function assignPolicy(api, agentId, policyId) {
@@ -1836,8 +1842,19 @@ async function assignPolicy(api, agentId, policyId) {
1836
1842
  printSuccess(`Policy ${policyId} assigned to agent`);
1837
1843
  }
1838
1844
  }
1839
- async function unassignPolicy(api, agentId, policyId) {
1840
- await api.unassignPolicyFromAgent(agentId, policyId);
1845
+ async function unassignPolicy(api, agentId, policyId, reviewOptions) {
1846
+ const result = await directOrReview(
1847
+ api,
1848
+ () => api.unassignPolicyFromAgent(agentId, policyId),
1849
+ async () => ({
1850
+ action: "remove_policy_from_agent",
1851
+ input: { policy_id: policyId, agent_id: agentId }
1852
+ }),
1853
+ reviewOptions
1854
+ );
1855
+ if ("review" in result) {
1856
+ return reportReview(result.review, `Policy ${policyId} unassigned from agent`);
1857
+ }
1841
1858
  if (isJsonMode()) {
1842
1859
  printJson({ success: true, agentId, policyId });
1843
1860
  } else {
@@ -1854,8 +1871,26 @@ async function addRule(api, policyId) {
1854
1871
  printSuccess(`Rule "${rule.ruleType}" added to policy`);
1855
1872
  }
1856
1873
  }
1857
- async function removeRule(api, policyId, ruleId) {
1858
- await api.deletePolicyRule(policyId, ruleId);
1874
+ async function removeRule(api, policyId, ruleId, reviewOptions) {
1875
+ const result = await directOrReview(
1876
+ api,
1877
+ () => api.deletePolicyRule(policyId, ruleId),
1878
+ async () => {
1879
+ const { rules } = await api.listPolicyRules(policyId);
1880
+ if (!rules.some((rule) => rule.id === ruleId)) {
1881
+ throw new Error(`Rule ${ruleId} is not on policy ${policyId}.`);
1882
+ }
1883
+ return {
1884
+ action: "update_policy",
1885
+ input: {
1886
+ policy_id: policyId,
1887
+ rules: toToolRules(rules.filter((rule) => rule.id !== ruleId))
1888
+ }
1889
+ };
1890
+ },
1891
+ reviewOptions
1892
+ );
1893
+ if ("review" in result) return reportReview(result.review, `Rule ${ruleId} removed from policy`);
1859
1894
  if (isJsonMode()) {
1860
1895
  printJson({ success: true, policyId, ruleId });
1861
1896
  } else {
@@ -1891,7 +1926,7 @@ async function promptForRule(policyType) {
1891
1926
  message: "Max transactions in that window",
1892
1927
  placeholder: "5",
1893
1928
  validate: (v) => {
1894
- const result = buildVelocityCountValue(v, period);
1929
+ const result = buildVelocityCountValue(v ?? "", period);
1895
1930
  return result.ok ? void 0 : result.error;
1896
1931
  }
1897
1932
  });
@@ -1932,7 +1967,7 @@ async function promptForRule(policyType) {
1932
1967
  message: `Value: ${valueHint}`,
1933
1968
  placeholder,
1934
1969
  validate: ruleStr === "TRUST_SCORE" ? (v) => {
1935
- const result = parseTrustScoreInput(v);
1970
+ const result = parseTrustScoreInput(v ?? "");
1936
1971
  return result.ok ? void 0 : result.error;
1937
1972
  } : void 0
1938
1973
  });
@@ -1956,8 +1991,8 @@ async function promptForRule(policyType) {
1956
1991
  };
1957
1992
  }
1958
1993
  function printPolicyHelp() {
1959
- console.log(chalk4.bold("\n Conto Policy Management\n"));
1960
- console.log(chalk4.bold(" Commands:"));
1994
+ console.log(chalk5.bold("\n Conto Policy Management\n"));
1995
+ console.log(chalk5.bold(" Commands:"));
1961
1996
  console.log(" conto policies List agent policies");
1962
1997
  console.log(" conto policies all List all org policies");
1963
1998
  console.log(" conto policies create Create a new policy");
@@ -1968,11 +2003,11 @@ function printPolicyHelp() {
1968
2003
  console.log(" conto policies add-rule <id> Add a rule");
1969
2004
  console.log(" conto policies remove-rule <id> <rid> Remove a rule");
1970
2005
  console.log(" conto policies help This help page");
1971
- console.log(chalk4.bold("\n Policy Types:"));
2006
+ console.log(chalk5.bold("\n Policy Types:"));
1972
2007
  for (const pt of POLICY_TYPES) {
1973
- console.log(` ${chalk4.cyan(pt.value.padEnd(22))} ${chalk4.dim(pt.hint)}`);
2008
+ console.log(` ${chalk5.cyan(pt.value.padEnd(22))} ${chalk5.dim(pt.hint)}`);
1974
2009
  }
1975
- console.log(chalk4.bold("\n Common Rule Types:"));
2010
+ console.log(chalk5.bold("\n Common Rule Types:"));
1976
2011
  const commonRules = [
1977
2012
  ["MAX_AMOUNT", "Max per-transaction amount (e.g. 500)"],
1978
2013
  ["DAILY_LIMIT", "Max total spend per day (e.g. 1000)"],
@@ -1986,9 +2021,9 @@ function printPolicyHelp() {
1986
2021
  ["DATE_RANGE", 'JSON: {"start":"2025-01-01","end":"2025-12-31"}']
1987
2022
  ];
1988
2023
  for (const [rule, desc] of commonRules) {
1989
- console.log(` ${chalk4.cyan(rule.padEnd(28))} ${chalk4.dim(desc)}`);
2024
+ console.log(` ${chalk5.cyan(rule.padEnd(28))} ${chalk5.dim(desc)}`);
1990
2025
  }
1991
- console.log(chalk4.bold("\n Value Examples:"));
2026
+ console.log(chalk5.bold("\n Value Examples:"));
1992
2027
  console.log(" Spend limits: 500");
1993
2028
  console.log(' Address lists: ["0xabc...","0xdef..."]');
1994
2029
  console.log(' Country codes: ["CU","IR","KP","SY","RU"]');
@@ -1996,24 +2031,24 @@ function printPolicyHelp() {
1996
2031
  console.log(' Velocity: {"maxCount":5,"period":"HOUR"}');
1997
2032
  console.log(' Date range: {"start":"2025-01-01","end":"2025-12-31"}');
1998
2033
  console.log(' Categories: ["API_PROVIDER","CLOUD","SAAS"]');
1999
- console.log(chalk4.bold("\n Operators:"));
2034
+ console.log(chalk5.bold("\n Operators:"));
2000
2035
  console.log(" LTE (<= at most) GTE (>= at least) EQUALS NOT_EQUALS");
2001
2036
  console.log(" IN_LIST NOT_IN_LIST BETWEEN DENY");
2002
- console.log(chalk4.bold("\n Actions:"));
2003
- console.log(` ${chalk4.green("ALLOW")} Payment proceeds if rule passes`);
2004
- console.log(` ${chalk4.red("DENY")} Payment is blocked`);
2005
- console.log(` ${chalk4.yellow("REQUIRE_APPROVAL")} Payment needs human approval`);
2006
- console.log(chalk4.bold("\n Examples:"));
2007
- console.log(chalk4.dim(" # Create a $500/day spend limit"));
2037
+ console.log(chalk5.bold("\n Actions:"));
2038
+ console.log(` ${chalk5.green("ALLOW")} Payment proceeds if rule passes`);
2039
+ console.log(` ${chalk5.red("DENY")} Payment is blocked`);
2040
+ console.log(` ${chalk5.yellow("REQUIRE_APPROVAL")} Payment needs human approval`);
2041
+ console.log(chalk5.bold("\n Examples:"));
2042
+ console.log(chalk5.dim(" # Create a $500/day spend limit"));
2008
2043
  console.log(" conto policies create");
2009
- console.log(chalk4.dim(" # Add a weekly limit rule to an existing policy"));
2044
+ console.log(chalk5.dim(" # Add a weekly limit rule to an existing policy"));
2010
2045
  console.log(" conto policies add-rule cmn4abc123");
2011
- console.log(chalk4.dim(" # Deactivate a policy without deleting"));
2046
+ console.log(chalk5.dim(" # Deactivate a policy without deleting"));
2012
2047
  console.log(" conto policies update cmn4abc123");
2013
- console.log(chalk4.dim(" # View all policies as JSON"));
2048
+ console.log(chalk5.dim(" # View all policies as JSON"));
2014
2049
  console.log(" conto policies all --json");
2015
2050
  console.log(`
2016
- ${chalk4.dim("Full docs: https://conto.finance/docs/cli/policies")}
2051
+ ${chalk5.dim("Full docs: https://conto.finance/docs/cli/policies")}
2017
2052
  `);
2018
2053
  }
2019
2054
  function formatRuleValue(ruleType, value) {
@@ -2028,9 +2063,89 @@ function formatRuleValue(ruleType, value) {
2028
2063
  }
2029
2064
  return value;
2030
2065
  }
2066
+ function toToolRules(rules) {
2067
+ return rules.map((rule) => ({
2068
+ rule_type: rule.ruleType,
2069
+ operator: rule.operator,
2070
+ value: rule.value,
2071
+ action: rule.action
2072
+ }));
2073
+ }
2074
+ async function listVersions(api, policyId) {
2075
+ const { versions } = await api.listPolicyVersions(policyId);
2076
+ if (isJsonMode()) return printJson(versions);
2077
+ if (versions.length === 0) return printInfo("This policy has no saved versions yet.");
2078
+ printHeader("Policy versions");
2079
+ for (const version of versions) {
2080
+ console.log(
2081
+ ` ${chalk5.bold(`v${version.version}`)} ${version.changeType.toLowerCase()} ${chalk5.dim(
2082
+ new Date(version.createdAt).toLocaleString()
2083
+ )} ${version.rulesCount} rule${version.rulesCount === 1 ? "" : "s"}${version.note ? chalk5.dim(` ${version.note}`) : ""}`
2084
+ );
2085
+ }
2086
+ console.log("");
2087
+ }
2088
+ async function rollbackPolicy(api, policyId, version, reviewOptions) {
2089
+ if (!Number.isInteger(version) || version < 1) {
2090
+ throw new Error(
2091
+ "Pass the version number to restore, for example: conto policies rollback <id> 3"
2092
+ );
2093
+ }
2094
+ const result = await directOrReview(
2095
+ api,
2096
+ () => api.rollbackPolicyDirect(policyId, version),
2097
+ async () => {
2098
+ const { snapshot } = await api.getPolicyVersion(policyId, version);
2099
+ return {
2100
+ action: "update_policy",
2101
+ input: {
2102
+ policy_id: policyId,
2103
+ name: snapshot.name,
2104
+ description: snapshot.description,
2105
+ priority: snapshot.priority,
2106
+ rules: toToolRules(snapshot.rules)
2107
+ }
2108
+ };
2109
+ },
2110
+ reviewOptions
2111
+ );
2112
+ if ("review" in result) return reportReview(result.review, `Policy restored to v${version}`);
2113
+ if (isJsonMode()) return printJson(result.direct);
2114
+ printSuccess(`Policy restored to v${version}`);
2115
+ }
2116
+ async function simulatePolicy(api, policyId) {
2117
+ const policy = await api.getPolicy(policyId);
2118
+ const { summary, results } = await api.simulatePolicy({
2119
+ candidatePolicy: {
2120
+ name: policy.name,
2121
+ policyType: policy.policyType,
2122
+ rules: policy.rules.map((rule) => ({
2123
+ ruleType: rule.ruleType,
2124
+ operator: rule.operator,
2125
+ value: rule.value,
2126
+ action: rule.action
2127
+ }))
2128
+ }
2129
+ });
2130
+ if (isJsonMode()) return printJson({ summary, results });
2131
+ printHeader(`${policy.name} on your last ${summary.total} payments`);
2132
+ console.log(
2133
+ ` ${summary.allow} allowed, ${summary.deny} blocked, ${summary.requireApproval} need approval`
2134
+ );
2135
+ console.log(
2136
+ chalk5.dim(` ${summary.newlyBlocked} newly blocked, ${summary.newlyAllowed} newly allowed`)
2137
+ );
2138
+ const changed = results.filter((row) => row.changed).slice(0, 10);
2139
+ for (const row of changed) {
2140
+ console.log(
2141
+ ` ${row.amount} to ${row.recipient ?? "unknown"}: ${row.currentResult} -> ${row.wouldBe}${row.reasons[0] ? chalk5.dim(` ${row.reasons[0]}`) : ""}`
2142
+ );
2143
+ }
2144
+ console.log("");
2145
+ }
2031
2146
 
2032
2147
  // src/commands/limits.ts
2033
- import chalk5 from "chalk";
2148
+ import chalk6 from "chalk";
2034
2149
  async function limitsCommand() {
2035
2150
  const config = loadConfig();
2036
2151
  if (!config.apiKey) {
@@ -2056,21 +2171,21 @@ async function limitsCommand() {
2056
2171
  printHeader("Spending Limits");
2057
2172
  for (const l of limits) {
2058
2173
  console.log(`
2059
- ${chalk5.bold(l.walletName)}`);
2174
+ ${chalk6.bold(l.walletName)}`);
2060
2175
  const dailyPct = l.daily.limit > 0 ? Math.round(l.daily.spent / l.daily.limit * 100) : 0;
2061
2176
  console.log(
2062
- ` ${chalk5.dim("Daily:")} ${bar(dailyPct)} ${printAmount(l.daily.spent, "USD")} / ${printAmount(l.daily.limit, "USD")} ${chalk5.dim(`(${printAmount(l.daily.remaining, "USD")} remaining)`)}`
2177
+ ` ${chalk6.dim("Daily:")} ${bar(dailyPct)} ${printAmount(l.daily.spent, "USD")} / ${printAmount(l.daily.limit, "USD")} ${chalk6.dim(`(${printAmount(l.daily.remaining, "USD")} remaining)`)}`
2063
2178
  );
2064
2179
  if (l.weekly) {
2065
2180
  const weeklyPct = l.weekly.limit > 0 ? Math.round(l.weekly.spent / l.weekly.limit * 100) : 0;
2066
2181
  console.log(
2067
- ` ${chalk5.dim("Weekly:")} ${bar(weeklyPct)} ${printAmount(l.weekly.spent, "USD")} / ${printAmount(l.weekly.limit, "USD")} ${chalk5.dim(`(${printAmount(l.weekly.remaining, "USD")} remaining)`)}`
2182
+ ` ${chalk6.dim("Weekly:")} ${bar(weeklyPct)} ${printAmount(l.weekly.spent, "USD")} / ${printAmount(l.weekly.limit, "USD")} ${chalk6.dim(`(${printAmount(l.weekly.remaining, "USD")} remaining)`)}`
2068
2183
  );
2069
2184
  }
2070
2185
  if (l.monthly) {
2071
2186
  const monthlyPct = l.monthly.limit > 0 ? Math.round(l.monthly.spent / l.monthly.limit * 100) : 0;
2072
2187
  console.log(
2073
- ` ${chalk5.dim("Monthly:")} ${bar(monthlyPct)} ${printAmount(l.monthly.spent, "USD")} / ${printAmount(l.monthly.limit, "USD")} ${chalk5.dim(`(${printAmount(l.monthly.remaining, "USD")} remaining)`)}`
2188
+ ` ${chalk6.dim("Monthly:")} ${bar(monthlyPct)} ${printAmount(l.monthly.spent, "USD")} / ${printAmount(l.monthly.limit, "USD")} ${chalk6.dim(`(${printAmount(l.monthly.remaining, "USD")} remaining)`)}`
2074
2189
  );
2075
2190
  }
2076
2191
  printKeyValue(" Per-TX max", printAmount(l.perTransaction, "USD"));
@@ -2094,7 +2209,64 @@ function bar(pct, width = 15) {
2094
2209
  }
2095
2210
 
2096
2211
  // src/commands/alerts.ts
2097
- import chalk6 from "chalk";
2212
+ import chalk8 from "chalk";
2213
+
2214
+ // src/lib/owner-command.ts
2215
+ import chalk7 from "chalk";
2216
+ var LOGIN_HINT = 'This command needs your organization login. Run "conto login" (or set CONTO_ORG_API_KEY) and try again.';
2217
+ async function runOwnerCommand(needs, fn) {
2218
+ const config = loadConfig();
2219
+ if (needs === "org" && !config.orgApiKey) {
2220
+ fail(LOGIN_HINT, "ORG_KEY_REQUIRED");
2221
+ return;
2222
+ }
2223
+ if (needs === "sdk" && !config.apiKey) {
2224
+ fail(
2225
+ 'Not configured. Run "npx @conto_finance/create-conto-agent" or "conto login" first.',
2226
+ "SDK_KEY_REQUIRED"
2227
+ );
2228
+ return;
2229
+ }
2230
+ const api = createOwnerClient({
2231
+ baseUrl: config.baseUrl,
2232
+ apiKey: config.apiKey,
2233
+ orgApiKey: config.orgApiKey
2234
+ });
2235
+ try {
2236
+ await fn({ api, config });
2237
+ } catch (err) {
2238
+ const error = err;
2239
+ if (error.status === 401) {
2240
+ fail(`${error.message}. ${LOGIN_HINT}`, error.code ?? "AUTH_FAILED");
2241
+ return;
2242
+ }
2243
+ fail(error.message || "Request failed", error.code, error.recovery);
2244
+ }
2245
+ }
2246
+ function fail(message, code, recovery) {
2247
+ process.exitCode = 1;
2248
+ if (isJsonMode()) {
2249
+ printJson({
2250
+ ok: false,
2251
+ error: message,
2252
+ ...code ? { code } : {},
2253
+ ...recovery ? { recovery } : {}
2254
+ });
2255
+ return;
2256
+ }
2257
+ printError(message);
2258
+ if (recovery) console.log(chalk7.dim(` ${recovery}`));
2259
+ }
2260
+ function parseUsd(value, flag) {
2261
+ if (value === void 0) return void 0;
2262
+ const amount = Number(value);
2263
+ if (!Number.isFinite(amount) || amount < 0) {
2264
+ throw new Error(`${flag} takes an amount in USD, for example 250`);
2265
+ }
2266
+ return amount;
2267
+ }
2268
+
2269
+ // src/commands/alerts.ts
2098
2270
  async function alertsCommand(options = {}) {
2099
2271
  const config = loadConfig();
2100
2272
  if (!config.apiKey) {
@@ -2143,20 +2315,449 @@ async function alertsCommand(options = {}) {
2143
2315
  function severityColor(severity) {
2144
2316
  switch (severity.toUpperCase()) {
2145
2317
  case "CRITICAL":
2146
- return chalk6.red.bold(severity);
2318
+ return chalk8.red.bold(severity);
2147
2319
  case "HIGH":
2148
- return chalk6.red(severity);
2320
+ return chalk8.red(severity);
2149
2321
  case "MEDIUM":
2150
- return chalk6.yellow(severity);
2322
+ return chalk8.yellow(severity);
2151
2323
  case "LOW":
2152
- return chalk6.dim(severity);
2324
+ return chalk8.dim(severity);
2153
2325
  default:
2154
2326
  return severity;
2155
2327
  }
2156
2328
  }
2329
+ async function alertUpdateCommand(alertId, action) {
2330
+ await runOwnerCommand("sdk", async ({ api }) => {
2331
+ const result = await api.updateAlert(alertId, action);
2332
+ if (isJsonMode()) return printJson(result);
2333
+ printSuccess(action === "acknowledge" ? "Alert acknowledged." : "Alert resolved.");
2334
+ });
2335
+ }
2336
+
2337
+ // src/commands/agents.ts
2338
+ import * as p2 from "@clack/prompts";
2339
+ async function agentsListCommand() {
2340
+ await runOwnerCommand("org", async ({ api }) => {
2341
+ const { agents } = await api.listAgents();
2342
+ if (isJsonMode()) return printJson(agents);
2343
+ if (agents.length === 0) return printInfo("No agents yet.");
2344
+ printHeader("Agents");
2345
+ printTable(
2346
+ ["ID", "Name", "Status", "Wallets", "Payments"],
2347
+ agents.map((agent) => [
2348
+ agent.id,
2349
+ agent.name,
2350
+ agent.status,
2351
+ agent.linkedWalletCount ?? 0,
2352
+ agent.transactionCount ?? 0
2353
+ ])
2354
+ );
2355
+ });
2356
+ }
2357
+ async function agentsShowCommand(agentId) {
2358
+ await runOwnerCommand("org", async ({ api }) => {
2359
+ const agent = await api.getAgent(agentId);
2360
+ if (isJsonMode()) return printJson(agent);
2361
+ printHeader(agent.name);
2362
+ printKeyValue("ID", agent.id);
2363
+ printKeyValue("Status", agent.status);
2364
+ if (agent.environment) printKeyValue("Environment", agent.environment);
2365
+ if (agent.owner?.name) printKeyValue("Owner", agent.owner.name);
2366
+ printKeyValue("Linked wallets", agent.linkedWalletCount ?? 0);
2367
+ printKeyValue("Payments", agent.transactionCount ?? 0);
2368
+ });
2369
+ }
2370
+ async function agentsPauseCommand(agentId) {
2371
+ await runOwnerCommand("org", async ({ api }) => {
2372
+ const agent = await api.updateAgentStatus(agentId, "PAUSED");
2373
+ if (isJsonMode()) return printJson(agent);
2374
+ printSuccess(`Agent ${agent.name} is paused. Its key stops working for new payments.`);
2375
+ });
2376
+ }
2377
+ async function agentsResumeCommand(agentId, options) {
2378
+ await runOwnerCommand("org", async ({ api }) => {
2379
+ const result = await directOrReview(
2380
+ api,
2381
+ () => api.updateAgentStatus(agentId, "ACTIVE"),
2382
+ async () => ({ action: "activate_agent", input: { agent_id: agentId } }),
2383
+ options
2384
+ );
2385
+ if ("review" in result) return reportReview(result.review, "Agent resumed.");
2386
+ if (isJsonMode()) return printJson(result.direct);
2387
+ printSuccess(`Agent ${result.direct.name} is active again.`);
2388
+ });
2389
+ }
2390
+ async function agentsFreezeCommand(agentId, options) {
2391
+ await runOwnerCommand("org", async ({ api }) => {
2392
+ const result = await api.freezeAgent(agentId, {
2393
+ ...options.reason ? { reason: options.reason } : {},
2394
+ freezeWallets: options.wallets === true
2395
+ });
2396
+ if (isJsonMode()) return printJson(result);
2397
+ printSuccess(
2398
+ options.wallets ? "Agent frozen, along with the wallets only it uses." : "Agent frozen. It cannot pay until the freeze is lifted."
2399
+ );
2400
+ });
2401
+ }
2402
+ async function agentsUnfreezeCommand(agentId, options) {
2403
+ await runOwnerCommand("org", async ({ api }) => {
2404
+ const result = await directOrReview(
2405
+ api,
2406
+ () => api.unfreezeAgent(agentId, {
2407
+ ...options.reason ? { reason: options.reason } : {},
2408
+ unfreezeWallets: options.wallets === true
2409
+ }),
2410
+ async () => ({
2411
+ action: "activate_agent",
2412
+ input: {
2413
+ agent_id: agentId,
2414
+ restore_wallets: options.wallets === true,
2415
+ ...options.reason ? { reason: options.reason } : {}
2416
+ }
2417
+ }),
2418
+ options
2419
+ );
2420
+ if ("review" in result) return reportReview(result.review, "Freeze lifted.");
2421
+ if (isJsonMode()) return printJson(result.direct);
2422
+ printSuccess("Freeze lifted. The agent can pay again within its limits.");
2423
+ });
2424
+ }
2425
+ async function agentsDeleteCommand(agentId, options) {
2426
+ await runOwnerCommand("org", async ({ api }) => {
2427
+ if (!options.yes) {
2428
+ if (!process.stdin.isTTY || isJsonMode()) {
2429
+ throw new Error("Deleting an agent cannot be undone. Pass --yes to confirm.");
2430
+ }
2431
+ const agent = await api.getAgent(agentId);
2432
+ const confirmed = await p2.confirm({
2433
+ message: `Delete agent ${agent.name}? Its keys stop working. This cannot be undone.`
2434
+ });
2435
+ if (p2.isCancel(confirmed) || !confirmed) return printInfo("Cancelled.");
2436
+ }
2437
+ const result = await directOrReview(
2438
+ api,
2439
+ () => api.deleteAgent(agentId),
2440
+ async () => ({ action: "delete_agent", input: { agent_id: agentId } }),
2441
+ options
2442
+ );
2443
+ if ("review" in result) return reportReview(result.review, "Agent deleted.");
2444
+ if (isJsonMode()) return printJson(result.direct);
2445
+ printSuccess("Agent deleted.");
2446
+ });
2447
+ }
2448
+ async function agentsKeysListCommand(agentId) {
2449
+ await runOwnerCommand("org", async ({ api }) => {
2450
+ const keys = await api.listSdkKeys(agentId);
2451
+ if (isJsonMode()) return printJson(keys);
2452
+ if (keys.length === 0) return printInfo("This agent has no SDK keys.");
2453
+ printHeader("SDK keys");
2454
+ printTable(
2455
+ ["ID", "Name", "Prefix", "Type", "Status", "Last used"],
2456
+ keys.map((key) => [
2457
+ key.id,
2458
+ key.name,
2459
+ key.keyPrefix,
2460
+ key.keyType,
2461
+ key.revokedAt ? "revoked" : key.isActive ? "active" : "inactive",
2462
+ key.lastUsedAt ? new Date(key.lastUsedAt).toLocaleString() : "never"
2463
+ ])
2464
+ );
2465
+ });
2466
+ }
2467
+ async function agentsKeysCreateCommand(agentId, options) {
2468
+ await runOwnerCommand("org", async ({ api }) => {
2469
+ const name = options.name?.trim() || "CLI key";
2470
+ const result = await directOrReview(
2471
+ api,
2472
+ () => api.createSdkKeyDirect(agentId, name),
2473
+ async () => ({ action: "generate_sdk_key", input: { agent_id: agentId, key_name: name } }),
2474
+ options
2475
+ );
2476
+ if ("review" in result) return reportReview(result.review, `SDK key "${name}" created.`);
2477
+ if (isJsonMode()) return printJson(result.direct);
2478
+ printSuccess(`SDK key "${name}" created.`);
2479
+ printKeyValue("SDK key", result.direct.key);
2480
+ printWarning("This key is shown once. Store it now, for example as CONTO_API_KEY in .env.");
2481
+ });
2482
+ }
2483
+ async function agentsKeysRevokeCommand(agentId, keyId) {
2484
+ await runOwnerCommand("org", async ({ api }) => {
2485
+ const result = await api.revokeSdkKey(agentId, keyId);
2486
+ if (isJsonMode()) return printJson(result);
2487
+ printSuccess("SDK key revoked. It stops working right away.");
2488
+ });
2489
+ }
2490
+
2491
+ // src/commands/wallet-controls.ts
2492
+ var PERIODS = [
2493
+ ["perTx", "per_tx", "PerTx"],
2494
+ ["daily", "daily", "Daily"],
2495
+ ["weekly", "weekly", "Weekly"],
2496
+ ["monthly", "monthly", "Monthly"]
2497
+ ];
2498
+ function readLimits(options) {
2499
+ const body = {};
2500
+ const input = {};
2501
+ for (const [flag, snake, camel] of PERIODS) {
2502
+ const amount = parseUsd(options[flag], `--${flag === "perTx" ? "per-tx" : flag}`);
2503
+ if (amount === void 0) continue;
2504
+ body[`spendLimit${camel}`] = amount;
2505
+ input[`spend_limit_${snake}`] = amount;
2506
+ }
2507
+ if (options.clearWeekly) {
2508
+ body.spendLimitWeekly = null;
2509
+ input.remove_weekly_limit = true;
2510
+ }
2511
+ if (options.clearMonthly) {
2512
+ body.spendLimitMonthly = null;
2513
+ input.remove_monthly_limit = true;
2514
+ }
2515
+ return { body, input };
2516
+ }
2517
+ async function walletFreezeCommand(walletId) {
2518
+ await runOwnerCommand("org", async ({ api }) => {
2519
+ const wallet = await api.updateWallet(walletId, "FROZEN");
2520
+ if (isJsonMode()) return printJson(wallet);
2521
+ printSuccess("Wallet frozen. No agent can pay from it until it is unfrozen.");
2522
+ });
2523
+ }
2524
+ async function walletUnfreezeCommand(walletId, options) {
2525
+ await runOwnerCommand("org", async ({ api }) => {
2526
+ const result = await directOrReview(
2527
+ api,
2528
+ () => api.updateWallet(walletId, "ACTIVE"),
2529
+ async () => ({ action: "reactivate_wallet", input: { wallet_id: walletId } }),
2530
+ options
2531
+ );
2532
+ if ("review" in result) return reportReview(result.review, "Wallet unfrozen.");
2533
+ if (isJsonMode()) return printJson(result.direct);
2534
+ printSuccess("Wallet unfrozen. Linked agents can pay from it again.");
2535
+ });
2536
+ }
2537
+ async function walletLinkCommand(agentId, walletId, options) {
2538
+ await runOwnerCommand("org", async ({ api }) => {
2539
+ const { body, input } = readLimits(options);
2540
+ const delegation = options.delegation?.toUpperCase();
2541
+ const result = await directOrReview(
2542
+ api,
2543
+ () => api.linkWallet(agentId, {
2544
+ walletId,
2545
+ ...body,
2546
+ ...delegation ? { delegationType: delegation } : {}
2547
+ }),
2548
+ async () => ({
2549
+ action: "link_wallet_to_agent",
2550
+ input: {
2551
+ agent_id: agentId,
2552
+ wallet_id: walletId,
2553
+ ...input,
2554
+ ...delegation ? { delegation_type: delegation } : {}
2555
+ }
2556
+ }),
2557
+ options
2558
+ );
2559
+ if ("review" in result) return reportReview(result.review, "Wallet linked.");
2560
+ if (isJsonMode()) return printJson(result.direct);
2561
+ printSuccess("Wallet linked. The agent can spend from it within the limits set.");
2562
+ });
2563
+ }
2564
+ async function walletUnlinkCommand(agentId, walletId) {
2565
+ await runOwnerCommand("org", async ({ api }) => {
2566
+ const result = await api.unlinkWallet(agentId, walletId);
2567
+ if (isJsonMode()) return printJson(result);
2568
+ printSuccess("Wallet unlinked. The agent can no longer spend from it.");
2569
+ });
2570
+ }
2571
+ async function walletLimitsCommand(agentId, walletId, options) {
2572
+ await runOwnerCommand("org", async ({ api }) => {
2573
+ const { body, input } = readLimits(options);
2574
+ if (Object.keys(body).length === 0) {
2575
+ throw new Error(
2576
+ "Pass at least one limit: --per-tx, --daily, --weekly, --monthly, --clear-weekly, or --clear-monthly."
2577
+ );
2578
+ }
2579
+ const result = await directOrReview(
2580
+ api,
2581
+ () => api.updateWalletLink(agentId, walletId, body),
2582
+ async () => ({
2583
+ action: "update_agent_wallet_limits",
2584
+ input: { agent_id: agentId, wallet_id: walletId, ...input }
2585
+ }),
2586
+ options
2587
+ );
2588
+ if ("review" in result) return reportReview(result.review, "Limits updated.");
2589
+ if (isJsonMode()) return printJson(result.direct);
2590
+ printSuccess("Limits updated.");
2591
+ });
2592
+ }
2593
+
2594
+ // src/commands/counterparties.ts
2595
+ async function counterpartiesListCommand() {
2596
+ await runOwnerCommand("org", async ({ api }) => {
2597
+ const { counterparties } = await api.listCounterparties();
2598
+ if (isJsonMode()) return printJson(counterparties);
2599
+ if (counterparties.length === 0) return printInfo("No payees yet.");
2600
+ printHeader("Payees");
2601
+ printTable(
2602
+ ["ID", "Name", "Address", "Status", "Trust"],
2603
+ counterparties.map((payee) => [
2604
+ payee.id,
2605
+ payee.name,
2606
+ payee.address ? truncateAddress(payee.address) : "",
2607
+ payee.lifecycleStatus,
2608
+ `${payee.trustLevel} (${payee.trustScore})`
2609
+ ])
2610
+ );
2611
+ });
2612
+ }
2613
+ async function counterpartiesShowCommand(id) {
2614
+ await runOwnerCommand("org", async ({ api }) => {
2615
+ const payee = await api.getCounterparty(id);
2616
+ if (isJsonMode()) return printJson(payee);
2617
+ printHeader(payee.name);
2618
+ printKeyValue("ID", payee.id);
2619
+ if (payee.address) printKeyValue("Address", payee.address);
2620
+ printKeyValue("Type", payee.type);
2621
+ printKeyValue("Status", payee.lifecycleStatus);
2622
+ printKeyValue("Trust", `${payee.trustLevel} (${payee.trustScore})`);
2623
+ });
2624
+ }
2625
+ async function counterpartiesAddCommand(options) {
2626
+ await runOwnerCommand("org", async ({ api }) => {
2627
+ if (!options.name || !options.address) {
2628
+ throw new Error("Pass --name and --address.");
2629
+ }
2630
+ const payee = await api.createCounterparty({
2631
+ name: options.name,
2632
+ address: options.address,
2633
+ ...options.type ? { type: options.type.toUpperCase() } : {},
2634
+ ...options.category ? { category: options.category } : {}
2635
+ });
2636
+ if (isJsonMode()) return printJson(payee);
2637
+ printSuccess(`Payee ${payee.name} added. It stays pending until it is approved.`);
2638
+ printKeyValue("ID", payee.id);
2639
+ });
2640
+ }
2641
+ async function counterpartiesBlockCommand(id) {
2642
+ await runOwnerCommand("org", async ({ api }) => {
2643
+ const payee = await api.updateCounterparty(id, { lifecycleStatus: "BLOCKED" });
2644
+ if (isJsonMode()) return printJson(payee);
2645
+ printSuccess(`Payee ${payee.name} is blocked. Agents cannot pay it.`);
2646
+ });
2647
+ }
2648
+ async function counterpartiesApproveCommand(id, options) {
2649
+ await runOwnerCommand("org", async ({ api }) => {
2650
+ const result = await directOrReview(
2651
+ api,
2652
+ () => api.updateCounterparty(id, { lifecycleStatus: "APPROVED" }),
2653
+ async () => ({
2654
+ action: "set_counterparty_status",
2655
+ input: {
2656
+ counterparty_id: id,
2657
+ status: "APPROVED",
2658
+ ...options.reason ? { reason: options.reason } : {}
2659
+ }
2660
+ }),
2661
+ options
2662
+ );
2663
+ if ("review" in result) return reportReview(result.review, "Payee approved.");
2664
+ if (isJsonMode()) return printJson(result.direct);
2665
+ printSuccess(`Payee ${result.direct.name} is approved.`);
2666
+ });
2667
+ }
2668
+
2669
+ // src/commands/channels.ts
2670
+ import { randomBytes } from "crypto";
2671
+ async function channelsListCommand() {
2672
+ await runOwnerCommand("org", async ({ api }) => {
2673
+ const { channels } = await api.listChannels();
2674
+ if (isJsonMode()) return printJson(channels);
2675
+ if (channels.length === 0) return printInfo("No event delivery channels yet.");
2676
+ printHeader("Event delivery channels");
2677
+ printTable(
2678
+ ["ID", "Name", "Type", "Sends to", "Events", "Status"],
2679
+ channels.map((channel) => [
2680
+ channel.id,
2681
+ channel.name,
2682
+ channel.channelType,
2683
+ channel.destination ?? "",
2684
+ channel.eventTypes.join(", "),
2685
+ channel.needsAttention ? "needs attention" : channel.isActive ? "active" : "off"
2686
+ ])
2687
+ );
2688
+ });
2689
+ }
2690
+ async function channelsAddCommand(options) {
2691
+ await runOwnerCommand("org", async ({ api }) => {
2692
+ const type = options.type?.toUpperCase();
2693
+ if (!options.name || !type) throw new Error("Pass --name and --type (email or webhook).");
2694
+ let config;
2695
+ let webhookSecret;
2696
+ if (type === "EMAIL") {
2697
+ const recipients = (options.recipients ?? "").split(",").map((email) => email.trim()).filter(Boolean);
2698
+ if (recipients.length === 0) throw new Error("Pass --recipients with one or more emails.");
2699
+ config = { recipients };
2700
+ } else if (type === "WEBHOOK") {
2701
+ if (!options.url) throw new Error("Pass --url with the https address to send events to.");
2702
+ webhookSecret = process.env.CONTO_WEBHOOK_SECRET || randomBytes(32).toString("hex");
2703
+ config = { url: options.url, secret: webhookSecret };
2704
+ } else {
2705
+ throw new Error(
2706
+ "The CLI adds email and webhook channels. Add Slack, Telegram or WhatsApp in Settings > Event Delivery."
2707
+ );
2708
+ }
2709
+ const eventTypes = options.events?.split(",").map((event) => event.trim()).filter(Boolean);
2710
+ const created = await api.createChannel({
2711
+ channelType: type,
2712
+ name: options.name,
2713
+ config,
2714
+ ...eventTypes?.length ? { eventTypes } : {}
2715
+ });
2716
+ if (isJsonMode()) {
2717
+ return printJson({ ...created, ...webhookSecret ? { webhookSecret } : {} });
2718
+ }
2719
+ printSuccess(`Channel ${options.name} added.`);
2720
+ if (webhookSecret && !process.env.CONTO_WEBHOOK_SECRET) {
2721
+ printKeyValue("Signing secret", webhookSecret);
2722
+ printWarning("Store this secret now to verify event signatures. It is not shown again.");
2723
+ }
2724
+ });
2725
+ }
2726
+ async function channelsTestCommand(id) {
2727
+ await runOwnerCommand("org", async ({ api }) => {
2728
+ const result = await api.testChannel(id);
2729
+ if (isJsonMode()) return printJson(result);
2730
+ printSuccess("Test event sent.");
2731
+ });
2732
+ }
2733
+ async function channelsRemoveCommand(id, options) {
2734
+ await runOwnerCommand("org", async ({ api }) => {
2735
+ const result = await directOrReview(
2736
+ api,
2737
+ () => api.deleteChannel(id),
2738
+ async () => ({ action: "remove_notification_channel", input: { channel_id: id } }),
2739
+ options
2740
+ );
2741
+ if ("review" in result) return reportReview(result.review, "Channel removed.");
2742
+ if (isJsonMode()) return printJson(result.direct);
2743
+ printSuccess("Channel removed.");
2744
+ });
2745
+ }
2746
+
2747
+ // src/commands/changes.ts
2748
+ async function changesStatusCommand(changeId, options) {
2749
+ await runOwnerCommand("org", async ({ api }) => {
2750
+ const change = await api.getOwnerAction(changeId);
2751
+ const outcome = await followChange(api, change, { open: false, wait: false, ...options });
2752
+ reportReview(
2753
+ outcome,
2754
+ change.change.action ? `${change.change.action}: done.` : "Change applied."
2755
+ );
2756
+ });
2757
+ }
2157
2758
 
2158
2759
  // src/commands/config.ts
2159
- import chalk7 from "chalk";
2760
+ import chalk9 from "chalk";
2160
2761
  var FORBIDDEN_CONFIG_PATH_SEGMENTS = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
2161
2762
  function isSafeConfigPath(parts) {
2162
2763
  return parts.length > 0 && parts.every(
@@ -2197,23 +2798,23 @@ async function configCommand(key, value) {
2197
2798
  return;
2198
2799
  }
2199
2800
  printHeader("Configuration");
2200
- printKeyValue("API Key", config.apiKey ? maskSecret(config.apiKey) : chalk7.dim("not set"));
2801
+ printKeyValue("API Key", config.apiKey ? maskSecret(config.apiKey) : chalk9.dim("not set"));
2201
2802
  printKeyValue(
2202
2803
  "Organization credential expires",
2203
- config.orgApiKeyExpiresAt || chalk7.dim("not recorded")
2804
+ config.orgApiKeyExpiresAt || chalk9.dim("not recorded")
2204
2805
  );
2205
2806
  printKeyValue("Base URL", config.baseUrl);
2206
- printKeyValue("Agent ID", config.agentId || chalk7.dim("not set"));
2207
- printKeyValue("Chain", config.chainName || chalk7.dim("not set"));
2208
- printKeyValue("Chain ID", config.chainId || chalk7.dim("not set"));
2209
- printKeyValue("Currency", config.currency || chalk7.dim("not set"));
2210
- printKeyValue("Explorer", config.explorerUrl || chalk7.dim("not set"));
2211
- printKeyValue("Wallet ID", config.walletId || chalk7.dim("not set"));
2212
- printKeyValue("Wallet Address", config.walletAddress || chalk7.dim("not set"));
2807
+ printKeyValue("Agent ID", config.agentId || chalk9.dim("not set"));
2808
+ printKeyValue("Chain", config.chainName || chalk9.dim("not set"));
2809
+ printKeyValue("Chain ID", config.chainId || chalk9.dim("not set"));
2810
+ printKeyValue("Currency", config.currency || chalk9.dim("not set"));
2811
+ printKeyValue("Explorer", config.explorerUrl || chalk9.dim("not set"));
2812
+ printKeyValue("Wallet ID", config.walletId || chalk9.dim("not set"));
2813
+ printKeyValue("Wallet Address", config.walletAddress || chalk9.dim("not set"));
2213
2814
  printKeyValue("Testnet", config.testnet ? "Yes" : "No");
2214
2815
  console.log("");
2215
- console.log(chalk7.dim(" Config sources: ~/.conto/config.json + .env.local"));
2216
- console.log(chalk7.dim(" Update with: conto config <key> <value>"));
2816
+ console.log(chalk9.dim(" Config sources: ~/.conto/config.json + .env.local"));
2817
+ console.log(chalk9.dim(" Update with: conto config <key> <value>"));
2217
2818
  console.log("");
2218
2819
  }
2219
2820
 
@@ -2348,17 +2949,17 @@ async function testWebhook(url) {
2348
2949
  }
2349
2950
 
2350
2951
  // src/commands/sandbox.ts
2351
- import fs from "fs";
2952
+ import fs2 from "fs";
2352
2953
  import path from "path";
2353
- import { setTimeout as sleep } from "timers/promises";
2354
- import chalk8 from "chalk";
2954
+ import { setTimeout as sleep2 } from "timers/promises";
2955
+ import chalk10 from "chalk";
2355
2956
 
2356
2957
  // src/lib/sandbox-handoff-client.ts
2357
2958
  var HANDOFF_PATH = "/api/agents/sandbox/handoff";
2358
2959
  var DEFAULT_POLL_INTERVAL_SECONDS = 5;
2359
2960
  var MIN_POLL_INTERVAL_SECONDS = 1;
2360
2961
  var MAX_POLL_INTERVAL_SECONDS = 60;
2361
- var REQUEST_TIMEOUT_MS2 = 15e3;
2962
+ var REQUEST_TIMEOUT_MS = 15e3;
2362
2963
  var SANDBOX_ORG_KEY_PATTERN = /^conto_[a-f0-9]{64}$/;
2363
2964
  var HANDOFF_TOKEN_PATTERN = /^conto_claim_[a-f0-9]{64}$/;
2364
2965
  function isHandoffToken(value) {
@@ -2462,7 +3063,7 @@ async function initiateHandoff(input) {
2462
3063
  url: apiUrl(input.baseUrl, HANDOFF_PATH),
2463
3064
  method: "POST",
2464
3065
  bearer: input.sandboxKey,
2465
- timeoutMs: REQUEST_TIMEOUT_MS2,
3066
+ timeoutMs: REQUEST_TIMEOUT_MS,
2466
3067
  signal: input.signal
2467
3068
  });
2468
3069
  } catch (error) {
@@ -2513,7 +3114,7 @@ async function inspectHandoff(input) {
2513
3114
  url: apiUrl(input.baseUrl, input.statusPath),
2514
3115
  method: "GET",
2515
3116
  bearer: input.token,
2516
- timeoutMs: REQUEST_TIMEOUT_MS2,
3117
+ timeoutMs: REQUEST_TIMEOUT_MS,
2517
3118
  signal: input.signal
2518
3119
  });
2519
3120
  } catch (error) {
@@ -2598,7 +3199,7 @@ var SANDBOX_CLAIM_EXIT_CODES = {
2598
3199
  interrupted: 130
2599
3200
  };
2600
3201
  var DEFAULT_BASE_URL = "https://conto.finance";
2601
- var DEFAULT_WAIT_SECONDS = 300;
3202
+ var DEFAULT_WAIT_SECONDS2 = 300;
2602
3203
  var MAX_WAIT_SECONDS = 3600;
2603
3204
  var MAX_CONSECUTIVE_POLL_ERRORS = 3;
2604
3205
  var TEST_MODE_AFTER_CLAIM = {
@@ -2612,7 +3213,7 @@ var TEST_MODE_AFTER_CLAIM = {
2612
3213
  credentialsPromoted: false
2613
3214
  };
2614
3215
  function cliPrefix() {
2615
- return fs.existsSync(path.join(process.cwd(), "node_modules", ".bin", "conto")) ? "npx conto" : "npx @conto_finance/create-conto-agent";
3216
+ return fs2.existsSync(path.join(process.cwd(), "node_modules", ".bin", "conto")) ? "npx conto" : "npx @conto_finance/create-conto-agent";
2616
3217
  }
2617
3218
  function emit(report) {
2618
3219
  if (isJsonMode()) {
@@ -2737,7 +3338,7 @@ function markExpired(cwd, state) {
2737
3338
  return expired;
2738
3339
  }
2739
3340
  function claimedReport(command, state, extra = {}) {
2740
- const setupKeyFileExists = fs.existsSync(path.join(process.cwd(), SANDBOX_SETUP_ENV_FILE));
3341
+ const setupKeyFileExists = fs2.existsSync(path.join(process.cwd(), SANDBOX_SETUP_ENV_FILE));
2741
3342
  return {
2742
3343
  command,
2743
3344
  status: "claimed",
@@ -2797,7 +3398,7 @@ function pendingFields(state, options) {
2797
3398
  function printHandoff(state, reused, cli) {
2798
3399
  console.log("");
2799
3400
  console.log(
2800
- ` ${chalk8.bold("Sandbox claim link")} ${chalk8.dim(`(expires ${state.expiresAt})`)}${reused ? chalk8.dim(" reused") : ""}`
3401
+ ` ${chalk10.bold("Sandbox claim link")} ${chalk10.dim(`(expires ${state.expiresAt})`)}${reused ? chalk10.dim(" reused") : ""}`
2801
3402
  );
2802
3403
  console.log("");
2803
3404
  console.log(` ${state.verificationUrl}`);
@@ -2812,7 +3413,7 @@ function printHandoff(state, reused, cli) {
2812
3413
  printInfo(`Check the status: ${cli} sandbox claim-status`);
2813
3414
  }
2814
3415
  function parseWaitSeconds(timeout) {
2815
- if (timeout === void 0) return { ok: true, seconds: DEFAULT_WAIT_SECONDS };
3416
+ if (timeout === void 0) return { ok: true, seconds: DEFAULT_WAIT_SECONDS2 };
2816
3417
  if (!/^\d+$/.test(timeout)) {
2817
3418
  return { ok: false, message: "--timeout takes a whole number of seconds." };
2818
3419
  }
@@ -2836,7 +3437,7 @@ async function waitForClaim(credential, state, timeoutSeconds, stats) {
2836
3437
  const remaining = deadline - Date.now();
2837
3438
  if (remaining <= 0) return { kind: "timeout", lastRetryAfterSeconds };
2838
3439
  try {
2839
- await sleep(Math.min(delayMs, remaining), void 0, { signal: interrupt.signal });
3440
+ await sleep2(Math.min(delayMs, remaining), void 0, { signal: interrupt.signal });
2840
3441
  } catch {
2841
3442
  return { kind: "interrupted" };
2842
3443
  }
@@ -3302,6 +3903,12 @@ async function runSandboxClaimStatus() {
3302
3903
 
3303
3904
  // src/cli.ts
3304
3905
  var program = new Command();
3906
+ function withReview(command) {
3907
+ return command.option("--wait [seconds]", "Wait for the owner review (default when run in a terminal)").option("--no-wait", "Print the review link and return without waiting").option("--no-open", "Do not open the review page in a browser").addHelpText("after", REVIEW_EXIT_CODES_HELP);
3908
+ }
3909
+ function withLimits(command) {
3910
+ return command.option("--per-tx <usd>", "Per-payment limit in USD").option("--daily <usd>", "Daily limit in USD").option("--weekly <usd>", "Weekly limit in USD").option("--monthly <usd>", "Monthly limit in USD");
3911
+ }
3305
3912
  var INIT_EXIT_CODES_HELP = `
3306
3913
  Exit codes:
3307
3914
  0 setup complete
@@ -3361,17 +3968,84 @@ program.command("webhooks").description("Test local webhook handlers").command("
3361
3968
  program.command("status").description("Agent info, wallet balances, spending summary").action(statusCommand);
3362
3969
  program.command("doctor").description("Diagnose setup: auth, key scopes, wallet, chain, balance, base URL").action(doctorCommand);
3363
3970
  program.command("balance").description("Wallet balances across all linked wallets").action(balanceCommand);
3364
- program.command("pay <address> <amount>").description("Request + execute a payment").option("--purpose <purpose>", "Payment purpose").option("--category <category>", "Spend category").option("--dry-run", "Validate input and show the request without sending it (no policy check)").option("--wallet <walletId>", "Specific wallet to use").action(payCommand);
3971
+ program.command("pay <address> <amount>").description("Request + execute a payment").option("--purpose <purpose>", "Payment purpose").option("--category <category>", "Spend category").option("--dry-run", "Validate input and show the request without sending it (no policy check)").option("--wallet <walletId>", "Specific wallet to use").option(
3972
+ "--wait [seconds]",
3973
+ "Wait for approval when it is needed (default when run in a terminal)"
3974
+ ).option("--no-wait", "Print the approval link and return without waiting").option("--no-open", "Do not open the approval page in a browser").addHelpText("after", PAYMENT_EXIT_CODES_HELP).action(payCommand);
3975
+ program.command("test-report").description("Save buyer-side payment, control, and review evidence without executing payments").requiredOption("--allowed <id>", "Completed allowed payment request ID").requiredOption("--denied <id>", "Policy-denied payment request ID").option("--review <id>", "Review exercise payment request ID").option("--review-outcome <outcome>", "Expected review outcome: approved, denied, or expired").requiredOption("--output <file>", "New owner-only JSON report file (never overwritten)").action(testReportCommand);
3365
3976
  program.command("transactions [id]").description("List recent transactions or view details").option("--limit <n>", "Number of transactions", "10").option("--status <status>", "Filter by status").action(transactionsCommand);
3366
- program.command("wallets").description("List wallets with balances").action(() => walletsCommand("list"));
3977
+ var walletsGroup = program.command("wallets").description("List wallets with balances, or change wallet controls").action(() => walletsCommand("list"));
3978
+ walletsGroup.command("list").description("List wallets with balances").action(() => walletsCommand("list"));
3979
+ walletsGroup.command("freeze <walletId>").description("Freeze a wallet so no agent can pay from it").action(walletFreezeCommand);
3980
+ withReview(
3981
+ walletsGroup.command("unfreeze <walletId>").description("Unfreeze a wallet (owner review)")
3982
+ ).action(walletUnfreezeCommand);
3983
+ withReview(
3984
+ withLimits(
3985
+ walletsGroup.command("link <agentId> <walletId>").description("Let an agent spend from a wallet (owner review)").option("--delegation <type>", "limited, full, view_only, preapproved, or allowlist")
3986
+ )
3987
+ ).action(walletLinkCommand);
3988
+ walletsGroup.command("unlink <agentId> <walletId>").description("Stop an agent spending from a wallet").action(walletUnlinkCommand);
3989
+ withReview(
3990
+ withLimits(
3991
+ walletsGroup.command("limits <agentId> <walletId>").description("Change an agent's limits on a wallet (raising one goes to owner review)").option("--clear-weekly", "Remove the weekly limit").option("--clear-monthly", "Remove the monthly limit")
3992
+ )
3993
+ ).action(walletLimitsCommand);
3994
+ var agentsGroup = program.command("agents").description("Manage the organization's agents");
3995
+ agentsGroup.command("list").description("List agents").action(agentsListCommand);
3996
+ agentsGroup.command("show <agentId>").description("Show one agent").action(agentsShowCommand);
3997
+ agentsGroup.command("pause <agentId>").description("Pause an agent").action(agentsPauseCommand);
3998
+ withReview(
3999
+ agentsGroup.command("resume <agentId>").description("Resume a paused agent (owner review)")
4000
+ ).action(agentsResumeCommand);
4001
+ agentsGroup.command("freeze <agentId>").description("Freeze an agent").option("--reason <text>", "Why, for the audit log").option("--wallets", "Also freeze wallets only this agent uses").action(agentsFreezeCommand);
4002
+ withReview(
4003
+ agentsGroup.command("unfreeze <agentId>").description("Lift a freeze (owner review)").option("--reason <text>", "Why, for the audit log").option("--wallets", "Also unfreeze the wallets frozen with it")
4004
+ ).action(agentsUnfreezeCommand);
4005
+ withReview(
4006
+ agentsGroup.command("delete <agentId>").description("Delete an agent (owner review)").option("--yes", "Skip the confirmation prompt")
4007
+ ).action(agentsDeleteCommand);
4008
+ var keysGroup = agentsGroup.command("keys").description("Manage an agent's SDK keys").argument("[agentId]", "Agent to list keys for").action((agentId) => {
4009
+ if (!agentId) {
4010
+ keysGroup.help();
4011
+ return;
4012
+ }
4013
+ return agentsKeysListCommand(agentId);
4014
+ });
4015
+ withReview(
4016
+ keysGroup.command("create <agentId>").description("Create an SDK key (owner review, shown once)").option("--name <name>", "Key label")
4017
+ ).action(agentsKeysCreateCommand);
4018
+ keysGroup.command("revoke <agentId> <keyId>").description("Revoke an SDK key").action(agentsKeysRevokeCommand);
4019
+ var payeesGroup = program.command("counterparties").description("Manage the organization's payees");
4020
+ payeesGroup.command("list").description("List payees").action(counterpartiesListCommand);
4021
+ payeesGroup.command("show <id>").description("Show one payee").action(counterpartiesShowCommand);
4022
+ payeesGroup.command("add").description("Add a payee for review").option("--name <name>", "Payee name").option("--address <address>", "Wallet address").option("--type <type>", "vendor, service, agent, or other").option("--category <category>", "Spend category").action(counterpartiesAddCommand);
4023
+ payeesGroup.command("block <id>").description("Block a payee").action(counterpartiesBlockCommand);
4024
+ withReview(
4025
+ payeesGroup.command("approve <id>").description("Approve or unblock a payee (owner review)").option("--reason <text>", "Why, for the audit log")
4026
+ ).action(counterpartiesApproveCommand);
4027
+ var channelsGroup = program.command("channels").description("Manage event delivery channels");
4028
+ channelsGroup.command("list").description("List channels").action(channelsListCommand);
4029
+ channelsGroup.command("add").description("Add an email or webhook channel").option("--name <name>", "Channel name").option("--type <type>", "email or webhook").option("--recipients <emails>", "Comma-separated emails (email)").option("--url <url>", "https address to send events to (webhook)").option("--events <types>", "Comma-separated event types (default: approval.requested)").action(channelsAddCommand);
4030
+ channelsGroup.command("test <id>").description("Send a test event").action(channelsTestCommand);
4031
+ withReview(
4032
+ channelsGroup.command("remove <id>").description("Remove a channel (owner review)")
4033
+ ).action(channelsRemoveCommand);
4034
+ withReview(
4035
+ program.command("changes").description("Follow changes sent to owner review").command("status <changeId>").description("Show where a change stands, and collect it once approved")
4036
+ ).action((changeId, opts) => changesStatusCommand(changeId, opts));
3367
4037
  program.command("fund").description("Show wallet funding instructions").option("--faucet", "Request testnet funds from the configured faucet").action((opts) => walletsCommand("fund", { faucet: opts.faucet === true }));
3368
- program.command("policies [subcommand] [id] [extra]").description(
3369
- "Manage spending policies (list, all, create, update, delete, assign, unassign, add-rule, remove-rule)"
4038
+ withReview(
4039
+ program.command("policies [subcommand] [id] [extra]").description(
4040
+ "Manage spending policies (list, all, create, update, delete, assign, unassign, add-rule, remove-rule, versions, rollback, simulate)"
4041
+ )
3370
4042
  ).action(
3371
- (subcommand, id, extra) => policiesCommand(subcommand || "list", id, extra)
4043
+ (subcommand, id, extra, opts) => policiesCommand(subcommand || "list", id, extra, opts)
3372
4044
  );
3373
4045
  program.command("limits").description("Show spending limits and remaining budget").action(limitsCommand);
3374
- program.command("alerts").description("List alerts").option("--active", "Show only active alerts").option("--unread", "Alias for --active").action(alertsCommand);
4046
+ var alertsGroup = program.command("alerts").description("List alerts, or acknowledge or resolve one").option("--active", "Show only active alerts").option("--unread", "Alias for --active").action(alertsCommand);
4047
+ alertsGroup.command("ack <alertId>").description("Acknowledge an alert").action((alertId) => alertUpdateCommand(alertId, "acknowledge"));
4048
+ alertsGroup.command("resolve <alertId>").description("Resolve an alert").action((alertId) => alertUpdateCommand(alertId, "resolve"));
3375
4049
  program.command("config [key] [value]").description("Show or update configuration").action(configCommand);
3376
4050
  program.command("login").description("Authenticate with Conto").option("--base-url <url>", "Conto instance URL").action(loginCommand);
3377
4051
  program.command("logout").description("Clear stored credentials").action(async () => {