seoanything-cli 0.0.0-stage → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/cli.js ADDED
@@ -0,0 +1,216 @@
1
+ // seoanything v2 CLI (TRD §17). Core commands: node:util.parseArgs + fetch + node:readline, zero runtime deps.
2
+ // v1 commands (init/install/audit/schema/llms-txt/sitemap/menu/list) pass through to the seoanything@1 package.
3
+ import { parseArgs } from "node:util";
4
+ import fs from "node:fs";
5
+ import readline from "node:readline";
6
+ import { CliError, client, qs, streamSse } from "./api.js";
7
+ import { DEFAULT_SERVER, configPath, loadConfig, resolveCreds, saveConfig } from "./config.js";
8
+ import { login } from "./login.js";
9
+ import { VERSION } from "./mcp.js";
10
+
11
+ export const EXIT = { ok: 0, error: 1, usage: 2, auth: 3, quota: 4, upstream: 5 };
12
+ const V1_COMMANDS = new Set(["init", "install", "schema", "llms-txt", "llms", "sitemap", "menu", "interactive", "list", "check"]);
13
+
14
+ const OPTS = {
15
+ json: { type: "boolean" }, quiet: { type: "boolean" }, "no-color": { type: "boolean" }, help: { type: "boolean", short: "h" }, version: { type: "boolean", short: "v" },
16
+ server: { type: "string" }, "api-key": { type: "string" }, "no-browser": { type: "boolean" }, local: { type: "boolean" }, cloud: { type: "boolean" }, yes: { type: "boolean" },
17
+ geo: { type: "string" }, hl: { type: "string" }, limit: { type: "string" }, hours: { type: "string" }, period: { type: "string" }, day: { type: "string" },
18
+ source: { type: "string" }, window: { type: "string" }, language: { type: "string" }, topic: { type: "string" },
19
+ 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" },
20
+ };
21
+
22
+ /** Parse argv into { command, sub, positionals, flags }. Exported for tests. */
23
+ export function parse(argv) {
24
+ const { values, positionals } = parseArgs({ args: argv, options: OPTS, allowPositionals: true, strict: false });
25
+ const [command, ...rest] = positionals;
26
+ return { command, sub: rest[0], positionals: rest, flags: values };
27
+ }
28
+
29
+ const HELP = `seoanything v${VERSION} — SEO trends, keywords, chat, blog studio, audits, MCP
30
+
31
+ usage: seoanything <command> [options]
32
+
33
+ login [--server <url>] [--api-key <key>] [--no-browser] device-flow login (opens browser) or store an API key
34
+ logout | whoami | usage credentials and quota
35
+ trends daily|realtime [--geo NP] [--hl en] [--limit 20] [--hours 4] [--local]
36
+ keywords suggest|interest|cluster "<seed>" [--period "today 12-m"] [--geo US]
37
+ topics [--day YYYY-MM-DD]
38
+ repos trending [--source all] [--window 7d] [--language ts] [--topic seo] [--limit 25]
39
+ chat ["question"] [--mode keywords] [--model fast] one-shot or REPL (/mode /model /new /exit)
40
+ blog new "<topic>" [--keyword k] [--words 1500] [--tone friendly] [--out post.md] [--frontmatter astro] [--yes]
41
+ blog list | blog get <id> [--format md|html|mdx] | blog publish <id> --target github
42
+ audit <path|url> [--cloud] local auditor, or cloud audit saved to history
43
+ mcp local stdio MCP server
44
+ connect [--no-browser] run your own claude/codex/gemini/agy for your web chats and posts
45
+ config get|set <key> [value] server, defaultGeo, defaultModel …
46
+ init | install | schema | llms-txt | sitemap | menu seoanything v1 commands, unchanged
47
+
48
+ global: --json --server <url> --quiet --no-color env: SEOANYTHING_SERVER SEOANYTHING_API_KEY SEOANYTHING_TOKEN
49
+ exit codes: 0 ok · 1 error · 2 usage · 3 not logged in · 4 quota/rate limit · 5 upstream unavailable`;
50
+
51
+ export async function main(argv, io = { out: console.log, err: console.error }) {
52
+ let p;
53
+ try { p = parse(argv); } catch (e) { io.err(e.message); return EXIT.usage; }
54
+ const { command, flags } = p;
55
+ const color = !flags["no-color"] && !flags.json && process.stdout.isTTY && !process.env.NO_COLOR;
56
+ const c = (code, s) => (color ? `\x1b[${code}m${s}\x1b[0m` : s);
57
+ const print = (data, text) => io.out(flags.json ? JSON.stringify(data, null, 2) : text ?? (typeof data === "string" ? data : JSON.stringify(data, null, 2)));
58
+ const note = (s) => { if (!flags.quiet && !flags.json) io.err(c("2", s)); };
59
+ try {
60
+ if (flags.version) { print({ version: VERSION }, `seoanything v${VERSION}`); return EXIT.ok; }
61
+ if (!command || flags.help || command === "help") { io.out(HELP); return command || flags.help ? EXIT.ok : EXIT.usage; }
62
+ if (V1_COMMANDS.has(command) || (command === "audit" && !flags.cloud)) { const { runCli } = await import("seoanything-v1"); await runCli(argv); return process.exitCode ?? EXIT.ok; }
63
+ const creds = resolveCreds(flags);
64
+ const api = client(creds);
65
+ const d = creds.defaults;
66
+ const geo = (flags.geo ?? d.geo ?? "US").toUpperCase(), hl = flags.hl ?? d.hl ?? "en";
67
+ const num = (v, dflt) => (v === undefined ? dflt : Number(v));
68
+ const needArg = (v, what) => { if (!v) throw new CliError(`usage: ${what}`, EXIT.usage); return v; };
69
+ switch (command) {
70
+ case "login": {
71
+ const r = await login({ server: creds.server, apiKey: flags["api-key"], noBrowser: flags["no-browser"], log: io.err });
72
+ print(r, c("32", `logged in to ${r.server}${r.user?.email ? ` as ${r.user.email}` : ""}. saved to ${configPath()}`));
73
+ return EXIT.ok;
74
+ }
75
+ case "logout": { const cfg = loadConfig(); delete cfg.token; delete cfg.apiKey; delete cfg.user; saveConfig(cfg); print({ ok: true }, "logged out."); return EXIT.ok; }
76
+ case "whoami": {
77
+ if (!creds.token) throw new CliError("not logged in. run `seoanything login`.", EXIT.auth);
78
+ const me = await api.get("/me");
79
+ print(me, `${me.user.email ?? me.user.id} · plan ${me.user.plan ?? "free"} · providers: ${me.providers?.join(", ") || "email"} · server ${creds.server}`);
80
+ return EXIT.ok;
81
+ }
82
+ case "usage": {
83
+ const u = await api.get("/usage");
84
+ print(u, u.metrics.map((m) => `${m.metric.padEnd(16)} ${String(m.used).padStart(5)} / ${m.limit}`).join("\n") + `\nshared AI capacity used: ${u.capacity.percent}% · resets ${u.resetAt}`);
85
+ return EXIT.ok;
86
+ }
87
+ case "trends": {
88
+ const sub = needArg(p.sub, "seoanything trends daily|realtime");
89
+ if (sub !== "daily" && sub !== "realtime") throw new CliError("usage: seoanything trends daily|realtime", EXIT.usage);
90
+ let snap;
91
+ if (flags.local) {
92
+ let GT; try { const m = await import("@alkalisummer/google-trends-js"); GT = m.default?.default ?? m.default; } catch { throw new CliError("--local needs the optional dependency: npm i @alkalisummer/google-trends-js", EXIT.error); }
93
+ const r = sub === "daily" ? await GT.dailyTrends({ geo, hl }) : await GT.realTimeTrends({ geo, trendingHours: num(flags.hours, 4) });
94
+ if (r.error) throw new CliError(`google trends: ${r.error.message ?? r.error}`, EXIT.upstream);
95
+ snap = { source: `google_${sub}`, geo, hl, fetchedAt: new Date().toISOString(), local: true, items: r.data.slice(0, num(flags.limit, 20)).map((it, i) => ({ rank: i + 1, keyword: it.keyword ?? it.title, traffic: it.traffic, related: it.relatedKeywords ?? [] })) };
96
+ } else snap = await api.get(`/trends/${sub}${qs(sub === "daily" ? { geo, hl, limit: flags.limit } : { geo, hours: flags.hours })}`);
97
+ print(snap, `${c("1", `${sub} trends · ${snap.geo}`)}${snap.stale ? c("33", " (stale)") : ""}\n` + snap.items.map((it) => `${c("32", `#${String(it.rank).padStart(2)}`)} ${it.keyword.padEnd(32)} ${it.traffic ? `${fmt(it.traffic)} searches` : ""}${it.opportunity != null ? ` · opp ${it.opportunity}` : ""}`).join("\n"));
98
+ return EXIT.ok;
99
+ }
100
+ case "keywords": {
101
+ const sub = needArg(p.sub, "seoanything keywords suggest|interest|cluster <seed>");
102
+ const seed = needArg(p.positionals[1], `seoanything keywords ${sub} "<seed>"`);
103
+ if (sub === "suggest") { const r = await api.get(`/keywords/suggest${qs({ q: seed, hl })}`); const list = Array.isArray(r) ? r : r.items ?? []; print(r, list.map((k, i) => `${c("32", `#${i + 1}`)} ${k}`).join("\n")); }
104
+ else if (sub === "interest") { const r = await api.post("/keywords/interest", { keywords: seed.split(",").map((s) => s.trim()).filter(Boolean).slice(0, 5), geo, period: flags.period ?? "today 12-m" }); print(r); }
105
+ else if (sub === "cluster") { const r = await api.post("/keywords/cluster", { seed, geo, hl }); const clusters = Array.isArray(r) ? r : r.clusters ?? r.items ?? []; print(r, clusters.map((cl) => `${c("1", cl.label ?? cl.name ?? "cluster")}${cl.intent ? c("2", ` · ${cl.intent}`) : ""}${cl.pillar ? c("35", " · pillar") : ""}\n ${(cl.keywords ?? []).join(", ")}`).join("\n")); }
106
+ else throw new CliError("usage: seoanything keywords suggest|interest|cluster <seed>", EXIT.usage);
107
+ return EXIT.ok;
108
+ }
109
+ case "topics": { const r = await api.get(`/topics${qs({ day: flags.day, limit: flags.limit })}`); const items = Array.isArray(r) ? r : r.items ?? []; print(r, items.map((t, i) => `${c("32", `#${i + 1}`)} ${c("1", t.label)} ${c("2", `score ${t.score}`)}\n ${t.summary}`).join("\n")); return EXIT.ok; }
110
+ case "repos": {
111
+ if (p.sub !== "trending") throw new CliError("usage: seoanything repos trending [--source --window --language --topic --limit]", EXIT.usage);
112
+ const r = await api.get(`/repos/trending${qs({ source: flags.source, window: flags.window, language: flags.language, topic: flags.topic, limit: flags.limit })}`);
113
+ const items = Array.isArray(r) ? r : r.items ?? [];
114
+ print(r, items.map((x, i) => `${c("32", `#${String(i + 1).padStart(2)}`)} ${x.fullName.padEnd(40)} ${c("33", `+${fmt(x.starDelta)}★`)} ${c("2", x.language ?? "")}\n ${x.description ?? ""}`).join("\n"));
115
+ return EXIT.ok;
116
+ }
117
+ case "chat": return chat(p, api, io, { print, c, note, d });
118
+ case "blog": return blog(p, api, io, { print, c, note, num, needArg, flags });
119
+ case "audit": {
120
+ const target = needArg(p.sub, "seoanything audit <path|url> [--cloud]");
121
+ const url = /^https?:\/\//i.test(target) ? target : `https://${target}`;
122
+ const r = await api.post("/seo/audit", { url });
123
+ print(r, `${c("1", `audit · ${url}`)} · grade ${c("32", r.grade ?? "?")} · score ${r.score ?? "?"}\n` + (r.issues ?? []).map((i) => `${c("31", "✖")} ${i.msg ?? i.message ?? JSON.stringify(i)}`).join("\n"));
124
+ return EXIT.ok;
125
+ }
126
+ case "mcp": { const { mcp } = await import("./mcp.js"); await mcp(flags); return EXIT.ok; }
127
+ case "connect": {
128
+ // link this computer: the web app's chats and blog posts can then run on the AI CLIs installed here
129
+ let token = creds.token;
130
+ if (!token) { const r = await login({ server: creds.server, noBrowser: flags["no-browser"], log: io.err }); io.err(c("32", `logged in as ${r.user?.email ?? "you"}`)); token = resolveCreds(flags).token; }
131
+ const { connect } = await import("./connect.js");
132
+ const ac = new AbortController();
133
+ for (const sig of ["SIGINT", "SIGTERM"]) process.on(sig, () => ac.abort());
134
+ io.err(connectReasonColor(c, await connect({ server: creds.server, token, log: io.err, signal: ac.signal })));
135
+ return EXIT.ok;
136
+ }
137
+ case "config": {
138
+ const cfg = loadConfig();
139
+ 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 && "••••" }, null, 2)); return EXIT.ok; }
140
+ if (p.sub === "set") {
141
+ const [, k, v] = p.positionals; needArg(k && v, "seoanything config set <key> <value>");
142
+ if (k === "server") cfg.server = v; else (cfg.defaults ??= {})[k.replace(/^default/, "").toLowerCase()] = v;
143
+ saveConfig(cfg); print({ [k]: v }, `${k} = ${v}`); return EXIT.ok;
144
+ }
145
+ throw new CliError("usage: seoanything config get|set <key> [value]", EXIT.usage);
146
+ }
147
+ default: io.err(`unknown command "${command}". run \`seoanything --help\`.`); return EXIT.usage;
148
+ }
149
+ } catch (e) {
150
+ if (e instanceof CliError) { io.err(flags.json ? JSON.stringify({ error: e.message, ...e.problem }) : c("31", `✖ ${e.message}`)); return e.exitCode; }
151
+ io.err(c("31", `✖ ${e.message ?? e}`)); return EXIT.error;
152
+ }
153
+ }
154
+
155
+ const connectReasonColor = (c, reason) => c(/disconnected|not accept|took over/.test(reason) ? "33" : "2", reason);
156
+
157
+ const fmt = (n) => (n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : n >= 1e3 ? `${Math.round(n / 1e3)}K` : String(n ?? ""));
158
+
159
+ async function chat(p, api, io, { print, c, note, d }) {
160
+ const flags = p.flags;
161
+ let mode = flags.mode ?? "general", model = flags.model ?? d.model, conv = null;
162
+ const ask = async (q) => {
163
+ conv ??= await api.post("/conversations", { mode, model });
164
+ const res = await api.raw("POST", `/conversations/${conv.id}/messages`, { content: q, mode, model });
165
+ let full = "";
166
+ if (flags.json) full = await streamSse(res); else { full = await streamSse(res, (t) => process.stdout.write(t)); io.out(""); }
167
+ return full;
168
+ };
169
+ const question = p.positionals.join(" ").trim();
170
+ if (question) { const answer = await ask(question); if (flags.json) print({ conversationId: conv.id, mode, answer }); return EXIT.ok; }
171
+ if (!process.stdin.isTTY) throw new CliError('usage: seoanything chat "question"', EXIT.usage);
172
+ note(`seo chat · mode ${mode} · /mode <m> · /model <m> · /new · /exit`);
173
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout, prompt: c("32", "you › ") });
174
+ rl.prompt();
175
+ for await (const line of rl) {
176
+ const t = line.trim();
177
+ if (!t) { rl.prompt(); continue; }
178
+ if (t === "/exit" || t === "/quit") break;
179
+ if (t.startsWith("/mode ")) { mode = t.slice(6).trim(); conv = null; note(`mode → ${mode}`); }
180
+ else if (t.startsWith("/model ")) { model = t.slice(7).trim(); conv = null; note(`model → ${model}`); }
181
+ else if (t === "/new") { conv = null; note("new conversation"); }
182
+ else { process.stdout.write(c("35", "seo › ")); try { await ask(t); } catch (e) { io.err(c("31", `✖ ${e.message}`)); if (e.exitCode === EXIT.auth) return EXIT.auth; } }
183
+ rl.prompt();
184
+ }
185
+ rl.close();
186
+ return EXIT.ok;
187
+ }
188
+
189
+ async function blog(p, api, io, { print, c, note, num, needArg, flags }) {
190
+ const sub = needArg(p.sub, "seoanything blog new|list|get|publish");
191
+ if (sub === "list") { const r = await api.get("/blog/posts"); const items = r.items ?? r; print(r, items.map((x) => `${c("2", x.id)} ${c("1", x.title ?? x.topic)} ${x.status ?? ""}`).join("\n") || "no posts yet. `seoanything blog new \"<topic>\"`"); return EXIT.ok; }
192
+ if (sub === "get") { const id = needArg(p.positionals[1], "seoanything blog get <id> [--format md|html|mdx]"); const r = flags.format ? await api.get(`/blog/posts/${id}/export${qs({ format: flags.format, frontmatter: flags.frontmatter })}`) : await api.get(`/blog/posts/${id}`); print(r, typeof r === "string" ? r : r.contentMd ?? r.content ?? JSON.stringify(r, null, 2)); return EXIT.ok; }
193
+ if (sub === "publish") { const id = needArg(p.positionals[1], "seoanything blog publish <id> --target site|github|gitlab"); const r = await api.post(`/blog/posts/${id}/publish`, { target: flags.target ?? "site" }); print(r, `published: ${r.url ?? JSON.stringify(r)}`); return EXIT.ok; }
194
+ if (sub !== "new") throw new CliError("usage: seoanything blog new|list|get|publish", EXIT.usage);
195
+ const topic = needArg(p.positionals.slice(1).join(" "), 'seoanything blog new "<topic>" [--keyword k] [--words 1500] [--tone friendly] [--out post.md]');
196
+ note("1/4 brief…");
197
+ const post = await api.post("/blog/posts", { topic, primaryKeyword: flags.keyword, targetWords: num(flags.words, undefined), tone: flags.tone });
198
+ const id = post.id;
199
+ note("2/4 outline…");
200
+ const outlineRes = await api.post(`/blog/posts/${id}/outline`);
201
+ const outline = outlineRes.outline ?? outlineRes.sections ?? outlineRes;
202
+ const sections = Array.isArray(outline) ? outline : outline.sections ?? [];
203
+ if (!flags.yes && process.stdin.isTTY && !flags.json) {
204
+ io.err(sections.map((s, i) => ` ${i + 1}. ${s.heading ?? s.title ?? s}`).join("\n"));
205
+ const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
206
+ const ans = await new Promise((r) => rl.question("write all sections? [Y/n] ", r)); rl.close();
207
+ if (/^n/i.test(ans.trim())) { print({ id, outline }, `stopped. post ${id} saved with its outline.`); return EXIT.ok; }
208
+ }
209
+ for (let i = 0; i < sections.length; i++) { note(`3/4 section ${i + 1}/${sections.length}…`); await streamSse(await api.raw("POST", `/blog/posts/${id}/sections/${i}`, {})); }
210
+ note("4/4 seo pass…");
211
+ const seo = await api.post(`/blog/posts/${id}/optimize`);
212
+ const md = await api.get(`/blog/posts/${id}/export${qs({ format: "md", frontmatter: flags.frontmatter })}`);
213
+ if (flags.out) { fs.writeFileSync(flags.out, typeof md === "string" ? md : JSON.stringify(md)); note(`wrote ${flags.out}`); }
214
+ print({ id, seo, file: flags.out ?? null, markdown: flags.out ? undefined : md }, flags.out ? `done. post ${id} · score ${seo.score ?? seo.audit?.score ?? "?"} → ${flags.out}` : md);
215
+ return EXIT.ok;
216
+ }
@@ -0,0 +1,38 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { EXIT, main, parse } from "./cli.js";
3
+ import { exitCodeFor } from "./api.js";
4
+
5
+ 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") }; };
6
+
7
+ describe("parse", () => {
8
+ it("splits command, sub, positionals and typed flags", () => {
9
+ const p = parse(["trends", "daily", "--geo", "np", "--limit", "5", "--json", "--local"]);
10
+ expect(p.command).toBe("trends"); expect(p.sub).toBe("daily");
11
+ expect(p.flags).toMatchObject({ geo: "np", limit: "5", json: true, local: true });
12
+ });
13
+ it("keeps quoted questions as positionals", () => {
14
+ expect(parse(["chat", "how do I rank for mcp seo", "--mode", "keywords"]).positionals).toEqual(["how do I rank for mcp seo"]);
15
+ });
16
+ });
17
+
18
+ describe("exit codes (TRD §17.1)", () => {
19
+ it("maps HTTP status to codes", () => {
20
+ expect(exitCodeFor(401)).toBe(EXIT.auth); expect(exitCodeFor(403)).toBe(EXIT.auth);
21
+ expect(exitCodeFor(429)).toBe(EXIT.quota); expect(exitCodeFor(503)).toBe(EXIT.upstream); expect(exitCodeFor(500)).toBe(EXIT.error);
22
+ });
23
+ it("usage errors exit 2, unknown command exits 2, help exits 0", async () => {
24
+ expect((await run(["bogus"])).code).toBe(2);
25
+ expect((await run(["trends"])).code).toBe(2);
26
+ expect((await run(["keywords", "suggest"])).code).toBe(2);
27
+ expect((await run(["--help"])).code).toBe(0);
28
+ expect((await run(["--version"])).out).toContain("2.0.0");
29
+ });
30
+ it("whoami without credentials exits 3; unreachable server exits 5", async () => {
31
+ const env = { ...process.env }; delete process.env.SEOANYTHING_API_KEY; delete process.env.SEOANYTHING_TOKEN;
32
+ process.env.XDG_CONFIG_HOME = "/nonexistent-seoanything-test";
33
+ expect((await run(["whoami"])).code).toBe(3);
34
+ const r = await run(["usage", "--server", "http://127.0.0.1:9", "--json"]);
35
+ expect(r.code).toBe(5);
36
+ process.env = env;
37
+ });
38
+ });
package/src/config.js ADDED
@@ -0,0 +1,30 @@
1
+ // Credentials + defaults (TRD §17.2). Zero deps. File mode 0600; env overrides win for CI.
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+
6
+ export const DEFAULT_SERVER = "https://www.seoanything.dev";
7
+
8
+ export function configDir() {
9
+ if (process.platform === "win32" && process.env.APPDATA) return path.join(process.env.APPDATA, "seoanything");
10
+ return path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config"), "seoanything");
11
+ }
12
+ export const configPath = () => path.join(configDir(), "config.json");
13
+
14
+ export function loadConfig() {
15
+ try { return JSON.parse(fs.readFileSync(configPath(), "utf8")); } catch { return {}; }
16
+ }
17
+
18
+ export function saveConfig(cfg) {
19
+ fs.mkdirSync(configDir(), { recursive: true, mode: 0o700 });
20
+ fs.writeFileSync(configPath(), JSON.stringify(cfg, null, 2) + "\n", { mode: 0o600 });
21
+ fs.chmodSync(configPath(), 0o600);
22
+ return configPath();
23
+ }
24
+
25
+ /** Effective server + credential: flags > env > config file. `token` is a session token or an sa_ API key (both go in Authorization: Bearer). */
26
+ export function resolveCreds(flags = {}, env = process.env, cfg = loadConfig()) {
27
+ const server = (flags.server || env.SEOANYTHING_SERVER || cfg.server || DEFAULT_SERVER).replace(/\/$/, "");
28
+ const token = env.SEOANYTHING_API_KEY || env.SEOANYTHING_TOKEN || cfg.apiKey || cfg.token || null;
29
+ return { server, token, defaults: cfg.defaults ?? {}, user: cfg.user };
30
+ }
@@ -0,0 +1,27 @@
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 } from "vitest";
5
+ import { configPath, loadConfig, resolveCreds, saveConfig, DEFAULT_SERVER } from "./config.js";
6
+
7
+ let dir;
8
+ beforeEach(() => { dir = fs.mkdtempSync(path.join(os.tmpdir(), "seoany-")); process.env.XDG_CONFIG_HOME = dir; });
9
+ afterEach(() => { fs.rmSync(dir, { recursive: true, force: true }); delete process.env.XDG_CONFIG_HOME; });
10
+
11
+ describe("config file", () => {
12
+ it("writes under $XDG_CONFIG_HOME/seoanything with mode 0600 and reads back", () => {
13
+ const p = saveConfig({ server: "https://x.test", token: "tok", defaults: { geo: "NP" } });
14
+ expect(p).toBe(path.join(dir, "seoanything", "config.json"));
15
+ expect(fs.statSync(p).mode & 0o777).toBe(0o600);
16
+ expect(loadConfig()).toEqual({ server: "https://x.test", token: "tok", defaults: { geo: "NP" } });
17
+ expect(configPath()).toBe(p);
18
+ });
19
+ it("returns {} when missing", () => { expect(loadConfig()).toEqual({}); });
20
+ it("resolves flags > env > file > default", () => {
21
+ saveConfig({ server: "https://file.test", token: "file-token" });
22
+ expect(resolveCreds({}, {})).toMatchObject({ server: "https://file.test", token: "file-token" });
23
+ expect(resolveCreds({}, { SEOANYTHING_SERVER: "https://env.test/", SEOANYTHING_API_KEY: "sa_env" })).toMatchObject({ server: "https://env.test", token: "sa_env" });
24
+ expect(resolveCreds({ server: "https://flag.test" }, { SEOANYTHING_SERVER: "https://env.test" }).server).toBe("https://flag.test");
25
+ expect(resolveCreds({}, {}, {}).server).toBe(DEFAULT_SERVER);
26
+ });
27
+ });
package/src/connect.js ADDED
@@ -0,0 +1,260 @@
1
+ // `seoanything connect`: keep one outbound WebSocket to the cloud and run the AI CLIs installed on this computer
2
+ // (claude, codex, gemini, agy) for your own chats and blog posts. The cloud sends a prompt, this process runs the
3
+ // CLI with its own login and sends the text back. No credential file is ever read or sent. Zero dependencies
4
+ // (Node 22+ for the built-in WebSocket).
5
+ import { spawn } from "node:child_process";
6
+ import { randomBytes } from "node:crypto";
7
+ import { accessSync, constants, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
8
+ import os from "node:os";
9
+ import path from "node:path";
10
+ import { CliError, client } from "./api.js";
11
+ import { loadConfig, saveConfig } from "./config.js";
12
+ import { VERSION } from "./mcp.js";
13
+
14
+ export const KINDS = {
15
+ claude: { label: "Claude Code", command: "claude" },
16
+ codex: { label: "Codex", command: "codex" },
17
+ gemini: { label: "Gemini CLI", command: "gemini" },
18
+ agy: { label: "Antigravity", command: "agy" },
19
+ };
20
+ export const MAX_JOBS = 2;
21
+ const MAX_PROMPT = 400 * 1024;
22
+ const MAX_STDOUT = 8 * 1024 * 1024;
23
+ const MAX_STDERR = 256 * 1024;
24
+ const IDLE_MS = 180_000;
25
+ const MODEL = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,119}$/;
26
+ // gemini takes an instruction as -p and the real prompt on stdin, like the council connector does
27
+ const GEMINI_INSTRUCTION = "Follow the request supplied on stdin and answer it directly.";
28
+
29
+ export class JobError extends Error {
30
+ constructor(code, message) { super(message); this.code = code; }
31
+ }
32
+
33
+ /** The CLI's own-login environment: PATH and home, nothing else from this shell (no API keys, no nested-session flags). */
34
+ export function ownEnv(env = process.env, platform = process.platform) {
35
+ const names = ["PATH", "HOME", "USER", "LOGNAME", "LANG", "LC_ALL", "TMPDIR", "SHELL"];
36
+ if (platform === "win32") names.push("Path", "SYSTEMROOT", "USERPROFILE", "APPDATA", "LOCALAPPDATA", "PATHEXT", "TEMP", "TMP", "HOMEDRIVE", "HOMEPATH");
37
+ const out = {};
38
+ for (const n of names) if (env[n] !== undefined) out[n] = env[n];
39
+ out.NO_COLOR = "1";
40
+ out.TERM = "dumb";
41
+ return out;
42
+ }
43
+
44
+ /** Find a CLI on PATH without a shell. Windows npm shims (.cmd) need a shell, so only .exe builds are found there. */
45
+ export function findBinary(command, env = process.env, platform = process.platform) {
46
+ const folders = (env.PATH || env.Path || "").split(path.delimiter).filter(Boolean);
47
+ const names = platform === "win32" ? [`${command}.exe`] : [command];
48
+ for (const folder of folders) for (const name of names) {
49
+ const candidate = path.join(folder, name);
50
+ try {
51
+ if (!statSync(candidate).isFile()) continue;
52
+ if (platform !== "win32") accessSync(candidate, constants.X_OK);
53
+ return candidate;
54
+ } catch { /* not here */ }
55
+ }
56
+ return null;
57
+ }
58
+
59
+ /** Installed CLIs with their versions. */
60
+ export async function detect(env = ownEnv(), run = runProcess) {
61
+ const found = [];
62
+ for (const [kind, { command }] of Object.entries(KINDS)) {
63
+ const bin = findBinary(command, env);
64
+ if (!bin) continue;
65
+ let version = "";
66
+ try { version = (await run([bin, "--version"], { env, timeoutMs: 20_000 })).stdout.trim().split("\n")[0].slice(0, 80); } catch { /* still usable */ }
67
+ found.push({ kind, path: bin, version });
68
+ }
69
+ return found;
70
+ }
71
+
72
+ export function checkJob(job) {
73
+ if (!(job.kind in KINDS)) throw new JobError("rejected", "unknown CLI.");
74
+ if (typeof job.prompt !== "string" || !job.prompt || Buffer.byteLength(job.prompt) > MAX_PROMPT) throw new JobError("rejected", "invalid prompt.");
75
+ if (job.system !== undefined && (typeof job.system !== "string" || Buffer.byteLength(job.system) > 64 * 1024)) throw new JobError("rejected", "invalid system prompt.");
76
+ if (job.model && (typeof job.model !== "string" || !MODEL.test(job.model))) throw new JobError("rejected", "invalid model name.");
77
+ if (!Number.isInteger(job.timeout) || job.timeout < 10 || job.timeout > 600) throw new JobError("rejected", "invalid timeout.");
78
+ if (job.prompt.startsWith("-")) throw new JobError("rejected", "a prompt may not start with a dash."); // never reads as a flag for agy/gemini
79
+ }
80
+
81
+ /** Argument array + stdin for one call. `root` is a fresh empty folder. Tools stay off: the CLI only writes text. */
82
+ export function buildArgs(kind, job, root, binary = KINDS[kind].command) {
83
+ const model = job.model ? [kind === "codex" || kind === "gemini" ? "-m" : "--model", job.model] : [];
84
+ const full = job.system ? `${job.system}\n\n${job.prompt}` : job.prompt;
85
+ if (kind === "claude") {
86
+ const mcp = path.join(root, "empty-mcp.json");
87
+ writeFileSync(mcp, '{"mcpServers":{}}');
88
+ return {
89
+ argv: [binary, "-p", ...model, "--output-format", "json", "--tools", "", "--disallowedTools", "mcp__*", "--strict-mcp-config", "--mcp-config", mcp,
90
+ "--no-session-persistence", "--disable-slash-commands", "--permission-mode", "plan", "--setting-sources", "", "--settings", '{"disableAllHooks":true}',
91
+ ...(job.system ? ["--system-prompt", job.system] : [])],
92
+ stdin: job.prompt,
93
+ };
94
+ }
95
+ if (kind === "codex") {
96
+ const last = path.join(root, "last-message.txt");
97
+ return {
98
+ argv: [binary, "exec", ...model, "--json", "--sandbox", "read-only", "--ephemeral", "--skip-git-repo-check", "--ignore-user-config", "--ignore-rules", "-c", 'approval_policy="never"', "-o", last, "-"],
99
+ stdin: full,
100
+ after: () => { try { return readFileSync(last, "utf8"); } catch { return ""; } },
101
+ };
102
+ }
103
+ if (kind === "gemini") return { argv: [binary, "-p", GEMINI_INSTRUCTION, ...model, "-o", "json", "--approval-mode", "plan"], stdin: full };
104
+ return { argv: [binary, "--print", full, ...model, "--output-format", "json", "--mode", "plan", "--sandbox", "--disable-slash-commands", "--print-timeout", `${job.timeout}s`], stdin: "" };
105
+ }
106
+
107
+ const safeJson = (s) => { try { return JSON.parse(s); } catch { return null; } };
108
+
109
+ /** The answer text (and usage when the CLI reports it) out of a finished process. */
110
+ export function parseOutput(kind, { stdout, stderr, code }, lastMessage = "") {
111
+ let text = "", model, tokensIn, tokensOut;
112
+ if (kind === "claude") {
113
+ let j = safeJson(stdout.trim());
114
+ if (Array.isArray(j)) j = j.find((e) => e?.type === "result") ?? null;
115
+ if (j?.is_error) throw new JobError("cli_failed", String(j.result ?? "claude reported an error").slice(0, 300));
116
+ text = typeof j?.result === "string" ? j.result : "";
117
+ tokensIn = j?.usage?.input_tokens; tokensOut = j?.usage?.output_tokens;
118
+ model = Object.keys(j?.modelUsage ?? {})[0];
119
+ } else if (kind === "codex") {
120
+ for (const line of stdout.split("\n")) {
121
+ const e = safeJson(line);
122
+ if (e?.type === "item.completed" && e.item?.type === "agent_message" && typeof e.item.text === "string") text = e.item.text;
123
+ if (e?.type === "turn.completed" && e.usage) { tokensIn = e.usage.input_tokens; tokensOut = e.usage.output_tokens; }
124
+ if (e?.type === "thread.started" && typeof e.model === "string") model = e.model;
125
+ }
126
+ if (lastMessage.trim()) text = lastMessage;
127
+ } else {
128
+ const j = safeJson(stdout.trim());
129
+ if (kind === "agy" && j?.status && j.status !== "SUCCESS") throw new JobError("cli_failed", String(j.error ?? j.message ?? j.status).slice(0, 300));
130
+ text = typeof j?.response === "string" ? j.response : typeof j?.result === "string" ? j.result : "";
131
+ if (kind === "gemini" && j?.stats?.models) { const m = Object.entries(j.stats.models)[0]; if (m) { model = m[0]; tokensIn = m[1]?.tokens?.prompt; tokensOut = m[1]?.tokens?.candidates; } }
132
+ }
133
+ text = text.trim();
134
+ if (!text) {
135
+ if (code !== 0) throw new JobError("cli_failed", `${KINDS[kind].label} exited with ${code}: ${(stderr.trim() || stdout.trim()).slice(-300) || "no output"}`);
136
+ text = stdout.trim();
137
+ if (!text) throw new JobError("invalid_output", `${KINDS[kind].label} returned no text.`);
138
+ }
139
+ const n = (v) => (typeof v === "number" && Number.isFinite(v) ? v : undefined);
140
+ return { text, model, tokensIn: n(tokensIn), tokensOut: n(tokensOut) };
141
+ }
142
+
143
+ /** Run argv with no shell, in its own process group, with wall/idle timeouts and output caps. */
144
+ export function runProcess(argv, { cwd, env, input = "", timeoutMs = 60_000, idleMs = IDLE_MS, signal } = {}) {
145
+ return new Promise((resolve, reject) => {
146
+ let child;
147
+ try { child = spawn(argv[0], argv.slice(1), { cwd, env, shell: false, detached: process.platform !== "win32", windowsHide: true, stdio: ["pipe", "pipe", "pipe"] }); }
148
+ catch { return reject(new JobError("unavailable", "the CLI could not be started.")); }
149
+ const out = [], err = [];
150
+ let outBytes = 0, errBytes = 0, failure = null, last = Date.now();
151
+ const kill = () => {
152
+ try { process.platform === "win32" ? child.kill() : process.kill(-child.pid, "SIGTERM"); } catch { /* gone */ }
153
+ setTimeout(() => { try { process.platform === "win32" ? child.kill("SIGKILL") : process.kill(-child.pid, "SIGKILL"); } catch { /* gone */ } }, 5000).unref();
154
+ };
155
+ const fail = (code, message) => { if (failure) return; failure = new JobError(code, message); kill(); };
156
+ const wall = setTimeout(() => fail("timeout", `the CLI took longer than ${Math.round(timeoutMs / 1000)} s.`), timeoutMs);
157
+ const idle = setInterval(() => { if (Date.now() - last > idleMs) fail("idle_timeout", `the CLI printed nothing for ${Math.round(idleMs / 1000)} s.`); }, 1000);
158
+ const onAbort = () => fail("cancelled", "the call was cancelled.");
159
+ signal?.addEventListener("abort", onAbort, { once: true });
160
+ child.stdout.on("data", (chunk) => { last = Date.now(); if ((outBytes += chunk.length) > MAX_STDOUT) return fail("output_limit", "the CLI printed too much."); out.push(chunk); });
161
+ child.stderr.on("data", (chunk) => { last = Date.now(); if ((errBytes += chunk.length) > MAX_STDERR) return fail("output_limit", "the CLI printed too much."); err.push(chunk); });
162
+ child.stdin.on("error", () => {});
163
+ child.stdin.end(input);
164
+ child.on("error", () => fail("unavailable", "the CLI could not be started."));
165
+ child.on("close", (code, sig) => {
166
+ clearTimeout(wall); clearInterval(idle); signal?.removeEventListener("abort", onAbort);
167
+ if (process.platform !== "win32") try { process.kill(-child.pid, "SIGKILL"); } catch { /* group already gone */ }
168
+ if (failure) return reject(failure);
169
+ resolve({ stdout: Buffer.concat(out).toString("utf8"), stderr: Buffer.concat(err).toString("utf8"), code: code ?? (sig ? 128 : 1) });
170
+ });
171
+ });
172
+ }
173
+
174
+ /** One job end to end in a throwaway folder. */
175
+ export async function runJob(job, { binaries, env = ownEnv(), signal, run = runProcess } = {}) {
176
+ checkJob(job);
177
+ const binary = binaries[job.kind];
178
+ if (!binary) throw new JobError("unavailable", `${KINDS[job.kind].label} is not installed on this computer.`);
179
+ const root = mkdtempSync(path.join(os.tmpdir(), "seoanything-"));
180
+ try {
181
+ const { argv, stdin, after } = buildArgs(job.kind, job, root, binary);
182
+ const res = await run(argv, { cwd: root, env, input: stdin, timeoutMs: job.timeout * 1000, signal });
183
+ return parseOutput(job.kind, res, after?.());
184
+ } finally { rmSync(root, { recursive: true, force: true }); }
185
+ }
186
+
187
+ /** Connect and serve until the user stops it or the server disconnects this computer. Resolves with the reason. */
188
+ export async function connect({ server, token, log = console.error, hostname = os.hostname(), signal, WebSocketImpl = globalThis.WebSocket } = {}) {
189
+ if (!WebSocketImpl) throw new CliError("seoanything connect needs Node 22 or newer (built-in WebSocket).", 1);
190
+ const api = client({ server, token });
191
+ const cfg = loadConfig();
192
+ const deviceId = cfg.deviceId ?? randomBytes(12).toString("hex");
193
+ if (!cfg.deviceId) saveConfig({ ...cfg, deviceId });
194
+ const env = ownEnv();
195
+ const found = await detect(env);
196
+ if (!found.length) throw new CliError("no AI CLI found on PATH. install claude, codex, gemini or agy, sign in to it once, then run connect again.", 1);
197
+ for (const f of found) log(`✓ found ${KINDS[f.kind].label} ${f.version} at ${f.path}`);
198
+ const binaries = Object.fromEntries(found.map((f) => [f.kind, f.path]));
199
+ const jobs = new Map();
200
+ let socket, attempt = 0, stopped = false, finish;
201
+ const done = new Promise((r) => (finish = r));
202
+ const stop = (reason) => { if (stopped) return; stopped = true; for (const j of jobs.values()) j.abort(); try { socket?.close(1000); } catch { /* closed */ } finish(reason); };
203
+ signal?.addEventListener("abort", () => stop("connector closed. your chats fall back to the cloud models until you run connect again."), { once: true });
204
+ const send = (ws, m) => { if (ws.readyState === 1) ws.send(JSON.stringify(m)); };
205
+
206
+ async function startJob(ws, job) {
207
+ if (typeof job.id !== "string" || jobs.has(job.id)) return;
208
+ const label = KINDS[job.kind]?.label ?? "the CLI";
209
+ if (jobs.size >= MAX_JOBS) return send(ws, { type: "failed", id: job.id, code: "busy", message: `this computer is already running ${MAX_JOBS} calls.` });
210
+ const ac = new AbortController();
211
+ jobs.set(job.id, ac);
212
+ const t0 = Date.now();
213
+ log(`→ ${label}: running a call…`);
214
+ try {
215
+ const r = await runJob(job, { binaries, env, signal: ac.signal });
216
+ send(ws, { type: "result", id: job.id, ...r });
217
+ log(`✓ ${label} answered in ${((Date.now() - t0) / 1000).toFixed(1)} s`);
218
+ } catch (e) {
219
+ if (e.code === "cancelled") return;
220
+ send(ws, { type: "failed", id: job.id, code: e instanceof JobError ? e.code : "cli_failed", message: String(e.message ?? "the CLI failed").slice(0, 300) });
221
+ log(`✗ ${label}: ${e.message}`);
222
+ } finally { jobs.delete(job.id); }
223
+ }
224
+
225
+ async function open() {
226
+ if (stopped) return;
227
+ let url;
228
+ try { ({ url } = await api.post("/cli/ticket")); }
229
+ catch (e) { if (e.exitCode === 3) return stop(e.message); log(`! ${e.message} retrying in 10 s.`); setTimeout(open, 10_000); return; }
230
+ const ws = new WebSocketImpl(url);
231
+ socket = ws;
232
+ let pinger;
233
+ ws.addEventListener("open", () => {
234
+ ws.send(JSON.stringify({ type: "hello", deviceId, name: hostname.slice(0, 80), platform: process.platform, version: VERSION, clis: found.map((f) => ({ kind: f.kind, version: f.version })) }));
235
+ pinger = setInterval(() => ws.readyState === 1 && ws.send("ping"), 30_000);
236
+ });
237
+ ws.addEventListener("message", (ev) => {
238
+ let m; try { m = JSON.parse(String(ev.data)); } catch { return; }
239
+ if (m.type === "welcome") { attempt = 0; log(`✓ linked to ${server} as "${hostname}". leave this window open; chats and blog posts can now use your CLI.`); }
240
+ else if (m.type === "run") startJob(ws, m);
241
+ else if (m.type === "cancel") jobs.get(m.id)?.abort();
242
+ else if (m.type === "revoked") stop("this computer was disconnected in SEOAnything settings.");
243
+ });
244
+ ws.addEventListener("close", (ev) => {
245
+ clearInterval(pinger);
246
+ if (socket !== ws || stopped) return;
247
+ for (const j of jobs.values()) j.abort();
248
+ jobs.clear();
249
+ if (ev.code === 4401) return stop("this computer was disconnected in SEOAnything settings. run connect again to link it.");
250
+ if (ev.code === 4400) return stop("the server did not accept this connector. update it: npm i -g seoanything-cli@latest");
251
+ if (ev.code === 4409) return stop("another connector took over on this computer.");
252
+ const wait = Math.min(30_000, 1000 * 2 ** Math.min(attempt++, 5));
253
+ log(`connection lost (${ev.code}). trying again in ${Math.round(wait / 1000)} s.`);
254
+ setTimeout(open, wait);
255
+ });
256
+ ws.addEventListener("error", () => {});
257
+ }
258
+ await open();
259
+ return done;
260
+ }