@conto_finance/create-conto-agent 0.8.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -28,16 +28,17 @@ import {
28
28
  retryAfterSeconds,
29
29
  runInit,
30
30
  writeProjectStateFile
31
- } from "./chunk-HGEZBNZB.js";
31
+ } from "./chunk-6PK4I5VO.js";
32
32
  import {
33
33
  BUDGET_PERIODS,
34
34
  VELOCITY_PERIODS,
35
35
  buildBudgetCapValue,
36
36
  buildVelocityCountValue,
37
37
  dateRangePlaceholder,
38
+ isBlocklistRuleType,
38
39
  parseTrustScoreInput,
39
40
  validatePaymentRequest
40
- } from "./chunk-2M2WVAJI.js";
41
+ } from "./chunk-PUHGIKBB.js";
41
42
  import {
42
43
  SANDBOX_SETUP_ENV_FILE,
43
44
  isSensitiveConfigKey,
@@ -46,8 +47,9 @@ import {
46
47
  loadProjectEnv,
47
48
  maskSecret,
48
49
  missingSdkKeyMessage,
49
- saveGlobalConfig
50
- } from "./chunk-RQ4PUBL7.js";
50
+ saveGlobalConfig,
51
+ savedOrgKeyFor
52
+ } from "./chunk-F72EK2TO.js";
51
53
  import {
52
54
  isJsonMode,
53
55
  printAmount,
@@ -67,14 +69,116 @@ import {
67
69
  // src/commands/spending.ts
68
70
  import { readFile, writeFile } from "fs/promises";
69
71
  import { basename, extname } from "path";
72
+
73
+ // src/lib/org-key.ts
74
+ var OrgKeyError = class extends Error {
75
+ constructor(code, message) {
76
+ super(message);
77
+ this.code = code;
78
+ this.name = "OrgKeyError";
79
+ }
80
+ code;
81
+ };
82
+ var SAVED = "The organization key saved in ~/.conto/config.json";
83
+ var REQUEST_TIMEOUT_MS = Number(process.env.CONTO_REQUEST_TIMEOUT_MS) || 3e4;
84
+ var checks = /* @__PURE__ */ new Map();
85
+ function hasOrgApiKey(config) {
86
+ return Boolean(config.orgApiKey || savedOrgKeyFor(config));
87
+ }
88
+ function resolveOrgApiKey(config) {
89
+ if (config.orgApiKey) return Promise.resolve(config.orgApiKey);
90
+ const saved = savedOrgKeyFor(config);
91
+ if (!saved || !config.apiKey) return Promise.resolve(void 0);
92
+ const id2 = [config.baseUrl, config.apiKey, saved.baseUrl, saved.orgApiKey].join("\n");
93
+ let check = checks.get(id2);
94
+ if (!check) {
95
+ check = confirmSameOrganization(config.baseUrl, config.apiKey, saved);
96
+ checks.set(id2, check);
97
+ }
98
+ return check;
99
+ }
100
+ function orgApiKeySource(config) {
101
+ if (config.orgApiKey) return config.orgApiKey;
102
+ return savedOrgKeyFor(config) ? () => resolveOrgApiKey(config) : void 0;
103
+ }
104
+ function sameBaseUrl(a, b) {
105
+ try {
106
+ return normalizeBaseUrl(a) === normalizeBaseUrl(b);
107
+ } catch {
108
+ return false;
109
+ }
110
+ }
111
+ async function get(baseUrl, path2, bearer) {
112
+ try {
113
+ return await requestJson({
114
+ url: apiUrl(baseUrl, path2),
115
+ method: "GET",
116
+ bearer,
117
+ timeoutMs: REQUEST_TIMEOUT_MS
118
+ });
119
+ } catch (err) {
120
+ throw unconfirmed(
121
+ err instanceof HttpTransportError && err.code === "REDIRECT_REFUSED" ? "the server answered with a redirect" : "the server could not be reached"
122
+ );
123
+ }
124
+ }
125
+ function unconfirmed(reason) {
126
+ return new OrgKeyError(
127
+ "ORG_KEY_UNCONFIRMED",
128
+ `${SAVED} was not used, because Conto could not confirm that it belongs to this project's organization: ${reason}. Try again, run "conto login", or set CONTO_ORG_API_KEY.`
129
+ );
130
+ }
131
+ function agentIdFrom(data) {
132
+ const body = data;
133
+ if (typeof body?.agent?.id === "string") return body.agent.id;
134
+ const agent = body?.diagnostics?.issues?.find(
135
+ (issue) => issue.resource?.type === "agent" && typeof issue.resource.id === "string"
136
+ );
137
+ return agent?.resource?.id;
138
+ }
139
+ async function confirmSameOrganization(baseUrl, apiKey, saved) {
140
+ if (!sameBaseUrl(saved.baseUrl, baseUrl)) {
141
+ throw new OrgKeyError(
142
+ "ORG_KEY_BASE_URL_MISMATCH",
143
+ `${SAVED} is for ${saved.baseUrl}, and this project uses ${baseUrl}, so it was not used. Run "conto login --base-url ${baseUrl}", or set CONTO_ORG_API_KEY.`
144
+ );
145
+ }
146
+ const setup = await get(baseUrl, "/api/sdk/setup", apiKey);
147
+ const agentId = agentIdFrom(setup.data);
148
+ if (!agentId) {
149
+ throw unconfirmed(`the agent key's setup returned HTTP ${setup.status}`);
150
+ }
151
+ const agent = await get(baseUrl, `/api/agents/${encodeURIComponent(agentId)}`, saved.orgApiKey);
152
+ if (agent.status === 200 && agent.data?.id === agentId) {
153
+ return saved.orgApiKey;
154
+ }
155
+ if (agent.status === 404) {
156
+ throw new OrgKeyError(
157
+ "ORG_KEY_ORG_MISMATCH",
158
+ `${SAVED} belongs to a different organization than this project's agent key, so it was not used. Run "conto login" and sign in to this project's organization, or set CONTO_ORG_API_KEY.`
159
+ );
160
+ }
161
+ throw unconfirmed(
162
+ agent.status === 401 ? "the saved key was refused and may have expired" : `looking up the agent returned HTTP ${agent.status}`
163
+ );
164
+ }
165
+
166
+ // src/commands/spending.ts
70
167
  async function run(work, owner = false) {
71
168
  try {
72
169
  const config = loadConfig();
73
- if (!(owner ? config.orgApiKey : config.apiKey))
170
+ if (!(owner ? hasOrgApiKey(config) : config.apiKey))
74
171
  throw new Error(
75
172
  owner ? "An organization key is required for owner actions." : "Run conto login first."
76
173
  );
77
- const result = await work(createApiClient(config));
174
+ if (owner) await resolveOrgApiKey(config);
175
+ const result = await work(
176
+ createApiClient({
177
+ baseUrl: config.baseUrl,
178
+ apiKey: config.apiKey,
179
+ orgApiKey: orgApiKeySource(config)
180
+ })
181
+ );
78
182
  if (isJsonMode()) printJson(result);
79
183
  else {
80
184
  const object = result;
@@ -111,7 +215,7 @@ function registerSpendingCommands(program2) {
111
215
  ).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) => {
112
216
  try {
113
217
  const config = loadConfig();
114
- if (!config.orgApiKey)
218
+ if (!hasOrgApiKey(config))
115
219
  throw new Error("An organization key is required for accounting exports.");
116
220
  const format = o.format ?? (isJsonMode() ? "json" : "csv");
117
221
  if (!["csv", "json"].includes(format)) throw new Error("Format must be csv or json.");
@@ -120,7 +224,10 @@ function registerSpendingCommands(program2) {
120
224
  const query = new URLSearchParams({ format });
121
225
  for (const key of ["from", "to", "limit", "cursor"])
122
226
  if (o[key] !== void 0) query.set(key, o[key]);
123
- const api = createApiClient(config);
227
+ const api = createApiClient({
228
+ baseUrl: config.baseUrl,
229
+ orgApiKey: await resolveOrgApiKey(config)
230
+ });
124
231
  const data = format === "csv" ? await api.spendingDownload(`export?${query}`, true) : JSON.stringify(
125
232
  await api.spending("GET", `export?${query}`, void 0, true),
126
233
  null,
@@ -300,7 +407,7 @@ import chalk from "chalk";
300
407
  var LOGIN_HINT = 'This command needs your organization login. Run "conto login" (or set CONTO_ORG_API_KEY) and try again.';
301
408
  async function runOwnerCommand(needs, fn) {
302
409
  const config = loadConfig();
303
- if (needs === "org" && !config.orgApiKey) {
410
+ if (needs === "org" && !hasOrgApiKey(config)) {
304
411
  fail(LOGIN_HINT, "ORG_KEY_REQUIRED");
305
412
  return;
306
413
  }
@@ -314,9 +421,10 @@ async function runOwnerCommand(needs, fn) {
314
421
  const api = createOwnerClient({
315
422
  baseUrl: config.baseUrl,
316
423
  apiKey: config.apiKey,
317
- orgApiKey: config.orgApiKey
424
+ orgApiKey: orgApiKeySource(config)
318
425
  });
319
426
  try {
427
+ if (needs === "org") await resolveOrgApiKey(config);
320
428
  await fn({ api, config });
321
429
  } catch (err) {
322
430
  const error = err;
@@ -792,9 +900,9 @@ function mergeIssues(diagnostics, local) {
792
900
  const reported = new Set(server.map((issue) => issue.code));
793
901
  return [...server, ...local.filter((issue) => !reported.has(issue.code))];
794
902
  }
795
- function exitCodeFor(checks, issues, unavailable) {
903
+ function exitCodeFor(checks2, issues, unavailable) {
796
904
  if (unavailable) return DOCTOR_EXIT_CODES.UNAVAILABLE;
797
- if (checks.some((check) => check.status === "fail")) return DOCTOR_EXIT_CODES.ACTION_REQUIRED;
905
+ if (checks2.some((check) => check.status === "fail")) return DOCTOR_EXIT_CODES.ACTION_REQUIRED;
798
906
  if (issues.some((issue) => issue.severity === "error")) {
799
907
  return DOCTOR_EXIT_CODES.ACTION_REQUIRED;
800
908
  }
@@ -844,7 +952,7 @@ async function doctorCommand() {
844
952
  }
845
953
  async function runDoctor() {
846
954
  const config = loadConfig();
847
- const checks = [];
955
+ const checks2 = [];
848
956
  const local = [];
849
957
  const addLocal = (issue) => {
850
958
  if (!local.some((existing) => existing.code === issue.code)) local.push(issue);
@@ -852,7 +960,7 @@ async function runDoctor() {
852
960
  const finish = (fields = {}) => {
853
961
  const diagnostics2 = fields.diagnostics ?? null;
854
962
  const issues = mergeIssues(diagnostics2, local);
855
- const exitCode = exitCodeFor(checks, issues, fields.unavailable === true);
963
+ const exitCode = exitCodeFor(checks2, issues, fields.unavailable === true);
856
964
  let setup2 = null;
857
965
  if (fields.setup) {
858
966
  const { diagnostics: _serverDiagnostics, ...setupFields } = fields.setup;
@@ -864,7 +972,7 @@ async function runDoctor() {
864
972
  exitCode,
865
973
  baseUrl: config.baseUrl,
866
974
  diagnosticsSource: diagnostics2 ? "server" : "cli",
867
- checks: checks.map((check) => ({ ...check, name: check.name.trim() })),
975
+ checks: checks2.map((check) => ({ ...check, name: check.name.trim() })),
868
976
  issues,
869
977
  diagnostics: diagnostics2,
870
978
  setup: setup2
@@ -873,19 +981,19 @@ async function runDoctor() {
873
981
  let api = null;
874
982
  try {
875
983
  api = createApiClient({ baseUrl: config.baseUrl, apiKey: config.apiKey });
876
- checks.push({ name: "Base URL", status: "ok", detail: config.baseUrl });
984
+ checks2.push({ name: "Base URL", status: "ok", detail: config.baseUrl });
877
985
  } catch (error) {
878
986
  const message = errorMessage(error, "Invalid base URL");
879
- checks.push({ name: "Base URL", status: "fail", detail: `${config.baseUrl}: ${message}` });
987
+ checks2.push({ name: "Base URL", status: "fail", detail: `${config.baseUrl}: ${message}` });
880
988
  addLocal(baseUrlInvalidIssue(message));
881
989
  }
882
990
  if (!config.apiKey) {
883
991
  const message = missingSdkKeyMessage(config);
884
- checks.push({ name: "SDK key", status: "fail", detail: message });
992
+ checks2.push({ name: "SDK key", status: "fail", detail: message });
885
993
  addLocal(sdkKeyNotConfiguredIssue(message));
886
994
  return finish();
887
995
  }
888
- checks.push({
996
+ checks2.push({
889
997
  name: "SDK key",
890
998
  status: "ok",
891
999
  detail: `${maskSecret(config.apiKey)} (from ${process.env.CONTO_API_KEY ? "environment" : ".env.local or ~/.conto/config.json"})`
@@ -899,7 +1007,7 @@ async function runDoctor() {
899
1007
  const failure = error;
900
1008
  const status = typeof failure.status === "number" ? failure.status : 0;
901
1009
  const message = errorMessage(error, "Request failed");
902
- checks.push({
1010
+ checks2.push({
903
1011
  name: "Authentication",
904
1012
  status: "fail",
905
1013
  detail: `${config.baseUrl}/api/sdk/setup: ${message}`
@@ -923,13 +1031,13 @@ async function runDoctor() {
923
1031
  }
924
1032
  return finish({ diagnostics: diagnostics2 });
925
1033
  }
926
- checks.push({
1034
+ checks2.push({
927
1035
  name: "Authentication",
928
1036
  status: "ok",
929
1037
  detail: `Authenticated as agent "${setup.agent.name}"`
930
1038
  });
931
1039
  const diagnostics = readServerDiagnostics(setup.diagnostics);
932
- checks.push(
1040
+ checks2.push(
933
1041
  ...diagnostics ? diagnosticChecks(setup, diagnostics) : legacyChecks(setup, config)
934
1042
  );
935
1043
  return finish({ diagnostics, setup });
@@ -976,12 +1084,12 @@ function cardCheck(name, card) {
976
1084
  };
977
1085
  }
978
1086
  function diagnosticChecks(setup, diagnostics) {
979
- const checks = [];
1087
+ const checks2 = [];
980
1088
  const environment = diagnostics.environment;
981
1089
  if (environment) {
982
1090
  const expiry = environment.kind === "anonymous_sandbox" && environment.sandboxExpiresAt ? `, expires ${environment.sandboxExpiresAt}` : "";
983
1091
  const agentEnvironment = environment.kind === "account" ? `, agent environment ${environment.agentEnvironment}` : "";
984
- checks.push({
1092
+ checks2.push({
985
1093
  name: "Environment",
986
1094
  status: "ok",
987
1095
  detail: `${ENVIRONMENT_DETAIL[environment.kind] ?? environment.kind}${agentEnvironment}${expiry}`
@@ -991,7 +1099,7 @@ function diagnosticChecks(setup, diagnostics) {
991
1099
  (issue) => issue.resource.type === "agent" && issue.code.startsWith("AGENT_")
992
1100
  );
993
1101
  const agentActive = setup.agent.status === "active" && !agentIssue;
994
- checks.push({
1102
+ checks2.push({
995
1103
  name: "Agent status",
996
1104
  status: agentActive ? "ok" : "fail",
997
1105
  detail: agentIssue?.message ?? (agentActive ? "Active" : setup.agent.status)
@@ -1007,7 +1115,7 @@ function diagnosticChecks(setup, diagnostics) {
1007
1115
  ];
1008
1116
  for (const scope of scopeNames) {
1009
1117
  const missing = scopeIssues.find((issue) => issue.requiredScope === scope);
1010
- checks.push({
1118
+ checks2.push({
1011
1119
  name: `Scope ${scope}`,
1012
1120
  status: scopes.includes(scope) ? "ok" : missing?.severity === "error" ? "fail" : "warn",
1013
1121
  detail: scopes.includes(scope) ? "Granted" : missing?.message ?? "Missing. None of this agent's wallets needs it."
@@ -1016,7 +1124,7 @@ function diagnosticChecks(setup, diagnostics) {
1016
1124
  const wallets = setup.wallets || [];
1017
1125
  if (wallets.length === 0) {
1018
1126
  const noWallet = diagnostics.issues.find((issue) => issue.code === "NO_WALLET");
1019
- checks.push({
1127
+ checks2.push({
1020
1128
  name: "Wallet",
1021
1129
  status: noWallet?.severity === "error" ? "fail" : "warn",
1022
1130
  detail: noWallet?.message ?? "No wallet is linked to this agent."
@@ -1031,7 +1139,7 @@ function diagnosticChecks(setup, diagnostics) {
1031
1139
  (issue) => issue.severity === "error" && WALLET_ACCESS_CODES.has(issue.code)
1032
1140
  );
1033
1141
  const chainLabel = `${wallet.chainName} (${wallet.chainId})${wallet.isTestnet ? " testnet" : ""}`;
1034
- checks.push({
1142
+ checks2.push({
1035
1143
  name: `Wallet ${shortAddress(wallet.address)}`,
1036
1144
  status: blocking ? "fail" : "ok",
1037
1145
  detail: `${chainLabel}, ${wallet.custodyMode} custody, status ${wallet.status}${blocking ? `. ${blocking.message}` : ""}`
@@ -1040,18 +1148,18 @@ function diagnosticChecks(setup, diagnostics) {
1040
1148
  const executionIssue = walletIssues.find(
1041
1149
  (issue) => issue.severity === "error" && issue !== blocking
1042
1150
  );
1043
- checks.push({
1151
+ checks2.push({
1044
1152
  name: " Execution",
1045
1153
  status: capabilityStatus(entry.canExecute),
1046
1154
  detail: `${EXECUTION_DETAIL[entry.executionMode] ?? entry.executionMode}${entry.canExecute === "no" && executionIssue ? `. ${executionIssue.message}` : ""}`
1047
1155
  });
1048
- checks.push({
1156
+ checks2.push({
1049
1157
  name: " Balance",
1050
1158
  status: entry.funding === "unfunded" ? "fail" : "ok",
1051
1159
  detail: entry.funding === "not_required" ? "Simulated sandbox: no onchain funding required" : entry.funding === "funded" ? printAmount(wallet.balance, wallet.currency) : entry.funding === "unfunded" ? `0 ${wallet.currency}. Fund this wallet before paying.` : "Not checked by Conto. The wallet you sign with must hold the funds."
1052
1160
  });
1053
1161
  if (wallet.limits?.daily != null) {
1054
- checks.push({
1162
+ checks2.push({
1055
1163
  name: " Daily limit",
1056
1164
  status: "ok",
1057
1165
  detail: `${printAmount(wallet.spent?.today ?? 0, "USD")} spent of ${printAmount(wallet.limits.daily, "USD")}`
@@ -1059,22 +1167,22 @@ function diagnosticChecks(setup, diagnostics) {
1059
1167
  }
1060
1168
  }
1061
1169
  if (diagnostics.connectedCards) {
1062
- checks.push(cardCheck("Test cards", diagnostics.connectedCards.test));
1063
- checks.push(cardCheck("Live cards", diagnostics.connectedCards.live));
1170
+ checks2.push(cardCheck("Test cards", diagnostics.connectedCards.test));
1171
+ checks2.push(cardCheck("Live cards", diagnostics.connectedCards.live));
1064
1172
  }
1065
1173
  const { canRequest, canExecute } = diagnostics.status;
1066
1174
  const sandbox = environment ? environment.kind !== "account" : false;
1067
- checks.push({
1175
+ checks2.push({
1068
1176
  name: "Payment readiness",
1069
1177
  status: canRequest === "yes" ? capabilityStatus(canExecute) : "fail",
1070
1178
  detail: canRequest !== "yes" ? "No wallet or card can take a payment request with this setup. See the next steps below." : canExecute === "yes" ? sandbox ? "Sandbox can request and record test payments" : "Can request and execute payments" : canExecute === "unknown" ? "Can request payments. Sending needs your own signer, which Conto cannot check." : "Requests work. Execution is blocked. See the next steps below."
1071
1179
  });
1072
- return checks;
1180
+ return checks2;
1073
1181
  }
1074
1182
  function legacyChecks(setup, config) {
1075
- const checks = [];
1183
+ const checks2 = [];
1076
1184
  const isSandbox = config.sandboxMode === "test";
1077
- checks.push({
1185
+ checks2.push({
1078
1186
  name: "Agent status",
1079
1187
  status: setup.agent.status === "active" ? "ok" : "fail",
1080
1188
  detail: setup.agent.status === "active" ? "Active" : `${setup.agent.status}. Activate the agent in the dashboard.`
@@ -1082,19 +1190,19 @@ function legacyChecks(setup, config) {
1082
1190
  const scopes = setup.scopes || [];
1083
1191
  const canRequest = scopes.includes("payments:request");
1084
1192
  const canExecute = scopes.includes("payments:execute");
1085
- checks.push({
1193
+ checks2.push({
1086
1194
  name: "Scope payments:request",
1087
1195
  status: canRequest ? "ok" : "fail",
1088
1196
  detail: canRequest ? "Granted" : "Missing. This key cannot request payments."
1089
1197
  });
1090
- checks.push({
1198
+ checks2.push({
1091
1199
  name: "Scope payments:execute",
1092
1200
  status: canExecute ? "ok" : "warn",
1093
1201
  detail: canExecute ? "Granted" : 'Missing. "conto pay" can request but not execute. Create a new standard SDK key.'
1094
1202
  });
1095
1203
  const wallets = setup.wallets || [];
1096
1204
  if (wallets.length === 0) {
1097
- checks.push({
1205
+ checks2.push({
1098
1206
  name: "Wallet",
1099
1207
  status: "fail",
1100
1208
  detail: 'No wallet linked to this agent. Run "npx @conto_finance/create-conto-agent" or link one in the dashboard.'
@@ -1102,24 +1210,24 @@ function legacyChecks(setup, config) {
1102
1210
  }
1103
1211
  for (const w of wallets) {
1104
1212
  const chainLabel = `${w.chainName} (${w.chainId})${w.isTestnet ? " testnet" : ""}`;
1105
- checks.push({
1213
+ checks2.push({
1106
1214
  name: `Wallet ${shortAddress(w.address)}`,
1107
1215
  status: w.status === "active" ? "ok" : "warn",
1108
1216
  detail: `${chainLabel}, ${w.custodyMode} custody, status ${w.status}`
1109
1217
  });
1110
1218
  const paymentMode = isSandbox ? "test" : w.custodyMode === "MANAGED" ? "managed" : "external";
1111
- checks.push({
1219
+ checks2.push({
1112
1220
  name: " Execution",
1113
1221
  status: paymentMode === "managed" || paymentMode === "test" ? "ok" : "warn",
1114
1222
  detail: paymentMode === "managed" ? "Managed by Conto (real transfers)" : paymentMode === "test" ? `Sandbox test mode${config.sandboxExpiresAt ? ` until ${config.sandboxExpiresAt}` : ""}; no onchain transfer required` : "External: the agent signs transactions and confirms them through the API"
1115
1223
  });
1116
- checks.push({
1224
+ checks2.push({
1117
1225
  name: " Balance",
1118
1226
  status: w.balance > 0 || isSandbox ? "ok" : "warn",
1119
1227
  detail: isSandbox ? "Simulated sandbox: no onchain funding required" : w.balance > 0 ? `${printAmount(w.balance, w.currency)}` : `0 ${w.currency}. Fund this wallet before paying${w.isTestnet ? " (testnet faucet available via init)" : ""}.`
1120
1228
  });
1121
1229
  if (w.limits?.daily != null) {
1122
- checks.push({
1230
+ checks2.push({
1123
1231
  name: " Daily limit",
1124
1232
  status: "ok",
1125
1233
  detail: `${printAmount(w.spent?.today ?? 0, "USD")} spent of ${printAmount(w.limits.daily, "USD")}`
@@ -1130,12 +1238,12 @@ function legacyChecks(setup, config) {
1130
1238
  (wallet) => wallet.status === "active" && wallet.custodyMode === "MANAGED" && wallet.balance > 0
1131
1239
  );
1132
1240
  const readyForManagedExecution = setup.agent.status === "active" && canRequest && canExecute && (hasManagedWallet || isSandbox && wallets.some((wallet) => wallet.status === "active"));
1133
- checks.push({
1241
+ checks2.push({
1134
1242
  name: "Payment readiness",
1135
1243
  status: readyForManagedExecution ? "ok" : canRequest ? "warn" : "fail",
1136
1244
  detail: readyForManagedExecution ? isSandbox ? "Sandbox can request and record test payments" : "Key and managed wallet can request and execute payments" : canRequest ? "Requests work; execution is limited (see checks above)" : "This key cannot request payments"
1137
1245
  });
1138
- return checks;
1246
+ return checks2;
1139
1247
  }
1140
1248
  function shortAddress(address) {
1141
1249
  if (!address || address.length <= 14) return address;
@@ -1255,7 +1363,7 @@ re-run with the printed key: --idempotency-key <key> returns the same request.
1255
1363
 
1256
1364
  Exit codes:
1257
1365
  0 sent, or already handled
1258
- 1 request failed
1366
+ 1 request failed, or denied by policy
1259
1367
  3 an approver rejected the payment
1260
1368
  4 not sent yet: waiting for approval (--no-wait, or the wait timed out),
1261
1369
  or approved and waiting for conto pay execute
@@ -1644,6 +1752,7 @@ async function payCommand(address, amountStr, options) {
1644
1752
  if (request.status === "DENIED") {
1645
1753
  if (isJsonMode()) {
1646
1754
  printJson({ ...request, idempotencyKey });
1755
+ process.exitCode = 1;
1647
1756
  return;
1648
1757
  }
1649
1758
  printError("Payment denied by policy");
@@ -1780,7 +1889,7 @@ async function walletsCommand(subcommand, options = {}) {
1780
1889
  const api = createApiClient({
1781
1890
  baseUrl: config.baseUrl,
1782
1891
  apiKey: config.apiKey,
1783
- orgApiKey: config.orgApiKey
1892
+ orgApiKey: orgApiKeySource(config)
1784
1893
  });
1785
1894
  try {
1786
1895
  await fetchChains(config.baseUrl);
@@ -1813,12 +1922,13 @@ async function walletsCommand(subcommand, options = {}) {
1813
1922
  return;
1814
1923
  }
1815
1924
  if (options.faucet) {
1816
- if (!config.orgApiKey) {
1925
+ if (!hasOrgApiKey(config)) {
1817
1926
  printError(
1818
1927
  'Faucet funding requires an organization key. Run "conto login" or create the project with "npx @conto_finance/create-conto-agent".'
1819
1928
  );
1820
1929
  process.exit(1);
1821
1930
  }
1931
+ await resolveOrgApiKey(config);
1822
1932
  const results = [];
1823
1933
  for (const w of wallets) {
1824
1934
  const chainEntry = getChain(w.chainId);
@@ -2166,6 +2276,23 @@ var ACTIONS = [
2166
2276
  hint: "Payment needs human approval if rule triggers"
2167
2277
  }
2168
2278
  ];
2279
+ function actionChoicesFor(ruleType) {
2280
+ return isBlocklistRuleType(ruleType) ? { options: ACTIONS.filter((action) => action.value !== "ALLOW"), initialValue: "DENY" } : { options: ACTIONS };
2281
+ }
2282
+ var ORG_KEY_SUBCOMMANDS = /* @__PURE__ */ new Set([
2283
+ "all",
2284
+ "create",
2285
+ "update",
2286
+ "delete",
2287
+ "assign",
2288
+ "unassign",
2289
+ "add-rule",
2290
+ "remove-rule",
2291
+ "versions",
2292
+ "rollback",
2293
+ "simulate"
2294
+ ]);
2295
+ var PROMPTING_SUBCOMMANDS = /* @__PURE__ */ new Set(["create", "update", "delete", "add-rule"]);
2169
2296
  async function policiesCommand(subcommand = "list", idOrAmount, extra, reviewOptions = {}) {
2170
2297
  const config = loadConfig();
2171
2298
  if (!config.apiKey) {
@@ -2177,9 +2304,15 @@ async function policiesCommand(subcommand = "list", idOrAmount, extra, reviewOpt
2177
2304
  const api = createOwnerClient({
2178
2305
  baseUrl: config.baseUrl,
2179
2306
  apiKey: config.apiKey,
2180
- orgApiKey: config.orgApiKey
2307
+ orgApiKey: orgApiKeySource(config)
2181
2308
  });
2182
2309
  try {
2310
+ if (isJsonMode() && PROMPTING_SUBCOMMANDS.has(subcommand)) {
2311
+ throw new Error(
2312
+ `conto policies ${subcommand} prompts for input, so it does not run with --json. Run it in a terminal without --json.`
2313
+ );
2314
+ }
2315
+ if (ORG_KEY_SUBCOMMANDS.has(subcommand)) await resolveOrgApiKey(config);
2183
2316
  switch (subcommand) {
2184
2317
  case "list":
2185
2318
  return await listAgentPolicies(api);
@@ -2655,7 +2788,7 @@ async function promptForRule(policyType) {
2655
2788
  }
2656
2789
  const action = await p.select({
2657
2790
  message: "Action when rule triggers",
2658
- options: ACTIONS
2791
+ ...actionChoicesFor(ruleType)
2659
2792
  });
2660
2793
  if (p.isCancel(action)) return null;
2661
2794
  return {
@@ -2900,25 +3033,25 @@ async function alertsCommand(options = {}) {
2900
3033
  try {
2901
3034
  const activeOnly = options.active || options.unread;
2902
3035
  const { alerts } = await api.getAlerts({
2903
- status: activeOnly ? "ACTIVE" : void 0
3036
+ status: activeOnly ? "open" : void 0
2904
3037
  });
2905
3038
  if (isJsonMode()) {
2906
3039
  printJson(alerts);
2907
3040
  return;
2908
3041
  }
2909
3042
  if (alerts.length === 0) {
2910
- console.log("\n No alerts." + (activeOnly ? " (showing active only)" : ""));
3043
+ console.log(activeOnly ? "\n No open alerts." : "\n No alerts.");
2911
3044
  return;
2912
3045
  }
2913
3046
  printHeader(`Alerts (${alerts.length})`);
2914
3047
  printTable(
2915
- ["Date", "Severity", "Type", "Message", "Status"],
3048
+ ["ID", "Date", "Severity", "Status", "Title"],
2916
3049
  alerts.map((a) => [
3050
+ a.id,
2917
3051
  new Date(a.createdAt).toLocaleDateString(),
2918
- severityColor(a.severity),
2919
- a.alertType,
2920
- a.message.length > 50 ? a.message.slice(0, 50) + "..." : a.message,
2921
- a.status
3052
+ severityColor(a.severity.label),
3053
+ a.status.label,
3054
+ a.title.length > 50 ? a.title.slice(0, 50) + "..." : a.title
2922
3055
  ])
2923
3056
  );
2924
3057
  console.log("");
@@ -2932,18 +3065,14 @@ async function alertsCommand(options = {}) {
2932
3065
  process.exit(1);
2933
3066
  }
2934
3067
  }
2935
- function severityColor(severity) {
2936
- switch (severity.toUpperCase()) {
2937
- case "CRITICAL":
2938
- return chalk8.red.bold(severity);
2939
- case "HIGH":
2940
- return chalk8.red(severity);
2941
- case "MEDIUM":
2942
- return chalk8.yellow(severity);
2943
- case "LOW":
2944
- return chalk8.dim(severity);
3068
+ function severityColor(label) {
3069
+ switch (label) {
3070
+ case "High":
3071
+ return chalk8.red(label);
3072
+ case "Medium":
3073
+ return chalk8.yellow(label);
2945
3074
  default:
2946
- return severity;
3075
+ return chalk8.dim(label);
2947
3076
  }
2948
3077
  }
2949
3078
  async function alertUpdateCommand(alertId, action) {
@@ -3020,18 +3149,28 @@ async function agentsFreezeCommand(agentId, options) {
3020
3149
  });
3021
3150
  }
3022
3151
  async function agentsUnfreezeCommand(agentId, options) {
3152
+ if (options.wallets && options.keepWallets) {
3153
+ if (isJsonMode()) {
3154
+ printJson({ ok: false, error: "Pick one of --wallets and --keep-wallets." });
3155
+ } else {
3156
+ printError("Pick one of --wallets and --keep-wallets.");
3157
+ }
3158
+ process.exitCode = 1;
3159
+ return;
3160
+ }
3161
+ const restoreWallets = options.keepWallets ? false : options.wallets ? true : void 0;
3023
3162
  await runOwnerCommand("org", async ({ api }) => {
3024
3163
  const result = await directOrReview(
3025
3164
  api,
3026
3165
  () => api.unfreezeAgent(agentId, {
3027
3166
  ...options.reason ? { reason: options.reason } : {},
3028
- unfreezeWallets: options.wallets === true
3167
+ ...restoreWallets === void 0 ? {} : { unfreezeWallets: restoreWallets }
3029
3168
  }),
3030
3169
  async () => ({
3031
3170
  action: "activate_agent",
3032
3171
  input: {
3033
3172
  agent_id: agentId,
3034
- restore_wallets: options.wallets === true,
3173
+ ...restoreWallets === void 0 ? {} : { restore_wallets: restoreWallets },
3035
3174
  ...options.reason ? { reason: options.reason } : {}
3036
3175
  }
3037
3176
  }),
@@ -3387,6 +3526,10 @@ function isSafeConfigPath(parts) {
3387
3526
  (part) => part.length > 0 && !FORBIDDEN_CONFIG_PATH_SEGMENTS.has(part.toLowerCase())
3388
3527
  );
3389
3528
  }
3529
+ var BASE_URL_NEEDS_LOGIN = 'conto config does not change server.baseUrl, because the saved keys would be sent to the new server. Run "conto login --base-url <url>" instead. It signs in to that server and removes the agent key saved for the old one.';
3530
+ function isServerBaseUrlPath(parts) {
3531
+ return parts.length >= 2 && parts[0].toLowerCase() === "server" && parts[1].toLowerCase() === "baseurl";
3532
+ }
3390
3533
  async function configCommand(key, value) {
3391
3534
  if (key && value) {
3392
3535
  const global = loadGlobalConfig();
@@ -3398,6 +3541,15 @@ async function configCommand(key, value) {
3398
3541
  process.exitCode = 1;
3399
3542
  return;
3400
3543
  }
3544
+ if (isServerBaseUrlPath(parts)) {
3545
+ if (isJsonMode()) {
3546
+ printJson({ ok: false, error: BASE_URL_NEEDS_LOGIN, code: "BASE_URL_NEEDS_LOGIN" });
3547
+ } else {
3548
+ printError(BASE_URL_NEEDS_LOGIN);
3549
+ }
3550
+ process.exitCode = 1;
3551
+ return;
3552
+ }
3401
3553
  let target = global;
3402
3554
  for (let i = 0; i < parts.length - 1; i++) {
3403
3555
  if (!target[parts[i]] || typeof target[parts[i]] !== "object") {
@@ -3457,7 +3609,8 @@ async function loginCommand(options = {}) {
3457
3609
  try {
3458
3610
  const { orgApiKey, organizationName, expiresAt } = await browserAuth(
3459
3611
  baseUrl,
3460
- (authUrl) => printInfo(`If the browser does not open, visit: ${authUrl}`)
3612
+ (authUrl) => printInfo(`If the browser does not open, visit: ${authUrl}`),
3613
+ (code) => printInfo(`Connect only if the browser shows this code: ${code}`)
3461
3614
  );
3462
3615
  const config = loadGlobalConfig();
3463
3616
  const previousBaseUrl = config.server?.baseUrl || DEFAULT_BASE_URL;
@@ -3527,6 +3680,7 @@ async function mcpCommand() {
3527
3680
 
3528
3681
  // src/commands/webhooks.ts
3529
3682
  import { createHmac, randomUUID as randomUUID2 } from "crypto";
3683
+ var sign = (secret, input) => createHmac("sha256", secret).update(input).digest("hex");
3530
3684
  async function testWebhook(url) {
3531
3685
  const started = Date.now();
3532
3686
  try {
@@ -3542,6 +3696,7 @@ async function testWebhook(url) {
3542
3696
  const event = "payment.confirmed";
3543
3697
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
3544
3698
  const paymentId = `test_${randomUUID2()}`;
3699
+ const deliveryId = randomUUID2();
3545
3700
  const body = JSON.stringify({
3546
3701
  event,
3547
3702
  timestamp,
@@ -3553,8 +3708,10 @@ async function testWebhook(url) {
3553
3708
  amount: 0.01,
3554
3709
  currency: "pathUSD",
3555
3710
  status: "CONFIRMED",
3711
+ settlementMode: "test",
3556
3712
  test: true
3557
- }
3713
+ },
3714
+ deliveryId
3558
3715
  });
3559
3716
  const response = await fetch(target, {
3560
3717
  method: "POST",
@@ -3564,8 +3721,10 @@ async function testWebhook(url) {
3564
3721
  "Content-Type": "application/json",
3565
3722
  "X-Conto-Event": event,
3566
3723
  "X-Conto-Timestamp": timestamp,
3724
+ "X-Conto-Delivery-Id": deliveryId,
3567
3725
  "X-Conto-Delivery-Attempt": "1",
3568
- "X-Conto-Signature": createHmac("sha256", secret).update(body).digest("hex")
3726
+ "X-Conto-Signature": sign(secret, body),
3727
+ "X-Conto-Signature-V2": sign(secret, `${timestamp}.${body}`)
3569
3728
  },
3570
3729
  body
3571
3730
  });
@@ -3576,6 +3735,7 @@ async function testWebhook(url) {
3576
3735
  elapsedMs: Date.now() - started,
3577
3736
  event,
3578
3737
  paymentId,
3738
+ deliveryId,
3579
3739
  test: true
3580
3740
  };
3581
3741
  if (isJsonMode()) printJson(result);
@@ -3607,7 +3767,7 @@ var HANDOFF_PATH = "/api/agents/sandbox/handoff";
3607
3767
  var DEFAULT_POLL_INTERVAL_SECONDS = 5;
3608
3768
  var MIN_POLL_INTERVAL_SECONDS = 1;
3609
3769
  var MAX_POLL_INTERVAL_SECONDS = 60;
3610
- var REQUEST_TIMEOUT_MS = 15e3;
3770
+ var REQUEST_TIMEOUT_MS2 = 15e3;
3611
3771
  var SANDBOX_ORG_KEY_PATTERN = /^conto_[a-f0-9]{64}$/;
3612
3772
  var HANDOFF_TOKEN_PATTERN = /^conto_claim_[a-f0-9]{64}$/;
3613
3773
  function isHandoffToken(value) {
@@ -3711,7 +3871,7 @@ async function initiateHandoff(input) {
3711
3871
  url: apiUrl(input.baseUrl, HANDOFF_PATH),
3712
3872
  method: "POST",
3713
3873
  bearer: input.sandboxKey,
3714
- timeoutMs: REQUEST_TIMEOUT_MS,
3874
+ timeoutMs: REQUEST_TIMEOUT_MS2,
3715
3875
  signal: input.signal
3716
3876
  });
3717
3877
  } catch (error) {
@@ -3762,7 +3922,7 @@ async function inspectHandoff(input) {
3762
3922
  url: apiUrl(input.baseUrl, input.statusPath),
3763
3923
  method: "GET",
3764
3924
  bearer: input.token,
3765
- timeoutMs: REQUEST_TIMEOUT_MS,
3925
+ timeoutMs: REQUEST_TIMEOUT_MS2,
3766
3926
  signal: input.signal
3767
3927
  });
3768
3928
  } catch (error) {
@@ -4652,7 +4812,7 @@ withReview(
4652
4812
  ).action(agentsResumeCommand);
4653
4813
  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);
4654
4814
  withReview(
4655
- 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")
4815
+ agentsGroup.command("unfreeze <agentId>").description("Lift a freeze (owner review)").option("--reason <text>", "Why, for the audit log").option("--wallets", "Unfreeze the wallets frozen with it, also for an older freeze record").option("--keep-wallets", "Leave every wallet frozen")
4656
4816
  ).action(agentsUnfreezeCommand);
4657
4817
  withReview(
4658
4818
  agentsGroup.command("delete <agentId>").description("Delete an agent (owner review)").option("--yes", "Skip the confirmation prompt")
@@ -4721,13 +4881,13 @@ withReview(
4721
4881
  (subcommand, id2, extra, opts) => policiesCommand(subcommand || "list", id2, extra, opts)
4722
4882
  );
4723
4883
  program.command("limits").description("Show spending limits and remaining budget").action(limitsCommand);
4724
- 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);
4884
+ var alertsGroup = program.command("alerts").description("List alerts, or acknowledge or resolve one").option("--active", "Show only open alerts").option("--unread", "Alias for --active").action(alertsCommand);
4725
4885
  alertsGroup.command("ack <alertId>").description("Acknowledge an alert").action((alertId) => alertUpdateCommand(alertId, "acknowledge"));
4726
4886
  alertsGroup.command("resolve <alertId>").description("Resolve an alert").action((alertId) => alertUpdateCommand(alertId, "resolve"));
4727
4887
  program.command("config [key] [value]").description("Show or update configuration").action(configCommand);
4728
4888
  program.command("login").description("Authenticate with Conto").option("--base-url <url>", "Conto instance URL").action(loginCommand);
4729
4889
  program.command("logout").description("Clear stored credentials").action(async () => {
4730
- const { clearGlobalConfig } = await import("./config-MACPIPYV.js");
4890
+ const { clearGlobalConfig } = await import("./config-2C6Q4NEJ.js");
4731
4891
  clearGlobalConfig();
4732
4892
  const { printSuccess: printSuccess2 } = await import("./output-GD3QK4HS.js");
4733
4893
  printSuccess2("Logged out. Credentials cleared.");