seoanything-cli 2.4.1 → 2.4.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/README.md CHANGED
@@ -36,6 +36,7 @@ npx seoanything mcp # stdio MCP server (Node ≥ 22.18)
36
36
  | `audit <path\|url> [--cloud]` | v1 local auditor; `--cloud` runs the cloud audit and saves history |
37
37
  | `mcp` | Local stdio MCP server exposing cloud tools + `local_audit`, `local_llms_txt`, `local_sitemap`, `local_install_skills` |
38
38
  | `config get\|set <key> <value>` | `server`, `geo`, `hl`, `model` defaults |
39
+ | `ai set claude\|openai\|gemini\|custom` · `ai` · `ai test` · `ai use` · `ai remove` | Your own AI provider key, kept on this computer and used through `connect` (see below) |
39
40
 
40
41
  Global flags: `--json` (machine output, no colours), `--server <url>`, `--quiet`, `--no-color`.
41
42
  Exit codes: `0` ok · `1` error · `2` usage · `3` not logged in · `4` quota / rate limited · `5` upstream unavailable.
@@ -43,7 +44,7 @@ Exit codes: `0` ok · `1` error · `2` usage · `3` not logged in · `4` quota /
43
44
  ## Credentials
44
45
 
45
46
  Saved to `$XDG_CONFIG_HOME/seoanything/config.json` (`~/.config/seoanything/`, `%APPDATA%\seoanything\` on Windows) with mode `0600`.
46
- Environment overrides for CI: `SEOANYTHING_SERVER`, `SEOANYTHING_API_KEY` (an `sa_…` key from Settings → API keys), `SEOANYTHING_TOKEN`.
47
+ Environment overrides for CI: `SEOANYTHING_SERVER`, `SEOANYTHING_API_KEY` (an `sa_…` key from Settings → API keys), `SEOANYTHING_TOKEN`, and for your own AI key `SEOANYTHING_AI_PROVIDER`, `SEOANYTHING_AI_KEY`, `SEOANYTHING_AI_MODEL`, `SEOANYTHING_AI_BASE_URL` (see below).
47
48
 
48
49
  ## Your own AI CLI (`connect`)
49
50
 
@@ -51,7 +52,7 @@ Environment overrides for CI: `SEOANYTHING_SERVER`, `SEOANYTHING_API_KEY` (an `s
51
52
  seoanything connect
52
53
  ```
53
54
 
54
- Links this computer to your SEOAnything account. The web app's chat and blog studio can then run on the AI CLIs installed here (Claude Code `claude`, Codex `codex`, Antigravity `agy`) with their own logins, instead of the shared cloud models and their daily limits. Pick the default engine under Settings, "your cli". Keep the window open; close it (Ctrl+C) and the app falls back to the cloud models. The cloud sends prompts and receives text; no credential file is read or sent, tools stay off, and each call runs in an empty temporary folder. Needs Node 22 or newer. Disconnect a computer from Settings at any time.
55
+ Links this computer to your SEOAnything account. The web app's chat and blog studio can then run on the AI CLIs installed here (Claude Code `claude`, Codex `codex`, Antigravity `agy`) with their own logins, or on your own API key kept here (`seoanything ai set`, below), instead of the shared cloud models and their daily limits. Pick the default engine under Settings, "your cli". Keep the window open; close it (Ctrl+C) and the app falls back to the cloud models. The cloud sends prompts and receives text; no credential file is read or sent, tools stay off, and each call runs in an empty temporary folder. Needs Node 22 or newer. Disconnect a computer from Settings at any time.
55
56
 
56
57
  ### Without a terminal: a setup prompt for your AI app
57
58
 
@@ -63,6 +64,30 @@ npx -y seoanything-cli@latest connect --code <setup code> --background
63
64
 
64
65
  The setup code works once and lapses after 10 minutes. It is traded for a token that can only open this computer's link (not your account), saved in the config file. `--background` keeps the connector running after the AI app's command finishes (log: `connect.log` next to the config file). "disconnect" in Settings stops it and revokes the token; from then on the computer needs a fresh setup prompt. "look for CLIs" in Settings picks up a CLI you installed after linking, without a restart, and refreshes each CLI's model list (`codex debug models`, `agy models`, and Claude Code's fable/opus/sonnet/haiku aliases) so you can pick a model per CLI in Settings or in the chat's model menu.
65
66
 
67
+ ### Your own AI key (`ai`)
68
+
69
+ ```bash
70
+ seoanything ai set claude # or openai, gemini; asks for the key without showing it
71
+ seoanything ai set custom --base-url https://api.groq.com/openai/v1 --model llama-3.3-70b-versatile
72
+ seoanything ai test # one short question to the provider, from this computer
73
+ seoanything connect --background # offers the key to the web app as "API key on your computer"
74
+ seoanything ai use # make it your default engine (or pick it in Settings › CLI and AI engines)
75
+ ```
76
+
77
+ Keeps your own Claude (Anthropic), ChatGPT (OpenAI), Gemini or OpenAI-compatible API key on this computer and uses it for your SEOAnything chats and blog posts. The key is checked by listing the provider's models (the newest is picked unless you give `--model`), saved in the config file (mode `0600`) and never sent to SEOAnything: while `connect` runs, the cloud sends a prompt, this computer calls the provider and sends back only the text. Answers are billed to your account with that provider, and calls on your own key get the raised daily limits. The key is never taken as an argument (it would stay in your shell history): it is asked for, read from a pipe, or taken from `SEOANYTHING_AI_KEY`. A custom API needs `--base-url` (https, or http only to this computer, for a local model such as Ollama) and `--model`; `--no-check` skips the model-list check for a server that has none.
78
+
79
+ | Command | What it does |
80
+ |---|---|
81
+ | `ai set claude\|openai\|gemini\|custom [--model m] [--base-url u] [--no-check]` | Check and save the key, provider and model |
82
+ | `ai` · `ai show` | Provider, model, address and the key's last four characters, and whether they come from the environment or the config file |
83
+ | `ai test` | Ask the provider for a one-word reply |
84
+ | `ai use` | Make this computer's key your account's default engine (it answers while `connect` runs here; otherwise the cloud does) |
85
+ | `ai remove` | Forget the saved key |
86
+
87
+ Environment variables win over the config file, for CI or a one-off: `SEOANYTHING_AI_PROVIDER` (`claude`, `openai`, `gemini` or `custom`), `SEOANYTHING_AI_KEY`, `SEOANYTHING_AI_MODEL`, `SEOANYTHING_AI_BASE_URL`. A key saved for one provider is never used for another. `connect` picks up a key set while it runs when you click "look for CLIs" in Settings.
88
+
89
+ To keep a key in your account instead (it then works without this computer), add it in the web app under Settings › CLI and AI engines › Your API keys; it is stored encrypted and only its last four characters are shown.
90
+
66
91
  ### Make videos on this computer (`--video`)
67
92
 
68
93
  ```bash
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "seoanything-cli",
3
- "version": "2.4.1",
4
- "description": "SEOAnything CLI: trends, keywords, SEO chat, blog studio, audits, a local MCP server, and `connect` to run the web app on the Claude/Codex/Gemini/Antigravity CLI on your own computer. https://www.seoanything.dev",
3
+ "version": "2.4.2",
4
+ "description": "SEOAnything CLI: trends, keywords, SEO chat, blog studio, audits, a local MCP server, and `connect` to run the web app on the Claude/Codex/Antigravity CLI or your own Claude, ChatGPT, Gemini or OpenAI-compatible API key on your own computer. https://www.seoanything.dev",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "bin": {
@@ -18,12 +18,6 @@
18
18
  "engines": {
19
19
  "node": ">=18"
20
20
  },
21
- "scripts": {
22
- "test": "vitest run",
23
- "typecheck": "echo skip",
24
- "build": "esbuild ../tools/src/index.ts --bundle --platform=node --format=esm --target=node18 --outfile=dist/tools.mjs --external:zod --external:@modelcontextprotocol/sdk/*",
25
- "prepack": "pnpm run build"
26
- },
27
21
  "optionalDependencies": {
28
22
  "@alkalisummer/google-trends-js": "0.3.7",
29
23
  "@modelcontextprotocol/sdk": "1.32.2",
@@ -54,5 +48,10 @@
54
48
  ],
55
49
  "publishConfig": {
56
50
  "access": "public"
51
+ },
52
+ "scripts": {
53
+ "test": "vitest run",
54
+ "typecheck": "echo skip",
55
+ "build": "esbuild ../tools/src/index.ts --bundle --platform=node --format=esm --target=node18 --outfile=dist/tools.mjs --external:zod --external:@modelcontextprotocol/sdk/*"
57
56
  }
58
- }
57
+ }
package/src/ai.js ADDED
@@ -0,0 +1,112 @@
1
+ // `seoanything ai`: your own AI provider key on this computer (Claude, ChatGPT, Gemini or any OpenAI-compatible API).
2
+ // Kept in the config file (mode 0600) or given by environment variables, and never sent to SEOAnything: `connect`
3
+ // offers it to the web app as the "api" engine, so the cloud sends a prompt, this computer calls the provider with the
4
+ // key and sends back only the text. Zero dependencies (fetch).
5
+ import { loadConfig } from "./config.js";
6
+
7
+ export const PROVIDERS = {
8
+ anthropic: { label: "Claude", base: "https://api.anthropic.com/v1", keysUrl: "https://platform.claude.com/settings/keys" },
9
+ openai: { label: "ChatGPT", base: "https://api.openai.com/v1", keysUrl: "https://platform.openai.com/api-keys" },
10
+ gemini: { label: "Gemini", base: "https://generativelanguage.googleapis.com/v1beta/openai", keysUrl: "https://aistudio.google.com/apikey" },
11
+ custom: { label: "Custom API", base: null, keysUrl: null },
12
+ };
13
+ const ALIASES = { claude: "anthropic", chatgpt: "openai" };
14
+ const ANTHROPIC_VERSION = "2023-06-01";
15
+ const HEADROOM = 3000; // reasoning models spend hidden thinking out of the same output budget
16
+ export const TEST_PROMPT = "Reply with the single word: ready";
17
+
18
+ /** "claude", "anthropic", "chatgpt", "openai", "gemini" or "custom" as a provider id; null for anything else. */
19
+ export const providerOf = (p) => { const id = ALIASES[p] ?? p; return Object.hasOwn(PROVIDERS, id) ? id : null; };
20
+ export const hint = (key) => (key ? `…${key.slice(-4)}` : "");
21
+
22
+ /**
23
+ * The provider set up here: SEOANYTHING_AI_PROVIDER, _KEY, _MODEL and _BASE_URL over the config file's `ai`. The file's
24
+ * key, model and address count only for the provider they were saved for, so a key never goes to another provider.
25
+ * Null when no provider is set.
26
+ */
27
+ export function resolveAi(env = process.env, cfg = loadConfig()) {
28
+ const file = cfg.ai ?? {};
29
+ const provider = providerOf(env.SEOANYTHING_AI_PROVIDER || file.provider || "");
30
+ if (!provider) return null;
31
+ const own = provider === file.provider ? file : {};
32
+ return {
33
+ provider, label: PROVIDERS[provider].label,
34
+ key: env.SEOANYTHING_AI_KEY || own.key || "",
35
+ model: env.SEOANYTHING_AI_MODEL || own.model || "",
36
+ baseUrl: (env.SEOANYTHING_AI_BASE_URL || own.baseUrl || "").replace(/\/+$/, ""),
37
+ from: env.SEOANYTHING_AI_KEY ? "environment" : "config file",
38
+ };
39
+ }
40
+
41
+ /** A custom base address: https, or http only to this computer (a local model such as Ollama). Returns it without a closing slash. */
42
+ export function checkBase(base) {
43
+ let u;
44
+ try { u = new URL(String(base ?? "").trim()); } catch { throw new Error("that is not a web address. it should look like https://api.example.com/v1"); }
45
+ if (u.username || u.password || u.search || u.hash) throw new Error("give the address alone: no user name, password, ? or # in it.");
46
+ const local = ["localhost", "127.0.0.1", "[::1]"].includes(u.hostname);
47
+ if (u.protocol !== "https:" && !(u.protocol === "http:" && local)) throw new Error("the address must start with https:// (http:// only for a model on this computer).");
48
+ return u.href.replace(/\/+$/, "");
49
+ }
50
+
51
+ const baseOf = (ai) => (ai.provider === "custom" ? checkBase(ai.baseUrl) : PROVIDERS[ai.provider].base);
52
+ const headersOf = (ai) => ({ "content-type": "application/json", ...(ai.provider === "anthropic" ? { "x-api-key": ai.key, "anthropic-version": ANTHROPIC_VERSION } : ai.key ? { authorization: `Bearer ${ai.key}` } : {}) });
53
+
54
+ /** What went wrong, in words to act on. Never includes the key. */
55
+ export function problem(ai, status, j) {
56
+ const e = Array.isArray(j) ? j[0]?.error : j?.error;
57
+ let said = String((typeof e === "string" ? e : e?.message) ?? j?.message ?? "").slice(0, 240);
58
+ if (ai.key) said = said.split(ai.key).join("…");
59
+ if (status === 401 || status === 403 || (status === 400 && /api.?key/i.test(said))) return `${ai.label} refused the API key. set a fresh one with \`seoanything ai set ${ai.provider}\`.`;
60
+ if (status === 404) return `${ai.label} doesn't know that model or address. ${said}`.trim();
61
+ if (status === 429) return `${ai.label} says this key is over its rate limit or out of credit. ${said}`.trim();
62
+ if (status >= 500) return `${ai.label} is overloaded or had an error (${status}). try again in a minute.`;
63
+ return `${ai.label} refused the request (${status}): ${said || "no details"}`;
64
+ }
65
+
66
+ async function call(ai, path, init, { fetchImpl = fetch, timeoutMs = 30_000, signal } = {}) {
67
+ let res;
68
+ const sig = signal ? AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs);
69
+ // no redirects: a key must never follow one to another host
70
+ try { res = await fetchImpl(`${baseOf(ai)}/${path}`, { ...init, headers: headersOf(ai), redirect: "error", signal: sig }); }
71
+ catch (e) { throw new Error(e?.name === "TimeoutError" ? `${ai.label} didn't answer in ${Math.round(timeoutMs / 1000)} s.` : signal?.aborted ? "the call was cancelled." : `cannot reach ${ai.label} (${e?.cause?.code ?? e?.message ?? "network error"}).`); }
72
+ const j = await res.json().catch(() => null);
73
+ if (!res.ok) throw new Error(problem(ai, res.status, j));
74
+ return j;
75
+ }
76
+
77
+ /** The chat models the key can use, newest first where the provider says: [{ id, label }]. Also how a key is checked. */
78
+ export async function listModels(ai, o = {}) {
79
+ const j = await call(ai, ai.provider === "anthropic" ? "models?limit=100" : "models", { method: "GET" }, o);
80
+ const rows = (j?.data ?? j?.models ?? []).filter((m) => m && typeof (m.id ?? m.name) === "string");
81
+ if (ai.provider === "anthropic") return rows.filter((m) => m.id.startsWith("claude")).map((m) => ({ id: m.id, label: m.display_name ?? m.id }));
82
+ if (ai.provider === "custom") return [...new Set(rows.map((m) => m.id ?? m.name))].map((id) => ({ id, label: id }));
83
+ const family = ai.provider === "openai" ? /^(gpt-|o\d|chatgpt)/ : /^gemini/;
84
+ const skip = /embed|audio|realtime|image|tts|transcri|whisper|dall-e|moderation|search|veo|imagen|live|aqa|computer-use|codex/i;
85
+ return [...new Set(rows.map((m) => ({ id: m.id.replace(/^models\//, ""), t: m.created ?? 0 })).filter((m) => family.test(m.id) && !skip.test(m.id)).sort((a, b) => b.t - a.t || b.id.localeCompare(a.id)).map((m) => m.id))].map((id) => ({ id, label: id }));
86
+ }
87
+
88
+ /** The request body for one prompt. No temperature: newer Claude and OpenAI reasoning models refuse anything but their default. */
89
+ export function bodyFor(ai, { system, prompt, model, maxTokens = 4096 }) {
90
+ if (ai.provider === "anthropic") return { model, max_tokens: maxTokens + HEADROOM, ...(system ? { system } : {}), messages: [{ role: "user", content: prompt }] };
91
+ return { model, messages: [...(system ? [{ role: "system", content: system }] : []), { role: "user", content: prompt }], [ai.provider === "openai" ? "max_completion_tokens" : "max_tokens"]: maxTokens + HEADROOM };
92
+ }
93
+
94
+ /** One prompt to the provider: { text, model, tokensIn?, tokensOut? }. Throws an Error whose message never holds the key. */
95
+ export async function ask(ai, { system, prompt, model, maxTokens, timeoutMs = 180_000, signal, fetchImpl } = {}) {
96
+ const m = model || ai.model;
97
+ if (!ai.key && ai.provider !== "custom") throw new Error(`no ${ai.label} key is set. run \`seoanything ai set ${ai.provider}\`.`);
98
+ if (!m) throw new Error("no model is set. run `seoanything ai set` with --model.");
99
+ const j = await call(ai, ai.provider === "anthropic" ? "messages" : "chat/completions", { method: "POST", body: JSON.stringify(bodyFor(ai, { system, prompt, model: m, maxTokens })) }, { fetchImpl, timeoutMs, signal });
100
+ let text = "", tokensIn, tokensOut;
101
+ if (ai.provider === "anthropic") {
102
+ if (j?.stop_reason === "refusal") throw new Error(`Claude declined this request${j.stop_details?.category ? ` (${j.stop_details.category})` : ""}.`);
103
+ text = (j?.content ?? []).filter((b) => b?.type === "text").map((b) => b.text ?? "").join("");
104
+ tokensIn = j?.usage?.input_tokens; tokensOut = j?.usage?.output_tokens;
105
+ } else {
106
+ const c = j?.choices?.[0]?.message?.content;
107
+ text = typeof c === "string" ? c : Array.isArray(c) ? c.map((x) => x?.text ?? "").join("") : "";
108
+ tokensIn = j?.usage?.prompt_tokens; tokensOut = j?.usage?.completion_tokens;
109
+ }
110
+ if (!text.trim()) throw new Error(`${ai.label} returned no text.`);
111
+ return { text: text.trim(), model: m, tokensIn, tokensOut };
112
+ }
package/src/ai.test.js ADDED
@@ -0,0 +1,113 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
5
+ import { ask, bodyFor, checkBase, hint, listModels, problem, providerOf, resolveAi } from "./ai.js";
6
+ import { main } from "./cli.js";
7
+ import { loadConfig, saveConfig } from "./config.js";
8
+ import { detect, runJob } from "./connect.js";
9
+
10
+ const KEY = "sk-ant-api03-secret-claude-WXYZ";
11
+ const claude = { provider: "anthropic", label: "Claude", key: KEY, model: "claude-opus-5-5", baseUrl: "" };
12
+ const json = (body, status = 200) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
13
+
14
+ let dir;
15
+ beforeEach(() => { dir = fs.mkdtempSync(path.join(os.tmpdir(), "seoany-ai-")); process.env.XDG_CONFIG_HOME = dir; });
16
+ afterEach(() => { fs.rmSync(dir, { recursive: true, force: true }); delete process.env.XDG_CONFIG_HOME; delete process.env.SEOANYTHING_AI_KEY; vi.unstubAllGlobals(); });
17
+
18
+ describe("the key set up on this computer", () => {
19
+ it("takes the environment over the config file, and the file's key only for the provider it was saved for", () => {
20
+ const cfg = { ai: { provider: "anthropic", key: KEY, model: "claude-opus-5-5" } };
21
+ expect(resolveAi({}, cfg)).toMatchObject({ provider: "anthropic", label: "Claude", key: KEY, model: "claude-opus-5-5", from: "config file" });
22
+ expect(resolveAi({ SEOANYTHING_AI_MODEL: "claude-sonnet-5-5" }, cfg).model).toBe("claude-sonnet-5-5");
23
+ expect(resolveAi({ SEOANYTHING_AI_PROVIDER: "openai" }, cfg)).toMatchObject({ provider: "openai", key: "", model: "" }); // Claude's key never goes to OpenAI
24
+ expect(resolveAi({ SEOANYTHING_AI_PROVIDER: "chatgpt", SEOANYTHING_AI_KEY: "sk-env", SEOANYTHING_AI_MODEL: "gpt-x" }, {})).toMatchObject({ provider: "openai", key: "sk-env", from: "environment" });
25
+ expect(resolveAi({}, {})).toBeNull();
26
+ expect([providerOf("claude"), providerOf("gemini"), providerOf("toString"), providerOf("nope")]).toEqual(["anthropic", "gemini", null, null]);
27
+ expect(hint(KEY)).toBe("…WXYZ");
28
+ });
29
+
30
+ it("takes a custom address on https, or http only to this computer, and alone", () => {
31
+ expect(checkBase("https://api.groq.com/openai/v1/")).toBe("https://api.groq.com/openai/v1");
32
+ expect(checkBase("http://localhost:11434/v1")).toBe("http://localhost:11434/v1");
33
+ for (const bad of ["http://api.example.com/v1", "https://u:p@api.example.com/v1", "https://api.example.com/v1?x=1", "ftp://x/v1", "nope"]) expect(() => checkBase(bad)).toThrow();
34
+ });
35
+ });
36
+
37
+ describe("calling the provider", () => {
38
+ it("sends Claude its own shape with the key in x-api-key, never follows a redirect, and reads the text", async () => {
39
+ const calls = [];
40
+ const fetchImpl = async (url, init) => { calls.push({ url, init }); return json({ stop_reason: "end_turn", content: [{ type: "text", text: " ready " }], usage: { input_tokens: 5, output_tokens: 1 } }); };
41
+ expect(await ask(claude, { system: "be brief", prompt: "hi", fetchImpl })).toEqual({ text: "ready", model: "claude-opus-5-5", tokensIn: 5, tokensOut: 1 });
42
+ const { url, init } = calls[0];
43
+ expect([url, init.headers["x-api-key"], init.redirect]).toEqual(["https://api.anthropic.com/v1/messages", KEY, "error"]);
44
+ expect(JSON.parse(init.body)).toEqual({ model: "claude-opus-5-5", max_tokens: 4096 + 3000, system: "be brief", messages: [{ role: "user", content: "hi" }] });
45
+ });
46
+
47
+ it("sends OpenAI-shaped providers chat completions with a bearer key", async () => {
48
+ expect(bodyFor({ provider: "openai" }, { prompt: "p", model: "gpt-x", maxTokens: 10 })).toEqual({ model: "gpt-x", messages: [{ role: "user", content: "p" }], max_completion_tokens: 3010 });
49
+ expect(bodyFor({ provider: "custom" }, { system: "s", prompt: "p", model: "m", maxTokens: 10 }).max_tokens).toBe(3010);
50
+ let seen;
51
+ const r = await ask({ provider: "custom", label: "Custom API", key: "gsk_x", model: "llama", baseUrl: "https://api.groq.com/openai/v1" }, { prompt: "hi", fetchImpl: async (url, init) => { seen = { url, auth: init.headers.authorization }; return json({ choices: [{ message: { content: "ok" } }] }); } });
52
+ expect([r.text, seen]).toEqual(["ok", { url: "https://api.groq.com/openai/v1/chat/completions", auth: "Bearer gsk_x" }]);
53
+ });
54
+
55
+ it("says what went wrong without the key, and a refusal is not an answer", async () => {
56
+ expect(problem(claude, 401, { error: { message: `bad key ${KEY}` } })).toContain("seoanything ai set anthropic");
57
+ expect(problem(claude, 429, { error: { message: `over quota for ${KEY}` } })).not.toContain(KEY);
58
+ await expect(ask(claude, { prompt: "x", fetchImpl: async () => json({ error: { message: `invalid ${KEY}` } }, 401) })).rejects.toThrow(/refused the API key/);
59
+ await expect(ask(claude, { prompt: "x", fetchImpl: async () => json({ stop_reason: "refusal", stop_details: { category: "cyber" }, content: [] }) })).rejects.toThrow("Claude declined this request (cyber).");
60
+ await expect(ask({ ...claude, model: "" }, { prompt: "x" })).rejects.toThrow(/no model/);
61
+ });
62
+
63
+ it("lists a key's chat models, newest first where the provider says", async () => {
64
+ const fetchImpl = async () => json({ data: [{ id: "gpt-4o", created: 1 }, { id: "text-embedding-3", created: 3 }, { id: "gpt-5", created: 2 }, { id: "whisper-1", created: 4 }] });
65
+ expect(await listModels({ provider: "openai", label: "ChatGPT", key: "k" }, { fetchImpl })).toEqual([{ id: "gpt-5", label: "gpt-5" }, { id: "gpt-4o", label: "gpt-4o" }]);
66
+ });
67
+ });
68
+
69
+ describe("connect offers the key as the api engine", () => {
70
+ it("lists it when a key and model are set, and runs a job on it with the model the app chose", async () => {
71
+ const found = await detect({ PATH: "" }, undefined, claude);
72
+ expect(found).toEqual([{ kind: "api", path: "", version: "Claude · claude-opus-5-5", models: [{ id: "claude-opus-5-5", label: "Claude · claude-opus-5-5" }] }]);
73
+ expect(await detect({ PATH: "" }, undefined, null)).toEqual([]);
74
+ let body;
75
+ const r = await runJob({ id: "j", kind: "api", prompt: "write", system: "s", model: "claude-sonnet-5-5", timeout: 60 }, { binaries: {}, ai: claude, fetchImpl: async (_u, init) => { body = JSON.parse(init.body); return json({ content: [{ type: "text", text: "done" }] }); } });
76
+ expect([r.text, body.model, body.system]).toEqual(["done", "claude-sonnet-5-5", "s"]);
77
+ await expect(runJob({ id: "j", kind: "api", prompt: "x", timeout: 60 }, { binaries: {}, ai: null })).rejects.toMatchObject({ code: "unavailable" });
78
+ });
79
+ });
80
+
81
+ describe("seoanything ai", () => {
82
+ const run = async (argv) => { const out = [], err = []; const code = await main(argv, { out: (s) => out.push(s), err: (s) => err.push(s) }); return { code, out: out.join("\n"), err: err.join("\n") }; };
83
+
84
+ it("checks a key from the environment, keeps it in the config file, shows only its last four and forgets it", async () => {
85
+ process.env.SEOANYTHING_AI_KEY = KEY;
86
+ const urls = [];
87
+ vi.stubGlobal("fetch", async (url, init) => { urls.push([url, init.headers["x-api-key"]]); return json({ data: [{ id: "claude-opus-5-5", display_name: "Claude Opus 5.5" }] }); });
88
+ const set = await run(["ai", "set", "claude"]);
89
+ expect(set.code).toBe(0);
90
+ expect(set.out).toContain("…WXYZ"); expect(set.out).not.toContain(KEY);
91
+ expect(urls).toEqual([["https://api.anthropic.com/v1/models?limit=100", KEY]]);
92
+ expect(loadConfig().ai).toEqual({ provider: "anthropic", key: KEY, model: "claude-opus-5-5" });
93
+ expect(fs.statSync(path.join(dir, "seoanything", "config.json")).mode & 0o777).toBe(0o600);
94
+ delete process.env.SEOANYTHING_AI_KEY;
95
+ const shown = await run(["ai", "--json"]);
96
+ expect(JSON.parse(shown.out)).toEqual({ provider: "anthropic", label: "Claude", model: "claude-opus-5-5", baseUrl: null, key: "…WXYZ", from: "config file" });
97
+ expect((await run(["ai", "remove"])).code).toBe(0);
98
+ expect(loadConfig().ai).toBeUndefined();
99
+ });
100
+
101
+ it("refuses a refused key, a custom API without an https address or model, and an unknown provider", async () => {
102
+ process.env.SEOANYTHING_AI_KEY = KEY;
103
+ vi.stubGlobal("fetch", async () => json({ error: { message: `invalid ${KEY}` } }, 401));
104
+ const r = await run(["ai", "set", "claude"]);
105
+ expect(r.code).toBe(5); expect(r.err).not.toContain(KEY); expect(loadConfig().ai).toBeUndefined();
106
+ expect((await run(["ai", "set", "custom", "--base-url", "http://api.example.com/v1", "--model", "m"])).code).toBe(2);
107
+ expect((await run(["ai", "set", "custom", "--base-url", "https://api.example.com/v1"])).code).toBe(2);
108
+ expect((await run(["ai", "set", "mistery"])).code).toBe(2);
109
+ saveConfig({ server: "https://x.test" });
110
+ expect((await run(["ai", "set", "custom", "--base-url", "https://api.example.com/v1", "--model", "m", "--no-check"])).code).toBe(0);
111
+ expect(loadConfig()).toEqual({ server: "https://x.test", ai: { provider: "custom", key: KEY, model: "m", baseUrl: "https://api.example.com/v1" } });
112
+ });
113
+ });
package/src/cli.js CHANGED
@@ -19,7 +19,7 @@ const OPTS = {
19
19
  code: { type: "string" }, background: { type: "boolean" }, video: { type: "boolean" }, calendar: { type: "string" },
20
20
  mode: { type: "string" }, model: { type: "string" }, keyword: { type: "string" }, words: { type: "string" }, tone: { type: "string" }, out: { type: "string" }, frontmatter: { type: "string" }, format: { type: "string" }, target: { type: "string" },
21
21
  replaces: { type: "string" }, views: { type: "string" }, clicks: { type: "string" }, reactions: { type: "string" }, comments: { type: "string" }, shares: { type: "string" },
22
- force: { type: "boolean" },
22
+ force: { type: "boolean" }, "base-url": { type: "string" }, "no-check": { type: "boolean" },
23
23
  };
24
24
  const HEX_ID = /^[a-f0-9]{16,32}$/, DAY = /^\d{4}-\d{2}-\d{2}$/;
25
25
  // app sends are a bare channel (devto, webhook); links recorded by hand are channel:host/path
@@ -61,10 +61,13 @@ usage: seoanything <command> [options]
61
61
  connect [--no-browser] run your own claude/codex/agy for your web chats and posts
62
62
  connect --code <setup code> [--background] link with a setup code from settings › ai engines, no login
63
63
  connect --video also make the content plan's videos here (cinematic-film skill, python3 + skia-python, ffmpeg, free voice)
64
+ ai set claude|openai|gemini|custom [--model m] [--base-url u] keep your own AI key on this computer (asked for, or $SEOANYTHING_AI_KEY)
65
+ ai [show] | ai test | ai use | ai remove the key's provider and model, a one-word test, make it your default engine, forget it
64
66
  config get|set <key> [value] server, defaultGeo, defaultModel …
65
67
  init | install | schema | llms-txt | sitemap | menu seoanything v1 commands, unchanged
66
68
 
67
69
  global: --json --server <url> --quiet --no-color env: SEOANYTHING_SERVER SEOANYTHING_API_KEY SEOANYTHING_TOKEN
70
+ own AI key env: SEOANYTHING_AI_PROVIDER SEOANYTHING_AI_KEY SEOANYTHING_AI_MODEL SEOANYTHING_AI_BASE_URL
68
71
  exit codes: 0 ok · 1 error · 2 usage · 3 not logged in · 4 quota/rate limit · 5 upstream unavailable`;
69
72
 
70
73
  export async function main(argv, io = { out: console.log, err: console.error }) {
@@ -235,6 +238,7 @@ export async function main(argv, io = { out: console.log, err: console.error })
235
238
  io.err(connectReasonColor(c, await connect({ server: creds.server, token, deviceToken, onUnlinked, log: io.err, signal: ac.signal, video: flags.video })));
236
239
  return EXIT.ok;
237
240
  }
241
+ case "ai": return await aiCommand(p, api, io, { print, c, note });
238
242
  case "config": {
239
243
  const cfg = loadConfig();
240
244
  if (p.sub === "get") { const k = p.positionals[1]; print(k ? { [k]: cfg[k] ?? cfg.defaults?.[k] } : cfg, k ? String(cfg[k] ?? cfg.defaults?.[k] ?? "") : JSON.stringify({ ...cfg, token: cfg.token && "••••", apiKey: cfg.apiKey && "••••", connector: cfg.connector && { ...cfg.connector, token: "••••" } }, null, 2)); return EXIT.ok; }
@@ -253,6 +257,74 @@ export async function main(argv, io = { out: console.log, err: console.error })
253
257
  }
254
258
  }
255
259
 
260
+ /** `seoanything ai`: your own provider key, kept in the config file on this computer and used through `connect`. */
261
+ async function aiCommand(p, api, io, { print, c, note }) {
262
+ const { PROVIDERS, TEST_PROMPT, ask, checkBase, hint, listModels, providerOf, resolveAi } = await import("./ai.js");
263
+ const { flags } = p, sub = p.sub ?? "show";
264
+ const usage = "seoanything ai set claude|openai|gemini|custom [--model m] [--base-url u] | ai [show] | ai test | ai use | ai remove";
265
+ const shown = (ai) => (ai ? { provider: ai.provider, label: ai.label, model: ai.model || null, baseUrl: ai.baseUrl || null, key: ai.key ? hint(ai.key) : null, from: ai.from } : null);
266
+ if (sub === "show") {
267
+ const ai = resolveAi();
268
+ print(shown(ai), ai ? `${c("1", ai.label)} · model ${ai.model || "not set"}${ai.baseUrl ? ` · ${ai.baseUrl}` : ""} · key ${ai.key ? hint(ai.key) : "not set"} (${ai.from})` : "no AI key on this computer. set one with `seoanything ai set claude|openai|gemini|custom`.");
269
+ return EXIT.ok;
270
+ }
271
+ if (sub === "remove") { const cfg = loadConfig(); delete cfg.ai; saveConfig(cfg); print({ ok: true }, "forgot the AI key saved on this computer (environment variables still apply)."); return EXIT.ok; }
272
+ if (sub === "use") {
273
+ // the account's default engine becomes this computer's key, reached through `connect`
274
+ const r = await api.request("PUT", "/engines/default", { engine: "cli:api" });
275
+ print(r, c("32", "✓ your SEOAnything chats and posts now use the API key on this computer while `seoanything connect` runs here; otherwise our cloud answers."));
276
+ return EXIT.ok;
277
+ }
278
+ if (sub === "test") {
279
+ const ai = resolveAi();
280
+ if (!ai) throw new CliError("no AI key on this computer. set one with `seoanything ai set`.", EXIT.usage);
281
+ const t0 = Date.now();
282
+ try {
283
+ const r = await ask(ai, { prompt: TEST_PROMPT, maxTokens: 50, timeoutMs: 60_000 });
284
+ print({ ok: /^ready\W*$/i.test(r.text), model: r.model, seconds: (Date.now() - t0) / 1000, text: r.text.slice(0, 60) }, c("32", `✓ ${ai.label} (${r.model}) answered "${r.text.slice(0, 60)}" in ${((Date.now() - t0) / 1000).toFixed(1)} s.`));
285
+ } catch (e) { throw new CliError(e.message, EXIT.upstream); }
286
+ return EXIT.ok;
287
+ }
288
+ if (sub !== "set") throw new CliError(`usage: ${usage}`, EXIT.usage);
289
+ const provider = providerOf(p.positionals[1] ?? "");
290
+ if (!provider) throw new CliError(`usage: ${usage}`, EXIT.usage);
291
+ const label = PROVIDERS[provider].label;
292
+ let baseUrl;
293
+ try { baseUrl = provider === "custom" ? checkBase(flags["base-url"]) : undefined; } catch (e) { throw new CliError(e.message, EXIT.usage); }
294
+ if (provider === "custom" && !flags.model) throw new CliError("a custom API needs --base-url and --model.", EXIT.usage);
295
+ // never an argument: it would stay in the shell's history
296
+ const key = (process.env.SEOANYTHING_AI_KEY || (await readSecret(`${label} API key${PROVIDERS[provider].keysUrl ? ` (from ${PROVIDERS[provider].keysUrl})` : ""}: `, io))).trim();
297
+ if ((!key && provider !== "custom") || /\s/.test(key) || key.length > 400) throw new CliError("that doesn't look like an API key.", EXIT.usage);
298
+ const ai = { provider, label, key, model: flags.model ?? "", baseUrl: baseUrl ?? "" };
299
+ if (!flags["no-check"]) {
300
+ note(`checking the key with ${label}…`);
301
+ let models = [];
302
+ try { models = await listModels(ai, { timeoutMs: 15_000 }); }
303
+ catch (e) { if (provider !== "custom" || /refused the API key/.test(e.message)) throw new CliError(e.message, EXIT.upstream); } // not every custom API lists its models
304
+ ai.model ||= models[0]?.id ?? "";
305
+ }
306
+ if (!ai.model) throw new CliError("no model to use: give one with --model.", EXIT.usage);
307
+ const cfg = loadConfig();
308
+ saveConfig({ ...cfg, ai: { provider, key, model: ai.model, ...(baseUrl ? { baseUrl } : {}) } });
309
+ print(shown({ ...ai, from: "config file" }), `${c("32", `✓ saved your ${label} key (${hint(key)}), model ${ai.model}, in ${configPath()}.`)}
310
+ it stays on this computer. to use it for your SEOAnything chats and posts:
311
+ seoanything connect --background link this computer (it offers the key as "API key on your computer")
312
+ seoanything ai use make it your default engine, or pick it in settings › cli and ai engines
313
+ try it now with: seoanything ai test`);
314
+ return EXIT.ok;
315
+ }
316
+
317
+ /** A secret typed at a prompt without showing it, or read whole from a pipe. */
318
+ async function readSecret(question, io) {
319
+ if (!process.stdin.isTTY) { let s = ""; for await (const chunk of process.stdin) s += chunk; return s; }
320
+ const rl = readline.createInterface({ input: process.stdin, output: process.stderr, terminal: true });
321
+ // shortcut: readline has no hidden mode; muting its echo (an internal method) is the usual way, swap for a real one if Node adds it
322
+ rl._writeToOutput = (s) => { if (s.startsWith(question)) rl.output.write(s); };
323
+ const answer = await new Promise((r) => rl.question(question, r));
324
+ rl.close(); io.err("");
325
+ return answer;
326
+ }
327
+
256
328
  const connectReasonColor = (c, reason) => c(/disconnected|not accept|took over|no longer linked/.test(reason) ? "33" : "2", reason);
257
329
 
258
330
  const fmt = (n) => (n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : n >= 1e3 ? `${Math.round(n / 1e3)}K` : String(n ?? ""));
package/src/connect.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // `seoanything connect`: keep one outbound WebSocket to the cloud and run the AI CLIs installed on this computer
2
- // (claude, codex, agy) for your own chats and blog posts. The cloud sends a prompt, this process runs the
2
+ // (claude, codex, agy), or your own API key kept here (`seoanything ai set`, see ./ai.js), for your own chats and blog posts. The cloud sends a prompt, this process runs the
3
3
  // CLI with its own login and sends the text back. No credential file is ever read or sent. Zero dependencies
4
4
  // (Node 22+ for the built-in WebSocket). It signs in with your login, or with a token from a one-use setup code
5
5
  // (`connect --code`, which the settings page hands to your own AI app) that can only open this computer's link.
@@ -10,6 +10,7 @@ import os from "node:os";
10
10
  import path from "node:path";
11
11
  import { StringDecoder } from "node:string_decoder";
12
12
  import { fileURLToPath } from "node:url";
13
+ import { ask as askAi, hint, resolveAi } from "./ai.js";
13
14
  import { CliError, client, exitCodeFor } from "./api.js";
14
15
  import { configDir, loadConfig, saveConfig } from "./config.js";
15
16
  import { VERSION } from "./mcp.js";
@@ -18,6 +19,7 @@ export const KINDS = {
18
19
  claude: { label: "Claude Code", command: "claude" },
19
20
  codex: { label: "Codex", command: "codex" },
20
21
  agy: { label: "Antigravity", command: "agy" },
22
+ api: { label: "API key on your computer", command: "seoanything ai" }, // not a CLI: the key set with `seoanything ai set`
21
23
  };
22
24
  export const MAX_JOBS = 2;
23
25
  const MAX_PROMPT = 400 * 1024;
@@ -56,16 +58,18 @@ export function findBinary(command, env = process.env, platform = process.platfo
56
58
  return null;
57
59
  }
58
60
 
59
- /** Installed CLIs with their versions and the models each offers, looked up side by side. */
60
- export async function detect(env = ownEnv(), run = runProcess) {
61
- const found = await Promise.all(Object.entries(KINDS).map(async ([kind, { command }]) => {
61
+ /** Installed CLIs with their versions and the models each offers, looked up side by side, and the API key set up here
62
+ * (`ai`, from ./ai.js resolveAi) as one more engine when it has a key or an address, and a model. */
63
+ export async function detect(env = ownEnv(), run = runProcess, ai = resolveAi()) {
64
+ const key = ai && (ai.key || ai.provider === "custom") && ai.model ? [{ kind: "api", path: "", version: `${ai.label} · ${ai.model}`, models: [{ id: ai.model, label: `${ai.label} · ${ai.model}` }].filter((m) => MODEL.test(m.id)) }] : [];
65
+ const found = await Promise.all(Object.entries(KINDS).filter(([kind]) => kind !== "api").map(async ([kind, { command }]) => {
62
66
  const bin = findBinary(command, env);
63
67
  if (!bin) return null;
64
68
  let version = "";
65
69
  try { version = (await run([bin, "--version"], { env, timeoutMs: 20_000 })).stdout.trim().split("\n")[0].slice(0, 80); } catch { /* still usable */ }
66
70
  return { kind, path: bin, version, models: await listModels(kind, bin, env, run) };
67
71
  }));
68
- return found.filter(Boolean);
72
+ return [...found.filter(Boolean), ...key];
69
73
  }
70
74
 
71
75
  // Claude Code has no command that lists models; these aliases always mean its latest of each.
@@ -206,9 +210,14 @@ export function runProcess(argv, { cwd, env, input = "", timeoutMs = 60_000, idl
206
210
  });
207
211
  }
208
212
 
209
- /** One job end to end in a throwaway folder. */
210
- export async function runJob(job, { binaries, env = ownEnv(), signal, run = runProcess, onDelta } = {}) {
213
+ /** One job end to end in a throwaway folder; an "api" job calls the provider with the key kept here instead. */
214
+ export async function runJob(job, { binaries, env = ownEnv(), signal, run = runProcess, onDelta, ai = resolveAi(), fetchImpl } = {}) {
211
215
  checkJob(job);
216
+ if (job.kind === "api") {
217
+ if (!ai) throw new JobError("unavailable", "no API key is set on this computer. run `seoanything ai set`.");
218
+ try { return await askAi(ai, { system: job.system, prompt: job.prompt, model: job.model, timeoutMs: job.timeout * 1000, signal, fetchImpl }); }
219
+ catch (e) { throw new JobError(signal?.aborted ? "cancelled" : "cli_failed", String(e.message).slice(0, 300)); }
220
+ }
212
221
  const binary = binaries[job.kind];
213
222
  if (!binary) throw new JobError("unavailable", `${KINDS[job.kind].label} is not installed on this computer.`);
214
223
  const root = mkdtempSync(path.join(os.tmpdir(), "seoanything-"));
@@ -441,9 +450,11 @@ export async function connect({ server, token, deviceToken, onUnlinked, log = co
441
450
  const api = client({ server, token });
442
451
  const deviceId = deviceIdFor();
443
452
  const env = ownEnv();
444
- let found = await detect(env);
445
- if (!found.length) throw new CliError("no AI CLI found on PATH. install claude, codex or agy, sign in to it once, then run connect again.", 1);
446
- for (const f of found) log(`✓ found ${KINDS[f.kind].label} ${f.version} at ${f.path}`);
453
+ let ai = resolveAi();
454
+ let found = await detect(env, undefined, ai);
455
+ if (!found.length) throw new CliError("no AI CLI found on PATH and no API key set. install claude, codex or agy and sign in to it once, or set your own key with `seoanything ai set`, then run connect again.", 1);
456
+ const say = (f) => (f.kind === "api" ? `✓ found your ${ai.label} key (${ai.key ? hint(ai.key) : "no key"}), model ${ai.model}; it stays on this computer` : `✓ found ${KINDS[f.kind].label} ${f.version} at ${f.path}`);
457
+ for (const f of found) log(say(f));
447
458
  let binaries = Object.fromEntries(found.map((f) => [f.kind, f.path]));
448
459
  // --video: offered only when the skill and its tools are all here
449
460
  let film = null;
@@ -455,8 +466,10 @@ export async function connect({ server, token, deviceToken, onUnlinked, log = co
455
466
  const hello = () => ({ type: "hello", deviceId, name: hostname.slice(0, 80), platform: process.platform, version: VERSION, clis: found.map((f) => ({ kind: f.kind, version: f.version, models: f.models })), features: film ? ["rescan", "video"] : ["rescan"] });
456
467
  // asked from the settings page: pick up a CLI installed since this connector started, without a restart
457
468
  async function rescan(ws) {
458
- const now = await detect(env);
459
- if (!now.length) return log("! looked again and found no AI CLI; keeping the ones already linked.");
469
+ const nextAi = resolveAi();
470
+ const now = await detect(env, undefined, nextAi);
471
+ if (!now.length) return log("! looked again and found no AI CLI or API key; keeping the ones already linked.");
472
+ ai = nextAi;
460
473
  found = now;
461
474
  binaries = Object.fromEntries(found.map((f) => [f.kind, f.path]));
462
475
  log(`✓ looked again: ${found.map((f) => KINDS[f.kind].label).join(", ")}`);
@@ -484,7 +497,7 @@ export async function connect({ server, token, deviceToken, onUnlinked, log = co
484
497
  const flush = () => { flushTimer = null; if (pend.text || pend.thinking) { send(ws, { type: "delta", id: job.id, ...pend }); pend = { text: "", thinking: "" }; } };
485
498
  const onDelta = job.stream ? (d) => { pend.text += d.text ?? ""; pend.thinking += d.thinking ?? ""; flushTimer ??= setTimeout(flush, 150); } : undefined;
486
499
  try {
487
- const r = await runJob(job, { binaries, env, signal: ac.signal, onDelta });
500
+ const r = await runJob(job, { binaries, env, signal: ac.signal, onDelta, ai });
488
501
  if (flushTimer) { clearTimeout(flushTimer); flush(); }
489
502
  send(ws, { type: "result", id: job.id, ...r });
490
503
  log(`✓ ${label} answered in ${((Date.now() - t0) / 1000).toFixed(1)} s`);
package/src/mcp.js CHANGED
@@ -3,7 +3,7 @@ import fs from "node:fs";
3
3
  import { CliError } from "./api.js";
4
4
  import { resolveCreds } from "./config.js";
5
5
 
6
- export const VERSION = "2.4.1";
6
+ export const VERSION = "2.4.2";
7
7
 
8
8
  export async function mcp(flags) {
9
9
  const [major, minor] = process.versions.node.split(".").map(Number);