@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.
@@ -4,6 +4,8 @@ import {
4
4
  printError,
5
5
  printInfo,
6
6
  printJson,
7
+ printKeyValue,
8
+ printPending,
7
9
  printSuccess,
8
10
  printWarning
9
11
  } from "./chunk-K4LBO234.js";
@@ -20,7 +22,7 @@ import {
20
22
  // package.json
21
23
  var package_default = {
22
24
  name: "@conto_finance/create-conto-agent",
23
- version: "0.4.6",
25
+ version: "0.5.0",
24
26
  description: "Set up an AI agent with Conto spending controls",
25
27
  bin: {
26
28
  "create-conto-agent": "bin/create-conto-agent.js",
@@ -71,28 +73,175 @@ var package_default = {
71
73
  email: "support@conto.finance"
72
74
  },
73
75
  dependencies: {
74
- "@clack/prompts": "^0.9.1",
76
+ "@clack/prompts": "^1.8.1",
75
77
  chalk: "^5.4.1",
76
78
  "cli-table3": "^0.6.5",
77
79
  commander: "^13.1.0",
78
- open: "^10.1.0"
80
+ open: "^11.0.4"
79
81
  },
80
82
  overrides: {
81
83
  esbuild: "0.28.1"
82
84
  },
83
85
  devDependencies: {
84
- "@types/node": "22.19.18",
85
- tsup: "^8.5.1",
86
- typescript: "^5.9.3"
86
+ "@types/node": "26.6.5",
87
+ tsup: "^9.0.0",
88
+ typescript: "^6.0.3"
87
89
  }
88
90
  };
89
91
 
90
92
  // src/lib/package-version.ts
91
93
  var CLI_PACKAGE_VERSION = package_default.version || "0.0.0";
92
94
 
95
+ // src/lib/owner-review.ts
96
+ import chalk from "chalk";
97
+ var REVIEW_EXIT_CODES_HELP = `
98
+ Changes that loosen controls go to owner review:
99
+ the command prints a review link, opens it when it can, and waits.
100
+
101
+ Exit codes:
102
+ 0 applied, or nothing needed to change
103
+ 1 request failed, or the change could not be applied
104
+ 3 the reviewer declined the change
105
+ 4 still waiting for review (--no-wait, or the wait timed out)
106
+ 5 the review expired
107
+ `;
108
+ var EXIT_DECLINED = 3;
109
+ var EXIT_PENDING = 4;
110
+ var EXIT_EXPIRED = 5;
111
+ var POLL_INTERVAL_MS = Number(process.env.CONTO_REVIEW_POLL_MS) || 3e3;
112
+ var DEFAULT_WAIT_SECONDS = 300;
113
+ var MAX_WAIT_SECONDS = 900;
114
+ var TIGHTEN_ONLY_CODES = /* @__PURE__ */ new Set([
115
+ "TIGHTEN_ONLY_ROUTE",
116
+ "AGENT_KEY_TIGHTEN_ONLY",
117
+ "WALLET_DELEGATION_REQUIRED",
118
+ "COUNTERPARTY_CHANGE_NOT_ALLOWED"
119
+ ]);
120
+ function isTightenOnlyRefusal(err) {
121
+ const error = err;
122
+ return error?.status === 403 && TIGHTEN_ONLY_CODES.has(error.code ?? "");
123
+ }
124
+ function interactive() {
125
+ return Boolean(process.stdout.isTTY) && !isJsonMode();
126
+ }
127
+ function waitSeconds(wait) {
128
+ if (wait === false) return 0;
129
+ if (typeof wait === "string" && wait.trim() !== "") {
130
+ const parsed = Number(wait);
131
+ if (!Number.isFinite(parsed) || parsed < 0) {
132
+ throw new Error("--wait takes a number of seconds");
133
+ }
134
+ return Math.min(Math.round(parsed), MAX_WAIT_SECONDS);
135
+ }
136
+ if (wait === true) return DEFAULT_WAIT_SECONDS;
137
+ return interactive() ? DEFAULT_WAIT_SECONDS : 0;
138
+ }
139
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
140
+ function exitCodeFor(status) {
141
+ switch (status) {
142
+ case "APPLIED":
143
+ case "NO_CHANGE":
144
+ return 0;
145
+ case "REJECTED":
146
+ return EXIT_DECLINED;
147
+ case "EXPIRED":
148
+ return EXIT_EXPIRED;
149
+ case "PENDING_REVIEW":
150
+ case "READY_TO_CLAIM":
151
+ case "APPLYING":
152
+ return EXIT_PENDING;
153
+ default:
154
+ return 1;
155
+ }
156
+ }
157
+ async function openReviewPage(url) {
158
+ try {
159
+ const open2 = (await import("open")).default;
160
+ await open2(url);
161
+ } catch {
162
+ }
163
+ }
164
+ async function followChange(api, change, options = {}) {
165
+ let current = change;
166
+ const seconds = waitSeconds(options.wait);
167
+ if (current.status === "PENDING_REVIEW" && current.reviewUrl && !isJsonMode()) {
168
+ printPending("This change needs an owner or admin to confirm it.");
169
+ printKeyValue("Review", current.reviewUrl);
170
+ if (options.open ?? interactive()) await openReviewPage(current.reviewUrl);
171
+ }
172
+ const deadline = Date.now() + seconds * 1e3;
173
+ while ((current.status === "PENDING_REVIEW" || current.status === "APPLYING") && Date.now() < deadline) {
174
+ await sleep(POLL_INTERVAL_MS);
175
+ current = await api.getOwnerAction(current.changeId);
176
+ }
177
+ if (current.status === "READY_TO_CLAIM") {
178
+ const claimed = await api.claimOwnerAction(current.changeId);
179
+ return {
180
+ change: claimed.change,
181
+ sdkKey: claimed.sdkKey,
182
+ exitCode: exitCodeFor(claimed.change.status)
183
+ };
184
+ }
185
+ return { change: current, exitCode: exitCodeFor(current.status) };
186
+ }
187
+ async function proposeForReview(api, action, input, options = {}) {
188
+ const proposed = await api.proposeOwnerAction(action, input, CLI_PACKAGE_VERSION);
189
+ if (!proposed.proposed) {
190
+ const reason = proposed.result;
191
+ const error = new Error(reason.message || "The change could not be proposed.");
192
+ error.code = reason.status === "no_op" ? "NO_CHANGE" : "NOT_PROPOSED";
193
+ error.recovery = reason.recovery;
194
+ throw error;
195
+ }
196
+ return followChange(api, proposed.change, options);
197
+ }
198
+ async function directOrReview(api, direct, proposal, options = {}) {
199
+ try {
200
+ return { direct: await direct() };
201
+ } catch (err) {
202
+ if (!isTightenOnlyRefusal(err)) throw err;
203
+ const { action, input } = await proposal();
204
+ return { review: await proposeForReview(api, action, input, options) };
205
+ }
206
+ }
207
+ function reportReview(outcome, appliedMessage) {
208
+ const { change, sdkKey, exitCode } = outcome;
209
+ process.exitCode = exitCode;
210
+ if (isJsonMode()) {
211
+ printJson({
212
+ changeId: change.changeId,
213
+ status: change.status,
214
+ nextAction: change.nextAction,
215
+ message: change.message,
216
+ ...change.reviewUrl ? { reviewUrl: change.reviewUrl } : {},
217
+ ...change.result ? { result: change.result } : {},
218
+ ...sdkKey ? { sdkKey } : {}
219
+ });
220
+ return;
221
+ }
222
+ if (change.status === "APPLIED") {
223
+ printSuccess(appliedMessage);
224
+ } else if (change.status === "NO_CHANGE") {
225
+ printInfo(change.result?.message ?? change.message);
226
+ } else if (change.status === "PENDING_REVIEW") {
227
+ printPending("Still waiting for review. Nothing has changed yet.");
228
+ printInfo(`Check later with: conto changes status ${change.changeId}`);
229
+ } else if (change.status === "REJECTED") {
230
+ printWarning(change.message);
231
+ } else {
232
+ printError(change.result?.message ?? change.message);
233
+ if (change.result?.recovery) console.log(chalk.dim(` ${change.result.recovery}`));
234
+ }
235
+ if (sdkKey) {
236
+ console.log("");
237
+ printKeyValue("SDK key", sdkKey.key);
238
+ printWarning("This key is shown once. Store it now, for example as CONTO_API_KEY in .env.");
239
+ }
240
+ }
241
+
93
242
  // src/commands/init.ts
94
243
  import * as p from "@clack/prompts";
95
- import chalk from "chalk";
244
+ import chalk2 from "chalk";
96
245
  import fs2 from "fs";
97
246
  import path2 from "path";
98
247
  import { spawnSync } from "child_process";
@@ -362,6 +511,477 @@ function getErrorHtml(error) {
362
511
  </html>`;
363
512
  }
364
513
 
514
+ // src/lib/api-client.ts
515
+ var REQUEST_TIMEOUT_MS = 3e4;
516
+ function assertSecureBaseUrl(baseUrl) {
517
+ let parsed;
518
+ try {
519
+ parsed = new URL(baseUrl);
520
+ } catch {
521
+ throw new Error(`Invalid base URL: ${baseUrl}`);
522
+ }
523
+ if (parsed.protocol !== "https:" && parsed.hostname !== "localhost" && parsed.hostname !== "127.0.0.1") {
524
+ throw new Error("baseUrl must use https (except for localhost)");
525
+ }
526
+ }
527
+ var ApiClient = class {
528
+ baseUrl;
529
+ apiKey;
530
+ orgApiKey;
531
+ constructor(options) {
532
+ this.baseUrl = options.baseUrl.replace(/\/$/, "");
533
+ assertSecureBaseUrl(this.baseUrl);
534
+ this.apiKey = options.apiKey;
535
+ this.orgApiKey = options.orgApiKey;
536
+ }
537
+ async request(method, path3, options) {
538
+ const url = `${this.baseUrl}${path3}`;
539
+ const authType = options?.auth || "sdk";
540
+ const token = authType === "org" ? this.orgApiKey : this.apiKey;
541
+ const headers = {
542
+ "Content-Type": "application/json",
543
+ "User-Agent": `create-conto-agent/${CLI_PACKAGE_VERSION}`
544
+ };
545
+ if (token) {
546
+ headers["Authorization"] = `Bearer ${token}`;
547
+ }
548
+ const controller = new AbortController();
549
+ const timeoutId = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
550
+ try {
551
+ const response = await fetch(url, {
552
+ method,
553
+ headers,
554
+ body: options?.body ? JSON.stringify(options.body) : void 0,
555
+ signal: controller.signal
556
+ });
557
+ const contentType = response.headers.get("content-type") || "";
558
+ if (!contentType.includes("application/json")) {
559
+ const error = new Error(
560
+ response.status === 404 ? `API endpoint not found: ${path3}` : `API returned non-JSON response (${response.status})`
561
+ );
562
+ error.code = response.status === 404 ? "NOT_FOUND" : "INVALID_RESPONSE";
563
+ error.status = response.status;
564
+ throw error;
565
+ }
566
+ const data = await response.json();
567
+ if (!response.ok) {
568
+ const error = new Error(data.error || `API request failed: ${response.status}`);
569
+ error.code = data.code || "API_ERROR";
570
+ error.status = response.status;
571
+ error.body = data;
572
+ throw error;
573
+ }
574
+ return data;
575
+ } catch (err) {
576
+ if (err instanceof Error && err.name === "AbortError") {
577
+ const error = new Error(
578
+ `Request timed out after ${REQUEST_TIMEOUT_MS / 1e3}s`
579
+ );
580
+ error.code = "TIMEOUT";
581
+ error.status = 0;
582
+ throw error;
583
+ }
584
+ throw err;
585
+ } finally {
586
+ clearTimeout(timeoutId);
587
+ }
588
+ }
589
+ async getTestReport(options) {
590
+ const query = new URLSearchParams({ allowed: options.allowed, denied: options.denied });
591
+ if (options.review) query.set("review", options.review);
592
+ if (options.reviewOutcome) query.set("reviewOutcome", options.reviewOutcome);
593
+ return this.request("GET", `/api/sdk/test-report?${query}`);
594
+ }
595
+ // ── Org-level Admin APIs (used during init) ──
596
+ async createWallet(params) {
597
+ return this.request("POST", "/api/wallets", { body: params, auth: "org" });
598
+ }
599
+ async createAgent(params) {
600
+ return this.request("POST", "/api/agents", { body: params, auth: "org" });
601
+ }
602
+ async linkWalletToAgent(agentId, params) {
603
+ return this.request("POST", `/api/agents/${encodeURIComponent(agentId)}/wallets`, {
604
+ body: params,
605
+ auth: "org"
606
+ });
607
+ }
608
+ async createPolicy(params) {
609
+ return this.request("POST", "/api/policies", { body: params, auth: "org" });
610
+ }
611
+ async updatePolicy(policyId, params) {
612
+ return this.request("PATCH", `/api/policies/${encodeURIComponent(policyId)}`, { body: params, auth: "org" });
613
+ }
614
+ async deletePolicy(policyId) {
615
+ return this.request("DELETE", `/api/policies/${encodeURIComponent(policyId)}`, { auth: "org" });
616
+ }
617
+ async addPolicyRule(policyId, rule) {
618
+ return this.request(
619
+ "POST",
620
+ `/api/policies/${encodeURIComponent(policyId)}/rules`,
621
+ {
622
+ body: rule,
623
+ auth: "org"
624
+ }
625
+ );
626
+ }
627
+ async deletePolicyRule(policyId, ruleId) {
628
+ return this.request(
629
+ "DELETE",
630
+ `/api/policies/${encodeURIComponent(policyId)}/rules/${encodeURIComponent(ruleId)}`,
631
+ { auth: "org" }
632
+ );
633
+ }
634
+ async listOrgPolicies() {
635
+ return this.request("GET", "/api/policies", { auth: "org" });
636
+ }
637
+ async assignPolicyToAgent(agentId, policyId) {
638
+ return this.request("POST", `/api/agents/${encodeURIComponent(agentId)}/policies`, {
639
+ body: { policyId },
640
+ auth: "org"
641
+ });
642
+ }
643
+ async unassignPolicyFromAgent(agentId, policyId) {
644
+ return this.request(
645
+ "DELETE",
646
+ `/api/agents/${encodeURIComponent(agentId)}/policies?policyId=${encodeURIComponent(policyId)}`,
647
+ {
648
+ auth: "org"
649
+ }
650
+ );
651
+ }
652
+ async createSdkKey(agentId, params) {
653
+ return this.request("POST", `/api/agents/${encodeURIComponent(agentId)}/sdk-keys`, {
654
+ body: params,
655
+ auth: "org"
656
+ });
657
+ }
658
+ async fundWallet(walletId) {
659
+ return this.request("POST", `/api/wallets/${encodeURIComponent(walletId)}/faucet`, { auth: "org" });
660
+ }
661
+ // ── SDK Agent APIs (used by CLI commands) ──
662
+ async getSetup() {
663
+ return this.request("GET", "/api/sdk/setup");
664
+ }
665
+ async getAgentInfo() {
666
+ const data = await this.request("GET", "/api/sdk/agents/me");
667
+ return {
668
+ agent: {
669
+ id: data.id,
670
+ name: data.name,
671
+ agentType: data.agentType,
672
+ status: data.status,
673
+ createdAt: data.createdAt
674
+ },
675
+ organization: { name: data.organizationId },
676
+ walletCount: data.summary?.walletCount ?? 0,
677
+ summary: data.summary
678
+ };
679
+ }
680
+ async getWallets() {
681
+ return this.request("GET", "/api/sdk/wallets");
682
+ }
683
+ async getSpendingLimits() {
684
+ const data = await this.request("GET", "/api/sdk/spending-limits");
685
+ return {
686
+ limits: (data.wallets || []).map((w) => ({
687
+ walletId: w.walletId,
688
+ walletName: w.name,
689
+ daily: {
690
+ limit: w.limits?.daily ?? 0,
691
+ spent: w.spent?.today ?? 0,
692
+ remaining: w.remaining?.daily ?? 0
693
+ },
694
+ weekly: w.limits?.weekly ? {
695
+ limit: w.limits.weekly,
696
+ spent: w.spent?.thisWeek ?? 0,
697
+ remaining: w.remaining?.weekly ?? 0
698
+ } : void 0,
699
+ monthly: w.limits?.monthly ? {
700
+ limit: w.limits.monthly,
701
+ spent: w.spent?.thisMonth ?? 0,
702
+ remaining: w.remaining?.monthly ?? 0
703
+ } : void 0,
704
+ perTransaction: w.limits?.perTransaction ?? 0
705
+ }))
706
+ };
707
+ }
708
+ async requestPayment(params) {
709
+ return this.request("POST", "/api/sdk/payments/request", { body: params });
710
+ }
711
+ async executePayment(requestId) {
712
+ return this.request("POST", `/api/sdk/payments/${encodeURIComponent(requestId)}/execute`, { body: {} });
713
+ }
714
+ async getPaymentStatus(requestId) {
715
+ return this.request("GET", `/api/sdk/payments/${encodeURIComponent(requestId)}`);
716
+ }
717
+ async getTransactions(params) {
718
+ const query = new URLSearchParams();
719
+ if (params?.limit) query.set("limit", String(params.limit));
720
+ if (params?.status) query.set("status", params.status);
721
+ const qs = query.toString() ? `?${query.toString()}` : "";
722
+ return this.request("GET", `/api/sdk/transactions${qs}`);
723
+ }
724
+ async getTransaction(id) {
725
+ return this.request("GET", `/api/sdk/transactions/${encodeURIComponent(id)}`);
726
+ }
727
+ async getPolicies() {
728
+ return this.request("GET", "/api/sdk/policies");
729
+ }
730
+ async getAlerts(params) {
731
+ const query = new URLSearchParams();
732
+ if (params?.status) query.set("status", params.status);
733
+ const qs = query.toString() ? `?${query.toString()}` : "";
734
+ return this.request("GET", `/api/sdk/alerts${qs}`);
735
+ }
736
+ async getAnalytics() {
737
+ return this.request("GET", "/api/sdk/analytics");
738
+ }
739
+ };
740
+ function createApiClient(options) {
741
+ return new ApiClient(options);
742
+ }
743
+
744
+ // src/lib/owner-client.ts
745
+ var enc = encodeURIComponent;
746
+ var OwnerApiClient = class extends ApiClient {
747
+ // ── Agents ──
748
+ listAgents() {
749
+ return this.request("GET", "/api/agents?limit=100", {
750
+ auth: "org"
751
+ });
752
+ }
753
+ getAgent(agentId) {
754
+ return this.request("GET", `/api/agents/${enc(agentId)}`, {
755
+ auth: "org"
756
+ });
757
+ }
758
+ updateAgentStatus(agentId, status) {
759
+ return this.request("PATCH", `/api/agents/${enc(agentId)}`, {
760
+ body: { status },
761
+ auth: "org"
762
+ });
763
+ }
764
+ freezeAgent(agentId, body) {
765
+ return this.request("POST", `/api/agents/${enc(agentId)}/freeze`, {
766
+ body,
767
+ auth: "org"
768
+ });
769
+ }
770
+ unfreezeAgent(agentId, body) {
771
+ return this.request("POST", `/api/agents/${enc(agentId)}/unfreeze`, {
772
+ body,
773
+ auth: "org"
774
+ });
775
+ }
776
+ deleteAgent(agentId) {
777
+ return this.request("DELETE", `/api/agents/${enc(agentId)}`, {
778
+ auth: "org"
779
+ });
780
+ }
781
+ listSdkKeys(agentId) {
782
+ return this.request("GET", `/api/agents/${enc(agentId)}/sdk-keys`, {
783
+ auth: "org"
784
+ });
785
+ }
786
+ revokeSdkKey(agentId, keyId) {
787
+ return this.request(
788
+ "DELETE",
789
+ `/api/agents/${enc(agentId)}/sdk-keys?keyId=${enc(keyId)}`,
790
+ { auth: "org" }
791
+ );
792
+ }
793
+ createSdkKeyDirect(agentId, name) {
794
+ return this.request(
795
+ "POST",
796
+ `/api/agents/${enc(agentId)}/sdk-keys`,
797
+ { body: { name }, auth: "org" }
798
+ );
799
+ }
800
+ // ── Wallet controls ──
801
+ updateWallet(walletId, status) {
802
+ return this.request("PATCH", `/api/wallets/${enc(walletId)}`, {
803
+ body: { status },
804
+ auth: "org"
805
+ });
806
+ }
807
+ linkWallet(agentId, body) {
808
+ return this.request("POST", `/api/agents/${enc(agentId)}/wallets`, {
809
+ body,
810
+ auth: "org"
811
+ });
812
+ }
813
+ updateWalletLink(agentId, walletId, body) {
814
+ return this.request(
815
+ "PATCH",
816
+ `/api/agents/${enc(agentId)}/wallets/${enc(walletId)}`,
817
+ { body, auth: "org" }
818
+ );
819
+ }
820
+ unlinkWallet(agentId, walletId) {
821
+ return this.request(
822
+ "DELETE",
823
+ `/api/agents/${enc(agentId)}/wallets/${enc(walletId)}`,
824
+ { auth: "org" }
825
+ );
826
+ }
827
+ // ── Payees ──
828
+ listCounterparties() {
829
+ return this.request(
830
+ "GET",
831
+ "/api/counterparties?limit=100",
832
+ { auth: "org" }
833
+ );
834
+ }
835
+ getCounterparty(id) {
836
+ return this.request(
837
+ "GET",
838
+ `/api/counterparties/${enc(id)}`,
839
+ { auth: "org" }
840
+ );
841
+ }
842
+ createCounterparty(body) {
843
+ return this.request("POST", "/api/counterparties", { body, auth: "org" });
844
+ }
845
+ updateCounterparty(id, body) {
846
+ return this.request("PATCH", `/api/counterparties/${enc(id)}`, {
847
+ body,
848
+ auth: "org"
849
+ });
850
+ }
851
+ // ── Event delivery ──
852
+ listChannels() {
853
+ return this.request("GET", "/api/notification-channels", {
854
+ auth: "org"
855
+ });
856
+ }
857
+ createChannel(body) {
858
+ return this.request("POST", "/api/notification-channels", {
859
+ body,
860
+ auth: "org"
861
+ });
862
+ }
863
+ testChannel(channelId) {
864
+ return this.request(
865
+ "POST",
866
+ `/api/notification-channels/${enc(channelId)}/test`,
867
+ { auth: "org" }
868
+ );
869
+ }
870
+ deleteChannel(channelId) {
871
+ return this.request(
872
+ "DELETE",
873
+ `/api/notification-channels/${enc(channelId)}`,
874
+ { auth: "org" }
875
+ );
876
+ }
877
+ // ── Policy history and testing ──
878
+ getPolicy(policyId) {
879
+ return this.request("GET", `/api/policies/${enc(policyId)}`, { auth: "org" });
880
+ }
881
+ listPolicyRules(policyId) {
882
+ return this.request(
883
+ "GET",
884
+ `/api/policies/${enc(policyId)}/rules`,
885
+ { auth: "org" }
886
+ );
887
+ }
888
+ listPolicyVersions(policyId) {
889
+ return this.request("GET", `/api/policies/${enc(policyId)}/versions`, { auth: "org" });
890
+ }
891
+ getPolicyVersion(policyId, version) {
892
+ return this.request("GET", `/api/policies/${enc(policyId)}/versions/${version}`, { auth: "org" });
893
+ }
894
+ rollbackPolicyDirect(policyId, version) {
895
+ return this.request(
896
+ "POST",
897
+ `/api/policies/${enc(policyId)}/versions/${version}/rollback`,
898
+ { body: {}, auth: "org" }
899
+ );
900
+ }
901
+ simulatePolicy(body) {
902
+ return this.request("POST", "/api/policies/simulate", { body, auth: "org" });
903
+ }
904
+ // ── Alerts (agent key) ──
905
+ updateAlert(alertId, action) {
906
+ return this.request("POST", `/api/sdk/alerts/${enc(alertId)}`, {
907
+ body: { action }
908
+ });
909
+ }
910
+ // ── Owner review ──
911
+ proposeOwnerAction(action, input, version) {
912
+ return this.request("POST", "/api/owner-actions", {
913
+ body: { action, input, client: { name: "conto-cli", version } },
914
+ auth: "org"
915
+ });
916
+ }
917
+ getOwnerAction(changeId) {
918
+ return this.request("GET", `/api/owner-actions/${enc(changeId)}`, {
919
+ auth: "org"
920
+ });
921
+ }
922
+ claimOwnerAction(changeId) {
923
+ return this.request("POST", `/api/owner-actions/${enc(changeId)}/claim`, {
924
+ auth: "org"
925
+ });
926
+ }
927
+ };
928
+ function createOwnerClient(options) {
929
+ return new OwnerApiClient(options);
930
+ }
931
+
932
+ // src/lib/init-review-access.ts
933
+ var TERMINAL_RETRY = /* @__PURE__ */ new Set(["EXPIRED", "STALE", "FAILED"]);
934
+ function toResult(outcome) {
935
+ const { change, sdkKey } = outcome;
936
+ if (change.status === "APPLIED" && sdkKey) {
937
+ return { kind: "applied", sdkKey: { key: sdkKey.key, keyId: sdkKey.keyId } };
938
+ }
939
+ if (change.status === "PENDING_REVIEW" || change.status === "APPLYING") {
940
+ return { kind: "pending", changeId: change.changeId, reviewUrl: change.reviewUrl };
941
+ }
942
+ if (change.status === "APPLIED") {
943
+ return {
944
+ kind: "failed",
945
+ code: "KEY_NOT_RECEIVED",
946
+ message: "The key was created but this terminal did not receive it. Revoke it in the dashboard and run setup again."
947
+ };
948
+ }
949
+ if (change.status === "REJECTED") {
950
+ return { kind: "failed", code: "REVIEW_DECLINED", message: change.message };
951
+ }
952
+ return {
953
+ kind: "failed",
954
+ code: `REVIEW_${change.status}`,
955
+ message: change.result?.message ?? change.message
956
+ };
957
+ }
958
+ function reviewAccessFor(baseUrl, orgApiKey) {
959
+ const api = createOwnerClient({ baseUrl, orgApiKey });
960
+ const interactive2 = Boolean(process.stdout.isTTY) && !isJsonMode();
961
+ const options = { wait: interactive2, open: interactive2 };
962
+ return async (params) => {
963
+ if (params.changeId) {
964
+ const earlier = await api.getOwnerAction(params.changeId);
965
+ if (!TERMINAL_RETRY.has(earlier.status)) {
966
+ return toResult(await followChange(api, earlier, options));
967
+ }
968
+ }
969
+ const outcome = await proposeForReview(
970
+ api,
971
+ "setup_agent_access",
972
+ {
973
+ agent_id: params.agentId,
974
+ wallet_id: params.walletId,
975
+ spend_limit_per_tx: params.perTransactionLimit,
976
+ spend_limit_daily: params.dailyLimit,
977
+ key_name: params.keyName
978
+ },
979
+ options
980
+ );
981
+ return toResult(outcome);
982
+ };
983
+ }
984
+
365
985
  // src/lib/http-json.ts
366
986
  var HttpTransportError = class extends Error {
367
987
  constructor(failure, code, message) {
@@ -696,6 +1316,7 @@ function hasServerSideEffects(checkpoint) {
696
1316
  // src/lib/init-provisioning.ts
697
1317
  var RECONCILE_WAIT_SECONDS = 300;
698
1318
  var iso = (ms = Date.now()) => new Date(ms).toISOString();
1319
+ var TIGHTEN_ONLY_CODE = "TIGHTEN_ONLY_ROUTE";
699
1320
  async function provisionOrganization(input) {
700
1321
  const { checkpoint, client, ui, chain } = input;
701
1322
  const steps = checkpoint.steps;
@@ -979,7 +1600,10 @@ async function provisionOrganization(input) {
979
1600
  }
980
1601
  }
981
1602
  const agent = resources.agent;
982
- if (steps.walletLink.status === "done") {
1603
+ let reviewedAccess = Boolean(input.reviewAccess) && steps.walletLink.status === "action_required" && (Boolean(steps.walletLink.ownerChangeId) || steps.walletLink.error?.code === TIGHTEN_ONLY_CODE);
1604
+ if (reviewedAccess) {
1605
+ ui.info("The wallet link and SDK key are waiting for owner review.");
1606
+ } else if (steps.walletLink.status === "done") {
983
1607
  if (input.resuming) {
984
1608
  const links = await client.listWalletLinks(agent.id);
985
1609
  if (!links.ok) return verifyFailed("walletLink", links.failure);
@@ -1034,13 +1658,23 @@ async function provisionOrganization(input) {
1034
1658
  spendLimitDaily: request.dailyLimit,
1035
1659
  spendLimitPerTx: request.perTransactionLimit
1036
1660
  });
1037
- if (!result.ok) {
1661
+ if (!result.ok && result.outcome === "not_created" && result.failure.code === TIGHTEN_ONLY_CODE && input.reviewAccess) {
1662
+ ui.stop("Wallet link needs owner review");
1663
+ steps.walletLink = {
1664
+ status: "action_required",
1665
+ attemptedAt: steps.walletLink.attemptedAt,
1666
+ error: result.failure
1667
+ };
1668
+ persist();
1669
+ reviewedAccess = true;
1670
+ } else if (!result.ok) {
1038
1671
  ui.stop("Wallet linking failed");
1039
1672
  return createFailed("walletLink", result);
1673
+ } else {
1674
+ complete("walletLink", { id: result.value.id });
1675
+ ui.stop("Wallet linked");
1676
+ ui.success(`Wallet linked ($${request.dailyLimit}/day limit)`);
1040
1677
  }
1041
- complete("walletLink", { id: result.value.id });
1042
- ui.stop("Wallet linked");
1043
- ui.success(`Wallet linked ($${request.dailyLimit}/day limit)`);
1044
1678
  }
1045
1679
  }
1046
1680
  if (steps.policy.status === "done") {
@@ -1142,6 +1776,62 @@ async function provisionOrganization(input) {
1142
1776
  }
1143
1777
  return "none";
1144
1778
  };
1779
+ if (reviewedAccess && input.reviewAccess && steps.sdkKey.status !== "done") {
1780
+ ui.start("Waiting for an owner to confirm the wallet link and SDK key...");
1781
+ begin("sdkKey");
1782
+ const review = await input.reviewAccess({
1783
+ agentId: agent.id,
1784
+ walletId: wallet.id,
1785
+ dailyLimit: request.dailyLimit,
1786
+ perTransactionLimit: request.perTransactionLimit,
1787
+ keyName: request.sdkKeyName,
1788
+ changeId: steps.walletLink.ownerChangeId
1789
+ });
1790
+ if (review.kind === "pending") {
1791
+ ui.stop("Still waiting for owner review");
1792
+ steps.walletLink = { ...steps.walletLink, ownerChangeId: review.changeId };
1793
+ steps.sdkKey = { ...steps.sdkKey, status: "pending" };
1794
+ return stopped({
1795
+ status: "owner_action_required",
1796
+ step: "walletLink",
1797
+ code: "OWNER_REVIEW_REQUIRED",
1798
+ message: "An owner or admin must confirm the wallet link and SDK key.",
1799
+ ownerAction: {
1800
+ action: "Confirm the change on the review page, then resume setup to collect the key.",
1801
+ dashboardUrl: review.reviewUrl ?? `${input.baseUrl}/approvals/review/changes/${review.changeId}`
1802
+ }
1803
+ });
1804
+ }
1805
+ if (review.kind === "failed") {
1806
+ ui.stop("Owner review did not complete");
1807
+ steps.walletLink = { ...steps.walletLink, ownerChangeId: void 0 };
1808
+ steps.sdkKey = { ...steps.sdkKey, status: "failed" };
1809
+ return stopped({
1810
+ status: "failed",
1811
+ step: "walletLink",
1812
+ code: review.code,
1813
+ message: review.message
1814
+ });
1815
+ }
1816
+ let storedIn;
1817
+ try {
1818
+ storedIn = input.storeSdkKey(review.sdkKey.key, wallet, agent);
1819
+ } catch {
1820
+ ui.stop("SDK key could not be saved");
1821
+ steps.sdkKey = {
1822
+ status: "action_required",
1823
+ id: review.sdkKey.keyId,
1824
+ attemptedAt: steps.sdkKey.attemptedAt
1825
+ };
1826
+ return stopped(rotationAction([{ id: review.sdkKey.keyId }]));
1827
+ }
1828
+ complete("walletLink", { ownerChangeId: steps.walletLink.ownerChangeId });
1829
+ complete("sdkKey", { id: review.sdkKey.keyId, secretStoredIn: storedIn });
1830
+ ui.stop("Owner confirmed the wallet link and SDK key");
1831
+ ui.success(`Wallet linked ($${request.dailyLimit}/day limit) and SDK key created`);
1832
+ resources.sdkKey = { key: review.sdkKey.key, scopes: review.sdkKey.scopes };
1833
+ return { kind: "complete", resources: { wallet, agent, sdkKey: resources.sdkKey } };
1834
+ }
1145
1835
  if (steps.sdkKey.status === "done" && input.resuming) {
1146
1836
  const stored = await adoptStoredKey();
1147
1837
  if (typeof stored === "object") return stopped(stored);
@@ -1234,7 +1924,7 @@ function reconcileAction(step) {
1234
1924
  }
1235
1925
 
1236
1926
  // src/lib/setup-resources-client.ts
1237
- var REQUEST_TIMEOUT_MS = 3e4;
1927
+ var REQUEST_TIMEOUT_MS2 = 3e4;
1238
1928
  function isRecord(value) {
1239
1929
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
1240
1930
  }
@@ -1343,7 +2033,7 @@ var SetupResourcesClient = class {
1343
2033
  bearer,
1344
2034
  body,
1345
2035
  headers,
1346
- timeoutMs: REQUEST_TIMEOUT_MS
2036
+ timeoutMs: REQUEST_TIMEOUT_MS2
1347
2037
  });
1348
2038
  }
1349
2039
  async create(path3, body, label, parse, headers) {
@@ -1634,7 +2324,7 @@ function organizationBindingProblem(checkpoint, credential) {
1634
2324
  }
1635
2325
  async function runOrganizationInit(options) {
1636
2326
  const cwd = process.cwd();
1637
- const interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY);
2327
+ const interactive2 = Boolean(process.stdin.isTTY && process.stdout.isTTY);
1638
2328
  const providedOrgApiKey = options.apiKey || process.env.CONTO_ORG_API_KEY;
1639
2329
  if (options.resume && options.restart) {
1640
2330
  refuse("Use --resume or --restart, not both.", { code: "INVALID_OPTIONS" });
@@ -1676,7 +2366,7 @@ async function runOrganizationInit(options) {
1676
2366
  }
1677
2367
  discarded = { operationId: partial?.operationId, resources: recordedResources(partial) };
1678
2368
  }
1679
- if (!interactive && !providedOrgApiKey) {
2369
+ if (!interactive2 && !providedOrgApiKey) {
1680
2370
  failInit(
1681
2371
  [
1682
2372
  resumeFrom ? "Resuming setup without an interactive terminal needs an organization API key." : "create-conto-agent needs an interactive terminal for the setup wizard.",
@@ -1728,16 +2418,16 @@ async function runOrganizationInit(options) {
1728
2418
  `Resuming the setup started ${resumeFrom?.createdAt} for agent "${resumed.agentName}".`
1729
2419
  );
1730
2420
  }
1731
- const agentName = options.name || resumed?.agentName || (interactive ? await p.text({
2421
+ const agentName = options.name || resumed?.agentName || (interactive2 ? await p.text({
1732
2422
  message: "Agent name",
1733
2423
  placeholder: "my-procurement-bot",
1734
- validate: (v) => v.length < 2 ? "Name must be at least 2 characters" : void 0
2424
+ validate: (v) => (v ?? "").length < 2 ? "Name must be at least 2 characters" : void 0
1735
2425
  }) : HEADLESS_DEFAULT_NAME);
1736
2426
  if (p.isCancel(agentName)) {
1737
2427
  p.cancel("Setup cancelled.");
1738
2428
  process.exit(0);
1739
2429
  }
1740
- const agentType = options.type || resumed?.agentType || (interactive ? await p.select({
2430
+ const agentType = options.type || resumed?.agentType || (interactive2 ? await p.select({
1741
2431
  message: "Agent type",
1742
2432
  options: [
1743
2433
  { value: "ANTHROPIC_CLAUDE", label: "Claude" },
@@ -1750,7 +2440,7 @@ async function runOrganizationInit(options) {
1750
2440
  p.cancel("Setup cancelled.");
1751
2441
  process.exit(0);
1752
2442
  }
1753
- const dailyLimit = options.limit || resumed?.dailyLimit || (interactive ? await p.text({
2443
+ const dailyLimit = options.limit || resumed?.dailyLimit || (interactive2 ? await p.text({
1754
2444
  message: "Daily spending limit (USD)",
1755
2445
  placeholder: "500",
1756
2446
  initialValue: "500",
@@ -1769,7 +2459,7 @@ async function runOrganizationInit(options) {
1769
2459
  const { chains: availableChains, defaultChainId } = await fetchChains(baseUrl);
1770
2460
  s0.stop(`Found ${Object.keys(availableChains).length} networks`);
1771
2461
  const chainChoices = getChainChoices(availableChains);
1772
- const selectedChain = options.chain || resumed?.chainId || process.env.CONTO_CHAIN_ID || (interactive ? await p.select({
2462
+ const selectedChain = options.chain || resumed?.chainId || process.env.CONTO_CHAIN_ID || (interactive2 ? await p.select({
1773
2463
  message: "Network",
1774
2464
  options: chainChoices,
1775
2465
  initialValue: defaultChainId
@@ -1786,7 +2476,7 @@ async function runOrganizationInit(options) {
1786
2476
  });
1787
2477
  }
1788
2478
  if (!chain.testnet && !options.confirmMainnet && !resumed?.mainnetConfirmed) {
1789
- if (!interactive) {
2479
+ if (!interactive2) {
1790
2480
  failInit(
1791
2481
  `Chain ${chain.chainId} (${chain.name}) is a mainnet and can move real funds. Re-run with --confirm-mainnet after reviewing the network and limits.`,
1792
2482
  { chainId: chain.chainId, requiresConfirmation: "--confirm-mainnet" }
@@ -1901,7 +2591,8 @@ async function runOrganizationInit(options) {
1901
2591
  ui,
1902
2592
  persist: () => saveCheckpoint(cwd, checkpoint),
1903
2593
  storeSdkKey: (sdkKey2, wallet2, agent2) => writeOrganizationEnvLocal(cwd, { sdkKey: sdkKey2, baseUrl, agent: agent2, wallet: wallet2, chain }),
1904
- storedSdkKey: (agentId) => storedSdkKeyFor(cwd, baseUrl, agentId)
2594
+ storedSdkKey: (agentId) => storedSdkKeyFor(cwd, baseUrl, agentId),
2595
+ reviewAccess: reviewAccessFor(baseUrl, orgApiKey)
1905
2596
  });
1906
2597
  if (provisioned.kind === "stopped") {
1907
2598
  reportStoppedSetup({
@@ -2007,28 +2698,28 @@ async function runOrganizationInit(options) {
2007
2698
  return;
2008
2699
  }
2009
2700
  console.log("");
2010
- console.log(chalk.green.bold(" Your agent is ready!") + " Files written:\n");
2011
- console.log(` ${chalk.bold(".env.local")} - SDK key + config`);
2012
- console.log(` ${chalk.bold("conto.config.json")} - Agent metadata`);
2013
- console.log(` ${chalk.bold("example.mjs")} - Runnable payment example`);
2701
+ console.log(chalk2.green.bold(" Your agent is ready!") + " Files written:\n");
2702
+ console.log(` ${chalk2.bold(".env.local")} - SDK key + config`);
2703
+ console.log(` ${chalk2.bold("conto.config.json")} - Agent metadata`);
2704
+ console.log(` ${chalk2.bold("example.mjs")} - Runnable payment example`);
2014
2705
  console.log("");
2015
2706
  console.log(
2016
- ` ${chalk.dim("Wallet:")} ${wallet.address} (${chain.name}${chain.testnet ? " testnet" : ""}, ${wallet.custodyMode ?? "MANAGED"} custody)`
2707
+ ` ${chalk2.dim("Wallet:")} ${wallet.address} (${chain.name}${chain.testnet ? " testnet" : ""}, ${wallet.custodyMode ?? "MANAGED"} custody)`
2017
2708
  );
2018
- console.log(` ${chalk.dim("Currency:")} ${chain.currency}`);
2019
- console.log(` ${chalk.dim("Explorer:")} ${chain.explorerUrl}`);
2709
+ console.log(` ${chalk2.dim("Currency:")} ${chain.currency}`);
2710
+ console.log(` ${chalk2.dim("Explorer:")} ${chain.explorerUrl}`);
2020
2711
  console.log("");
2021
- console.log(chalk.bold(" Next steps:"));
2712
+ console.log(chalk2.bold(" Next steps:"));
2022
2713
  let step = 1;
2023
- console.log(` ${step++}. Verify setup: ${chalk.cyan(`${cli} doctor`)}`);
2714
+ console.log(` ${step++}. Verify setup: ${chalk2.cyan(`${cli} doctor`)}`);
2024
2715
  if (!chain.faucetAvailable) {
2025
2716
  console.log(
2026
- ` ${step++}. Fund your wallet with ${chain.currency} ${chalk.dim("\u2192")} ${wallet.address}`
2717
+ ` ${step++}. Fund your wallet with ${chain.currency} ${chalk2.dim("\u2192")} ${wallet.address}`
2027
2718
  );
2028
2719
  }
2029
- console.log(` ${step++}. Run the example: ${chalk.cyan("node example.mjs")}`);
2030
- console.log(` ${step++}. Make a payment: ${chalk.cyan(`${cli} pay <address> <amount>`)}`);
2031
- console.log(` ${step++}. Connect Claude: ${chalk.cyan(`${cli} mcp`)}`);
2720
+ console.log(` ${step++}. Run the example: ${chalk2.cyan("node example.mjs")}`);
2721
+ console.log(` ${step++}. Make a payment: ${chalk2.cyan(`${cli} pay <address> <amount>`)}`);
2722
+ console.log(` ${step++}. Connect Claude: ${chalk2.cyan(`${cli} mcp`)}`);
2032
2723
  if (!cliResolves) {
2033
2724
  printInfo(
2034
2725
  'Tip: "npx conto <command>" works after: npm install --save-dev @conto_finance/create-conto-agent'
@@ -2096,7 +2787,7 @@ function reportStoppedSetup(input) {
2096
2787
  const resources = recordedResources(checkpoint);
2097
2788
  if (completedSteps.length > 0) {
2098
2789
  console.log("");
2099
- console.log(chalk.bold(" Created and kept:"));
2790
+ console.log(chalk2.bold(" Created and kept:"));
2100
2791
  if (resources.walletId) {
2101
2792
  console.log(` Wallet ${resources.walletAddress ?? ""} (${resources.walletId})`);
2102
2793
  }
@@ -2331,32 +3022,32 @@ async function runSandboxInit(options) {
2331
3022
  return;
2332
3023
  }
2333
3024
  console.log("");
2334
- console.log(chalk.green.bold(" Sandbox agent ready!") + " Files written:\n");
2335
- console.log(` ${chalk.bold(".env.local")} - SDK key + config (shown once)`);
2336
- console.log(` ${chalk.bold("conto.config.json")} - Agent metadata`);
2337
- console.log(` ${chalk.bold("example.mjs")} - Runnable payment example`);
3025
+ console.log(chalk2.green.bold(" Sandbox agent ready!") + " Files written:\n");
3026
+ console.log(` ${chalk2.bold(".env.local")} - SDK key + config (shown once)`);
3027
+ console.log(` ${chalk2.bold("conto.config.json")} - Agent metadata`);
3028
+ console.log(` ${chalk2.bold("example.mjs")} - Runnable payment example`);
2338
3029
  if (setupKeyFile) {
2339
3030
  console.log(
2340
- ` ${chalk.bold(setupKeyFile)} - Setup key for policies and limits (keep out of the agent runtime)`
3031
+ ` ${chalk2.bold(setupKeyFile)} - Setup key for policies and limits (keep out of the agent runtime)`
2341
3032
  );
2342
3033
  }
2343
3034
  console.log("");
2344
3035
  console.log(
2345
- ` ${chalk.dim("Wallet:")} ${sandbox.wallet.address} (${chain?.name || sandbox.wallet.chainId}, test mode)`
3036
+ ` ${chalk2.dim("Wallet:")} ${sandbox.wallet.address} (${chain?.name || sandbox.wallet.chainId}, test mode)`
2346
3037
  );
2347
3038
  console.log(
2348
- ` ${chalk.dim("Balance:")} ${sandbox.wallet.balance} ${sandbox.wallet.currency} (test balance)`
3039
+ ` ${chalk2.dim("Balance:")} ${sandbox.wallet.balance} ${sandbox.wallet.currency} (test balance)`
2349
3040
  );
2350
3041
  console.log(
2351
- ` ${chalk.dim("Limits:")} $${sandbox.wallet.limits.perTransaction}/tx, $${sandbox.wallet.limits.daily}/day${setupKeyFile ? " (editable with the setup key)" : ""}`
3042
+ ` ${chalk2.dim("Limits:")} $${sandbox.wallet.limits.perTransaction}/tx, $${sandbox.wallet.limits.daily}/day${setupKeyFile ? " (editable with the setup key)" : ""}`
2352
3043
  );
2353
- console.log(` ${chalk.dim("Expires:")} ${sandbox.expiresAt}`);
3044
+ console.log(` ${chalk2.dim("Expires:")} ${sandbox.expiresAt}`);
2354
3045
  console.log("");
2355
- console.log(chalk.bold(" Next steps:"));
2356
- console.log(` 1. Run the example: ${chalk.cyan("node example.mjs")}`);
2357
- console.log(` 2. Continue it: ${chalk.cyan("node example.mjs --resume REQUEST_ID")}`);
3046
+ console.log(chalk2.bold(" Next steps:"));
3047
+ console.log(` 1. Run the example: ${chalk2.cyan("node example.mjs")}`);
3048
+ console.log(` 2. Continue it: ${chalk2.cyan("node example.mjs --resume REQUEST_ID")}`);
2358
3049
  console.log(" Replace REQUEST_ID with the ID printed by the example.");
2359
- console.log(` 3. Verify setup: ${chalk.cyan(`${cli} doctor`)}`);
3050
+ console.log(` 3. Verify setup: ${chalk2.cyan(`${cli} doctor`)}`);
2360
3051
  console.log("");
2361
3052
  printInfo(
2362
3053
  "Sandbox test payments exercise policy checks, receipts, and spend tracking without an onchain transfer."
@@ -2548,8 +3239,17 @@ main().catch((err) => {
2548
3239
 
2549
3240
  export {
2550
3241
  CLI_PACKAGE_VERSION,
3242
+ ApiClient,
3243
+ createApiClient,
2551
3244
  fetchChains,
2552
3245
  getChain,
3246
+ createOwnerClient,
3247
+ REVIEW_EXIT_CODES_HELP,
3248
+ isTightenOnlyRefusal,
3249
+ followChange,
3250
+ proposeForReview,
3251
+ directOrReview,
3252
+ reportReview,
2553
3253
  browserAuth,
2554
3254
  HttpTransportError,
2555
3255
  redactSecrets,