@agenticmail/enterprise 0.5.528 → 0.5.530

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,322 @@
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-6KTIEZYC.js");
97
+ const { createServer } = await import("./server-H5MOBKCB.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 { startWatcherEngine, initWatcherTables, setWatcherRuntime } = await import("./polymarket-watcher-BFVZLR7U.js");
110
+ const edb = db.getEngineDB?.();
111
+ if (edb) {
112
+ await initWatcherTables(edb);
113
+ startWatcherEngine(db, {
114
+ log: (...args) => console.log(...args),
115
+ onEvent: (agentId, event) => {
116
+ if (event.severity === "critical") {
117
+ console.log(`[poly-watcher] CRITICAL signal for agent ${agentId}: ${event.title}`);
118
+ }
119
+ }
120
+ });
121
+ setTimeout(async () => {
122
+ try {
123
+ const routes = await import("./routes-JDDQBS4W.js");
124
+ setWatcherRuntime(
125
+ () => routes.getRuntime?.() || null
126
+ );
127
+ } catch (e) {
128
+ console.warn("[poly-watcher] Could not inject runtime:", e.message);
129
+ }
130
+ }, 5e3);
131
+ console.log("[startup] Polymarket watcher engine started");
132
+ }
133
+ setTimeout(async () => {
134
+ try {
135
+ const { autoConnectProxy } = await import("./polymarket-runtime-SVQQ3PVF.js");
136
+ const pdb = db.getEngineDB?.();
137
+ if (pdb) await autoConnectProxy(pdb);
138
+ } catch {
139
+ }
140
+ }, 8e3);
141
+ } catch (e) {
142
+ console.warn("[startup] Polymarket watcher engine skipped:", e.message);
143
+ }
144
+ try {
145
+ const { startBackgroundUpdateCheck } = await import("./cli-update-SX7GACL3.js");
146
+ startBackgroundUpdateCheck();
147
+ } catch {
148
+ }
149
+ try {
150
+ const { startPreventSleep } = await import("./screen-unlock-4RPZBHOI.js");
151
+ const adminDb = server.getAdminDb?.() || server.adminDb;
152
+ if (adminDb) {
153
+ const settings = await adminDb.getSettings?.().catch(() => null);
154
+ const screenAccess = settings?.securityConfig?.screenAccess;
155
+ if (screenAccess?.enabled && screenAccess?.preventSleep) {
156
+ startPreventSleep();
157
+ console.log("[startup] Prevent-sleep enabled \u2014 system will stay awake while agents are active");
158
+ }
159
+ }
160
+ } catch {
161
+ }
162
+ try {
163
+ await setupSystemPersistence();
164
+ } catch (e) {
165
+ console.warn("[startup] System persistence setup skipped: " + e.message);
166
+ }
167
+ const tunnelToken = process.env.CLOUDFLARED_TOKEN;
168
+ if (tunnelToken) {
169
+ try {
170
+ const { execSync, spawn } = await import("child_process");
171
+ try {
172
+ execSync(process.platform === "win32" ? "where cloudflared" : "which cloudflared", { timeout: 3e3 });
173
+ } catch {
174
+ console.log("[startup] cloudflared not found \u2014 skipping tunnel auto-start");
175
+ console.log("[startup] Install cloudflared to enable tunnel: https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/");
176
+ return;
177
+ }
178
+ try {
179
+ if (process.platform === "win32") {
180
+ const tasklist = execSync('tasklist /FI "IMAGENAME eq cloudflared.exe" /NH', { encoding: "utf8", timeout: 5e3 });
181
+ if (tasklist.includes("cloudflared.exe")) {
182
+ console.log("[startup] cloudflared tunnel already running");
183
+ return;
184
+ }
185
+ } else {
186
+ execSync('pgrep -f "cloudflared.*tunnel.*run"', { timeout: 3e3 });
187
+ console.log("[startup] cloudflared tunnel already running");
188
+ return;
189
+ }
190
+ } catch {
191
+ }
192
+ const subdomain = process.env.AGENTICMAIL_SUBDOMAIN || process.env.AGENTICMAIL_DOMAIN || "";
193
+ console.log(`[startup] Starting cloudflared tunnel${subdomain ? ` for ${subdomain}.agenticmail.io` : ""}...`);
194
+ let cfBin = "cloudflared";
195
+ if (process.platform === "win32") {
196
+ try {
197
+ cfBin = execSync("where cloudflared", { encoding: "utf8", timeout: 3e3 }).trim().split("\n")[0].trim();
198
+ } catch {
199
+ const candidate = `${process.env.LOCALAPPDATA || ""}\\cloudflared\\cloudflared.exe`;
200
+ try {
201
+ (await import("fs")).statSync(candidate);
202
+ cfBin = candidate;
203
+ } catch {
204
+ }
205
+ }
206
+ }
207
+ const child = spawn(cfBin, ["tunnel", "--no-autoupdate", "run", "--token", tunnelToken], {
208
+ detached: true,
209
+ stdio: "ignore"
210
+ });
211
+ child.unref();
212
+ console.log("[startup] cloudflared tunnel started (pid " + child.pid + ")");
213
+ } catch (e) {
214
+ console.warn("[startup] Could not auto-start cloudflared: " + e.message);
215
+ }
216
+ }
217
+ }
218
+ async function setupSystemPersistence() {
219
+ const { execSync, spawnSync } = await import("child_process");
220
+ const { existsSync: exists, writeFileSync, mkdirSync } = await import("fs");
221
+ const { join: pathJoin } = await import("path");
222
+ const platform = process.platform;
223
+ if (!process.env.PM2_HOME && !process.env.pm_id) {
224
+ return;
225
+ }
226
+ const markerDir = pathJoin(homedir(), ".agenticmail");
227
+ const markerFile = pathJoin(markerDir, ".persistence-configured");
228
+ if (exists(markerFile)) {
229
+ try {
230
+ execSync("pm2 save --silent", { timeout: 1e4, stdio: "ignore" });
231
+ } catch {
232
+ }
233
+ return;
234
+ }
235
+ console.log("[startup] Configuring system persistence (one-time setup)...");
236
+ try {
237
+ if (platform === "darwin") {
238
+ const result = spawnSync("pm2", ["startup", "launchd", "--silent"], {
239
+ timeout: 15e3,
240
+ stdio: "pipe",
241
+ encoding: "utf-8"
242
+ });
243
+ const output = (result.stdout || "") + (result.stderr || "");
244
+ const sudoMatch = output.match(/sudo\s+env\s+.*pm2\s+startup.*/);
245
+ if (sudoMatch) {
246
+ console.log("[startup] PM2 startup requires sudo. Run this once:");
247
+ console.log(" " + sudoMatch[0]);
248
+ } else {
249
+ console.log("[startup] PM2 startup configured (launchd)");
250
+ }
251
+ const plistPath = pathJoin(homedir(), "Library", "LaunchAgents", `pm2.${process.env.USER || "user"}.plist`);
252
+ if (exists(plistPath)) {
253
+ try {
254
+ execSync(`launchctl load -w "${plistPath}"`, { timeout: 5e3, stdio: "ignore" });
255
+ } catch {
256
+ }
257
+ }
258
+ } else if (platform === "linux") {
259
+ const result = spawnSync("pm2", ["startup", "systemd", "--silent"], {
260
+ timeout: 15e3,
261
+ stdio: "pipe",
262
+ encoding: "utf-8"
263
+ });
264
+ const output = (result.stdout || "") + (result.stderr || "");
265
+ const sudoMatch = output.match(/sudo\s+env\s+.*pm2\s+startup.*/);
266
+ if (sudoMatch) {
267
+ try {
268
+ execSync(sudoMatch[0], { timeout: 15e3, stdio: "ignore" });
269
+ console.log("[startup] PM2 startup configured (systemd)");
270
+ } catch {
271
+ console.log("[startup] PM2 startup requires root. Run this once:");
272
+ console.log(" " + sudoMatch[0]);
273
+ }
274
+ } else {
275
+ console.log("[startup] PM2 startup configured (systemd)");
276
+ }
277
+ } else if (platform === "win32") {
278
+ try {
279
+ execSync("npm list -g pm2-windows-startup", { timeout: 1e4, stdio: "ignore" });
280
+ } catch {
281
+ console.log("[startup] Installing pm2-windows-startup...");
282
+ try {
283
+ execSync("npm install -g pm2-windows-startup", { timeout: 6e4, stdio: "ignore" });
284
+ execSync("pm2-startup install", { timeout: 15e3, stdio: "ignore" });
285
+ console.log("[startup] PM2 startup configured (Windows Service)");
286
+ } catch (e) {
287
+ console.warn("[startup] Could not install pm2-windows-startup: " + e.message);
288
+ }
289
+ }
290
+ }
291
+ } catch (e) {
292
+ console.warn("[startup] PM2 startup setup: " + e.message);
293
+ }
294
+ try {
295
+ const moduleList = execSync("pm2 ls --silent 2>/dev/null || true", { timeout: 1e4, encoding: "utf-8" });
296
+ if (!moduleList.includes("pm2-logrotate")) {
297
+ console.log("[startup] Installing pm2-logrotate...");
298
+ execSync("pm2 install pm2-logrotate --silent", { timeout: 6e4, stdio: "ignore" });
299
+ execSync("pm2 set pm2-logrotate:max_size 10M --silent", { timeout: 5e3, stdio: "ignore" });
300
+ execSync("pm2 set pm2-logrotate:retain 5 --silent", { timeout: 5e3, stdio: "ignore" });
301
+ execSync("pm2 set pm2-logrotate:compress true --silent", { timeout: 5e3, stdio: "ignore" });
302
+ console.log("[startup] Log rotation configured (10MB, 5 files)");
303
+ }
304
+ } catch {
305
+ }
306
+ try {
307
+ execSync("pm2 save --silent", { timeout: 1e4, stdio: "ignore" });
308
+ console.log("[startup] Process list saved");
309
+ } catch {
310
+ }
311
+ try {
312
+ if (!exists(markerDir)) mkdirSync(markerDir, { recursive: true });
313
+ writeFileSync(markerFile, (/* @__PURE__ */ new Date()).toISOString() + `
314
+ platform=${platform}
315
+ `, { mode: 384 });
316
+ console.log("[startup] System persistence configured successfully");
317
+ } catch {
318
+ }
319
+ }
320
+ export {
321
+ runServe
322
+ };
package/dist/cli.js CHANGED
@@ -65,14 +65,14 @@ Skill Development:
65
65
  break;
66
66
  case "serve":
67
67
  case "start":
68
- import("./cli-serve-R4K2E4ZR.js").then((m) => m.runServe(args.slice(1))).catch(fatal);
68
+ import("./cli-serve-IYTI6P3G.js").then((m) => m.runServe(args.slice(1))).catch(fatal);
69
69
  break;
70
70
  case "agent":
71
- import("./cli-agent-HTPQCEN4.js").then((m) => m.runAgent(args.slice(1))).catch(fatal);
71
+ import("./cli-agent-UZ3ND3G6.js").then((m) => m.runAgent(args.slice(1))).catch(fatal);
72
72
  break;
73
73
  case "setup":
74
74
  default:
75
- import("./setup-C66RQXDO.js").then((m) => m.runSetupWizard()).catch(fatal);
75
+ import("./setup-76LAQJRZ.js").then((m) => m.runSetupWizard()).catch(fatal);
76
76
  break;
77
77
  }
78
78
  function fatal(err) {
@@ -132,6 +132,12 @@ export function PolymarketPage() {
132
132
  const [swapLoading, setSwapLoading] = useState(false);
133
133
  const [swapCountdown, setSwapCountdown] = useState(0);
134
134
  const [chartVisible, setChartVisible] = useState(function() { try { return localStorage.getItem('pm_chart_visible') !== 'false'; } catch { return true; } });
135
+ // Export key PIN verification
136
+ const [exportStep, setExportStep] = useState('idle'); // 'idle' | 'pin' | 'setup_pin' | 'revealed'
137
+ const [exportPin, setExportPin] = useState('');
138
+ const [exportPinSetup, setExportPinSetup] = useState({ pin: '', confirm: '' });
139
+ const [exportLoading, setExportLoading] = useState(false);
140
+ const [exportAutoCloseTimer, setExportAutoCloseTimer] = useState(null);
135
141
 
136
142
  // Countdown timer during swap
137
143
  useEffect(function() {
@@ -1072,11 +1078,12 @@ export function PolymarketPage() {
1072
1078
  // Custom modal for pending orders on a position
1073
1079
  if (selectedRow.tab === 'pendingForPosition' && d.orders) {
1074
1080
  return h('div', { className: 'modal-overlay', onClick: function() { setSelectedRow(null); } },
1075
- h('div', { className: 'modal-content', style: { maxWidth: 560, maxHeight: '80vh', overflow: 'auto' }, onClick: function(e) { e.stopPropagation(); } },
1076
- h('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 } },
1077
- h('h3', { style: { margin: 0 } }, 'Pending Orders'),
1078
- h('button', { className: 'btn btn-sm btn-secondary', onClick: function() { setSelectedRow(null); } }, '\u2715')
1081
+ h('div', { className: 'modal', onClick: function(e) { e.stopPropagation(); }, style: { width: 560, maxHeight: '85vh', overflow: 'auto' } },
1082
+ h('div', { className: 'modal-header' },
1083
+ h('h2', { style: { fontSize: 16, flex: 1, display: 'flex', alignItems: 'center', gap: 8 } }, I('clock'), ' Pending Orders'),
1084
+ h('button', { className: 'btn btn-ghost btn-icon', onClick: function() { setSelectedRow(null); } }, '\u00d7')
1079
1085
  ),
1086
+ h('div', { className: 'modal-body', style: { padding: 20 } },
1080
1087
  h('div', { style: { marginBottom: 16, padding: '10px 14px', background: 'var(--bg-secondary)', borderRadius: 8, fontSize: 13 } },
1081
1088
  h('div', { style: { fontWeight: 600, marginBottom: 4 } }, d.market || 'Position'),
1082
1089
  h('div', { style: { color: 'var(--text-muted)' } }, 'Filled shares: ', h('strong', null, (d.filled_shares || 0).toFixed(1)),
@@ -1101,6 +1108,10 @@ export function PolymarketPage() {
1101
1108
  ),
1102
1109
  h('div', { style: { marginTop: 12, fontSize: 12, color: 'var(--text-muted)', fontStyle: 'italic' } },
1103
1110
  'Total pending capital: $' + d.orders.reduce(function(s, o) { return s + (o.price || 0) * (o.size || 0); }, 0).toFixed(2))
1111
+ ),
1112
+ h('div', { className: 'modal-footer' },
1113
+ h('button', { className: 'btn btn-primary', onClick: function() { setSelectedRow(null); } }, 'Close')
1114
+ )
1104
1115
  )
1105
1116
  );
1106
1117
  }
@@ -2376,13 +2387,13 @@ export function PolymarketPage() {
2376
2387
  ),
2377
2388
  // Wallet management bar
2378
2389
  (wallet || walletBalance) && h('div', { style: { display: 'flex', gap: 8, marginTop: 16, marginBottom: 4 } },
2379
- h('button', { className: 'btn btn-sm btn-secondary', onClick: async function() {
2380
- if (!(await showConfirm('Export your wallet private key?\n\nThis will reveal the private key that controls all funds. Only do this if you need to import the wallet into MetaMask, Rabby, or another wallet app.\n\nThis action is logged in the audit trail.'))) return;
2381
- try {
2382
- var res = await apiCall('/polymarket/' + selectedAgent + '/wallet/export', { method: 'POST', body: JSON.stringify({ confirm: 'EXPORT' }) });
2383
- if (res.privateKey) { setExportedKey(res); }
2384
- else { toast(res.error || 'Export failed', 'error'); }
2385
- } catch (e) { toast(e.message || 'Export failed — owner access required', 'error'); }
2390
+ h('button', { className: 'btn btn-sm btn-secondary', onClick: function() {
2391
+ // Start PIN verification flow for export
2392
+ if (walletSecurity && walletSecurity.hasPin) {
2393
+ setExportStep('pin'); setExportPin('');
2394
+ } else {
2395
+ setExportStep('setup_pin'); setExportPinSetup({ pin: '', confirm: '' });
2396
+ }
2386
2397
  } }, I('key'), ' Export Private Key'),
2387
2398
  h('button', { className: 'btn btn-sm btn-secondary', onClick: function() { setImportKey(''); setShowImportWallet(true); } }, I('download'), ' Import Wallet'),
2388
2399
  h('button', { className: 'btn btn-sm btn-secondary', onClick: async function() {
@@ -3054,58 +3065,136 @@ export function PolymarketPage() {
3054
3065
  )
3055
3066
  ),
3056
3067
 
3057
- // Export key modal
3058
- exportedKey && h('div', { className: 'modal-overlay', onMouseMove: hideTip, onClick: function() { setExportedKey(null); } },
3068
+ // Export key modal — PIN-gated with auto-close
3069
+ exportStep !== 'idle' && h('div', { className: 'modal-overlay', onMouseMove: hideTip, onClick: function() { setExportStep('idle'); setExportedKey(null); if (exportAutoCloseTimer) clearTimeout(exportAutoCloseTimer); } },
3059
3070
  h('div', { className: 'modal', onClick: function(e) { e.stopPropagation(); }, style: { width: 520, maxHeight: '85vh', overflow: 'auto' } },
3060
3071
  h('div', { className: 'modal-header' },
3061
- h('h2', { style: { fontSize: 16, flex: 1, display: 'flex', alignItems: 'center', gap: 8 } }, I('key'), ' Wallet Private Key'),
3062
- h('button', { className: 'btn btn-ghost btn-icon', onClick: function() { setExportedKey(null); } }, '\u00d7')
3072
+ h('h2', { style: { fontSize: 16, flex: 1, display: 'flex', alignItems: 'center', gap: 8 } }, I('key'), ' Export Private Key'),
3073
+ h('button', { className: 'btn btn-ghost btn-icon', onClick: function() { setExportStep('idle'); setExportedKey(null); if (exportAutoCloseTimer) clearTimeout(exportAutoCloseTimer); } }, '\u00d7')
3063
3074
  ),
3064
3075
  h('div', { className: 'modal-body', style: { padding: 20 } },
3065
- h('div', { style: { padding: 12, background: 'rgba(239,68,68,0.08)', border: '1px solid rgba(239,68,68,0.25)', borderRadius: 8, marginBottom: 16, fontSize: 12, color: '#ef4444', lineHeight: 1.6 } },
3066
- h('strong', null, '\u26A0 SECURITY WARNING'), h('br'),
3067
- 'Anyone with this key has FULL CONTROL of this wallet and all funds. Never share it. Never paste it into untrusted sites.'
3068
- ),
3069
- exportedKey.mismatch && h('div', { style: { padding: 12, background: 'rgba(239,68,68,0.15)', border: '2px solid rgba(239,68,68,0.5)', borderRadius: 8, marginBottom: 16, fontSize: 12, color: '#dc2626', lineHeight: 1.6 } },
3070
- h('strong', null, '\u26A0 CRITICAL: KEY MISMATCH'), h('br'),
3071
- 'This private key derives address ', h('code', null, exportedKey.address),
3072
- ' but your funded wallet is ', h('code', null, exportedKey.storedFunderAddress), '. ',
3073
- h('br'), h('strong', null, 'The agent CANNOT access funds at the stored address. '),
3074
- 'This is likely caused by a VAULT_KEY environment variable change. Restore the original VAULT_KEY and restart to recover access.'
3075
- ),
3076
- h('div', { style: { marginBottom: 16 } },
3077
- h('label', { style: _labelStyle }, exportedKey.mismatch ? 'Derived Address (from private key)' : 'Wallet Address'),
3078
- h('div', { style: { fontFamily: 'var(--font-mono)', fontSize: 13, padding: '10px 12px', background: 'var(--bg-secondary)', borderRadius: 6, wordBreak: 'break-all', userSelect: 'all' } }, exportedKey.address),
3079
- exportedKey.mismatch && h('div', { style: { marginTop: 8 } },
3080
- h('label', { style: _labelStyle }, 'Stored Funder Address (has funds)'),
3081
- h('div', { style: { fontFamily: 'var(--font-mono)', fontSize: 13, padding: '10px 12px', background: 'rgba(239,68,68,0.06)', borderRadius: 6, wordBreak: 'break-all', userSelect: 'all', border: '1px solid rgba(239,68,68,0.2)' } }, exportedKey.storedFunderAddress)
3076
+
3077
+ // Step: Enter PIN
3078
+ exportStep === 'pin' && h('div', null,
3079
+ h('div', { style: { textAlign: 'center', padding: '16px 0' } },
3080
+ h('div', { style: { marginBottom: 12, color: 'var(--text-muted)' } }, I('lock', 40)),
3081
+ h('h3', { style: { marginBottom: 8 } }, 'Enter Wallet PIN'),
3082
+ h('p', { style: { fontSize: 12, color: 'var(--text-muted)', marginBottom: 16 } }, 'Enter your 6-digit wallet PIN to reveal the private key.')
3083
+ ),
3084
+ h('input', { type: 'password', value: exportPin, maxLength: 6, placeholder: '\u2022\u2022\u2022\u2022\u2022\u2022', autoFocus: true,
3085
+ style: { width: '100%', padding: '12px 16px', fontSize: 24, textAlign: 'center', letterSpacing: 8, fontFamily: 'var(--font-mono)', border: '2px solid var(--border)', borderRadius: 8, background: 'var(--bg-secondary)' },
3086
+ onChange: function(e) { setExportPin(e.target.value.replace(/\D/g, '').slice(0, 6)); }
3087
+ }),
3088
+ h('div', { style: { display: 'flex', gap: 8, marginTop: 16 } },
3089
+ h('button', { className: 'btn btn-secondary', onClick: function() { setExportStep('idle'); } }, 'Cancel'),
3090
+ h('button', { className: 'btn btn-primary', disabled: exportPin.length !== 6 || exportLoading, onClick: async function() {
3091
+ setExportLoading(true);
3092
+ try {
3093
+ var verify = await apiCall('/polymarket/' + selectedAgent + '/wallet/verify-transfer', { method: 'POST', body: JSON.stringify({ method: 'pin', code: exportPin }) });
3094
+ if (verify.ok) {
3095
+ var res = await apiCall('/polymarket/' + selectedAgent + '/wallet/export', { method: 'POST', body: JSON.stringify({ confirm: 'EXPORT' }) });
3096
+ if (res.privateKey) {
3097
+ setExportedKey(res); setExportStep('revealed');
3098
+ // Auto-close after 60 seconds
3099
+ var timer = setTimeout(function() { setExportStep('idle'); setExportedKey(null); toast('Export modal auto-closed for security', 'info'); }, 60000);
3100
+ setExportAutoCloseTimer(timer);
3101
+ } else { toast(res.error || 'Export failed', 'error'); }
3102
+ } else { toast(verify.error || 'Invalid PIN', 'error'); }
3103
+ } catch (e) { toast(e.message || 'Verification failed', 'error'); }
3104
+ setExportLoading(false);
3105
+ } }, exportLoading ? 'Verifying...' : 'Verify & Export')
3082
3106
  )
3083
3107
  ),
3084
- h('div', { style: { marginBottom: 16 } },
3085
- h('label', { style: _labelStyle }, 'Private Key'),
3086
- h('div', { style: { fontFamily: 'var(--font-mono)', fontSize: 12, padding: '10px 12px', background: 'var(--bg-secondary)', borderRadius: 6, wordBreak: 'break-all', userSelect: 'all', border: '1px solid rgba(239,68,68,0.3)' } }, exportedKey.privateKey)
3087
- ),
3088
- h('div', { style: { display: 'flex', gap: 8, marginBottom: 16 } },
3089
- h('button', { className: 'btn btn-sm btn-secondary', onClick: function() { navigator.clipboard?.writeText(exportedKey.privateKey); toast('Private key copied', 'success'); } }, 'Copy Key'),
3090
- h('button', { className: 'btn btn-sm btn-secondary', onClick: function() { navigator.clipboard?.writeText(exportedKey.address); toast('Address copied', 'success'); } }, 'Copy Address')
3091
- ),
3092
- h('div', { style: { fontSize: 13, color: 'var(--text-secondary)' } },
3093
- h('div', { style: { fontWeight: 600, marginBottom: 6 } }, 'Import into a wallet app:'),
3094
- h('div', { style: { display: 'grid', gap: 8 } },
3095
- h('div', { style: { padding: '8px 12px', background: 'var(--bg-secondary)', borderRadius: 6, fontSize: 12 } },
3096
- h('strong', null, 'MetaMask: '), 'Open MetaMask \u2192 Account menu \u2192 Import Account \u2192 Paste private key'
3108
+
3109
+ // Step: Set up PIN (first time)
3110
+ exportStep === 'setup_pin' && (function() {
3111
+ var pinVal = exportPinSetup.pin;
3112
+ var confVal = exportPinSetup.confirm;
3113
+ var isTrivial = pinVal.length === 6 && (/^(.)\1{5}$/.test(pinVal) || pinVal === '123456' || pinVal === '654321');
3114
+ var mismatch = pinVal.length === 6 && confVal.length === 6 && pinVal !== confVal;
3115
+ var canSubmit = pinVal.length === 6 && confVal.length === 6 && pinVal === confVal && !isTrivial && !exportLoading;
3116
+ return h('div', null,
3117
+ h('div', { style: { textAlign: 'center', padding: '12px 0 16px' } },
3118
+ h('div', { style: { marginBottom: 12, color: '#b45309' } }, I('shield', 40)),
3119
+ h('h3', { style: { marginBottom: 8 } }, 'Set Up Wallet PIN First'),
3120
+ h('p', { style: { fontSize: 12, color: 'var(--text-muted)', marginBottom: 4 } }, 'A 6-digit wallet PIN is required to export your private key. This PIN is also used for fund transfers.')
3097
3121
  ),
3098
- h('div', { style: { padding: '8px 12px', background: 'var(--bg-secondary)', borderRadius: 6, fontSize: 12 } },
3099
- h('strong', null, 'Rabby: '), 'Open Rabby \u2192 Add Address \u2192 Import Private Key \u2192 Paste'
3122
+ h('div', { style: { marginBottom: 12 } },
3123
+ h('label', { style: { fontSize: 12, fontWeight: 600, display: 'block', marginBottom: 4 } }, 'PIN (6 digits)'),
3124
+ h('input', { type: 'password', inputMode: 'numeric', value: pinVal, maxLength: 6, placeholder: '\u2022\u2022\u2022\u2022\u2022\u2022', autoComplete: 'new-password',
3125
+ style: { width: '100%', padding: '10px 14px', fontSize: 20, textAlign: 'center', letterSpacing: 8, fontFamily: 'var(--font-mono)', border: '2px solid ' + (isTrivial ? '#ef4444' : 'var(--border)'), borderRadius: 8, background: 'var(--bg-secondary)' },
3126
+ onInput: function(e) { setExportPinSetup(Object.assign({}, exportPinSetup, { pin: e.target.value.replace(/\D/g, '').slice(0, 6) })); }
3127
+ }),
3128
+ isTrivial && h('div', { style: { fontSize: 11, color: '#ef4444', marginTop: 4 } }, 'PIN is too simple. Choose a less predictable PIN.')
3100
3129
  ),
3101
- h('div', { style: { padding: '8px 12px', background: 'var(--bg-secondary)', borderRadius: 6, fontSize: 12 } },
3102
- h('strong', null, 'Polymarket: '), 'Go to polymarket.com \u2192 Login \u2192 Connect Wallet \u2192 Use imported wallet via MetaMask/Rabby'
3130
+ h('div', { style: { marginBottom: 12 } },
3131
+ h('label', { style: { fontSize: 12, fontWeight: 600, display: 'block', marginBottom: 4 } }, 'Confirm PIN'),
3132
+ h('input', { type: 'password', inputMode: 'numeric', value: confVal, maxLength: 6, placeholder: '\u2022\u2022\u2022\u2022\u2022\u2022', autoComplete: 'new-password',
3133
+ style: { width: '100%', padding: '10px 14px', fontSize: 20, textAlign: 'center', letterSpacing: 8, fontFamily: 'var(--font-mono)', border: '2px solid ' + (mismatch ? '#ef4444' : 'var(--border)'), borderRadius: 8, background: 'var(--bg-secondary)' },
3134
+ onInput: function(e) { setExportPinSetup(Object.assign({}, exportPinSetup, { confirm: e.target.value.replace(/\D/g, '').slice(0, 6) })); }
3135
+ }),
3136
+ mismatch && h('div', { style: { fontSize: 11, color: '#ef4444', marginTop: 4 } }, 'PINs do not match')
3137
+ ),
3138
+ h('div', { style: { display: 'flex', gap: 8, marginTop: 16 } },
3139
+ h('button', { className: 'btn btn-secondary', onClick: function() { setExportStep('idle'); } }, 'Cancel'),
3140
+ h('button', { className: 'btn btn-primary', disabled: !canSubmit, onClick: async function() {
3141
+ setExportLoading(true);
3142
+ try {
3143
+ var res = await apiCall('/polymarket/' + selectedAgent + '/wallet/setup-pin', { method: 'POST', body: JSON.stringify({ pin: pinVal }) });
3144
+ if (res.ok) {
3145
+ toast('Wallet PIN created!', 'success');
3146
+ setWalletSecurity(Object.assign({}, walletSecurity, { hasPin: true }));
3147
+ // Now export immediately
3148
+ var exp = await apiCall('/polymarket/' + selectedAgent + '/wallet/export', { method: 'POST', body: JSON.stringify({ confirm: 'EXPORT' }) });
3149
+ if (exp.privateKey) {
3150
+ setExportedKey(exp); setExportStep('revealed');
3151
+ var timer = setTimeout(function() { setExportStep('idle'); setExportedKey(null); toast('Export modal auto-closed for security', 'info'); }, 60000);
3152
+ setExportAutoCloseTimer(timer);
3153
+ }
3154
+ } else { toast(res.error || 'PIN setup failed', 'error'); }
3155
+ } catch (e) { toast(e.message, 'error'); }
3156
+ setExportLoading(false);
3157
+ } }, exportLoading ? 'Setting up...' : 'Create PIN & Export Key')
3158
+ )
3159
+ );
3160
+ })(),
3161
+
3162
+ // Step: Key revealed (auto-closes in 60s)
3163
+ exportStep === 'revealed' && exportedKey && h('div', null,
3164
+ h('div', { style: { padding: 10, background: 'rgba(180,83,9,0.1)', border: '1px solid rgba(180,83,9,0.3)', borderRadius: 8, marginBottom: 12, fontSize: 12, color: '#b45309', textAlign: 'center' } },
3165
+ I('clock'), ' This window will auto-close in 60 seconds for security.'
3166
+ ),
3167
+ h('div', { style: { padding: 12, background: 'rgba(239,68,68,0.08)', border: '1px solid rgba(239,68,68,0.25)', borderRadius: 8, marginBottom: 16, fontSize: 12, color: '#ef4444', lineHeight: 1.6 } },
3168
+ h('strong', null, '\u26A0 SECURITY WARNING'), h('br'),
3169
+ 'Anyone with this key has FULL CONTROL of this wallet and all funds. Never share it.'
3170
+ ),
3171
+ exportedKey.mismatch && h('div', { style: { padding: 12, background: 'rgba(239,68,68,0.15)', border: '2px solid rgba(239,68,68,0.5)', borderRadius: 8, marginBottom: 16, fontSize: 12, color: '#dc2626', lineHeight: 1.6 } },
3172
+ h('strong', null, '\u26A0 KEY MISMATCH'), h('br'),
3173
+ 'Key derives ', h('code', null, exportedKey.address), ' but funded wallet is ', h('code', null, exportedKey.storedFunderAddress)
3174
+ ),
3175
+ h('div', { style: { marginBottom: 16 } },
3176
+ h('label', { style: _labelStyle }, 'Wallet Address'),
3177
+ h('div', { style: { fontFamily: 'var(--font-mono)', fontSize: 13, padding: '10px 12px', background: 'var(--bg-secondary)', borderRadius: 6, wordBreak: 'break-all', userSelect: 'all' } }, exportedKey.address)
3178
+ ),
3179
+ h('div', { style: { marginBottom: 16 } },
3180
+ h('label', { style: _labelStyle }, 'Private Key'),
3181
+ h('div', { style: { fontFamily: 'var(--font-mono)', fontSize: 12, padding: '10px 12px', background: 'var(--bg-secondary)', borderRadius: 6, wordBreak: 'break-all', userSelect: 'all', border: '1px solid rgba(239,68,68,0.3)' } }, exportedKey.privateKey)
3182
+ ),
3183
+ h('div', { style: { display: 'flex', gap: 8, marginBottom: 16 } },
3184
+ h('button', { className: 'btn btn-sm btn-secondary', onClick: function() { navigator.clipboard?.writeText(exportedKey.privateKey); toast('Private key copied', 'success'); } }, 'Copy Key'),
3185
+ h('button', { className: 'btn btn-sm btn-secondary', onClick: function() { navigator.clipboard?.writeText(exportedKey.address); toast('Address copied', 'success'); } }, 'Copy Address')
3186
+ ),
3187
+ h('div', { style: { fontSize: 13, color: 'var(--text-secondary)' } },
3188
+ h('div', { style: { fontWeight: 600, marginBottom: 6 } }, 'Import into a wallet app:'),
3189
+ h('div', { style: { display: 'grid', gap: 8 } },
3190
+ h('div', { style: { padding: '8px 12px', background: 'var(--bg-secondary)', borderRadius: 6, fontSize: 12 } }, h('strong', null, 'MetaMask: '), 'Account menu \u2192 Import Account \u2192 Paste key'),
3191
+ h('div', { style: { padding: '8px 12px', background: 'var(--bg-secondary)', borderRadius: 6, fontSize: 12 } }, h('strong', null, 'Rabby: '), 'Add Address \u2192 Import Private Key \u2192 Paste')
3103
3192
  )
3104
3193
  )
3105
3194
  )
3106
3195
  ),
3107
3196
  h('div', { className: 'modal-footer' },
3108
- h('button', { className: 'btn btn-primary', onClick: function() { setExportedKey(null); } }, 'Done')
3197
+ h('button', { className: 'btn btn-primary', onClick: function() { setExportStep('idle'); setExportedKey(null); if (exportAutoCloseTimer) clearTimeout(exportAutoCloseTimer); } }, 'Close')
3109
3198
  )
3110
3199
  )
3111
3200
  ),
package/dist/index.js CHANGED
@@ -7,7 +7,7 @@ import {
7
7
  import {
8
8
  provision,
9
9
  runSetupWizard
10
- } from "./chunk-ILFP55AY.js";
10
+ } from "./chunk-F4JP4JTF.js";
11
11
  import {
12
12
  AgenticMailManager,
13
13
  GoogleEmailProvider,
@@ -28,7 +28,7 @@ import {
28
28
  executeTool,
29
29
  runAgentLoop,
30
30
  toolsToDefinitions
31
- } from "./chunk-7OINTHV5.js";
31
+ } from "./chunk-C2NLQSYZ.js";
32
32
  import "./chunk-HP63Q326.js";
33
33
  import {
34
34
  ValidationError,
@@ -43,7 +43,7 @@ import {
43
43
  requireRole,
44
44
  securityHeaders,
45
45
  validate
46
- } from "./chunk-LQ5OYZ7O.js";
46
+ } from "./chunk-OEXL5Z7T.js";
47
47
  import "./chunk-DJBCRQTD.js";
48
48
  import {
49
49
  PROVIDER_REGISTRY,
@@ -117,10 +117,10 @@ import {
117
117
  init_agent_config,
118
118
  init_deployer
119
119
  } from "./chunk-PSZU6FMQ.js";
120
- import "./chunk-APNB5LUP.js";
120
+ import "./chunk-OU4SSVW2.js";
121
121
  import "./chunk-X5IZUXDC.js";
122
122
  import "./chunk-I5IGHBXW.js";
123
- import "./chunk-MKE6LND3.js";
123
+ import "./chunk-JPYR5M5N.js";
124
124
  import {
125
125
  SecureVault,
126
126
  init_vault
@@ -128,7 +128,7 @@ import {
128
128
  import "./chunk-2CDGYMJK.js";
129
129
  import "./chunk-V3LPIDTL.js";
130
130
  import "./chunk-A4CX3XQS.js";
131
- import "./chunk-5CENM5VB.js";
131
+ import "./chunk-6SYNFKPW.js";
132
132
  import {
133
133
  CircuitBreaker,
134
134
  CircuitOpenError,