@conto_finance/create-conto-agent 0.4.4 → 0.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,11 +1,23 @@
1
1
  import {
2
2
  CLI_PACKAGE_VERSION,
3
+ HttpTransportError,
4
+ apiUrl,
3
5
  browserAuth,
4
- createApiClient,
5
6
  fetchChains,
7
+ fingerprintSecret,
6
8
  getChain,
7
- runInit
8
- } from "./chunk-ETJJHYIL.js";
9
+ normalizeBaseUrl,
10
+ parseSecureBaseUrl,
11
+ projectStateFile,
12
+ readProjectStateFile,
13
+ redactSecrets,
14
+ requestJson,
15
+ responseErrorCode,
16
+ responseErrorMessage,
17
+ retryAfterSeconds,
18
+ runInit,
19
+ writeProjectStateFile
20
+ } from "./chunk-TBAJKVGC.js";
9
21
  import {
10
22
  VELOCITY_PERIODS,
11
23
  buildVelocityCountValue,
@@ -28,17 +40,243 @@ import {
28
40
  truncateAddress
29
41
  } from "./chunk-K4LBO234.js";
30
42
  import {
43
+ SANDBOX_SETUP_ENV_FILE,
31
44
  isSensitiveConfigKey,
32
45
  loadConfig,
33
46
  loadGlobalConfig,
47
+ loadProjectEnv,
34
48
  maskSecret,
35
49
  missingSdkKeyMessage,
36
50
  saveGlobalConfig
37
- } from "./chunk-CR3H37ZX.js";
51
+ } from "./chunk-XWUWB3FT.js";
38
52
 
39
53
  // src/cli.ts
40
54
  import { Command } from "commander";
41
55
 
56
+ // src/lib/api-client.ts
57
+ var REQUEST_TIMEOUT_MS = 3e4;
58
+ function assertSecureBaseUrl(baseUrl) {
59
+ let parsed;
60
+ try {
61
+ parsed = new URL(baseUrl);
62
+ } catch {
63
+ throw new Error(`Invalid base URL: ${baseUrl}`);
64
+ }
65
+ if (parsed.protocol !== "https:" && parsed.hostname !== "localhost" && parsed.hostname !== "127.0.0.1") {
66
+ throw new Error("baseUrl must use https (except for localhost)");
67
+ }
68
+ }
69
+ var ApiClient = class {
70
+ baseUrl;
71
+ apiKey;
72
+ orgApiKey;
73
+ constructor(options) {
74
+ this.baseUrl = options.baseUrl.replace(/\/$/, "");
75
+ assertSecureBaseUrl(this.baseUrl);
76
+ this.apiKey = options.apiKey;
77
+ this.orgApiKey = options.orgApiKey;
78
+ }
79
+ async request(method, path2, options) {
80
+ const url = `${this.baseUrl}${path2}`;
81
+ const authType = options?.auth || "sdk";
82
+ const token = authType === "org" ? this.orgApiKey : this.apiKey;
83
+ const headers = {
84
+ "Content-Type": "application/json",
85
+ "User-Agent": `create-conto-agent/${CLI_PACKAGE_VERSION}`
86
+ };
87
+ if (token) {
88
+ headers["Authorization"] = `Bearer ${token}`;
89
+ }
90
+ const controller = new AbortController();
91
+ const timeoutId = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
92
+ try {
93
+ const response = await fetch(url, {
94
+ method,
95
+ headers,
96
+ body: options?.body ? JSON.stringify(options.body) : void 0,
97
+ signal: controller.signal
98
+ });
99
+ const contentType = response.headers.get("content-type") || "";
100
+ if (!contentType.includes("application/json")) {
101
+ const error = new Error(
102
+ response.status === 404 ? `API endpoint not found: ${path2}` : `API returned non-JSON response (${response.status})`
103
+ );
104
+ error.code = response.status === 404 ? "NOT_FOUND" : "INVALID_RESPONSE";
105
+ error.status = response.status;
106
+ throw error;
107
+ }
108
+ const data = await response.json();
109
+ if (!response.ok) {
110
+ const error = new Error(data.error || `API request failed: ${response.status}`);
111
+ error.code = data.code || "API_ERROR";
112
+ error.status = response.status;
113
+ error.body = data;
114
+ throw error;
115
+ }
116
+ return data;
117
+ } catch (err) {
118
+ if (err instanceof Error && err.name === "AbortError") {
119
+ const error = new Error(
120
+ `Request timed out after ${REQUEST_TIMEOUT_MS / 1e3}s`
121
+ );
122
+ error.code = "TIMEOUT";
123
+ error.status = 0;
124
+ throw error;
125
+ }
126
+ throw err;
127
+ } finally {
128
+ clearTimeout(timeoutId);
129
+ }
130
+ }
131
+ // ── Org-level Admin APIs (used during init) ──
132
+ async createWallet(params) {
133
+ return this.request("POST", "/api/wallets", { body: params, auth: "org" });
134
+ }
135
+ async createAgent(params) {
136
+ return this.request("POST", "/api/agents", { body: params, auth: "org" });
137
+ }
138
+ async linkWalletToAgent(agentId, params) {
139
+ return this.request("POST", `/api/agents/${encodeURIComponent(agentId)}/wallets`, {
140
+ body: params,
141
+ auth: "org"
142
+ });
143
+ }
144
+ async createPolicy(params) {
145
+ return this.request("POST", "/api/policies", { body: params, auth: "org" });
146
+ }
147
+ async updatePolicy(policyId, params) {
148
+ return this.request("PATCH", `/api/policies/${encodeURIComponent(policyId)}`, { body: params, auth: "org" });
149
+ }
150
+ async deletePolicy(policyId) {
151
+ return this.request("DELETE", `/api/policies/${encodeURIComponent(policyId)}`, { auth: "org" });
152
+ }
153
+ async addPolicyRule(policyId, rule) {
154
+ return this.request(
155
+ "POST",
156
+ `/api/policies/${encodeURIComponent(policyId)}/rules`,
157
+ {
158
+ body: rule,
159
+ auth: "org"
160
+ }
161
+ );
162
+ }
163
+ async deletePolicyRule(policyId, ruleId) {
164
+ return this.request(
165
+ "DELETE",
166
+ `/api/policies/${encodeURIComponent(policyId)}/rules/${encodeURIComponent(ruleId)}`,
167
+ { auth: "org" }
168
+ );
169
+ }
170
+ async listOrgPolicies() {
171
+ return this.request("GET", "/api/policies", { auth: "org" });
172
+ }
173
+ async assignPolicyToAgent(agentId, policyId) {
174
+ return this.request("POST", `/api/agents/${encodeURIComponent(agentId)}/policies`, {
175
+ body: { policyId },
176
+ auth: "org"
177
+ });
178
+ }
179
+ async unassignPolicyFromAgent(agentId, policyId) {
180
+ return this.request(
181
+ "DELETE",
182
+ `/api/agents/${encodeURIComponent(agentId)}/policies?policyId=${encodeURIComponent(policyId)}`,
183
+ {
184
+ auth: "org"
185
+ }
186
+ );
187
+ }
188
+ async createSdkKey(agentId, params) {
189
+ return this.request("POST", `/api/agents/${encodeURIComponent(agentId)}/sdk-keys`, {
190
+ body: params,
191
+ auth: "org"
192
+ });
193
+ }
194
+ async fundWallet(walletId) {
195
+ return this.request("POST", `/api/wallets/${encodeURIComponent(walletId)}/faucet`, { auth: "org" });
196
+ }
197
+ // ── SDK Agent APIs (used by CLI commands) ──
198
+ async getSetup() {
199
+ return this.request("GET", "/api/sdk/setup");
200
+ }
201
+ async getAgentInfo() {
202
+ const data = await this.request("GET", "/api/sdk/agents/me");
203
+ return {
204
+ agent: {
205
+ id: data.id,
206
+ name: data.name,
207
+ agentType: data.agentType,
208
+ status: data.status,
209
+ createdAt: data.createdAt
210
+ },
211
+ organization: { name: data.organizationId },
212
+ walletCount: data.summary?.walletCount ?? 0,
213
+ summary: data.summary
214
+ };
215
+ }
216
+ async getWallets() {
217
+ return this.request("GET", "/api/sdk/wallets");
218
+ }
219
+ async getSpendingLimits() {
220
+ const data = await this.request("GET", "/api/sdk/spending-limits");
221
+ return {
222
+ limits: (data.wallets || []).map((w) => ({
223
+ walletId: w.walletId,
224
+ walletName: w.name,
225
+ daily: {
226
+ limit: w.limits?.daily ?? 0,
227
+ spent: w.spent?.today ?? 0,
228
+ remaining: w.remaining?.daily ?? 0
229
+ },
230
+ weekly: w.limits?.weekly ? {
231
+ limit: w.limits.weekly,
232
+ spent: w.spent?.thisWeek ?? 0,
233
+ remaining: w.remaining?.weekly ?? 0
234
+ } : void 0,
235
+ monthly: w.limits?.monthly ? {
236
+ limit: w.limits.monthly,
237
+ spent: w.spent?.thisMonth ?? 0,
238
+ remaining: w.remaining?.monthly ?? 0
239
+ } : void 0,
240
+ perTransaction: w.limits?.perTransaction ?? 0
241
+ }))
242
+ };
243
+ }
244
+ async requestPayment(params) {
245
+ return this.request("POST", "/api/sdk/payments/request", { body: params });
246
+ }
247
+ async executePayment(requestId) {
248
+ return this.request("POST", `/api/sdk/payments/${encodeURIComponent(requestId)}/execute`, { body: {} });
249
+ }
250
+ async getPaymentStatus(requestId) {
251
+ return this.request("GET", `/api/sdk/payments/${encodeURIComponent(requestId)}`);
252
+ }
253
+ async getTransactions(params) {
254
+ const query = new URLSearchParams();
255
+ if (params?.limit) query.set("limit", String(params.limit));
256
+ if (params?.status) query.set("status", params.status);
257
+ const qs = query.toString() ? `?${query.toString()}` : "";
258
+ return this.request("GET", `/api/sdk/transactions${qs}`);
259
+ }
260
+ async getTransaction(id) {
261
+ return this.request("GET", `/api/sdk/transactions/${encodeURIComponent(id)}`);
262
+ }
263
+ async getPolicies() {
264
+ return this.request("GET", "/api/sdk/policies");
265
+ }
266
+ async getAlerts(params) {
267
+ const query = new URLSearchParams();
268
+ if (params?.status) query.set("status", params.status);
269
+ const qs = query.toString() ? `?${query.toString()}` : "";
270
+ return this.request("GET", `/api/sdk/alerts${qs}`);
271
+ }
272
+ async getAnalytics() {
273
+ return this.request("GET", "/api/sdk/analytics");
274
+ }
275
+ };
276
+ function createApiClient(options) {
277
+ return new ApiClient(options);
278
+ }
279
+
42
280
  // src/commands/status.ts
43
281
  async function statusCommand() {
44
282
  const config = loadConfig();
@@ -100,53 +338,428 @@ function progressBar(pct, width = 20) {
100
338
 
101
339
  // src/commands/doctor.ts
102
340
  import chalk from "chalk";
341
+
342
+ // src/lib/setup-diagnostics.ts
343
+ var SETUP_DIAGNOSTICS_VERSION = "conto.setup-diagnostics.v1";
344
+ var DOCTOR_EXIT_CODES = {
345
+ /** No failed check and no error-severity issue. */
346
+ OK: 0,
347
+ /** Setup needs action: a failed check or an error-severity issue. */
348
+ ACTION_REQUIRED: 1,
349
+ /** The doctor could not reach a verdict: network, timeout, or server error. */
350
+ UNAVAILABLE: 2
351
+ };
352
+ var SEVERITIES = /* @__PURE__ */ new Set(["error", "warning", "info"]);
353
+ var ACTORS = /* @__PURE__ */ new Set(["agent", "owner"]);
354
+ var CAPABILITIES = /* @__PURE__ */ new Set(["yes", "no", "unknown"]);
355
+ function isRecord(value) {
356
+ return typeof value === "object" && value !== null && !Array.isArray(value);
357
+ }
358
+ function readServerDiagnostics(value) {
359
+ if (!isRecord(value) || value.version !== SETUP_DIAGNOSTICS_VERSION) return null;
360
+ const status = value.status;
361
+ if (!isRecord(status) || typeof status.authenticated !== "boolean" || !CAPABILITIES.has(String(status.canRequest)) || !CAPABILITIES.has(String(status.canExecute)) || typeof status.ownerActionRequired !== "boolean" || !Array.isArray(value.issues) || !Array.isArray(value.wallets)) {
362
+ return null;
363
+ }
364
+ const issues = value.issues.filter(
365
+ (issue) => isRecord(issue) && typeof issue.code === "string" && SEVERITIES.has(String(issue.severity)) && ACTORS.has(String(issue.actor)) && typeof issue.message === "string" && isRecord(issue.resource) && Array.isArray(issue.actions)
366
+ ).map((issue) => ({
367
+ ...issue,
368
+ actions: issue.actions.filter(isKnownAction)
369
+ }));
370
+ const wallets = value.wallets.filter(
371
+ (wallet) => isRecord(wallet) && typeof wallet.walletId === "string"
372
+ );
373
+ const cards = value.connectedCards;
374
+ const connectedCards = isRecord(cards) && isRecord(cards.test) && isRecord(cards.live) ? cards : null;
375
+ return {
376
+ ...value,
377
+ wallets,
378
+ connectedCards,
379
+ issues
380
+ };
381
+ }
382
+ function isKnownAction(action) {
383
+ if (!isRecord(action) || typeof action.description !== "string") return false;
384
+ if (action.type === "command") return typeof action.command === "string";
385
+ if (action.type === "owner_url") return typeof action.url === "string";
386
+ return action.type === "api" && typeof action.method === "string" && typeof action.href === "string" && typeof action.credential === "string";
387
+ }
388
+ var CREATE_SANDBOX_COMMAND = "npx @conto_finance/create-conto-agent --sandbox";
389
+ function cliIssue(code, fields) {
390
+ return { code, requiredScope: null, ...fields, source: "cli" };
391
+ }
392
+ function sdkKeyNotConfiguredIssue(message) {
393
+ return cliIssue("SDK_KEY_NOT_CONFIGURED", {
394
+ severity: "error",
395
+ actor: "agent",
396
+ resource: { type: "sdk_key", id: null },
397
+ message,
398
+ actions: [
399
+ {
400
+ type: "command",
401
+ command: CREATE_SANDBOX_COMMAND,
402
+ description: "Create an anonymous test sandbox and save its keys to .env.local."
403
+ },
404
+ {
405
+ type: "command",
406
+ command: "npx @conto_finance/create-conto-agent --api-key <organization-api-key>",
407
+ description: "Create an agent in an owner's organization with its API key."
408
+ }
409
+ ]
410
+ });
411
+ }
412
+ function baseUrlInvalidIssue(message) {
413
+ return cliIssue("BASE_URL_INVALID", {
414
+ severity: "error",
415
+ actor: "agent",
416
+ resource: { type: "cli_config", id: "CONTO_BASE_URL" },
417
+ message: `${message}. Set CONTO_BASE_URL to an https URL, such as https://conto.finance.`,
418
+ actions: []
419
+ });
420
+ }
421
+ function serverUnreachableIssue(detail) {
422
+ return cliIssue("SERVER_UNREACHABLE", {
423
+ severity: "error",
424
+ actor: "agent",
425
+ resource: { type: "server", id: null },
426
+ message: `The setup check did not complete: ${detail}. Nothing about this setup was verified.`,
427
+ actions: [
428
+ {
429
+ type: "command",
430
+ command: "conto doctor --json",
431
+ description: "Run the check again after confirming CONTO_BASE_URL and network access."
432
+ }
433
+ ]
434
+ });
435
+ }
436
+ function authenticationFailedIssue(detail) {
437
+ return cliIssue("AUTHENTICATION_FAILED", {
438
+ severity: "error",
439
+ actor: "owner",
440
+ resource: { type: "sdk_key", id: null },
441
+ message: `Conto did not accept this SDK key: ${detail}. Check that CONTO_API_KEY holds the agent SDK key (conto_agent_...). An owner can issue a new key.`,
442
+ actions: [{ type: "owner_url", url: "/agents", description: "Issue a new SDK key." }]
443
+ });
444
+ }
445
+ function scopeRemediationIssue(body) {
446
+ const scope = body.requiredScope;
447
+ if (typeof scope !== "string" || !/^[a-z]+:[a-z]+$/.test(scope)) return null;
448
+ return cliIssue("SCOPE_MISSING", {
449
+ severity: "error",
450
+ actor: body.actor === "agent" ? "agent" : "owner",
451
+ resource: { type: "sdk_key", id: null },
452
+ requiredScope: scope,
453
+ message: `This SDK key does not have ${scope}, so it cannot read its own setup. Conto does not add scopes to an existing key. An owner can issue a new key with ${scope}.`,
454
+ actions: [{ type: "owner_url", url: "/agents", description: "Issue a new SDK key." }]
455
+ });
456
+ }
457
+ function sandboxExpiredIssue(expiresAt) {
458
+ return cliIssue("SANDBOX_EXPIRED", {
459
+ severity: "error",
460
+ actor: "agent",
461
+ resource: { type: "organization", id: null },
462
+ message: `This project's sandbox expired${expiresAt ? ` at ${expiresAt}` : ""}. Its keys no longer work. Create a new sandbox to keep testing.`,
463
+ actions: [
464
+ { type: "command", command: CREATE_SANDBOX_COMMAND, description: "Create a new sandbox." }
465
+ ]
466
+ });
467
+ }
468
+ function localSandboxExpired(sandboxMode, expiresAt, now = /* @__PURE__ */ new Date()) {
469
+ if (sandboxMode !== "test" || !expiresAt) return false;
470
+ const time = Date.parse(expiresAt);
471
+ return Number.isFinite(time) && time <= now.getTime();
472
+ }
473
+ function mergeIssues(diagnostics, local) {
474
+ const server = (diagnostics?.issues ?? []).map((issue) => ({
475
+ ...issue,
476
+ source: "server"
477
+ }));
478
+ const reported = new Set(server.map((issue) => issue.code));
479
+ return [...server, ...local.filter((issue) => !reported.has(issue.code))];
480
+ }
481
+ function exitCodeFor(checks, issues, unavailable) {
482
+ if (unavailable) return DOCTOR_EXIT_CODES.UNAVAILABLE;
483
+ if (checks.some((check) => check.status === "fail")) return DOCTOR_EXIT_CODES.ACTION_REQUIRED;
484
+ if (issues.some((issue) => issue.severity === "error")) {
485
+ return DOCTOR_EXIT_CODES.ACTION_REQUIRED;
486
+ }
487
+ return DOCTOR_EXIT_CODES.OK;
488
+ }
489
+ function describeAction(action, baseUrl) {
490
+ if (action.type === "command") return `Run: ${action.command}`;
491
+ if (action.type === "owner_url") {
492
+ const origin = baseUrl.replace(/\/+$/, "");
493
+ return `Owner: ${action.url.startsWith("/") ? `${origin}${action.url}` : action.url}`;
494
+ }
495
+ const scope = action.requiredScope ? `, ${action.requiredScope}` : "";
496
+ return `API: ${action.method} ${action.href} (${action.credential.replace(/_/g, " ")}${scope})`;
497
+ }
498
+
499
+ // src/commands/doctor.ts
103
500
  function mark(status) {
104
501
  if (status === "ok") return chalk.green("\u2713");
105
502
  if (status === "warn") return chalk.yellow("\u26A0");
106
503
  return chalk.red("\u2717");
107
504
  }
505
+ function errorMessage(error, fallback) {
506
+ return error instanceof Error && error.message ? error.message : fallback;
507
+ }
508
+ function isRecord2(value) {
509
+ return typeof value === "object" && value !== null && !Array.isArray(value);
510
+ }
108
511
  async function doctorCommand() {
512
+ let report;
513
+ try {
514
+ report = await runDoctor();
515
+ } catch (error) {
516
+ const issues = [serverUnreachableIssue(errorMessage(error, "Unexpected error"))];
517
+ report = {
518
+ ok: false,
519
+ exitCode: DOCTOR_EXIT_CODES.UNAVAILABLE,
520
+ baseUrl: "",
521
+ diagnosticsSource: "cli",
522
+ checks: [],
523
+ issues,
524
+ diagnostics: null,
525
+ setup: null
526
+ };
527
+ }
528
+ printReport(report);
529
+ process.exitCode = report.exitCode;
530
+ }
531
+ async function runDoctor() {
109
532
  const config = loadConfig();
110
533
  const checks = [];
111
- const isSandbox = config.sandboxMode === "test";
112
- checks.push({
113
- name: "Base URL",
114
- status: "ok",
115
- detail: config.baseUrl
116
- });
534
+ const local = [];
535
+ const addLocal = (issue) => {
536
+ if (!local.some((existing) => existing.code === issue.code)) local.push(issue);
537
+ };
538
+ const finish = (fields = {}) => {
539
+ const diagnostics2 = fields.diagnostics ?? null;
540
+ const issues = mergeIssues(diagnostics2, local);
541
+ const exitCode = exitCodeFor(checks, issues, fields.unavailable === true);
542
+ let setup2 = null;
543
+ if (fields.setup) {
544
+ const { diagnostics: _serverDiagnostics, ...setupFields } = fields.setup;
545
+ void _serverDiagnostics;
546
+ setup2 = setupFields;
547
+ }
548
+ return {
549
+ ok: exitCode === DOCTOR_EXIT_CODES.OK,
550
+ exitCode,
551
+ baseUrl: config.baseUrl,
552
+ diagnosticsSource: diagnostics2 ? "server" : "cli",
553
+ checks: checks.map((check) => ({ ...check, name: check.name.trim() })),
554
+ issues,
555
+ diagnostics: diagnostics2,
556
+ setup: setup2
557
+ };
558
+ };
559
+ let api = null;
560
+ try {
561
+ api = createApiClient({ baseUrl: config.baseUrl, apiKey: config.apiKey });
562
+ checks.push({ name: "Base URL", status: "ok", detail: config.baseUrl });
563
+ } catch (error) {
564
+ const message = errorMessage(error, "Invalid base URL");
565
+ checks.push({ name: "Base URL", status: "fail", detail: `${config.baseUrl}: ${message}` });
566
+ addLocal(baseUrlInvalidIssue(message));
567
+ }
117
568
  if (!config.apiKey) {
118
- checks.push({
119
- name: "SDK key",
120
- status: "fail",
121
- detail: missingSdkKeyMessage(config)
122
- });
123
- report(checks, null);
124
- process.exit(1);
569
+ const message = missingSdkKeyMessage(config);
570
+ checks.push({ name: "SDK key", status: "fail", detail: message });
571
+ addLocal(sdkKeyNotConfiguredIssue(message));
572
+ return finish();
125
573
  }
126
574
  checks.push({
127
575
  name: "SDK key",
128
576
  status: "ok",
129
577
  detail: `${maskSecret(config.apiKey)} (from ${process.env.CONTO_API_KEY ? "environment" : ".env.local or ~/.conto/config.json"})`
130
578
  });
131
- const api = createApiClient({ baseUrl: config.baseUrl, apiKey: config.apiKey });
579
+ const localExpiry = localSandboxExpired(config.sandboxMode, config.sandboxExpiresAt) ? config.sandboxExpiresAt : null;
580
+ if (!api) return finish();
132
581
  let setup;
133
582
  try {
134
583
  setup = await api.getSetup();
135
- } catch (err) {
136
- const message = err instanceof Error ? err.message : "Request failed";
584
+ } catch (error) {
585
+ const failure = error;
586
+ const status = typeof failure.status === "number" ? failure.status : 0;
587
+ const message = errorMessage(error, "Request failed");
137
588
  checks.push({
138
589
  name: "Authentication",
139
590
  status: "fail",
140
591
  detail: `${config.baseUrl}/api/sdk/setup: ${message}`
141
592
  });
142
- report(checks, null);
143
- process.exit(1);
593
+ const body = isRecord2(failure.body) ? failure.body : {};
594
+ const answered = status >= 400 && status < 500 && status !== 429 && failure.code !== "NOT_FOUND";
595
+ if (!answered) {
596
+ addLocal(serverUnreachableIssue(message));
597
+ if (localExpiry) addLocal(sandboxExpiredIssue(localExpiry));
598
+ return finish({ unavailable: true });
599
+ }
600
+ const diagnostics2 = readServerDiagnostics(body.diagnostics);
601
+ if (!diagnostics2) {
602
+ addLocal(
603
+ (status === 403 ? scopeRemediationIssue(body) : null) ?? authenticationFailedIssue(message)
604
+ );
605
+ }
606
+ const keyExpired = diagnostics2?.issues.some((issue) => issue.code === "SDK_KEY_EXPIRED") ?? /expired/i.test(message);
607
+ if (status === 401 && (localExpiry || keyExpired && config.sandboxMode === "test")) {
608
+ addLocal(sandboxExpiredIssue(localExpiry ?? config.sandboxExpiresAt));
609
+ }
610
+ return finish({ diagnostics: diagnostics2 });
144
611
  }
145
612
  checks.push({
146
613
  name: "Authentication",
147
614
  status: "ok",
148
615
  detail: `Authenticated as agent "${setup.agent.name}"`
149
616
  });
617
+ const diagnostics = readServerDiagnostics(setup.diagnostics);
618
+ checks.push(
619
+ ...diagnostics ? diagnosticChecks(setup, diagnostics) : legacyChecks(setup, config)
620
+ );
621
+ return finish({ diagnostics, setup });
622
+ }
623
+ var ENVIRONMENT_DETAIL = {
624
+ anonymous_sandbox: "Anonymous sandbox: payments are simulated and no funds move",
625
+ claimed_sandbox: "Claimed sandbox: payments are still simulated and no funds move",
626
+ account: "Conto organization"
627
+ };
628
+ var EXECUTION_DETAIL = {
629
+ simulated: "Sandbox test mode: payments are simulated and no funds move",
630
+ managed: "Managed by Conto (real transfers)",
631
+ external: "External: the agent signs transactions and confirms them through the API",
632
+ unknown: "Unknown: Conto does not execute payments from this wallet"
633
+ };
634
+ var WALLET_ACCESS_CODES = /* @__PURE__ */ new Set([
635
+ "WALLET_PAUSED",
636
+ "WALLET_UNAVAILABLE",
637
+ "WALLET_VIEW_ONLY",
638
+ "MAINNET_REQUIRES_PROD_AGENT"
639
+ ]);
640
+ var CARD_UNAVAILABLE_DETAIL = {
641
+ sandbox_organization: "Not available in a sandbox",
642
+ disabled: "Not enabled for this organization",
643
+ plan: "Not included in this organization's plan"
644
+ };
645
+ function capabilityStatus(state) {
646
+ if (state === "yes") return "ok";
647
+ if (state === "unknown") return "warn";
648
+ return "fail";
649
+ }
650
+ function cardCheck(name, card) {
651
+ if (card.availability !== "available") {
652
+ return {
653
+ name,
654
+ status: "ok",
655
+ detail: CARD_UNAVAILABLE_DETAIL[card.reason ?? ""] ?? "Not available"
656
+ };
657
+ }
658
+ return {
659
+ name,
660
+ status: "ok",
661
+ detail: card.canUse === "yes" ? `Ready: ${card.activeAuthorizations} active authorization${card.activeAuthorizations === 1 ? "" : "s"} on ${card.assignedCards} card${card.assignedCards === 1 ? "" : "s"}` : `Available. Not ready for this agent (${card.assignedCards} assigned, ${card.activeAuthorizations} active authorizations)`
662
+ };
663
+ }
664
+ function diagnosticChecks(setup, diagnostics) {
665
+ const checks = [];
666
+ const environment = diagnostics.environment;
667
+ if (environment) {
668
+ const expiry = environment.kind === "anonymous_sandbox" && environment.sandboxExpiresAt ? `, expires ${environment.sandboxExpiresAt}` : "";
669
+ const agentEnvironment = environment.kind === "account" ? `, agent environment ${environment.agentEnvironment}` : "";
670
+ checks.push({
671
+ name: "Environment",
672
+ status: "ok",
673
+ detail: `${ENVIRONMENT_DETAIL[environment.kind] ?? environment.kind}${agentEnvironment}${expiry}`
674
+ });
675
+ }
676
+ const agentIssue = diagnostics.issues.find(
677
+ (issue) => issue.resource.type === "agent" && issue.code.startsWith("AGENT_")
678
+ );
679
+ const agentActive = setup.agent.status === "active" && !agentIssue;
680
+ checks.push({
681
+ name: "Agent status",
682
+ status: agentActive ? "ok" : "fail",
683
+ detail: agentIssue?.message ?? (agentActive ? "Active" : setup.agent.status)
684
+ });
685
+ const scopes = setup.scopes || [];
686
+ const scopeIssues = diagnostics.issues.filter((issue) => issue.code === "SCOPE_MISSING");
687
+ const scopeNames = [
688
+ "payments:request",
689
+ "payments:execute",
690
+ ...scopeIssues.map((issue) => issue.requiredScope).filter(
691
+ (scope) => typeof scope === "string" && scope !== "payments:request" && scope !== "payments:execute"
692
+ )
693
+ ];
694
+ for (const scope of scopeNames) {
695
+ const missing = scopeIssues.find((issue) => issue.requiredScope === scope);
696
+ checks.push({
697
+ name: `Scope ${scope}`,
698
+ status: scopes.includes(scope) ? "ok" : missing?.severity === "error" ? "fail" : "warn",
699
+ detail: scopes.includes(scope) ? "Granted" : missing?.message ?? "Missing. None of this agent's wallets needs it."
700
+ });
701
+ }
702
+ const wallets = setup.wallets || [];
703
+ if (wallets.length === 0) {
704
+ const noWallet = diagnostics.issues.find((issue) => issue.code === "NO_WALLET");
705
+ checks.push({
706
+ name: "Wallet",
707
+ status: noWallet?.severity === "error" ? "fail" : "warn",
708
+ detail: noWallet?.message ?? "No wallet is linked to this agent."
709
+ });
710
+ }
711
+ for (const wallet of wallets) {
712
+ const entry = diagnostics.wallets.find((item) => item.walletId === wallet.id);
713
+ const walletIssues = diagnostics.issues.filter(
714
+ (issue) => issue.resource.type === "wallet" && issue.resource.id === wallet.id
715
+ );
716
+ const blocking = walletIssues.find(
717
+ (issue) => issue.severity === "error" && WALLET_ACCESS_CODES.has(issue.code)
718
+ );
719
+ const chainLabel = `${wallet.chainName} (${wallet.chainId})${wallet.isTestnet ? " testnet" : ""}`;
720
+ checks.push({
721
+ name: `Wallet ${shortAddress(wallet.address)}`,
722
+ status: blocking ? "fail" : "ok",
723
+ detail: `${chainLabel}, ${wallet.custodyMode} custody, status ${wallet.status}${blocking ? `. ${blocking.message}` : ""}`
724
+ });
725
+ if (!entry) continue;
726
+ const executionIssue = walletIssues.find(
727
+ (issue) => issue.severity === "error" && issue !== blocking
728
+ );
729
+ checks.push({
730
+ name: " Execution",
731
+ status: capabilityStatus(entry.canExecute),
732
+ detail: `${EXECUTION_DETAIL[entry.executionMode] ?? entry.executionMode}${entry.canExecute === "no" && executionIssue ? `. ${executionIssue.message}` : ""}`
733
+ });
734
+ checks.push({
735
+ name: " Balance",
736
+ status: entry.funding === "unfunded" ? "fail" : "ok",
737
+ 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."
738
+ });
739
+ if (wallet.limits?.daily != null) {
740
+ checks.push({
741
+ name: " Daily limit",
742
+ status: "ok",
743
+ detail: `${printAmount(wallet.spent?.today ?? 0, "USD")} spent of ${printAmount(wallet.limits.daily, "USD")}`
744
+ });
745
+ }
746
+ }
747
+ if (diagnostics.connectedCards) {
748
+ checks.push(cardCheck("Test cards", diagnostics.connectedCards.test));
749
+ checks.push(cardCheck("Live cards", diagnostics.connectedCards.live));
750
+ }
751
+ const { canRequest, canExecute } = diagnostics.status;
752
+ const sandbox = environment ? environment.kind !== "account" : false;
753
+ checks.push({
754
+ name: "Payment readiness",
755
+ status: canRequest === "yes" ? capabilityStatus(canExecute) : "fail",
756
+ 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."
757
+ });
758
+ return checks;
759
+ }
760
+ function legacyChecks(setup, config) {
761
+ const checks = [];
762
+ const isSandbox = config.sandboxMode === "test";
150
763
  checks.push({
151
764
  name: "Agent status",
152
765
  status: setup.agent.status === "active" ? "ok" : "fail",
@@ -208,41 +821,56 @@ async function doctorCommand() {
208
821
  status: readyForManagedExecution ? "ok" : canRequest ? "warn" : "fail",
209
822
  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"
210
823
  });
211
- report(checks, setup);
212
- const failed = checks.some((c) => c.status === "fail");
213
- if (failed) process.exit(1);
824
+ return checks;
214
825
  }
215
826
  function shortAddress(address) {
216
827
  if (!address || address.length <= 14) return address;
217
828
  return `${address.slice(0, 8)}...${address.slice(-6)}`;
218
829
  }
219
- function report(checks, setup) {
830
+ var ISSUE_MARK = {
831
+ error: chalk.red("\u2717"),
832
+ warning: chalk.yellow("\u26A0"),
833
+ info: chalk.cyan("\u2022")
834
+ };
835
+ function printReport(report) {
220
836
  if (isJsonMode()) {
221
- printJson({
222
- ok: !checks.some((c) => c.status === "fail"),
223
- checks: checks.map((c) => ({ name: c.name.trim(), status: c.status, detail: c.detail })),
224
- setup
225
- });
837
+ printJson(report);
226
838
  return;
227
839
  }
228
840
  printHeader("Conto Doctor");
229
- for (const c of checks) {
841
+ for (const c of report.checks) {
230
842
  console.log(` ${mark(c.status)} ${chalk.bold(c.name)}`);
231
843
  console.log(` ${chalk.dim(c.detail)}`);
232
844
  }
233
845
  console.log("");
234
- const fails = checks.filter((c) => c.status === "fail").length;
235
- const warns = checks.filter((c) => c.status === "warn").length;
236
- if (fails === 0 && warns === 0) {
846
+ if (report.issues.length > 0) {
847
+ console.log(` ${chalk.bold("Next steps")}`);
848
+ for (const issue of report.issues) {
849
+ const who = issue.actor === "owner" ? "owner action" : "agent action";
850
+ console.log(` ${ISSUE_MARK[issue.severity] ?? "\u2022"} ${chalk.bold(issue.code)} (${who})`);
851
+ console.log(` ${issue.message}`);
852
+ for (const action of issue.actions) {
853
+ console.log(` ${chalk.dim(describeAction(action, report.baseUrl))}`);
854
+ }
855
+ }
856
+ console.log("");
857
+ }
858
+ const fails = report.checks.filter((c) => c.status === "fail").length;
859
+ const warns = report.checks.filter((c) => c.status === "warn").length;
860
+ if (report.exitCode === DOCTOR_EXIT_CODES.UNAVAILABLE) {
861
+ console.log(chalk.red(" The check could not complete. Nothing was verified."));
862
+ } else if (report.exitCode === DOCTOR_EXIT_CODES.OK && warns === 0) {
237
863
  console.log(chalk.green(" All checks passed."));
238
- } else if (fails === 0) {
864
+ } else if (report.exitCode === DOCTOR_EXIT_CODES.OK) {
239
865
  console.log(
240
866
  chalk.yellow(
241
867
  ` ${warns} warning${warns === 1 ? "" : "s"}. Payments may still work; read the notes above.`
242
868
  )
243
869
  );
244
- } else {
870
+ } else if (fails > 0) {
245
871
  console.log(chalk.red(` ${fails} check${fails === 1 ? "" : "s"} failed.`));
872
+ } else {
873
+ console.log(chalk.red(" Action required. See the next steps above."));
246
874
  }
247
875
  console.log("");
248
876
  }
@@ -1719,8 +2347,980 @@ async function testWebhook(url) {
1719
2347
  }
1720
2348
  }
1721
2349
 
2350
+ // src/commands/sandbox.ts
2351
+ import fs from "fs";
2352
+ import path from "path";
2353
+ import { setTimeout as sleep } from "timers/promises";
2354
+ import chalk8 from "chalk";
2355
+
2356
+ // src/lib/sandbox-handoff-client.ts
2357
+ var HANDOFF_PATH = "/api/agents/sandbox/handoff";
2358
+ var DEFAULT_POLL_INTERVAL_SECONDS = 5;
2359
+ var MIN_POLL_INTERVAL_SECONDS = 1;
2360
+ var MAX_POLL_INTERVAL_SECONDS = 60;
2361
+ var REQUEST_TIMEOUT_MS2 = 15e3;
2362
+ var SANDBOX_ORG_KEY_PATTERN = /^conto_[a-f0-9]{64}$/;
2363
+ var HANDOFF_TOKEN_PATTERN = /^conto_claim_[a-f0-9]{64}$/;
2364
+ function isHandoffToken(value) {
2365
+ return typeof value === "string" && HANDOFF_TOKEN_PATTERN.test(value);
2366
+ }
2367
+ function checkSandboxKeyRole(key) {
2368
+ if (SANDBOX_ORG_KEY_PATTERN.test(key)) return { ok: true };
2369
+ if (key.startsWith("conto_agent_")) {
2370
+ return {
2371
+ ok: false,
2372
+ message: "CONTO_SANDBOX_API_KEY holds an agent SDK key (conto_agent_). The claim handoff needs the sandbox organization key (conto_ followed by 64 hex characters)."
2373
+ };
2374
+ }
2375
+ if (key.startsWith("conto_setup_")) {
2376
+ return {
2377
+ ok: false,
2378
+ message: "CONTO_SANDBOX_API_KEY holds the sandbox setup key (conto_setup_). The claim handoff needs the sandbox organization key."
2379
+ };
2380
+ }
2381
+ if (key.startsWith("conto_claim_")) {
2382
+ return {
2383
+ ok: false,
2384
+ message: "CONTO_SANDBOX_API_KEY holds a handoff token. The claim handoff needs the sandbox organization key."
2385
+ };
2386
+ }
2387
+ return {
2388
+ ok: false,
2389
+ message: "CONTO_SANDBOX_API_KEY is not a sandbox organization key (expected conto_ followed by 64 hex characters)."
2390
+ };
2391
+ }
2392
+ function transportFailure(error) {
2393
+ if (error instanceof HttpTransportError) {
2394
+ return { code: error.code, message: redactSecrets(error.message) };
2395
+ }
2396
+ return {
2397
+ code: "NETWORK_ERROR",
2398
+ message: redactSecrets(error instanceof Error ? error.message : String(error))
2399
+ };
2400
+ }
2401
+ function httpFailure(response, fallback) {
2402
+ return {
2403
+ code: responseErrorCode(response, response.status >= 500 ? "SERVER_ERROR" : "API_ERROR"),
2404
+ message: responseErrorMessage(response, `${fallback} (HTTP ${response.status})`),
2405
+ httpStatus: response.status
2406
+ };
2407
+ }
2408
+ function clampInterval(value) {
2409
+ if (typeof value !== "number" || !Number.isFinite(value)) return DEFAULT_POLL_INTERVAL_SECONDS;
2410
+ return Math.min(MAX_POLL_INTERVAL_SECONDS, Math.max(MIN_POLL_INTERVAL_SECONDS, Math.ceil(value)));
2411
+ }
2412
+ function resolveStatusPath(baseUrl, statusUrl) {
2413
+ if (statusUrl === void 0 || statusUrl === null) return HANDOFF_PATH;
2414
+ if (typeof statusUrl !== "string") return null;
2415
+ const base = new URL(normalizeBaseUrl(baseUrl));
2416
+ let resolved;
2417
+ try {
2418
+ resolved = new URL(statusUrl, base);
2419
+ } catch {
2420
+ return null;
2421
+ }
2422
+ if (resolved.origin !== base.origin || resolved.search || resolved.hash) return null;
2423
+ const basePath = base.pathname.replace(/\/+$/, "");
2424
+ const relative = resolved.pathname.startsWith(basePath) ? resolved.pathname.slice(basePath.length) : resolved.pathname;
2425
+ return relative === HANDOFF_PATH || resolved.pathname === HANDOFF_PATH ? HANDOFF_PATH : null;
2426
+ }
2427
+ function validVerificationUrl(baseUrl, value, token) {
2428
+ if (typeof value !== "string") return null;
2429
+ let parsed;
2430
+ try {
2431
+ parsed = new URL(value);
2432
+ } catch {
2433
+ return null;
2434
+ }
2435
+ const base = new URL(normalizeBaseUrl(baseUrl));
2436
+ if (parsed.origin !== base.origin || parsed.username || parsed.password) return null;
2437
+ if (parsed.hash !== `#${token}` || parsed.search) return null;
2438
+ return parsed.toString();
2439
+ }
2440
+ function parseIssuedHandoff(baseUrl, data) {
2441
+ const body = data;
2442
+ if (!body || !isHandoffToken(body.token)) return null;
2443
+ const token = body.token;
2444
+ const verificationUrl = validVerificationUrl(baseUrl, body.verificationUrl, token);
2445
+ const statusPath = resolveStatusPath(baseUrl, body.statusUrl);
2446
+ const expiresAt = typeof body.expiresAt === "string" ? body.expiresAt : "";
2447
+ if (!verificationUrl || !statusPath || !Number.isFinite(Date.parse(expiresAt))) return null;
2448
+ return {
2449
+ token,
2450
+ verificationUrl,
2451
+ statusPath,
2452
+ intervalSeconds: clampInterval(body.intervalSeconds),
2453
+ expiresAt: new Date(expiresAt).toISOString(),
2454
+ requestedPermission: typeof body.requestedPermission === "string" ? body.requestedPermission : null,
2455
+ organizationName: typeof body.organizationName === "string" ? body.organizationName : null
2456
+ };
2457
+ }
2458
+ async function initiateHandoff(input) {
2459
+ let response;
2460
+ try {
2461
+ response = await requestJson({
2462
+ url: apiUrl(input.baseUrl, HANDOFF_PATH),
2463
+ method: "POST",
2464
+ bearer: input.sandboxKey,
2465
+ timeoutMs: REQUEST_TIMEOUT_MS2,
2466
+ signal: input.signal
2467
+ });
2468
+ } catch (error) {
2469
+ return { kind: "error", failure: transportFailure(error) };
2470
+ }
2471
+ if (response.status === 201 || response.status === 200) {
2472
+ const handoff = parseIssuedHandoff(input.baseUrl, response.data);
2473
+ if (!handoff) {
2474
+ return {
2475
+ kind: "error",
2476
+ failure: {
2477
+ code: "UNTRUSTED_HANDOFF_RESPONSE",
2478
+ message: "The handoff response did not match the expected format or pointed to another origin. Nothing was stored.",
2479
+ httpStatus: response.status
2480
+ }
2481
+ };
2482
+ }
2483
+ return { kind: "created", handoff };
2484
+ }
2485
+ if (response.status === 409 && responseErrorCode(response, "") === "ALREADY_CLAIMED") {
2486
+ return {
2487
+ kind: "already_claimed",
2488
+ message: responseErrorMessage(response, "This sandbox already has a human owner.")
2489
+ };
2490
+ }
2491
+ if (response.status === 401) {
2492
+ return { kind: "auth_failed", failure: httpFailure(response, "The sandbox key was rejected") };
2493
+ }
2494
+ if (response.status === 429) {
2495
+ return {
2496
+ kind: "rate_limited",
2497
+ retryAfterSeconds: retryAfterSeconds(response.headers, response.data),
2498
+ failure: httpFailure(response, "Too many handoff requests")
2499
+ };
2500
+ }
2501
+ return { kind: "error", failure: httpFailure(response, "The handoff could not be created") };
2502
+ }
2503
+ async function inspectHandoff(input) {
2504
+ if (input.statusPath !== HANDOFF_PATH || !isHandoffToken(input.token)) {
2505
+ return {
2506
+ kind: "invalid",
2507
+ failure: { code: "INVALID_STATE", message: "The stored handoff is not valid." }
2508
+ };
2509
+ }
2510
+ let response;
2511
+ try {
2512
+ response = await requestJson({
2513
+ url: apiUrl(input.baseUrl, input.statusPath),
2514
+ method: "GET",
2515
+ bearer: input.token,
2516
+ timeoutMs: REQUEST_TIMEOUT_MS2,
2517
+ signal: input.signal
2518
+ });
2519
+ } catch (error) {
2520
+ return { kind: "error", failure: transportFailure(error) };
2521
+ }
2522
+ if (response.status === 200) {
2523
+ const body = response.data;
2524
+ if (body?.status === "claimed") return { kind: "claimed" };
2525
+ if (body?.status === "pending") {
2526
+ return {
2527
+ kind: "pending",
2528
+ expiresAt: typeof body.expiresAt === "string" ? body.expiresAt : null,
2529
+ organizationName: typeof body.organizationName === "string" ? body.organizationName : null
2530
+ };
2531
+ }
2532
+ return {
2533
+ kind: "error",
2534
+ failure: {
2535
+ code: "INVALID_RESPONSE",
2536
+ message: "The handoff status response was not recognized.",
2537
+ httpStatus: 200
2538
+ }
2539
+ };
2540
+ }
2541
+ if (response.status === 410) {
2542
+ return { kind: "expired", failure: httpFailure(response, "The handoff expired") };
2543
+ }
2544
+ if (response.status === 400) {
2545
+ return { kind: "invalid", failure: httpFailure(response, "The handoff is not valid") };
2546
+ }
2547
+ if (response.status === 429) {
2548
+ return {
2549
+ kind: "rate_limited",
2550
+ retryAfterSeconds: retryAfterSeconds(response.headers, response.data),
2551
+ failure: httpFailure(response, "Too many status checks")
2552
+ };
2553
+ }
2554
+ return { kind: "error", failure: httpFailure(response, "The handoff status check failed") };
2555
+ }
2556
+
2557
+ // src/lib/sandbox-claim-state.ts
2558
+ var SANDBOX_CLAIM_STATE_NAME = "sandbox-claim.json";
2559
+ var SANDBOX_CLAIM_STATE_FILE = projectStateFile(SANDBOX_CLAIM_STATE_NAME);
2560
+ function isState(value) {
2561
+ const state = value;
2562
+ if (!state || typeof state !== "object" || state.version !== 1) return false;
2563
+ if (typeof state.baseUrl !== "string" || typeof state.sandboxKeyFingerprint !== "string") {
2564
+ return false;
2565
+ }
2566
+ if (!["pending", "claimed", "expired"].includes(state.status)) return false;
2567
+ if (typeof state.expiresAt !== "string" || !Number.isFinite(Date.parse(state.expiresAt))) {
2568
+ return false;
2569
+ }
2570
+ if (state.statusPath !== HANDOFF_PATH) return false;
2571
+ if (state.status === "pending") {
2572
+ return isHandoffToken(state.token) && typeof state.verificationUrl === "string";
2573
+ }
2574
+ return true;
2575
+ }
2576
+ function loadClaimState(cwd) {
2577
+ const read = readProjectStateFile(cwd, SANDBOX_CLAIM_STATE_NAME);
2578
+ if (!read.found) return { kind: "none" };
2579
+ if (read.corrupt || !isState(read.value)) return { kind: "corrupt" };
2580
+ return { kind: "found", state: read.value };
2581
+ }
2582
+ function saveClaimState(cwd, state) {
2583
+ const record = state.status === "pending" ? state : (() => {
2584
+ const { token: _token, verificationUrl: _verificationUrl, ...rest } = state;
2585
+ return rest;
2586
+ })();
2587
+ return writeProjectStateFile(cwd, SANDBOX_CLAIM_STATE_NAME, record);
2588
+ }
2589
+
2590
+ // src/commands/sandbox.ts
2591
+ var SANDBOX_CLAIM_EXIT_CODES = {
2592
+ ok: 0,
2593
+ failed: 1,
2594
+ credential: 2,
2595
+ expired: 3,
2596
+ pending: 4,
2597
+ rateLimited: 5,
2598
+ interrupted: 130
2599
+ };
2600
+ var DEFAULT_BASE_URL = "https://conto.finance";
2601
+ var DEFAULT_WAIT_SECONDS = 300;
2602
+ var MAX_WAIT_SECONDS = 3600;
2603
+ var MAX_CONSECUTIVE_POLL_ERRORS = 3;
2604
+ var TEST_MODE_AFTER_CLAIM = {
2605
+ mode: "test",
2606
+ productionPayments: "disabled",
2607
+ ownerAssigned: true,
2608
+ setupKeyActive: false,
2609
+ walletFunded: false,
2610
+ limitsChanged: false,
2611
+ scopesGranted: false,
2612
+ credentialsPromoted: false
2613
+ };
2614
+ function cliPrefix() {
2615
+ return fs.existsSync(path.join(process.cwd(), "node_modules", ".bin", "conto")) ? "npx conto" : "npx @conto_finance/create-conto-agent";
2616
+ }
2617
+ function emit(report) {
2618
+ if (isJsonMode()) {
2619
+ printJson({
2620
+ ok: report.exitCode === SANDBOX_CLAIM_EXIT_CODES.ok,
2621
+ command: report.command,
2622
+ status: report.status,
2623
+ ...report.fields
2624
+ });
2625
+ } else {
2626
+ report.human();
2627
+ }
2628
+ process.exitCode = report.exitCode;
2629
+ }
2630
+ function failureReport(command, exitCode, error, extra = {}, status = "failed") {
2631
+ const safeError = { ...error, message: redactSecrets(error.message) };
2632
+ const nextSteps = Array.isArray(extra.nextSteps) ? extra.nextSteps : [];
2633
+ return {
2634
+ command,
2635
+ status,
2636
+ exitCode,
2637
+ fields: { error: safeError, ...extra },
2638
+ human: () => {
2639
+ printError(safeError.message);
2640
+ if (typeof extra.retryAfterSeconds === "number") {
2641
+ printInfo(`Retry after ${extra.retryAfterSeconds}s.`);
2642
+ }
2643
+ for (const step of nextSteps) printInfo(step);
2644
+ }
2645
+ };
2646
+ }
2647
+ function resolveSandboxCredential(command) {
2648
+ const env = loadProjectEnv();
2649
+ const fromProcess = process.env.CONTO_SANDBOX_API_KEY;
2650
+ const key = fromProcess || env.CONTO_SANDBOX_API_KEY;
2651
+ if (!key) {
2652
+ return {
2653
+ ok: false,
2654
+ report: failureReport(command, SANDBOX_CLAIM_EXIT_CODES.credential, {
2655
+ code: "NO_SANDBOX_KEY",
2656
+ message: "No sandbox organization key found. Set CONTO_SANDBOX_API_KEY, or run this in the project where you created the sandbox."
2657
+ })
2658
+ };
2659
+ }
2660
+ const role = checkSandboxKeyRole(key);
2661
+ if (!role.ok) {
2662
+ return {
2663
+ ok: false,
2664
+ report: failureReport(command, SANDBOX_CLAIM_EXIT_CODES.credential, {
2665
+ code: "SANDBOX_KEY_ROLE",
2666
+ message: role.message
2667
+ })
2668
+ };
2669
+ }
2670
+ const baseUrl = fromProcess ? process.env.CONTO_BASE_URL || DEFAULT_BASE_URL : process.env.CONTO_BASE_URL || env.CONTO_BASE_URL || DEFAULT_BASE_URL;
2671
+ try {
2672
+ parseSecureBaseUrl(baseUrl);
2673
+ } catch (error) {
2674
+ return {
2675
+ ok: false,
2676
+ report: failureReport(command, SANDBOX_CLAIM_EXIT_CODES.credential, {
2677
+ code: "INVALID_BASE_URL",
2678
+ message: error instanceof Error ? error.message : "Invalid base URL"
2679
+ })
2680
+ };
2681
+ }
2682
+ return {
2683
+ ok: true,
2684
+ credential: {
2685
+ key,
2686
+ source: fromProcess ? "environment" : ".env.local",
2687
+ baseUrl: normalizeBaseUrl(baseUrl),
2688
+ fingerprint: fingerprintSecret(key),
2689
+ sandboxExpiresAt: process.env.CONTO_SANDBOX_EXPIRES_AT || env.CONTO_SANDBOX_EXPIRES_AT
2690
+ }
2691
+ };
2692
+ }
2693
+ function boundTo(state, credential) {
2694
+ return state.sandboxKeyFingerprint === credential.fingerprint && normalizeBaseUrl(state.baseUrl) === credential.baseUrl;
2695
+ }
2696
+ function expiredLocally(state) {
2697
+ return Date.parse(state.expiresAt) <= Date.now();
2698
+ }
2699
+ function sandboxExpired(credential) {
2700
+ const expiresAt = credential.sandboxExpiresAt ? Date.parse(credential.sandboxExpiresAt) : NaN;
2701
+ return Number.isFinite(expiresAt) && expiresAt <= Date.now();
2702
+ }
2703
+ function stateFromHandoff(credential, handoff) {
2704
+ return {
2705
+ version: 1,
2706
+ baseUrl: credential.baseUrl,
2707
+ sandboxKeyFingerprint: credential.fingerprint,
2708
+ status: "pending",
2709
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
2710
+ expiresAt: handoff.expiresAt,
2711
+ intervalSeconds: handoff.intervalSeconds,
2712
+ statusPath: handoff.statusPath,
2713
+ requestedPermission: handoff.requestedPermission,
2714
+ organizationName: handoff.organizationName,
2715
+ token: handoff.token,
2716
+ verificationUrl: handoff.verificationUrl
2717
+ };
2718
+ }
2719
+ function markClaimed(cwd, state) {
2720
+ const now = (/* @__PURE__ */ new Date()).toISOString();
2721
+ const claimed = {
2722
+ ...state,
2723
+ status: "claimed",
2724
+ claimedAt: state.claimedAt || now,
2725
+ lastCheckedAt: now
2726
+ };
2727
+ saveClaimState(cwd, claimed);
2728
+ return claimed;
2729
+ }
2730
+ function markExpired(cwd, state) {
2731
+ const expired = {
2732
+ ...state,
2733
+ status: "expired",
2734
+ lastCheckedAt: (/* @__PURE__ */ new Date()).toISOString()
2735
+ };
2736
+ saveClaimState(cwd, expired);
2737
+ return expired;
2738
+ }
2739
+ function claimedReport(command, state, extra = {}) {
2740
+ const setupKeyFileExists = fs.existsSync(path.join(process.cwd(), SANDBOX_SETUP_ENV_FILE));
2741
+ return {
2742
+ command,
2743
+ status: "claimed",
2744
+ exitCode: SANDBOX_CLAIM_EXIT_CODES.ok,
2745
+ fields: {
2746
+ claimedAt: state.claimedAt ?? null,
2747
+ organizationName: state.organizationName,
2748
+ resumable: false,
2749
+ stateFile: SANDBOX_CLAIM_STATE_FILE,
2750
+ testMode: TEST_MODE_AFTER_CLAIM,
2751
+ ...extra,
2752
+ nextSteps: [
2753
+ "The owner reviews held payments and edits controls in Conto.",
2754
+ "Payments in this sandbox stay simulated. CONTO_API_KEY keeps working until the sandbox expires."
2755
+ ]
2756
+ },
2757
+ human: () => {
2758
+ printSuccess(
2759
+ "The sandbox was claimed. Its owner can review held payments and edit controls in Conto."
2760
+ );
2761
+ printInfo(
2762
+ "It stays in test mode. Claiming did not fund a wallet, change spending limits, grant scopes, or enable live payments."
2763
+ );
2764
+ printInfo(
2765
+ setupKeyFileExists ? `Claiming revoked the setup key in ${SANDBOX_SETUP_ENV_FILE}. The owner edits controls in Conto now.` : "Claiming revokes the sandbox setup key. The owner edits controls in Conto now."
2766
+ );
2767
+ }
2768
+ };
2769
+ }
2770
+ function expiredReport(command, expiresAt, error, cli) {
2771
+ return failureReport(
2772
+ command,
2773
+ SANDBOX_CLAIM_EXIT_CODES.expired,
2774
+ error,
2775
+ {
2776
+ expiresAt,
2777
+ resumable: false,
2778
+ nextSteps: [
2779
+ `${cli} sandbox claim --json issues a new link. If the owner already claimed the sandbox, it reports that instead.`
2780
+ ]
2781
+ },
2782
+ "expired"
2783
+ );
2784
+ }
2785
+ function pendingFields(state, options) {
2786
+ return {
2787
+ ...options.includeUrl ? { verificationUrl: state.verificationUrl } : {},
2788
+ expiresAt: state.expiresAt,
2789
+ requestedPermission: state.requestedPermission,
2790
+ organizationName: state.organizationName,
2791
+ ...options.includeUrl ? { reused: options.reused } : {},
2792
+ resumable: true,
2793
+ pollIntervalSeconds: state.intervalSeconds,
2794
+ stateFile: SANDBOX_CLAIM_STATE_FILE
2795
+ };
2796
+ }
2797
+ function printHandoff(state, reused, cli) {
2798
+ console.log("");
2799
+ console.log(
2800
+ ` ${chalk8.bold("Sandbox claim link")} ${chalk8.dim(`(expires ${state.expiresAt})`)}${reused ? chalk8.dim(" reused") : ""}`
2801
+ );
2802
+ console.log("");
2803
+ console.log(` ${state.verificationUrl}`);
2804
+ console.log("");
2805
+ printInfo(
2806
+ "Send this link only to the person who will own the sandbox. It holds a temporary secret."
2807
+ );
2808
+ printInfo("They sign in, review the request, and choose Claim sandbox.");
2809
+ if (state.requestedPermission) printInfo(`Requested permission: ${state.requestedPermission}`);
2810
+ console.log("");
2811
+ printInfo(`Wait for the claim: ${cli} sandbox claim --wait`);
2812
+ printInfo(`Check the status: ${cli} sandbox claim-status`);
2813
+ }
2814
+ function parseWaitSeconds(timeout) {
2815
+ if (timeout === void 0) return { ok: true, seconds: DEFAULT_WAIT_SECONDS };
2816
+ if (!/^\d+$/.test(timeout)) {
2817
+ return { ok: false, message: "--timeout takes a whole number of seconds." };
2818
+ }
2819
+ const seconds = Number(timeout);
2820
+ if (seconds < 1 || seconds > MAX_WAIT_SECONDS) {
2821
+ return { ok: false, message: `--timeout must be between 1 and ${MAX_WAIT_SECONDS} seconds.` };
2822
+ }
2823
+ return { ok: true, seconds };
2824
+ }
2825
+ async function waitForClaim(credential, state, timeoutSeconds, stats) {
2826
+ const interrupt = new AbortController();
2827
+ const onSigint = () => interrupt.abort();
2828
+ process.once("SIGINT", onSigint);
2829
+ const deadline = stats.startedAt + timeoutSeconds * 1e3;
2830
+ const intervalMs = state.intervalSeconds * 1e3;
2831
+ let delayMs = intervalMs;
2832
+ let consecutiveErrors = 0;
2833
+ let lastRetryAfterSeconds;
2834
+ try {
2835
+ for (; ; ) {
2836
+ const remaining = deadline - Date.now();
2837
+ if (remaining <= 0) return { kind: "timeout", lastRetryAfterSeconds };
2838
+ try {
2839
+ await sleep(Math.min(delayMs, remaining), void 0, { signal: interrupt.signal });
2840
+ } catch {
2841
+ return { kind: "interrupted" };
2842
+ }
2843
+ const result = await inspectHandoff({
2844
+ baseUrl: credential.baseUrl,
2845
+ statusPath: state.statusPath,
2846
+ token: state.token,
2847
+ signal: interrupt.signal
2848
+ });
2849
+ if (interrupt.signal.aborted) return { kind: "interrupted" };
2850
+ stats.polls += 1;
2851
+ delayMs = intervalMs;
2852
+ if (result.kind === "claimed") return { kind: "claimed" };
2853
+ if (result.kind === "expired") return { kind: "expired", failure: result.failure };
2854
+ if (result.kind === "invalid") return { kind: "invalid", failure: result.failure };
2855
+ if (result.kind === "pending") {
2856
+ consecutiveErrors = 0;
2857
+ lastRetryAfterSeconds = void 0;
2858
+ continue;
2859
+ }
2860
+ if (result.kind === "rate_limited") {
2861
+ consecutiveErrors = 0;
2862
+ lastRetryAfterSeconds = result.retryAfterSeconds;
2863
+ delayMs = Math.max(intervalMs, (result.retryAfterSeconds ?? state.intervalSeconds) * 1e3);
2864
+ continue;
2865
+ }
2866
+ consecutiveErrors += 1;
2867
+ if (consecutiveErrors >= MAX_CONSECUTIVE_POLL_ERRORS) {
2868
+ return { kind: "failed", failure: result.failure };
2869
+ }
2870
+ }
2871
+ } finally {
2872
+ process.removeListener("SIGINT", onSigint);
2873
+ }
2874
+ }
2875
+ async function withFailureReport(command, run) {
2876
+ try {
2877
+ await run();
2878
+ } catch (error) {
2879
+ emit(
2880
+ failureReport(command, SANDBOX_CLAIM_EXIT_CODES.failed, {
2881
+ code: "UNEXPECTED_ERROR",
2882
+ message: error instanceof Error ? error.message : String(error)
2883
+ })
2884
+ );
2885
+ }
2886
+ }
2887
+ function sandboxClaimCommand(options) {
2888
+ return withFailureReport("sandbox claim", () => runSandboxClaim(options));
2889
+ }
2890
+ function sandboxClaimStatusCommand() {
2891
+ return withFailureReport("sandbox claim-status", runSandboxClaimStatus);
2892
+ }
2893
+ async function runSandboxClaim(options) {
2894
+ const command = "sandbox claim";
2895
+ const cli = cliPrefix();
2896
+ const cwd = process.cwd();
2897
+ if (options.timeout !== void 0 && !options.wait) {
2898
+ emit(
2899
+ failureReport(command, SANDBOX_CLAIM_EXIT_CODES.credential, {
2900
+ code: "INVALID_OPTIONS",
2901
+ message: "--timeout applies only with --wait."
2902
+ })
2903
+ );
2904
+ return;
2905
+ }
2906
+ const wait = parseWaitSeconds(options.timeout);
2907
+ if (!wait.ok) {
2908
+ emit(
2909
+ failureReport(command, SANDBOX_CLAIM_EXIT_CODES.credential, {
2910
+ code: "INVALID_OPTIONS",
2911
+ message: wait.message
2912
+ })
2913
+ );
2914
+ return;
2915
+ }
2916
+ const resolved = resolveSandboxCredential(command);
2917
+ if (!resolved.ok) {
2918
+ emit(resolved.report);
2919
+ return;
2920
+ }
2921
+ const credential = resolved.credential;
2922
+ const stored = loadClaimState(cwd);
2923
+ let previousHandoff;
2924
+ let state;
2925
+ let reused = false;
2926
+ if (stored.kind === "corrupt") {
2927
+ previousHandoff = {
2928
+ status: "unreadable",
2929
+ reason: "The stored handoff record could not be read."
2930
+ };
2931
+ } else if (stored.kind === "found" && !boundTo(stored.state, credential)) {
2932
+ previousHandoff = {
2933
+ status: stored.state.status,
2934
+ reason: "The stored handoff belongs to a different sandbox key or base URL."
2935
+ };
2936
+ } else if (stored.kind === "found") {
2937
+ const current = stored.state;
2938
+ if (current.status === "claimed") {
2939
+ emit(claimedReport(command, current));
2940
+ return;
2941
+ }
2942
+ if (current.status === "pending" && expiredLocally(current)) {
2943
+ markExpired(cwd, current);
2944
+ previousHandoff = {
2945
+ status: "expired",
2946
+ reason: `The previous link expired at ${current.expiresAt}.`
2947
+ };
2948
+ } else if (current.status === "expired") {
2949
+ previousHandoff = {
2950
+ status: "expired",
2951
+ reason: `The previous link expired at ${current.expiresAt}.`
2952
+ };
2953
+ } else {
2954
+ const check = await inspectHandoff({
2955
+ baseUrl: credential.baseUrl,
2956
+ statusPath: current.statusPath,
2957
+ token: current.token
2958
+ });
2959
+ if (check.kind === "pending") {
2960
+ state = { ...current, lastCheckedAt: (/* @__PURE__ */ new Date()).toISOString() };
2961
+ saveClaimState(cwd, state);
2962
+ reused = true;
2963
+ } else if (check.kind === "claimed") {
2964
+ emit(claimedReport(command, markClaimed(cwd, current)));
2965
+ return;
2966
+ } else if (check.kind === "expired") {
2967
+ markExpired(cwd, current);
2968
+ previousHandoff = { status: "expired", reason: check.failure.message };
2969
+ } else if (check.kind === "invalid") {
2970
+ previousHandoff = { status: "invalid", reason: check.failure.message };
2971
+ } else if (check.kind === "rate_limited") {
2972
+ emit(
2973
+ failureReport(command, SANDBOX_CLAIM_EXIT_CODES.rateLimited, check.failure, {
2974
+ lastKnownStatus: "pending",
2975
+ resumable: true,
2976
+ stateFile: SANDBOX_CLAIM_STATE_FILE,
2977
+ retryAfterSeconds: check.retryAfterSeconds ?? null,
2978
+ nextSteps: [`Retry ${cli} sandbox claim once the rate limit resets.`]
2979
+ })
2980
+ );
2981
+ return;
2982
+ } else {
2983
+ emit(
2984
+ failureReport(command, SANDBOX_CLAIM_EXIT_CODES.failed, check.failure, {
2985
+ lastKnownStatus: "pending",
2986
+ resumable: true,
2987
+ stateFile: SANDBOX_CLAIM_STATE_FILE,
2988
+ nextSteps: [`Retry ${cli} sandbox claim. The stored link was kept.`]
2989
+ })
2990
+ );
2991
+ return;
2992
+ }
2993
+ }
2994
+ }
2995
+ let issuedNow = false;
2996
+ if (!state) {
2997
+ const result = await initiateHandoff({
2998
+ baseUrl: credential.baseUrl,
2999
+ sandboxKey: credential.key
3000
+ });
3001
+ if (result.kind === "created") {
3002
+ state = stateFromHandoff(credential, result.handoff);
3003
+ saveClaimState(cwd, state);
3004
+ issuedNow = true;
3005
+ } else if (result.kind === "already_claimed") {
3006
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3007
+ const claimed = markClaimed(cwd, {
3008
+ version: 1,
3009
+ baseUrl: credential.baseUrl,
3010
+ sandboxKeyFingerprint: credential.fingerprint,
3011
+ status: "claimed",
3012
+ createdAt: now,
3013
+ expiresAt: now,
3014
+ intervalSeconds: DEFAULT_POLL_INTERVAL_SECONDS,
3015
+ statusPath: HANDOFF_PATH,
3016
+ requestedPermission: null,
3017
+ organizationName: null,
3018
+ claimedAt: now
3019
+ });
3020
+ emit(claimedReport(command, claimed, previousHandoff ? { previousHandoff } : {}));
3021
+ return;
3022
+ } else if (result.kind === "auth_failed") {
3023
+ if (sandboxExpired(credential)) {
3024
+ emit(
3025
+ failureReport(
3026
+ command,
3027
+ SANDBOX_CLAIM_EXIT_CODES.expired,
3028
+ {
3029
+ code: "SANDBOX_EXPIRED",
3030
+ message: `The sandbox expired at ${credential.sandboxExpiresAt}. Its keys no longer work.`,
3031
+ httpStatus: result.failure.httpStatus
3032
+ },
3033
+ {
3034
+ resumable: false,
3035
+ nextSteps: [
3036
+ "Create a new sandbox: npx @conto_finance/create-conto-agent --sandbox --json"
3037
+ ]
3038
+ },
3039
+ "expired"
3040
+ )
3041
+ );
3042
+ return;
3043
+ }
3044
+ emit(
3045
+ failureReport(command, SANDBOX_CLAIM_EXIT_CODES.credential, result.failure, {
3046
+ resumable: false,
3047
+ nextSteps: [
3048
+ `The server rejected CONTO_SANDBOX_API_KEY from ${credential.source}. Use the organization key returned when the sandbox was created.`
3049
+ ]
3050
+ })
3051
+ );
3052
+ return;
3053
+ } else if (result.kind === "rate_limited") {
3054
+ emit(
3055
+ failureReport(command, SANDBOX_CLAIM_EXIT_CODES.rateLimited, result.failure, {
3056
+ resumable: false,
3057
+ retryAfterSeconds: result.retryAfterSeconds ?? null,
3058
+ ...previousHandoff ? { previousHandoff } : {},
3059
+ nextSteps: [`Retry ${cli} sandbox claim once the rate limit resets.`]
3060
+ })
3061
+ );
3062
+ return;
3063
+ } else {
3064
+ emit(
3065
+ failureReport(command, SANDBOX_CLAIM_EXIT_CODES.failed, result.failure, {
3066
+ resumable: false,
3067
+ ...previousHandoff ? { previousHandoff } : {},
3068
+ nextSteps: [`Retry ${cli} sandbox claim.`]
3069
+ })
3070
+ );
3071
+ return;
3072
+ }
3073
+ }
3074
+ const pendingState = state;
3075
+ const nextSteps = [
3076
+ "Give verificationUrl to the person who will own the sandbox. Do not post it publicly.",
3077
+ `${cli} sandbox claim --wait --json`,
3078
+ `${cli} sandbox claim-status --json`
3079
+ ];
3080
+ if (!options.wait || issuedNow && isJsonMode()) {
3081
+ emit({
3082
+ command,
3083
+ status: "pending",
3084
+ exitCode: SANDBOX_CLAIM_EXIT_CODES.ok,
3085
+ fields: {
3086
+ ...pendingFields(pendingState, { reused, includeUrl: true }),
3087
+ ...options.wait ? {
3088
+ wait: {
3089
+ waited: false,
3090
+ reason: "A new link was issued. Deliver it, then run the command again to wait."
3091
+ }
3092
+ } : {},
3093
+ ...previousHandoff ? { previousHandoff } : {},
3094
+ nextSteps
3095
+ },
3096
+ human: () => printHandoff(pendingState, reused, cli)
3097
+ });
3098
+ return;
3099
+ }
3100
+ if (!isJsonMode()) {
3101
+ printHandoff(pendingState, reused, cli);
3102
+ console.log("");
3103
+ printInfo(
3104
+ `Waiting up to ${wait.seconds}s for the owner. Press Ctrl+C to stop. Rerun to keep waiting on the same link.`
3105
+ );
3106
+ }
3107
+ const stats = { polls: 0, startedAt: Date.now() };
3108
+ const outcome = await waitForClaim(credential, pendingState, wait.seconds, stats);
3109
+ const waitInfo = {
3110
+ waited: true,
3111
+ timeoutSeconds: wait.seconds,
3112
+ elapsedSeconds: Math.round((Date.now() - stats.startedAt) / 1e3),
3113
+ polls: stats.polls
3114
+ };
3115
+ if (outcome.kind === "claimed") {
3116
+ emit(claimedReport(command, markClaimed(cwd, pendingState), { wait: waitInfo }));
3117
+ return;
3118
+ }
3119
+ if (outcome.kind === "expired") {
3120
+ markExpired(cwd, pendingState);
3121
+ const report = expiredReport(command, pendingState.expiresAt, outcome.failure, cli);
3122
+ report.fields.wait = waitInfo;
3123
+ emit(report);
3124
+ return;
3125
+ }
3126
+ if (outcome.kind === "invalid") {
3127
+ emit(
3128
+ failureReport(command, SANDBOX_CLAIM_EXIT_CODES.credential, outcome.failure, {
3129
+ resumable: false,
3130
+ wait: waitInfo,
3131
+ nextSteps: [`${cli} sandbox claim --json issues a new link.`]
3132
+ })
3133
+ );
3134
+ return;
3135
+ }
3136
+ if (outcome.kind === "failed") {
3137
+ emit(
3138
+ failureReport(command, SANDBOX_CLAIM_EXIT_CODES.failed, outcome.failure, {
3139
+ lastKnownStatus: "pending",
3140
+ resumable: true,
3141
+ stateFile: SANDBOX_CLAIM_STATE_FILE,
3142
+ wait: waitInfo,
3143
+ nextSteps: [`${cli} sandbox claim --wait --json resumes with the same link.`]
3144
+ })
3145
+ );
3146
+ return;
3147
+ }
3148
+ saveClaimState(cwd, { ...pendingState, lastCheckedAt: (/* @__PURE__ */ new Date()).toISOString() });
3149
+ const interrupted = outcome.kind === "interrupted";
3150
+ emit({
3151
+ command,
3152
+ status: "pending",
3153
+ exitCode: interrupted ? SANDBOX_CLAIM_EXIT_CODES.interrupted : SANDBOX_CLAIM_EXIT_CODES.pending,
3154
+ fields: {
3155
+ ...pendingFields(pendingState, { reused: true, includeUrl: true }),
3156
+ wait: {
3157
+ ...waitInfo,
3158
+ ...interrupted ? { interrupted: true } : { timedOut: true },
3159
+ ...outcome.kind === "timeout" && outcome.lastRetryAfterSeconds !== void 0 ? { rateLimited: true, retryAfterSeconds: outcome.lastRetryAfterSeconds } : {}
3160
+ },
3161
+ nextSteps: [`${cli} sandbox claim --wait --json resumes with the same link.`]
3162
+ },
3163
+ human: () => {
3164
+ printWarning(
3165
+ interrupted ? "Stopped waiting. The link is still valid." : `The owner has not claimed the sandbox yet (waited ${waitInfo.elapsedSeconds}s). The link is still valid.`
3166
+ );
3167
+ printInfo(`Keep waiting: ${cli} sandbox claim --wait`);
3168
+ }
3169
+ });
3170
+ }
3171
+ async function runSandboxClaimStatus() {
3172
+ const command = "sandbox claim-status";
3173
+ const cli = cliPrefix();
3174
+ const cwd = process.cwd();
3175
+ const resolved = resolveSandboxCredential(command);
3176
+ if (!resolved.ok) {
3177
+ emit(resolved.report);
3178
+ return;
3179
+ }
3180
+ const credential = resolved.credential;
3181
+ const stored = loadClaimState(cwd);
3182
+ if (stored.kind === "none") {
3183
+ emit(
3184
+ failureReport(
3185
+ command,
3186
+ SANDBOX_CLAIM_EXIT_CODES.credential,
3187
+ { code: "NO_HANDOFF", message: "No claim handoff has been started in this project." },
3188
+ { resumable: false, nextSteps: [`${cli} sandbox claim --json`] },
3189
+ "none"
3190
+ )
3191
+ );
3192
+ return;
3193
+ }
3194
+ if (stored.kind === "corrupt") {
3195
+ emit(
3196
+ failureReport(
3197
+ command,
3198
+ SANDBOX_CLAIM_EXIT_CODES.credential,
3199
+ {
3200
+ code: "INVALID_STATE",
3201
+ message: `${SANDBOX_CLAIM_STATE_FILE} could not be read.`
3202
+ },
3203
+ { resumable: false, nextSteps: [`${cli} sandbox claim --json issues a new link.`] }
3204
+ )
3205
+ );
3206
+ return;
3207
+ }
3208
+ const state = stored.state;
3209
+ if (!boundTo(state, credential)) {
3210
+ emit(
3211
+ failureReport(
3212
+ command,
3213
+ SANDBOX_CLAIM_EXIT_CODES.credential,
3214
+ {
3215
+ code: "STATE_MISMATCH",
3216
+ message: "The stored handoff belongs to a different sandbox key or base URL than this project uses."
3217
+ },
3218
+ {
3219
+ resumable: false,
3220
+ nextSteps: [`${cli} sandbox claim --json issues a link for this sandbox.`]
3221
+ }
3222
+ )
3223
+ );
3224
+ return;
3225
+ }
3226
+ if (state.status === "claimed") {
3227
+ emit(claimedReport(command, state));
3228
+ return;
3229
+ }
3230
+ if (state.status === "expired" || expiredLocally(state)) {
3231
+ if (state.status !== "expired") markExpired(cwd, state);
3232
+ emit(
3233
+ expiredReport(
3234
+ command,
3235
+ state.expiresAt,
3236
+ { code: "HANDOFF_EXPIRED", message: `The claim link expired at ${state.expiresAt}.` },
3237
+ cli
3238
+ )
3239
+ );
3240
+ return;
3241
+ }
3242
+ const check = await inspectHandoff({
3243
+ baseUrl: credential.baseUrl,
3244
+ statusPath: state.statusPath,
3245
+ token: state.token
3246
+ });
3247
+ if (check.kind === "pending") {
3248
+ const updated = { ...state, lastCheckedAt: (/* @__PURE__ */ new Date()).toISOString() };
3249
+ saveClaimState(cwd, updated);
3250
+ emit({
3251
+ command,
3252
+ status: "pending",
3253
+ exitCode: SANDBOX_CLAIM_EXIT_CODES.ok,
3254
+ fields: {
3255
+ ...pendingFields(updated, { reused: true, includeUrl: false }),
3256
+ lastCheckedAt: updated.lastCheckedAt,
3257
+ nextSteps: [
3258
+ `${cli} sandbox claim --json shows the link again.`,
3259
+ `${cli} sandbox claim --wait --json waits for the owner.`
3260
+ ]
3261
+ },
3262
+ human: () => {
3263
+ printInfo(`Waiting for the owner. The link expires at ${state.expiresAt}.`);
3264
+ printInfo(`Show the link again: ${cli} sandbox claim`);
3265
+ }
3266
+ });
3267
+ return;
3268
+ }
3269
+ if (check.kind === "claimed") {
3270
+ emit(claimedReport(command, markClaimed(cwd, state)));
3271
+ return;
3272
+ }
3273
+ if (check.kind === "expired") {
3274
+ markExpired(cwd, state);
3275
+ emit(expiredReport(command, state.expiresAt, check.failure, cli));
3276
+ return;
3277
+ }
3278
+ if (check.kind === "invalid") {
3279
+ emit(
3280
+ failureReport(command, SANDBOX_CLAIM_EXIT_CODES.credential, check.failure, {
3281
+ resumable: false,
3282
+ nextSteps: [`${cli} sandbox claim --json issues a new link.`]
3283
+ })
3284
+ );
3285
+ return;
3286
+ }
3287
+ emit(
3288
+ failureReport(
3289
+ command,
3290
+ check.kind === "rate_limited" ? SANDBOX_CLAIM_EXIT_CODES.rateLimited : SANDBOX_CLAIM_EXIT_CODES.failed,
3291
+ check.failure,
3292
+ {
3293
+ lastKnownStatus: "pending",
3294
+ resumable: true,
3295
+ stateFile: SANDBOX_CLAIM_STATE_FILE,
3296
+ ...check.kind === "rate_limited" ? { retryAfterSeconds: check.retryAfterSeconds ?? null } : {},
3297
+ nextSteps: [`Retry ${cli} sandbox claim-status.`]
3298
+ }
3299
+ )
3300
+ );
3301
+ }
3302
+
1722
3303
  // src/cli.ts
1723
3304
  var program = new Command();
3305
+ var INIT_EXIT_CODES_HELP = `
3306
+ Exit codes:
3307
+ 0 setup complete
3308
+ 1 setup failed before anything was created
3309
+ 2 refused: an unfinished setup exists, the resume does not match it,
3310
+ or the credential was rejected
3311
+ 3 partial setup: run again with --resume
3312
+ 4 reconciliation or owner action needed before --resume (see the output)
3313
+ `;
3314
+ var SANDBOX_CLAIM_EXIT_CODES_HELP = `
3315
+ Exit codes:
3316
+ 0 link issued or reused, or the sandbox was claimed
3317
+ 1 request failed
3318
+ 2 credential or local state problem
3319
+ 3 the link or the sandbox expired
3320
+ 4 --wait timed out, the link is still valid
3321
+ 5 rate limited
3322
+ 130 interrupted while waiting, the link is still valid
3323
+ `;
1724
3324
  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) => {
1725
3325
  const opts = actionCommand.optsWithGlobals();
1726
3326
  if (opts.json) {
@@ -1736,7 +3336,7 @@ program.command("init").description("Run the setup wizard (interactive, or headl
1736
3336
  ).option(
1737
3337
  "--confirm-mainnet",
1738
3338
  "Confirm that the selected network can move real funds (required for headless mainnet setup)"
1739
- ).option("--no-install", "Skip installing the conto CLI into the project").action(async (opts, command) => {
3339
+ ).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) => {
1740
3340
  if (command.optsWithGlobals().json) {
1741
3341
  setJsonMode(true);
1742
3342
  }
@@ -1749,9 +3349,14 @@ program.command("init").description("Run the setup wizard (interactive, or headl
1749
3349
  install: opts.install,
1750
3350
  sandbox: opts.sandbox === true,
1751
3351
  apiKey: opts.apiKey,
1752
- confirmMainnet: opts.confirmMainnet === true
3352
+ confirmMainnet: opts.confirmMainnet === true,
3353
+ resume: opts.resume === true,
3354
+ restart: opts.restart === true
1753
3355
  });
1754
3356
  });
3357
+ var sandboxCommand = program.command("sandbox").description("Hand an anonymous sandbox to the person who will own it");
3358
+ sandboxCommand.command("claim").description("Create or reuse a claim link for the sandbox owner (uses CONTO_SANDBOX_API_KEY)").option("--wait", "Wait until the owner claims the sandbox").option("--timeout <seconds>", "Longest wait in seconds with --wait (default 300)").addHelpText("after", SANDBOX_CLAIM_EXIT_CODES_HELP).action((opts) => sandboxClaimCommand({ wait: opts.wait === true, timeout: opts.timeout }));
3359
+ sandboxCommand.command("claim-status").description("Check whether the owner has claimed the sandbox").addHelpText("after", SANDBOX_CLAIM_EXIT_CODES_HELP).action(() => sandboxClaimStatusCommand());
1755
3360
  program.command("webhooks").description("Test local webhook handlers").command("test <url>").description("Send one signed synthetic payment event to a localhost handler").action(testWebhook);
1756
3361
  program.command("status").description("Agent info, wallet balances, spending summary").action(statusCommand);
1757
3362
  program.command("doctor").description("Diagnose setup: auth, key scopes, wallet, chain, balance, base URL").action(doctorCommand);
@@ -1770,7 +3375,7 @@ program.command("alerts").description("List alerts").option("--active", "Show on
1770
3375
  program.command("config [key] [value]").description("Show or update configuration").action(configCommand);
1771
3376
  program.command("login").description("Authenticate with Conto").option("--base-url <url>", "Conto instance URL").action(loginCommand);
1772
3377
  program.command("logout").description("Clear stored credentials").action(async () => {
1773
- const { clearGlobalConfig } = await import("./config-YV6X7VKJ.js");
3378
+ const { clearGlobalConfig } = await import("./config-N7W4ZJJY.js");
1774
3379
  clearGlobalConfig();
1775
3380
  const { printSuccess: printSuccess2 } = await import("./output-IN47X4NU.js");
1776
3381
  printSuccess2("Logged out. Credentials cleared.");