@conto_finance/create-conto-agent 0.9.1 → 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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,24 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.10.0
4
+
5
+ - `create-conto-agent --connect` sets an agent up in a person's real Conto account without a
6
+ browser on the agent's computer. It prints a link and a code. The person opens the link, signs up
7
+ or signs in, checks the code and approves. With `--email you@example.com`, Conto emails the link.
8
+ `--wait` waits for the approval and saves the agent key (`conto_agent_`, never an organization
9
+ key) to the project's `.env.local`. Without `--wait` it returns right away and keeps the request
10
+ in `.conto/setup-request.json`, so a second run with `--wait` picks it up. From a sandbox project,
11
+ approval also copies the sandbox's policies to the new agent. `conto init --connect` and
12
+ `conto init --email` do the same. Exit codes: 0 approved or waiting, 1 failed or expired,
13
+ 2 declined or refused, 4 still waiting when `--wait` ran out of time.
14
+ - `create-conto-agent --sandbox` no longer replaces a login saved in `~/.conto/config.json`. The
15
+ sandbox runs from the project's `.env.local` as before. The `--json` result has
16
+ `savedLoginKept: true` when the saved login was kept.
17
+ - The `--json` next steps use the full package name, `npx @conto_finance/create-conto-agent`, which
18
+ works from any folder. They also include the line that adds Conto to Claude Code:
19
+ `claude mcp add conto -- npx -y @conto_finance/create-conto-agent mcp`. The printed next steps
20
+ show the same line in place of `conto mcp`, which only starts the server.
21
+
3
22
  ## 0.9.1
4
23
 
5
24
  - `conto login` and the `conto init` sign-in now collect the organization key from Conto instead
package/README.md CHANGED
@@ -66,6 +66,21 @@ Setup keeps the other lines in an existing `.env.local` and replaces only its `C
66
66
  before replacing an existing `conto.config.json` or `example.mjs`. A headless run keeps them unless
67
67
  you pass `--overwrite`.
68
68
 
69
+ ## Connect to a person's account
70
+
71
+ ```bash
72
+ npx @conto_finance/create-conto-agent --connect --email owner@example.com --json
73
+ npx @conto_finance/create-conto-agent --connect --wait --json
74
+ ```
75
+
76
+ `--connect` sets the agent up in a person's real Conto account without a browser on the agent's
77
+ computer. The first run prints a link and a code, and with `--email` Conto emails the link. The
78
+ person opens it, signs up or signs in, checks the code and approves. `--wait` waits for the approval
79
+ and saves the agent key to the project's `.env.local`. From a sandbox project, approval also copies
80
+ the sandbox's policies. Exit codes: 0 approved or the link is out, 1 failed or expired, 2 declined
81
+ or refused, 4 still waiting. See
82
+ [connect to a person's account](https://conto.finance/docs/cli/commands#connect-to-a-persons-account).
83
+
69
84
  ## Hand a sandbox to its owner
70
85
 
71
86
  ```bash
@@ -22,7 +22,7 @@ import {
22
22
  // package.json
23
23
  var package_default = {
24
24
  name: "@conto_finance/create-conto-agent",
25
- version: "0.9.1",
25
+ version: "0.10.0",
26
26
  description: "Set up an AI agent with Conto spending controls",
27
27
  bin: {
28
28
  "create-conto-agent": "bin/create-conto-agent.js",
@@ -481,7 +481,7 @@ async function browserAuth(baseUrl, onAuthUrl, onPairingCode) {
481
481
  },
482
482
  5 * 60 * 1e3
483
483
  );
484
- const poll = async () => {
484
+ const poll2 = async () => {
485
485
  if (settled) return;
486
486
  const outcome = await pollPickup(baseUrl, pickupCode, state);
487
487
  if (settled) return;
@@ -490,7 +490,7 @@ async function browserAuth(baseUrl, onAuthUrl, onPairingCode) {
490
490
  else reject(new Error(`Authentication failed: ${outcome.error}`));
491
491
  return;
492
492
  }
493
- if (!outcome.stop) pollTimer = setTimeout(() => void poll(), PICKUP_POLL_MS);
493
+ if (!outcome.stop) pollTimer = setTimeout(() => void poll2(), PICKUP_POLL_MS);
494
494
  };
495
495
  const server = http.createServer((req, res) => {
496
496
  void (async () => {
@@ -544,7 +544,7 @@ async function browserAuth(baseUrl, onAuthUrl, onPairingCode) {
544
544
  onPairingCode?.(pairingCode(pickupHash));
545
545
  open(authUrl).catch(() => {
546
546
  });
547
- pollTimer = setTimeout(() => void poll(), PICKUP_POLL_MS);
547
+ pollTimer = setTimeout(() => void poll2(), PICKUP_POLL_MS);
548
548
  });
549
549
  });
550
550
  }
@@ -609,6 +609,7 @@ var NOT_SENT_CODES = /* @__PURE__ */ new Set([
609
609
  var SECRET_PATTERNS = [
610
610
  [/conto_claim_[A-Za-z0-9]+/g, "conto_claim_[redacted]"],
611
611
  [/conto_agent_[A-Za-z0-9]+/g, "conto_agent_[redacted]"],
612
+ [/conto_setupreq_[A-Za-z0-9]+/g, "conto_setupreq_[redacted]"],
612
613
  [/conto_setup_[A-Za-z0-9]+/g, "conto_setup_[redacted]"],
613
614
  [/conto_[A-Fa-f0-9]{16,}/g, "conto_[redacted]"],
614
615
  [/(Bearer\s+)\S+/gi, "$1[redacted]"]
@@ -781,8 +782,8 @@ var ApiClient = class {
781
782
  async orgToken() {
782
783
  return typeof this.orgApiKey === "function" ? this.orgApiKey() : this.orgApiKey;
783
784
  }
784
- async request(method, path3, options) {
785
- const url = `${this.baseUrl}${path3}`;
785
+ async request(method, path4, options) {
786
+ const url = `${this.baseUrl}${path4}`;
786
787
  const authType = options?.auth || "sdk";
787
788
  const token = authType === "org" ? await this.orgToken() : this.apiKey;
788
789
  const headers = {
@@ -805,7 +806,7 @@ var ApiClient = class {
805
806
  const contentType = response.headers.get("content-type") || "";
806
807
  if (!contentType.includes("application/json")) {
807
808
  const error = new Error(
808
- 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})`
809
810
  );
810
811
  error.code = response.status === 404 ? "NOT_FOUND" : "INVALID_RESPONSE";
811
812
  error.status = response.status;
@@ -839,11 +840,11 @@ var ApiClient = class {
839
840
  * POST a payment call through requestJson, which refuses redirects and says
840
841
  * whether a failed call may have reached the server.
841
842
  */
842
- async paymentPost(path3, body) {
843
+ async paymentPost(path4, body) {
843
844
  let response;
844
845
  try {
845
846
  response = await requestJson({
846
- url: apiUrl(this.baseUrl, path3),
847
+ url: apiUrl(this.baseUrl, path4),
847
848
  method: "POST",
848
849
  bearer: this.apiKey,
849
850
  body,
@@ -856,7 +857,7 @@ var ApiClient = class {
856
857
  throw err;
857
858
  }
858
859
  if (!response.isJson) {
859
- 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(
860
861
  `API returned non-JSON response (${response.status})`,
861
862
  "INVALID_RESPONSE",
862
863
  response.status,
@@ -875,10 +876,10 @@ var ApiClient = class {
875
876
  }
876
877
  return response.data;
877
878
  }
878
- async spendingDownload(path3, owner = false) {
879
+ async spendingDownload(path4, owner = false) {
879
880
  const token = owner ? await this.orgToken() : this.apiKey;
880
881
  const response = await fetch(
881
- `${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}`,
882
883
  {
883
884
  headers: { Authorization: `Bearer ${token}` },
884
885
  signal: AbortSignal.timeout(3e4),
@@ -888,10 +889,10 @@ var ApiClient = class {
888
889
  if (!response.ok) throw new Error(`Export failed (${response.status}). No file was saved.`);
889
890
  return new Uint8Array(await response.arrayBuffer());
890
891
  }
891
- spending(method, path3, body, owner = false) {
892
+ spending(method, path4, body, owner = false) {
892
893
  return this.request(
893
894
  method,
894
- `/api/${owner ? "spending" : path3.startsWith("purchases") ? "sdk/spending" : "sdk"}/${path3}`,
895
+ `/api/${owner ? "spending" : path4.startsWith("purchases") ? "sdk/spending" : "sdk"}/${path4}`,
895
896
  { body, auth: owner ? "org" : "sdk" }
896
897
  );
897
898
  }
@@ -1529,13 +1530,13 @@ async function provisionOrganization(input) {
1529
1530
  checkpoint.binding.organization.credentialFingerprint = input.organization.credentialFingerprint;
1530
1531
  if (input.organization.name) checkpoint.binding.organization.name = input.organization.name;
1531
1532
  };
1532
- const stopped = (stop) => {
1533
- if (stop.status !== "refused") {
1534
- checkpoint.failedStep = stop.step;
1535
- 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";
1536
1537
  persist();
1537
1538
  }
1538
- return { kind: "stopped", stop, resources };
1539
+ return { kind: "stopped", stop: stop2, resources };
1539
1540
  };
1540
1541
  const refuse2 = (step, code, message) => stopped({ status: "refused", step, code, message });
1541
1542
  const credentialRejected = (step, failure) => failure.httpStatus === 401 || failure.httpStatus === 403 ? stopped({
@@ -2227,9 +2228,9 @@ var SetupResourcesClient = class {
2227
2228
  }
2228
2229
  baseUrl;
2229
2230
  orgApiKey;
2230
- async send(method, path3, body, headers, bearer = this.orgApiKey) {
2231
+ async send(method, path4, body, headers, bearer = this.orgApiKey) {
2231
2232
  return requestJson({
2232
- url: apiUrl(this.baseUrl, path3),
2233
+ url: apiUrl(this.baseUrl, path4),
2233
2234
  method,
2234
2235
  bearer,
2235
2236
  body,
@@ -2237,19 +2238,19 @@ var SetupResourcesClient = class {
2237
2238
  timeoutMs: REQUEST_TIMEOUT_MS2
2238
2239
  });
2239
2240
  }
2240
- async create(path3, body, label, parse, headers) {
2241
+ async create(path4, body, label, parse, headers) {
2241
2242
  let response;
2242
2243
  try {
2243
- response = await this.send("POST", path3, body, headers);
2244
+ response = await this.send("POST", path4, body, headers);
2244
2245
  } catch (error) {
2245
2246
  return classifyTransport(error);
2246
2247
  }
2247
2248
  return classifyCreate(response, label, parse);
2248
2249
  }
2249
- async read(path3, label, parse, bearer) {
2250
+ async read(path4, label, parse, bearer) {
2250
2251
  let response;
2251
2252
  try {
2252
- response = await this.send("GET", path3, void 0, void 0, bearer);
2253
+ response = await this.send("GET", path4, void 0, void 0, bearer);
2253
2254
  } catch (error) {
2254
2255
  return { ok: false, notFound: false, failure: failureFromTransport(error) };
2255
2256
  }
@@ -2430,6 +2431,8 @@ var HEADLESS_DEFAULT_NAME = "conto-agent";
2430
2431
  var HEADLESS_DEFAULT_TYPE = "CUSTOM";
2431
2432
  var HEADLESS_DEFAULT_LIMIT = 500;
2432
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`;
2433
2436
  function failInit(message, details = {}, exitCode = INIT_EXIT_CODES.failed) {
2434
2437
  if (isJsonMode()) {
2435
2438
  printJson({ ok: false, error: message, ...details });
@@ -2910,10 +2913,10 @@ async function runOrganizationInit(options) {
2910
2913
  const cli = cliResolves ? "npx conto" : "npx @conto_finance/create-conto-agent";
2911
2914
  const exampleKept = keptFiles.includes("example.mjs");
2912
2915
  const nextSteps = [
2913
- `${cli} doctor`,
2916
+ `${FULL_CLI} doctor`,
2914
2917
  ...exampleKept ? [] : ["node example.mjs"],
2915
- `${cli} pay <address> <amount>`,
2916
- `${cli} mcp`
2918
+ `${FULL_CLI} pay <address> <amount>`,
2919
+ MCP_ADD_LINE
2917
2920
  ];
2918
2921
  if (isJsonMode()) {
2919
2922
  printJson({
@@ -2974,7 +2977,7 @@ async function runOrganizationInit(options) {
2974
2977
  console.log(` ${step++}. Run the example: ${chalk2.cyan("node example.mjs")}`);
2975
2978
  }
2976
2979
  console.log(` ${step++}. Make a payment: ${chalk2.cyan(`${cli} pay <address> <amount>`)}`);
2977
- console.log(` ${step++}. Connect Claude: ${chalk2.cyan(`${cli} mcp`)}`);
2980
+ console.log(` ${step++}. Add to Claude Code: ${chalk2.cyan(MCP_ADD_LINE)}`);
2978
2981
  if (!cliResolves) {
2979
2982
  printInfo(
2980
2983
  'Tip: "npx conto <command>" works after: npm install --save-dev @conto_finance/create-conto-agent'
@@ -2983,39 +2986,39 @@ async function runOrganizationInit(options) {
2983
2986
  console.log("");
2984
2987
  }
2985
2988
  function reportStoppedSetup(input) {
2986
- const { stop, checkpoint } = input;
2987
- const label = STEP_LABELS[stop.step];
2989
+ const { stop: stop2, checkpoint } = input;
2990
+ const label = STEP_LABELS[stop2.step];
2988
2991
  const failure = {
2989
- code: stop.code,
2990
- message: stop.message,
2991
- ...stop.httpStatus !== void 0 ? { httpStatus: stop.httpStatus } : {}
2992
+ code: stop2.code,
2993
+ message: stop2.message,
2994
+ ...stop2.httpStatus !== void 0 ? { httpStatus: stop2.httpStatus } : {}
2992
2995
  };
2993
- if (stop.status === "failed") {
2996
+ if (stop2.status === "failed") {
2994
2997
  removeCheckpoint(input.cwd);
2995
- failInit(`Setup failed at the ${label} step: ${stop.message}`, {
2998
+ failInit(`Setup failed at the ${label} step: ${stop2.message}`, {
2996
2999
  status: "failed",
2997
- code: stop.code,
2998
- failedStep: stop.step,
3000
+ code: stop2.code,
3001
+ failedStep: stop2.step,
2999
3002
  failure,
3000
- ...stop.retryAfterSeconds !== void 0 ? { retryAfterSeconds: stop.retryAfterSeconds } : {}
3003
+ ...stop2.retryAfterSeconds !== void 0 ? { retryAfterSeconds: stop2.retryAfterSeconds } : {}
3001
3004
  });
3002
3005
  }
3003
- 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;
3004
3007
  const completedSteps = STEP_ORDER.filter((step) => checkpoint.steps[step].status === "done");
3005
3008
  const pendingSteps = STEP_ORDER.filter(
3006
3009
  (step) => step !== "faucet" && !["done", "skipped"].includes(checkpoint.steps[step].status)
3007
3010
  );
3008
3011
  const credentialsWritten = checkpoint.steps.sdkKey.status === "done";
3009
3012
  const command = resumeCommand(input.baseUrl, input.options);
3010
- const resumable = stop.status !== "refused";
3013
+ const resumable = stop2.status !== "refused";
3011
3014
  if (isJsonMode()) {
3012
3015
  printJson({
3013
3016
  ok: false,
3014
3017
  mode: "organization",
3015
- status: stop.status,
3016
- code: stop.code,
3017
- error: stop.message,
3018
- failedStep: stop.step,
3018
+ status: stop2.status,
3019
+ code: stop2.code,
3020
+ error: stop2.message,
3021
+ failedStep: stop2.step,
3019
3022
  failure,
3020
3023
  completedSteps,
3021
3024
  pendingSteps,
@@ -3025,20 +3028,20 @@ function reportStoppedSetup(input) {
3025
3028
  resume: resumable ? {
3026
3029
  command,
3027
3030
  credential: resumeCredentialHint(),
3028
- ...stop.reconciliation?.notBefore ? { notBefore: stop.reconciliation.notBefore } : {}
3031
+ ...stop2.reconciliation?.notBefore ? { notBefore: stop2.reconciliation.notBefore } : {}
3029
3032
  } : null,
3030
- ...stop.retryAfterSeconds !== void 0 ? { retryAfterSeconds: stop.retryAfterSeconds } : {},
3031
- ...stop.reconciliation ? { reconciliation: stop.reconciliation } : {},
3032
- ...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 } : {},
3033
3036
  ...input.discarded ? { discardedSetup: input.discarded } : {}
3034
3037
  });
3035
3038
  process.exit(exitCode);
3036
3039
  }
3037
3040
  console.log("");
3038
3041
  printError(
3039
- 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.`
3040
3043
  );
3041
- printInfo(`${stop.message}${stop.httpStatus ? ` (HTTP ${stop.httpStatus})` : ""}`);
3044
+ printInfo(`${stop2.message}${stop2.httpStatus ? ` (HTTP ${stop2.httpStatus})` : ""}`);
3042
3045
  const resources = recordedResources(checkpoint);
3043
3046
  if (completedSteps.length > 0) {
3044
3047
  console.log("");
@@ -3060,19 +3063,19 @@ function reportStoppedSetup(input) {
3060
3063
  if (!credentialsWritten) {
3061
3064
  printInfo("No agent credentials were written. The agent cannot pay until setup finishes.");
3062
3065
  }
3063
- if (stop.reconciliation) {
3064
- printWarning(stop.reconciliation.reason);
3065
- printInfo(stop.reconciliation.action);
3066
- if (stop.reconciliation.resourceIds?.length) {
3067
- 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(", ")}`);
3068
3071
  }
3069
3072
  }
3070
- if (stop.ownerAction) {
3071
- printWarning(stop.ownerAction.action);
3072
- if (stop.ownerAction.dashboardUrl) printInfo(`Open: ${stop.ownerAction.dashboardUrl}`);
3073
- 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) {
3074
3077
  printInfo(
3075
- `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})`
3076
3079
  );
3077
3080
  }
3078
3081
  }
@@ -3210,35 +3213,38 @@ async function runSandboxInit(options) {
3210
3213
  options
3211
3214
  );
3212
3215
  const exampleKept = keptFiles.includes("example.mjs");
3213
- saveGlobalConfig({
3214
- agent: {
3215
- id: sandbox.agent.id,
3216
- name: sandbox.agent.name,
3217
- type: options.type || "CUSTOM"
3218
- },
3219
- network: {
3220
- chain: sandbox.wallet.chainId,
3221
- chainId: sandbox.wallet.chainId,
3222
- rpcUrl: chain?.rpcUrl || "",
3223
- explorerUrl: chain?.explorerUrl || "",
3224
- currency: chain?.currency || sandbox.wallet.currency,
3225
- testnet: true
3226
- },
3227
- wallet: {
3228
- id: sandbox.wallet.id,
3229
- address: sandbox.wallet.address,
3230
- custodyMode: sandbox.wallet.custodyMode
3231
- },
3232
- server: {
3233
- baseUrl,
3234
- apiKey: sandbox.credentials.sdkKey,
3235
- orgApiKey: sandbox.credentials.apiKey
3236
- },
3237
- sandbox: {
3238
- mode: "test",
3239
- expiresAt: sandbox.expiresAt
3240
- }
3241
- });
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
+ });
3242
3248
  let cliResolves = hasLocalCliBin(cwd);
3243
3249
  if (!cliResolves && options.install !== false) {
3244
3250
  cliResolves = installCliLocally(cwd, sandbox.agent.name) === "installed";
@@ -3264,16 +3270,19 @@ async function runSandboxInit(options) {
3264
3270
  ...setupKeyFile ? [setupKeyFile] : []
3265
3271
  ],
3266
3272
  ...keptFiles.length > 0 ? { keptFiles } : {},
3273
+ ...keepGlobal ? { savedLoginKept: true } : {},
3267
3274
  claim: {
3268
- command: `${cli} sandbox claim --json`,
3275
+ command: `${FULL_CLI} sandbox claim --json`,
3269
3276
  credentialEnv: "CONTO_SANDBOX_API_KEY",
3270
3277
  ...sandbox.claim ? { method: sandbox.claim.method, endpoint: sandbox.claim.endpoint } : {}
3271
3278
  },
3272
3279
  nextSteps: [
3273
3280
  ...exampleKept ? [] : ["node example.mjs", "node example.mjs --resume REQUEST_ID"],
3274
- `${cli} doctor`,
3275
- `${cli} pay 0x742d35Cc6634C0532925a3b844Bc454e4438f44e 1 --purpose test`,
3276
- `${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`
3277
3286
  ]
3278
3287
  });
3279
3288
  return;
@@ -3318,7 +3327,14 @@ async function runSandboxInit(options) {
3318
3327
  printInfo(
3319
3328
  "Sandbox test payments exercise policy checks, receipts, and spend tracking without an onchain transfer."
3320
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
+ );
3321
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
+ }
3322
3338
  console.log("");
3323
3339
  }
3324
3340
  function hasLocalCliBin(cwd) {
@@ -3552,6 +3568,556 @@ main().catch((err) => {
3552
3568
  `;
3553
3569
  }
3554
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
+
3555
4121
  export {
3556
4122
  CLI_PACKAGE_VERSION,
3557
4123
  HttpTransportError,
@@ -3581,5 +4147,6 @@ export {
3581
4147
  readProjectStateFile,
3582
4148
  writeProjectStateFile,
3583
4149
  fingerprintSecret,
3584
- runInit
4150
+ runInit,
4151
+ runConnect
3585
4152
  };
package/dist/cli.js CHANGED
@@ -26,9 +26,10 @@ import {
26
26
  responseErrorCode,
27
27
  responseErrorMessage,
28
28
  retryAfterSeconds,
29
+ runConnect,
29
30
  runInit,
30
31
  writeProjectStateFile
31
- } from "./chunk-6PK4I5VO.js";
32
+ } from "./chunk-ALQ6UCGI.js";
32
33
  import {
33
34
  BUDGET_PERIODS,
34
35
  VELOCITY_PERIODS,
@@ -4725,6 +4726,12 @@ Exit codes:
4725
4726
  or the credential was rejected
4726
4727
  3 partial setup: run again with --resume
4727
4728
  4 reconciliation or owner action needed before --resume (see the output)
4729
+
4730
+ With --connect:
4731
+ 0 approved and saved to .env.local, or (without --wait) the link is out
4732
+ 1 failed, or the link expired
4733
+ 2 the person declined, or the request was refused
4734
+ 4 --wait ran out of time, the link is still valid. Run it again with --wait
4728
4735
  `;
4729
4736
  var SANDBOX_CLAIM_EXIT_CODES_HELP = `
4730
4737
  Exit codes:
@@ -4751,10 +4758,45 @@ program.command("init").description("Run the setup wizard (interactive, or headl
4751
4758
  ).option(
4752
4759
  "--confirm-mainnet",
4753
4760
  "Confirm that the selected network can move real funds (required for headless mainnet setup)"
4754
- ).option("--no-install", "Skip installing the conto CLI into the project").option("--resume", "Finish an unfinished organization setup recorded in .conto/").option("--restart", "Discard an unfinished setup record and start a new setup").option("--overwrite", "Replace an existing conto.config.json and example.mjs without asking").addHelpText("after", INIT_EXIT_CODES_HELP).action(async (opts, command) => {
4761
+ ).option("--no-install", "Skip installing the conto CLI into the project").option("--resume", "Finish an unfinished organization setup recorded in .conto/").option("--restart", "Discard an unfinished setup record and start a new setup").option("--overwrite", "Replace an existing conto.config.json and example.mjs without asking").option(
4762
+ "--connect",
4763
+ "Set up this agent in a person's real account: they approve it from a link (headless)"
4764
+ ).option("--email <email>", "With --connect: email the approval link to this person").option(
4765
+ "--wait [seconds]",
4766
+ "With --connect: wait for approval and save the agent key (default: until the link expires)"
4767
+ ).option(
4768
+ "--sandbox-key <key>",
4769
+ "With --connect: copy this sandbox's policies on approval (default: CONTO_SANDBOX_API_KEY in .env.local)"
4770
+ ).addHelpText("after", INIT_EXIT_CODES_HELP).action(async (opts, command) => {
4755
4771
  if (command.optsWithGlobals().json) {
4756
4772
  setJsonMode(true);
4757
4773
  }
4774
+ const connect = opts.connect === true || typeof opts.email === "string";
4775
+ if (connect && (opts.sandbox || opts.apiKey || opts.resume)) {
4776
+ const error = "--connect and --email set up an agent in a real account through an approval link. Leave out --sandbox, --api-key and --resume.";
4777
+ if (isJsonMode()) printJson({ ok: false, code: "INVALID_OPTIONS", error });
4778
+ else console.error(error);
4779
+ process.exit(2);
4780
+ }
4781
+ if (!connect && (opts.wait !== void 0 || opts.sandboxKey)) {
4782
+ const error = "--wait and --sandbox-key go with --connect or --email.";
4783
+ if (isJsonMode()) printJson({ ok: false, code: "INVALID_OPTIONS", error });
4784
+ else console.error(error);
4785
+ process.exit(2);
4786
+ }
4787
+ if (connect) {
4788
+ await runConnect({
4789
+ email: opts.email,
4790
+ name: opts.name,
4791
+ baseUrl: opts.baseUrl,
4792
+ wait: opts.wait === void 0 ? false : opts.wait === true ? true : Number(opts.wait),
4793
+ sandboxKey: opts.sandboxKey,
4794
+ restart: opts.restart === true,
4795
+ install: opts.install,
4796
+ overwrite: opts.overwrite === true
4797
+ });
4798
+ return;
4799
+ }
4758
4800
  await runInit({
4759
4801
  chain: opts.chain,
4760
4802
  name: opts.name,
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import {
2
+ runConnect,
2
3
  runInit
3
- } from "./chunk-6PK4I5VO.js";
4
+ } from "./chunk-ALQ6UCGI.js";
4
5
  import {
5
6
  delegatesToCli
6
7
  } from "./chunk-D6JPJHU4.js";
@@ -31,6 +32,15 @@ if (delegatesToCli(args)) {
31
32
  options.baseUrl = args[++i];
32
33
  } else if (arg === "--api-key" && args[i + 1]) {
33
34
  options.apiKey = args[++i];
35
+ } else if (arg === "--email" && args[i + 1]) {
36
+ options.email = args[++i];
37
+ } else if (arg === "--sandbox-key" && args[i + 1]) {
38
+ options.sandboxKey = args[++i];
39
+ } else if (arg === "--connect") {
40
+ options.connect = true;
41
+ } else if (arg === "--wait") {
42
+ if (args[i + 1] && /^\d+$/.test(args[i + 1])) options.wait = args[++i];
43
+ else options.wait = true;
34
44
  } else if (arg === "--sandbox") {
35
45
  options.sandbox = true;
36
46
  } else if (arg === "--no-browser") {
@@ -58,7 +68,29 @@ if (delegatesToCli(args)) {
58
68
  else console.error(error);
59
69
  process.exit(1);
60
70
  }
61
- runInit({
71
+ const connect = options.connect === true || typeof options.email === "string";
72
+ if (connect && (options.sandbox || options.apiKey || options.resume)) {
73
+ const error = "--connect and --email set up an agent in a real account through an approval link. Leave out --sandbox, --api-key and --resume.";
74
+ if (isJsonMode()) printJson({ ok: false, code: "INVALID_OPTIONS", error });
75
+ else console.error(error);
76
+ process.exit(2);
77
+ }
78
+ if (!connect && (options.wait || options.sandboxKey)) {
79
+ const error = "--wait and --sandbox-key go with --connect or --email.";
80
+ if (isJsonMode()) printJson({ ok: false, code: "INVALID_OPTIONS", error });
81
+ else console.error(error);
82
+ process.exit(2);
83
+ }
84
+ const run = connect ? runConnect({
85
+ email: options.email,
86
+ name: options.name,
87
+ baseUrl: options.baseUrl,
88
+ wait: options.wait === true ? true : options.wait ? Number(options.wait) : false,
89
+ sandboxKey: options.sandboxKey,
90
+ restart: options.restart === true,
91
+ install: options.noInstall ? false : void 0,
92
+ overwrite: options.overwrite === true
93
+ }) : runInit({
62
94
  chain: options.chain,
63
95
  name: options.name,
64
96
  type: options.type,
@@ -71,7 +103,8 @@ if (delegatesToCli(args)) {
71
103
  resume: options.resume === true,
72
104
  restart: options.restart === true,
73
105
  overwrite: options.overwrite === true
74
- }).catch((err) => {
106
+ });
107
+ run.catch((err) => {
75
108
  const error = err instanceof Error ? err.message : String(err);
76
109
  if (isJsonMode()) printJson({ ok: false, error });
77
110
  else console.error("Fatal error:", error);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@conto_finance/create-conto-agent",
3
- "version": "0.9.1",
3
+ "version": "0.10.0",
4
4
  "description": "Set up an AI agent with Conto spending controls",
5
5
  "bin": {
6
6
  "create-conto-agent": "bin/create-conto-agent.js",