apow-cli 0.11.18 → 0.12.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/dist/index.js CHANGED
@@ -45,18 +45,25 @@ const viem_1 = require("viem");
45
45
  const MiningAgent_json_1 = __importDefault(require("./abi/MiningAgent.json"));
46
46
  const config_1 = require("./config");
47
47
  const constants_1 = require("./bridge/constants");
48
- const uniswap_1 = require("./bridge/uniswap");
49
48
  const detect_1 = require("./detect");
49
+ const errors_1 = require("./errors");
50
50
  const explorer_1 = require("./explorer");
51
51
  const fund_1 = require("./fund");
52
+ const llm_setup_1 = require("./llm-setup");
52
53
  const mint_1 = require("./mint");
53
54
  const miner_1 = require("./miner");
54
55
  const preflight_1 = require("./preflight");
56
+ const secure_env_1 = require("./secure-env");
57
+ const session_1 = require("./signer/session");
55
58
  const stats_1 = require("./stats");
59
+ const sweep_1 = require("./sweep");
56
60
  const update_1 = require("./update");
57
61
  const ui = __importStar(require("./ui"));
62
+ const brand_intro_1 = require("./brand-intro");
58
63
  const wallet_store_1 = require("./wallet-store");
59
64
  const wallet_1 = require("./wallet");
65
+ const context_1 = require("./policy/context");
66
+ const policy_1 = require("./policy/policy");
60
67
  const miningAgentAbi = MiningAgent_json_1.default;
61
68
  const erc20BalanceAbi = [
62
69
  {
@@ -98,44 +105,134 @@ function ensureGitignoreSafetyEntries() {
98
105
  (0, node_fs_1.writeFileSync)(gitignorePath, content, "utf8");
99
106
  ui.ok(`Updated .gitignore: added ${missing.join(", ")}`);
100
107
  }
101
- async function maybeCreateEncryptedKeystoreBackup(address, privateKey, opts = {}) {
102
- const envPassword = process.env.KEYSTORE_PASSWORD?.trim();
103
- let password = envPassword ?? "";
104
- if (!password && opts.promptIfMissingPassword && ui.isInteractiveSession()) {
105
- const createBackup = await ui.confirm("Create encrypted JSON keystore backup? (recommended)");
106
- if (!createBackup) {
107
- return null;
108
+ async function getKeystorePassword(required, confirmPassword = true) {
109
+ const configuredPassword = (0, config_1.resolveKeystorePassword)();
110
+ if (configuredPassword) {
111
+ return configuredPassword;
112
+ }
113
+ if (!ui.isInteractiveSession()) {
114
+ if (required) {
115
+ ui.error("KEYSTORE_PASSWORD is required to create or unlock an encrypted wallet in a headless session.");
116
+ ui.hint("Set KEYSTORE_PASSWORD in your shell or secret manager, not in chat or command history.");
108
117
  }
109
- const entered = await ui.promptSecret("Keystore password");
110
- const confirm = await ui.promptSecret("Confirm keystore password");
111
- if (!entered) {
112
- ui.warn("No keystore password entered — skipping encrypted backup.");
113
- return null;
118
+ return null;
119
+ }
120
+ const entered = await ui.promptSecret("Keystore password");
121
+ if (!entered) {
122
+ if (required) {
123
+ ui.error("No keystore password entered.");
114
124
  }
125
+ return null;
126
+ }
127
+ if (confirmPassword) {
128
+ const confirm = await ui.promptSecret("Confirm keystore password");
115
129
  if (entered !== confirm) {
116
- ui.warn("Keystore passwords did not match — skipping encrypted backup.");
130
+ ui.error("Keystore passwords did not match.");
117
131
  return null;
118
132
  }
119
- password = entered;
120
- }
121
- if (!password) {
122
- return null;
123
133
  }
134
+ (0, session_1.setSessionPassword)(entered);
135
+ return entered;
136
+ }
137
+ async function saveKeystoreWithPassword(address, privateKey, password) {
138
+ (0, session_1.setSessionPassword)(password);
124
139
  return (0, wallet_store_1.saveEncryptedKeystoreFile)(address, privateKey, password);
125
140
  }
126
141
  async function saveWalletArtifacts(address, privateKey, opts = {}) {
127
142
  const result = {};
128
- if (opts.createPlaintextImportFile !== false) {
129
- result.plaintextPath = (0, wallet_store_1.savePlaintextImportFile)(address, privateKey);
143
+ const password = await getKeystorePassword(opts.requireKeystore === true);
144
+ if (password) {
145
+ result.keystorePath = await saveKeystoreWithPassword(address, privateKey, password);
130
146
  }
131
- const keystorePath = await maybeCreateEncryptedKeystoreBackup(address, privateKey, {
132
- promptIfMissingPassword: opts.promptForKeystoreBackup === true,
133
- });
134
- if (keystorePath) {
135
- result.keystorePath = keystorePath;
147
+ else if (opts.requireKeystore) {
148
+ throw new Error("Encrypted keystore was not created.");
136
149
  }
137
150
  return result;
138
151
  }
152
+ async function unlockConfiguredKeystoreIfNeeded() {
153
+ if (wallet_1.account && config_1.config.privateKey) {
154
+ return true;
155
+ }
156
+ if (!config_1.config.keystorePath) {
157
+ return false;
158
+ }
159
+ const password = await getKeystorePassword(true, false);
160
+ if (!password) {
161
+ return false;
162
+ }
163
+ try {
164
+ (0, wallet_store_1.loadEncryptedKeystoreFile)(config_1.config.keystorePath, password);
165
+ (0, config_1.reloadConfig)();
166
+ (0, wallet_1.reinitClients)();
167
+ return !!wallet_1.account && !!config_1.config.privateKey;
168
+ }
169
+ catch (error) {
170
+ ui.error(`Could not unlock encrypted keystore: ${(0, errors_1.errorText)(error)}`);
171
+ return false;
172
+ }
173
+ }
174
+ function isActiveGeneratedWallet(wallet) {
175
+ return !!config_1.config.keystorePath
176
+ && (0, wallet_store_1.resolveKeystorePath)(config_1.config.keystorePath) === (0, wallet_store_1.resolveKeystorePath)(wallet.keystorePath);
177
+ }
178
+ function printGeneratedWallets(wallets) {
179
+ console.log("");
180
+ console.log(` ${ui.bold("APoW WALLETS")}`);
181
+ console.log("");
182
+ for (const [index, wallet] of wallets.entries()) {
183
+ const active = isActiveGeneratedWallet(wallet) ? ` ${ui.green("(active)")}` : "";
184
+ console.log(` ${index + 1}. ${wallet.address}${active}`);
185
+ }
186
+ console.log("");
187
+ }
188
+ function resolveGeneratedWalletSelection(wallets, selection) {
189
+ if (/^\d+$/.test(selection)) {
190
+ const index = Number(selection) - 1;
191
+ return wallets[index];
192
+ }
193
+ if (!/^0x[0-9a-fA-F]{40}$/.test(selection)) {
194
+ return undefined;
195
+ }
196
+ return wallets.find((wallet) => wallet.address.toLowerCase() === selection.toLowerCase());
197
+ }
198
+ async function unlockGeneratedWallet(wallet) {
199
+ const configuredPassword = (0, config_1.resolveKeystorePassword)();
200
+ if (configuredPassword) {
201
+ try {
202
+ const privateKey = (0, wallet_store_1.loadEncryptedKeystoreFile)(wallet.keystorePath, configuredPassword);
203
+ const { privateKeyToAccount } = await Promise.resolve().then(() => __importStar(require("viem/accounts")));
204
+ if (privateKeyToAccount(privateKey).address.toLowerCase() === wallet.address.toLowerCase()) {
205
+ return configuredPassword;
206
+ }
207
+ }
208
+ catch {
209
+ // This wallet may use a different password; prompt below when interactive.
210
+ }
211
+ }
212
+ if (!ui.isInteractiveSession()) {
213
+ ui.error("Could not unlock the selected wallet in this headless session.");
214
+ ui.hint("Provide its password through KEYSTORE_PASSWORD_CMD or a shell secret manager.");
215
+ return null;
216
+ }
217
+ const password = await ui.promptSecret(`Keystore password for ${wallet.address.slice(0, 6)}...${wallet.address.slice(-4)}`);
218
+ if (!password) {
219
+ ui.error("No keystore password entered.");
220
+ return null;
221
+ }
222
+ try {
223
+ const privateKey = (0, wallet_store_1.loadEncryptedKeystoreFile)(wallet.keystorePath, password);
224
+ const { privateKeyToAccount } = await Promise.resolve().then(() => __importStar(require("viem/accounts")));
225
+ if (privateKeyToAccount(privateKey).address.toLowerCase() !== wallet.address.toLowerCase()) {
226
+ ui.error("The selected keystore does not match its registered wallet address.");
227
+ return null;
228
+ }
229
+ return password;
230
+ }
231
+ catch {
232
+ ui.error("Could not unlock the selected wallet. Check the password and try again.");
233
+ return null;
234
+ }
235
+ }
139
236
  function shouldSkipUpdateCheck(argv) {
140
237
  return argv.includes("--help")
141
238
  || argv.includes("-h")
@@ -143,35 +240,70 @@ function shouldSkipUpdateCheck(argv) {
143
240
  || argv.includes("-V")
144
241
  || argv[0] === "help";
145
242
  }
146
- async function setupWizard() {
147
- console.log("");
148
- ui.banner(["APoW Agent Setup"]);
149
- console.log("");
243
+ async function setupWizard(options = {}) {
244
+ if (options.showBrandIntro !== false) {
245
+ await (0, brand_intro_1.showBrandIntro)("setup");
246
+ }
150
247
  // Mode selection
151
- console.log(` ${ui.bold("Choose an operating mode")}`);
152
- console.log("");
153
- console.log(` ${ui.cyan("1.")} Easy Mode ${ui.dim("(recommended)")}`);
154
- console.log(` ${ui.dim("No config. Wallet + x402 RPC + x402 LLM + x402 GPU grind.")}`);
155
- console.log(` ${ui.cyan("2.")} Advanced Mode`);
156
- console.log(` ${ui.dim("Choose which parts your agent manages and which credentials you supply.")}`);
157
- console.log("");
158
- const modeInput = await ui.prompt("Choice", "1");
159
- const easyMode = modeInput !== "2";
248
+ let easyMode = true;
249
+ if (options.easyMode) {
250
+ ui.ok("Easy Mode selected.");
251
+ }
252
+ else {
253
+ console.log(` ${ui.bold("Choose an operating mode")}`);
254
+ console.log("");
255
+ console.log(` ${ui.cyan("1.")} Easy Mode ${ui.dim("(recommended)")}`);
256
+ console.log(` ${ui.dim("No config. Wallet + QuickNode x402 RPC + ClawRouter x402 LLM + RunPod x402 GPU.")}`);
257
+ console.log(` ${ui.cyan("2.")} Advanced Mode`);
258
+ console.log(` ${ui.dim("Choose which parts your agent manages and which credentials you supply.")}`);
259
+ console.log("");
260
+ const modeInput = await ui.prompt("Choice", "1");
261
+ easyMode = modeInput !== "2";
262
+ }
160
263
  console.log("");
161
264
  const totalSteps = easyMode ? 2 : 4;
162
265
  const values = {};
163
266
  // Step 1: Wallet
164
267
  console.log(` ${ui.bold(`Step 1/${totalSteps}: Wallet`)}`);
165
- console.log(` ${ui.dim("Your agent can manage a wallet for you, or you can supply your own.")}`);
166
- console.log("");
167
- console.log(` ${ui.cyan("1.")} Agent-managed wallet ${ui.dim("(generate one now)")}`);
168
- console.log(` ${ui.cyan("2.")} Existing wallet ${ui.dim("(paste private key)")}`);
169
- console.log("");
170
- const walletMode = await ui.prompt("Wallet choice", "1");
171
- const useExistingWallet = walletMode === "2";
172
- let privateKey;
268
+ let walletMode = "1";
269
+ if (options.easyMode) {
270
+ console.log(` ${ui.dim("Generating one dedicated encrypted APoW wallet.")}`);
271
+ console.log("");
272
+ }
273
+ else {
274
+ console.log(` ${ui.dim("Your agent can manage a wallet for you, or you can supply your own.")}`);
275
+ console.log("");
276
+ console.log(` ${ui.cyan("1.")} Agent-managed encrypted wallet ${ui.dim("(generate one now)")}`);
277
+ console.log(` ${ui.cyan("2.")} Existing encrypted keystore`);
278
+ console.log(` ${ui.cyan("3.")} Existing private key ${ui.dim("(encrypt before saving)")}`);
279
+ console.log("");
280
+ walletMode = await ui.prompt("Wallet choice", "1");
281
+ }
173
282
  let addr;
174
- if (useExistingWallet) {
283
+ let keystorePath;
284
+ if (walletMode === "2") {
285
+ const inputPath = await ui.prompt("Keystore path", process.env.KEYSTORE_PATH ?? "");
286
+ if (!inputPath) {
287
+ ui.error("Keystore path is required.");
288
+ return;
289
+ }
290
+ const password = await getKeystorePassword(true, false);
291
+ if (!password) {
292
+ return;
293
+ }
294
+ try {
295
+ const privateKey = (0, wallet_store_1.loadEncryptedKeystoreFile)(inputPath, password);
296
+ const { privateKeyToAccount } = await Promise.resolve().then(() => __importStar(require("viem/accounts")));
297
+ const walletAccount = privateKeyToAccount(privateKey);
298
+ addr = walletAccount.address;
299
+ keystorePath = (0, wallet_store_1.resolveKeystorePath)(inputPath);
300
+ }
301
+ catch (error) {
302
+ ui.error(`Could not unlock keystore: ${(0, errors_1.errorText)(error)}`);
303
+ return;
304
+ }
305
+ }
306
+ else if (walletMode === "3") {
175
307
  const inputKey = await ui.promptSecret("Private key (0x-prefixed)");
176
308
  if (!inputKey) {
177
309
  ui.error("Private key is required.");
@@ -181,69 +313,68 @@ async function setupWizard() {
181
313
  ui.error("Invalid private key format. Must be 0x + 64 hex characters.");
182
314
  return;
183
315
  }
184
- privateKey = inputKey;
185
316
  const { privateKeyToAccount } = await Promise.resolve().then(() => __importStar(require("viem/accounts")));
186
- const walletAccount = privateKeyToAccount(privateKey);
317
+ const walletAccount = privateKeyToAccount(inputKey);
187
318
  addr = walletAccount.address;
319
+ const password = await getKeystorePassword(true);
320
+ if (!password) {
321
+ return;
322
+ }
323
+ keystorePath = await saveKeystoreWithPassword(addr, inputKey, password);
324
+ console.log("");
325
+ console.log(` ${ui.dim(`Encrypted keystore saved to: ${keystorePath}`)}`);
188
326
  }
189
327
  else {
328
+ const password = await getKeystorePassword(true);
329
+ if (!password) {
330
+ return;
331
+ }
190
332
  const { generatePrivateKey, privateKeyToAccount } = await Promise.resolve().then(() => __importStar(require("viem/accounts")));
191
- privateKey = generatePrivateKey();
333
+ const privateKey = generatePrivateKey();
192
334
  const walletAccount = privateKeyToAccount(privateKey);
193
335
  addr = walletAccount.address;
336
+ keystorePath = await saveKeystoreWithPassword(addr, privateKey, password);
337
+ (0, wallet_store_1.registerGeneratedWallet)(addr, keystorePath);
194
338
  console.log("");
195
339
  console.log(` ${ui.bold("NEW WALLET GENERATED")}`);
196
340
  console.log("");
197
341
  console.log(` Address: ${addr}`);
198
- console.log(` Private Key: ${privateKey}`);
342
+ console.log(` Keystore: ${keystorePath}`);
199
343
  console.log("");
200
- console.log(` ${ui.yellow("⚠ SAVE YOUR PRIVATE KEY — this is the only time")}`);
201
- console.log(` ${ui.yellow(" it will be displayed. Anyone with this key")}`);
202
- console.log(` ${ui.yellow(" controls your funds.")}`);
203
- console.log("");
204
- console.log(` ${ui.dim("Import into Phantom, MetaMask, or any EVM wallet")}`);
205
- console.log(` ${ui.dim("to view your AGENT tokens and Mining Rig NFT.")}`);
344
+ console.log(` ${ui.dim("Back up the encrypted keystore and its password separately.")}`);
206
345
  console.log("");
207
346
  console.log(` ${ui.dim("Fund this address with ≥0.005 ETH on Base to start.")}`);
208
347
  console.log("");
209
- const artifacts = await saveWalletArtifacts(addr, privateKey);
210
- if (artifacts.plaintextPath) {
211
- console.log(` ${ui.dim(`Import helper saved to: ${artifacts.plaintextPath}`)}`);
212
- console.log(` ${ui.yellow("This plaintext file is easy to import, but less secure than an encrypted keystore.")}`);
213
- }
214
- if (artifacts.keystorePath) {
215
- console.log(` ${ui.dim(`Encrypted keystore saved to: ${artifacts.keystorePath}`)}`);
216
- }
217
- else {
218
- console.log(` ${ui.dim("Tip: set KEYSTORE_PASSWORD or rerun wallet export to create an encrypted JSON keystore backup.")}`);
219
- }
220
- console.log("");
221
348
  }
222
- values.PRIVATE_KEY = privateKey;
349
+ values.PRIVATE_KEY = "";
350
+ if (keystorePath) {
351
+ values.KEYSTORE_PATH = keystorePath;
352
+ }
223
353
  ui.ok(`Wallet: ${addr.slice(0, 6)}...${addr.slice(-4)}`);
224
354
  console.log("");
225
355
  if (easyMode) {
226
- // Easy Mode: fully autonomous x402 stack
356
+ // Easy Mode: automated wallet-paid x402 stack
227
357
  console.log(` ${ui.bold(`Step 2/${totalSteps}: Configuration`)}`);
228
358
  values.USE_X402 = "true";
229
359
  values.USE_X402_GRIND = "true";
230
360
  values.LLM_PROVIDER = "clawrouter";
231
- values.LLM_MODEL = "blockrun/eco";
232
361
  values.ALLOW_LOCAL_FALLBACK_WITH_X402 = "false";
233
- ui.ok("RPC: QuickNode x402 (wallet-paid, no API key)");
234
- ui.ok("LLM: ClawRouter x402 (wallet-paid, no API key)");
235
- ui.ok("Grinder: x402 GPU (remote, wallet-paid, no local CPU fallback)");
362
+ ui.ok("RPC: Auto (Zero Config via QuickNode x402; wallet-paid in USDC)");
363
+ ui.ok("LLM: Auto (Zero Config via ClawRouter x402; wallet-paid in USDC)");
364
+ ui.ok("Grinder: Auto (Zero Config via RunPod x402; wallet-paid in USDC)");
236
365
  console.log(` ${ui.dim("Easy mode is agent-first: no RPC key, no LLM key, no GPU rental setup.")}`);
237
- console.log(` ${ui.dim("Fund the wallet with ETH + USDC on Base, then run: apow start")}`);
366
+ console.log(` ${ui.dim(`Fund the wallet with ETH + USDC on Base, then run: apow start${options.easyMode ? " --easy" : ""}`)}`);
238
367
  }
239
368
  else {
240
369
  // Advanced: user picks which services remain autonomous
241
370
  // Step 2: RPC
242
371
  console.log(` ${ui.bold(`Step 2/${totalSteps}: RPC`)}`);
243
- console.log(` ${ui.dim("Choose whether your agent pays for RPC via x402 or you provide your own endpoint.")}`);
372
+ console.log(` ${ui.dim("Choose automatic wallet-paid RPC or provide your own Base endpoint.")}`);
244
373
  console.log("");
245
- console.log(` ${ui.cyan("1.")} Agent-managed x402 RPC ${ui.dim("(recommended)")}`);
374
+ console.log(` ${ui.cyan("1.")} Auto ${ui.dim("(recommended — Zero Config via QuickNode x402)")}`);
375
+ console.log(` ${ui.dim("No account or API key to connect.")}`);
246
376
  console.log(` ${ui.cyan("2.")} Custom RPC URL`);
377
+ console.log(` ${ui.dim("Get a free Base RPC URL from Alchemy: https://www.alchemy.com/")}`);
247
378
  console.log("");
248
379
  const rpcMode = await ui.prompt("RPC choice", "1");
249
380
  if (rpcMode === "2") {
@@ -253,42 +384,48 @@ async function setupWizard() {
253
384
  ui.ok(`RPC: Custom (${rpcUrl.slice(0, 40)}${rpcUrl.length > 40 ? "..." : ""})`);
254
385
  }
255
386
  else {
256
- ui.warn("No URL provided — using QuickNode x402");
387
+ ui.warn("No URL provided — using Auto RPC via x402");
257
388
  values.USE_X402 = "true";
258
- ui.ok("RPC: QuickNode x402");
389
+ ui.ok("RPC: Auto (Zero Config via QuickNode x402)");
259
390
  }
260
391
  }
261
392
  else {
262
393
  values.USE_X402 = "true";
263
- ui.ok("RPC: QuickNode x402 (wallet-paid)");
394
+ ui.ok("RPC: Auto (Zero Config via QuickNode x402; wallet-paid in USDC)");
264
395
  }
265
396
  console.log("");
266
397
  // Step 3: LLM (for minting)
267
398
  console.log(` ${ui.bold(`Step 3/${totalSteps}: LLM (minting only)`)}`);
268
399
  console.log(` ${ui.dim("An LLM solves the SMHL challenge when minting your Mining Rig.")}`);
269
400
  console.log(` ${ui.dim("Mining uses optimized solving — no LLM needed after minting.")}`);
270
- console.log(` ${ui.dim(" clawrouter (recommended) — wallet-paid via x402")}`);
271
- console.log(` ${ui.dim(" openai / anthropic / gemini / deepseek / qwen — API key")}`);
272
- console.log(` ${ui.dim(" ollama / claude-code / codex — local")}`);
273
- const providerInput = await ui.prompt("Provider", "clawrouter");
274
- const provider = (["clawrouter", "openai", "anthropic", "gemini", "ollama", "deepseek", "qwen", "claude-code", "codex"].includes(providerInput) ? providerInput : "clawrouter");
275
- values.LLM_PROVIDER = provider;
276
- if (provider === "clawrouter") {
277
- ui.ok("ClawRouter x402 — no API key needed, pays with USDC from your wallet");
401
+ console.log("");
402
+ console.log(` ${ui.cyan("1.")} Auto ${ui.dim("(recommended — Zero Config via ClawRouter x402)")}`);
403
+ console.log(` ${ui.dim("No account or API key to connect.")}`);
404
+ console.log(` ${ui.dim("Typical ClawRouter eco cost: $0–$0.0004 USDC per call; varies by usage.")}`);
405
+ console.log(` ${ui.cyan("2.")} API key ${ui.dim("(OpenAI, Anthropic, or Gemini; more providers available)")}`);
406
+ console.log(` ${ui.cyan("3.")} Local / subscription CLI ${ui.dim("(Ollama, Claude Code, or Codex)")}`);
407
+ console.log("");
408
+ const llmMode = (0, llm_setup_1.resolveLlmSetupMode)(await ui.prompt("LLM choice", "1"));
409
+ let provider;
410
+ if (llmMode === "x402") {
411
+ provider = "clawrouter";
412
+ values.LLM_PROVIDER = provider;
413
+ ui.ok("Auto LLM enabled — Zero Config via ClawRouter x402; wallet-paid in USDC");
278
414
  if (!values.USE_X402 && !values.RPC_URL) {
279
415
  values.USE_X402 = "true";
280
416
  ui.ok("Auto-enabled x402 RPC (same wallet, same USDC balance)");
281
417
  }
282
418
  }
283
- else if (provider === "ollama") {
284
- const ollamaUrl = await ui.prompt("Ollama URL", "http://127.0.0.1:11434");
285
- values.OLLAMA_URL = ollamaUrl;
286
- ui.ok(`Ollama at ${ollamaUrl}`);
287
- }
288
- else if (provider === "claude-code" || provider === "codex") {
289
- ui.ok(`Using local ${provider} CLI — make sure you're already authenticated`);
290
- }
291
- else {
419
+ else if (llmMode === "api-key") {
420
+ console.log("");
421
+ console.log(` ${ui.cyan("1.")} OpenAI`);
422
+ console.log(` ${ui.cyan("2.")} Anthropic`);
423
+ console.log(` ${ui.cyan("3.")} Gemini`);
424
+ console.log(` ${ui.cyan("4.")} DeepSeek`);
425
+ console.log(` ${ui.cyan("5.")} Qwen`);
426
+ console.log("");
427
+ provider = (0, llm_setup_1.resolveApiProvider)(await ui.prompt("API provider", "1"));
428
+ values.LLM_PROVIDER = provider;
292
429
  const apiKey = await ui.promptSecret("API key");
293
430
  if (apiKey) {
294
431
  values.LLM_API_KEY = apiKey;
@@ -298,38 +435,57 @@ async function setupWizard() {
298
435
  ui.fail("No API key provided");
299
436
  ui.hint("Set LLM_API_KEY in .env later");
300
437
  }
438
+ const model = await ui.prompt("Model", (0, config_1.resolveDefaultModel)(provider));
439
+ values.LLM_MODEL = model;
440
+ if ((0, config_1.isExpensiveModel)(model)) {
441
+ ui.warn(`${model} is expensive. Consider a smaller model for lower cost.`);
442
+ }
301
443
  }
302
- const defaultModel = (0, config_1.resolveDefaultModel)(provider);
303
- const model = await ui.prompt("Model", defaultModel);
304
- values.LLM_MODEL = model;
305
- if ((0, config_1.isExpensiveModel)(model)) {
306
- ui.warn(`${model} is expensive. Consider gpt-4o-mini for lower cost.`);
444
+ else {
445
+ console.log("");
446
+ console.log(` ${ui.cyan("1.")} Ollama ${ui.dim("(model runs on this machine)")}`);
447
+ console.log(` ${ui.cyan("2.")} Claude Code ${ui.dim("(hosted via your Claude subscription)")}`);
448
+ console.log(` ${ui.cyan("3.")} Codex ${ui.dim("(hosted via your ChatGPT subscription)")}`);
449
+ console.log("");
450
+ provider = (0, llm_setup_1.resolveLocalProvider)(await ui.prompt("Local / subscription provider", "1"));
451
+ values.LLM_PROVIDER = provider;
452
+ const model = (0, config_1.resolveDefaultModel)(provider);
453
+ values.LLM_MODEL = model;
454
+ if (provider === "ollama") {
455
+ const ollamaUrl = await ui.prompt("Ollama URL", "http://127.0.0.1:11434");
456
+ values.OLLAMA_URL = ollamaUrl;
457
+ values.LLM_MODEL = await ui.prompt("Ollama model", model);
458
+ ui.ok(`Ollama at ${ollamaUrl} (local inference)`);
459
+ ui.hint(`Run \`ollama pull ${values.LLM_MODEL}\` before minting.`);
460
+ }
461
+ else if (provider === "claude-code") {
462
+ ui.ok(`Claude Code subscription — ${model} auto-selected`);
463
+ ui.hint("Requires an installed, signed-in Claude Code CLI. APoW disables its tools for SMHL.");
464
+ }
465
+ else {
466
+ ui.ok(`Codex subscription — ${model} auto-selected`);
467
+ ui.hint("Requires an installed, signed-in Codex CLI. APoW uses a read-only isolated run for SMHL.");
468
+ }
307
469
  }
308
470
  console.log("");
309
471
  // Step 4: Nonce grinding strategy
310
472
  console.log(` ${ui.bold(`Step 4/${totalSteps}: GPU Grinding`)}`);
311
473
  console.log(` ${ui.dim("Choose how the miner should find nonces at current network difficulty.")}`);
312
474
  console.log("");
313
- console.log(` ${ui.cyan("1.")} Agent-managed x402 GPU ${ui.dim("(recommended, no setup)")}`);
314
- console.log(` ${ui.cyan("2.")} Local / custom grinders only`);
315
- console.log(` ${ui.cyan("3.")} Hybrid ${ui.dim("(x402 GPU + local JS fallback)")}`);
475
+ console.log(` ${ui.cyan("1.")} Auto ${ui.dim("(recommended — Zero Config via RunPod x402)")}`);
476
+ console.log(` ${ui.dim("No account, API key, or GPU rental setup to connect.")}`);
477
+ console.log(` ${ui.cyan("2.")} Local CPU/GPU`);
316
478
  console.log("");
317
479
  const grindMode = await ui.prompt("Grinding choice", "1");
318
480
  if (grindMode === "2") {
319
481
  values.USE_X402_GRIND = "false";
320
482
  values.ALLOW_LOCAL_FALLBACK_WITH_X402 = "false";
321
- ui.ok("Grinding: local/custom only");
322
- ui.hint("Configure GPU_GRINDER_PATH, CUDA_GRINDER_PATH, or VAST_* yourself if needed.");
323
- }
324
- else if (grindMode === "3") {
325
- values.USE_X402_GRIND = "true";
326
- values.ALLOW_LOCAL_FALLBACK_WITH_X402 = "true";
327
- ui.ok("Grinding: x402 GPU with local JS fallback");
483
+ ui.ok("Grinding: Local CPU/GPU");
328
484
  }
329
485
  else {
330
486
  values.USE_X402_GRIND = "true";
331
487
  values.ALLOW_LOCAL_FALLBACK_WITH_X402 = "false";
332
- ui.ok("Grinding: x402 GPU only");
488
+ ui.ok("Grinding: Auto (Zero Config via RunPod x402)");
333
489
  }
334
490
  }
335
491
  // Contract addresses
@@ -338,43 +494,49 @@ async function setupWizard() {
338
494
  console.log("");
339
495
  // Check for existing .env
340
496
  const envPath = (0, node_path_1.join)(process.cwd(), ".env");
341
- if ((0, node_fs_1.existsSync)(envPath)) {
342
- const overwrite = await ui.confirm("Overwrite existing .env?");
343
- if (!overwrite) {
497
+ if ((0, node_fs_1.existsSync)(envPath) && !options.easyMode) {
498
+ ui.hint("This updates APoW setup values, including the active wallet. Unrelated environment variables are kept.");
499
+ const update = await ui.confirm("Update existing .env with these settings?");
500
+ if (!update) {
344
501
  console.log(" Setup cancelled.");
345
502
  return;
346
503
  }
347
504
  }
348
505
  await (0, config_1.writeEnvFile)(values);
506
+ const policyFile = (0, policy_1.writeDefaultPolicyFile)();
349
507
  (0, config_1.reloadConfig)();
350
508
  (0, wallet_1.reinitClients)();
351
509
  ui.ok("Config saved to .env");
510
+ ui.ok(`Policy ready at ${policyFile}`);
352
511
  ensureGitignoreSafetyEntries();
353
- console.log("");
354
- console.log(` Next: ${ui.cyan("apow start")}`);
355
- console.log(` ${ui.dim("Guided happy path: setup -> fund -> mint -> mine")}`);
356
- console.log("");
512
+ if (!options.easyMode) {
513
+ console.log("");
514
+ console.log(` Next: ${ui.cyan("apow start")}`);
515
+ console.log(` ${ui.dim("Guided happy path: setup -> fund -> mint -> mine")}`);
516
+ console.log("");
517
+ }
357
518
  }
358
- function showHeadlessFundingHandoff(address, needsEth, needsUsdc) {
359
- ui.warn("Headless session detected — pausing before funding.");
519
+ function showFundingHandoff(address, needsEth, needsUsdc, easyMode) {
520
+ ui.warn("Pausing for Base funding.");
360
521
  ui.hint(`Send funds to ${address} on Base.`);
361
522
  if (needsEth) {
362
523
  ui.hint(`Need at least ${constants_1.MIN_ETH} ETH for gas and minting.`);
363
524
  }
364
525
  if (needsUsdc) {
365
- ui.hint(`Need at least ${constants_1.MIN_USDC} USDC for QuickNode + ClawRouter x402.`);
526
+ ui.hint(`Need at least ${constants_1.MIN_USDC} USDC for x402 RPC + LLM services.`);
366
527
  }
367
- ui.hint("Funding routes:");
368
- ui.hint("Direct on Base: send ETH and/or USDC to this wallet");
369
- ui.hint("Bridge from Solana: apow fund --chain solana --token sol");
370
- ui.hint("Bridge from Ethereum: apow fund --chain ethereum");
371
- ui.hint("After funds arrive, rerun `apow start`.");
528
+ ui.hint(`After funds arrive, rerun \`apow start${easyMode ? " --easy" : ""}\`.`);
372
529
  }
373
- async function runStartFlow() {
530
+ async function runStartFlow(options = {}) {
531
+ await (0, brand_intro_1.showBrandIntro)("start");
532
+ const unlockedConfiguredWallet = await unlockConfiguredKeystoreIfNeeded();
533
+ if (config_1.config.keystorePath && !unlockedConfiguredWallet && !wallet_1.account) {
534
+ return;
535
+ }
374
536
  if (!config_1.config.privateKey || !wallet_1.account) {
375
537
  console.log("");
376
538
  ui.warn("No wallet configured — launching setup.");
377
- await setupWizard();
539
+ await setupWizard({ easyMode: options.easyMode === true, showBrandIntro: false });
378
540
  (0, config_1.reloadConfig)();
379
541
  (0, wallet_1.reinitClients)();
380
542
  }
@@ -382,12 +544,17 @@ async function runStartFlow() {
382
544
  ui.error("Wallet configuration did not complete.");
383
545
  return;
384
546
  }
385
- const bootstrapClient = config_1.config.useX402 && config_1.config.chainName === "base"
386
- ? (0, viem_1.createPublicClient)({ chain: config_1.config.chain, transport: (0, viem_1.http)("https://1rpc.io/base") })
547
+ if (options.easyMode) {
548
+ const policyError = (0, policy_1.validateEasyModePolicyCaps)((0, policy_1.loadPolicy)());
549
+ if (policyError) {
550
+ ui.error(policyError);
551
+ ui.hint("Restore the default enforce-mode Easy Mode caps, then retry.");
552
+ return;
553
+ }
554
+ }
555
+ const bootstrapClient = config_1.config.useX402 && config_1.config.chainName === "base" && config_1.config.rpcUrl
556
+ ? (0, viem_1.createPublicClient)({ chain: config_1.config.chain, transport: (0, viem_1.http)(config_1.config.rpcUrl) })
387
557
  : wallet_1.publicClient;
388
- console.log("");
389
- ui.banner(["APoW Start"]);
390
- console.log("");
391
558
  let miners = [];
392
559
  try {
393
560
  miners = await (0, detect_1.detectMinersWithClient)(bootstrapClient, wallet_1.account.address);
@@ -400,7 +567,7 @@ async function runStartFlow() {
400
567
  console.log(` ${ui.green("Wallet ready.")} Found ${miners.length} rig${miners.length === 1 ? "" : "s"} — starting miner #${best.tokenId}.`);
401
568
  console.log("");
402
569
  await (0, preflight_1.runPreflight)("mining");
403
- await (0, miner_1.startMining)(best.tokenId);
570
+ await (0, miner_1.startMining)(best.tokenId, { easyMode: options.easyMode === true });
404
571
  return;
405
572
  }
406
573
  let ethBalance = 0;
@@ -429,31 +596,26 @@ async function runStartFlow() {
429
596
  const needsUsdc = config_1.config.useX402 && (!balanceChecksAvailable || usdcBalance < constants_1.MIN_USDC);
430
597
  if (needsEth || needsUsdc) {
431
598
  console.log(` ${ui.yellow("Funding needed before minting.")}`);
432
- ui.table([
599
+ const fundingRows = [
433
600
  ["Wallet", `${wallet_1.account.address.slice(0, 6)}...${wallet_1.account.address.slice(-4)}`],
434
601
  ["ETH", balanceChecksAvailable ? `${ethBalance.toFixed(6)} ETH${needsEth ? ` (need ≥${constants_1.MIN_ETH})` : ""}` : "unknown (RPC check failed)"],
435
- ["USDC", config_1.config.useX402 ? (balanceChecksAvailable ? `${usdcBalance.toFixed(2)} USDC${needsUsdc ? ` (need ≥${constants_1.MIN_USDC})` : ""}` : "unknown (RPC check failed)") : "not required"],
436
- ]);
437
- console.log("");
438
- if (!ui.isInteractiveSession()) {
439
- showHeadlessFundingHandoff(wallet_1.account.address, needsEth, needsUsdc);
440
- return;
441
- }
442
- const runFunding = await ui.confirm("Run funding flow now?");
443
- if (!runFunding) {
444
- ui.hint("Fund the wallet, then rerun `apow start`.");
445
- return;
446
- }
447
- await (0, fund_1.runFundFlow)({});
448
- const refreshedEth = Number((0, viem_1.formatEther)(await (0, wallet_1.getEthBalance)()));
449
- const refreshedUsdc = config_1.config.useX402 ? Number((0, viem_1.formatUnits)(await (0, uniswap_1.getUsdcBalance)(wallet_1.account.address), 6)) : usdcBalance;
450
- if (refreshedEth < constants_1.MIN_ETH || (config_1.config.useX402 && refreshedUsdc < constants_1.MIN_USDC)) {
451
- ui.warn("Funding is still incomplete.");
452
- ui.hint("Bridge or deposit may still be pending. Rerun `apow start` once balances update.");
453
- return;
602
+ ];
603
+ if (config_1.config.useX402) {
604
+ fundingRows.push([
605
+ "USDC",
606
+ balanceChecksAvailable ? `${usdcBalance.toFixed(2)} USDC${needsUsdc ? ` (need ≥${constants_1.MIN_USDC})` : ""}` : "unknown (RPC check failed)",
607
+ ]);
454
608
  }
609
+ ui.table(fundingRows);
610
+ console.log("");
611
+ showFundingHandoff(wallet_1.account.address, needsEth, needsUsdc, options.easyMode === true);
612
+ return;
455
613
  }
456
- await (0, mint_1.runMintFlow)({ startMiningAfterMint: true });
614
+ (0, context_1.setSignerContext)("mint");
615
+ await (0, mint_1.runMintFlow)({
616
+ easyMode: options.easyMode === true,
617
+ startMiningAfterMint: true,
618
+ });
457
619
  }
458
620
  async function main() {
459
621
  const version = readVersion();
@@ -479,6 +641,9 @@ async function main() {
479
641
  .name("apow")
480
642
  .description("Mine AGENT tokens on Base L2 with Agentic Proof of Work")
481
643
  .version(version);
644
+ if (config_1.config.walletSource === "private-key") {
645
+ ui.warn("Legacy PRIVATE_KEY is loaded. Run `apow wallet migrate` to encrypt it into a keystore.");
646
+ }
482
647
  program
483
648
  .command("setup")
484
649
  .description("Agent-first setup wizard — choose Easy Mode (x402 for everything) or Advanced Mode")
@@ -487,9 +652,10 @@ async function main() {
487
652
  });
488
653
  program
489
654
  .command("start")
490
- .description("Agent-first happy path: setup -> fund -> mint -> mine")
491
- .action(async () => {
492
- await runStartFlow();
655
+ .description("Agent-first path: setup -> Base funding handoff -> mint -> mine")
656
+ .option("--easy", "Use the existing Easy Mode without the mode-selection prompt")
657
+ .action(async (opts) => {
658
+ await runStartFlow({ easyMode: opts.easy === true });
493
659
  });
494
660
  program
495
661
  .command("fund")
@@ -499,6 +665,8 @@ async function main() {
499
665
  .option("--amount <eth>", "Target ETH amount (default: 0.005)")
500
666
  .option("--no-swap", "Skip auto-split after bridging")
501
667
  .action(async (opts) => {
668
+ (0, context_1.setSignerContext)("fund");
669
+ await unlockConfiguredKeystoreIfNeeded();
502
670
  if (!config_1.config.privateKey || !wallet_1.account) {
503
671
  ui.warn("No wallet configured — launching setup first.");
504
672
  await setupWizard();
@@ -515,6 +683,8 @@ async function main() {
515
683
  .command("mint")
516
684
  .description("Mint a new miner NFT (Easy Mode: x402 LLM, no API key)")
517
685
  .action(async () => {
686
+ (0, context_1.setSignerContext)("mint");
687
+ await unlockConfiguredKeystoreIfNeeded();
518
688
  if (!config_1.config.privateKey || !wallet_1.account) {
519
689
  ui.warn("No wallet configured — launching setup first.");
520
690
  await setupWizard();
@@ -533,6 +703,8 @@ async function main() {
533
703
  .description("Start the mining loop (Easy Mode: remote x402 GPU)")
534
704
  .argument("[tokenId]", "Miner token ID (auto-detects if omitted)")
535
705
  .action(async (tokenIdArg) => {
706
+ (0, context_1.setSignerContext)("mine");
707
+ await unlockConfiguredKeystoreIfNeeded();
536
708
  const hasWallet = !!config_1.config.privateKey && !!wallet_1.account;
537
709
  const hasRpc = config_1.config.useX402 || !!config_1.config.rpcUrl;
538
710
  if (!hasWallet || !hasRpc) {
@@ -610,83 +782,223 @@ async function main() {
610
782
  const { buildGrinders } = await Promise.resolve().then(() => __importStar(require("./build")));
611
783
  await buildGrinders(opts);
612
784
  });
785
+ const policyCmd = program
786
+ .command("policy")
787
+ .description("Show and configure local wallet signing policy");
788
+ policyCmd
789
+ .command("show")
790
+ .description("Print the current wallet policy")
791
+ .action(() => {
792
+ (0, context_1.setSignerContext)("policy");
793
+ console.log(JSON.stringify((0, policy_1.loadPolicy)(), null, 2));
794
+ });
795
+ policyCmd
796
+ .command("init")
797
+ .description("Write the default policy file")
798
+ .option("--force", "Overwrite existing policy.json")
799
+ .action((opts) => {
800
+ const path = (0, policy_1.writeDefaultPolicyFile)(opts.force === true);
801
+ ui.ok(`Policy file ready: ${path}`);
802
+ });
803
+ policyCmd
804
+ .command("set")
805
+ .description("Set policy values")
806
+ .command("mode <mode>")
807
+ .description("Set policy mode: enforce, warn, or off")
808
+ .action((mode) => {
809
+ if (mode !== "enforce" && mode !== "warn" && mode !== "off") {
810
+ ui.error("Mode must be enforce, warn, or off.");
811
+ return;
812
+ }
813
+ const policy = (0, policy_1.loadPolicy)();
814
+ policy.mode = mode;
815
+ const path = (0, policy_1.savePolicy)(policy);
816
+ ui.ok(`Policy mode set to ${mode} in ${path}`);
817
+ if (mode !== "enforce") {
818
+ ui.warn("Policy is not enforcing. Use only as a temporary recovery mode.");
819
+ }
820
+ });
613
821
  const walletCmd = program
614
822
  .command("wallet")
615
823
  .description("Wallet generation and management");
616
824
  walletCmd
617
825
  .command("new")
618
- .description("Generate a new Base wallet (prints key and saves to file)")
826
+ .description("Generate a new encrypted Base wallet")
619
827
  .action(async () => {
828
+ const password = await getKeystorePassword(true);
829
+ if (!password) {
830
+ return;
831
+ }
620
832
  const { generatePrivateKey, privateKeyToAccount } = await Promise.resolve().then(() => __importStar(require("viem/accounts")));
621
833
  const key = generatePrivateKey();
622
834
  const acct = privateKeyToAccount(key);
835
+ const artifacts = await saveWalletArtifacts(acct.address, key, {
836
+ requireKeystore: true,
837
+ });
838
+ (0, wallet_store_1.registerGeneratedWallet)(acct.address, artifacts.keystorePath);
623
839
  console.log("");
624
840
  console.log(` ${ui.bold("NEW WALLET GENERATED")}`);
625
841
  console.log("");
626
842
  console.log(` Address: ${acct.address}`);
627
- console.log(` Private Key: ${key}`);
843
+ if (artifacts.keystorePath) {
844
+ console.log(` Keystore: ${artifacts.keystorePath}`);
845
+ }
628
846
  console.log("");
629
- console.log(` ${ui.yellow("⚠ SAVE YOUR PRIVATE KEY — this is the only time")}`);
630
- console.log(` ${ui.yellow(" it will be displayed. Anyone with this key")}`);
631
- console.log(` ${ui.yellow(" controls your funds.")}`);
847
+ console.log(` ${ui.dim("Private key remains encrypted and is never printed.")}`);
848
+ console.log(` ${ui.dim("Back up the keystore and its password separately.")}`);
849
+ console.log(` ${ui.dim(`Activate it in this project with: apow wallet use ${acct.address}`)}`);
632
850
  console.log("");
633
- const artifacts = await saveWalletArtifacts(acct.address, key);
634
- if (artifacts.plaintextPath) {
635
- console.log(` ${ui.dim(`Import helper saved to: ${artifacts.plaintextPath}`)}`);
636
- console.log(` ${ui.yellow("This plaintext file is easy to import, but less secure than an encrypted keystore.")}`);
851
+ });
852
+ walletCmd
853
+ .command("list")
854
+ .description("List wallets generated locally by this APoW CLI")
855
+ .action(() => {
856
+ const wallets = (0, wallet_store_1.loadGeneratedWallets)();
857
+ if (wallets.length === 0) {
858
+ ui.error("No locally generated APoW wallets found.");
859
+ ui.hint("Create one with `apow wallet new` or the setup wizard.");
860
+ return;
637
861
  }
638
- if (artifacts.keystorePath) {
639
- console.log(` ${ui.dim(`Encrypted keystore saved to: ${artifacts.keystorePath}`)}`);
862
+ printGeneratedWallets(wallets);
863
+ });
864
+ walletCmd
865
+ .command("use")
866
+ .alias("select")
867
+ .description("Select a locally generated APoW wallet for this project")
868
+ .argument("[wallet]", "Wallet address or number from `apow wallet list`")
869
+ .action(async (walletArg) => {
870
+ const wallets = (0, wallet_store_1.loadGeneratedWallets)();
871
+ if (wallets.length === 0) {
872
+ ui.error("No locally generated APoW wallets found.");
873
+ ui.hint("Create one with `apow wallet new` or the setup wizard.");
874
+ return;
640
875
  }
641
- else {
642
- console.log(` ${ui.dim("Tip: set KEYSTORE_PASSWORD or rerun wallet export to create an encrypted JSON keystore backup.")}`);
876
+ let selection = walletArg?.trim() ?? "";
877
+ if (!selection) {
878
+ if (!ui.isInteractiveSession()) {
879
+ ui.error("Specify a wallet address or number from `apow wallet list`.");
880
+ return;
881
+ }
882
+ printGeneratedWallets(wallets);
883
+ const activeIndex = wallets.findIndex(isActiveGeneratedWallet);
884
+ selection = await ui.prompt("Wallet number or address", String(activeIndex >= 0 ? activeIndex + 1 : 1));
643
885
  }
644
- console.log("");
645
- console.log(` ${ui.dim("Import into Phantom, MetaMask, or any EVM wallet")}`);
646
- console.log(` ${ui.dim("to view your AGENT tokens and Mining Rig NFT.")}`);
647
- console.log("");
886
+ const selected = resolveGeneratedWalletSelection(wallets, selection);
887
+ if (!selected) {
888
+ ui.error("Wallet not found. Use an address or list number from `apow wallet list`.");
889
+ return;
890
+ }
891
+ if (isActiveGeneratedWallet(selected)) {
892
+ ui.ok(`Wallet already active: ${selected.address}`);
893
+ return;
894
+ }
895
+ const password = await unlockGeneratedWallet(selected);
896
+ if (!password) {
897
+ return;
898
+ }
899
+ (0, session_1.setSessionPassword)(password);
900
+ await (0, config_1.writeEnvFile)({ PRIVATE_KEY: "", KEYSTORE_PATH: selected.keystorePath });
901
+ (0, wallet_1.reinitClients)();
902
+ ui.ok(`Active wallet: ${selected.address}`);
903
+ ui.hint(`Project config updated: ${(0, node_path_1.join)(process.cwd(), ".env")}`);
648
904
  });
649
905
  walletCmd
650
906
  .command("show")
651
- .description("Show wallet address from current .env PRIVATE_KEY")
907
+ .description("Show configured wallet address")
652
908
  .action(async () => {
909
+ await unlockConfiguredKeystoreIfNeeded();
653
910
  if (!wallet_1.account) {
654
- ui.error("No wallet configured. Run `apow setup` and choose Easy Mode, or set PRIVATE_KEY in .env.");
911
+ ui.error("No wallet configured. Run `apow setup` and choose Easy Mode, or configure KEYSTORE_PATH.");
655
912
  return;
656
913
  }
657
914
  console.log("");
658
915
  console.log(` Address: ${wallet_1.account.address}`);
916
+ if (config_1.config.walletSource === "keystore" && config_1.config.keystorePath) {
917
+ console.log(` Source: encrypted keystore (${config_1.config.keystorePath})`);
918
+ }
919
+ else if (config_1.config.walletSource === "private-key") {
920
+ console.log(" Source: legacy PRIVATE_KEY");
921
+ }
659
922
  console.log("");
660
923
  });
661
924
  walletCmd
662
- .command("export")
663
- .description("Export wallet private key (with confirmation)")
925
+ .command("backup")
926
+ .description("Show the encrypted wallet backup location (never displays private keys)")
664
927
  .action(async () => {
665
- if (!wallet_1.account || !config_1.config.privateKey) {
666
- ui.error("No wallet configured. Run `apow setup` and choose Easy Mode, or set PRIVATE_KEY in .env.");
928
+ await unlockConfiguredKeystoreIfNeeded();
929
+ if (!wallet_1.account) {
930
+ ui.error("No wallet configured. Run `apow setup` and choose Easy Mode, or configure KEYSTORE_PATH.");
667
931
  return;
668
932
  }
669
- const proceed = await ui.confirm("This will display your private key. Continue?");
670
- if (!proceed) {
671
- console.log(" Cancelled.");
933
+ if (config_1.config.walletSource !== "keystore" || !config_1.config.keystorePath) {
934
+ ui.error("This wallet is using the legacy environment-key path.");
935
+ ui.hint("Run `apow wallet migrate` to create an encrypted keystore backup.");
672
936
  return;
673
937
  }
674
938
  console.log("");
675
- console.log(` Address: ${wallet_1.account.address}`);
676
- console.log(` Private Key: ${config_1.config.privateKey}`);
939
+ console.log(` Address: ${wallet_1.account.address}`);
940
+ console.log(` Keystore: ${config_1.config.keystorePath}`);
941
+ console.log(` ${ui.dim("Back up this encrypted file and its password separately.")}`);
942
+ console.log(` ${ui.dim("APoW never prints or writes a plaintext private-key export.")}`);
677
943
  console.log("");
678
- const savePlaintext = await ui.confirm("Save plaintext import helper?");
679
- const artifacts = await saveWalletArtifacts(wallet_1.account.address, config_1.config.privateKey, {
680
- createPlaintextImportFile: savePlaintext,
681
- promptForKeystoreBackup: true,
682
- });
683
- if (artifacts.plaintextPath) {
684
- console.log(` ${ui.dim(`Saved import helper: ${artifacts.plaintextPath}`)}`);
944
+ });
945
+ walletCmd
946
+ .command("migrate")
947
+ .description("Encrypt legacy PRIVATE_KEY into a keystore and clear .env PRIVATE_KEY")
948
+ .action(async () => {
949
+ if (config_1.config.walletSource !== "private-key" || !config_1.config.privateKey || !wallet_1.account) {
950
+ ui.error("No legacy PRIVATE_KEY wallet is loaded.");
951
+ return;
685
952
  }
686
- if (artifacts.keystorePath) {
687
- console.log(` ${ui.dim(`Saved encrypted keystore: ${artifacts.keystorePath}`)}`);
953
+ const password = await getKeystorePassword(true);
954
+ if (!password)
955
+ return;
956
+ const keystorePath = await saveKeystoreWithPassword(wallet_1.account.address, config_1.config.privateKey, password);
957
+ await (0, config_1.writeEnvFile)({ PRIVATE_KEY: "", KEYSTORE_PATH: keystorePath });
958
+ (0, config_1.reloadConfig)();
959
+ (0, wallet_1.reinitClients)();
960
+ ui.ok(`Encrypted keystore saved to ${keystorePath}`);
961
+ ui.hint("Unset PRIVATE_KEY in your shell or process manager if it is exported outside .env.");
962
+ });
963
+ const payoutCmd = walletCmd
964
+ .command("payout")
965
+ .description("Configure the cold payout address for mined AGENT sweeps");
966
+ payoutCmd
967
+ .command("set <address>")
968
+ .description("Set payout address")
969
+ .action(async (address) => {
970
+ await unlockConfiguredKeystoreIfNeeded();
971
+ if (!/^0x[0-9a-fA-F]{40}$/.test(address)) {
972
+ ui.error("Invalid payout address.");
973
+ return;
974
+ }
975
+ const payout = (0, viem_1.getAddress)(address);
976
+ if (wallet_1.account && payout.toLowerCase() === wallet_1.account.address.toLowerCase()) {
977
+ ui.error("Payout address must differ from the mining wallet.");
978
+ return;
688
979
  }
980
+ const policy = (0, policy_1.loadPolicy)();
981
+ policy.payout = payout;
982
+ const path = (0, policy_1.savePolicy)(policy);
983
+ ui.ok(`Payout set to ${payout.slice(0, 6)}...${payout.slice(-4)} in ${path}`);
984
+ });
985
+ payoutCmd
986
+ .command("show")
987
+ .description("Show configured payout address")
988
+ .action(() => {
989
+ const payout = (0, policy_1.getPayoutAddress)();
689
990
  console.log("");
991
+ console.log(` Payout: ${payout ?? "(not configured)"}`);
992
+ console.log("");
993
+ });
994
+ walletCmd
995
+ .command("sweep")
996
+ .description("Sweep mined AGENT to the configured payout address")
997
+ .option("--all", "Also sweep excess ETH and USDC working balances")
998
+ .action(async (opts) => {
999
+ (0, context_1.setSignerContext)("sweep");
1000
+ await unlockConfiguredKeystoreIfNeeded();
1001
+ await (0, sweep_1.runSweep)({ all: opts.all === true });
690
1002
  });
691
1003
  walletCmd
692
1004
  .command("fund")
@@ -694,6 +1006,8 @@ async function main() {
694
1006
  .argument("<address>", "Destination address (0x-prefixed)")
695
1007
  .argument("[amount]", "ETH amount to send (default: mint price + 0.003 ETH gas buffer)")
696
1008
  .action(async (address, amountArg) => {
1009
+ (0, context_1.setSignerContext)("wallet-fund");
1010
+ await unlockConfiguredKeystoreIfNeeded();
697
1011
  if (!config_1.config.privateKey || !wallet_1.account) {
698
1012
  ui.warn("No wallet configured — launching setup first.");
699
1013
  await setupWizard();
@@ -777,28 +1091,30 @@ async function main() {
777
1091
  .command("start", { isDefault: true })
778
1092
  .description("Launch the dashboard web UI")
779
1093
  .action(async () => {
780
- const walletsPath = getWalletsPath();
781
- // Seed wallets.json if it doesn't exist
782
- if (!(0, node_fs_1.existsSync)(walletsPath)) {
783
- const walletsDir = (0, node_path_1.join)(process.env.HOME ?? "", ".apow");
784
- if (!(0, node_fs_1.existsSync)(walletsDir))
785
- (0, node_fs_1.mkdirSync)(walletsDir, { recursive: true });
786
- const initial = wallet_1.account ? [wallet_1.account.address] : [];
787
- (0, node_fs_1.writeFileSync)(walletsPath, JSON.stringify(initial, null, 2), "utf8");
788
- if (wallet_1.account) {
789
- ui.ok(`Seeded ${walletsPath} with ${wallet_1.account.address.slice(0, 6)}...${wallet_1.account.address.slice(-4)}`);
790
- }
791
- else {
792
- ui.ok(`Created ${walletsPath} (empty — add wallets with: apow dashboard add <address>)`);
1094
+ (0, context_1.setSignerContext)("dashboard");
1095
+ if (config_1.config.useX402) {
1096
+ await unlockConfiguredKeystoreIfNeeded();
1097
+ const policy = (0, policy_1.loadPolicy)();
1098
+ if (policy.mode !== "enforce") {
1099
+ ui.error("Paid dashboard reads require the wallet signing policy in enforce mode.");
1100
+ ui.hint("Run `apow policy set mode enforce`, then retry.");
1101
+ return;
793
1102
  }
794
1103
  }
795
- // Auto-detect wallets from CWD
796
- const { addresses, newCount } = detectWallets(process.cwd());
797
- if (newCount > 0) {
798
- ui.ok(`Detected ${addresses.length} wallets (${newCount} new)`);
1104
+ const generatedWallets = (0, wallet_store_1.loadGeneratedWalletAddresses)();
1105
+ const configuredAccount = wallet_1.account;
1106
+ const signerIsGenerated = !!configuredAccount && generatedWallets.some((address) => address.toLowerCase() === configuredAccount.address.toLowerCase());
1107
+ if (config_1.config.useX402 && !signerIsGenerated) {
1108
+ ui.error("Dashboard x402 requires a configured wallet generated locally by this APoW CLI.");
1109
+ ui.hint("Run `apow wallet new`, configure its KEYSTORE_PATH, then retry.");
1110
+ return;
1111
+ }
1112
+ if (generatedWallets.length === 0) {
1113
+ ui.warn("No locally generated APoW wallets are registered. The dashboard will be empty.");
1114
+ ui.hint("Run `apow wallet new` to create and register one.");
799
1115
  }
800
- else if (addresses.length > 0) {
801
- console.log(` ${ui.dim(`${addresses.length} wallets loaded`)}`);
1116
+ else {
1117
+ console.log(` ${ui.dim(`${generatedWallets.length} locally generated wallets loaded`)}`);
802
1118
  }
803
1119
  const { startDashboardServer } = await Promise.resolve().then(() => __importStar(require("./dashboard")));
804
1120
  console.log("");
@@ -807,17 +1123,16 @@ async function main() {
807
1123
  console.log("");
808
1124
  const server = startDashboardServer({
809
1125
  port: 3847,
810
- walletsPath,
811
1126
  rpcUrl: config_1.config.rpcUrl,
812
1127
  useX402: config_1.config.useX402,
813
- privateKey: config_1.config.privateKey,
1128
+ signer: signerIsGenerated ? configuredAccount ?? undefined : undefined,
814
1129
  miningAgentAddress: config_1.config.miningAgentAddress,
815
1130
  agentCoinAddress: config_1.config.agentCoinAddress,
816
1131
  });
817
1132
  // Open browser after short delay (server starts instantly)
818
1133
  setTimeout(() => {
819
1134
  const openCmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
820
- (0, node_child_process_1.spawn)(openCmd, ["http://localhost:3847"], { stdio: "ignore" });
1135
+ (0, node_child_process_1.spawn)(openCmd, ["http://localhost:3847"], { stdio: "ignore", env: (0, secure_env_1.childEnv)() });
821
1136
  }, 500);
822
1137
  // Wait for SIGINT
823
1138
  await new Promise((resolve) => {
@@ -827,72 +1142,17 @@ async function main() {
827
1142
  });
828
1143
  });
829
1144
  });
830
- dashboardCmd
831
- .command("add <address>")
832
- .description("Add a wallet address to monitor")
833
- .action((address) => {
834
- if (!/^0x[0-9a-fA-F]{40}$/.test(address)) {
835
- ui.error("Invalid address. Must be 0x + 40 hex characters.");
836
- return;
837
- }
838
- const walletsPath = getWalletsPath();
839
- const wallets = loadWallets(walletsPath);
840
- const lower = address.toLowerCase();
841
- if (wallets.some((w) => w.toLowerCase() === lower)) {
842
- ui.warn("Address already monitored.");
843
- return;
844
- }
845
- wallets.push(address);
846
- saveWallets(walletsPath, wallets);
847
- ui.ok(`Added ${address.slice(0, 6)}...${address.slice(-4)} (${wallets.length} wallets total)`);
848
- });
849
- dashboardCmd
850
- .command("remove <address>")
851
- .description("Remove a wallet address from monitoring")
852
- .action((address) => {
853
- const walletsPath = getWalletsPath();
854
- const wallets = loadWallets(walletsPath);
855
- const lower = address.toLowerCase();
856
- const filtered = wallets.filter((w) => w.toLowerCase() !== lower);
857
- if (filtered.length === wallets.length) {
858
- ui.warn("Address not found in wallet list.");
859
- return;
860
- }
861
- saveWallets(walletsPath, filtered);
862
- ui.ok(`Removed ${address.slice(0, 6)}...${address.slice(-4)} (${filtered.length} wallets remaining)`);
863
- });
864
- dashboardCmd
865
- .command("scan [dir]")
866
- .description("Auto-detect wallets from wallet-0x*.txt or wallet-0x*.json files in a directory")
867
- .action((dir) => {
868
- const scanDir = dir ?? process.cwd();
869
- const { addresses, newCount } = detectWallets(scanDir);
870
- console.log("");
871
- if (addresses.length === 0) {
872
- console.log(` No wallets found in ${scanDir}`);
873
- console.log(` ${ui.dim("Expected files named wallet-0x<address>.txt or wallet-0x<address>.json")}`);
874
- }
875
- else {
876
- console.log(` ${ui.bold("Detected Wallets")} (${newCount} new, ${addresses.length} total)`);
877
- console.log("");
878
- for (const addr of addresses) {
879
- console.log(` ${addr}`);
880
- }
881
- }
882
- console.log("");
883
- });
884
1145
  dashboardCmd
885
1146
  .command("wallets")
886
- .description("List monitored wallet addresses")
1147
+ .description("List locally generated APoW wallet addresses")
887
1148
  .action(() => {
888
- const walletsPath = getWalletsPath();
889
- const wallets = loadWallets(walletsPath);
1149
+ const wallets = (0, wallet_store_1.loadGeneratedWalletAddresses)();
890
1150
  if (wallets.length === 0) {
891
- console.log(" No wallets configured. Run: apow dashboard add <address>");
1151
+ console.log(" No locally generated APoW wallets. Run: apow wallet new");
892
1152
  return;
893
1153
  }
894
1154
  console.log("");
895
- console.log(` ${ui.bold("Monitored Wallets")} (${wallets.length})`);
1155
+ console.log(` ${ui.bold("Locally Generated Wallets")} (${wallets.length})`);
896
1156
  console.log("");
897
1157
  for (const w of wallets) {
898
1158
  console.log(` ${w}`);
@@ -901,70 +1161,7 @@ async function main() {
901
1161
  });
902
1162
  await program.parseAsync(process.argv);
903
1163
  }
904
- function getWalletsPath() {
905
- return (0, node_path_1.join)(process.env.HOME ?? "", ".apow", "wallets.json");
906
- }
907
- function loadWallets(path) {
908
- try {
909
- const raw = (0, node_fs_1.readFileSync)(path, "utf8");
910
- const data = JSON.parse(raw);
911
- return Array.isArray(data) ? data.filter((a) => typeof a === "string") : [];
912
- }
913
- catch {
914
- return [];
915
- }
916
- }
917
- function saveWallets(path, wallets) {
918
- const dir = (0, node_path_1.join)(process.env.HOME ?? "", ".apow");
919
- if (!(0, node_fs_1.existsSync)(dir))
920
- (0, node_fs_1.mkdirSync)(dir, { recursive: true });
921
- (0, node_fs_1.writeFileSync)(path, JSON.stringify(wallets, null, 2), "utf8");
922
- }
923
- function detectWallets(scanDir) {
924
- const walletsPath = getWalletsPath();
925
- const existing = loadWallets(walletsPath);
926
- const seen = new Set(existing.map((a) => a.toLowerCase()));
927
- const detected = [];
928
- // Scan scanDir for wallet-0x*.txt / .json files
929
- try {
930
- const entries = (0, node_fs_1.readdirSync)(scanDir, { withFileTypes: true });
931
- for (const entry of entries) {
932
- if (entry.isFile()) {
933
- const address = (0, wallet_store_1.detectWalletAddressFromFilename)(entry.name);
934
- if (address && !seen.has(address.toLowerCase())) {
935
- detected.push(address);
936
- seen.add(address.toLowerCase());
937
- }
938
- }
939
- // Scan rig*/wallet-0x* subdirectories
940
- if (entry.isDirectory() && entry.name.startsWith("rig")) {
941
- try {
942
- const rigFiles = (0, node_fs_1.readdirSync)((0, node_path_1.join)(scanDir, entry.name));
943
- for (const file of rigFiles) {
944
- const address = (0, wallet_store_1.detectWalletAddressFromFilename)(file);
945
- if (address && !seen.has(address.toLowerCase())) {
946
- detected.push(address);
947
- seen.add(address.toLowerCase());
948
- }
949
- }
950
- }
951
- catch {
952
- // rig dir not readable — skip
953
- }
954
- }
955
- }
956
- }
957
- catch {
958
- // scanDir not readable
959
- }
960
- const merged = [...existing, ...detected];
961
- if (detected.length > 0) {
962
- saveWallets(walletsPath, merged);
963
- }
964
- return { addresses: merged, newCount: detected.length };
965
- }
966
1164
  main().catch((error) => {
967
- const message = error instanceof Error ? error.message : String(error);
968
- ui.error(message);
1165
+ ui.error((0, errors_1.errorText)(error));
969
1166
  process.exitCode = 1;
970
1167
  });