@conto_finance/create-conto-agent 0.1.0 → 0.1.2

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.
@@ -8,7 +8,7 @@ import {
8
8
  saveGlobalConfig,
9
9
  writeContoConfig,
10
10
  writeEnvLocal
11
- } from "./chunk-X7AY7G2E.js";
11
+ } from "./chunk-NK52PCTE.js";
12
12
 
13
13
  // src/commands/init.ts
14
14
  import * as p from "@clack/prompts";
@@ -0,0 +1,78 @@
1
+ // src/lib/config.ts
2
+ import fs from "fs";
3
+ import path from "path";
4
+ import os from "os";
5
+ var CONTO_DIR = path.join(os.homedir(), ".conto");
6
+ var CONFIG_FILE = path.join(CONTO_DIR, "config.json");
7
+ function ensureContoDir() {
8
+ if (!fs.existsSync(CONTO_DIR)) {
9
+ fs.mkdirSync(CONTO_DIR, { recursive: true });
10
+ }
11
+ }
12
+ function loadGlobalConfig() {
13
+ try {
14
+ if (fs.existsSync(CONFIG_FILE)) {
15
+ const raw = fs.readFileSync(CONFIG_FILE, "utf-8");
16
+ return JSON.parse(raw);
17
+ }
18
+ } catch {
19
+ }
20
+ return {};
21
+ }
22
+ function saveGlobalConfig(config) {
23
+ ensureContoDir();
24
+ fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2) + "\n");
25
+ }
26
+ function loadProjectEnv(dir) {
27
+ const envPath = path.join(dir || process.cwd(), ".env.local");
28
+ if (fs.existsSync(envPath)) {
29
+ const content = fs.readFileSync(envPath, "utf-8");
30
+ const result = {};
31
+ for (const line of content.split("\n")) {
32
+ const match = line.match(/^([A-Z_][A-Z0-9_]*)=(.*)$/);
33
+ if (match) result[match[1]] = match[2];
34
+ }
35
+ return result;
36
+ }
37
+ return {};
38
+ }
39
+ function loadConfig() {
40
+ const global = loadGlobalConfig();
41
+ const env = loadProjectEnv();
42
+ return {
43
+ apiKey: env.CONTO_API_KEY || global.server?.apiKey,
44
+ baseUrl: env.CONTO_BASE_URL || global.server?.baseUrl || "https://conto.finance",
45
+ agentId: env.CONTO_AGENT_ID || global.agent?.id,
46
+ chainId: env.CONTO_CHAIN_ID || global.network?.chainId,
47
+ chainName: env.CONTO_CHAIN_NAME || global.network?.chain,
48
+ currency: env.CONTO_CURRENCY || global.network?.currency,
49
+ explorerUrl: env.CONTO_EXPLORER_URL || global.network?.explorerUrl,
50
+ walletId: env.CONTO_WALLET_ID || global.wallet?.id,
51
+ walletAddress: env.CONTO_WALLET_ADDRESS || global.wallet?.address,
52
+ orgApiKey: global.server?.orgApiKey,
53
+ testnet: global.network?.testnet || env.CONTO_CHAIN_ID === "42431"
54
+ };
55
+ }
56
+ function writeEnvLocal(dir, vars) {
57
+ const lines = Object.entries(vars).map(([key, value]) => `${key}=${value}`);
58
+ const content = lines.join("\n") + "\n";
59
+ fs.writeFileSync(path.join(dir, ".env.local"), content);
60
+ }
61
+ function writeContoConfig(dir, config) {
62
+ fs.writeFileSync(path.join(dir, "conto.config.json"), JSON.stringify(config, null, 2) + "\n");
63
+ }
64
+ function clearGlobalConfig() {
65
+ if (fs.existsSync(CONFIG_FILE)) {
66
+ fs.unlinkSync(CONFIG_FILE);
67
+ }
68
+ }
69
+
70
+ export {
71
+ loadGlobalConfig,
72
+ saveGlobalConfig,
73
+ loadProjectEnv,
74
+ loadConfig,
75
+ writeEnvLocal,
76
+ writeContoConfig,
77
+ clearGlobalConfig
78
+ };
package/dist/cli.js CHANGED
@@ -4,7 +4,7 @@ import {
4
4
  fetchChains,
5
5
  getChain,
6
6
  runInit
7
- } from "./chunk-M7X7S5QC.js";
7
+ } from "./chunk-AWKUQSTP.js";
8
8
  import {
9
9
  isJsonMode,
10
10
  printAmount,
@@ -23,8 +23,7 @@ import {
23
23
  loadConfig,
24
24
  loadGlobalConfig,
25
25
  saveGlobalConfig
26
- } from "./chunk-X7AY7G2E.js";
27
- import "./chunk-QGM4M3NI.js";
26
+ } from "./chunk-NK52PCTE.js";
28
27
 
29
28
  // src/cli.ts
30
29
  import { Command } from "commander";
@@ -700,11 +699,11 @@ async function policiesCommand(subcommand = "list", idOrAmount, extra) {
700
699
  process.exit(1);
701
700
  }
702
701
  return await removeRule(api, idOrAmount, extra);
702
+ case "help":
703
+ return printPolicyHelp();
703
704
  default:
704
705
  printError(`Unknown subcommand: ${subcommand}`);
705
- printInfo(
706
- "Available: list, all, create, update <id>, delete <id>, assign <id>, unassign <id>, add-rule <id>, remove-rule <policyId> <ruleId>"
707
- );
706
+ printInfo('Run "conto policies help" for usage guide');
708
707
  process.exit(1);
709
708
  }
710
709
  } catch (err) {
@@ -957,6 +956,66 @@ async function promptForRule(policyType) {
957
956
  action
958
957
  };
959
958
  }
959
+ function printPolicyHelp() {
960
+ console.log(chalk3.bold("\n Conto Policy Management\n"));
961
+ console.log(chalk3.bold(" Commands:"));
962
+ console.log(" conto policies List agent policies");
963
+ console.log(" conto policies all List all org policies");
964
+ console.log(" conto policies create Create a new policy");
965
+ console.log(" conto policies update <id> Update name/priority/status");
966
+ console.log(" conto policies delete <id> Delete a policy");
967
+ console.log(" conto policies assign <id> Assign to current agent");
968
+ console.log(" conto policies unassign <id> Remove from agent");
969
+ console.log(" conto policies add-rule <id> Add a rule");
970
+ console.log(" conto policies remove-rule <id> <rid> Remove a rule");
971
+ console.log(" conto policies help This help page");
972
+ console.log(chalk3.bold("\n Policy Types:"));
973
+ for (const pt of POLICY_TYPES) {
974
+ console.log(` ${chalk3.cyan(pt.value.padEnd(22))} ${chalk3.dim(pt.hint)}`);
975
+ }
976
+ console.log(chalk3.bold("\n Common Rule Types:"));
977
+ const commonRules = [
978
+ ["MAX_AMOUNT", "Max per-transaction amount (e.g. 500)"],
979
+ ["DAILY_LIMIT", "Max total spend per day (e.g. 1000)"],
980
+ ["WEEKLY_LIMIT", "Max total spend per week"],
981
+ ["MONTHLY_LIMIT", "Max total spend per month"],
982
+ ["REQUIRE_APPROVAL_ABOVE", "Human approval above $ amount"],
983
+ ["ALLOWED_COUNTERPARTIES", "JSON array of allowed addresses"],
984
+ ["BLOCKED_COUNTERPARTIES", "JSON array of blocked addresses"],
985
+ ["GEOGRAPHIC_RESTRICTION", "JSON array of blocked country codes"],
986
+ ["VELOCITY_LIMIT", "Max transactions per time window"],
987
+ ["DATE_RANGE", 'JSON: {"start":"2025-01-01","end":"2025-12-31"}']
988
+ ];
989
+ for (const [rule, desc] of commonRules) {
990
+ console.log(` ${chalk3.cyan(rule.padEnd(28))} ${chalk3.dim(desc)}`);
991
+ }
992
+ console.log(chalk3.bold("\n Value Examples:"));
993
+ console.log(" Spend limits: 500");
994
+ console.log(' Address lists: ["0xabc...","0xdef..."]');
995
+ console.log(' Country codes: ["CU","IR","KP","SY","RU"]');
996
+ console.log(" Trust score: 50 (0-100)");
997
+ console.log(' Date range: {"start":"2025-01-01","end":"2025-12-31"}');
998
+ console.log(' Categories: ["API_PROVIDER","CLOUD","SAAS"]');
999
+ console.log(chalk3.bold("\n Operators:"));
1000
+ console.log(" LTE (<= at most) GTE (>= at least) EQUALS NOT_EQUALS");
1001
+ console.log(" IN_LIST NOT_IN_LIST BETWEEN DENY");
1002
+ console.log(chalk3.bold("\n Actions:"));
1003
+ console.log(` ${chalk3.green("ALLOW")} Payment proceeds if rule passes`);
1004
+ console.log(` ${chalk3.red("DENY")} Payment is blocked`);
1005
+ console.log(` ${chalk3.yellow("REQUIRE_APPROVAL")} Payment needs human approval`);
1006
+ console.log(chalk3.bold("\n Examples:"));
1007
+ console.log(chalk3.dim(" # Create a $500/day spend limit"));
1008
+ console.log(" conto policies create");
1009
+ console.log(chalk3.dim(" # Add a weekly limit rule to an existing policy"));
1010
+ console.log(" conto policies add-rule cmn4abc123");
1011
+ console.log(chalk3.dim(" # Deactivate a policy without deleting"));
1012
+ console.log(" conto policies update cmn4abc123");
1013
+ console.log(chalk3.dim(" # View all policies as JSON"));
1014
+ console.log(" conto policies all --json");
1015
+ console.log(`
1016
+ ${chalk3.dim("Full docs: https://docs.conto.finance/cli/policies")}
1017
+ `);
1018
+ }
960
1019
  function formatRuleValue(ruleType, value) {
961
1020
  if (ruleType.includes("LIMIT") || ruleType.includes("AMOUNT") || ruleType.includes("CAP")) {
962
1021
  const num = Number(value);
@@ -1168,7 +1227,7 @@ async function mcpCommand() {
1168
1227
  }
1169
1228
  printInfo("Starting Conto MCP server...");
1170
1229
  printInfo("Press Ctrl+C to stop.\n");
1171
- const child = spawn("npx", ["conto-mcp-server"], {
1230
+ const child = spawn("npx", ["@conto_finance/mcp-server"], {
1172
1231
  stdio: "inherit",
1173
1232
  env: {
1174
1233
  ...process.env,
@@ -1178,7 +1237,7 @@ async function mcpCommand() {
1178
1237
  });
1179
1238
  child.on("error", (err) => {
1180
1239
  printError(`Failed to start MCP server: ${err.message}`);
1181
- printInfo("Install it with: npm install -g conto-mcp-server");
1240
+ printInfo("Install it with: npm install -g @conto_finance/mcp-server");
1182
1241
  process.exit(1);
1183
1242
  });
1184
1243
  child.on("exit", (code) => {
@@ -1219,10 +1278,24 @@ program.command("alerts").description("List alerts").option("--unread", "Show on
1219
1278
  program.command("config [key] [value]").description("Show or update configuration").action(configCommand);
1220
1279
  program.command("login").description("Authenticate with Conto").option("--base-url <url>", "Conto instance URL").action(loginCommand);
1221
1280
  program.command("logout").description("Clear stored credentials").action(async () => {
1222
- const { clearGlobalConfig } = await import("./config-63WIUTLL.js");
1281
+ const { clearGlobalConfig } = await import("./config-CFVDT6M4.js");
1223
1282
  clearGlobalConfig();
1224
- const { printSuccess: printSuccess3 } = await import("./output-6522BGYZ.js");
1283
+ const { printSuccess: printSuccess3 } = await import("./output-VT23PY74.js");
1225
1284
  printSuccess3("Logged out. Credentials cleared.");
1226
1285
  });
1227
1286
  program.command("mcp").description("Start MCP server for AI agent integration").action(mcpCommand);
1287
+ program.command("docs [topic]").description("Open Conto documentation (cli, policies, sdk, api)").action(async (topic) => {
1288
+ const open = (await import("open")).default;
1289
+ const urls = {
1290
+ cli: "https://docs.conto.finance/cli/quickstart",
1291
+ policies: "https://docs.conto.finance/cli/policies",
1292
+ commands: "https://docs.conto.finance/cli/commands",
1293
+ sdk: "https://docs.conto.finance/sdk/installation",
1294
+ api: "https://docs.conto.finance/api"
1295
+ };
1296
+ const url = urls[topic || "cli"] || urls.cli;
1297
+ const { printInfo: printInfo3 } = await import("./output-VT23PY74.js");
1298
+ printInfo3(`Opening ${url}`);
1299
+ open(url);
1300
+ });
1228
1301
  program.parse();
@@ -6,8 +6,7 @@ import {
6
6
  saveGlobalConfig,
7
7
  writeContoConfig,
8
8
  writeEnvLocal
9
- } from "./chunk-X7AY7G2E.js";
10
- import "./chunk-QGM4M3NI.js";
9
+ } from "./chunk-NK52PCTE.js";
11
10
  export {
12
11
  clearGlobalConfig,
13
12
  loadConfig,
package/dist/index.js CHANGED
@@ -1,9 +1,8 @@
1
1
  import {
2
2
  runInit
3
- } from "./chunk-M7X7S5QC.js";
3
+ } from "./chunk-AWKUQSTP.js";
4
4
  import "./chunk-6TRDZ4JG.js";
5
- import "./chunk-X7AY7G2E.js";
6
- import "./chunk-QGM4M3NI.js";
5
+ import "./chunk-NK52PCTE.js";
7
6
 
8
7
  // src/index.ts
9
8
  var args = process.argv.slice(2);
@@ -14,7 +14,6 @@ import {
14
14
  setJsonMode,
15
15
  truncateAddress
16
16
  } from "./chunk-6TRDZ4JG.js";
17
- import "./chunk-QGM4M3NI.js";
18
17
  export {
19
18
  isJsonMode,
20
19
  printAmount,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@conto_finance/create-conto-agent",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "CLI quickstart for Conto — Agentic Payments Control Center",
5
5
  "bin": {
6
6
  "create-conto-agent": "bin/create-conto-agent.js",
@@ -1,37 +0,0 @@
1
- var __create = Object.create;
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
8
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
9
- }) : x)(function(x) {
10
- if (typeof require !== "undefined") return require.apply(this, arguments);
11
- throw Error('Dynamic require of "' + x + '" is not supported');
12
- });
13
- var __commonJS = (cb, mod) => function __require2() {
14
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
15
- };
16
- var __copyProps = (to, from, except, desc) => {
17
- if (from && typeof from === "object" || typeof from === "function") {
18
- for (let key of __getOwnPropNames(from))
19
- if (!__hasOwnProp.call(to, key) && key !== except)
20
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
21
- }
22
- return to;
23
- };
24
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
25
- // If the importer is in node compatibility mode or this is not an ESM
26
- // file that has been converted to a CommonJS file using a Babel-
27
- // compatible transform (i.e. "__esModule" has not been set), then set
28
- // "default" to the CommonJS "module.exports" for node compatibility.
29
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
30
- mod
31
- ));
32
-
33
- export {
34
- __require,
35
- __commonJS,
36
- __toESM
37
- };
@@ -1,439 +0,0 @@
1
- import {
2
- __commonJS,
3
- __require,
4
- __toESM
5
- } from "./chunk-QGM4M3NI.js";
6
-
7
- // node_modules/dotenv/package.json
8
- var require_package = __commonJS({
9
- "node_modules/dotenv/package.json"(exports, module) {
10
- module.exports = {
11
- name: "dotenv",
12
- version: "16.6.1",
13
- description: "Loads environment variables from .env file",
14
- main: "lib/main.js",
15
- types: "lib/main.d.ts",
16
- exports: {
17
- ".": {
18
- types: "./lib/main.d.ts",
19
- require: "./lib/main.js",
20
- default: "./lib/main.js"
21
- },
22
- "./config": "./config.js",
23
- "./config.js": "./config.js",
24
- "./lib/env-options": "./lib/env-options.js",
25
- "./lib/env-options.js": "./lib/env-options.js",
26
- "./lib/cli-options": "./lib/cli-options.js",
27
- "./lib/cli-options.js": "./lib/cli-options.js",
28
- "./package.json": "./package.json"
29
- },
30
- scripts: {
31
- "dts-check": "tsc --project tests/types/tsconfig.json",
32
- lint: "standard",
33
- pretest: "npm run lint && npm run dts-check",
34
- test: "tap run --allow-empty-coverage --disable-coverage --timeout=60000",
35
- "test:coverage": "tap run --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov",
36
- prerelease: "npm test",
37
- release: "standard-version"
38
- },
39
- repository: {
40
- type: "git",
41
- url: "git://github.com/motdotla/dotenv.git"
42
- },
43
- homepage: "https://github.com/motdotla/dotenv#readme",
44
- funding: "https://dotenvx.com",
45
- keywords: [
46
- "dotenv",
47
- "env",
48
- ".env",
49
- "environment",
50
- "variables",
51
- "config",
52
- "settings"
53
- ],
54
- readmeFilename: "README.md",
55
- license: "BSD-2-Clause",
56
- devDependencies: {
57
- "@types/node": "^18.11.3",
58
- decache: "^4.6.2",
59
- sinon: "^14.0.1",
60
- standard: "^17.0.0",
61
- "standard-version": "^9.5.0",
62
- tap: "^19.2.0",
63
- typescript: "^4.8.4"
64
- },
65
- engines: {
66
- node: ">=12"
67
- },
68
- browser: {
69
- fs: false
70
- }
71
- };
72
- }
73
- });
74
-
75
- // node_modules/dotenv/lib/main.js
76
- var require_main = __commonJS({
77
- "node_modules/dotenv/lib/main.js"(exports, module) {
78
- "use strict";
79
- var fs2 = __require("fs");
80
- var path2 = __require("path");
81
- var os2 = __require("os");
82
- var crypto = __require("crypto");
83
- var packageJson = require_package();
84
- var version = packageJson.version;
85
- var LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;
86
- function parse(src) {
87
- const obj = {};
88
- let lines = src.toString();
89
- lines = lines.replace(/\r\n?/mg, "\n");
90
- let match;
91
- while ((match = LINE.exec(lines)) != null) {
92
- const key = match[1];
93
- let value = match[2] || "";
94
- value = value.trim();
95
- const maybeQuote = value[0];
96
- value = value.replace(/^(['"`])([\s\S]*)\1$/mg, "$2");
97
- if (maybeQuote === '"') {
98
- value = value.replace(/\\n/g, "\n");
99
- value = value.replace(/\\r/g, "\r");
100
- }
101
- obj[key] = value;
102
- }
103
- return obj;
104
- }
105
- function _parseVault(options) {
106
- options = options || {};
107
- const vaultPath = _vaultPath(options);
108
- options.path = vaultPath;
109
- const result = DotenvModule.configDotenv(options);
110
- if (!result.parsed) {
111
- const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`);
112
- err.code = "MISSING_DATA";
113
- throw err;
114
- }
115
- const keys = _dotenvKey(options).split(",");
116
- const length = keys.length;
117
- let decrypted;
118
- for (let i = 0; i < length; i++) {
119
- try {
120
- const key = keys[i].trim();
121
- const attrs = _instructions(result, key);
122
- decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key);
123
- break;
124
- } catch (error) {
125
- if (i + 1 >= length) {
126
- throw error;
127
- }
128
- }
129
- }
130
- return DotenvModule.parse(decrypted);
131
- }
132
- function _warn(message) {
133
- console.log(`[dotenv@${version}][WARN] ${message}`);
134
- }
135
- function _debug(message) {
136
- console.log(`[dotenv@${version}][DEBUG] ${message}`);
137
- }
138
- function _log(message) {
139
- console.log(`[dotenv@${version}] ${message}`);
140
- }
141
- function _dotenvKey(options) {
142
- if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) {
143
- return options.DOTENV_KEY;
144
- }
145
- if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) {
146
- return process.env.DOTENV_KEY;
147
- }
148
- return "";
149
- }
150
- function _instructions(result, dotenvKey) {
151
- let uri;
152
- try {
153
- uri = new URL(dotenvKey);
154
- } catch (error) {
155
- if (error.code === "ERR_INVALID_URL") {
156
- const err = new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");
157
- err.code = "INVALID_DOTENV_KEY";
158
- throw err;
159
- }
160
- throw error;
161
- }
162
- const key = uri.password;
163
- if (!key) {
164
- const err = new Error("INVALID_DOTENV_KEY: Missing key part");
165
- err.code = "INVALID_DOTENV_KEY";
166
- throw err;
167
- }
168
- const environment = uri.searchParams.get("environment");
169
- if (!environment) {
170
- const err = new Error("INVALID_DOTENV_KEY: Missing environment part");
171
- err.code = "INVALID_DOTENV_KEY";
172
- throw err;
173
- }
174
- const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`;
175
- const ciphertext = result.parsed[environmentKey];
176
- if (!ciphertext) {
177
- const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`);
178
- err.code = "NOT_FOUND_DOTENV_ENVIRONMENT";
179
- throw err;
180
- }
181
- return { ciphertext, key };
182
- }
183
- function _vaultPath(options) {
184
- let possibleVaultPath = null;
185
- if (options && options.path && options.path.length > 0) {
186
- if (Array.isArray(options.path)) {
187
- for (const filepath of options.path) {
188
- if (fs2.existsSync(filepath)) {
189
- possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`;
190
- }
191
- }
192
- } else {
193
- possibleVaultPath = options.path.endsWith(".vault") ? options.path : `${options.path}.vault`;
194
- }
195
- } else {
196
- possibleVaultPath = path2.resolve(process.cwd(), ".env.vault");
197
- }
198
- if (fs2.existsSync(possibleVaultPath)) {
199
- return possibleVaultPath;
200
- }
201
- return null;
202
- }
203
- function _resolveHome(envPath) {
204
- return envPath[0] === "~" ? path2.join(os2.homedir(), envPath.slice(1)) : envPath;
205
- }
206
- function _configVault(options) {
207
- const debug = Boolean(options && options.debug);
208
- const quiet = options && "quiet" in options ? options.quiet : true;
209
- if (debug || !quiet) {
210
- _log("Loading env from encrypted .env.vault");
211
- }
212
- const parsed = DotenvModule._parseVault(options);
213
- let processEnv = process.env;
214
- if (options && options.processEnv != null) {
215
- processEnv = options.processEnv;
216
- }
217
- DotenvModule.populate(processEnv, parsed, options);
218
- return { parsed };
219
- }
220
- function configDotenv(options) {
221
- const dotenvPath = path2.resolve(process.cwd(), ".env");
222
- let encoding = "utf8";
223
- const debug = Boolean(options && options.debug);
224
- const quiet = options && "quiet" in options ? options.quiet : true;
225
- if (options && options.encoding) {
226
- encoding = options.encoding;
227
- } else {
228
- if (debug) {
229
- _debug("No encoding is specified. UTF-8 is used by default");
230
- }
231
- }
232
- let optionPaths = [dotenvPath];
233
- if (options && options.path) {
234
- if (!Array.isArray(options.path)) {
235
- optionPaths = [_resolveHome(options.path)];
236
- } else {
237
- optionPaths = [];
238
- for (const filepath of options.path) {
239
- optionPaths.push(_resolveHome(filepath));
240
- }
241
- }
242
- }
243
- let lastError;
244
- const parsedAll = {};
245
- for (const path3 of optionPaths) {
246
- try {
247
- const parsed = DotenvModule.parse(fs2.readFileSync(path3, { encoding }));
248
- DotenvModule.populate(parsedAll, parsed, options);
249
- } catch (e) {
250
- if (debug) {
251
- _debug(`Failed to load ${path3} ${e.message}`);
252
- }
253
- lastError = e;
254
- }
255
- }
256
- let processEnv = process.env;
257
- if (options && options.processEnv != null) {
258
- processEnv = options.processEnv;
259
- }
260
- DotenvModule.populate(processEnv, parsedAll, options);
261
- if (debug || !quiet) {
262
- const keysCount = Object.keys(parsedAll).length;
263
- const shortPaths = [];
264
- for (const filePath of optionPaths) {
265
- try {
266
- const relative = path2.relative(process.cwd(), filePath);
267
- shortPaths.push(relative);
268
- } catch (e) {
269
- if (debug) {
270
- _debug(`Failed to load ${filePath} ${e.message}`);
271
- }
272
- lastError = e;
273
- }
274
- }
275
- _log(`injecting env (${keysCount}) from ${shortPaths.join(",")}`);
276
- }
277
- if (lastError) {
278
- return { parsed: parsedAll, error: lastError };
279
- } else {
280
- return { parsed: parsedAll };
281
- }
282
- }
283
- function config(options) {
284
- if (_dotenvKey(options).length === 0) {
285
- return DotenvModule.configDotenv(options);
286
- }
287
- const vaultPath = _vaultPath(options);
288
- if (!vaultPath) {
289
- _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`);
290
- return DotenvModule.configDotenv(options);
291
- }
292
- return DotenvModule._configVault(options);
293
- }
294
- function decrypt(encrypted, keyStr) {
295
- const key = Buffer.from(keyStr.slice(-64), "hex");
296
- let ciphertext = Buffer.from(encrypted, "base64");
297
- const nonce = ciphertext.subarray(0, 12);
298
- const authTag = ciphertext.subarray(-16);
299
- ciphertext = ciphertext.subarray(12, -16);
300
- try {
301
- const aesgcm = crypto.createDecipheriv("aes-256-gcm", key, nonce);
302
- aesgcm.setAuthTag(authTag);
303
- return `${aesgcm.update(ciphertext)}${aesgcm.final()}`;
304
- } catch (error) {
305
- const isRange = error instanceof RangeError;
306
- const invalidKeyLength = error.message === "Invalid key length";
307
- const decryptionFailed = error.message === "Unsupported state or unable to authenticate data";
308
- if (isRange || invalidKeyLength) {
309
- const err = new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");
310
- err.code = "INVALID_DOTENV_KEY";
311
- throw err;
312
- } else if (decryptionFailed) {
313
- const err = new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");
314
- err.code = "DECRYPTION_FAILED";
315
- throw err;
316
- } else {
317
- throw error;
318
- }
319
- }
320
- }
321
- function populate(processEnv, parsed, options = {}) {
322
- const debug = Boolean(options && options.debug);
323
- const override = Boolean(options && options.override);
324
- if (typeof parsed !== "object") {
325
- const err = new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");
326
- err.code = "OBJECT_REQUIRED";
327
- throw err;
328
- }
329
- for (const key of Object.keys(parsed)) {
330
- if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
331
- if (override === true) {
332
- processEnv[key] = parsed[key];
333
- }
334
- if (debug) {
335
- if (override === true) {
336
- _debug(`"${key}" is already defined and WAS overwritten`);
337
- } else {
338
- _debug(`"${key}" is already defined and was NOT overwritten`);
339
- }
340
- }
341
- } else {
342
- processEnv[key] = parsed[key];
343
- }
344
- }
345
- }
346
- var DotenvModule = {
347
- configDotenv,
348
- _configVault,
349
- _parseVault,
350
- config,
351
- decrypt,
352
- parse,
353
- populate
354
- };
355
- module.exports.configDotenv = DotenvModule.configDotenv;
356
- module.exports._configVault = DotenvModule._configVault;
357
- module.exports._parseVault = DotenvModule._parseVault;
358
- module.exports.config = DotenvModule.config;
359
- module.exports.decrypt = DotenvModule.decrypt;
360
- module.exports.parse = DotenvModule.parse;
361
- module.exports.populate = DotenvModule.populate;
362
- module.exports = DotenvModule;
363
- }
364
- });
365
-
366
- // src/lib/config.ts
367
- var import_dotenv = __toESM(require_main(), 1);
368
- import fs from "fs";
369
- import path from "path";
370
- import os from "os";
371
- var CONTO_DIR = path.join(os.homedir(), ".conto");
372
- var CONFIG_FILE = path.join(CONTO_DIR, "config.json");
373
- function ensureContoDir() {
374
- if (!fs.existsSync(CONTO_DIR)) {
375
- fs.mkdirSync(CONTO_DIR, { recursive: true });
376
- }
377
- }
378
- function loadGlobalConfig() {
379
- try {
380
- if (fs.existsSync(CONFIG_FILE)) {
381
- const raw = fs.readFileSync(CONFIG_FILE, "utf-8");
382
- return JSON.parse(raw);
383
- }
384
- } catch {
385
- }
386
- return {};
387
- }
388
- function saveGlobalConfig(config) {
389
- ensureContoDir();
390
- fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2) + "\n");
391
- }
392
- function loadProjectEnv(dir) {
393
- const envPath = path.join(dir || process.cwd(), ".env.local");
394
- if (fs.existsSync(envPath)) {
395
- const result = import_dotenv.default.parse(fs.readFileSync(envPath, "utf-8"));
396
- return result;
397
- }
398
- return {};
399
- }
400
- function loadConfig() {
401
- const global = loadGlobalConfig();
402
- const env = loadProjectEnv();
403
- return {
404
- apiKey: env.CONTO_API_KEY || global.server?.apiKey,
405
- baseUrl: env.CONTO_BASE_URL || global.server?.baseUrl || "https://conto.finance",
406
- agentId: env.CONTO_AGENT_ID || global.agent?.id,
407
- chainId: env.CONTO_CHAIN_ID || global.network?.chainId,
408
- chainName: env.CONTO_CHAIN_NAME || global.network?.chain,
409
- currency: env.CONTO_CURRENCY || global.network?.currency,
410
- explorerUrl: env.CONTO_EXPLORER_URL || global.network?.explorerUrl,
411
- walletId: env.CONTO_WALLET_ID || global.wallet?.id,
412
- walletAddress: env.CONTO_WALLET_ADDRESS || global.wallet?.address,
413
- orgApiKey: global.server?.orgApiKey,
414
- testnet: global.network?.testnet || env.CONTO_CHAIN_ID === "42431"
415
- };
416
- }
417
- function writeEnvLocal(dir, vars) {
418
- const lines = Object.entries(vars).map(([key, value]) => `${key}=${value}`);
419
- const content = lines.join("\n") + "\n";
420
- fs.writeFileSync(path.join(dir, ".env.local"), content);
421
- }
422
- function writeContoConfig(dir, config) {
423
- fs.writeFileSync(path.join(dir, "conto.config.json"), JSON.stringify(config, null, 2) + "\n");
424
- }
425
- function clearGlobalConfig() {
426
- if (fs.existsSync(CONFIG_FILE)) {
427
- fs.unlinkSync(CONFIG_FILE);
428
- }
429
- }
430
-
431
- export {
432
- loadGlobalConfig,
433
- saveGlobalConfig,
434
- loadProjectEnv,
435
- loadConfig,
436
- writeEnvLocal,
437
- writeContoConfig,
438
- clearGlobalConfig
439
- };