@agenticmail/enterprise 0.5.336 → 0.5.337

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.
@@ -0,0 +1,260 @@
1
+ import "./chunk-KFQGP6VL.js";
2
+
3
+ // src/cli-serve.ts
4
+ import { existsSync, readFileSync } from "fs";
5
+ import { join } from "path";
6
+ import { homedir } from "os";
7
+ function loadEnvFile() {
8
+ const candidates = [
9
+ join(process.cwd(), ".env"),
10
+ join(homedir(), ".agenticmail", ".env")
11
+ ];
12
+ for (const envPath of candidates) {
13
+ if (!existsSync(envPath)) continue;
14
+ try {
15
+ const content = readFileSync(envPath, "utf8");
16
+ for (const line of content.split("\n")) {
17
+ const trimmed = line.trim();
18
+ if (!trimmed || trimmed.startsWith("#")) continue;
19
+ const eq = trimmed.indexOf("=");
20
+ if (eq < 0) continue;
21
+ const key = trimmed.slice(0, eq).trim();
22
+ let val = trimmed.slice(eq + 1).trim();
23
+ if (val.startsWith('"') && val.endsWith('"') || val.startsWith("'") && val.endsWith("'")) {
24
+ val = val.slice(1, -1);
25
+ }
26
+ if (!process.env[key]) process.env[key] = val;
27
+ }
28
+ console.log(`Loaded config from ${envPath}`);
29
+ return;
30
+ } catch {
31
+ }
32
+ }
33
+ }
34
+ async function ensureSecrets() {
35
+ const { randomUUID } = await import("crypto");
36
+ const envDir = join(homedir(), ".agenticmail");
37
+ const envPath = join(envDir, ".env");
38
+ let dirty = false;
39
+ if (!process.env.JWT_SECRET) {
40
+ process.env.JWT_SECRET = randomUUID() + randomUUID();
41
+ dirty = true;
42
+ console.log("[startup] Generated new JWT_SECRET (existing sessions will need to re-login)");
43
+ }
44
+ if (!process.env.AGENTICMAIL_VAULT_KEY) {
45
+ process.env.AGENTICMAIL_VAULT_KEY = randomUUID() + randomUUID();
46
+ dirty = true;
47
+ console.log("[startup] Generated new AGENTICMAIL_VAULT_KEY");
48
+ console.log("[startup] \u26A0\uFE0F Previously encrypted credentials will need to be re-entered in the dashboard");
49
+ }
50
+ if (dirty) {
51
+ try {
52
+ if (!existsSync(envDir)) {
53
+ const { mkdirSync } = await import("fs");
54
+ mkdirSync(envDir, { recursive: true });
55
+ }
56
+ const { appendFileSync } = await import("fs");
57
+ const lines = [];
58
+ let existing = "";
59
+ if (existsSync(envPath)) {
60
+ existing = readFileSync(envPath, "utf8");
61
+ }
62
+ if (!existing.includes("JWT_SECRET=")) {
63
+ lines.push(`JWT_SECRET=${process.env.JWT_SECRET}`);
64
+ }
65
+ if (!existing.includes("AGENTICMAIL_VAULT_KEY=")) {
66
+ lines.push(`AGENTICMAIL_VAULT_KEY=${process.env.AGENTICMAIL_VAULT_KEY}`);
67
+ }
68
+ if (lines.length) {
69
+ appendFileSync(envPath, "\n" + lines.join("\n") + "\n", { mode: 384 });
70
+ console.log(`[startup] Saved secrets to ${envPath}`);
71
+ }
72
+ } catch (e) {
73
+ console.warn(`[startup] Could not save secrets to ${envPath}: ${e.message}`);
74
+ }
75
+ }
76
+ }
77
+ async function runServe(_args) {
78
+ loadEnvFile();
79
+ const DATABASE_URL = process.env.DATABASE_URL;
80
+ const PORT = parseInt(process.env.PORT || "8080", 10);
81
+ await ensureSecrets();
82
+ const JWT_SECRET = process.env.JWT_SECRET;
83
+ const _VAULT_KEY = process.env.AGENTICMAIL_VAULT_KEY;
84
+ if (!DATABASE_URL) {
85
+ console.error("ERROR: DATABASE_URL is required.");
86
+ console.error("");
87
+ console.error("Set it via environment variable or .env file:");
88
+ console.error(" DATABASE_URL=postgresql://user:pass@host:5432/db npx @agenticmail/enterprise start");
89
+ console.error("");
90
+ console.error("Or create a .env file (in cwd or ~/.agenticmail/.env):");
91
+ console.error(" DATABASE_URL=postgresql://user:pass@host:5432/db");
92
+ console.error(" JWT_SECRET=your-secret-here");
93
+ console.error(" PORT=3200");
94
+ process.exit(1);
95
+ }
96
+ const { createAdapter, smartDbConfig } = await import("./factory-RTZU2K54.js");
97
+ const { createServer } = await import("./server-ZFVGQJUL.js");
98
+ const db = await createAdapter(smartDbConfig(DATABASE_URL));
99
+ await db.migrate();
100
+ const server = createServer({
101
+ port: PORT,
102
+ db,
103
+ jwtSecret: JWT_SECRET,
104
+ corsOrigins: ["*"]
105
+ });
106
+ await server.start();
107
+ console.log(`AgenticMail Enterprise server running on :${PORT}`);
108
+ try {
109
+ const { startPreventSleep } = await import("./screen-unlock-4RPZBHOI.js");
110
+ const adminDb = server.getAdminDb?.() || server.adminDb;
111
+ if (adminDb) {
112
+ const settings = await adminDb.getSettings?.().catch(() => null);
113
+ const screenAccess = settings?.securityConfig?.screenAccess;
114
+ if (screenAccess?.enabled && screenAccess?.preventSleep) {
115
+ startPreventSleep();
116
+ console.log("[startup] Prevent-sleep enabled \u2014 system will stay awake while agents are active");
117
+ }
118
+ }
119
+ } catch {
120
+ }
121
+ try {
122
+ await setupSystemPersistence();
123
+ } catch (e) {
124
+ console.warn("[startup] System persistence setup skipped: " + e.message);
125
+ }
126
+ const tunnelToken = process.env.CLOUDFLARED_TOKEN;
127
+ if (tunnelToken) {
128
+ try {
129
+ const { execSync, spawn } = await import("child_process");
130
+ try {
131
+ execSync("which cloudflared", { timeout: 3e3 });
132
+ } catch {
133
+ console.log("[startup] cloudflared not found \u2014 skipping tunnel auto-start");
134
+ console.log("[startup] Install cloudflared to enable tunnel: https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/");
135
+ return;
136
+ }
137
+ try {
138
+ execSync('pgrep -f "cloudflared.*tunnel.*run"', { timeout: 3e3 });
139
+ console.log("[startup] cloudflared tunnel already running");
140
+ return;
141
+ } catch {
142
+ }
143
+ const subdomain = process.env.AGENTICMAIL_SUBDOMAIN || process.env.AGENTICMAIL_DOMAIN || "";
144
+ console.log(`[startup] Starting cloudflared tunnel${subdomain ? ` for ${subdomain}.agenticmail.io` : ""}...`);
145
+ const child = spawn("cloudflared", ["tunnel", "--no-autoupdate", "run", "--token", tunnelToken], {
146
+ detached: true,
147
+ stdio: "ignore"
148
+ });
149
+ child.unref();
150
+ console.log("[startup] cloudflared tunnel started (pid " + child.pid + ")");
151
+ } catch (e) {
152
+ console.warn("[startup] Could not auto-start cloudflared: " + e.message);
153
+ }
154
+ }
155
+ }
156
+ async function setupSystemPersistence() {
157
+ const { execSync, spawnSync } = await import("child_process");
158
+ const { existsSync: exists, writeFileSync, mkdirSync } = await import("fs");
159
+ const { join: pathJoin } = await import("path");
160
+ const platform = process.platform;
161
+ if (!process.env.PM2_HOME && !process.env.pm_id) {
162
+ return;
163
+ }
164
+ const markerDir = pathJoin(homedir(), ".agenticmail");
165
+ const markerFile = pathJoin(markerDir, ".persistence-configured");
166
+ if (exists(markerFile)) {
167
+ try {
168
+ execSync("pm2 save --silent", { timeout: 1e4, stdio: "ignore" });
169
+ } catch {
170
+ }
171
+ return;
172
+ }
173
+ console.log("[startup] Configuring system persistence (one-time setup)...");
174
+ try {
175
+ if (platform === "darwin") {
176
+ const result = spawnSync("pm2", ["startup", "launchd", "--silent"], {
177
+ timeout: 15e3,
178
+ stdio: "pipe",
179
+ encoding: "utf-8"
180
+ });
181
+ const output = (result.stdout || "") + (result.stderr || "");
182
+ const sudoMatch = output.match(/sudo\s+env\s+.*pm2\s+startup.*/);
183
+ if (sudoMatch) {
184
+ console.log("[startup] PM2 startup requires sudo. Run this once:");
185
+ console.log(" " + sudoMatch[0]);
186
+ } else {
187
+ console.log("[startup] PM2 startup configured (launchd)");
188
+ }
189
+ const plistPath = pathJoin(homedir(), "Library", "LaunchAgents", `pm2.${process.env.USER || "user"}.plist`);
190
+ if (exists(plistPath)) {
191
+ try {
192
+ execSync(`launchctl load -w "${plistPath}"`, { timeout: 5e3, stdio: "ignore" });
193
+ } catch {
194
+ }
195
+ }
196
+ } else if (platform === "linux") {
197
+ const result = spawnSync("pm2", ["startup", "systemd", "--silent"], {
198
+ timeout: 15e3,
199
+ stdio: "pipe",
200
+ encoding: "utf-8"
201
+ });
202
+ const output = (result.stdout || "") + (result.stderr || "");
203
+ const sudoMatch = output.match(/sudo\s+env\s+.*pm2\s+startup.*/);
204
+ if (sudoMatch) {
205
+ try {
206
+ execSync(sudoMatch[0], { timeout: 15e3, stdio: "ignore" });
207
+ console.log("[startup] PM2 startup configured (systemd)");
208
+ } catch {
209
+ console.log("[startup] PM2 startup requires root. Run this once:");
210
+ console.log(" " + sudoMatch[0]);
211
+ }
212
+ } else {
213
+ console.log("[startup] PM2 startup configured (systemd)");
214
+ }
215
+ } else if (platform === "win32") {
216
+ try {
217
+ execSync("npm list -g pm2-windows-startup", { timeout: 1e4, stdio: "ignore" });
218
+ } catch {
219
+ console.log("[startup] Installing pm2-windows-startup...");
220
+ try {
221
+ execSync("npm install -g pm2-windows-startup", { timeout: 6e4, stdio: "ignore" });
222
+ execSync("pm2-startup install", { timeout: 15e3, stdio: "ignore" });
223
+ console.log("[startup] PM2 startup configured (Windows Service)");
224
+ } catch (e) {
225
+ console.warn("[startup] Could not install pm2-windows-startup: " + e.message);
226
+ }
227
+ }
228
+ }
229
+ } catch (e) {
230
+ console.warn("[startup] PM2 startup setup: " + e.message);
231
+ }
232
+ try {
233
+ const moduleList = execSync("pm2 ls --silent 2>/dev/null || true", { timeout: 1e4, encoding: "utf-8" });
234
+ if (!moduleList.includes("pm2-logrotate")) {
235
+ console.log("[startup] Installing pm2-logrotate...");
236
+ execSync("pm2 install pm2-logrotate --silent", { timeout: 6e4, stdio: "ignore" });
237
+ execSync("pm2 set pm2-logrotate:max_size 10M --silent", { timeout: 5e3, stdio: "ignore" });
238
+ execSync("pm2 set pm2-logrotate:retain 5 --silent", { timeout: 5e3, stdio: "ignore" });
239
+ execSync("pm2 set pm2-logrotate:compress true --silent", { timeout: 5e3, stdio: "ignore" });
240
+ console.log("[startup] Log rotation configured (10MB, 5 files)");
241
+ }
242
+ } catch {
243
+ }
244
+ try {
245
+ execSync("pm2 save --silent", { timeout: 1e4, stdio: "ignore" });
246
+ console.log("[startup] Process list saved");
247
+ } catch {
248
+ }
249
+ try {
250
+ if (!exists(markerDir)) mkdirSync(markerDir, { recursive: true });
251
+ writeFileSync(markerFile, (/* @__PURE__ */ new Date()).toISOString() + `
252
+ platform=${platform}
253
+ `, { mode: 384 });
254
+ console.log("[startup] System persistence configured successfully");
255
+ } catch {
256
+ }
257
+ }
258
+ export {
259
+ runServe
260
+ };
@@ -0,0 +1,149 @@
1
+ import {
2
+ DomainLock
3
+ } from "./chunk-UPU23ZRG.js";
4
+ import "./chunk-KFQGP6VL.js";
5
+
6
+ // src/domain-lock/cli-verify.ts
7
+ function getFlag(args, name) {
8
+ const idx = args.indexOf(name);
9
+ if (idx !== -1 && args[idx + 1]) return args[idx + 1];
10
+ return void 0;
11
+ }
12
+ function hasFlag(args, name) {
13
+ return args.includes(name);
14
+ }
15
+ function detectDbType(url) {
16
+ const u = url.toLowerCase().trim();
17
+ if (u.startsWith("postgres") || u.startsWith("pg:")) return "postgres";
18
+ if (u.startsWith("mysql")) return "mysql";
19
+ if (u.startsWith("mongodb")) return "mongodb";
20
+ if (u.startsWith("libsql") || u.includes(".turso.io")) return "turso";
21
+ if (u.endsWith(".db") || u.endsWith(".sqlite") || u.endsWith(".sqlite3") || u.startsWith("file:")) return "sqlite";
22
+ return "postgres";
23
+ }
24
+ async function runVerifyDomain(args) {
25
+ const { default: chalk } = await import("chalk");
26
+ const { default: ora } = await import("ora");
27
+ console.log("");
28
+ console.log(chalk.bold(" AgenticMail Enterprise \u2014 Domain Verification"));
29
+ console.log("");
30
+ let domain = getFlag(args, "--domain");
31
+ let dnsChallenge;
32
+ let db = null;
33
+ let dbConnected = false;
34
+ const envDbUrl = process.env.DATABASE_URL;
35
+ if (envDbUrl) {
36
+ const dbType = detectDbType(envDbUrl);
37
+ const spinner = ora(`Connecting to database (${dbType})...`).start();
38
+ try {
39
+ const { createAdapter } = await import("./factory-RTZU2K54.js");
40
+ db = await createAdapter({ type: dbType, connectionString: envDbUrl });
41
+ await db.migrate();
42
+ const settings = await db.getSettings();
43
+ if (!domain && settings?.domain) domain = settings.domain;
44
+ if (settings?.domainDnsChallenge) dnsChallenge = settings.domainDnsChallenge;
45
+ dbConnected = true;
46
+ spinner.succeed(`Connected to ${dbType} database` + (domain ? ` (domain: ${domain})` : ""));
47
+ } catch (err) {
48
+ spinner.warn(`Could not connect via DATABASE_URL: ${err.message}`);
49
+ db = null;
50
+ }
51
+ }
52
+ if (!dbConnected) {
53
+ const dbPath = getFlag(args, "--db");
54
+ const dbType = getFlag(args, "--db-type") || "sqlite";
55
+ if (dbPath) {
56
+ const spinner = ora(`Connecting to ${dbType} database...`).start();
57
+ try {
58
+ const { createAdapter } = await import("./factory-RTZU2K54.js");
59
+ db = await createAdapter({ type: dbType, connectionString: dbPath });
60
+ await db.migrate();
61
+ const settings = await db.getSettings();
62
+ if (!domain && settings?.domain) domain = settings.domain;
63
+ if (settings?.domainDnsChallenge) dnsChallenge = settings.domainDnsChallenge;
64
+ dbConnected = true;
65
+ spinner.succeed(`Connected to ${dbType} database`);
66
+ } catch {
67
+ spinner.warn("Could not read local database");
68
+ }
69
+ }
70
+ }
71
+ if (!domain) {
72
+ const { default: inquirer } = await import("inquirer");
73
+ const answer = await inquirer.prompt([{
74
+ type: "input",
75
+ name: "domain",
76
+ message: "Domain to verify:",
77
+ suffix: chalk.dim(" (e.g. agents.yourcompany.com)"),
78
+ validate: (v) => v.includes(".") || "Enter a valid domain",
79
+ filter: (v) => v.trim().toLowerCase()
80
+ }]);
81
+ domain = answer.domain;
82
+ }
83
+ const lock = new DomainLock();
84
+ const maxAttempts = hasFlag(args, "--poll") ? 5 : 1;
85
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
86
+ const spinner = ora(
87
+ maxAttempts > 1 ? `Checking DNS verification (attempt ${attempt}/${maxAttempts})...` : "Checking DNS verification..."
88
+ ).start();
89
+ try {
90
+ const result = await lock.checkVerification(domain);
91
+ if (!result.success) {
92
+ spinner.fail("Verification check failed");
93
+ console.log("");
94
+ console.error(chalk.red(` ${result.error}`));
95
+ console.log("");
96
+ if (db) await db.disconnect();
97
+ process.exit(1);
98
+ }
99
+ if (result.verified) {
100
+ spinner.succeed("Domain verified!");
101
+ if (dbConnected && db) {
102
+ try {
103
+ await db.updateSettings({
104
+ domainStatus: "verified",
105
+ domainVerifiedAt: (/* @__PURE__ */ new Date()).toISOString()
106
+ });
107
+ console.log(chalk.dim(" Database updated with verified status."));
108
+ } catch {
109
+ }
110
+ }
111
+ console.log("");
112
+ console.log(chalk.green.bold(` \u2713 ${domain} is verified and protected.`));
113
+ console.log(chalk.dim(" Your deployment domain is locked. No other instance can claim it."));
114
+ console.log(chalk.dim(" The system now operates 100% offline \u2014 no outbound calls are made."));
115
+ console.log("");
116
+ if (db) await db.disconnect();
117
+ return;
118
+ }
119
+ } catch (err) {
120
+ spinner.warn(`Check failed: ${err.message}`);
121
+ }
122
+ if (attempt < maxAttempts) {
123
+ const waitSpinner = ora(`DNS record not found yet. Retrying in 10 seconds...`).start();
124
+ await new Promise((r) => setTimeout(r, 1e4));
125
+ waitSpinner.stop();
126
+ }
127
+ }
128
+ console.log("");
129
+ console.log(chalk.yellow(" DNS record not detected yet."));
130
+ console.log("");
131
+ console.log(chalk.bold(" Make sure this TXT record exists at your DNS provider:"));
132
+ console.log("");
133
+ console.log(` ${chalk.bold("Host:")} ${chalk.cyan(`_agenticmail-verify.${domain}`)}`);
134
+ console.log(` ${chalk.bold("Type:")} ${chalk.cyan("TXT")}`);
135
+ if (dnsChallenge) {
136
+ console.log(` ${chalk.bold("Value:")} ${chalk.cyan(dnsChallenge)}`);
137
+ } else {
138
+ console.log(` ${chalk.bold("Value:")} ${chalk.dim("(check your dashboard or setup output)")}`);
139
+ }
140
+ console.log("");
141
+ console.log(chalk.dim(" DNS propagation can take up to 48 hours."));
142
+ console.log(chalk.dim(" Run with --poll to retry automatically:"));
143
+ console.log(chalk.dim(` npx @agenticmail/enterprise verify-domain --domain ${domain} --poll`));
144
+ console.log("");
145
+ if (db) await db.disconnect();
146
+ }
147
+ export {
148
+ runVerifyDomain
149
+ };
package/dist/cli.js CHANGED
@@ -14,10 +14,10 @@ switch (command) {
14
14
  import("./cli-submit-skill-SNGAHVB7.js").then((m) => m.runSubmitSkill(args.slice(1))).catch(fatal);
15
15
  break;
16
16
  case "recover":
17
- import("./cli-recover-7UPG4QZ6.js").then((m) => m.runRecover(args.slice(1))).catch(fatal);
17
+ import("./cli-recover-K7A4IIQY.js").then((m) => m.runRecover(args.slice(1))).catch(fatal);
18
18
  break;
19
19
  case "verify-domain":
20
- import("./cli-verify-WICBVLAM.js").then((m) => m.runVerifyDomain(args.slice(1))).catch(fatal);
20
+ import("./cli-verify-7EMGBE46.js").then((m) => m.runVerifyDomain(args.slice(1))).catch(fatal);
21
21
  break;
22
22
  case "reset-password":
23
23
  import("./cli-reset-password-SO5Y6MW7.js").then((m) => m.runResetPassword(args.slice(1))).catch(fatal);
@@ -57,14 +57,14 @@ Skill Development:
57
57
  break;
58
58
  case "serve":
59
59
  case "start":
60
- import("./cli-serve-BQ7NJMGJ.js").then((m) => m.runServe(args.slice(1))).catch(fatal);
60
+ import("./cli-serve-DUUELMXK.js").then((m) => m.runServe(args.slice(1))).catch(fatal);
61
61
  break;
62
62
  case "agent":
63
- import("./cli-agent-HWEJ3REY.js").then((m) => m.runAgent(args.slice(1))).catch(fatal);
63
+ import("./cli-agent-35EZUQ4N.js").then((m) => m.runAgent(args.slice(1))).catch(fatal);
64
64
  break;
65
65
  case "setup":
66
66
  default:
67
- import("./setup-2E6ZFVSS.js").then((m) => m.runSetupWizard()).catch(fatal);
67
+ import("./setup-3LZARKFD.js").then((m) => m.runSetupWizard()).catch(fatal);
68
68
  break;
69
69
  }
70
70
  function fatal(err) {
@@ -0,0 +1,11 @@
1
+ import {
2
+ createAdapter,
3
+ getSupportedDatabases,
4
+ smartDbConfig
5
+ } from "./chunk-Z3I6GNTS.js";
6
+ import "./chunk-KFQGP6VL.js";
7
+ export {
8
+ createAdapter,
9
+ getSupportedDatabases,
10
+ smartDbConfig
11
+ };
package/dist/index.js CHANGED
@@ -13,7 +13,7 @@ import {
13
13
  import {
14
14
  provision,
15
15
  runSetupWizard
16
- } from "./chunk-VIHOFXA4.js";
16
+ } from "./chunk-KHYCWUTO.js";
17
17
  import {
18
18
  AgentRuntime,
19
19
  EmailChannel,
@@ -42,7 +42,7 @@ import {
42
42
  requireRole,
43
43
  securityHeaders,
44
44
  validate
45
- } from "./chunk-JH76GUKT.js";
45
+ } from "./chunk-URC3SFYD.js";
46
46
  import "./chunk-DJBCRQTD.js";
47
47
  import {
48
48
  PROVIDER_REGISTRY,
@@ -139,7 +139,7 @@ import {
139
139
  import {
140
140
  createAdapter,
141
141
  getSupportedDatabases
142
- } from "./chunk-PAHT4ABL.js";
142
+ } from "./chunk-Z3I6GNTS.js";
143
143
  import {
144
144
  AGENTICMAIL_TOOLS,
145
145
  ALL_TOOLS,