alvin-bot 4.4.5 → 4.4.6

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/CHANGELOG.md CHANGED
@@ -2,6 +2,50 @@
2
2
 
3
3
  All notable changes to Alvin Bot are documented here.
4
4
 
5
+ ## [4.4.6] — 2026-04-09
6
+
7
+ ### šŸ› Bug Fixes
8
+
9
+ **`alvin-bot audit` now reads `.env` from `DATA_DIR`** — Before this release, `audit` was a subprocess that never loaded the bot's config: it only inspected `process.env`, which for an ad-hoc CLI invocation is the shell environment, not the bot's actual runtime state. Result: `ALLOWED_USERS` and `WEB_PASSWORD` were always reported as "not set" even when the bot was correctly configured and running. `audit` now calls `dotenv.config({ path: ENV_FILE })` at the start of `runAudit()` so its output matches `alvin-bot doctor` and the actual engine.
10
+
11
+ **`alvin-bot doctor` no longer hangs indefinitely on missing `.env`** — The CLI's `readline` interface was created eagerly at module load, which made `stdin` readable for the entire process lifetime. Commands like `doctor`, `audit`, `version` that have no interactive prompts would therefore never terminate — even though the `doctor()` function correctly early-returned when `.env` was missing, `node` refused to exit because the event loop still saw stdin as a live resource. Readline is now lazy-created only when `ask()` is actually called. Measured improvement: **doctor with missing .env terminates in 82 ms** (previously: 20+ second hang, often requiring Ctrl+C).
12
+
13
+ **`validateProviderKey("claude-sdk", …)` no longer false-negatives on Agent SDK auth** — The CLI's Claude check ran `claude auth status` and hard-failed on `loggedIn: false`. But the Claude Agent SDK has multiple auth paths that the CLI doesn't see: `ANTHROPIC_API_KEY` env var, Claude Code IDE sessions, and native-binary session cookies. Real-world example: a bot that was actively answering Telegram messages correctly was reported as "āŒ Claude CLI not authenticated" by `doctor`. The validation is now:
14
+ - `ANTHROPIC_API_KEY` set → `ok: true` (immediate pass, CLI irrelevant)
15
+ - `claude` binary present + `auth status: loggedIn: true` → `ok: true`
16
+ - `claude` binary present + `auth status: loggedIn: false` → `ok: true` with a **warning** (the Agent SDK may still work via session / env var; user is advised to run `claude auth login` only if the bot fails to respond)
17
+ - `claude` binary missing → `ok: false` (hard error with install hint)
18
+
19
+ `doctor` now renders the warning as āš ļø instead of āŒ, making the output match actual behavior.
20
+
21
+ ### ✨ New Feature
22
+
23
+ **`alvin-bot setup --non-interactive` for CI, Docker, and scripted installs** — The interactive setup wizard was the only way to write `~/.alvin-bot/.env`, which blocked automated provisioning. Now supports flag-driven, non-interactive setup:
24
+
25
+ ```bash
26
+ alvin-bot setup --non-interactive \
27
+ --bot-token=123456789:AAE... \
28
+ --allowed-users=12345,67890 \
29
+ --primary-provider=claude-sdk \
30
+ --fallback-providers=ollama \
31
+ --groq-key=gsk_... \
32
+ --google-key=AIza... \
33
+ --openai-key=sk-... \
34
+ --nvidia-key=nvapi-... \
35
+ --anthropic-key=sk-ant-... \
36
+ --openrouter-key=sk-or-... \
37
+ --web-password=... \
38
+ --platform=telegram \
39
+ --skip-validation # optional, skips the live Telegram getMe call
40
+ ```
41
+
42
+ - Refuses to overwrite an existing `.env` (exits 1 with a clear message).
43
+ - Writes with mode `0600`.
44
+ - Validates `--bot-token` format and `--allowed-users` numeric format before writing.
45
+ - Optionally pings Telegram `getMe` unless `--skip-validation` is passed.
46
+
47
+ `-y` and `--yes` work as aliases for `--non-interactive`.
48
+
5
49
  ## [4.4.5] — 2026-04-09
6
50
 
7
51
  ### šŸ” Security / Information Disclosure
package/bin/cli.js CHANGED
@@ -29,8 +29,20 @@ const DATA_DIR = process.env.ALVIN_DATA_DIR || join(homedir(), ".alvin-bot");
29
29
  // Init i18n early
30
30
  initI18n();
31
31
 
32
- const rl = createInterface({ input: process.stdin, output: process.stdout });
33
- const ask = (q) => new Promise((r) => rl.question(q, r));
32
+ // Lazy-create the readline interface. If we create it eagerly, stdin becomes
33
+ // "active" and Node refuses to exit even when a command like `doctor` has
34
+ // finished synchronously. Before v4.4.6 this caused `alvin-bot doctor` to
35
+ // hang indefinitely when .env was missing — early-return worked, but the
36
+ // process couldn't terminate. Creating rl only when `ask()` is actually
37
+ // called keeps non-interactive commands (audit/doctor/version/start/stop)
38
+ // terminating cleanly.
39
+ let rl = null;
40
+ const ensureRL = () => {
41
+ if (!rl) rl = createInterface({ input: process.stdin, output: process.stdout });
42
+ return rl;
43
+ };
44
+ const closeRL = () => { if (rl) { rl.close(); rl = null; } };
45
+ const ask = (q) => new Promise((r) => ensureRL().question(q, r));
34
46
 
35
47
  const LOGO = `
36
48
  ╔══════════════════════════════════════╗
@@ -164,6 +176,17 @@ async function validateProviderKey(providerKey, apiKey) {
164
176
  }
165
177
 
166
178
  case "claude-sdk": {
179
+ // The Claude Agent SDK can authenticate through multiple paths that
180
+ // `claude auth status` does not see:
181
+ // 1. ANTHROPIC_API_KEY env var (bypasses CLI entirely)
182
+ // 2. An active Claude Code session (IDE-initiated, not via `auth login`)
183
+ // 3. Native binary session cookies
184
+ // Prior to v4.4.6 this check hard-failed on `loggedIn: false` even when
185
+ // the engine ran fine — confusing users whose bot was actually working.
186
+ if (process.env.ANTHROPIC_API_KEY) {
187
+ return { ok: true, detail: "Claude SDK via ANTHROPIC_API_KEY env var" };
188
+ }
189
+
167
190
  // Find claude binary — check PATH and common locations
168
191
  let claudeBin = null;
169
192
  try {
@@ -180,10 +203,13 @@ async function validateProviderKey(providerKey, apiKey) {
180
203
  }
181
204
  }
182
205
  if (!claudeBin) {
183
- return { ok: false, error: "Claude CLI not installed" };
206
+ return { ok: false, error: "Claude CLI not installed. Run: curl -fsSL https://claude.ai/install.sh | sh" };
184
207
  }
208
+
209
+ // Check `claude auth status`. On mismatch, we DON'T hard-fail:
210
+ // we return a warning so the Agent SDK still gets a chance to run
211
+ // (it has independent auth paths the CLI doesn't know about).
185
212
  try {
186
- // Use `auth status` instead of `-p "ping"` — faster and doesn't require a full query
187
213
  const authJson = execSync(`${claudeBin} auth status`, {
188
214
  stdio: "pipe", timeout: 10000, encoding: "utf-8",
189
215
  });
@@ -191,7 +217,11 @@ async function validateProviderKey(providerKey, apiKey) {
191
217
  if (authData.loggedIn) {
192
218
  return { ok: true, detail: `Claude SDK authenticated (${authData.authMethod || "OK"})` };
193
219
  }
194
- return { ok: false, error: "Claude CLI not authenticated. Run: claude auth login" };
220
+ return {
221
+ ok: true,
222
+ warning: "Claude CLI reports not logged in, but the Agent SDK may still work via session/env-var. If the bot fails to respond, run: claude auth login",
223
+ detail: "Claude CLI present (not logged in via `auth status` — Agent SDK may still work)",
224
+ };
195
225
  } catch (err) {
196
226
  const msg = err.stdout?.toString() || err.stderr?.toString() || err.message || "";
197
227
  // Try parsing JSON from stdout (auth status exits with code 1 when not logged in)
@@ -201,7 +231,11 @@ async function validateProviderKey(providerKey, apiKey) {
201
231
  return { ok: true, detail: `Claude SDK authenticated (${authData.authMethod || "OK"})` };
202
232
  }
203
233
  } catch {}
204
- return { ok: false, error: "Claude CLI not authenticated. Run: claude auth login" };
234
+ return {
235
+ ok: true,
236
+ warning: "Claude CLI `auth status` failed. Agent SDK may still work via session/env-var. If the bot fails to respond, run: claude auth login",
237
+ detail: "Claude CLI present (auth status check failed — Agent SDK may still work)",
238
+ };
205
239
  }
206
240
  }
207
241
 
@@ -298,9 +332,148 @@ async function runPostSetupValidation(providerKey, apiKey, botToken, webPort) {
298
332
  return allGood;
299
333
  }
300
334
 
335
+ // ── Setup: Argument Parsing ─────────────────────────────────────────────────
336
+
337
+ /**
338
+ * Parse `alvin-bot setup --non-interactive` style CLI args.
339
+ * Returns a flat object with the values found (or null for unset fields).
340
+ *
341
+ * Supports both `--flag=value` and `--flag value` syntax.
342
+ */
343
+ function parseSetupArgs(argv) {
344
+ const args = {};
345
+ const flags = new Set(["--non-interactive", "-y", "--yes", "--skip-validation"]);
346
+ const valueFlags = [
347
+ "--bot-token", "--allowed-users", "--primary-provider",
348
+ "--groq-key", "--google-key", "--openai-key", "--nvidia-key",
349
+ "--openrouter-key", "--anthropic-key",
350
+ "--fallback-providers", "--web-password", "--platform",
351
+ ];
352
+ for (let i = 3; i < argv.length; i++) {
353
+ const a = argv[i];
354
+ if (flags.has(a)) {
355
+ args[a.replace(/^-+/, "")] = true;
356
+ continue;
357
+ }
358
+ for (const vf of valueFlags) {
359
+ if (a === vf) {
360
+ args[vf.replace(/^-+/, "")] = argv[++i];
361
+ break;
362
+ }
363
+ if (a.startsWith(vf + "=")) {
364
+ args[vf.replace(/^-+/, "")] = a.slice(vf.length + 1);
365
+ break;
366
+ }
367
+ }
368
+ }
369
+ return args;
370
+ }
371
+
372
+ /**
373
+ * Non-interactive setup path for CI/Docker/automation.
374
+ *
375
+ * Writes ~/.alvin-bot/.env directly from CLI args, with no prompts.
376
+ * The bot's own `ensureDataDirs()` + `seedDefaults()` handle the rest
377
+ * on the next `alvin-bot start`.
378
+ *
379
+ * Usage:
380
+ * alvin-bot setup --non-interactive \
381
+ * --bot-token=123:AAE... \
382
+ * --allowed-users=12345,67890 \
383
+ * --primary-provider=claude-sdk \
384
+ * --groq-key=gsk_... \
385
+ * --fallback-providers=groq,ollama
386
+ */
387
+ async function setupNonInteractive(args) {
388
+ console.log("šŸ¤– Alvin Bot — Non-interactive setup\n");
389
+
390
+ // Ensure DATA_DIR exists (will also be recreated on bot start, but we
391
+ // need it now to write the .env).
392
+ if (!existsSync(DATA_DIR)) {
393
+ mkdirSync(DATA_DIR, { recursive: true });
394
+ console.log(`āœ“ Created ${DATA_DIR}`);
395
+ }
396
+
397
+ const envFile = resolve(DATA_DIR, ".env");
398
+ if (existsSync(envFile)) {
399
+ console.log(`āš ļø ${envFile} already exists — refusing to overwrite.`);
400
+ console.log(` Delete it manually first, or edit it directly.`);
401
+ process.exit(1);
402
+ }
403
+
404
+ // Validate required fields
405
+ const token = args["bot-token"];
406
+ if (token && !/^\d+:[A-Za-z0-9_-]+$/.test(token)) {
407
+ console.log(`āŒ --bot-token format invalid. Expected: 123456789:ABCdef...`);
408
+ process.exit(1);
409
+ }
410
+ const users = args["allowed-users"];
411
+ if (users) {
412
+ const ids = users.split(",").map(s => s.trim());
413
+ const bad = ids.filter(id => !/^\d+$/.test(id));
414
+ if (bad.length > 0) {
415
+ console.log(`āŒ --allowed-users must be comma-separated numeric IDs. Got invalid: ${bad.join(", ")}`);
416
+ process.exit(1);
417
+ }
418
+ }
419
+
420
+ // Optional: validate token with Telegram API unless --skip-validation
421
+ if (token && !args["skip-validation"]) {
422
+ const tgResult = await validateTelegramToken(token);
423
+ if (tgResult.ok) {
424
+ console.log(`āœ“ Telegram: ${tgResult.botName}`);
425
+ } else {
426
+ console.log(`āš ļø Telegram token validation failed: ${tgResult.error}`);
427
+ console.log(` Writing .env anyway. Pass --skip-validation to suppress this warning.`);
428
+ }
429
+ }
430
+
431
+ const primary = args["primary-provider"] || "groq";
432
+ const fallbacks = args["fallback-providers"] || "";
433
+ const platform = args["platform"] || "telegram";
434
+
435
+ const envLines = [
436
+ "# === Telegram ===",
437
+ `BOT_TOKEN=${token || ""}`,
438
+ `ALLOWED_USERS=${users || ""}`,
439
+ "",
440
+ "# === AI Provider ===",
441
+ `PRIMARY_PROVIDER=${primary}`,
442
+ `FALLBACK_PROVIDERS=${fallbacks}`,
443
+ "",
444
+ "# === API Keys ===",
445
+ ];
446
+ if (args["groq-key"]) envLines.push(`GROQ_API_KEY=${args["groq-key"]}`);
447
+ if (args["google-key"]) envLines.push(`GOOGLE_API_KEY=${args["google-key"]}`);
448
+ if (args["openai-key"]) envLines.push(`OPENAI_API_KEY=${args["openai-key"]}`);
449
+ if (args["nvidia-key"]) envLines.push(`NVIDIA_API_KEY=${args["nvidia-key"]}`);
450
+ if (args["openrouter-key"]) envLines.push(`OPENROUTER_API_KEY=${args["openrouter-key"]}`);
451
+ if (args["anthropic-key"]) envLines.push(`ANTHROPIC_API_KEY=${args["anthropic-key"]}`);
452
+ envLines.push("");
453
+ envLines.push("# === Agent ===");
454
+ envLines.push("WORKING_DIR=" + homedir());
455
+ envLines.push("MAX_BUDGET_USD=5.0");
456
+ envLines.push("WEB_PORT=3100");
457
+ if (args["web-password"]) envLines.push(`WEB_PASSWORD=${args["web-password"]}`);
458
+ envLines.push("");
459
+ envLines.push("# === Platforms ===");
460
+ envLines.push(`WHATSAPP_ENABLED=${platform === "whatsapp" ? "true" : "false"}`);
461
+
462
+ writeFileSync(envFile, envLines.join("\n") + "\n", { mode: 0o600 });
463
+ console.log(`āœ“ Wrote ${envFile} (mode 0600)`);
464
+ console.log(`\nāœ… Setup complete. Start the bot with: alvin-bot start\n`);
465
+ }
466
+
301
467
  // ── Setup Wizard ────────────────────────────────────────────────────────────
302
468
 
303
469
  async function setup() {
470
+ // Non-interactive path for CI/automation/scripted installs.
471
+ const args = parseSetupArgs(process.argv);
472
+ if (args["non-interactive"] || args["yes"] || args["y"]) {
473
+ await setupNonInteractive(args);
474
+ return;
475
+ }
476
+
304
477
  console.log(LOGO);
305
478
 
306
479
  // ── Prerequisites
@@ -318,7 +491,7 @@ async function setup() {
318
491
 
319
492
  if (!hasNode) {
320
493
  console.log(`\nāŒ ${t("setup.nodeRequired")}`);
321
- rl.close();
494
+ closeRL();
322
495
  return;
323
496
  }
324
497
 
@@ -337,7 +510,7 @@ async function setup() {
337
510
  console.log(` Get one from @BotFather on Telegram.\n`);
338
511
  const proceed = (await ask(` Continue anyway? (y/n): `)).trim().toLowerCase();
339
512
  if (proceed !== "y" && proceed !== "yes" && proceed !== "j" && proceed !== "ja") {
340
- rl.close();
513
+ closeRL();
341
514
  return;
342
515
  }
343
516
  }
@@ -381,7 +554,7 @@ async function setup() {
381
554
  console.log(` Send /start to @userinfobot on Telegram to get your numeric ID.\n`);
382
555
  const proceed = (await ask(` Continue anyway? (y/n): `)).trim().toLowerCase();
383
556
  if (proceed !== "y" && proceed !== "yes" && proceed !== "j" && proceed !== "ja") {
384
- rl.close();
557
+ closeRL();
385
558
  return;
386
559
  }
387
560
  }
@@ -759,7 +932,7 @@ async function setup() {
759
932
  console.log(`\n āŒ ${t("setup.buildFailed")}`);
760
933
  console.log(` The bot cannot start without a successful build.`);
761
934
  console.log(` Try running 'npm run build' manually to see the error.\n`);
762
- rl.close();
935
+ closeRL();
763
936
  return;
764
937
  }
765
938
  }
@@ -804,7 +977,7 @@ Bot commands:
804
977
  ${t("setup.haveFun")}
805
978
  `);
806
979
 
807
- rl.close();
980
+ closeRL();
808
981
  }
809
982
 
810
983
  // ── Doctor ──────────────────────────────────────────────────────────────────
@@ -866,7 +1039,10 @@ async function doctor() {
866
1039
 
867
1040
  console.log(` Validating ${primary}...`);
868
1041
  const result = await validateProviderKey(primary, key);
869
- if (result.ok) {
1042
+ if (result.ok && result.warning) {
1043
+ console.log(` āš ļø ${primary} — ${result.detail}`);
1044
+ console.log(` ${result.warning}`);
1045
+ } else if (result.ok) {
870
1046
  console.log(` āœ… ${primary} — ${result.detail}`);
871
1047
  } else {
872
1048
  console.log(` āŒ ${primary} — ${result.error}`);
@@ -1,11 +1,19 @@
1
1
  import fs from "fs";
2
2
  import { execSync } from "child_process";
3
- import { resolve } from "path";
4
- import { DATA_DIR } from "../paths.js";
3
+ import dotenv from "dotenv";
4
+ import { DATA_DIR, ENV_FILE } from "../paths.js";
5
5
  export function runAudit() {
6
6
  const checks = [];
7
+ // `alvin-bot audit` runs in its own process (outside the main bot) and
8
+ // does NOT go through src/config.ts, so process.env is empty by default.
9
+ // We must load the .env ourselves or ALLOWED_USERS/WEB_PASSWORD checks
10
+ // will always report as "not set" — which silently contradicts the bot's
11
+ // actual runtime state (a bug up to v4.4.5).
12
+ if (fs.existsSync(ENV_FILE)) {
13
+ dotenv.config({ path: ENV_FILE });
14
+ }
7
15
  // 1. .env file permissions
8
- const envFile = resolve(DATA_DIR, ".env");
16
+ const envFile = ENV_FILE;
9
17
  if (fs.existsSync(envFile)) {
10
18
  const stat = fs.statSync(envFile);
11
19
  const mode = (stat.mode & 0o777).toString(8);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "alvin-bot",
3
- "version": "4.4.5",
3
+ "version": "4.4.6",
4
4
  "description": "Alvin Bot — Your personal AI agent on Telegram, WhatsApp, Discord, Signal, and Web.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",