apow-cli 0.9.0 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.env.example CHANGED
@@ -7,12 +7,14 @@ RPC_URL=
7
7
  # Option 2: Auto-pay via QuickNode x402 ($10 USDC for ~1M calls, no API key needed)
8
8
  # USE_X402=true
9
9
 
10
- # LLM Provider (openai / anthropic / gemini / ollama / claude-code / codex)
11
- LLM_PROVIDER=openai
12
- LLM_MODEL=gpt-4o-mini
10
+ # LLM Provider (clawrouter / openai / anthropic / gemini / ollama / claude-code / codex)
11
+ # clawrouter (recommended): Zero credentials. Pays with USDC from your wallet via x402.
12
+ LLM_PROVIDER=clawrouter
13
+ LLM_MODEL=blockrun/eco
14
+ # CLAWROUTER_PORT=8402 # only if default port is in use
13
15
 
14
- # API key (not needed for ollama, claude-code, or codex)
15
- LLM_API_KEY=
16
+ # API key (not needed for clawrouter, ollama, claude-code, or codex)
17
+ # LLM_API_KEY=
16
18
 
17
19
  # Provider-specific keys (alternative to LLM_API_KEY)
18
20
  # OPENAI_API_KEY=
@@ -27,8 +29,10 @@ LLM_API_KEY=
27
29
  # SQUID_INTEGRATOR_ID=
28
30
 
29
31
  # GPU Mining (optional — auto-detected, massive speed boost)
32
+ # Run `apow build-grinders` to compile native binaries automatically.
30
33
  # GRINDER_MODE=auto # auto (default) or js (force JS-only)
31
34
  # GPU_GRINDER_PATH=./gpu/grinder-gpu # Metal binary (macOS, auto-detected)
35
+ # CUDA_GRINDER_PATH=~/.apow/grinder-cuda # CUDA binary (NVIDIA GPU, auto-detected)
32
36
  # CPU_GRINDER_PATH=./gpu/grinder-cpu # C binary (any platform, auto-detected)
33
37
  # CPU_THREADS=16 # Threads for CPU-C grinder (default: all cores)
34
38
  # Remote GPU via Vast.ai (see: local/vast-setup.sh)
package/dist/build.js ADDED
@@ -0,0 +1,229 @@
1
+ "use strict";
2
+ /**
3
+ * Build native grinder binaries for GPU/CPU mining.
4
+ *
5
+ * Auto-detects available compilers and GPU architecture, then compiles
6
+ * whichever grinders are possible on the current platform:
7
+ * - CPU-C (any platform with clang or gcc)
8
+ * - CUDA (Linux/Windows with nvcc + NVIDIA GPU)
9
+ * - Metal (macOS with clang)
10
+ *
11
+ * Installs compiled binaries to ~/.apow/ where auto-detection will find them.
12
+ */
13
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ var desc = Object.getOwnPropertyDescriptor(m, k);
16
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
17
+ desc = { enumerable: true, get: function() { return m[k]; } };
18
+ }
19
+ Object.defineProperty(o, k2, desc);
20
+ }) : (function(o, m, k, k2) {
21
+ if (k2 === undefined) k2 = k;
22
+ o[k2] = m[k];
23
+ }));
24
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
25
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
26
+ }) : function(o, v) {
27
+ o["default"] = v;
28
+ });
29
+ var __importStar = (this && this.__importStar) || (function () {
30
+ var ownKeys = function(o) {
31
+ ownKeys = Object.getOwnPropertyNames || function (o) {
32
+ var ar = [];
33
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
34
+ return ar;
35
+ };
36
+ return ownKeys(o);
37
+ };
38
+ return function (mod) {
39
+ if (mod && mod.__esModule) return mod;
40
+ var result = {};
41
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
42
+ __setModuleDefault(result, mod);
43
+ return result;
44
+ };
45
+ })();
46
+ var __importDefault = (this && this.__importDefault) || function (mod) {
47
+ return (mod && mod.__esModule) ? mod : { "default": mod };
48
+ };
49
+ Object.defineProperty(exports, "__esModule", { value: true });
50
+ exports.buildGrinders = buildGrinders;
51
+ const node_child_process_1 = require("node:child_process");
52
+ const node_fs_1 = require("node:fs");
53
+ const node_path_1 = require("node:path");
54
+ const node_os_1 = __importDefault(require("node:os"));
55
+ const ui = __importStar(require("./ui"));
56
+ const INSTALL_DIR = (0, node_path_1.join)(node_os_1.default.homedir(), ".apow");
57
+ function findSourceDir() {
58
+ // Check relative to this file's compiled location (dist/)
59
+ const fromDist = (0, node_path_1.join)((0, node_path_1.dirname)(__dirname), "local", "gpu");
60
+ if ((0, node_fs_1.existsSync)((0, node_path_1.join)(fromDist, "grinder-cpu.c")))
61
+ return fromDist;
62
+ // Check CWD (git clone case)
63
+ const fromCwd = (0, node_path_1.join)(process.cwd(), "local", "gpu");
64
+ if ((0, node_fs_1.existsSync)((0, node_path_1.join)(fromCwd, "grinder-cpu.c")))
65
+ return fromCwd;
66
+ const fromCwdGpu = (0, node_path_1.join)(process.cwd(), "gpu");
67
+ if ((0, node_fs_1.existsSync)((0, node_path_1.join)(fromCwdGpu, "grinder-cpu.c")))
68
+ return fromCwdGpu;
69
+ return null;
70
+ }
71
+ function which(cmd) {
72
+ try {
73
+ (0, node_child_process_1.execSync)(`which ${cmd}`, { stdio: "ignore" });
74
+ return true;
75
+ }
76
+ catch {
77
+ return false;
78
+ }
79
+ }
80
+ function detectCudaArch() {
81
+ try {
82
+ const raw = (0, node_child_process_1.execSync)("nvidia-smi --query-gpu=compute_cap --format=csv,noheader", { encoding: "utf8", timeout: 5000 }).trim();
83
+ // e.g. "8.9" → "sm_89"
84
+ const first = raw.split("\n")[0].trim();
85
+ if (/^\d+\.\d+$/.test(first)) {
86
+ return "sm_" + first.replace(".", "");
87
+ }
88
+ }
89
+ catch { }
90
+ return null;
91
+ }
92
+ function buildCpuC(sourceDir) {
93
+ const src = (0, node_path_1.join)(sourceDir, "grinder-cpu.c");
94
+ const out = (0, node_path_1.join)(INSTALL_DIR, "grinder-cpu");
95
+ const name = "CPU-C";
96
+ if (!(0, node_fs_1.existsSync)(src)) {
97
+ return { name, success: false, error: "source file not found" };
98
+ }
99
+ // Prefer clang, fall back to gcc
100
+ const cc = which("clang") ? "clang" : which("gcc") ? "gcc" : null;
101
+ if (!cc) {
102
+ return { name, success: false, error: "no C compiler found (need clang or gcc)" };
103
+ }
104
+ try {
105
+ (0, node_child_process_1.execSync)(`${cc} -O2 -pthread "${src}" -o "${out}"`, {
106
+ stdio: "pipe",
107
+ timeout: 60000,
108
+ });
109
+ (0, node_fs_1.chmodSync)(out, 0o755);
110
+ return { name, success: true, path: out };
111
+ }
112
+ catch (e) {
113
+ const msg = e instanceof Error ? e.message : String(e);
114
+ return { name, success: false, error: msg.split("\n")[0] };
115
+ }
116
+ }
117
+ function buildCuda(sourceDir, archOverride) {
118
+ const src = (0, node_path_1.join)(sourceDir, "grinder-cuda.cu");
119
+ const out = (0, node_path_1.join)(INSTALL_DIR, "grinder-cuda");
120
+ const name = "CUDA";
121
+ if (!(0, node_fs_1.existsSync)(src)) {
122
+ return { name, success: false, error: "source file not found" };
123
+ }
124
+ if (!which("nvcc")) {
125
+ return { name, success: false, error: "nvcc not found (install CUDA toolkit)" };
126
+ }
127
+ const arch = archOverride ?? detectCudaArch() ?? "sm_89";
128
+ try {
129
+ (0, node_child_process_1.execSync)(`nvcc "${src}" -o "${out}" -std=c++17 -O3 -arch=${arch}`, { stdio: "pipe", timeout: 120000 });
130
+ (0, node_fs_1.chmodSync)(out, 0o755);
131
+ return { name: `CUDA (${arch})`, success: true, path: out };
132
+ }
133
+ catch (e) {
134
+ const msg = e instanceof Error ? e.message : String(e);
135
+ return { name, success: false, error: msg.split("\n")[0] };
136
+ }
137
+ }
138
+ function buildMetal(sourceDir) {
139
+ const src = (0, node_path_1.join)(sourceDir, "grinder.m");
140
+ const out = (0, node_path_1.join)(INSTALL_DIR, "grinder-gpu");
141
+ const name = "Metal GPU";
142
+ if (process.platform !== "darwin") {
143
+ return { name, success: false, error: "macOS only" };
144
+ }
145
+ if (!(0, node_fs_1.existsSync)(src)) {
146
+ return { name, success: false, error: "source file not found" };
147
+ }
148
+ if (!which("clang")) {
149
+ return { name, success: false, error: "clang not found (install Xcode CLI tools)" };
150
+ }
151
+ try {
152
+ (0, node_child_process_1.execSync)(`clang -O2 -framework Metal -framework Foundation "${src}" -o "${out}"`, { stdio: "pipe", timeout: 60000 });
153
+ (0, node_fs_1.chmodSync)(out, 0o755);
154
+ return { name, success: true, path: out };
155
+ }
156
+ catch (e) {
157
+ const msg = e instanceof Error ? e.message : String(e);
158
+ return { name, success: false, error: msg.split("\n")[0] };
159
+ }
160
+ }
161
+ async function buildGrinders(opts) {
162
+ console.log("");
163
+ ui.banner(["Build Native Grinders"]);
164
+ console.log("");
165
+ // Find source files
166
+ const sourceDir = findSourceDir();
167
+ if (!sourceDir) {
168
+ ui.error("Grinder source files not found.");
169
+ ui.hint("Ensure local/gpu/ exists (included in npm package since v0.9.2)");
170
+ return;
171
+ }
172
+ console.log(` Source: ${ui.dim(sourceDir)}`);
173
+ // Create install directory
174
+ if (!(0, node_fs_1.existsSync)(INSTALL_DIR)) {
175
+ (0, node_fs_1.mkdirSync)(INSTALL_DIR, { recursive: true });
176
+ }
177
+ console.log(` Install: ${ui.dim(INSTALL_DIR)}`);
178
+ console.log("");
179
+ // Build each grinder
180
+ const results = [];
181
+ const cpuSpinner = ui.spinner("Building CPU-C grinder...");
182
+ const cpuResult = buildCpuC(sourceDir);
183
+ results.push(cpuResult);
184
+ if (cpuResult.success) {
185
+ cpuSpinner.stop(`Building CPU-C grinder... ${ui.green("OK")}`);
186
+ }
187
+ else {
188
+ cpuSpinner.stop(`Building CPU-C grinder... ${ui.yellow("skipped")} (${cpuResult.error})`);
189
+ }
190
+ const cudaSpinner = ui.spinner("Building CUDA grinder...");
191
+ const cudaResult = buildCuda(sourceDir, opts.cudaArch);
192
+ results.push(cudaResult);
193
+ if (cudaResult.success) {
194
+ cudaSpinner.stop(`Building CUDA grinder... ${ui.green("OK")}`);
195
+ }
196
+ else {
197
+ cudaSpinner.stop(`Building CUDA grinder... ${ui.yellow("skipped")} (${cudaResult.error})`);
198
+ }
199
+ const metalSpinner = ui.spinner("Building Metal GPU grinder...");
200
+ const metalResult = buildMetal(sourceDir);
201
+ results.push(metalResult);
202
+ if (metalResult.success) {
203
+ metalSpinner.stop(`Building Metal GPU grinder... ${ui.green("OK")}`);
204
+ }
205
+ else {
206
+ metalSpinner.stop(`Building Metal GPU grinder... ${ui.yellow("skipped")} (${metalResult.error})`);
207
+ }
208
+ // Summary
209
+ console.log("");
210
+ const built = results.filter((r) => r.success);
211
+ if (built.length === 0) {
212
+ ui.warn("No grinders could be built on this system.");
213
+ console.log("");
214
+ console.log(` ${ui.dim("Requirements:")}`);
215
+ console.log(` ${ui.dim(" CPU-C: clang or gcc")}`);
216
+ console.log(` ${ui.dim(" CUDA: nvcc + NVIDIA GPU (nvidia-smi)")}`);
217
+ console.log(` ${ui.dim(" Metal: macOS + Xcode CLI tools")}`);
218
+ }
219
+ else {
220
+ ui.ok(`Built ${built.length} grinder${built.length > 1 ? "s" : ""}:`);
221
+ for (const r of built) {
222
+ console.log(` ${ui.green(r.name)} → ${ui.dim(r.path)}`);
223
+ }
224
+ console.log("");
225
+ console.log(` Grinders installed to ${ui.cyan("~/.apow/")} — auto-detected on next mine.`);
226
+ console.log(` Run ${ui.cyan("apow mine")} to start GPU mining.`);
227
+ }
228
+ console.log("");
229
+ }
@@ -0,0 +1,96 @@
1
+ "use strict";
2
+ /**
3
+ * ClawRouter x402 LLM proxy lifecycle.
4
+ *
5
+ * Manages an in-process ClawRouter proxy that routes LLM calls through x402,
6
+ * paying for inference with USDC from the agent's existing wallet.
7
+ */
8
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
9
+ if (k2 === undefined) k2 = k;
10
+ var desc = Object.getOwnPropertyDescriptor(m, k);
11
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
12
+ desc = { enumerable: true, get: function() { return m[k]; } };
13
+ }
14
+ Object.defineProperty(o, k2, desc);
15
+ }) : (function(o, m, k, k2) {
16
+ if (k2 === undefined) k2 = k;
17
+ o[k2] = m[k];
18
+ }));
19
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
20
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
21
+ }) : function(o, v) {
22
+ o["default"] = v;
23
+ });
24
+ var __importStar = (this && this.__importStar) || (function () {
25
+ var ownKeys = function(o) {
26
+ ownKeys = Object.getOwnPropertyNames || function (o) {
27
+ var ar = [];
28
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
29
+ return ar;
30
+ };
31
+ return ownKeys(o);
32
+ };
33
+ return function (mod) {
34
+ if (mod && mod.__esModule) return mod;
35
+ var result = {};
36
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
37
+ __setModuleDefault(result, mod);
38
+ return result;
39
+ };
40
+ })();
41
+ Object.defineProperty(exports, "__esModule", { value: true });
42
+ exports.isClawRouterRunning = isClawRouterRunning;
43
+ exports.getClawRouterBaseUrl = getClawRouterBaseUrl;
44
+ exports.ensureClawRouter = ensureClawRouter;
45
+ exports.stopClawRouter = stopClawRouter;
46
+ let _handle = null;
47
+ let _starting = null;
48
+ function getPort() {
49
+ const envPort = process.env.CLAWROUTER_PORT;
50
+ if (envPort) {
51
+ const parsed = parseInt(envPort, 10);
52
+ if (!isNaN(parsed) && parsed > 0 && parsed < 65536)
53
+ return parsed;
54
+ }
55
+ return 8402;
56
+ }
57
+ function isClawRouterRunning() {
58
+ return _handle !== null;
59
+ }
60
+ function getClawRouterBaseUrl() {
61
+ if (_handle)
62
+ return _handle.baseUrl;
63
+ return `http://127.0.0.1:${getPort()}`;
64
+ }
65
+ async function ensureClawRouter(privateKey) {
66
+ if (_handle)
67
+ return;
68
+ // Concurrent startup gate — if another call is already starting, wait for it
69
+ if (_starting) {
70
+ await _starting;
71
+ return;
72
+ }
73
+ _starting = (async () => {
74
+ const { startProxy } = await Promise.resolve().then(() => __importStar(require("@blockrun/clawrouter")));
75
+ const port = getPort();
76
+ const handle = await startProxy({
77
+ wallet: privateKey,
78
+ port,
79
+ paymentChain: "base",
80
+ });
81
+ _handle = handle;
82
+ return handle;
83
+ })();
84
+ try {
85
+ await _starting;
86
+ }
87
+ finally {
88
+ _starting = null;
89
+ }
90
+ }
91
+ async function stopClawRouter() {
92
+ if (_handle) {
93
+ await _handle.close();
94
+ _handle = null;
95
+ }
96
+ }
package/dist/config.js CHANGED
@@ -24,7 +24,7 @@ const DEFAULT_AGENT_COIN_ADDRESS = "0x12577CF0D8a07363224D6909c54C056A183e13b3";
24
24
  const EXPENSIVE_MODELS = ["gpt-4o", "gpt-4", "claude-3-opus", "claude-3-5-sonnet"];
25
25
  const CHEAP_OVERRIDES = ["gpt-4o-mini", "gpt-4-mini"];
26
26
  function normalizeProvider(value) {
27
- if (value === "anthropic" || value === "ollama" || value === "openai" || value === "gemini" || value === "claude-code" || value === "codex" || value === "deepseek" || value === "qwen") {
27
+ if (value === "anthropic" || value === "ollama" || value === "openai" || value === "gemini" || value === "claude-code" || value === "codex" || value === "deepseek" || value === "qwen" || value === "clawrouter") {
28
28
  return value;
29
29
  }
30
30
  return DEFAULT_LLM_PROVIDER;
@@ -61,7 +61,7 @@ function parseAddress(envKey, fallback) {
61
61
  return ZERO_ADDRESS;
62
62
  }
63
63
  function resolveLlmApiKey(provider) {
64
- if (provider === "claude-code" || provider === "codex")
64
+ if (provider === "claude-code" || provider === "codex" || provider === "clawrouter")
65
65
  return "";
66
66
  if (process.env.LLM_API_KEY)
67
67
  return process.env.LLM_API_KEY;
@@ -91,6 +91,7 @@ exports.config = {
91
91
  grinderMode: (process.env.GRINDER_MODE === "js" ? "js" : "auto"),
92
92
  gpuGrinderPath: process.env.GPU_GRINDER_PATH,
93
93
  cpuGrinderPath: process.env.CPU_GRINDER_PATH,
94
+ cudaGrinderPath: process.env.CUDA_GRINDER_PATH,
94
95
  vastIp: process.env.VAST_IP,
95
96
  vastPort: process.env.VAST_PORT,
96
97
  cpuGrinderThreads: parseInt(process.env.CPU_THREADS ?? String(node_os_1.default.cpus().length), 10),
@@ -103,7 +104,7 @@ function requirePrivateKey() {
103
104
  return exports.config.privateKey;
104
105
  }
105
106
  function requireLlmApiKey() {
106
- if (exports.config.llmProvider === "ollama" || exports.config.llmProvider === "claude-code" || exports.config.llmProvider === "codex") {
107
+ if (exports.config.llmProvider === "ollama" || exports.config.llmProvider === "claude-code" || exports.config.llmProvider === "codex" || exports.config.llmProvider === "clawrouter") {
107
108
  return "";
108
109
  }
109
110
  if (!exports.config.llmApiKey) {
package/dist/errors.js CHANGED
@@ -93,6 +93,22 @@ const patterns = [
93
93
  recovery: "Try a different model (gpt-4o-mini recommended) or check your LLM API key",
94
94
  }),
95
95
  },
96
+ {
97
+ test: (m) => m.includes("EADDRINUSE") && m.includes("8402"),
98
+ classify: () => ({
99
+ category: "setup",
100
+ userMessage: "ClawRouter proxy port 8402 is already in use",
101
+ recovery: "Set CLAWROUTER_PORT in .env to use a different port",
102
+ }),
103
+ },
104
+ {
105
+ test: (m) => m.toLowerCase().includes("insufficient") && m.toLowerCase().includes("clawrouter"),
106
+ classify: () => ({
107
+ category: "setup",
108
+ userMessage: "Insufficient USDC for ClawRouter x402 LLM payment",
109
+ recovery: "Send USDC to your wallet on Base",
110
+ }),
111
+ },
96
112
  {
97
113
  test: (m) => m.includes("INSUFFICIENT_OUTPUT_AMOUNT") || m.includes("Too little received"),
98
114
  classify: () => ({
@@ -39,6 +39,7 @@ const config_1 = require("./config");
39
39
  function detectGrinders() {
40
40
  return {
41
41
  gpu: detectLocalGpu(),
42
+ cuda: detectLocalCuda(),
42
43
  cpu: detectLocalCpu(),
43
44
  remoteGpu: !!(config_1.config.vastIp && config_1.config.vastPort),
44
45
  };
@@ -61,6 +62,22 @@ function detectLocalGpu() {
61
62
  }
62
63
  return null;
63
64
  }
65
+ function detectLocalCuda() {
66
+ if (config_1.config.cudaGrinderPath) {
67
+ return (0, node_fs_1.existsSync)(config_1.config.cudaGrinderPath) ? config_1.config.cudaGrinderPath : null;
68
+ }
69
+ const candidates = [
70
+ (0, node_path_1.join)(process.cwd(), "gpu", "grinder-cuda"),
71
+ (0, node_path_1.join)(process.cwd(), "local", "gpu", "grinder-cuda"),
72
+ (0, node_path_1.join)(process.cwd(), "grinder-cuda"),
73
+ (0, node_path_1.join)(node_os_1.default.homedir(), ".apow", "grinder-cuda"),
74
+ ];
75
+ for (const p of candidates) {
76
+ if ((0, node_fs_1.existsSync)(p))
77
+ return p;
78
+ }
79
+ return null;
80
+ }
64
81
  function detectLocalCpu() {
65
82
  if (config_1.config.cpuGrinderPath) {
66
83
  return (0, node_fs_1.existsSync)(config_1.config.cpuGrinderPath) ? config_1.config.cpuGrinderPath : null;
@@ -78,12 +95,14 @@ function detectLocalCpu() {
78
95
  return null;
79
96
  }
80
97
  function hasNativeGrinders(info) {
81
- return !!(info.gpu || info.cpu || info.remoteGpu);
98
+ return !!(info.gpu || info.cuda || info.cpu || info.remoteGpu);
82
99
  }
83
100
  function grinderLabel(info) {
84
101
  const parts = [];
85
102
  if (info.remoteGpu)
86
103
  parts.push("CUDA (remote)");
104
+ if (info.cuda)
105
+ parts.push("CUDA GPU");
87
106
  if (info.gpu)
88
107
  parts.push(process.platform === "darwin" ? "Metal GPU" : "GPU");
89
108
  if (info.cpu)
@@ -96,7 +115,7 @@ function grinderLabel(info) {
96
115
  * Grind nonce using all available native grinders in parallel.
97
116
  * First to find a valid nonce wins; all others are killed.
98
117
  */
99
- async function grindNonceNative(challengeNumber, target, minerAddress, info) {
118
+ async function grindNonceNative(challengeNumber, target, minerAddress, info, signal) {
100
119
  const targetHex = "0x" + target.toString(16).padStart(64, "0");
101
120
  const processes = [];
102
121
  const start = process.hrtime();
@@ -132,6 +151,20 @@ async function grindNonceNative(challengeNumber, target, minerAddress, info) {
132
151
  catch { }
133
152
  }
134
153
  }
154
+ // Abort signal support — kill all grinder processes if challenge goes stale
155
+ if (signal) {
156
+ if (signal.aborted) {
157
+ reject(new Error("Grind aborted: challenge stale"));
158
+ return;
159
+ }
160
+ signal.addEventListener("abort", () => {
161
+ if (!settled) {
162
+ settled = true;
163
+ cleanup();
164
+ reject(new Error("Grind aborted: challenge stale"));
165
+ }
166
+ }, { once: true });
167
+ }
135
168
  function onResult(result) {
136
169
  if (settled)
137
170
  return;
@@ -175,6 +208,42 @@ async function grindNonceNative(challengeNumber, target, minerAddress, info) {
175
208
  });
176
209
  proc.on("error", () => onFail());
177
210
  }
211
+ // Local CUDA GPU
212
+ if (info.cuda) {
213
+ totalGrinders++;
214
+ // CUDA arg order: <challenge> <target> <address>
215
+ const proc = (0, node_child_process_1.spawn)(info.cuda, [challengeNumber, targetHex, minerAddress]);
216
+ processes.push(proc);
217
+ let buf = "";
218
+ proc.stdout.on("data", (d) => {
219
+ if (settled)
220
+ return;
221
+ buf += d.toString();
222
+ let nl;
223
+ while ((nl = buf.indexOf("\n")) !== -1) {
224
+ const line = buf.slice(0, nl).trim();
225
+ buf = buf.slice(nl + 1);
226
+ if (line.startsWith("F ")) {
227
+ const parts = line.split(/\s+/);
228
+ if (parts.length >= 4) {
229
+ const e = parseFloat(parts[3]);
230
+ onResult({
231
+ nonce: BigInt(parts[2]),
232
+ attempts: 0n,
233
+ elapsed: e,
234
+ hashrate: 0,
235
+ });
236
+ return;
237
+ }
238
+ }
239
+ }
240
+ });
241
+ proc.on("close", () => {
242
+ if (!settled)
243
+ onFail();
244
+ });
245
+ proc.on("error", () => onFail());
246
+ }
178
247
  // Local CPU-C
179
248
  if (info.cpu) {
180
249
  totalGrinders++;
package/dist/grinder.js CHANGED
@@ -57,6 +57,20 @@ async function grindNonceParallel(params) {
57
57
  const [s, ns] = process.hrtime(start);
58
58
  return s + ns / 1_000_000_000;
59
59
  }
60
+ // Abort signal support — kill all workers if challenge goes stale
61
+ if (params.signal) {
62
+ if (params.signal.aborted) {
63
+ reject(new Error("Grind aborted: challenge stale"));
64
+ return;
65
+ }
66
+ params.signal.addEventListener("abort", () => {
67
+ if (!settled) {
68
+ settled = true;
69
+ cleanup();
70
+ reject(new Error("Grind aborted: challenge stale"));
71
+ }
72
+ }, { once: true });
73
+ }
60
74
  for (let i = 0; i < threadCount; i++) {
61
75
  // Each worker starts at a random offset to avoid overlap
62
76
  const startNonce = BigInt(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER));
package/dist/index.js CHANGED
@@ -197,10 +197,20 @@ async function setupWizard() {
197
197
  console.log(` ${ui.bold("Step 3/3: LLM Provider (for minting)")}`);
198
198
  console.log(` ${ui.dim("An LLM solves the SMHL challenge when minting your Mining Rig.")}`);
199
199
  console.log(` ${ui.dim("Mining uses optimized solving — no LLM needed after minting.")}`);
200
- const providerInput = await ui.prompt("Provider (openai/anthropic/gemini/ollama/deepseek/qwen/claude-code/codex)", "openai");
201
- const provider = (["openai", "anthropic", "gemini", "ollama", "deepseek", "qwen", "claude-code", "codex"].includes(providerInput) ? providerInput : "openai");
200
+ console.log(` ${ui.dim(" clawrouter (recommended) — Zero credentials. Pays with USDC from your wallet.")}`);
201
+ console.log(` ${ui.dim(" openai / anthropic / gemini / deepseek / qwen — Requires API key.")}`);
202
+ console.log(` ${ui.dim(" ollama / claude-code / codex — Local, no API key.")}`);
203
+ const providerInput = await ui.prompt("Provider", "clawrouter");
204
+ const provider = (["clawrouter", "openai", "anthropic", "gemini", "ollama", "deepseek", "qwen", "claude-code", "codex"].includes(providerInput) ? providerInput : "clawrouter");
202
205
  values.LLM_PROVIDER = provider;
203
- if (provider === "ollama") {
206
+ if (provider === "clawrouter") {
207
+ ui.ok("ClawRouter x402 — no API key needed, pays with USDC from your wallet");
208
+ if (!values.USE_X402 && !values.RPC_URL) {
209
+ values.USE_X402 = "true";
210
+ ui.ok("Auto-enabled x402 RPC (same wallet, same USDC balance)");
211
+ }
212
+ }
213
+ else if (provider === "ollama") {
204
214
  const ollamaUrl = await ui.prompt("Ollama URL", "http://127.0.0.1:11434");
205
215
  values.OLLAMA_URL = ollamaUrl;
206
216
  ui.ok(`Ollama at ${ollamaUrl}`);
@@ -219,7 +229,7 @@ async function setupWizard() {
219
229
  ui.hint(`Set LLM_API_KEY in .env later`);
220
230
  }
221
231
  }
222
- const defaultModel = provider === "gemini" ? "gemini-2.5-flash" : provider === "anthropic" ? "claude-sonnet-4-5-20250929" : provider === "deepseek" ? "deepseek-chat" : provider === "qwen" ? "qwen-plus" : provider === "claude-code" || provider === "codex" ? "default" : "gpt-4o-mini";
232
+ const defaultModel = provider === "clawrouter" ? "blockrun/eco" : provider === "gemini" ? "gemini-2.5-flash" : provider === "anthropic" ? "claude-sonnet-4-5-20250929" : provider === "deepseek" ? "deepseek-chat" : provider === "qwen" ? "qwen-plus" : provider === "claude-code" || provider === "codex" ? "default" : "gpt-4o-mini";
223
233
  const model = await ui.prompt("Model", defaultModel);
224
234
  values.LLM_MODEL = model;
225
235
  if ((0, config_1.isExpensiveModel)(model)) {
@@ -260,8 +270,14 @@ async function main() {
260
270
  const version = readVersion();
261
271
  const program = new commander_1.Command();
262
272
  // SIGINT handler
263
- process.on("SIGINT", () => {
273
+ process.on("SIGINT", async () => {
264
274
  ui.stopAll();
275
+ try {
276
+ const { stopClawRouter, isClawRouterRunning } = await Promise.resolve().then(() => __importStar(require("./clawrouter")));
277
+ if (isClawRouterRunning())
278
+ await stopClawRouter();
279
+ }
280
+ catch { }
265
281
  console.log("");
266
282
  console.log(ui.dim(" Interrupted. Bye!"));
267
283
  process.exit(0);
@@ -334,6 +350,14 @@ async function main() {
334
350
  }
335
351
  await (0, stats_1.displayStats)(tokenId);
336
352
  });
353
+ program
354
+ .command("build-grinders")
355
+ .description("Compile native grinder binaries for GPU/CPU mining (~10-100x faster)")
356
+ .option("--cuda-arch <arch>", "CUDA architecture override (e.g., sm_89)")
357
+ .action(async (opts) => {
358
+ const { buildGrinders } = await Promise.resolve().then(() => __importStar(require("./build")));
359
+ await buildGrinders(opts);
360
+ });
337
361
  const walletCmd = program
338
362
  .command("wallet")
339
363
  .description("Wallet generation and management");