apow-cli 0.11.19 → 0.12.3

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/preflight.js CHANGED
@@ -39,18 +39,21 @@ Object.defineProperty(exports, "__esModule", { value: true });
39
39
  exports.runPreflight = runPreflight;
40
40
  const node_child_process_1 = require("node:child_process");
41
41
  const viem_1 = require("viem");
42
- const chains_1 = require("viem/chains");
43
42
  const AgentCoin_json_1 = __importDefault(require("./abi/AgentCoin.json"));
44
43
  const MiningAgent_json_1 = __importDefault(require("./abi/MiningAgent.json"));
45
44
  const config_1 = require("./config");
45
+ const errors_1 = require("./errors");
46
46
  const grinder_http_1 = require("./grinder-http");
47
+ const policy_1 = require("./policy/policy");
48
+ const spend_ledger_1 = require("./policy/spend-ledger");
49
+ const secure_env_1 = require("./secure-env");
47
50
  const wallet_1 = require("./wallet");
51
+ const base_funding_1 = require("./base-funding");
48
52
  const ui = __importStar(require("./ui"));
49
53
  const agentCoinAbi = AgentCoin_json_1.default;
50
54
  const miningAgentAbi = MiningAgent_json_1.default;
51
55
  const USDC_ADDRESS = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
52
56
  const USDC_DECIMALS = 6;
53
- const MINT_GAS_RESERVE_ETH = (0, viem_1.parseEther)("0.003");
54
57
  const erc20BalanceAbi = [
55
58
  {
56
59
  type: "function",
@@ -60,13 +63,60 @@ const erc20BalanceAbi = [
60
63
  stateMutability: "view",
61
64
  },
62
65
  ];
63
- function hasLocalCli(command) {
66
+ function runLocalCliCheck(command, args, env) {
67
+ const result = (0, node_child_process_1.spawnSync)(command, args, {
68
+ encoding: "utf8",
69
+ env,
70
+ timeout: 5_000,
71
+ stdio: ["ignore", "pipe", "pipe"],
72
+ });
73
+ return {
74
+ passed: result.status === 0,
75
+ output: `${result.stdout ?? ""}\n${result.stderr ?? ""}`,
76
+ };
77
+ }
78
+ function hasLocalCli(command, env) {
79
+ return runLocalCliCheck(command, ["--version"], env).passed;
80
+ }
81
+ function hasClaudeSubscriptionAuth() {
82
+ const result = runLocalCliCheck("claude", ["auth", "status"], (0, secure_env_1.claudeSubscriptionEnv)());
83
+ return result.passed && /claude\.ai|subscription/i.test(result.output);
84
+ }
85
+ function hasCodexSubscriptionAuth() {
86
+ const result = runLocalCliCheck("codex", ["login", "status"], (0, secure_env_1.codexSubscriptionEnv)());
87
+ return result.passed && /chatgpt/i.test(result.output);
88
+ }
89
+ async function checkOllamaReadiness() {
90
+ const endpoint = `${config_1.config.ollamaUrl.replace(/\/+$/, "")}/api/tags`;
64
91
  try {
65
- (0, node_child_process_1.execFileSync)(command, ["--version"], { stdio: "ignore" });
66
- return true;
92
+ const response = await fetch(endpoint, { signal: AbortSignal.timeout(3_000) });
93
+ if (!response.ok) {
94
+ throw new Error(`HTTP ${response.status}`);
95
+ }
96
+ const data = (await response.json());
97
+ const expected = config_1.config.llmModel.split(":")[0];
98
+ const installed = (data.models ?? []).some(({ name, model }) => {
99
+ const candidate = name ?? model ?? "";
100
+ return candidate === config_1.config.llmModel || candidate.split(":")[0] === expected;
101
+ });
102
+ if (!installed) {
103
+ return {
104
+ label: `LLM provider: ollama is missing ${config_1.config.llmModel}`,
105
+ passed: false,
106
+ fix: `Run \`ollama pull ${config_1.config.llmModel}\`, then retry`,
107
+ };
108
+ }
109
+ return {
110
+ label: `LLM provider: ollama (${config_1.config.llmModel}, local inference)`,
111
+ passed: true,
112
+ };
67
113
  }
68
114
  catch {
69
- return false;
115
+ return {
116
+ label: `LLM provider: ollama is unreachable at ${(0, errors_1.redactUrls)(config_1.config.ollamaUrl)}`,
117
+ passed: false,
118
+ fix: "Install and start Ollama, then retry",
119
+ };
70
120
  }
71
121
  }
72
122
  async function runPreflight(level) {
@@ -94,40 +144,37 @@ async function runPreflight(level) {
94
144
  // Check x402: USDC balance BEFORE RPC check (can't use x402 without USDC)
95
145
  let x402Funded = false;
96
146
  if (config_1.config.useX402 && wallet_1.account) {
97
- try {
98
- // Use a separate lightweight client to avoid chicken-and-egg
99
- // (can't use x402 to check if we can pay for x402)
100
- const checkClient = (0, viem_1.createPublicClient)({
101
- chain: chains_1.base,
102
- transport: (0, viem_1.http)("https://mainnet.base.org"),
103
- });
104
- const usdcBalance = (await checkClient.readContract({
105
- address: USDC_ADDRESS,
106
- abi: erc20BalanceAbi,
107
- functionName: "balanceOf",
108
- args: [wallet_1.account.address],
109
- }));
110
- if (usdcBalance === 0n) {
111
- results.push({
112
- label: "No USDC balance — QuickNode x402 requires USDC on Base",
113
- passed: false,
114
- fix: `Send at least 2.00 USDC to ${wallet_1.account.address} on Base for x402 starting balance; add more if you want extra headroom. Run \`apow fund\` to bridge from Solana or Ethereum.`,
115
- });
147
+ {
148
+ try {
149
+ // Use a separate lightweight client to avoid chicken-and-egg
150
+ // (can't use x402 to check if we can pay for x402)
151
+ const checkClient = (0, wallet_1.getFundingClients)().publicClient;
152
+ const usdcBalance = (await checkClient.readContract({
153
+ address: USDC_ADDRESS,
154
+ abi: erc20BalanceAbi,
155
+ functionName: "balanceOf",
156
+ args: [wallet_1.account.address],
157
+ }));
158
+ if (usdcBalance === 0n) {
159
+ results.push({
160
+ label: "No USDC balance — QuickNode x402 requires USDC on Base",
161
+ passed: false,
162
+ fix: "Run `apow start --easy` to quote an ETH-only deposit and convert the service budget to USDC.",
163
+ });
164
+ }
165
+ else {
166
+ x402Funded = true;
167
+ const formatted = (0, viem_1.formatUnits)(usdcBalance, USDC_DECIMALS);
168
+ results.push({
169
+ label: `RPC: QuickNode x402 (${formatted} USDC available)`,
170
+ passed: true,
171
+ });
172
+ }
116
173
  }
117
- else {
118
- x402Funded = true;
119
- const formatted = (0, viem_1.formatUnits)(usdcBalance, USDC_DECIMALS);
120
- results.push({
121
- label: `RPC: QuickNode x402 (${formatted} USDC available)`,
122
- passed: true,
123
- });
174
+ catch {
175
+ results.push({ label: "Could not verify x402 funding", passed: false, fix: "Retry when the funding RPC responds" });
124
176
  }
125
177
  }
126
- catch {
127
- // USDC check failed — can't verify, warn but don't block
128
- x402Funded = true; // optimistic — let the RPC check determine reachability
129
- ui.warn("Could not check USDC balance — QuickNode x402 may fail if wallet has no USDC");
130
- }
131
178
  }
132
179
  // Check 2: RPC reachable + chain ID
133
180
  // Skip when: no RPC configured at all, or x402 active but unfunded
@@ -151,7 +198,7 @@ async function runPreflight(level) {
151
198
  }
152
199
  catch {
153
200
  results.push({
154
- label: `RPC unreachable — could not connect to ${config_1.config.useX402 ? "QuickNode x402" : config_1.config.rpcUrl}`,
201
+ label: `RPC unreachable — could not connect to ${config_1.config.useX402 ? "QuickNode x402" : (0, errors_1.redactUrls)(config_1.config.rpcUrl)}`,
155
202
  passed: false,
156
203
  fix: config_1.config.useX402
157
204
  ? "Check internet connection and USDC balance, or set RPC_URL in .env for a custom RPC"
@@ -160,18 +207,33 @@ async function runPreflight(level) {
160
207
  }
161
208
  }
162
209
  if (level === "wallet" || level === "mining") {
210
+ const policy = (0, policy_1.loadPolicy)();
211
+ const spent = wallet_1.account ? (0, spend_ledger_1.spentTodayUsdc)(wallet_1.account.address) : 0;
212
+ const remaining = Math.max(0, policy.x402.dailyUsdc - spent);
213
+ results.push({
214
+ label: `Policy: ${policy.mode} (${remaining.toFixed(2)} USDC x402 budget remaining today)`,
215
+ passed: true,
216
+ });
163
217
  // Check 3: Private key valid
164
218
  if (wallet_1.account) {
219
+ const source = config_1.config.walletSource === "keystore" ? "encrypted keystore" : "legacy PRIVATE_KEY";
165
220
  results.push({
166
- label: `Private key valid (${wallet_1.account.address.slice(0, 6)}...${wallet_1.account.address.slice(-4)})`,
221
+ label: `Wallet signer unlocked via ${source} (${wallet_1.account.address.slice(0, 6)}...${wallet_1.account.address.slice(-4)})`,
167
222
  passed: true,
168
223
  });
169
224
  }
225
+ else if (config_1.config.keystorePath && config_1.config.walletLoadError) {
226
+ results.push({
227
+ label: "Encrypted keystore locked",
228
+ passed: false,
229
+ fix: config_1.config.walletLoadError,
230
+ });
231
+ }
170
232
  else {
171
233
  results.push({
172
234
  label: "Private key not configured",
173
235
  passed: false,
174
- fix: "Run `apow setup` and choose Easy Mode, or set PRIVATE_KEY in .env (0x-prefixed 32-byte hex)",
236
+ fix: "Run `apow setup` and choose Easy Mode, or set KEYSTORE_PATH to an encrypted keystore",
175
237
  });
176
238
  }
177
239
  // Check 4: Wallet has ETH (skip if RPC already failed — avoids duplicate errors)
@@ -185,12 +247,12 @@ async function runPreflight(level) {
185
247
  abi: miningAgentAbi,
186
248
  functionName: "getMintPrice",
187
249
  }));
188
- const requiredBalance = mintPrice + MINT_GAS_RESERVE_ETH;
250
+ const requiredBalance = mintPrice + base_funding_1.MINT_GAS_RESERVE_ETH;
189
251
  if (balance < requiredBalance) {
190
252
  results.push({
191
253
  label: `Mint-ready ETH balance (${ethBalance.toFixed(6)} ETH)`,
192
254
  passed: false,
193
- fix: `Mint needs ${(0, viem_1.formatEther)(mintPrice)} ETH for the rig plus ~${(0, viem_1.formatEther)(MINT_GAS_RESERVE_ETH)} ETH for the getChallenge and mint transactions. Send at least ${(0, viem_1.formatEther)(requiredBalance)} ETH to ${wallet_1.account.address} on Base.`,
255
+ fix: `Mint price is ${(0, viem_1.formatEther)(mintPrice)} ETH; the CLI also retains a conservative ${(0, viem_1.formatEther)(base_funding_1.MINT_GAS_RESERVE_ETH)} ETH reserve. The reserve is not a transaction fee. Run apow start --easy for the complete ETH-only quote.`,
194
256
  });
195
257
  }
196
258
  else {
@@ -224,48 +286,64 @@ async function runPreflight(level) {
224
286
  if (config_1.config.llmProvider === "clawrouter") {
225
287
  if (!wallet_1.account) {
226
288
  results.push({
227
- label: "ClawRouter requires PRIVATE_KEY (wallet signs x402 payments)",
289
+ label: "The x402 LLM service requires an unlocked wallet signer",
228
290
  passed: false,
229
- fix: "Set PRIVATE_KEY in .env",
291
+ fix: "Unlock KEYSTORE_PATH with KEYSTORE_PASSWORD",
230
292
  });
231
293
  }
232
294
  else {
233
295
  results.push({
234
- label: "LLM provider: clawrouter (x402, same wallet as mining)",
296
+ label: "LLM provider: automatic x402 model selection",
235
297
  passed: true,
236
298
  });
237
299
  }
238
300
  }
239
301
  else if (config_1.config.llmProvider === "ollama") {
240
- results.push({ label: `LLM provider: ollama (${config_1.config.ollamaUrl})`, passed: true });
302
+ results.push(await checkOllamaReadiness());
241
303
  }
242
304
  else if (config_1.config.llmProvider === "claude-code") {
243
- if (hasLocalCli("claude")) {
305
+ const env = (0, secure_env_1.claudeSubscriptionEnv)();
306
+ if (!hasLocalCli("claude", env)) {
244
307
  results.push({
245
- label: "LLM provider: claude-code (local CLI detected; auth checked at mint time)",
308
+ label: "LLM provider claude-code not installed",
309
+ passed: false,
310
+ fix: "Install Claude Code or switch to LLM_PROVIDER=clawrouter",
311
+ });
312
+ }
313
+ else if (hasClaudeSubscriptionAuth()) {
314
+ results.push({
315
+ label: "LLM provider: Claude Code (Claude subscription authenticated)",
246
316
  passed: true,
247
317
  });
248
318
  }
249
319
  else {
250
320
  results.push({
251
- label: "LLM provider claude-code not installed",
321
+ label: "Claude Code is not signed in with a Claude subscription",
252
322
  passed: false,
253
- fix: "Install the Claude CLI or switch to LLM_PROVIDER=clawrouter",
323
+ fix: "Run `claude login`, choose your Claude.ai subscription, then retry",
254
324
  });
255
325
  }
256
326
  }
257
327
  else if (config_1.config.llmProvider === "codex") {
258
- if (hasLocalCli("codex")) {
328
+ const env = (0, secure_env_1.codexSubscriptionEnv)();
329
+ if (!hasLocalCli("codex", env)) {
259
330
  results.push({
260
- label: "LLM provider: codex (local CLI detected; auth/region checked at mint time)",
331
+ label: "LLM provider codex not installed",
332
+ passed: false,
333
+ fix: "Install Codex CLI or switch to LLM_PROVIDER=clawrouter",
334
+ });
335
+ }
336
+ else if (hasCodexSubscriptionAuth()) {
337
+ results.push({
338
+ label: "LLM provider: Codex (ChatGPT subscription authenticated)",
261
339
  passed: true,
262
340
  });
263
341
  }
264
342
  else {
265
343
  results.push({
266
- label: "LLM provider codex not installed",
344
+ label: "Codex is not signed in with ChatGPT",
267
345
  passed: false,
268
- fix: "Install the Codex CLI or switch to LLM_PROVIDER=clawrouter",
346
+ fix: "Run `codex login`, choose ChatGPT subscription access, then retry",
269
347
  });
270
348
  }
271
349
  }
@@ -276,7 +354,7 @@ async function runPreflight(level) {
276
354
  results.push({
277
355
  label: `LLM API key not set for ${config_1.config.llmProvider}`,
278
356
  passed: false,
279
- fix: "Set LLM_API_KEY in .env, or switch to LLM_PROVIDER=clawrouter (zero credentials, pays with USDC)",
357
+ fix: "Set LLM_API_KEY in .env, or switch to LLM_PROVIDER=clawrouter (no API key; wallet-paid in USDC)",
280
358
  });
281
359
  }
282
360
  }
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.childEnv = childEnv;
4
+ exports.claudeSubscriptionEnv = claudeSubscriptionEnv;
5
+ exports.codexSubscriptionEnv = codexSubscriptionEnv;
6
+ const SECRET_ENV_KEYS = new Set([
7
+ "KEYSTORE_PASSWORD",
8
+ "APOW_KEYSTORE_PASSWORD",
9
+ "PRIVATE_KEY",
10
+ ]);
11
+ const SUBSCRIPTION_CLI_ENV_KEYS = new Set([
12
+ "PATH",
13
+ "HOME",
14
+ "USER",
15
+ "LOGNAME",
16
+ "SHELL",
17
+ "TMPDIR",
18
+ "TMP",
19
+ "TEMP",
20
+ "LANG",
21
+ "LC_ALL",
22
+ "LC_CTYPE",
23
+ "TERM",
24
+ "NO_COLOR",
25
+ "FORCE_COLOR",
26
+ "SSL_CERT_FILE",
27
+ "SSL_CERT_DIR",
28
+ "NODE_EXTRA_CA_CERTS",
29
+ "CODEX_HOME",
30
+ "CLAUDE_CONFIG_DIR",
31
+ "XDG_CONFIG_HOME",
32
+ "XDG_DATA_HOME",
33
+ "XDG_CACHE_HOME",
34
+ "PATHEXT",
35
+ "SystemRoot",
36
+ "ComSpec",
37
+ "WINDIR",
38
+ "USERPROFILE",
39
+ "LOCALAPPDATA",
40
+ "APPDATA",
41
+ ]);
42
+ function childEnv(base = process.env) {
43
+ const next = {};
44
+ for (const [key, value] of Object.entries(base)) {
45
+ if (!SECRET_ENV_KEYS.has(key)) {
46
+ next[key] = value;
47
+ }
48
+ }
49
+ return next;
50
+ }
51
+ function subscriptionCliEnv(base) {
52
+ const next = {};
53
+ for (const [key, value] of Object.entries(base)) {
54
+ if (SUBSCRIPTION_CLI_ENV_KEYS.has(key)) {
55
+ next[key] = value;
56
+ }
57
+ }
58
+ return next;
59
+ }
60
+ function claudeSubscriptionEnv(base = process.env) {
61
+ return subscriptionCliEnv(base);
62
+ }
63
+ function codexSubscriptionEnv(base = process.env) {
64
+ return subscriptionCliEnv(base);
65
+ }
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createGuardedAccount = createGuardedAccount;
4
+ const audit_log_1 = require("../policy/audit-log");
5
+ const context_1 = require("../policy/context");
6
+ const policy_1 = require("../policy/policy");
7
+ const spend_ledger_1 = require("../policy/spend-ledger");
8
+ const decode_1 = require("../policy/decode");
9
+ function createGuardedAccount(base) {
10
+ return {
11
+ ...base,
12
+ async signTransaction(transaction, options) {
13
+ const context = (0, context_1.getSignerContext)();
14
+ const verdict = (0, policy_1.evaluateTx)({
15
+ account: base.address,
16
+ to: transaction.to,
17
+ value: transaction.value,
18
+ data: transaction.data,
19
+ context,
20
+ });
21
+ (0, audit_log_1.appendAudit)({
22
+ address: base.address,
23
+ kind: verdict.kind,
24
+ target: transaction.to ?? undefined,
25
+ selector: (0, decode_1.calldataSelector)(transaction.data),
26
+ valueWei: transaction.value?.toString(),
27
+ verdict: verdict.verdict,
28
+ policyRule: verdict.rule,
29
+ context,
30
+ });
31
+ (0, policy_1.assertAllowed)(verdict);
32
+ return base.signTransaction(transaction, options);
33
+ },
34
+ async signTypedData(parameters) {
35
+ const context = (0, context_1.getSignerContext)();
36
+ const verdict = (0, policy_1.evaluateTypedData)({ account: base.address, parameters, context });
37
+ (0, audit_log_1.appendAudit)({
38
+ address: base.address,
39
+ kind: verdict.kind,
40
+ target: "typed-data",
41
+ usdc: verdict.usdc?.toString(),
42
+ payee: verdict.payee,
43
+ verdict: verdict.verdict,
44
+ policyRule: verdict.rule,
45
+ context,
46
+ });
47
+ (0, policy_1.assertAllowed)(verdict);
48
+ if (verdict.kind === "x402" && verdict.usdc !== undefined) {
49
+ (0, spend_ledger_1.recordSpend)({ address: base.address, kind: "x402", usdc: verdict.usdc, payee: verdict.payee });
50
+ }
51
+ return base.signTypedData(parameters);
52
+ },
53
+ async signMessage({ message }) {
54
+ (0, audit_log_1.appendAudit)({
55
+ address: base.address,
56
+ kind: "other",
57
+ target: "signMessage",
58
+ verdict: "deny",
59
+ policyRule: "sign-message-denied",
60
+ context: (0, context_1.getSignerContext)(),
61
+ });
62
+ throw new Error("Policy denied: sign-message-denied. APoW CLI does not sign arbitrary messages.");
63
+ },
64
+ sign: base.sign
65
+ ? async ({ hash }) => {
66
+ (0, audit_log_1.appendAudit)({
67
+ address: base.address,
68
+ kind: "other",
69
+ target: "raw-sign",
70
+ verdict: "deny",
71
+ policyRule: "raw-sign-denied",
72
+ context: (0, context_1.getSignerContext)(),
73
+ });
74
+ throw new Error(`Policy denied: raw-sign-denied. Refusing to sign raw hash ${hash.slice(0, 10)}...`);
75
+ }
76
+ : undefined,
77
+ };
78
+ }
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resetSigner = resetSigner;
4
+ exports.getSigner = getSigner;
5
+ const accounts_1 = require("viem/accounts");
6
+ const config_1 = require("../config");
7
+ const audit_log_1 = require("../policy/audit-log");
8
+ const guarded_account_1 = require("./guarded-account");
9
+ let cachedKey;
10
+ let cachedSigner = null;
11
+ function resetSigner() {
12
+ cachedKey = undefined;
13
+ cachedSigner = null;
14
+ }
15
+ function getSigner() {
16
+ if (!config_1.config.privateKey)
17
+ return null;
18
+ if (cachedSigner && cachedKey === config_1.config.privateKey)
19
+ return cachedSigner;
20
+ const rawKey = config_1.config.privateKey;
21
+ const base = (0, accounts_1.privateKeyToAccount)(rawKey);
22
+ const guarded = (0, guarded_account_1.createGuardedAccount)(base);
23
+ cachedKey = rawKey;
24
+ cachedSigner = {
25
+ address: base.address,
26
+ kind: config_1.config.walletSource === "keystore" ? "keystore" : "env-key",
27
+ account: guarded,
28
+ unsafeRawKeyFor(consumer) {
29
+ (0, audit_log_1.appendAudit)({
30
+ address: base.address,
31
+ kind: "raw-key-handout",
32
+ target: consumer,
33
+ verdict: "allow",
34
+ policyRule: "raw-key-handout",
35
+ });
36
+ return rawKey;
37
+ },
38
+ };
39
+ return cachedSigner;
40
+ }
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.setSessionPassword = setSessionPassword;
4
+ exports.getSessionPassword = getSessionPassword;
5
+ let sessionPassword = "";
6
+ function setSessionPassword(password) {
7
+ sessionPassword = password;
8
+ }
9
+ function getSessionPassword() {
10
+ return sessionPassword;
11
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/dist/smhl.js CHANGED
@@ -42,8 +42,15 @@ exports.validateSmhlSolution = validateSmhlSolution;
42
42
  exports.solveSmhlAlgorithmic = solveSmhlAlgorithmic;
43
43
  exports.solveSmhlChallenge = solveSmhlChallenge;
44
44
  const node_child_process_1 = require("node:child_process");
45
+ const node_fs_1 = require("node:fs");
46
+ const node_os_1 = require("node:os");
47
+ const node_path_1 = require("node:path");
45
48
  const openai_1 = __importDefault(require("openai"));
46
49
  const config_1 = require("./config");
50
+ const secure_env_1 = require("./secure-env");
51
+ const local_keystore_1 = require("./signer/local-keystore");
52
+ const SMHL_SYSTEM_PROMPT = "You generate short lowercase word sequences that match exact constraints. "
53
+ + "Return only the words separated by spaces. Do not use tools. Nothing else.";
47
54
  function normalizeSmhlChallenge(raw) {
48
55
  if (Array.isArray(raw)) {
49
56
  const [targetAsciiSum, firstNChars, wordCount, charPosition, charValue, totalLength] = raw;
@@ -320,8 +327,11 @@ async function requestQwenSolutionForModel(prompt, model) {
320
327
  }
321
328
  async function requestClawRouterSolution(prompt, model) {
322
329
  const { ensureClawRouter, getClawRouterBaseUrl } = await Promise.resolve().then(() => __importStar(require("./clawrouter")));
323
- const { requirePrivateKey } = await Promise.resolve().then(() => __importStar(require("./config")));
324
- await ensureClawRouter(requirePrivateKey());
330
+ const signer = (0, local_keystore_1.getSigner)();
331
+ if (!signer) {
332
+ throw new Error("ClawRouter requires an unlocked wallet signer.");
333
+ }
334
+ await ensureClawRouter(signer.unsafeRawKeyFor("clawrouter"));
325
335
  const client = new openai_1.default({
326
336
  apiKey: "x402",
327
337
  baseURL: `${getClawRouterBaseUrl()}/v1`,
@@ -339,10 +349,41 @@ async function requestClawRouterSolution(prompt, model) {
339
349
  }, { timeout: 15_000 });
340
350
  return response.choices[0]?.message.content ?? "";
341
351
  }
342
- async function requestClaudeCodeSolution(prompt) {
352
+ function createIsolatedCliDirectory(prefix) {
353
+ return (0, node_fs_1.mkdtempSync)((0, node_path_1.join)((0, node_os_1.tmpdir)(), prefix));
354
+ }
355
+ function removeIsolatedCliDirectory(path) {
356
+ try {
357
+ (0, node_fs_1.rmSync)(path, { recursive: true, force: true });
358
+ }
359
+ catch {
360
+ // Best-effort cleanup after a short-lived, non-persistent inference run.
361
+ }
362
+ }
363
+ async function requestClaudeCodeSolution(prompt, model) {
343
364
  return new Promise((resolve, reject) => {
344
- const escaped = prompt.replace(/'/g, "'\\''");
345
- (0, node_child_process_1.exec)(`claude -p '${escaped}'`, { timeout: 120_000 }, (error, stdout, stderr) => {
365
+ const cwd = createIsolatedCliDirectory("apow-claude-smhl-");
366
+ (0, node_child_process_1.execFile)("claude", [
367
+ "-p",
368
+ prompt,
369
+ "--no-session-persistence",
370
+ "--safe-mode",
371
+ "--disable-slash-commands",
372
+ "--tools",
373
+ "",
374
+ "--model",
375
+ model,
376
+ "--effort",
377
+ "low",
378
+ "--system-prompt",
379
+ SMHL_SYSTEM_PROMPT,
380
+ ], {
381
+ cwd,
382
+ timeout: 15_000,
383
+ maxBuffer: 64 * 1024,
384
+ env: (0, secure_env_1.claudeSubscriptionEnv)(),
385
+ }, (error, stdout, stderr) => {
386
+ removeIsolatedCliDirectory(cwd);
346
387
  if (error) {
347
388
  reject(new Error(`Claude Code error: ${error.message}${stderr ? `\nstderr: ${stderr}` : ""}${stdout ? `\nstdout: ${stdout}` : ""}`));
348
389
  return;
@@ -351,15 +392,41 @@ async function requestClaudeCodeSolution(prompt) {
351
392
  });
352
393
  });
353
394
  }
354
- async function requestCodexSolution(prompt) {
395
+ async function requestCodexSolution(prompt, model) {
355
396
  return new Promise((resolve, reject) => {
356
- (0, node_child_process_1.execFile)("codex", ["exec", prompt, "--full-auto"], { timeout: 15_000 }, (error, stdout, stderr) => {
397
+ const cwd = createIsolatedCliDirectory("apow-codex-smhl-");
398
+ const child = (0, node_child_process_1.execFile)("codex", [
399
+ "exec",
400
+ "--ephemeral",
401
+ "--ignore-user-config",
402
+ "--ignore-rules",
403
+ "--sandbox",
404
+ "read-only",
405
+ "--skip-git-repo-check",
406
+ "--color",
407
+ "never",
408
+ "--model",
409
+ model,
410
+ "--config",
411
+ 'model_reasoning_effort="low"',
412
+ "--config",
413
+ 'shell_environment_policy.inherit="none"',
414
+ "-",
415
+ ], {
416
+ cwd,
417
+ timeout: 15_000,
418
+ maxBuffer: 64 * 1024,
419
+ env: (0, secure_env_1.codexSubscriptionEnv)(),
420
+ }, (error, stdout, stderr) => {
421
+ removeIsolatedCliDirectory(cwd);
357
422
  if (error) {
358
423
  reject(new Error(`Codex error: ${error.message}${stderr ? `\nstderr: ${stderr}` : ""}${stdout ? `\nstdout: ${stdout}` : ""}`));
359
424
  return;
360
425
  }
361
426
  resolve(stdout.trim());
362
427
  });
428
+ child.stdin?.on("error", () => { });
429
+ child.stdin?.end(`${SMHL_SYSTEM_PROMPT}\n\n${prompt}`);
363
430
  });
364
431
  }
365
432
  function resolveModelForProvider(provider) {
@@ -373,7 +440,13 @@ function resolveProviderOrder() {
373
440
  return providers;
374
441
  }
375
442
  function describeProvider(provider) {
376
- return provider === "claude-code" ? "Claude Code" : provider === "clawrouter" ? "ClawRouter" : provider;
443
+ return provider === "claude-code"
444
+ ? "Claude Code"
445
+ : provider === "codex"
446
+ ? "Codex"
447
+ : provider === "clawrouter"
448
+ ? "ClawRouter"
449
+ : provider;
377
450
  }
378
451
  function isPermanentProviderError(message) {
379
452
  const normalized = message.toLowerCase();
@@ -399,9 +472,9 @@ async function requestProviderSolution(provider, prompt) {
399
472
  case "ollama":
400
473
  return requestOllamaSolutionForModel(prompt, model);
401
474
  case "claude-code":
402
- return requestClaudeCodeSolution(prompt);
475
+ return requestClaudeCodeSolution(prompt, model);
403
476
  case "codex":
404
- return requestCodexSolution(prompt);
477
+ return requestCodexSolution(prompt, model);
405
478
  case "deepseek":
406
479
  return requestDeepSeekSolutionForModel(prompt, model);
407
480
  case "qwen":