seoanything-cli 0.0.0-stage → 2.1.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/README.md +57 -2
- package/bin/seoanything.js +4 -0
- package/dist/tools.mjs +211 -0
- package/package.json +56 -4
- package/src/api.js +50 -0
- package/src/cli.js +216 -0
- package/src/cli.test.js +39 -0
- package/src/config.js +30 -0
- package/src/config.test.js +27 -0
- package/src/connect.js +285 -0
- package/src/connect.test.js +109 -0
- package/src/login.js +42 -0
- package/src/mcp.js +31 -0
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { afterEach, describe, expect, it } from "vitest";
|
|
5
|
+
import { buildArgs, checkJob, deltaOf, ownEnv, parseOutput, runJob } from "./connect.js";
|
|
6
|
+
|
|
7
|
+
const job = { kind: "claude", prompt: "say ok", system: "be brief", timeout: 60 };
|
|
8
|
+
let root;
|
|
9
|
+
afterEach(() => root && rmSync(root, { recursive: true, force: true }));
|
|
10
|
+
|
|
11
|
+
describe("ownEnv", () => {
|
|
12
|
+
it("passes PATH and home, drops API keys and nested-session flags", () => {
|
|
13
|
+
const e = ownEnv({ PATH: "/bin", HOME: "/h", ANTHROPIC_API_KEY: "x", CLAUDECODE: "1", OPENAI_API_KEY: "y" }, "darwin");
|
|
14
|
+
expect(e).toEqual({ PATH: "/bin", HOME: "/h", NO_COLOR: "1", TERM: "dumb" });
|
|
15
|
+
});
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
describe("buildArgs", () => {
|
|
19
|
+
it("runs claude with tools off, hooks off and the system prompt as a flag", () => {
|
|
20
|
+
root = mkdtempSync(path.join(os.tmpdir(), "t-"));
|
|
21
|
+
const { argv, stdin } = buildArgs("claude", job, root, "/bin/claude");
|
|
22
|
+
expect(argv.slice(0, 2)).toEqual(["/bin/claude", "-p"]);
|
|
23
|
+
expect(argv).toContain("--tools"); expect(argv[argv.indexOf("--tools") + 1]).toBe("");
|
|
24
|
+
expect(argv).toContain("--no-session-persistence"); expect(argv).toContain("--system-prompt");
|
|
25
|
+
expect(argv).not.toContain("--model"); expect(stdin).toBe("say ok");
|
|
26
|
+
});
|
|
27
|
+
it("gives codex the whole prompt on stdin, read-only sandbox, and a last-message file", () => {
|
|
28
|
+
root = mkdtempSync(path.join(os.tmpdir(), "t-"));
|
|
29
|
+
const { argv, stdin, after } = buildArgs("codex", { ...job, kind: "codex", model: "gpt-5" }, root, "codex");
|
|
30
|
+
expect(argv).toEqual(expect.arrayContaining(["exec", "-m", "gpt-5", "--sandbox", "read-only", "--ephemeral", "-"]));
|
|
31
|
+
expect(stdin).toBe("be brief\n\nsay ok"); expect(after()).toBe("");
|
|
32
|
+
});
|
|
33
|
+
it("passes agy the prompt as an argument, streaming, sandboxed, with a print timeout and no plan mode", () => {
|
|
34
|
+
const { argv, stdin } = buildArgs("agy", { ...job, kind: "agy" }, "/tmp", "agy");
|
|
35
|
+
expect(argv).toEqual(expect.arrayContaining(["--print", "be brief\n\nsay ok", "--output-format", "stream-json", "--sandbox", "--print-timeout", "60s"]));
|
|
36
|
+
expect(argv).not.toContain("--mode");
|
|
37
|
+
expect(stdin).toBe("");
|
|
38
|
+
});
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
describe("streaming output", () => {
|
|
42
|
+
const claude = ['{"type":"system","subtype":"init"}', '{"type":"stream_event","event":{"type":"content_block_delta","delta":{"type":"thinking_delta","thinking":"hmm"}}}', '{"type":"stream_event","event":{"type":"content_block_delta","delta":{"type":"text_delta","text":"o"}}}', '{"type":"stream_event","event":{"type":"content_block_delta","delta":{"type":"text_delta","text":"k"}}}', '{"type":"result","is_error":false,"result":"ok","usage":{"input_tokens":4,"output_tokens":1}}'];
|
|
43
|
+
const agy = ['{"event":"init"}', '{"event":"step_update","step_update":{"step_type":"agent_response","state":"ACTIVE","text_delta":"he"}}', '{"event":"step_update","step_update":{"step_type":"agent_response","state":"DONE","text_delta":"y"}}', '{"event":"result","result":{"status":"SUCCESS","response":"hey","usage":{"input_tokens":9,"output_tokens":2}}}'];
|
|
44
|
+
it("pulls answer text and reasoning out of claude and agy lines, nothing out of the rest", () => {
|
|
45
|
+
expect(claude.map((l) => deltaOf("claude", l))).toEqual([null, { thinking: "hmm" }, { text: "o" }, { text: "k" }, null]);
|
|
46
|
+
expect(agy.map((l) => deltaOf("agy", l))).toEqual([null, { text: "he" }, { text: "y" }, null]);
|
|
47
|
+
expect(deltaOf("codex", '{"type":"item.completed"}')).toBeNull();
|
|
48
|
+
});
|
|
49
|
+
it("reads the final answer and usage from stream-json", () => {
|
|
50
|
+
expect(parseOutput("claude", { stdout: claude.join("\n"), stderr: "", code: 0 })).toMatchObject({ text: "ok", tokensIn: 4, tokensOut: 1 });
|
|
51
|
+
expect(parseOutput("agy", { stdout: agy.join("\n"), stderr: "", code: 0 })).toMatchObject({ text: "hey", tokensIn: 9, tokensOut: 2 });
|
|
52
|
+
});
|
|
53
|
+
it("hands runJob's deltas over line by line, even when a chunk splits a line", async () => {
|
|
54
|
+
const out = claude.join("\n") + "\n";
|
|
55
|
+
const fake = async (_argv, { onStdout }) => { onStdout(Buffer.from(out.slice(0, 150))); onStdout(Buffer.from(out.slice(150))); return { stdout: out, stderr: "", code: 0 }; };
|
|
56
|
+
const seen = [];
|
|
57
|
+
const r = await runJob({ ...job, kind: "claude" }, { binaries: { claude: "/bin/claude" }, run: fake, onDelta: (d) => seen.push(d) });
|
|
58
|
+
expect(seen).toEqual([{ thinking: "hmm" }, { text: "o" }, { text: "k" }]);
|
|
59
|
+
expect(r.text).toBe("ok");
|
|
60
|
+
});
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
describe("checkJob", () => {
|
|
64
|
+
it("refuses unknown kinds, flag-like prompts and bad timeouts", () => {
|
|
65
|
+
expect(() => checkJob({ ...job, kind: "bash" })).toThrow("unknown CLI");
|
|
66
|
+
expect(() => checkJob({ ...job, prompt: "--help" })).toThrow("dash");
|
|
67
|
+
expect(() => checkJob({ ...job, timeout: 5 })).toThrow("timeout");
|
|
68
|
+
expect(() => checkJob({ ...job, model: "x y" })).toThrow("model");
|
|
69
|
+
expect(() => checkJob(job)).not.toThrow();
|
|
70
|
+
});
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
describe("parseOutput", () => {
|
|
74
|
+
it("reads claude json with usage and model", () => {
|
|
75
|
+
const r = parseOutput("claude", { stdout: JSON.stringify({ type: "result", is_error: false, result: " ok ", usage: { input_tokens: 12, output_tokens: 3 }, modelUsage: { "claude-x": {} } }), stderr: "", code: 0 });
|
|
76
|
+
expect(r).toEqual({ text: "ok", model: "claude-x", tokensIn: 12, tokensOut: 3 });
|
|
77
|
+
});
|
|
78
|
+
it("surfaces a claude error", () => {
|
|
79
|
+
expect(() => parseOutput("claude", { stdout: JSON.stringify({ is_error: true, result: "no credits" }), stderr: "", code: 1 })).toThrow("no credits");
|
|
80
|
+
});
|
|
81
|
+
it("takes the codex last-message file over the event stream, with usage from turn.completed", () => {
|
|
82
|
+
const stdout = ['{"type":"thread.started","model":"gpt-5"}', '{"type":"item.completed","item":{"type":"agent_message","text":"from events"}}', '{"type":"turn.completed","usage":{"input_tokens":5,"output_tokens":2}}'].join("\n");
|
|
83
|
+
expect(parseOutput("codex", { stdout, stderr: "", code: 0 }, "from file\n")).toEqual({ text: "from file", model: "gpt-5", tokensIn: 5, tokensOut: 2 });
|
|
84
|
+
expect(parseOutput("codex", { stdout, stderr: "", code: 0 }, "").text).toBe("from events");
|
|
85
|
+
});
|
|
86
|
+
it("reads agy responses and fails on agy errors", () => {
|
|
87
|
+
expect(parseOutput("agy", { stdout: '{"status":"SUCCESS","response":"hi"}', stderr: "", code: 0 }).text).toBe("hi");
|
|
88
|
+
expect(() => parseOutput("agy", { stdout: '{"status":"ERROR","error":"quota"}', stderr: "", code: 1 })).toThrow("quota");
|
|
89
|
+
expect(() => checkJob({ kind: "gemini", prompt: "hi", timeout: 60 })).toThrow("unknown CLI");
|
|
90
|
+
});
|
|
91
|
+
it("falls back to raw stdout, and reports the exit code when there is none", () => {
|
|
92
|
+
expect(parseOutput("claude", { stdout: "plain text", stderr: "", code: 0 }).text).toBe("plain text");
|
|
93
|
+
expect(() => parseOutput("claude", { stdout: "", stderr: "boom", code: 2 })).toThrow("exited with 2: boom");
|
|
94
|
+
});
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
describe("runJob", () => {
|
|
98
|
+
it("runs the binary in a throwaway folder with the own-login env and parses its output", async () => {
|
|
99
|
+
const calls = [];
|
|
100
|
+
const run = async (argv, opts) => { calls.push({ argv, opts }); return { stdout: JSON.stringify({ result: "done" }), stderr: "", code: 0 }; };
|
|
101
|
+
const r = await runJob(job, { binaries: { claude: "/bin/claude" }, env: { PATH: "/bin", NO_COLOR: "1" }, run });
|
|
102
|
+
expect(r.text).toBe("done");
|
|
103
|
+
expect(calls[0].argv[0]).toBe("/bin/claude"); expect(calls[0].opts.env).toEqual({ PATH: "/bin", NO_COLOR: "1" }); expect(calls[0].opts.timeoutMs).toBe(60_000);
|
|
104
|
+
expect(calls[0].opts.cwd).toMatch(/seoanything-/);
|
|
105
|
+
});
|
|
106
|
+
it("refuses a CLI that is not installed", async () => {
|
|
107
|
+
await expect(runJob({ ...job, kind: "codex" }, { binaries: { claude: "/bin/claude" }, run: async () => ({}) })).rejects.toThrow("not installed");
|
|
108
|
+
});
|
|
109
|
+
});
|
package/src/login.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// Device-flow login exactly per TRD §17.3, or store an API key for CI.
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
import { CliError } from "./api.js";
|
|
4
|
+
import { saveConfig, loadConfig } from "./config.js";
|
|
5
|
+
|
|
6
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
7
|
+
const post = (url, body) => fetch(url, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
|
|
8
|
+
|
|
9
|
+
export function openBrowser(url) {
|
|
10
|
+
const [cmd, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", ["/c", "start", "", url]] : ["xdg-open", [url]];
|
|
11
|
+
return new Promise((resolve, reject) => { const p = spawn(cmd, args, { stdio: "ignore", detached: true }); p.on("error", reject); p.on("spawn", () => { p.unref(); resolve(); }); });
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export async function login({ server, apiKey, noBrowser, log = console.error }) {
|
|
15
|
+
if (apiKey) {
|
|
16
|
+
saveConfig({ ...loadConfig(), server, apiKey, token: undefined });
|
|
17
|
+
return { server, method: "api_key" };
|
|
18
|
+
}
|
|
19
|
+
const startRes = await post(`${server}/api/auth/device/code`, { client_id: "seoanything-cli", scope: "openid profile email" });
|
|
20
|
+
if (!startRes.ok) throw new CliError(`device login is not available on ${server} (${startRes.status})`, 5);
|
|
21
|
+
const start = await startRes.json();
|
|
22
|
+
const url = start.verification_uri_complete ?? `${server}${start.verification_uri}?user_code=${start.user_code}`;
|
|
23
|
+
log(`\nOpen ${url}\nand confirm code: ${start.user_code}\n`);
|
|
24
|
+
if (!noBrowser) await openBrowser(url).catch(() => {});
|
|
25
|
+
let interval = (start.interval ?? 5) * 1000;
|
|
26
|
+
const deadline = Date.now() + start.expires_in * 1000;
|
|
27
|
+
while (Date.now() < deadline) {
|
|
28
|
+
await sleep(interval);
|
|
29
|
+
const r = await post(`${server}/api/auth/device/token`, { grant_type: "urn:ietf:params:oauth:grant-type:device_code", device_code: start.device_code, client_id: "seoanything-cli" });
|
|
30
|
+
if (r.ok) {
|
|
31
|
+
const { access_token } = await r.json();
|
|
32
|
+
const me = await fetch(`${server}/api/v1/me`, { headers: { authorization: `Bearer ${access_token}` } }).then((x) => (x.ok ? x.json() : null)).catch(() => null);
|
|
33
|
+
saveConfig({ ...loadConfig(), server, token: access_token, apiKey: undefined, user: me?.user ? { id: me.user.id, email: me.user.email } : undefined });
|
|
34
|
+
return { server, method: "device", user: me?.user };
|
|
35
|
+
}
|
|
36
|
+
const { error } = await r.json().catch(() => ({ error: "server_error" }));
|
|
37
|
+
if (error === "authorization_pending") continue;
|
|
38
|
+
if (error === "slow_down") { interval += 5000; continue; }
|
|
39
|
+
throw new CliError(error === "access_denied" ? "Login was denied." : "Login code expired. Run login again.", 3);
|
|
40
|
+
}
|
|
41
|
+
throw new CliError("Login timed out.", 3);
|
|
42
|
+
}
|
package/src/mcp.js
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// Local stdio MCP server (TRD §16.4): tools from @seoanything/tools with surface "local"; stdout is the protocol channel.
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import { CliError } from "./api.js";
|
|
4
|
+
import { resolveCreds } from "./config.js";
|
|
5
|
+
|
|
6
|
+
export const VERSION = "2.1.0";
|
|
7
|
+
|
|
8
|
+
export async function mcp(flags) {
|
|
9
|
+
const [major, minor] = process.versions.node.split(".").map(Number);
|
|
10
|
+
if (major < 22 || (major === 22 && minor < 18)) throw new CliError(`seoanything mcp needs Node >= 22.18 (you have ${process.versions.node}). upgrade at https://nodejs.org`, 1);
|
|
11
|
+
console.log = (...a) => console.error(...a);
|
|
12
|
+
let McpServer, StdioServerTransport, tools;
|
|
13
|
+
try {
|
|
14
|
+
({ McpServer } = await import("@modelcontextprotocol/sdk/server/mcp.js"));
|
|
15
|
+
({ StdioServerTransport } = await import("@modelcontextprotocol/sdk/server/stdio.js"));
|
|
16
|
+
} catch { throw new CliError("missing optional dependency. run: npm i -g @modelcontextprotocol/sdk", 1); }
|
|
17
|
+
// published package: the tools (+core) bundle built by `pnpm run build`; monorepo checkout: the TypeScript source (Node 22.18+ strips types)
|
|
18
|
+
try { tools = await import("../dist/tools.mjs").catch(() => import("@seoanything/tools")); } catch (e) { throw new CliError(`cannot load the SEO tools: ${e.message}`, 1); }
|
|
19
|
+
const v1 = await import("seoanything-v1");
|
|
20
|
+
const { server, token } = resolveCreds(flags);
|
|
21
|
+
const api = token ? tools.httpApi(server, token) : new Proxy({}, { get: () => async () => { throw new Error("not logged in: run `seoanything login` (or set SEOANYTHING_API_KEY) to use cloud tools"); } });
|
|
22
|
+
const srv = new McpServer({ name: "seoanything-local", version: VERSION });
|
|
23
|
+
tools.registerAll(srv, {
|
|
24
|
+
surface: "local",
|
|
25
|
+
api,
|
|
26
|
+
local: { cwd: process.cwd(), runAudit: v1.runAudit, generateLlmsTxt: v1.generateLlmsTxt, generateSitemap: v1.generateSitemap, installSkills: v1.installSkills, chdir: (d) => process.chdir(d), readFile: (p) => fs.readFileSync(p, "utf8"), rm: (p) => fs.rmSync(p, { force: true }) },
|
|
27
|
+
});
|
|
28
|
+
await srv.connect(new StdioServerTransport());
|
|
29
|
+
console.error(`seoanything mcp ready (${token ? "cloud + local tools" : "local tools only — run \`seoanything login\` for cloud tools"})`);
|
|
30
|
+
await new Promise(() => {}); // run until the client closes stdin
|
|
31
|
+
}
|