@conto_finance/create-conto-agent 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -2,6 +2,7 @@ import {
2
2
  ApiClient,
3
3
  CLI_PACKAGE_VERSION,
4
4
  HttpTransportError,
5
+ NOTHING_SENT_CODES,
5
6
  REVIEW_EXIT_CODES_HELP,
6
7
  apiUrl,
7
8
  browserAuth,
@@ -26,13 +27,26 @@ import {
26
27
  retryAfterSeconds,
27
28
  runInit,
28
29
  writeProjectStateFile
29
- } from "./chunk-HDSRGTWB.js";
30
+ } from "./chunk-QJIXCSI2.js";
30
31
  import {
32
+ BUDGET_PERIODS,
31
33
  VELOCITY_PERIODS,
34
+ buildBudgetCapValue,
32
35
  buildVelocityCountValue,
36
+ dateRangePlaceholder,
33
37
  parseTrustScoreInput,
34
38
  validatePaymentRequest
35
- } from "./chunk-TJJY5NFH.js";
39
+ } from "./chunk-2M2WVAJI.js";
40
+ import {
41
+ SANDBOX_SETUP_ENV_FILE,
42
+ isSensitiveConfigKey,
43
+ loadConfig,
44
+ loadGlobalConfig,
45
+ loadProjectEnv,
46
+ maskSecret,
47
+ missingSdkKeyMessage,
48
+ saveGlobalConfig
49
+ } from "./chunk-RQ4PUBL7.js";
36
50
  import {
37
51
  isJsonMode,
38
52
  printAmount,
@@ -47,17 +61,238 @@ import {
47
61
  printWarning,
48
62
  setJsonMode,
49
63
  truncateAddress
50
- } from "./chunk-K4LBO234.js";
51
- import {
52
- SANDBOX_SETUP_ENV_FILE,
53
- isSensitiveConfigKey,
54
- loadConfig,
55
- loadGlobalConfig,
56
- loadProjectEnv,
57
- maskSecret,
58
- missingSdkKeyMessage,
59
- saveGlobalConfig
60
- } from "./chunk-XWUWB3FT.js";
64
+ } from "./chunk-DT5NOLBD.js";
65
+
66
+ // src/commands/spending.ts
67
+ import { readFile, writeFile } from "fs/promises";
68
+ import { basename, extname } from "path";
69
+ async function run(work, owner = false) {
70
+ try {
71
+ const config = loadConfig();
72
+ if (!(owner ? config.orgApiKey : config.apiKey))
73
+ throw new Error(
74
+ owner ? "An organization key is required for owner actions." : "Run conto login first."
75
+ );
76
+ const result = await work(createApiClient(config));
77
+ if (isJsonMode()) printJson(result);
78
+ else {
79
+ const object = result;
80
+ for (const [key, value] of Object.entries(object)) {
81
+ if (Array.isArray(value))
82
+ for (const row of value) {
83
+ console.log("");
84
+ if (typeof row === "object" && row !== null)
85
+ for (const [field, item] of Object.entries(row))
86
+ printKeyValue(
87
+ field,
88
+ typeof item === "object" ? JSON.stringify(item) : String(item ?? "-")
89
+ );
90
+ else console.log(String(row));
91
+ }
92
+ else
93
+ printKeyValue(
94
+ key,
95
+ typeof value === "object" ? JSON.stringify(value) : String(value ?? "-")
96
+ );
97
+ }
98
+ }
99
+ } catch (error) {
100
+ const e = error;
101
+ if (isJsonMode()) printJson({ error: e.message, code: e.code, ...e.details });
102
+ else printError(e.message);
103
+ process.exitCode = 1;
104
+ }
105
+ }
106
+ var id = encodeURIComponent;
107
+ function registerSpendingCommands(program2) {
108
+ program2.command("spending").description("Organization accounting exports").command("export").description(
109
+ "Export cross-rail spend with categories and GL accounts (organization key required)"
110
+ ).option("--from <timestamp>", "Inclusive ISO timestamp").option("--to <timestamp>", "Exclusive ISO timestamp").option("--format <format>", "csv or json (JSON returns one page)").option("--limit <count>", "JSON page size, at most 1000").option("--cursor <cursor>", "JSON nextCursor from the previous page").option("--output <file>", "Save to a new file; refuse to overwrite").action(async (o) => {
111
+ try {
112
+ const config = loadConfig();
113
+ if (!config.orgApiKey)
114
+ throw new Error("An organization key is required for accounting exports.");
115
+ const format = o.format ?? (isJsonMode() ? "json" : "csv");
116
+ if (!["csv", "json"].includes(format)) throw new Error("Format must be csv or json.");
117
+ if (format === "csv" && (o.cursor || o.limit))
118
+ throw new Error("Cursor and limit require JSON format.");
119
+ const query = new URLSearchParams({ format });
120
+ for (const key of ["from", "to", "limit", "cursor"])
121
+ if (o[key] !== void 0) query.set(key, o[key]);
122
+ const api = createApiClient(config);
123
+ const data = format === "csv" ? await api.spendingDownload(`export?${query}`, true) : JSON.stringify(
124
+ await api.spending("GET", `export?${query}`, void 0, true),
125
+ null,
126
+ 2
127
+ ) + "\n";
128
+ if (o.output) {
129
+ await writeFile(o.output, data, { flag: "wx", mode: 384 });
130
+ if (isJsonMode()) printJson({ savedTo: o.output });
131
+ else printKeyValue("Saved", o.output);
132
+ } else process.stdout.write(data);
133
+ } catch (error) {
134
+ const message = error instanceof Error ? error.message : "Export failed";
135
+ if (isJsonMode()) printJson({ error: message });
136
+ else printError(message);
137
+ process.exitCode = 1;
138
+ }
139
+ });
140
+ const budgets = program2.command("budgets").description("Shared budget availability and owner controls");
141
+ budgets.command("list").option("--owner", "Use organization credentials").action((o) => run((api) => api.spending("GET", "budgets", void 0, o.owner), o.owner));
142
+ budgets.command("create <file>").description("Owner: create a budget from a JSON definition").action(
143
+ (file) => run(
144
+ async (api) => api.spending("POST", "budgets", JSON.parse(await readFile(file, "utf8")), true),
145
+ true
146
+ )
147
+ );
148
+ budgets.command("update <budgetId>").requiredOption("--expected-version <version>", "Current version").option("--amount <amount>", "Exact decimal ceiling").option("--expires <iso-date>", "Owner-approved extension of budget expiry").option("--pause", "Stop new purchases").option("--activate", "Resume within original expiry").action(
149
+ (budgetId, o) => run(async (api) => {
150
+ if (o.pause && o.activate) throw new Error("Choose either --pause or --activate.");
151
+ return api.spending(
152
+ "PATCH",
153
+ `budgets/${id(budgetId)}`,
154
+ {
155
+ version: Number(o.expectedVersion),
156
+ ...o.amount ? { amount: o.amount } : {},
157
+ ...o.expires ? { periodEnd: o.expires } : {},
158
+ ...o.pause ? { isActive: false } : o.activate ? { isActive: true } : {}
159
+ },
160
+ true
161
+ );
162
+ }, true)
163
+ );
164
+ const tasks = program2.command("tasks").description("Request and inspect bounded task authority");
165
+ tasks.command("list").option("--cursor <cursor>", "Next page cursor").option("--owner", "Use organization credentials").action(
166
+ (o) => run(
167
+ (api) => api.spending(
168
+ "GET",
169
+ `tasks${o.cursor ? `?cursor=${id(o.cursor)}` : ""}`,
170
+ void 0,
171
+ o.owner
172
+ ),
173
+ o.owner
174
+ )
175
+ );
176
+ tasks.command("request").requiredOption("--purpose <purpose>", "Purpose").requiredOption("--amount <amount>", "Exact ceiling").requiredOption("--currency <currency>", "Exact currency").requiredOption("--expires <iso-date>", "Expiry").option("--merchants <ids...>", "Exact permitted merchant identifiers").option("--sources <ids...>", "Permitted wallet or card IDs").action(
177
+ (o) => run(
178
+ (api) => api.spending("POST", "tasks", {
179
+ purpose: o.purpose,
180
+ amount: o.amount,
181
+ currency: o.currency,
182
+ expiresAt: o.expires,
183
+ permittedMerchants: o.merchants || [],
184
+ permittedSourceIds: o.sources || []
185
+ })
186
+ )
187
+ );
188
+ tasks.command("decide <taskId> <decision>").description("Owner: APPROVE, REJECT, or CLOSE").option("--amount <amount>", "Approved ceiling").option("--agents <ids...>", "Approved participants, including requester").action(
189
+ (taskId, decision, o) => run(
190
+ (api) => api.spending(
191
+ "POST",
192
+ `tasks/${id(taskId)}/decide`,
193
+ {
194
+ decision: decision.toUpperCase(),
195
+ ...o.amount ? { amount: o.amount } : {},
196
+ ...o.agents ? { participantIds: o.agents } : {}
197
+ },
198
+ true
199
+ ),
200
+ true
201
+ )
202
+ );
203
+ const purchases = program2.command("purchases").description("Inspect purchases, preview allowances, and attach evidence");
204
+ purchases.command("list").option("--cursor <cursor>", "Next page cursor").option("--owner", "Use organization credentials").action(
205
+ (o) => run(
206
+ (api) => api.spending(
207
+ "GET",
208
+ `purchases${o.cursor ? `?cursor=${id(o.cursor)}` : ""}`,
209
+ void 0,
210
+ o.owner
211
+ ),
212
+ o.owner
213
+ )
214
+ );
215
+ purchases.command("show <purchaseId>").option("--owner", "Use organization credentials").action(
216
+ (purchaseId, o) => run((api) => api.spending("GET", `purchases/${id(purchaseId)}`, void 0, o.owner), o.owner)
217
+ );
218
+ purchases.command("preview").requiredOption("--amount <amount>", "Exact amount").requiredOption("--currency <currency>", "Exact currency").requiredOption("--wallet <walletId>", "Managed wallet").requiredOption("--merchant <merchant>", "Recipient identifier").option("--task <taskId>", "Approved task").option("--purchase-key <key>", "Stable purchase identity").action(
219
+ (o) => run(
220
+ (api) => api.spending("POST", "purchases/preview", {
221
+ amount: o.amount,
222
+ currency: o.currency,
223
+ sourceId: o.wallet,
224
+ merchant: o.merchant,
225
+ ...o.task ? { taskRequestId: o.task } : {},
226
+ ...o.purchaseKey ? { purchaseKey: o.purchaseKey } : {}
227
+ })
228
+ )
229
+ );
230
+ purchases.command("status <paymentRequestId>").description("Check an existing payment request, including pending approval").action((requestId) => run((api) => api.getPaymentStatus(requestId)));
231
+ purchases.command("export <file>").description("Export one row per purchase; refuses to overwrite an existing file").option("--owner", "Export all workspace purchases using organization credentials").action(
232
+ (file, o) => run(async (api) => {
233
+ const bytes = await api.spendingDownload("purchases/export", o.owner);
234
+ await writeFile(file, bytes, { flag: "wx" });
235
+ return { saved: file };
236
+ }, o.owner)
237
+ );
238
+ purchases.command("accounting <purchaseId> <file>").description("Owner: set department, project, and accountingCode from JSON").action(
239
+ (purchaseId, file) => run(
240
+ async (api) => api.spending(
241
+ "PATCH",
242
+ `purchases/${id(purchaseId)}`,
243
+ JSON.parse(await readFile(file, "utf8")),
244
+ true
245
+ ),
246
+ true
247
+ )
248
+ );
249
+ purchases.command("review-evidence <purchaseId> <evidenceId> <file>").description("Owner: compare amount, currency, and merchant from a document").action(
250
+ (purchaseId, evidenceId, file) => run(
251
+ async (api) => api.spending(
252
+ "PATCH",
253
+ `purchases/${id(purchaseId)}/evidence/${id(evidenceId)}`,
254
+ JSON.parse(await readFile(file, "utf8")),
255
+ true
256
+ ),
257
+ true
258
+ )
259
+ );
260
+ purchases.command("resume <paymentRequestId>").description(
261
+ "Execute the existing authorized managed-wallet request; never create a replacement"
262
+ ).action((requestId) => run((api) => api.executePayment(requestId)));
263
+ purchases.command("attach <purchaseId> <file>").description("Attach a receipt or invoice (PDF, PNG, JPEG; 2 MiB)").action(
264
+ (purchaseId, file) => run(async (api) => {
265
+ const bytes = await readFile(file);
266
+ if (bytes.length > 2 * 1024 * 1024) throw new Error("Evidence exceeds 2 MiB.");
267
+ const mime = {
268
+ ".pdf": "application/pdf",
269
+ ".png": "image/png",
270
+ ".jpg": "image/jpeg",
271
+ ".jpeg": "image/jpeg"
272
+ };
273
+ const form = new FormData();
274
+ form.set(
275
+ "file",
276
+ new Blob([bytes], {
277
+ type: mime[extname(file).toLowerCase()] || "application/octet-stream"
278
+ }),
279
+ basename(file)
280
+ );
281
+ return api.spending("POST", `purchases/${id(purchaseId)}/evidence`, form);
282
+ })
283
+ );
284
+ purchases.command("reconcile <purchaseId> <file>").description("Owner: apply a verified outcome from a JSON file with a stable eventKey").action(
285
+ (purchaseId, file) => run(
286
+ async (api) => api.spending(
287
+ "POST",
288
+ `purchases/${id(purchaseId)}/reconcile`,
289
+ JSON.parse(await readFile(file, "utf8")),
290
+ true
291
+ ),
292
+ true
293
+ )
294
+ );
295
+ }
61
296
 
62
297
  // src/cli.ts
63
298
  import { Command } from "commander";
@@ -745,6 +980,7 @@ async function balanceCommand() {
745
980
  }
746
981
 
747
982
  // src/commands/pay.ts
983
+ import { randomUUID } from "crypto";
748
984
  import chalk3 from "chalk";
749
985
 
750
986
  // src/lib/payment-review.ts
@@ -754,19 +990,27 @@ Payments that need approval:
754
990
  the command prints a review link, opens it when it can, waits for the
755
991
  decision, and sends the payment once it is approved.
756
992
 
757
- conto pay status <requestId> Check a payment waiting for approval
758
- conto pay execute <requestId> Send a payment an approver already approved
993
+ conto pay status <requestId> Check any payment, and send it if an approver
994
+ approved it meanwhile
995
+ conto pay execute <requestId> Send a payment that is approved
996
+
997
+ When the outcome is unknown (exit 6), do not re-run the command, which would
998
+ start a new payment. Run conto pay status <requestId>. With no request ID yet,
999
+ re-run with the printed key: --idempotency-key <key> returns the same request.
759
1000
 
760
1001
  Exit codes:
761
1002
  0 sent, or already handled
762
1003
  1 request failed
763
1004
  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
1005
+ 4 not sent yet: waiting for approval (--no-wait, or the wait timed out),
1006
+ or approved and waiting for conto pay execute
1007
+ 5 the approval or the payment expired, or the approval was cancelled
1008
+ 6 outcome unknown: the payment may have gone through
766
1009
  `;
767
1010
  var PAY_EXIT_REJECTED = 3;
768
1011
  var PAY_EXIT_PENDING = 4;
769
1012
  var PAY_EXIT_EXPIRED = 5;
1013
+ var PAY_EXIT_OUTCOME_UNKNOWN = 6;
770
1014
  var POLL_INTERVAL_MS = Number(process.env.CONTO_REVIEW_POLL_MS) || 3e3;
771
1015
  var DEFAULT_WAIT_SECONDS = 300;
772
1016
  var PaymentReviewClient = class extends ApiClient {
@@ -838,10 +1082,17 @@ function printReviewOutcome(review, requestId) {
838
1082
  }
839
1083
 
840
1084
  // src/commands/pay.ts
841
- async function sendPayment(api, requestId, config) {
1085
+ function printRecoveryId(label, value) {
1086
+ if (isJsonMode()) {
1087
+ console.error(`${label}: ${value}`);
1088
+ } else {
1089
+ printKeyValue(label, value);
1090
+ }
1091
+ }
1092
+ async function sendPayment(api, requestId, config, idempotencyKey) {
842
1093
  const result = await api.executePayment(requestId);
843
1094
  if (isJsonMode()) {
844
- printJson(result);
1095
+ printJson(idempotencyKey ? { ...result, idempotencyKey } : result);
845
1096
  return;
846
1097
  }
847
1098
  if (config.sandboxMode === "test") {
@@ -859,23 +1110,52 @@ async function sendPayment(api, requestId, config) {
859
1110
  if (result.receipt?.explorerUrl) printKeyValue("Explorer", result.receipt?.explorerUrl);
860
1111
  console.log("");
861
1112
  }
862
- async function reviewAndSend(api, requestId, config, options) {
1113
+ async function reviewAndSend(api, requestId, config, options, idempotencyKey) {
863
1114
  const review = await followPaymentReview(api, requestId, options);
864
1115
  if (review.nextAction.type === "EXECUTE_PAYMENT") {
865
- return sendPayment(api, requestId, config);
1116
+ return sendPayment(api, requestId, config, idempotencyKey);
866
1117
  }
867
1118
  process.exitCode = paymentReviewExitCode(review);
868
1119
  if (isJsonMode()) {
869
- printJson({ requestId, review });
1120
+ printJson({ requestId, review, ...idempotencyKey ? { idempotencyKey } : {} });
870
1121
  return;
871
1122
  }
872
1123
  printReviewOutcome(review, requestId);
873
1124
  }
874
- function handlePayError(err) {
875
- const code = err.code;
1125
+ function exitOutcomeUnknown(message, code, identity) {
1126
+ const { requestId, idempotencyKey } = identity;
1127
+ const nextAction = requestId ? `conto pay status ${requestId}` : `Re-run the same command with --idempotency-key ${idempotencyKey}`;
1128
+ if (isJsonMode()) {
1129
+ printJson({ error: message, code, outcome: "unknown", ...identity, nextAction });
1130
+ process.exit(PAY_EXIT_OUTCOME_UNKNOWN);
1131
+ }
1132
+ printError(message);
1133
+ printWarning(
1134
+ requestId ? "Outcome unknown: this payment may have gone through." : "Outcome unknown: Conto may have recorded this request."
1135
+ );
1136
+ console.log(chalk3.dim(" Do not re-run this command as it is. It would start a new payment."));
1137
+ if (requestId) {
1138
+ printKeyValue("Request ID", requestId);
1139
+ console.log(chalk3.dim(` Check it with: ${nextAction}`));
1140
+ } else {
1141
+ console.log(chalk3.dim(` ${nextAction}. That returns the same request.`));
1142
+ }
1143
+ process.exit(PAY_EXIT_OUTCOME_UNKNOWN);
1144
+ }
1145
+ function handlePayError(err, identity = {}) {
1146
+ const { code, outcomeUnknown } = err;
876
1147
  const message = err instanceof Error ? err.message : "Payment failed";
1148
+ if (outcomeUnknown) exitOutcomeUnknown(message, code, identity);
1149
+ const { requestId } = identity;
1150
+ const nothingSent = code !== void 0 && NOTHING_SENT_CODES.has(code);
1151
+ const sendLater = requestId ? `conto pay execute ${requestId}` : void 0;
877
1152
  if (isJsonMode()) {
878
- printJson({ error: message, code });
1153
+ printJson({
1154
+ error: message,
1155
+ code,
1156
+ ...identity,
1157
+ ...nothingSent && sendLater ? { nextAction: sendLater } : {}
1158
+ });
879
1159
  process.exit(1);
880
1160
  }
881
1161
  printError(message);
@@ -884,11 +1164,94 @@ function handlePayError(err) {
884
1164
  chalk3.dim(' This SDK key cannot execute payments. Run "conto doctor" to see its scopes,')
885
1165
  );
886
1166
  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."));
1167
+ } else if (nothingSent) {
1168
+ console.log(
1169
+ chalk3.dim(" Nothing was sent. Try again later or contact Conto support if it continues.")
1170
+ );
1171
+ }
1172
+ if (requestId) {
1173
+ printKeyValue("Request ID", requestId);
1174
+ console.log(
1175
+ chalk3.dim(
1176
+ nothingSent ? ` Send it later with: ${sendLater}` : ` Check it with: conto pay status ${requestId}`
1177
+ )
1178
+ );
889
1179
  }
890
1180
  process.exit(1);
891
1181
  }
1182
+ function storedPaymentExitCode(status) {
1183
+ switch (status) {
1184
+ case "completed":
1185
+ case "processing":
1186
+ return 0;
1187
+ case "failed":
1188
+ case "declined":
1189
+ return 1;
1190
+ case "expired":
1191
+ return PAY_EXIT_EXPIRED;
1192
+ case "reconciliation_required":
1193
+ return PAY_EXIT_OUTCOME_UNKNOWN;
1194
+ default:
1195
+ return PAY_EXIT_PENDING;
1196
+ }
1197
+ }
1198
+ async function reportStoredPayment(api, requestId) {
1199
+ const payment = await api.getPaymentStatus(requestId);
1200
+ process.exitCode = storedPaymentExitCode(payment.status);
1201
+ if (isJsonMode()) {
1202
+ printJson(payment);
1203
+ return;
1204
+ }
1205
+ switch (payment.status) {
1206
+ case "completed":
1207
+ printSuccess("Payment sent");
1208
+ break;
1209
+ case "processing":
1210
+ printPending("Payment is processing. Do not send it again.");
1211
+ break;
1212
+ case "approved":
1213
+ printPending("Approved and not sent yet.");
1214
+ console.log(chalk3.dim(` Send it with: conto pay execute ${requestId}`));
1215
+ break;
1216
+ case "reconciliation_required":
1217
+ printWarning("Conto is confirming whether this transfer went through. Do not send it again.");
1218
+ break;
1219
+ case "failed":
1220
+ printError("The payment failed.");
1221
+ break;
1222
+ case "declined":
1223
+ printError("The payment was declined.");
1224
+ break;
1225
+ case "expired":
1226
+ printError("The payment expired before it was sent.");
1227
+ break;
1228
+ default:
1229
+ printPending(`Payment is ${payment.status}.`);
1230
+ console.log(chalk3.dim(" Check the Conto dashboard for next steps."));
1231
+ }
1232
+ if (payment.transaction?.txHash) printKeyValue("TX Hash", payment.transaction.txHash);
1233
+ printKeyValue("Amount", printAmount(payment.amount, payment.currency));
1234
+ printKeyValue("Recipient", payment.recipient);
1235
+ printKeyValue("Status", payment.status);
1236
+ printKeyValue("Request ID", requestId);
1237
+ if (payment.transaction?.explorerUrl) printKeyValue("Explorer", payment.transaction.explorerUrl);
1238
+ if (payment.reasons?.length) {
1239
+ console.log(chalk3.dim(` Reasons: ${payment.reasons.join(", ")}`));
1240
+ }
1241
+ console.log("");
1242
+ }
1243
+ function isNoApprovalRequired(err) {
1244
+ const { code, details } = err;
1245
+ return code === "NO_APPROVAL_REQUIRED" || details?.code === "NO_APPROVAL_REQUIRED";
1246
+ }
1247
+ async function payStatus(api, requestId, config, options) {
1248
+ try {
1249
+ return await reviewAndSend(api, requestId, config, { wait: false, open: false, ...options });
1250
+ } catch (err) {
1251
+ if (!isNoApprovalRequired(err)) throw err;
1252
+ }
1253
+ return reportStoredPayment(api, requestId);
1254
+ }
892
1255
  async function payFollowUpCommand(subcommand, requestId, options) {
893
1256
  const config = loadConfig();
894
1257
  if (!config.apiKey) {
@@ -900,9 +1263,9 @@ async function payFollowUpCommand(subcommand, requestId, options) {
900
1263
  const api = new PaymentReviewClient({ baseUrl: config.baseUrl, apiKey: config.apiKey });
901
1264
  try {
902
1265
  if (subcommand === "execute") return await sendPayment(api, requestId, config);
903
- return await reviewAndSend(api, requestId, config, { wait: false, open: false, ...options });
1266
+ return await payStatus(api, requestId, config, options);
904
1267
  } catch (err) {
905
- handlePayError(err);
1268
+ handlePayError(err, { requestId });
906
1269
  }
907
1270
  }
908
1271
  var DRY_RUN_NOTICE = "Dry run: nothing was sent to Conto and no policy evaluation was performed.";
@@ -918,6 +1281,15 @@ async function payCommand(address, amountStr, options) {
918
1281
  category: options.category,
919
1282
  walletId: options.wallet
920
1283
  });
1284
+ const identity = {
1285
+ ...options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {},
1286
+ ...options.task || options.purchaseKey ? {
1287
+ context: {
1288
+ ...options.task ? { taskRequestId: options.task } : {},
1289
+ ...options.purchaseKey ? { purchaseKey: options.purchaseKey } : {}
1290
+ }
1291
+ } : {}
1292
+ };
921
1293
  if (options.dryRun) {
922
1294
  const baseUrl = (config.baseUrl || "https://conto.finance").replace(/\/+$/, "");
923
1295
  const url = `${baseUrl}/api/sdk/payments/request`;
@@ -942,7 +1314,7 @@ async function payCommand(address, amountStr, options) {
942
1314
  valid: true,
943
1315
  policyEvaluated: false,
944
1316
  apiKeyConfigured: Boolean(config.apiKey),
945
- request: { method: "POST", url, body: validation.body },
1317
+ request: { method: "POST", url, body: { ...validation.body, ...identity } },
946
1318
  note: DRY_RUN_NOTICE
947
1319
  });
948
1320
  return;
@@ -956,7 +1328,7 @@ async function payCommand(address, amountStr, options) {
956
1328
  console.log("");
957
1329
  printSuccess("Input is valid");
958
1330
  console.log(chalk3.dim(` Would send: POST ${url}`));
959
- console.log(chalk3.dim(` ${JSON.stringify(validation.body)}`));
1331
+ console.log(chalk3.dim(` ${JSON.stringify({ ...validation.body, ...identity })}`));
960
1332
  if (!config.apiKey) {
961
1333
  printWarning('No API key configured. Run "conto login" before sending payments.');
962
1334
  }
@@ -982,24 +1354,41 @@ async function payCommand(address, amountStr, options) {
982
1354
  baseUrl: config.baseUrl,
983
1355
  apiKey: config.apiKey
984
1356
  });
1357
+ const idempotencyKey = options.idempotencyKey ?? randomUUID();
1358
+ const payIdentity = { idempotencyKey };
985
1359
  try {
986
1360
  if (!isJsonMode()) {
987
1361
  printHeader("Payment Request");
988
1362
  printKeyValue("To", address);
989
1363
  printKeyValue("Amount", printAmount(amount, config.currency || "USD"));
990
1364
  if (options.purpose) printKeyValue("Purpose", options.purpose);
991
- console.log("");
992
1365
  }
1366
+ printRecoveryId("Idempotency key", idempotencyKey);
1367
+ if (!isJsonMode()) console.log("");
993
1368
  const request = await api.requestPayment({
994
1369
  amount,
995
1370
  recipientAddress: address,
996
1371
  purpose: options.purpose,
997
1372
  category: options.category,
998
- walletId: options.wallet
1373
+ walletId: options.wallet,
1374
+ ...identity,
1375
+ idempotencyKey
999
1376
  });
1377
+ payIdentity.requestId = request.requestId;
1378
+ if (request.status === "COMPLETED" || request.status === "PROCESSING") {
1379
+ if (isJsonMode()) {
1380
+ printJson({ ...request, idempotencyKey });
1381
+ return;
1382
+ }
1383
+ printSuccess("This payment was already sent. No new payment was created.");
1384
+ printKeyValue("Status", request.status);
1385
+ printKeyValue("Request ID", request.requestId);
1386
+ console.log(chalk3.dim(` Check it with: conto pay status ${request.requestId}`));
1387
+ return;
1388
+ }
1000
1389
  if (request.status === "DENIED") {
1001
1390
  if (isJsonMode()) {
1002
- printJson(request);
1391
+ printJson({ ...request, idempotencyKey });
1003
1392
  return;
1004
1393
  }
1005
1394
  printError("Payment denied by policy");
@@ -1015,12 +1404,12 @@ async function payCommand(address, amountStr, options) {
1015
1404
  process.exit(1);
1016
1405
  }
1017
1406
  if (request.status === "REQUIRES_APPROVAL") {
1018
- if (!isJsonMode()) printKeyValue("Request ID", request.requestId);
1019
- return await reviewAndSend(api, request.requestId, config, options);
1407
+ printRecoveryId("Request ID", request.requestId);
1408
+ return await reviewAndSend(api, request.requestId, config, options, idempotencyKey);
1020
1409
  }
1021
1410
  if (request.status !== "APPROVED") {
1022
1411
  if (isJsonMode()) {
1023
- printJson(request);
1412
+ printJson({ ...request, idempotencyKey });
1024
1413
  return;
1025
1414
  }
1026
1415
  printPending(`Payment is ${request.status}`);
@@ -1031,14 +1420,15 @@ async function payCommand(address, amountStr, options) {
1031
1420
  console.log(chalk3.dim(" Check the Conto dashboard for next steps."));
1032
1421
  return;
1033
1422
  }
1034
- await sendPayment(api, request.requestId, config);
1423
+ printRecoveryId("Request ID", request.requestId);
1424
+ await sendPayment(api, request.requestId, config, idempotencyKey);
1035
1425
  } catch (err) {
1036
- handlePayError(err);
1426
+ handlePayError(err, payIdentity);
1037
1427
  }
1038
1428
  }
1039
1429
 
1040
1430
  // src/commands/transactions.ts
1041
- async function transactionsCommand(id, options) {
1431
+ async function transactionsCommand(id2, options) {
1042
1432
  const config = loadConfig();
1043
1433
  if (!config.apiKey) {
1044
1434
  printError(missingSdkKeyMessage(config));
@@ -1049,8 +1439,8 @@ async function transactionsCommand(id, options) {
1049
1439
  apiKey: config.apiKey
1050
1440
  });
1051
1441
  try {
1052
- if (id) {
1053
- const tx = await api.getTransaction(id);
1442
+ if (id2) {
1443
+ const tx = await api.getTransaction(id2);
1054
1444
  if (isJsonMode()) {
1055
1445
  printJson(tx);
1056
1446
  return;
@@ -1080,7 +1470,7 @@ async function transactionsCommand(id, options) {
1080
1470
  if (tx.alerts && tx.alerts.length > 0) {
1081
1471
  printHeader("Alerts");
1082
1472
  for (const a of tx.alerts) {
1083
- console.log(` [${a.severity.label}] ${a.title} \u2014 ${a.status.label}`);
1473
+ console.log(` [${a.severity.label}] ${a.title}: ${a.status.label}`);
1084
1474
  console.log(` ${a.message}`);
1085
1475
  if (a.reviewUrl) console.log(` Review: ${a.reviewUrl}`);
1086
1476
  }
@@ -1106,9 +1496,9 @@ async function transactionsCommand(id, options) {
1106
1496
  new Date(tx.initiatedAt).toLocaleDateString(),
1107
1497
  printAmount(Number(tx.amount), tx.currency),
1108
1498
  tx.recipientAgent?.name || tx.merchantName || truncateAddress(tx.toAddress),
1109
- tx.purpose || "\u2014",
1499
+ tx.purpose || "-",
1110
1500
  tx.status,
1111
- tx.txHash ? truncateAddress(tx.txHash, 8) : "\u2014"
1501
+ tx.txHash ? truncateAddress(tx.txHash, 8) : "-"
1112
1502
  ])
1113
1503
  );
1114
1504
  }
@@ -1945,6 +2335,36 @@ async function promptForRule(policyType) {
1945
2335
  action: action2
1946
2336
  };
1947
2337
  }
2338
+ if (ruleStr === "BUDGET_CAP") {
2339
+ const period = await p.select({
2340
+ message: "Budget period",
2341
+ options: BUDGET_PERIODS.map((value2) => ({ value: value2, label: value2.toLowerCase() })),
2342
+ initialValue: "MONTHLY"
2343
+ });
2344
+ if (p.isCancel(period)) return null;
2345
+ const amount = await p.text({
2346
+ message: "Budget amount in dollars",
2347
+ placeholder: "500",
2348
+ validate: (v) => {
2349
+ const result = buildBudgetCapValue(v ?? "", period);
2350
+ return result.ok ? void 0 : result.error;
2351
+ }
2352
+ });
2353
+ if (p.isCancel(amount)) return null;
2354
+ const built = buildBudgetCapValue(amount, period);
2355
+ if (!built.ok) return null;
2356
+ const action2 = await p.select({
2357
+ message: "Action when rule triggers",
2358
+ options: ACTIONS
2359
+ });
2360
+ if (p.isCancel(action2)) return null;
2361
+ return {
2362
+ ruleType: ruleStr,
2363
+ operator,
2364
+ value: built.value,
2365
+ action: action2
2366
+ };
2367
+ }
1948
2368
  let placeholder = "500";
1949
2369
  let valueHint = "Enter a number for limits, or JSON for lists";
1950
2370
  if (ruleStr.includes("LIMIT") || ruleStr.includes("AMOUNT") || ruleStr.includes("CAP") || ruleStr === "REQUIRE_APPROVAL_ABOVE") {
@@ -1960,7 +2380,7 @@ async function promptForRule(policyType) {
1960
2380
  placeholder = '["US","GB","DE"]';
1961
2381
  valueHint = "JSON array of country codes";
1962
2382
  } else if (ruleStr === "DATE_RANGE") {
1963
- placeholder = '{"start":"2025-01-01","end":"2025-12-31"}';
2383
+ placeholder = dateRangePlaceholder();
1964
2384
  valueHint = "JSON with start and end dates (ISO format)";
1965
2385
  }
1966
2386
  const value = await p.text({
@@ -2146,6 +2566,7 @@ async function simulatePolicy(api, policyId) {
2146
2566
 
2147
2567
  // src/commands/limits.ts
2148
2568
  import chalk6 from "chalk";
2569
+ var UNLIMITED = "unlimited";
2149
2570
  async function limitsCommand() {
2150
2571
  const config = loadConfig();
2151
2572
  if (!config.apiKey) {
@@ -2172,23 +2593,13 @@ async function limitsCommand() {
2172
2593
  for (const l of limits) {
2173
2594
  console.log(`
2174
2595
  ${chalk6.bold(l.walletName)}`);
2175
- const dailyPct = l.daily.limit > 0 ? Math.round(l.daily.spent / l.daily.limit * 100) : 0;
2176
- console.log(
2177
- ` ${chalk6.dim("Daily:")} ${bar(dailyPct)} ${printAmount(l.daily.spent, "USD")} / ${printAmount(l.daily.limit, "USD")} ${chalk6.dim(`(${printAmount(l.daily.remaining, "USD")} remaining)`)}`
2596
+ printWindow("Daily: ", l.daily);
2597
+ printWindow("Weekly: ", l.weekly);
2598
+ printWindow("Monthly: ", l.monthly);
2599
+ printKeyValue(
2600
+ " Per-TX max",
2601
+ l.perTransaction === null ? UNLIMITED : printAmount(l.perTransaction, "USD")
2178
2602
  );
2179
- if (l.weekly) {
2180
- const weeklyPct = l.weekly.limit > 0 ? Math.round(l.weekly.spent / l.weekly.limit * 100) : 0;
2181
- console.log(
2182
- ` ${chalk6.dim("Weekly:")} ${bar(weeklyPct)} ${printAmount(l.weekly.spent, "USD")} / ${printAmount(l.weekly.limit, "USD")} ${chalk6.dim(`(${printAmount(l.weekly.remaining, "USD")} remaining)`)}`
2183
- );
2184
- }
2185
- if (l.monthly) {
2186
- const monthlyPct = l.monthly.limit > 0 ? Math.round(l.monthly.spent / l.monthly.limit * 100) : 0;
2187
- console.log(
2188
- ` ${chalk6.dim("Monthly:")} ${bar(monthlyPct)} ${printAmount(l.monthly.spent, "USD")} / ${printAmount(l.monthly.limit, "USD")} ${chalk6.dim(`(${printAmount(l.monthly.remaining, "USD")} remaining)`)}`
2189
- );
2190
- }
2191
- printKeyValue(" Per-TX max", printAmount(l.perTransaction, "USD"));
2192
2603
  }
2193
2604
  console.log("");
2194
2605
  } catch (err) {
@@ -2201,6 +2612,17 @@ async function limitsCommand() {
2201
2612
  process.exit(1);
2202
2613
  }
2203
2614
  }
2615
+ function printWindow(label, window) {
2616
+ const spent = printAmount(window.spent, "USD");
2617
+ if (window.limit === null) {
2618
+ console.log(` ${chalk6.dim(label)} ${UNLIMITED} ${chalk6.dim(`(${spent} spent)`)}`);
2619
+ return;
2620
+ }
2621
+ const pct = window.limit > 0 ? Math.round(window.spent / window.limit * 100) : 0;
2622
+ console.log(
2623
+ ` ${chalk6.dim(label)} ${bar(pct)} ${spent} / ${printAmount(window.limit, "USD")} ${chalk6.dim(`(${printAmount(window.remaining ?? 0, "USD")} remaining)`)}`
2624
+ );
2625
+ }
2204
2626
  function bar(pct, width = 15) {
2205
2627
  const filled = Math.round(pct / 100 * width);
2206
2628
  const empty = width - filled;
@@ -2610,9 +3032,9 @@ async function counterpartiesListCommand() {
2610
3032
  );
2611
3033
  });
2612
3034
  }
2613
- async function counterpartiesShowCommand(id) {
3035
+ async function counterpartiesShowCommand(id2) {
2614
3036
  await runOwnerCommand("org", async ({ api }) => {
2615
- const payee = await api.getCounterparty(id);
3037
+ const payee = await api.getCounterparty(id2);
2616
3038
  if (isJsonMode()) return printJson(payee);
2617
3039
  printHeader(payee.name);
2618
3040
  printKeyValue("ID", payee.id);
@@ -2638,22 +3060,22 @@ async function counterpartiesAddCommand(options) {
2638
3060
  printKeyValue("ID", payee.id);
2639
3061
  });
2640
3062
  }
2641
- async function counterpartiesBlockCommand(id) {
3063
+ async function counterpartiesBlockCommand(id2) {
2642
3064
  await runOwnerCommand("org", async ({ api }) => {
2643
- const payee = await api.updateCounterparty(id, { lifecycleStatus: "BLOCKED" });
3065
+ const payee = await api.updateCounterparty(id2, { lifecycleStatus: "BLOCKED" });
2644
3066
  if (isJsonMode()) return printJson(payee);
2645
3067
  printSuccess(`Payee ${payee.name} is blocked. Agents cannot pay it.`);
2646
3068
  });
2647
3069
  }
2648
- async function counterpartiesApproveCommand(id, options) {
3070
+ async function counterpartiesApproveCommand(id2, options) {
2649
3071
  await runOwnerCommand("org", async ({ api }) => {
2650
3072
  const result = await directOrReview(
2651
3073
  api,
2652
- () => api.updateCounterparty(id, { lifecycleStatus: "APPROVED" }),
3074
+ () => api.updateCounterparty(id2, { lifecycleStatus: "APPROVED" }),
2653
3075
  async () => ({
2654
3076
  action: "set_counterparty_status",
2655
3077
  input: {
2656
- counterparty_id: id,
3078
+ counterparty_id: id2,
2657
3079
  status: "APPROVED",
2658
3080
  ...options.reason ? { reason: options.reason } : {}
2659
3081
  }
@@ -2692,15 +3114,15 @@ async function channelsAddCommand(options) {
2692
3114
  const type = options.type?.toUpperCase();
2693
3115
  if (!options.name || !type) throw new Error("Pass --name and --type (email or webhook).");
2694
3116
  let config;
2695
- let webhookSecret;
3117
+ let generatedSecret;
2696
3118
  if (type === "EMAIL") {
2697
3119
  const recipients = (options.recipients ?? "").split(",").map((email) => email.trim()).filter(Boolean);
2698
3120
  if (recipients.length === 0) throw new Error("Pass --recipients with one or more emails.");
2699
3121
  config = { recipients };
2700
3122
  } else if (type === "WEBHOOK") {
2701
3123
  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 };
3124
+ if (!process.env.CONTO_WEBHOOK_SECRET) generatedSecret = randomBytes(32).toString("hex");
3125
+ config = { url: options.url, secret: process.env.CONTO_WEBHOOK_SECRET || generatedSecret };
2704
3126
  } else {
2705
3127
  throw new Error(
2706
3128
  "The CLI adds email and webhook channels. Add Slack, Telegram or WhatsApp in Settings > Event Delivery."
@@ -2714,28 +3136,31 @@ async function channelsAddCommand(options) {
2714
3136
  ...eventTypes?.length ? { eventTypes } : {}
2715
3137
  });
2716
3138
  if (isJsonMode()) {
2717
- return printJson({ ...created, ...webhookSecret ? { webhookSecret } : {} });
3139
+ return printJson({
3140
+ ...created,
3141
+ ...generatedSecret ? { webhookSecret: generatedSecret } : {}
3142
+ });
2718
3143
  }
2719
3144
  printSuccess(`Channel ${options.name} added.`);
2720
- if (webhookSecret && !process.env.CONTO_WEBHOOK_SECRET) {
2721
- printKeyValue("Signing secret", webhookSecret);
3145
+ if (generatedSecret) {
3146
+ printKeyValue("Signing secret", generatedSecret);
2722
3147
  printWarning("Store this secret now to verify event signatures. It is not shown again.");
2723
3148
  }
2724
3149
  });
2725
3150
  }
2726
- async function channelsTestCommand(id) {
3151
+ async function channelsTestCommand(id2) {
2727
3152
  await runOwnerCommand("org", async ({ api }) => {
2728
- const result = await api.testChannel(id);
3153
+ const result = await api.testChannel(id2);
2729
3154
  if (isJsonMode()) return printJson(result);
2730
3155
  printSuccess("Test event sent.");
2731
3156
  });
2732
3157
  }
2733
- async function channelsRemoveCommand(id, options) {
3158
+ async function channelsRemoveCommand(id2, options) {
2734
3159
  await runOwnerCommand("org", async ({ api }) => {
2735
3160
  const result = await directOrReview(
2736
3161
  api,
2737
- () => api.deleteChannel(id),
2738
- async () => ({ action: "remove_notification_channel", input: { channel_id: id } }),
3162
+ () => api.deleteChannel(id2),
3163
+ async () => ({ action: "remove_notification_channel", input: { channel_id: id2 } }),
2739
3164
  options
2740
3165
  );
2741
3166
  if ("review" in result) return reportReview(result.review, "Channel removed.");
@@ -2819,13 +3244,38 @@ async function configCommand(key, value) {
2819
3244
  }
2820
3245
 
2821
3246
  // src/commands/login.ts
3247
+ var DEFAULT_BASE_URL = "https://conto.finance";
3248
+ function isSameServer(a, b) {
3249
+ try {
3250
+ return normalizeBaseUrl(a) === normalizeBaseUrl(b);
3251
+ } catch {
3252
+ return false;
3253
+ }
3254
+ }
2822
3255
  async function loginCommand(options = {}) {
2823
3256
  const existingConfig = loadGlobalConfig();
2824
- const baseUrl = options.baseUrl || existingConfig.server?.baseUrl || "https://conto.finance";
3257
+ const baseUrl = options.baseUrl || existingConfig.server?.baseUrl || DEFAULT_BASE_URL;
2825
3258
  printInfo("Opening browser to authenticate...");
2826
3259
  try {
2827
- const { orgApiKey, organizationName, expiresAt } = await browserAuth(baseUrl);
3260
+ const { orgApiKey, organizationName, expiresAt } = await browserAuth(
3261
+ baseUrl,
3262
+ (authUrl) => printInfo(`If the browser does not open, visit: ${authUrl}`)
3263
+ );
2828
3264
  const config = loadGlobalConfig();
3265
+ const previousBaseUrl = config.server?.baseUrl || DEFAULT_BASE_URL;
3266
+ if (!isSameServer(previousBaseUrl, baseUrl)) {
3267
+ const hadAgent = Boolean(config.server?.apiKey || config.agent);
3268
+ delete config.agent;
3269
+ delete config.wallet;
3270
+ delete config.network;
3271
+ delete config.sandbox;
3272
+ config.server = { baseUrl };
3273
+ if (hadAgent) {
3274
+ printInfo(
3275
+ `Removed the agent key saved for ${previousBaseUrl}. Run "conto init" to set up an agent on ${baseUrl}.`
3276
+ );
3277
+ }
3278
+ }
2829
3279
  if (!config.server) {
2830
3280
  config.server = { baseUrl };
2831
3281
  }
@@ -2878,7 +3328,7 @@ async function mcpCommand() {
2878
3328
  }
2879
3329
 
2880
3330
  // src/commands/webhooks.ts
2881
- import { createHmac, randomUUID } from "crypto";
3331
+ import { createHmac, randomUUID as randomUUID2 } from "crypto";
2882
3332
  async function testWebhook(url) {
2883
3333
  const started = Date.now();
2884
3334
  try {
@@ -2893,13 +3343,13 @@ async function testWebhook(url) {
2893
3343
  );
2894
3344
  const event = "payment.confirmed";
2895
3345
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
2896
- const paymentId = `test_${randomUUID()}`;
3346
+ const paymentId = `test_${randomUUID2()}`;
2897
3347
  const body = JSON.stringify({
2898
3348
  event,
2899
3349
  timestamp,
2900
3350
  data: {
2901
3351
  paymentId,
2902
- transactionId: `test_${randomUUID()}`,
3352
+ transactionId: `test_${randomUUID2()}`,
2903
3353
  agentId: "test_agent",
2904
3354
  transactionHash: `0x${"0".repeat(64)}`,
2905
3355
  amount: 0.01,
@@ -3198,7 +3648,7 @@ var SANDBOX_CLAIM_EXIT_CODES = {
3198
3648
  rateLimited: 5,
3199
3649
  interrupted: 130
3200
3650
  };
3201
- var DEFAULT_BASE_URL = "https://conto.finance";
3651
+ var DEFAULT_BASE_URL2 = "https://conto.finance";
3202
3652
  var DEFAULT_WAIT_SECONDS2 = 300;
3203
3653
  var MAX_WAIT_SECONDS = 3600;
3204
3654
  var MAX_CONSECUTIVE_POLL_ERRORS = 3;
@@ -3268,7 +3718,7 @@ function resolveSandboxCredential(command) {
3268
3718
  })
3269
3719
  };
3270
3720
  }
3271
- const baseUrl = fromProcess ? process.env.CONTO_BASE_URL || DEFAULT_BASE_URL : process.env.CONTO_BASE_URL || env.CONTO_BASE_URL || DEFAULT_BASE_URL;
3721
+ const baseUrl = fromProcess ? process.env.CONTO_BASE_URL || DEFAULT_BASE_URL2 : process.env.CONTO_BASE_URL || env.CONTO_BASE_URL || DEFAULT_BASE_URL2;
3272
3722
  try {
3273
3723
  parseSecureBaseUrl(baseUrl);
3274
3724
  } catch (error) {
@@ -3473,9 +3923,9 @@ async function waitForClaim(credential, state, timeoutSeconds, stats) {
3473
3923
  process.removeListener("SIGINT", onSigint);
3474
3924
  }
3475
3925
  }
3476
- async function withFailureReport(command, run) {
3926
+ async function withFailureReport(command, run2) {
3477
3927
  try {
3478
- await run();
3928
+ await run2();
3479
3929
  } catch (error) {
3480
3930
  emit(
3481
3931
  failureReport(command, SANDBOX_CLAIM_EXIT_CODES.failed, {
@@ -3928,7 +4378,7 @@ Exit codes:
3928
4378
  5 rate limited
3929
4379
  130 interrupted while waiting, the link is still valid
3930
4380
  `;
3931
- program.name("conto").description("Conto CLI \u2014 Agentic Payments Control Center").version(CLI_PACKAGE_VERSION).option("--json", "Output in JSON format").hook("preAction", (_thisCommand, actionCommand) => {
4381
+ program.name("conto").description("Conto CLI: agentic payments control center").version(CLI_PACKAGE_VERSION).option("--json", "Output in JSON format").hook("preAction", (_thisCommand, actionCommand) => {
3932
4382
  const opts = actionCommand.optsWithGlobals();
3933
4383
  if (opts.json) {
3934
4384
  setJsonMode(true);
@@ -3943,7 +4393,7 @@ program.command("init").description("Run the setup wizard (interactive, or headl
3943
4393
  ).option(
3944
4394
  "--confirm-mainnet",
3945
4395
  "Confirm that the selected network can move real funds (required for headless mainnet setup)"
3946
- ).option("--no-install", "Skip installing the conto CLI into the project").option("--resume", "Finish an unfinished organization setup recorded in .conto/").option("--restart", "Discard an unfinished setup record and start a new setup").addHelpText("after", INIT_EXIT_CODES_HELP).action(async (opts, command) => {
4396
+ ).option("--no-install", "Skip installing the conto CLI into the project").option("--resume", "Finish an unfinished organization setup recorded in .conto/").option("--restart", "Discard an unfinished setup record and start a new setup").option("--overwrite", "Replace an existing conto.config.json and example.mjs without asking").addHelpText("after", INIT_EXIT_CODES_HELP).action(async (opts, command) => {
3947
4397
  if (command.optsWithGlobals().json) {
3948
4398
  setJsonMode(true);
3949
4399
  }
@@ -3958,7 +4408,8 @@ program.command("init").description("Run the setup wizard (interactive, or headl
3958
4408
  apiKey: opts.apiKey,
3959
4409
  confirmMainnet: opts.confirmMainnet === true,
3960
4410
  resume: opts.resume === true,
3961
- restart: opts.restart === true
4411
+ restart: opts.restart === true,
4412
+ overwrite: opts.overwrite === true
3962
4413
  });
3963
4414
  });
3964
4415
  var sandboxCommand = program.command("sandbox").description("Hand an anonymous sandbox to the person who will own it");
@@ -3968,7 +4419,10 @@ program.command("webhooks").description("Test local webhook handlers").command("
3968
4419
  program.command("status").description("Agent info, wallet balances, spending summary").action(statusCommand);
3969
4420
  program.command("doctor").description("Diagnose setup: auth, key scopes, wallet, chain, balance, base URL").action(doctorCommand);
3970
4421
  program.command("balance").description("Wallet balances across all linked wallets").action(balanceCommand);
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(
4422
+ 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("--task <taskId>", "Approved shared task authority").option("--purchase-key <key>", "Stable identity for the purchase").option(
4423
+ "--idempotency-key <key>",
4424
+ "Reuse the key a failed run printed, so the retry returns the same request"
4425
+ ).option(
3972
4426
  "--wait [seconds]",
3973
4427
  "Wait for approval when it is needed (default when run in a terminal)"
3974
4428
  ).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);
@@ -4040,7 +4494,7 @@ withReview(
4040
4494
  "Manage spending policies (list, all, create, update, delete, assign, unassign, add-rule, remove-rule, versions, rollback, simulate)"
4041
4495
  )
4042
4496
  ).action(
4043
- (subcommand, id, extra, opts) => policiesCommand(subcommand || "list", id, extra, opts)
4497
+ (subcommand, id2, extra, opts) => policiesCommand(subcommand || "list", id2, extra, opts)
4044
4498
  );
4045
4499
  program.command("limits").description("Show spending limits and remaining budget").action(limitsCommand);
4046
4500
  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);
@@ -4049,9 +4503,9 @@ alertsGroup.command("resolve <alertId>").description("Resolve an alert").action(
4049
4503
  program.command("config [key] [value]").description("Show or update configuration").action(configCommand);
4050
4504
  program.command("login").description("Authenticate with Conto").option("--base-url <url>", "Conto instance URL").action(loginCommand);
4051
4505
  program.command("logout").description("Clear stored credentials").action(async () => {
4052
- const { clearGlobalConfig } = await import("./config-N7W4ZJJY.js");
4506
+ const { clearGlobalConfig } = await import("./config-MACPIPYV.js");
4053
4507
  clearGlobalConfig();
4054
- const { printSuccess: printSuccess2 } = await import("./output-IN47X4NU.js");
4508
+ const { printSuccess: printSuccess2 } = await import("./output-GD3QK4HS.js");
4055
4509
  printSuccess2("Logged out. Credentials cleared.");
4056
4510
  });
4057
4511
  program.command("mcp").description("Start MCP server for AI agent integration").action(mcpCommand);
@@ -4065,8 +4519,9 @@ program.command("docs [topic]").description("Open Conto documentation (cli, poli
4065
4519
  api: "https://conto.finance/docs/api"
4066
4520
  };
4067
4521
  const url = urls[topic || "cli"] || urls.cli;
4068
- const { printInfo: printInfo2 } = await import("./output-IN47X4NU.js");
4522
+ const { printInfo: printInfo2 } = await import("./output-GD3QK4HS.js");
4069
4523
  printInfo2(`Opening ${url}`);
4070
4524
  open(url);
4071
4525
  });
4526
+ registerSpendingCommands(program);
4072
4527
  program.parse();