@conto_finance/create-conto-agent 0.9.0 → 0.10.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.
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  ensureContoDirGitignored,
3
3
  ensureEnvLocalGitignored,
4
+ loadGlobalConfig,
4
5
  loadProjectEnv,
5
6
  saveGlobalConfig,
6
7
  writeEnvLocal,
@@ -21,7 +22,7 @@ import {
21
22
  // package.json
22
23
  var package_default = {
23
24
  name: "@conto_finance/create-conto-agent",
24
- version: "0.9.0",
25
+ version: "0.10.0",
25
26
  description: "Set up an AI agent with Conto spending controls",
26
27
  bin: {
27
28
  "create-conto-agent": "bin/create-conto-agent.js",
@@ -364,7 +365,7 @@ function chainHint(chain) {
364
365
 
365
366
  // src/lib/auth.ts
366
367
  import http from "http";
367
- import { randomBytes } from "crypto";
368
+ import { createHash, randomBytes } from "crypto";
368
369
  import open from "open";
369
370
  var CALLBACK_BODY_LIMIT_BYTES = 16 * 1024;
370
371
  async function readRequestBody(req) {
@@ -404,16 +405,93 @@ async function parseCallbackPayload(req) {
404
405
  returnedState: params.get("state")
405
406
  };
406
407
  }
407
- async function browserAuth(baseUrl, onAuthUrl) {
408
- return new Promise((resolve, reject) => {
408
+ var PICKUP_POLL_MS = 2e3;
409
+ var PAIRING_ALPHABET = "BCDFGHJKLMNPQRSTVWXZ";
410
+ var PICKUP_FINAL_CODES = /* @__PURE__ */ new Set([
411
+ "CLI_AUTH_REFUSED",
412
+ "EXPIRED",
413
+ "ALREADY_PICKED_UP",
414
+ "INVALID_PICKUP_CODE"
415
+ ]);
416
+ function pairingCode(pickupHash) {
417
+ const digest = createHash("sha256").update(`conto-cli-pairing:${pickupHash}`).digest();
418
+ let code = "";
419
+ for (let i = 0; i < 8; i += 1) code += PAIRING_ALPHABET[digest[i] % PAIRING_ALPHABET.length];
420
+ return `${code.slice(0, 4)}-${code.slice(4)}`;
421
+ }
422
+ async function pollPickup(baseUrl, code, state) {
423
+ let response;
424
+ try {
425
+ response = await fetch(`${baseUrl.replace(/\/+$/, "")}/api/cli-auth/pickup`, {
426
+ method: "POST",
427
+ headers: { "Content-Type": "application/json" },
428
+ body: JSON.stringify({ code, state }),
429
+ redirect: "error"
430
+ });
431
+ } catch {
432
+ return { done: false };
433
+ }
434
+ const body = await response.json().catch(() => null);
435
+ if (response.status === 200 && body?.status === "DELIVERED" && typeof body.token === "string") {
436
+ if (body.state !== state) return { done: true, error: "Invalid authentication state" };
437
+ return {
438
+ done: true,
439
+ result: {
440
+ orgApiKey: body.token,
441
+ organizationName: typeof body.organizationName === "string" ? body.organizationName : "",
442
+ expiresAt: typeof body.expiresAt === "string" ? body.expiresAt : ""
443
+ }
444
+ };
445
+ }
446
+ if (typeof body?.code === "string" && PICKUP_FINAL_CODES.has(body.code)) {
447
+ return {
448
+ done: true,
449
+ error: typeof body.error === "string" ? body.error : "Authentication failed"
450
+ };
451
+ }
452
+ const retry = response.status === 202 || response.status === 429 || response.status >= 500;
453
+ return { done: false, stop: !retry };
454
+ }
455
+ async function browserAuth(baseUrl, onAuthUrl, onPairingCode) {
456
+ return new Promise((rawResolve, rawReject) => {
409
457
  const state = randomBytes(16).toString("hex");
458
+ const pickupCode = `conto_clipickup_${randomBytes(32).toString("hex")}`;
459
+ const pickupHash = createHash("sha256").update(pickupCode).digest("hex");
460
+ let settled = false;
461
+ let pollTimer;
462
+ const finish = () => {
463
+ settled = true;
464
+ clearTimeout(timeout);
465
+ clearTimeout(pollTimer);
466
+ server.close();
467
+ };
468
+ const resolve = (result) => {
469
+ if (settled) return;
470
+ finish();
471
+ rawResolve(result);
472
+ };
473
+ const reject = (error) => {
474
+ if (settled) return;
475
+ finish();
476
+ rawReject(error);
477
+ };
410
478
  const timeout = setTimeout(
411
479
  () => {
412
- server.close();
413
480
  reject(new Error("Authentication timed out. Please try again."));
414
481
  },
415
482
  5 * 60 * 1e3
416
483
  );
484
+ const poll2 = async () => {
485
+ if (settled) return;
486
+ const outcome = await pollPickup(baseUrl, pickupCode, state);
487
+ if (settled) return;
488
+ if (outcome.done) {
489
+ if ("result" in outcome) resolve(outcome.result);
490
+ else reject(new Error(`Authentication failed: ${outcome.error}`));
491
+ return;
492
+ }
493
+ if (!outcome.stop) pollTimer = setTimeout(() => void poll2(), PICKUP_POLL_MS);
494
+ };
417
495
  const server = http.createServer((req, res) => {
418
496
  void (async () => {
419
497
  const url = new URL(req.url || "/", "http://127.0.0.1");
@@ -436,44 +514,37 @@ async function browserAuth(baseUrl, onAuthUrl) {
436
514
  if (error) {
437
515
  res.writeHead(200, { "Content-Type": "text/html" });
438
516
  res.end(getErrorHtml(error));
439
- clearTimeout(timeout);
440
- server.close();
441
517
  reject(new Error(`Authentication failed: ${error}`));
442
518
  return;
443
519
  }
444
520
  if (!orgApiKey) {
445
521
  res.writeHead(200, { "Content-Type": "text/html" });
446
522
  res.end(getErrorHtml("No token received"));
447
- clearTimeout(timeout);
448
- server.close();
449
523
  reject(new Error("No authentication token received"));
450
524
  return;
451
525
  }
452
526
  res.writeHead(200, { "Content-Type": "text/html" });
453
527
  res.end(getSuccessHtml());
454
- clearTimeout(timeout);
455
- server.close();
456
528
  resolve({ orgApiKey, organizationName, expiresAt });
457
529
  })().catch((error) => {
458
530
  res.writeHead(500, { "Content-Type": "text/html" });
459
531
  res.end(getErrorHtml("Authentication callback failed"));
460
- clearTimeout(timeout);
461
- server.close();
462
532
  reject(error instanceof Error ? error : new Error(String(error)));
463
533
  });
464
534
  });
465
535
  server.listen(0, "127.0.0.1", () => {
466
536
  const address = server.address();
467
537
  if (!address || typeof address === "string") {
468
- clearTimeout(timeout);
469
538
  reject(new Error("Failed to start local auth server"));
470
539
  return;
471
540
  }
472
541
  const callbackUrl = `http://127.0.0.1:${address.port}/callback`;
473
- const authUrl = `${baseUrl}/cli-auth?callback=${encodeURIComponent(callbackUrl)}&state=${encodeURIComponent(state)}`;
542
+ const authUrl = `${baseUrl}/cli-auth?pickup=${pickupHash}&callback=${encodeURIComponent(callbackUrl)}&state=${encodeURIComponent(state)}`;
474
543
  onAuthUrl?.(authUrl);
544
+ onPairingCode?.(pairingCode(pickupHash));
475
545
  open(authUrl).catch(() => {
476
546
  });
547
+ pollTimer = setTimeout(() => void poll2(), PICKUP_POLL_MS);
477
548
  });
478
549
  });
479
550
  }
@@ -538,6 +609,7 @@ var NOT_SENT_CODES = /* @__PURE__ */ new Set([
538
609
  var SECRET_PATTERNS = [
539
610
  [/conto_claim_[A-Za-z0-9]+/g, "conto_claim_[redacted]"],
540
611
  [/conto_agent_[A-Za-z0-9]+/g, "conto_agent_[redacted]"],
612
+ [/conto_setupreq_[A-Za-z0-9]+/g, "conto_setupreq_[redacted]"],
541
613
  [/conto_setup_[A-Za-z0-9]+/g, "conto_setup_[redacted]"],
542
614
  [/conto_[A-Fa-f0-9]{16,}/g, "conto_[redacted]"],
543
615
  [/(Bearer\s+)\S+/gi, "$1[redacted]"]
@@ -710,8 +782,8 @@ var ApiClient = class {
710
782
  async orgToken() {
711
783
  return typeof this.orgApiKey === "function" ? this.orgApiKey() : this.orgApiKey;
712
784
  }
713
- async request(method, path3, options) {
714
- const url = `${this.baseUrl}${path3}`;
785
+ async request(method, path4, options) {
786
+ const url = `${this.baseUrl}${path4}`;
715
787
  const authType = options?.auth || "sdk";
716
788
  const token = authType === "org" ? await this.orgToken() : this.apiKey;
717
789
  const headers = {
@@ -734,7 +806,7 @@ var ApiClient = class {
734
806
  const contentType = response.headers.get("content-type") || "";
735
807
  if (!contentType.includes("application/json")) {
736
808
  const error = new Error(
737
- response.status === 404 ? `API endpoint not found: ${path3}` : `API returned non-JSON response (${response.status})`
809
+ response.status === 404 ? `API endpoint not found: ${path4}` : `API returned non-JSON response (${response.status})`
738
810
  );
739
811
  error.code = response.status === 404 ? "NOT_FOUND" : "INVALID_RESPONSE";
740
812
  error.status = response.status;
@@ -768,11 +840,11 @@ var ApiClient = class {
768
840
  * POST a payment call through requestJson, which refuses redirects and says
769
841
  * whether a failed call may have reached the server.
770
842
  */
771
- async paymentPost(path3, body) {
843
+ async paymentPost(path4, body) {
772
844
  let response;
773
845
  try {
774
846
  response = await requestJson({
775
- url: apiUrl(this.baseUrl, path3),
847
+ url: apiUrl(this.baseUrl, path4),
776
848
  method: "POST",
777
849
  bearer: this.apiKey,
778
850
  body,
@@ -785,7 +857,7 @@ var ApiClient = class {
785
857
  throw err;
786
858
  }
787
859
  if (!response.isJson) {
788
- throw response.status === 404 ? paymentCallError(`API endpoint not found: ${path3}`, "NOT_FOUND", 404, false) : paymentCallError(
860
+ throw response.status === 404 ? paymentCallError(`API endpoint not found: ${path4}`, "NOT_FOUND", 404, false) : paymentCallError(
789
861
  `API returned non-JSON response (${response.status})`,
790
862
  "INVALID_RESPONSE",
791
863
  response.status,
@@ -804,10 +876,10 @@ var ApiClient = class {
804
876
  }
805
877
  return response.data;
806
878
  }
807
- async spendingDownload(path3, owner = false) {
879
+ async spendingDownload(path4, owner = false) {
808
880
  const token = owner ? await this.orgToken() : this.apiKey;
809
881
  const response = await fetch(
810
- `${this.baseUrl}/api/${owner ? "spending" : path3.startsWith("purchases") ? "sdk/spending" : "sdk"}/${path3}`,
882
+ `${this.baseUrl}/api/${owner ? "spending" : path4.startsWith("purchases") ? "sdk/spending" : "sdk"}/${path4}`,
811
883
  {
812
884
  headers: { Authorization: `Bearer ${token}` },
813
885
  signal: AbortSignal.timeout(3e4),
@@ -817,10 +889,10 @@ var ApiClient = class {
817
889
  if (!response.ok) throw new Error(`Export failed (${response.status}). No file was saved.`);
818
890
  return new Uint8Array(await response.arrayBuffer());
819
891
  }
820
- spending(method, path3, body, owner = false) {
892
+ spending(method, path4, body, owner = false) {
821
893
  return this.request(
822
894
  method,
823
- `/api/${owner ? "spending" : path3.startsWith("purchases") ? "sdk/spending" : "sdk"}/${path3}`,
895
+ `/api/${owner ? "spending" : path4.startsWith("purchases") ? "sdk/spending" : "sdk"}/${path4}`,
824
896
  { body, auth: owner ? "org" : "sdk" }
825
897
  );
826
898
  }
@@ -1270,7 +1342,7 @@ function reviewAccessFor(baseUrl, orgApiKey) {
1270
1342
  // src/lib/project-state.ts
1271
1343
  import fs from "fs";
1272
1344
  import path from "path";
1273
- import { createHash, randomBytes as randomBytes2 } from "crypto";
1345
+ import { createHash as createHash2, randomBytes as randomBytes2 } from "crypto";
1274
1346
  var PROJECT_STATE_DIR = ".conto";
1275
1347
  var PRIVATE_DIR_MODE = 448;
1276
1348
  var PRIVATE_FILE_MODE = 384;
@@ -1329,11 +1401,11 @@ function removeProjectStateFile(cwd, fileName) {
1329
1401
  }
1330
1402
  }
1331
1403
  function fingerprintSecret(secret) {
1332
- return `sha256:${createHash("sha256").update(secret).digest("hex").slice(0, 16)}`;
1404
+ return `sha256:${createHash2("sha256").update(secret).digest("hex").slice(0, 16)}`;
1333
1405
  }
1334
1406
 
1335
1407
  // src/lib/init-checkpoint.ts
1336
- import { createHash as createHash2, randomBytes as randomBytes3 } from "crypto";
1408
+ import { createHash as createHash3, randomBytes as randomBytes3 } from "crypto";
1337
1409
  var INIT_CHECKPOINT_NAME = "init-checkpoint.json";
1338
1410
  var INIT_CHECKPOINT_FILE = projectStateFile(INIT_CHECKPOINT_NAME);
1339
1411
  var STEP_ORDER = ["wallet", "faucet", "agent", "walletLink", "policy", "sdkKey"];
@@ -1354,7 +1426,7 @@ function canonicalJson(value) {
1354
1426
  return JSON.stringify(value);
1355
1427
  }
1356
1428
  function configurationHash(request) {
1357
- return `sha256:${createHash2("sha256").update(canonicalJson(request)).digest("hex")}`;
1429
+ return `sha256:${createHash3("sha256").update(canonicalJson(request)).digest("hex")}`;
1358
1430
  }
1359
1431
  function newOperationId() {
1360
1432
  return randomBytes3(8).toString("hex");
@@ -1458,13 +1530,13 @@ async function provisionOrganization(input) {
1458
1530
  checkpoint.binding.organization.credentialFingerprint = input.organization.credentialFingerprint;
1459
1531
  if (input.organization.name) checkpoint.binding.organization.name = input.organization.name;
1460
1532
  };
1461
- const stopped = (stop) => {
1462
- if (stop.status !== "refused") {
1463
- checkpoint.failedStep = stop.step;
1464
- checkpoint.status = stop.status === "reconciliation_required" || stop.status === "owner_action_required" ? stop.status : "partial";
1533
+ const stopped = (stop2) => {
1534
+ if (stop2.status !== "refused") {
1535
+ checkpoint.failedStep = stop2.step;
1536
+ checkpoint.status = stop2.status === "reconciliation_required" || stop2.status === "owner_action_required" ? stop2.status : "partial";
1465
1537
  persist();
1466
1538
  }
1467
- return { kind: "stopped", stop, resources };
1539
+ return { kind: "stopped", stop: stop2, resources };
1468
1540
  };
1469
1541
  const refuse2 = (step, code, message) => stopped({ status: "refused", step, code, message });
1470
1542
  const credentialRejected = (step, failure) => failure.httpStatus === 401 || failure.httpStatus === 403 ? stopped({
@@ -2156,9 +2228,9 @@ var SetupResourcesClient = class {
2156
2228
  }
2157
2229
  baseUrl;
2158
2230
  orgApiKey;
2159
- async send(method, path3, body, headers, bearer = this.orgApiKey) {
2231
+ async send(method, path4, body, headers, bearer = this.orgApiKey) {
2160
2232
  return requestJson({
2161
- url: apiUrl(this.baseUrl, path3),
2233
+ url: apiUrl(this.baseUrl, path4),
2162
2234
  method,
2163
2235
  bearer,
2164
2236
  body,
@@ -2166,19 +2238,19 @@ var SetupResourcesClient = class {
2166
2238
  timeoutMs: REQUEST_TIMEOUT_MS2
2167
2239
  });
2168
2240
  }
2169
- async create(path3, body, label, parse, headers) {
2241
+ async create(path4, body, label, parse, headers) {
2170
2242
  let response;
2171
2243
  try {
2172
- response = await this.send("POST", path3, body, headers);
2244
+ response = await this.send("POST", path4, body, headers);
2173
2245
  } catch (error) {
2174
2246
  return classifyTransport(error);
2175
2247
  }
2176
2248
  return classifyCreate(response, label, parse);
2177
2249
  }
2178
- async read(path3, label, parse, bearer) {
2250
+ async read(path4, label, parse, bearer) {
2179
2251
  let response;
2180
2252
  try {
2181
- response = await this.send("GET", path3, void 0, void 0, bearer);
2253
+ response = await this.send("GET", path4, void 0, void 0, bearer);
2182
2254
  } catch (error) {
2183
2255
  return { ok: false, notFound: false, failure: failureFromTransport(error) };
2184
2256
  }
@@ -2359,6 +2431,8 @@ var HEADLESS_DEFAULT_NAME = "conto-agent";
2359
2431
  var HEADLESS_DEFAULT_TYPE = "CUSTOM";
2360
2432
  var HEADLESS_DEFAULT_LIMIT = 500;
2361
2433
  var SDK_KEY_NAME = "CLI Quickstart Key";
2434
+ var FULL_CLI = "npx @conto_finance/create-conto-agent";
2435
+ var MCP_ADD_LINE = `claude mcp add conto -- npx -y @conto_finance/create-conto-agent mcp`;
2362
2436
  function failInit(message, details = {}, exitCode = INIT_EXIT_CODES.failed) {
2363
2437
  if (isJsonMode()) {
2364
2438
  printJson({ ok: false, error: message, ...details });
@@ -2400,7 +2474,9 @@ function resumeCommand(baseUrl, options) {
2400
2474
  ...isJsonMode() ? ["--json"] : []
2401
2475
  ].join(" ");
2402
2476
  }
2403
- var RESUME_CREDENTIAL_HINT = "Resume with the same organization: pass --api-key or set CONTO_ORG_API_KEY, or run it in a terminal to sign in with the browser.";
2477
+ function resumeCredentialHint() {
2478
+ return isJsonMode() ? "Resume with the same organization: pass --api-key or set CONTO_ORG_API_KEY, or run it in a terminal without --json to sign in with the browser." : "Resume with the same organization: pass --api-key or set CONTO_ORG_API_KEY, or run it in a terminal to sign in with the browser.";
2479
+ }
2404
2480
  function refuse(message, details) {
2405
2481
  failInit(message, { status: "refused", ...details }, INIT_EXIT_CODES.refused);
2406
2482
  }
@@ -2442,6 +2518,22 @@ function storedSdkKeyFor(cwd, baseUrl, agentId) {
2442
2518
  return void 0;
2443
2519
  }
2444
2520
  }
2521
+ var ORG_KEY_NOT_SAVED = 'The organization key was used for this setup only. It was not saved in ~/.conto/config.json. For commands that need it, set CONTO_ORG_API_KEY or run "conto login".';
2522
+ function isSameServer(a, b) {
2523
+ try {
2524
+ return normalizeBaseUrl(a) === normalizeBaseUrl(b);
2525
+ } catch {
2526
+ return false;
2527
+ }
2528
+ }
2529
+ function orgKeySavedFor(baseUrl) {
2530
+ const server = loadGlobalConfig().server;
2531
+ if (!server?.orgApiKey || !isSameServer(server.baseUrl || DEFAULT_BASE_URL, baseUrl)) return {};
2532
+ return { orgApiKey: server.orgApiKey, orgApiKeyExpiresAt: server.orgApiKeyExpiresAt };
2533
+ }
2534
+ function isSavedOrgApiKey(orgApiKey, baseUrl) {
2535
+ return orgKeySavedFor(baseUrl).orgApiKey === orgApiKey;
2536
+ }
2445
2537
  function organizationBindingProblem(checkpoint, credential) {
2446
2538
  const organization = checkpoint.binding.organization;
2447
2539
  if (organization.anchor) return null;
@@ -2454,7 +2546,7 @@ function organizationBindingProblem(checkpoint, credential) {
2454
2546
  }
2455
2547
  async function runOrganizationInit(options) {
2456
2548
  const cwd = process.cwd();
2457
- const interactive2 = Boolean(process.stdin.isTTY && process.stdout.isTTY);
2549
+ const interactive2 = Boolean(process.stdin.isTTY && process.stdout.isTTY) && !isJsonMode();
2458
2550
  const providedOrgApiKey = options.apiKey || process.env.CONTO_ORG_API_KEY;
2459
2551
  if (options.resume && options.restart) {
2460
2552
  refuse("Use --resume or --restart, not both.", { code: "INVALID_OPTIONS" });
@@ -2499,9 +2591,9 @@ async function runOrganizationInit(options) {
2499
2591
  if (!interactive2 && !providedOrgApiKey) {
2500
2592
  failInit(
2501
2593
  [
2502
- resumeFrom ? "Resuming setup without an interactive terminal needs an organization API key." : "create-conto-agent needs an interactive terminal for the setup wizard.",
2594
+ isJsonMode() ? "A --json run does not prompt or open a browser, so it needs an organization API key." : resumeFrom ? "Resuming setup without an interactive terminal needs an organization API key." : "create-conto-agent needs an interactive terminal for the setup wizard.",
2503
2595
  "Headless options: --sandbox, or --api-key <org-api-key>.",
2504
- "Add --json for machine-readable output."
2596
+ ...isJsonMode() ? [] : ["Add --json for machine-readable output."]
2505
2597
  ].join(" "),
2506
2598
  { headlessOptions: ["--sandbox", "--api-key <org-api-key>"] }
2507
2599
  );
@@ -2626,13 +2718,30 @@ async function runOrganizationInit(options) {
2626
2718
  let orgApiKey;
2627
2719
  let orgApiKeyExpiresAt;
2628
2720
  let organizationName;
2721
+ let saveOrgApiKey = true;
2629
2722
  if (providedOrgApiKey) {
2630
2723
  orgApiKey = providedOrgApiKey;
2631
2724
  printSuccess("Using provided organization API key");
2725
+ saveOrgApiKey = isSavedOrgApiKey(providedOrgApiKey, baseUrl);
2726
+ if (!saveOrgApiKey && interactive2) {
2727
+ const save = await p.confirm({
2728
+ message: "Save this organization key in ~/.conto/config.json? Other projects of this organization on this machine can then use it.",
2729
+ initialValue: false
2730
+ });
2731
+ if (p.isCancel(save)) {
2732
+ p.cancel("Setup cancelled.");
2733
+ process.exit(0);
2734
+ }
2735
+ saveOrgApiKey = save === true;
2736
+ }
2632
2737
  } else {
2633
2738
  s.start("Opening browser to authenticate...");
2634
2739
  try {
2635
- const authResult = await browserAuth(baseUrl);
2740
+ const authResult = await browserAuth(
2741
+ baseUrl,
2742
+ void 0,
2743
+ (code) => s.message(`Waiting for the browser. Connect only if it shows ${code}`)
2744
+ );
2636
2745
  orgApiKey = authResult.orgApiKey;
2637
2746
  orgApiKeyExpiresAt = authResult.expiresAt || void 0;
2638
2747
  organizationName = authResult.organizationName || void 0;
@@ -2763,6 +2872,8 @@ async function runOrganizationInit(options) {
2763
2872
  },
2764
2873
  options
2765
2874
  );
2875
+ const previousOrgKey = orgKeySavedFor(baseUrl);
2876
+ const savedOrgKey = !providedOrgApiKey ? { orgApiKey, orgApiKeyExpiresAt } : saveOrgApiKey && previousOrgKey.orgApiKey !== orgApiKey ? { orgApiKey } : previousOrgKey;
2766
2877
  saveGlobalConfig({
2767
2878
  agent: { id: agent.id, name: agent.name, type: agentType },
2768
2879
  network: {
@@ -2778,7 +2889,7 @@ async function runOrganizationInit(options) {
2778
2889
  address: wallet.address,
2779
2890
  custodyMode: wallet.custodyMode ?? "MANAGED"
2780
2891
  },
2781
- server: { baseUrl, apiKey: sdkKey.key, orgApiKey, orgApiKeyExpiresAt }
2892
+ server: { baseUrl, apiKey: sdkKey.key, ...savedOrgKey }
2782
2893
  });
2783
2894
  removeCheckpoint(cwd);
2784
2895
  let cliResolves = false;
@@ -2802,10 +2913,10 @@ async function runOrganizationInit(options) {
2802
2913
  const cli = cliResolves ? "npx conto" : "npx @conto_finance/create-conto-agent";
2803
2914
  const exampleKept = keptFiles.includes("example.mjs");
2804
2915
  const nextSteps = [
2805
- `${cli} doctor`,
2916
+ `${FULL_CLI} doctor`,
2806
2917
  ...exampleKept ? [] : ["node example.mjs"],
2807
- `${cli} pay <address> <amount>`,
2808
- `${cli} mcp`
2918
+ `${FULL_CLI} pay <address> <amount>`,
2919
+ MCP_ADD_LINE
2809
2920
  ];
2810
2921
  if (isJsonMode()) {
2811
2922
  printJson({
@@ -2822,7 +2933,8 @@ async function runOrganizationInit(options) {
2822
2933
  },
2823
2934
  credentials: {
2824
2935
  storedIn: ".env.local",
2825
- sdkKeyEnv: "CONTO_API_KEY"
2936
+ sdkKeyEnv: "CONTO_API_KEY",
2937
+ orgApiKeySaved: saveOrgApiKey
2826
2938
  },
2827
2939
  files: PROJECT_FILES.filter((file) => !keptFiles.includes(file)),
2828
2940
  ...keptFiles.length > 0 ? { keptFiles } : {},
@@ -2843,6 +2955,10 @@ async function runOrganizationInit(options) {
2843
2955
  }
2844
2956
  console.log("");
2845
2957
  printKeptFiles(keptFiles);
2958
+ if (!saveOrgApiKey) {
2959
+ printInfo(ORG_KEY_NOT_SAVED);
2960
+ console.log("");
2961
+ }
2846
2962
  console.log(
2847
2963
  ` ${chalk2.dim("Wallet:")} ${wallet.address} (${chain.name}${chain.testnet ? " testnet" : ""}, ${wallet.custodyMode ?? "MANAGED"} custody)`
2848
2964
  );
@@ -2861,7 +2977,7 @@ async function runOrganizationInit(options) {
2861
2977
  console.log(` ${step++}. Run the example: ${chalk2.cyan("node example.mjs")}`);
2862
2978
  }
2863
2979
  console.log(` ${step++}. Make a payment: ${chalk2.cyan(`${cli} pay <address> <amount>`)}`);
2864
- console.log(` ${step++}. Connect Claude: ${chalk2.cyan(`${cli} mcp`)}`);
2980
+ console.log(` ${step++}. Add to Claude Code: ${chalk2.cyan(MCP_ADD_LINE)}`);
2865
2981
  if (!cliResolves) {
2866
2982
  printInfo(
2867
2983
  'Tip: "npx conto <command>" works after: npm install --save-dev @conto_finance/create-conto-agent'
@@ -2870,39 +2986,39 @@ async function runOrganizationInit(options) {
2870
2986
  console.log("");
2871
2987
  }
2872
2988
  function reportStoppedSetup(input) {
2873
- const { stop, checkpoint } = input;
2874
- const label = STEP_LABELS[stop.step];
2989
+ const { stop: stop2, checkpoint } = input;
2990
+ const label = STEP_LABELS[stop2.step];
2875
2991
  const failure = {
2876
- code: stop.code,
2877
- message: stop.message,
2878
- ...stop.httpStatus !== void 0 ? { httpStatus: stop.httpStatus } : {}
2992
+ code: stop2.code,
2993
+ message: stop2.message,
2994
+ ...stop2.httpStatus !== void 0 ? { httpStatus: stop2.httpStatus } : {}
2879
2995
  };
2880
- if (stop.status === "failed") {
2996
+ if (stop2.status === "failed") {
2881
2997
  removeCheckpoint(input.cwd);
2882
- failInit(`Setup failed at the ${label} step: ${stop.message}`, {
2998
+ failInit(`Setup failed at the ${label} step: ${stop2.message}`, {
2883
2999
  status: "failed",
2884
- code: stop.code,
2885
- failedStep: stop.step,
3000
+ code: stop2.code,
3001
+ failedStep: stop2.step,
2886
3002
  failure,
2887
- ...stop.retryAfterSeconds !== void 0 ? { retryAfterSeconds: stop.retryAfterSeconds } : {}
3003
+ ...stop2.retryAfterSeconds !== void 0 ? { retryAfterSeconds: stop2.retryAfterSeconds } : {}
2888
3004
  });
2889
3005
  }
2890
- const exitCode = stop.status === "refused" ? INIT_EXIT_CODES.refused : stop.status === "partial" ? INIT_EXIT_CODES.partial : INIT_EXIT_CODES.actionRequired;
3006
+ const exitCode = stop2.status === "refused" ? INIT_EXIT_CODES.refused : stop2.status === "partial" ? INIT_EXIT_CODES.partial : INIT_EXIT_CODES.actionRequired;
2891
3007
  const completedSteps = STEP_ORDER.filter((step) => checkpoint.steps[step].status === "done");
2892
3008
  const pendingSteps = STEP_ORDER.filter(
2893
3009
  (step) => step !== "faucet" && !["done", "skipped"].includes(checkpoint.steps[step].status)
2894
3010
  );
2895
3011
  const credentialsWritten = checkpoint.steps.sdkKey.status === "done";
2896
3012
  const command = resumeCommand(input.baseUrl, input.options);
2897
- const resumable = stop.status !== "refused";
3013
+ const resumable = stop2.status !== "refused";
2898
3014
  if (isJsonMode()) {
2899
3015
  printJson({
2900
3016
  ok: false,
2901
3017
  mode: "organization",
2902
- status: stop.status,
2903
- code: stop.code,
2904
- error: stop.message,
2905
- failedStep: stop.step,
3018
+ status: stop2.status,
3019
+ code: stop2.code,
3020
+ error: stop2.message,
3021
+ failedStep: stop2.step,
2906
3022
  failure,
2907
3023
  completedSteps,
2908
3024
  pendingSteps,
@@ -2911,21 +3027,21 @@ function reportStoppedSetup(input) {
2911
3027
  checkpoint: INIT_CHECKPOINT_FILE,
2912
3028
  resume: resumable ? {
2913
3029
  command,
2914
- credential: RESUME_CREDENTIAL_HINT,
2915
- ...stop.reconciliation?.notBefore ? { notBefore: stop.reconciliation.notBefore } : {}
3030
+ credential: resumeCredentialHint(),
3031
+ ...stop2.reconciliation?.notBefore ? { notBefore: stop2.reconciliation.notBefore } : {}
2916
3032
  } : null,
2917
- ...stop.retryAfterSeconds !== void 0 ? { retryAfterSeconds: stop.retryAfterSeconds } : {},
2918
- ...stop.reconciliation ? { reconciliation: stop.reconciliation } : {},
2919
- ...stop.ownerAction ? { ownerAction: stop.ownerAction } : {},
3033
+ ...stop2.retryAfterSeconds !== void 0 ? { retryAfterSeconds: stop2.retryAfterSeconds } : {},
3034
+ ...stop2.reconciliation ? { reconciliation: stop2.reconciliation } : {},
3035
+ ...stop2.ownerAction ? { ownerAction: stop2.ownerAction } : {},
2920
3036
  ...input.discarded ? { discardedSetup: input.discarded } : {}
2921
3037
  });
2922
3038
  process.exit(exitCode);
2923
3039
  }
2924
3040
  console.log("");
2925
3041
  printError(
2926
- stop.status === "refused" ? `Resume refused at the ${label} step.` : `Setup stopped at the ${label} step. It is not complete.`
3042
+ stop2.status === "refused" ? `Resume refused at the ${label} step.` : `Setup stopped at the ${label} step. It is not complete.`
2927
3043
  );
2928
- printInfo(`${stop.message}${stop.httpStatus ? ` (HTTP ${stop.httpStatus})` : ""}`);
3044
+ printInfo(`${stop2.message}${stop2.httpStatus ? ` (HTTP ${stop2.httpStatus})` : ""}`);
2929
3045
  const resources = recordedResources(checkpoint);
2930
3046
  if (completedSteps.length > 0) {
2931
3047
  console.log("");
@@ -2947,26 +3063,26 @@ function reportStoppedSetup(input) {
2947
3063
  if (!credentialsWritten) {
2948
3064
  printInfo("No agent credentials were written. The agent cannot pay until setup finishes.");
2949
3065
  }
2950
- if (stop.reconciliation) {
2951
- printWarning(stop.reconciliation.reason);
2952
- printInfo(stop.reconciliation.action);
2953
- if (stop.reconciliation.resourceIds?.length) {
2954
- printInfo(`Records: ${stop.reconciliation.resourceIds.join(", ")}`);
3066
+ if (stop2.reconciliation) {
3067
+ printWarning(stop2.reconciliation.reason);
3068
+ printInfo(stop2.reconciliation.action);
3069
+ if (stop2.reconciliation.resourceIds?.length) {
3070
+ printInfo(`Records: ${stop2.reconciliation.resourceIds.join(", ")}`);
2955
3071
  }
2956
3072
  }
2957
- if (stop.ownerAction) {
2958
- printWarning(stop.ownerAction.action);
2959
- if (stop.ownerAction.dashboardUrl) printInfo(`Open: ${stop.ownerAction.dashboardUrl}`);
2960
- if (stop.ownerAction.api) {
3073
+ if (stop2.ownerAction) {
3074
+ printWarning(stop2.ownerAction.action);
3075
+ if (stop2.ownerAction.dashboardUrl) printInfo(`Open: ${stop2.ownerAction.dashboardUrl}`);
3076
+ if (stop2.ownerAction.api) {
2961
3077
  printInfo(
2962
- `API: ${stop.ownerAction.api.method} ${stop.ownerAction.api.path} (organization key with ${stop.ownerAction.api.requiredScope})`
3078
+ `API: ${stop2.ownerAction.api.method} ${stop2.ownerAction.api.path} (organization key with ${stop2.ownerAction.api.requiredScope})`
2963
3079
  );
2964
3080
  }
2965
3081
  }
2966
3082
  console.log("");
2967
3083
  if (resumable) {
2968
3084
  printInfo(`Resume: ${command}`);
2969
- printInfo(RESUME_CREDENTIAL_HINT);
3085
+ printInfo(resumeCredentialHint());
2970
3086
  } else {
2971
3087
  printInfo(`The unfinished setup is kept in ${INIT_CHECKPOINT_FILE}. Nothing was changed.`);
2972
3088
  }
@@ -3097,35 +3213,38 @@ async function runSandboxInit(options) {
3097
3213
  options
3098
3214
  );
3099
3215
  const exampleKept = keptFiles.includes("example.mjs");
3100
- saveGlobalConfig({
3101
- agent: {
3102
- id: sandbox.agent.id,
3103
- name: sandbox.agent.name,
3104
- type: options.type || "CUSTOM"
3105
- },
3106
- network: {
3107
- chain: sandbox.wallet.chainId,
3108
- chainId: sandbox.wallet.chainId,
3109
- rpcUrl: chain?.rpcUrl || "",
3110
- explorerUrl: chain?.explorerUrl || "",
3111
- currency: chain?.currency || sandbox.wallet.currency,
3112
- testnet: true
3113
- },
3114
- wallet: {
3115
- id: sandbox.wallet.id,
3116
- address: sandbox.wallet.address,
3117
- custodyMode: sandbox.wallet.custodyMode
3118
- },
3119
- server: {
3120
- baseUrl,
3121
- apiKey: sandbox.credentials.sdkKey,
3122
- orgApiKey: sandbox.credentials.apiKey
3123
- },
3124
- sandbox: {
3125
- mode: "test",
3126
- expiresAt: sandbox.expiresAt
3127
- }
3128
- });
3216
+ const existingGlobal = loadGlobalConfig();
3217
+ const keepGlobal = Boolean(existingGlobal.server?.apiKey || existingGlobal.server?.orgApiKey) && existingGlobal.sandbox?.mode !== "test";
3218
+ if (!keepGlobal)
3219
+ saveGlobalConfig({
3220
+ agent: {
3221
+ id: sandbox.agent.id,
3222
+ name: sandbox.agent.name,
3223
+ type: options.type || "CUSTOM"
3224
+ },
3225
+ network: {
3226
+ chain: sandbox.wallet.chainId,
3227
+ chainId: sandbox.wallet.chainId,
3228
+ rpcUrl: chain?.rpcUrl || "",
3229
+ explorerUrl: chain?.explorerUrl || "",
3230
+ currency: chain?.currency || sandbox.wallet.currency,
3231
+ testnet: true
3232
+ },
3233
+ wallet: {
3234
+ id: sandbox.wallet.id,
3235
+ address: sandbox.wallet.address,
3236
+ custodyMode: sandbox.wallet.custodyMode
3237
+ },
3238
+ server: {
3239
+ baseUrl,
3240
+ apiKey: sandbox.credentials.sdkKey,
3241
+ orgApiKey: sandbox.credentials.apiKey
3242
+ },
3243
+ sandbox: {
3244
+ mode: "test",
3245
+ expiresAt: sandbox.expiresAt
3246
+ }
3247
+ });
3129
3248
  let cliResolves = hasLocalCliBin(cwd);
3130
3249
  if (!cliResolves && options.install !== false) {
3131
3250
  cliResolves = installCliLocally(cwd, sandbox.agent.name) === "installed";
@@ -3151,16 +3270,19 @@ async function runSandboxInit(options) {
3151
3270
  ...setupKeyFile ? [setupKeyFile] : []
3152
3271
  ],
3153
3272
  ...keptFiles.length > 0 ? { keptFiles } : {},
3273
+ ...keepGlobal ? { savedLoginKept: true } : {},
3154
3274
  claim: {
3155
- command: `${cli} sandbox claim --json`,
3275
+ command: `${FULL_CLI} sandbox claim --json`,
3156
3276
  credentialEnv: "CONTO_SANDBOX_API_KEY",
3157
3277
  ...sandbox.claim ? { method: sandbox.claim.method, endpoint: sandbox.claim.endpoint } : {}
3158
3278
  },
3159
3279
  nextSteps: [
3160
3280
  ...exampleKept ? [] : ["node example.mjs", "node example.mjs --resume REQUEST_ID"],
3161
- `${cli} doctor`,
3162
- `${cli} pay 0x742d35Cc6634C0532925a3b844Bc454e4438f44e 1 --purpose test`,
3163
- `${cli} sandbox claim --json`
3281
+ `${FULL_CLI} doctor`,
3282
+ `${FULL_CLI} pay 0x742d35Cc6634C0532925a3b844Bc454e4438f44e 1 --purpose test`,
3283
+ MCP_ADD_LINE,
3284
+ `${FULL_CLI} --connect --email <owner email> --json`,
3285
+ `${FULL_CLI} sandbox claim --json`
3164
3286
  ]
3165
3287
  });
3166
3288
  return;
@@ -3205,7 +3327,14 @@ async function runSandboxInit(options) {
3205
3327
  printInfo(
3206
3328
  "Sandbox test payments exercise policy checks, receipts, and spend tracking without an onchain transfer."
3207
3329
  );
3330
+ printInfo(`Add it to Claude Code: ${MCP_ADD_LINE}`);
3331
+ printInfo(
3332
+ `To set this agent up in a real account, run: ${FULL_CLI} --connect --email <owner email>`
3333
+ );
3208
3334
  printInfo(`To hand this sandbox to its owner before it expires, run: ${cli} sandbox claim`);
3335
+ if (keepGlobal) {
3336
+ printInfo("Your saved login in ~/.conto was kept. This sandbox is used from this folder only.");
3337
+ }
3209
3338
  console.log("");
3210
3339
  }
3211
3340
  function hasLocalCliBin(cwd) {
@@ -3439,6 +3568,556 @@ main().catch((err) => {
3439
3568
  `;
3440
3569
  }
3441
3570
 
3571
+ // src/commands/connect.ts
3572
+ import chalk3 from "chalk";
3573
+ import fs3 from "fs";
3574
+ import path3 from "path";
3575
+ var SETUP_REQUEST_PATH = "/api/agents/setup-requests";
3576
+ var SETUP_REQUEST_FILE = path3.join(".conto", "setup-request.json");
3577
+ var FULL_CLI2 = "npx @conto_finance/create-conto-agent";
3578
+ var DEFAULT_BASE_URL2 = "https://conto.finance";
3579
+ var DEFAULT_AGENT_NAME = "conto-agent";
3580
+ var CLIENT_NAME = "create-conto-agent";
3581
+ var REQUEST_TIMEOUT_MS3 = 3e4;
3582
+ var DEVICE_CODE_PATTERN = /^conto_setupreq_[a-f0-9]{64}$/;
3583
+ var SANDBOX_KEY_PATTERN = /^conto_[a-f0-9]{64}$/;
3584
+ var CONNECT_EXIT_CODES = {
3585
+ done: 0,
3586
+ failed: 1,
3587
+ refused: 2,
3588
+ stillWaiting: 4
3589
+ };
3590
+ var ConnectStop = class extends Error {
3591
+ constructor(exitCode, code, message, details = {}) {
3592
+ super(message);
3593
+ this.exitCode = exitCode;
3594
+ this.code = code;
3595
+ this.details = details;
3596
+ }
3597
+ exitCode;
3598
+ code;
3599
+ details;
3600
+ };
3601
+ function stop(error) {
3602
+ if (isJsonMode()) {
3603
+ printJson({
3604
+ ok: false,
3605
+ mode: "connect",
3606
+ code: error.code,
3607
+ error: error.message,
3608
+ ...error.details
3609
+ });
3610
+ } else {
3611
+ console.error(chalk3.red(` ${error.message}`));
3612
+ const next = error.details.nextStep;
3613
+ if (typeof next === "string") console.error(` ${next}`);
3614
+ }
3615
+ process.exit(error.exitCode);
3616
+ }
3617
+ function loadSavedRequest(cwd) {
3618
+ try {
3619
+ const raw = JSON.parse(fs3.readFileSync(path3.join(cwd, SETUP_REQUEST_FILE), "utf8"));
3620
+ if (raw && typeof raw.baseUrl === "string" && typeof raw.deviceCode === "string" && DEVICE_CODE_PATTERN.test(raw.deviceCode) && typeof raw.userCode === "string" && typeof raw.link === "string" && typeof raw.expiresAt === "string") {
3621
+ return {
3622
+ intervalSeconds: 5,
3623
+ agentName: DEFAULT_AGENT_NAME,
3624
+ emailed: false,
3625
+ sandboxRules: false,
3626
+ ...raw
3627
+ };
3628
+ }
3629
+ } catch {
3630
+ }
3631
+ return null;
3632
+ }
3633
+ function saveRequest(cwd, request) {
3634
+ ensureContoDirGitignored(cwd);
3635
+ const dir = path3.join(cwd, ".conto");
3636
+ fs3.mkdirSync(dir, { recursive: true, mode: 448 });
3637
+ const file = path3.join(cwd, SETUP_REQUEST_FILE);
3638
+ fs3.writeFileSync(file, JSON.stringify(request, null, 2) + "\n", { mode: 384 });
3639
+ fs3.chmodSync(file, 384);
3640
+ }
3641
+ function removeSavedRequest(cwd) {
3642
+ try {
3643
+ fs3.unlinkSync(path3.join(cwd, SETUP_REQUEST_FILE));
3644
+ } catch {
3645
+ }
3646
+ }
3647
+ function isExpired(request) {
3648
+ const at = Date.parse(request.expiresAt);
3649
+ return !Number.isFinite(at) || at <= Date.now();
3650
+ }
3651
+ async function call(input) {
3652
+ try {
3653
+ return await requestJson({
3654
+ url: apiUrl(input.baseUrl, input.apiPath),
3655
+ method: input.method,
3656
+ bearer: input.bearer,
3657
+ body: input.body,
3658
+ timeoutMs: REQUEST_TIMEOUT_MS3
3659
+ });
3660
+ } catch (error) {
3661
+ const message = error instanceof HttpTransportError || error instanceof Error ? error.message : String(error);
3662
+ throw new ConnectStop(
3663
+ CONNECT_EXIT_CODES.failed,
3664
+ "NETWORK_ERROR",
3665
+ `Could not reach ${input.baseUrl}. ${message}`
3666
+ );
3667
+ }
3668
+ }
3669
+ function refusal(response, fallback) {
3670
+ const code = responseErrorCode(response, "REQUEST_FAILED");
3671
+ const message = responseErrorMessage(response, fallback);
3672
+ if (response.status === 429) {
3673
+ const retry = retryAfterSeconds(response.headers, response.data);
3674
+ return new ConnectStop(CONNECT_EXIT_CODES.failed, "RATE_LIMITED", message, {
3675
+ ...retry !== void 0 ? { retryAfterSeconds: retry } : {}
3676
+ });
3677
+ }
3678
+ return new ConnectStop(
3679
+ response.status >= 500 ? CONNECT_EXIT_CODES.failed : CONNECT_EXIT_CODES.refused,
3680
+ code,
3681
+ message
3682
+ );
3683
+ }
3684
+ async function createRequest(input) {
3685
+ const response = await call({
3686
+ baseUrl: input.baseUrl,
3687
+ method: "POST",
3688
+ apiPath: SETUP_REQUEST_PATH,
3689
+ body: {
3690
+ agentName: input.agentName,
3691
+ clientName: CLIENT_NAME,
3692
+ ...input.email ? { email: input.email } : {},
3693
+ ...input.sandboxKey ? { sandboxApiKey: input.sandboxKey } : {}
3694
+ }
3695
+ });
3696
+ if (response.status !== 201 && response.status !== 200) {
3697
+ throw refusal(response, `Setup request failed (HTTP ${response.status}).`);
3698
+ }
3699
+ const body = response.data;
3700
+ const deviceCode = body?.deviceCode;
3701
+ const userCode = body?.userCode;
3702
+ const link = body?.verificationUrlComplete;
3703
+ const expiresAt = body?.expiresAt;
3704
+ if (typeof deviceCode !== "string" || !DEVICE_CODE_PATTERN.test(deviceCode) || typeof userCode !== "string" || typeof link !== "string" || typeof expiresAt !== "string") {
3705
+ throw new ConnectStop(
3706
+ CONNECT_EXIT_CODES.failed,
3707
+ "UNEXPECTED_RESPONSE",
3708
+ "The server answered without a setup link. Is this a Conto server with agent setup requests?"
3709
+ );
3710
+ }
3711
+ if (new URL(link).origin !== new URL(input.baseUrl).origin) {
3712
+ throw new ConnectStop(
3713
+ CONNECT_EXIT_CODES.failed,
3714
+ "UNEXPECTED_RESPONSE",
3715
+ "The server returned a setup link for a different site. Not showing it."
3716
+ );
3717
+ }
3718
+ const interval = Number(body?.intervalSeconds);
3719
+ return {
3720
+ baseUrl: input.baseUrl,
3721
+ deviceCode,
3722
+ userCode,
3723
+ link,
3724
+ expiresAt,
3725
+ intervalSeconds: Number.isFinite(interval) && interval >= 1 && interval <= 60 ? interval : 5,
3726
+ agentName: input.agentName,
3727
+ // The server says whether the email went out. Without it, tell the agent to send the link.
3728
+ emailed: Boolean(input.email) && body?.emailSent !== false,
3729
+ ...input.email && body?.emailSent === false ? { emailFailed: true } : {},
3730
+ sandboxRules: Boolean(input.sandboxKey)
3731
+ };
3732
+ }
3733
+ async function poll(request) {
3734
+ const response = await call({
3735
+ baseUrl: request.baseUrl,
3736
+ method: "GET",
3737
+ apiPath: SETUP_REQUEST_PATH,
3738
+ bearer: request.deviceCode
3739
+ });
3740
+ if (response.status === 429) {
3741
+ return { status: "pending", intervalSeconds: retryAfterSeconds(response.headers) ?? 10 };
3742
+ }
3743
+ if (response.status !== 200) {
3744
+ throw refusal(response, `Checking the setup request failed (HTTP ${response.status}).`);
3745
+ }
3746
+ const body = response.data || {};
3747
+ switch (body.status) {
3748
+ case "pending": {
3749
+ const interval = Number(body.intervalSeconds);
3750
+ return {
3751
+ status: "pending",
3752
+ ...Number.isFinite(interval) ? { intervalSeconds: interval } : {}
3753
+ };
3754
+ }
3755
+ case "approved":
3756
+ if (typeof body.sdkKey !== "string" || typeof body.agentId !== "string") break;
3757
+ return {
3758
+ status: "approved",
3759
+ sdkKey: body.sdkKey,
3760
+ agentId: body.agentId,
3761
+ ...typeof body.agentName === "string" ? { agentName: body.agentName } : {}
3762
+ };
3763
+ case "denied":
3764
+ case "expired":
3765
+ case "delivered":
3766
+ return {
3767
+ status: body.status,
3768
+ ...typeof body.nextStep === "string" ? { nextStep: body.nextStep } : {}
3769
+ };
3770
+ }
3771
+ throw new ConnectStop(
3772
+ CONNECT_EXIT_CODES.failed,
3773
+ "UNEXPECTED_RESPONSE",
3774
+ "The server answered the setup check in a form this CLI does not know. Update the CLI."
3775
+ );
3776
+ }
3777
+ async function readSetup(baseUrl, sdkKey) {
3778
+ try {
3779
+ const response = await call({
3780
+ baseUrl,
3781
+ method: "GET",
3782
+ apiPath: "/api/sdk/setup",
3783
+ bearer: sdkKey
3784
+ });
3785
+ if (response.status !== 200) return { wallets: [], policies: [] };
3786
+ const body = response.data || {};
3787
+ return {
3788
+ wallets: Array.isArray(body.wallets) ? body.wallets : [],
3789
+ policies: Array.isArray(body.policies) ? body.policies.map((policy) => policy.name).filter((name) => !!name) : []
3790
+ };
3791
+ } catch {
3792
+ return { wallets: [], policies: [] };
3793
+ }
3794
+ }
3795
+ async function saveApproved(cwd, request, approved, options) {
3796
+ const agentName = approved.agentName || request.agentName;
3797
+ const setup = await readSetup(request.baseUrl, approved.sdkKey);
3798
+ const wallet = setup.wallets.length === 1 ? setup.wallets[0] : void 0;
3799
+ let chain;
3800
+ if (wallet) {
3801
+ try {
3802
+ chain = (await fetchChains(request.baseUrl)).chains[wallet.chainId];
3803
+ } catch {
3804
+ chain = void 0;
3805
+ }
3806
+ }
3807
+ const hadSandbox = Boolean(loadProjectEnv(cwd).CONTO_SANDBOX_API_KEY);
3808
+ ensureEnvLocalGitignored(cwd);
3809
+ writeEnvLocal(cwd, [
3810
+ "# Conto Agent Configuration",
3811
+ "# Generated by: npx @conto_finance/create-conto-agent --connect",
3812
+ "",
3813
+ "# SDK Authentication",
3814
+ ["CONTO_API_KEY", approved.sdkKey],
3815
+ ["CONTO_BASE_URL", request.baseUrl],
3816
+ "",
3817
+ "# Agent Identity",
3818
+ ["CONTO_AGENT_ID", approved.agentId],
3819
+ ["CONTO_AGENT_NAME", agentName],
3820
+ ...wallet ? [
3821
+ "",
3822
+ `# Network: ${chain?.name || wallet.chainName || wallet.chainId}${wallet.isTestnet ? " (testnet)" : ""}`,
3823
+ ["CONTO_CHAIN_ID", wallet.chainId],
3824
+ ...chain ? [
3825
+ ["CONTO_CHAIN_NAME", chain.name],
3826
+ ["CONTO_RPC_URL", chain.rpcUrl],
3827
+ ["CONTO_EXPLORER_URL", chain.explorerUrl],
3828
+ ["CONTO_CURRENCY", chain.currency]
3829
+ ] : wallet.currency ? [["CONTO_CURRENCY", wallet.currency]] : [],
3830
+ "",
3831
+ "# Wallet",
3832
+ ["CONTO_WALLET_ID", wallet.id],
3833
+ ["CONTO_WALLET_ADDRESS", wallet.address]
3834
+ ] : []
3835
+ ]);
3836
+ removeSavedRequest(cwd);
3837
+ const keptFiles = await writeProjectFiles(
3838
+ cwd,
3839
+ {
3840
+ agent: { id: approved.agentId, name: agentName, type: "CUSTOM" },
3841
+ ...wallet ? {
3842
+ network: {
3843
+ chain: chain?.name || wallet.chainName || wallet.chainId,
3844
+ chainId: wallet.chainId,
3845
+ rpcUrl: chain?.rpcUrl || "",
3846
+ explorerUrl: chain?.explorerUrl || "",
3847
+ currency: chain?.currency || wallet.currency || "",
3848
+ testnet: wallet.isTestnet === true
3849
+ },
3850
+ wallet: { id: wallet.id, address: wallet.address, custodyMode: wallet.custodyMode }
3851
+ } : {},
3852
+ server: { baseUrl: request.baseUrl }
3853
+ },
3854
+ { overwrite: options.overwrite }
3855
+ );
3856
+ let cliResolves = hasLocalCliBin(cwd);
3857
+ if (!cliResolves && options.install !== false) {
3858
+ cliResolves = installCliLocally(cwd, agentName) === "installed";
3859
+ }
3860
+ return { agentName, setup, wallet, keptFiles, hadSandbox, cliResolves };
3861
+ }
3862
+ function waitSeconds2(wait, request) {
3863
+ const untilExpiry = Math.max(0, Math.ceil((Date.parse(request.expiresAt) - Date.now()) / 1e3));
3864
+ if (typeof wait === "number" && Number.isFinite(wait) && wait > 0) {
3865
+ return Math.min(wait, untilExpiry);
3866
+ }
3867
+ return untilExpiry;
3868
+ }
3869
+ function sleep2(ms) {
3870
+ return new Promise((resolve) => setTimeout(resolve, ms));
3871
+ }
3872
+ function printRequest(request, reused) {
3873
+ console.log("");
3874
+ console.log(
3875
+ chalk3.bold(
3876
+ reused ? " Still waiting for approval" : " Ask the account owner to approve this agent"
3877
+ )
3878
+ );
3879
+ console.log("");
3880
+ console.log(` Link: ${chalk3.cyan(request.link)}`);
3881
+ console.log(` Code: ${chalk3.bold(request.userCode)}`);
3882
+ console.log(` Until: ${request.expiresAt}`);
3883
+ console.log("");
3884
+ if (request.emailFailed) {
3885
+ printWarning("Conto could not send the email. Send this link to the person yourself.");
3886
+ }
3887
+ if (request.emailed) {
3888
+ printInfo(
3889
+ "Conto emailed this link. The person opens it, signs up or signs in, checks the code and approves."
3890
+ );
3891
+ } else {
3892
+ printInfo("Send this link to the person. They sign in, check the code and approve.");
3893
+ }
3894
+ if (request.sandboxRules) {
3895
+ printInfo("Approving also copies this project's sandbox policies to the new agent.");
3896
+ }
3897
+ }
3898
+ function pendingNextSteps() {
3899
+ return [`${FULL_CLI2} --connect --wait --json`];
3900
+ }
3901
+ async function runConnect(options = {}) {
3902
+ try {
3903
+ await connect(options);
3904
+ } catch (error) {
3905
+ if (error instanceof ConnectStop) stop(error);
3906
+ throw error;
3907
+ }
3908
+ }
3909
+ async function connect(options) {
3910
+ const cwd = process.cwd();
3911
+ let baseUrl;
3912
+ try {
3913
+ baseUrl = normalizeBaseUrl(
3914
+ parseSecureBaseUrl(options.baseUrl || process.env.CONTO_BASE_URL || DEFAULT_BASE_URL2).href
3915
+ );
3916
+ } catch (error) {
3917
+ throw new ConnectStop(
3918
+ CONNECT_EXIT_CODES.failed,
3919
+ "INVALID_OPTIONS",
3920
+ error instanceof Error ? error.message : "Invalid base URL"
3921
+ );
3922
+ }
3923
+ const env = loadProjectEnv(cwd);
3924
+ let sandboxKey = options.sandboxKey?.trim() || env.CONTO_SANDBOX_API_KEY?.trim() || void 0;
3925
+ if (options.sandboxKey && !SANDBOX_KEY_PATTERN.test(options.sandboxKey.trim())) {
3926
+ throw new ConnectStop(
3927
+ CONNECT_EXIT_CODES.refused,
3928
+ "INVALID_OPTIONS",
3929
+ "--sandbox-key takes the sandbox organization key (conto_ followed by 64 hex characters), CONTO_SANDBOX_API_KEY in .env.local."
3930
+ );
3931
+ }
3932
+ if (!options.sandboxKey && sandboxKey) {
3933
+ let sameServer = false;
3934
+ try {
3935
+ sameServer = Boolean(env.CONTO_BASE_URL) && normalizeBaseUrl(env.CONTO_BASE_URL) === baseUrl;
3936
+ } catch {
3937
+ sameServer = false;
3938
+ }
3939
+ if (!sameServer) sandboxKey = void 0;
3940
+ }
3941
+ if (!options.sandboxKey && sandboxKey && !SANDBOX_KEY_PATTERN.test(sandboxKey))
3942
+ sandboxKey = void 0;
3943
+ if (!options.sandboxKey && sandboxKey && env.CONTO_SANDBOX_EXPIRES_AT && Date.parse(env.CONTO_SANDBOX_EXPIRES_AT) <= Date.now()) {
3944
+ sandboxKey = void 0;
3945
+ }
3946
+ let request = null;
3947
+ let reused = false;
3948
+ const saved = loadSavedRequest(cwd);
3949
+ if (saved && !options.restart) {
3950
+ if (saved.baseUrl === baseUrl && !isExpired(saved)) {
3951
+ request = saved;
3952
+ reused = true;
3953
+ } else {
3954
+ removeSavedRequest(cwd);
3955
+ }
3956
+ } else if (saved) {
3957
+ removeSavedRequest(cwd);
3958
+ }
3959
+ if (!request) {
3960
+ if (!isJsonMode()) printInfo(`Asking ${baseUrl} to set up this agent...`);
3961
+ try {
3962
+ request = await createRequest({
3963
+ baseUrl,
3964
+ agentName: options.name?.trim() || DEFAULT_AGENT_NAME,
3965
+ email: options.email?.trim() || void 0,
3966
+ sandboxKey
3967
+ });
3968
+ } catch (error) {
3969
+ if (error instanceof ConnectStop && error.code === "INVALID_SANDBOX_KEY" && !options.sandboxKey && sandboxKey) {
3970
+ if (!isJsonMode()) {
3971
+ printWarning(
3972
+ "This project's sandbox key is no longer valid. Its policies will not be copied."
3973
+ );
3974
+ }
3975
+ sandboxKey = void 0;
3976
+ request = await createRequest({
3977
+ baseUrl,
3978
+ agentName: options.name?.trim() || DEFAULT_AGENT_NAME,
3979
+ email: options.email?.trim() || void 0
3980
+ });
3981
+ } else {
3982
+ throw error;
3983
+ }
3984
+ }
3985
+ saveRequest(cwd, request);
3986
+ }
3987
+ if (!options.wait) {
3988
+ if (isJsonMode()) {
3989
+ printJson({
3990
+ ok: true,
3991
+ mode: "connect",
3992
+ status: "pending",
3993
+ link: request.link,
3994
+ userCode: request.userCode,
3995
+ expiresAt: request.expiresAt,
3996
+ emailed: request.emailed,
3997
+ ...request.emailFailed ? { emailFailed: true } : {},
3998
+ sandboxPoliciesCopied: request.sandboxRules,
3999
+ savedIn: SETUP_REQUEST_FILE,
4000
+ ...reused ? { reused: true } : {},
4001
+ tellThePerson: request.emailed ? `Conto emailed you a link. Check that it shows the code ${request.userCode}, then approve.` : `Open ${request.link}, check that it shows the code ${request.userCode}, then approve.`,
4002
+ nextSteps: pendingNextSteps()
4003
+ });
4004
+ } else {
4005
+ printRequest(request, reused);
4006
+ console.log("");
4007
+ console.log(` Then run: ${chalk3.cyan(`${FULL_CLI2} --connect --wait`)}`);
4008
+ console.log("");
4009
+ }
4010
+ return;
4011
+ }
4012
+ if (!isJsonMode()) {
4013
+ printRequest(request, reused);
4014
+ console.log("");
4015
+ printInfo("Waiting for approval. Press Ctrl+C to stop. The link stays valid until it expires.");
4016
+ }
4017
+ const deadline = Date.now() + waitSeconds2(options.wait, request) * 1e3;
4018
+ let interval = request.intervalSeconds;
4019
+ for (; ; ) {
4020
+ const result = await poll(request);
4021
+ if (result.status === "approved") {
4022
+ const saved2 = await saveApproved(cwd, request, result, options);
4023
+ reportApproved(request, result, saved2);
4024
+ return;
4025
+ }
4026
+ if (result.status === "denied") {
4027
+ removeSavedRequest(cwd);
4028
+ throw new ConnectStop(
4029
+ CONNECT_EXIT_CODES.refused,
4030
+ "DENIED",
4031
+ "The person declined this agent.",
4032
+ {
4033
+ nextStep: result.nextStep || "Do not ask again unless they tell you to."
4034
+ }
4035
+ );
4036
+ }
4037
+ if (result.status === "expired") {
4038
+ removeSavedRequest(cwd);
4039
+ throw new ConnectStop(CONNECT_EXIT_CODES.failed, "EXPIRED", "The setup request expired.", {
4040
+ nextStep: `Start a new one: ${FULL_CLI2} --connect${request.emailed ? " --email <their email>" : ""}`
4041
+ });
4042
+ }
4043
+ if (result.status === "delivered") {
4044
+ removeSavedRequest(cwd);
4045
+ throw new ConnectStop(
4046
+ CONNECT_EXIT_CODES.failed,
4047
+ "ALREADY_DELIVERED",
4048
+ "This request was approved and its key was already picked up somewhere else.",
4049
+ {
4050
+ nextStep: result.nextStep || "Ask the person to revoke that key and start a new request."
4051
+ }
4052
+ );
4053
+ }
4054
+ if (result.status === "pending" && result.intervalSeconds && result.intervalSeconds >= 1 && result.intervalSeconds <= 60) {
4055
+ interval = result.intervalSeconds;
4056
+ }
4057
+ if (Date.now() + interval * 1e3 > deadline) {
4058
+ throw new ConnectStop(
4059
+ CONNECT_EXIT_CODES.stillWaiting,
4060
+ "STILL_WAITING",
4061
+ "Still waiting for the person to approve.",
4062
+ {
4063
+ link: request.link,
4064
+ userCode: request.userCode,
4065
+ expiresAt: request.expiresAt,
4066
+ nextStep: `Run it again to keep waiting: ${FULL_CLI2} --connect --wait`
4067
+ }
4068
+ );
4069
+ }
4070
+ await sleep2(interval * 1e3);
4071
+ }
4072
+ }
4073
+ function reportApproved(request, approved, saved) {
4074
+ const exampleKept = saved.keptFiles.includes("example.mjs");
4075
+ const cli = saved.cliResolves ? "npx conto" : FULL_CLI2;
4076
+ if (isJsonMode()) {
4077
+ printJson({
4078
+ ok: true,
4079
+ mode: "connect",
4080
+ status: "approved",
4081
+ baseUrl: request.baseUrl,
4082
+ agent: { id: approved.agentId, name: saved.agentName },
4083
+ wallet: saved.wallet ? { id: saved.wallet.id, address: saved.wallet.address, chainId: saved.wallet.chainId } : null,
4084
+ policies: saved.setup.policies,
4085
+ credentials: { storedIn: ".env.local", sdkKeyEnv: "CONTO_API_KEY" },
4086
+ files: PROJECT_FILES.filter((file) => !saved.keptFiles.includes(file)),
4087
+ ...saved.keptFiles.length > 0 ? { keptFiles: saved.keptFiles } : {},
4088
+ ...saved.hadSandbox ? { replacedSandbox: true } : {},
4089
+ nextSteps: [`${FULL_CLI2} doctor`, ...exampleKept ? [] : ["node example.mjs"], MCP_ADD_LINE]
4090
+ });
4091
+ return;
4092
+ }
4093
+ console.log("");
4094
+ printSuccess(`Approved. ${saved.agentName} is connected to the account.`);
4095
+ console.log("");
4096
+ console.log(` ${chalk3.bold(".env.local")} - agent key and config (shown once)`);
4097
+ if (saved.wallet) {
4098
+ console.log(` ${chalk3.dim("Wallet:")} ${saved.wallet.address}`);
4099
+ } else {
4100
+ console.log(
4101
+ ` ${chalk3.dim("Wallet:")} none yet. The account owner adds one in the dashboard.`
4102
+ );
4103
+ }
4104
+ if (saved.setup.policies.length) {
4105
+ console.log(` ${chalk3.dim("Policies:")} ${saved.setup.policies.join(", ")}`);
4106
+ }
4107
+ console.log("");
4108
+ printKeptFiles(saved.keptFiles);
4109
+ if (saved.hadSandbox) {
4110
+ printInfo(
4111
+ "This project now uses the real account. The sandbox keys were removed from .env.local."
4112
+ );
4113
+ }
4114
+ console.log(chalk3.bold(" Next steps:"));
4115
+ console.log(` 1. Check the setup: ${chalk3.cyan(`${cli} doctor`)}`);
4116
+ if (!exampleKept) console.log(` 2. Run the example: ${chalk3.cyan("node example.mjs")}`);
4117
+ console.log(` ${exampleKept ? 2 : 3}. Add it to Claude Code: ${chalk3.cyan(MCP_ADD_LINE)}`);
4118
+ console.log("");
4119
+ }
4120
+
3442
4121
  export {
3443
4122
  CLI_PACKAGE_VERSION,
3444
4123
  HttpTransportError,
@@ -3468,5 +4147,6 @@ export {
3468
4147
  readProjectStateFile,
3469
4148
  writeProjectStateFile,
3470
4149
  fingerprintSecret,
3471
- runInit
4150
+ runInit,
4151
+ runConnect
3472
4152
  };