seoanything-cli 2.1.0 → 2.3.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 +10 -0
- package/package.json +1 -1
- package/src/cli.js +24 -6
- package/src/connect.js +97 -24
- package/src/connect.test.js +98 -3
- package/src/mcp.js +1 -1
package/README.md
CHANGED
|
@@ -45,6 +45,16 @@ seoanything connect
|
|
|
45
45
|
|
|
46
46
|
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.
|
|
47
47
|
|
|
48
|
+
### Without a terminal: a setup prompt for your AI app
|
|
49
|
+
|
|
50
|
+
Settings › ai engines › connect a computer › "from your AI app" gives you a setup prompt. Paste it into Claude Code, Codex or Antigravity on the computer you want to link (desktop app, editor or terminal session); it runs:
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
npx -y seoanything-cli@latest connect --code <setup code> --background
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
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.
|
|
57
|
+
|
|
48
58
|
## MCP
|
|
49
59
|
|
|
50
60
|
```json
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "seoanything-cli",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.3.0",
|
|
4
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",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
package/src/cli.js
CHANGED
|
@@ -16,6 +16,7 @@ const OPTS = {
|
|
|
16
16
|
server: { type: "string" }, "api-key": { type: "string" }, "no-browser": { type: "boolean" }, local: { type: "boolean" }, cloud: { type: "boolean" }, yes: { type: "boolean" },
|
|
17
17
|
geo: { type: "string" }, hl: { type: "string" }, limit: { type: "string" }, hours: { type: "string" }, period: { type: "string" }, day: { type: "string" },
|
|
18
18
|
source: { type: "string" }, window: { type: "string" }, language: { type: "string" }, topic: { type: "string" },
|
|
19
|
+
code: { type: "string" }, background: { type: "boolean" },
|
|
19
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" },
|
|
20
21
|
};
|
|
21
22
|
|
|
@@ -42,6 +43,7 @@ usage: seoanything <command> [options]
|
|
|
42
43
|
audit <path|url> [--cloud] local auditor, or cloud audit saved to history
|
|
43
44
|
mcp local stdio MCP server
|
|
44
45
|
connect [--no-browser] run your own claude/codex/agy for your web chats and posts
|
|
46
|
+
connect --code <setup code> [--background] link with a setup code from settings › ai engines, no login
|
|
45
47
|
config get|set <key> [value] server, defaultGeo, defaultModel …
|
|
46
48
|
init | install | schema | llms-txt | sitemap | menu seoanything v1 commands, unchanged
|
|
47
49
|
|
|
@@ -126,17 +128,33 @@ export async function main(argv, io = { out: console.log, err: console.error })
|
|
|
126
128
|
case "mcp": { const { mcp } = await import("./mcp.js"); await mcp(flags); return EXIT.ok; }
|
|
127
129
|
case "connect": {
|
|
128
130
|
// link this computer: the web app's chats and blog posts can then run on the AI CLIs installed here
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
131
|
+
const { connect, detect, ownEnv, pair, startBackground } = await import("./connect.js");
|
|
132
|
+
const saved = loadConfig().connector;
|
|
133
|
+
let deviceToken = saved?.server === creds.server ? saved.token : null;
|
|
134
|
+
if (flags.code) {
|
|
135
|
+
// checked first, so a setup code is not spent on a computer that can't serve
|
|
136
|
+
if (!globalThis.WebSocket) throw new CliError("seoanything connect needs Node 22 or newer (built-in WebSocket).", EXIT.error);
|
|
137
|
+
if (!(await detect(ownEnv())).length) throw new CliError("no AI CLI found on PATH. install claude, codex or agy, sign in to it once, then use a fresh setup prompt.", EXIT.error);
|
|
138
|
+
deviceToken = await pair({ server: creds.server, code: flags.code });
|
|
139
|
+
saveConfig({ ...loadConfig(), connector: { server: creds.server, token: deviceToken } });
|
|
140
|
+
io.err(c("32", "✓ paired this computer with your SEOAnything account."));
|
|
141
|
+
}
|
|
142
|
+
let token = deviceToken ? null : creds.token;
|
|
143
|
+
if (!deviceToken && !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; }
|
|
144
|
+
if (flags.background) {
|
|
145
|
+
const bg = startBackground(creds.server);
|
|
146
|
+
print({ ok: true, pid: bg.pid, log: bg.log }, c("32", `✓ the connector now runs in the background (pid ${bg.pid}, log ${bg.log}). you can close this window; stop it with "disconnect" in settings › ai engines.`));
|
|
147
|
+
return EXIT.ok;
|
|
148
|
+
}
|
|
132
149
|
const ac = new AbortController();
|
|
133
150
|
for (const sig of ["SIGINT", "SIGTERM"]) process.on(sig, () => ac.abort());
|
|
134
|
-
|
|
151
|
+
const onUnlinked = () => { const cfg = loadConfig(); delete cfg.connector; saveConfig(cfg); };
|
|
152
|
+
io.err(connectReasonColor(c, await connect({ server: creds.server, token, deviceToken, onUnlinked, log: io.err, signal: ac.signal })));
|
|
135
153
|
return EXIT.ok;
|
|
136
154
|
}
|
|
137
155
|
case "config": {
|
|
138
156
|
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; }
|
|
157
|
+
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; }
|
|
140
158
|
if (p.sub === "set") {
|
|
141
159
|
const [, k, v] = p.positionals; needArg(k && v, "seoanything config set <key> <value>");
|
|
142
160
|
if (k === "server") cfg.server = v; else (cfg.defaults ??= {})[k.replace(/^default/, "").toLowerCase()] = v;
|
|
@@ -152,7 +170,7 @@ export async function main(argv, io = { out: console.log, err: console.error })
|
|
|
152
170
|
}
|
|
153
171
|
}
|
|
154
172
|
|
|
155
|
-
const connectReasonColor = (c, reason) => c(/disconnected|not accept|took over/.test(reason) ? "33" : "2", reason);
|
|
173
|
+
const connectReasonColor = (c, reason) => c(/disconnected|not accept|took over|no longer linked/.test(reason) ? "33" : "2", reason);
|
|
156
174
|
|
|
157
175
|
const fmt = (n) => (n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : n >= 1e3 ? `${Math.round(n / 1e3)}K` : String(n ?? ""));
|
|
158
176
|
|
package/src/connect.js
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
// `seoanything connect`: keep one outbound WebSocket to the cloud and run the AI CLIs installed on this computer
|
|
2
2
|
// (claude, codex, agy) 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
|
-
// (Node 22+ for the built-in WebSocket).
|
|
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
|
+
// (`connect --code`, which the settings page hands to your own AI app) that can only open this computer's link.
|
|
5
6
|
import { spawn } from "node:child_process";
|
|
6
7
|
import { randomBytes } from "node:crypto";
|
|
7
|
-
import { accessSync, constants, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
8
|
+
import { accessSync, closeSync, constants, mkdirSync, mkdtempSync, openSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
8
9
|
import os from "node:os";
|
|
9
10
|
import path from "node:path";
|
|
10
11
|
import { StringDecoder } from "node:string_decoder";
|
|
11
|
-
import { CliError, client } from "./api.js";
|
|
12
|
-
import { loadConfig, saveConfig } from "./config.js";
|
|
12
|
+
import { CliError, client, exitCodeFor } from "./api.js";
|
|
13
|
+
import { configDir, loadConfig, saveConfig } from "./config.js";
|
|
13
14
|
import { VERSION } from "./mcp.js";
|
|
14
15
|
|
|
15
16
|
export const KINDS = {
|
|
@@ -54,17 +55,37 @@ export function findBinary(command, env = process.env, platform = process.platfo
|
|
|
54
55
|
return null;
|
|
55
56
|
}
|
|
56
57
|
|
|
57
|
-
/** Installed CLIs with their versions. */
|
|
58
|
+
/** Installed CLIs with their versions and the models each offers, looked up side by side. */
|
|
58
59
|
export async function detect(env = ownEnv(), run = runProcess) {
|
|
59
|
-
const found = []
|
|
60
|
-
for (const [kind, { command }] of Object.entries(KINDS)) {
|
|
60
|
+
const found = await Promise.all(Object.entries(KINDS).map(async ([kind, { command }]) => {
|
|
61
61
|
const bin = findBinary(command, env);
|
|
62
|
-
if (!bin)
|
|
62
|
+
if (!bin) return null;
|
|
63
63
|
let version = "";
|
|
64
64
|
try { version = (await run([bin, "--version"], { env, timeoutMs: 20_000 })).stdout.trim().split("\n")[0].slice(0, 80); } catch { /* still usable */ }
|
|
65
|
-
|
|
66
|
-
}
|
|
67
|
-
return found;
|
|
65
|
+
return { kind, path: bin, version, models: await listModels(kind, bin, env, run) };
|
|
66
|
+
}));
|
|
67
|
+
return found.filter(Boolean);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// Claude Code has no command that lists models; these aliases always mean its latest of each.
|
|
71
|
+
const CLAUDE_MODELS = [{ id: "fable", label: "Fable (latest)" }, { id: "opus", label: "Opus (latest)" }, { id: "sonnet", label: "Sonnet (latest)" }, { id: "haiku", label: "Haiku (latest)" }];
|
|
72
|
+
|
|
73
|
+
/** The models a CLI offers, from its own list where it has one. None when the list can't be read; the app then offers the CLI's default. */
|
|
74
|
+
export async function listModels(kind, bin, env = ownEnv(), run = runProcess) {
|
|
75
|
+
if (kind === "claude") return CLAUDE_MODELS;
|
|
76
|
+
try { return parseModels(kind, (await run(kind === "codex" ? [bin, "debug", "models"] : [bin, "models"], { env, timeoutMs: 20_000 })).stdout); }
|
|
77
|
+
catch { return []; }
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** `codex debug models` prints a JSON catalog (hidden ones skipped, in its own order); `agy models` prints `id<TAB>name` lines. */
|
|
81
|
+
export function parseModels(kind, stdout) {
|
|
82
|
+
let rows = [];
|
|
83
|
+
if (kind === "codex") {
|
|
84
|
+
const list = safeJson(stdout.trim())?.models;
|
|
85
|
+
rows = (Array.isArray(list) ? list : []).filter((m) => m && m.visibility !== "hide").sort((a, b) => (a.priority ?? 99) - (b.priority ?? 99)).map((m) => ({ id: m.slug, label: m.display_name }));
|
|
86
|
+
} else rows = stdout.split("\n").map((l) => l.split("\t")).filter((c) => c.length >= 2).map(([id, label]) => ({ id: id.trim(), label: label.trim() }));
|
|
87
|
+
// only ids this connector would pass on as --model
|
|
88
|
+
return rows.filter((m) => typeof m.id === "string" && MODEL.test(m.id)).slice(0, 40).map((m) => ({ id: m.id, label: String(m.label || m.id).slice(0, 80) }));
|
|
68
89
|
}
|
|
69
90
|
|
|
70
91
|
export function checkJob(job) {
|
|
@@ -204,18 +225,66 @@ export async function runJob(job, { binaries, env = ownEnv(), signal, run = runP
|
|
|
204
225
|
} finally { rmSync(root, { recursive: true, force: true }); }
|
|
205
226
|
}
|
|
206
227
|
|
|
207
|
-
/**
|
|
208
|
-
export
|
|
228
|
+
/** This computer's stable id, made once and kept in the config file. */
|
|
229
|
+
export function deviceIdFor() {
|
|
230
|
+
const cfg = loadConfig();
|
|
231
|
+
if (cfg.deviceId) return cfg.deviceId;
|
|
232
|
+
const deviceId = randomBytes(12).toString("hex");
|
|
233
|
+
saveConfig({ ...cfg, deviceId });
|
|
234
|
+
return deviceId;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** POST without a login: the setup-code and computer-token endpoints authenticate with their body. */
|
|
238
|
+
async function postOpen(server, path, body) {
|
|
239
|
+
let res;
|
|
240
|
+
try { res = await fetch(`${server}/api/v1${path}`, { method: "POST", headers: { "content-type": "application/json", "user-agent": `seoanything-cli/${VERSION}` }, body: JSON.stringify(body) }); }
|
|
241
|
+
catch (e) { throw new CliError(`cannot reach ${server} (${e.cause?.code ?? e.message})`, 5); }
|
|
242
|
+
const j = await res.json().catch(() => ({}));
|
|
243
|
+
if (!res.ok) throw new CliError(j.detail ?? j.title ?? res.statusText, exitCodeFor(res.status), j);
|
|
244
|
+
return j;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** Spend a one-use setup code from the settings page; returns a token that can only open this computer's link. */
|
|
248
|
+
export async function pair({ server, code, deviceId = deviceIdFor(), hostname = os.hostname() }) {
|
|
249
|
+
const { token } = await postOpen(server, "/cli/pair", { code: String(code).trim(), deviceId, name: hostname.slice(0, 80), platform: process.platform, version: VERSION });
|
|
250
|
+
return token;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** Re-run `connect` detached from this terminal or AI app, logging to a file, and return at once. */
|
|
254
|
+
export function startBackground(server, { script = process.argv[1], spawnImpl = spawn } = {}) {
|
|
255
|
+
mkdirSync(configDir(), { recursive: true, mode: 0o700 });
|
|
256
|
+
const log = path.join(configDir(), "connect.log");
|
|
257
|
+
const out = openSync(log, "w", 0o600);
|
|
258
|
+
try {
|
|
259
|
+
const child = spawnImpl(process.execPath, [script, "connect", "--server", server], { detached: true, stdio: ["ignore", out, out], windowsHide: true });
|
|
260
|
+
child.unref();
|
|
261
|
+
return { pid: child.pid, log };
|
|
262
|
+
} finally { closeSync(out); }
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* Connect and serve until the user stops it or the server disconnects this computer. Resolves with the reason.
|
|
267
|
+
* `deviceToken` (from a setup code) wins over `token` (the user's login); `onUnlinked` runs when the cloud no longer accepts it.
|
|
268
|
+
*/
|
|
269
|
+
export async function connect({ server, token, deviceToken, onUnlinked, log = console.error, hostname = os.hostname(), signal, WebSocketImpl = globalThis.WebSocket } = {}) {
|
|
209
270
|
if (!WebSocketImpl) throw new CliError("seoanything connect needs Node 22 or newer (built-in WebSocket).", 1);
|
|
210
271
|
const api = client({ server, token });
|
|
211
|
-
const
|
|
212
|
-
const deviceId = cfg.deviceId ?? randomBytes(12).toString("hex");
|
|
213
|
-
if (!cfg.deviceId) saveConfig({ ...cfg, deviceId });
|
|
272
|
+
const deviceId = deviceIdFor();
|
|
214
273
|
const env = ownEnv();
|
|
215
|
-
|
|
274
|
+
let found = await detect(env);
|
|
216
275
|
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);
|
|
217
276
|
for (const f of found) log(`✓ found ${KINDS[f.kind].label} ${f.version} at ${f.path}`);
|
|
218
|
-
|
|
277
|
+
let binaries = Object.fromEntries(found.map((f) => [f.kind, f.path]));
|
|
278
|
+
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: ["rescan"] });
|
|
279
|
+
// asked from the settings page: pick up a CLI installed since this connector started, without a restart
|
|
280
|
+
async function rescan(ws) {
|
|
281
|
+
const now = await detect(env);
|
|
282
|
+
if (!now.length) return log("! looked again and found no AI CLI; keeping the ones already linked.");
|
|
283
|
+
found = now;
|
|
284
|
+
binaries = Object.fromEntries(found.map((f) => [f.kind, f.path]));
|
|
285
|
+
log(`✓ looked again: ${found.map((f) => KINDS[f.kind].label).join(", ")}`);
|
|
286
|
+
send(ws, hello());
|
|
287
|
+
}
|
|
219
288
|
const jobs = new Map();
|
|
220
289
|
let socket, attempt = 0, stopped = false, finish;
|
|
221
290
|
const done = new Promise((r) => (finish = r));
|
|
@@ -250,28 +319,32 @@ export async function connect({ server, token, log = console.error, hostname = o
|
|
|
250
319
|
async function open() {
|
|
251
320
|
if (stopped) return;
|
|
252
321
|
let url;
|
|
253
|
-
try { ({ url } = await api.post("/cli/ticket")); }
|
|
254
|
-
catch (e) {
|
|
322
|
+
try { ({ url } = deviceToken ? await postOpen(server, "/cli/device-ticket", { token: deviceToken, deviceId }) : await api.post("/cli/ticket")); }
|
|
323
|
+
catch (e) {
|
|
324
|
+
if (e.exitCode === 3) { if (deviceToken) onUnlinked?.(); return stop(e.message); }
|
|
325
|
+
log(`! ${e.message} retrying in 10 s.`); setTimeout(open, 10_000); return;
|
|
326
|
+
}
|
|
255
327
|
const ws = new WebSocketImpl(url);
|
|
256
328
|
socket = ws;
|
|
257
329
|
let pinger;
|
|
258
330
|
ws.addEventListener("open", () => {
|
|
259
|
-
ws.send(JSON.stringify(
|
|
331
|
+
ws.send(JSON.stringify(hello()));
|
|
260
332
|
pinger = setInterval(() => ws.readyState === 1 && ws.send("ping"), 30_000);
|
|
261
333
|
});
|
|
262
334
|
ws.addEventListener("message", (ev) => {
|
|
263
335
|
let m; try { m = JSON.parse(String(ev.data)); } catch { return; }
|
|
264
|
-
if (m.type === "welcome") { attempt = 0; log(`✓ linked to ${server} as "${hostname}".
|
|
336
|
+
if (m.type === "welcome") { attempt = 0; log(`✓ linked to ${server} as "${hostname}". chats and blog posts can now use your CLI while this keeps running.`); }
|
|
265
337
|
else if (m.type === "run") startJob(ws, m);
|
|
338
|
+
else if (m.type === "rescan") rescan(ws);
|
|
266
339
|
else if (m.type === "cancel") jobs.get(m.id)?.abort();
|
|
267
|
-
else if (m.type === "revoked") stop("this computer was disconnected in SEOAnything settings.");
|
|
340
|
+
else if (m.type === "revoked") { if (deviceToken) onUnlinked?.(); stop("this computer was disconnected in SEOAnything settings."); }
|
|
268
341
|
});
|
|
269
342
|
ws.addEventListener("close", (ev) => {
|
|
270
343
|
clearInterval(pinger);
|
|
271
344
|
if (socket !== ws || stopped) return;
|
|
272
345
|
for (const j of jobs.values()) j.abort();
|
|
273
346
|
jobs.clear();
|
|
274
|
-
if (ev.code === 4401) return stop("this computer was disconnected in SEOAnything settings. run connect again to link it.");
|
|
347
|
+
if (ev.code === 4401) { if (deviceToken) onUnlinked?.(); return stop("this computer was disconnected in SEOAnything settings. run connect again, or use a fresh setup prompt, to link it."); }
|
|
275
348
|
if (ev.code === 4400) return stop("the server did not accept this connector. update it: npm i -g seoanything-cli@latest");
|
|
276
349
|
if (ev.code === 4409) return stop("another connector took over on this computer.");
|
|
277
350
|
const wait = Math.min(30_000, 1000 * 2 ** Math.min(attempt++, 5));
|
package/src/connect.test.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { mkdtempSync, rmSync } from "node:fs";
|
|
1
|
+
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
2
2
|
import os from "node:os";
|
|
3
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";
|
|
4
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
5
|
+
import { buildArgs, checkJob, connect, deltaOf, listModels, ownEnv, pair, parseModels, parseOutput, runJob, startBackground } from "./connect.js";
|
|
6
6
|
|
|
7
7
|
const job = { kind: "claude", prompt: "say ok", system: "be brief", timeout: 60 };
|
|
8
8
|
let root;
|
|
@@ -107,3 +107,98 @@ describe("runJob", () => {
|
|
|
107
107
|
await expect(runJob({ ...job, kind: "codex" }, { binaries: { claude: "/bin/claude" }, run: async () => ({}) })).rejects.toThrow("not installed");
|
|
108
108
|
});
|
|
109
109
|
});
|
|
110
|
+
|
|
111
|
+
describe("linking with a setup code", () => {
|
|
112
|
+
const server = "https://seo.test";
|
|
113
|
+
let dir, saved;
|
|
114
|
+
beforeEach(() => {
|
|
115
|
+
dir = mkdtempSync(path.join(os.tmpdir(), "link-"));
|
|
116
|
+
saved = { PATH: process.env.PATH, XDG_CONFIG_HOME: process.env.XDG_CONFIG_HOME };
|
|
117
|
+
// one fake AI CLI on PATH, and a private config folder
|
|
118
|
+
writeFileSync(path.join(dir, "claude"), "#!/bin/sh\necho 9.9.9\n", { mode: 0o755 });
|
|
119
|
+
process.env.PATH = dir; process.env.XDG_CONFIG_HOME = dir;
|
|
120
|
+
});
|
|
121
|
+
afterEach(() => { process.env.PATH = saved.PATH; process.env.XDG_CONFIG_HOME = saved.XDG_CONFIG_HOME; vi.unstubAllGlobals(); rmSync(dir, { recursive: true, force: true }); });
|
|
122
|
+
|
|
123
|
+
class FakeSocket {
|
|
124
|
+
static all = [];
|
|
125
|
+
constructor(url) { this.url = url; this.readyState = 1; this.sent = []; this.on = {}; FakeSocket.all.push(this); queueMicrotask(() => this.emit("open")); }
|
|
126
|
+
addEventListener(t, f) { (this.on[t] ??= []).push(f); }
|
|
127
|
+
emit(t, ev = {}) { for (const f of this.on[t] ?? []) f(ev); }
|
|
128
|
+
send(s) { this.sent.push(s === "ping" ? s : JSON.parse(s)); }
|
|
129
|
+
close(code = 1000) { this.readyState = 3; this.emit("close", { code }); }
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
it("trades the code for a computer token, sending only the code and who this computer is", async () => {
|
|
133
|
+
const f = vi.fn(async () => Response.json({ token: "u1." + "a".repeat(64) }));
|
|
134
|
+
vi.stubGlobal("fetch", f);
|
|
135
|
+
expect(await pair({ server, code: " u1.abc ", deviceId: "d00d", hostname: "box" })).toBe("u1." + "a".repeat(64));
|
|
136
|
+
expect(f.mock.calls[0][0]).toBe(`${server}/api/v1/cli/pair`);
|
|
137
|
+
expect(JSON.parse(f.mock.calls[0][1].body)).toMatchObject({ code: "u1.abc", deviceId: "d00d", name: "box" });
|
|
138
|
+
vi.stubGlobal("fetch", vi.fn(async () => Response.json({ detail: "that setup code is unknown, used or expired." }, { status: 401 })));
|
|
139
|
+
await expect(pair({ server, code: "u1.x", deviceId: "d00d" })).rejects.toMatchObject({ exitCode: 3, message: "that setup code is unknown, used or expired." });
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
it("starts in the background, detached, logging to the config folder", () => {
|
|
143
|
+
const child = { pid: 42, unref: vi.fn() };
|
|
144
|
+
const spawnImpl = vi.fn(() => child);
|
|
145
|
+
const r = startBackground(server, { script: "/bin/seo.js", spawnImpl });
|
|
146
|
+
expect(r).toEqual({ pid: 42, log: path.join(dir, "seoanything", "connect.log") });
|
|
147
|
+
const [cmd, args, opts] = spawnImpl.mock.calls[0];
|
|
148
|
+
expect([cmd, args]).toEqual([process.execPath, ["/bin/seo.js", "connect", "--server", server]]);
|
|
149
|
+
expect(opts.detached).toBe(true); expect(child.unref).toHaveBeenCalled();
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
it("links with the computer token, says hello once per scan, and looks again when asked", async () => {
|
|
153
|
+
FakeSocket.all = [];
|
|
154
|
+
const f = vi.fn(async () => Response.json({ url: "wss://seo.test/api/v1/cli/connect?ticket=u1.t" }));
|
|
155
|
+
vi.stubGlobal("fetch", f);
|
|
156
|
+
const ac = new AbortController();
|
|
157
|
+
const done = connect({ server, deviceToken: "u1.tok", hostname: "box", log: () => {}, signal: ac.signal, WebSocketImpl: FakeSocket });
|
|
158
|
+
await vi.waitFor(() => expect(FakeSocket.all[0]?.sent.length).toBe(1), { timeout: 5000 });
|
|
159
|
+
expect(f.mock.calls[0][0]).toBe(`${server}/api/v1/cli/device-ticket`);
|
|
160
|
+
expect(JSON.parse(f.mock.calls[0][1].body)).toMatchObject({ token: "u1.tok" });
|
|
161
|
+
const ws = FakeSocket.all[0];
|
|
162
|
+
expect(ws.sent[0]).toMatchObject({ type: "hello", name: "box", clis: [{ kind: "claude", version: "9.9.9" }], features: ["rescan"] });
|
|
163
|
+
writeFileSync(path.join(dir, "codex"), "#!/bin/sh\necho 1.0\n", { mode: 0o755 });
|
|
164
|
+
ws.emit("message", { data: JSON.stringify({ type: "rescan" }) });
|
|
165
|
+
await vi.waitFor(() => expect(ws.sent.length).toBe(2), { timeout: 5000 });
|
|
166
|
+
expect(ws.sent.at(-1).clis.map((c) => c.kind)).toEqual(["claude", "codex"]);
|
|
167
|
+
ac.abort();
|
|
168
|
+
expect(await done).toMatch(/connector closed/);
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
it("forgets the computer token when it is disconnected from the settings page", async () => {
|
|
172
|
+
FakeSocket.all = [];
|
|
173
|
+
vi.stubGlobal("fetch", vi.fn(async () => Response.json({ url: "wss://seo.test/x" })));
|
|
174
|
+
const onUnlinked = vi.fn();
|
|
175
|
+
const done = connect({ server, deviceToken: "u1.tok", onUnlinked, log: () => {}, WebSocketImpl: FakeSocket });
|
|
176
|
+
await vi.waitFor(() => expect(FakeSocket.all[0]?.sent.length).toBe(1), { timeout: 5000 });
|
|
177
|
+
FakeSocket.all[0].emit("message", { data: JSON.stringify({ type: "revoked" }) });
|
|
178
|
+
expect(await done).toMatch(/disconnected/);
|
|
179
|
+
expect(onUnlinked).toHaveBeenCalledOnce();
|
|
180
|
+
});
|
|
181
|
+
it("forgets the computer token when the cloud no longer accepts it", async () => {
|
|
182
|
+
vi.stubGlobal("fetch", vi.fn(async () => Response.json({ detail: "this computer is no longer linked." }, { status: 401 })));
|
|
183
|
+
const onUnlinked = vi.fn();
|
|
184
|
+
expect(await connect({ server, deviceToken: "u1.tok", onUnlinked, log: () => {}, WebSocketImpl: FakeSocket })).toBe("this computer is no longer linked.");
|
|
185
|
+
expect(onUnlinked).toHaveBeenCalledOnce();
|
|
186
|
+
});
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
describe("model lists", () => {
|
|
190
|
+
it("reads the codex catalog: hidden models skipped, in its own order, names kept", () => {
|
|
191
|
+
const out = JSON.stringify({ models: [{ slug: "gpt-b", display_name: "GPT B", visibility: "list", priority: 2 }, { slug: "hidden-x", display_name: "X", visibility: "hide", priority: 0 }, { slug: "gpt-a", display_name: "GPT A", visibility: "list", priority: 1 }, { slug: "bad id!", display_name: "Bad", visibility: "list", priority: 3 }] });
|
|
192
|
+
expect(parseModels("codex", out)).toEqual([{ id: "gpt-a", label: "GPT A" }, { id: "gpt-b", label: "GPT B" }]);
|
|
193
|
+
expect(parseModels("codex", "not json")).toEqual([]);
|
|
194
|
+
});
|
|
195
|
+
it("reads agy's id and name lines, ignoring its status line", () => {
|
|
196
|
+
expect(parseModels("agy", "Fetching available models...\ngemini-3.8-flash-high\tGemini 3.8 Flash (High)\nclaude-sonnet-4-6\tClaude Sonnet 4.6 (Thinking)\n")).toEqual([{ id: "gemini-3.8-flash-high", label: "Gemini 3.8 Flash (High)" }, { id: "claude-sonnet-4-6", label: "Claude Sonnet 4.6 (Thinking)" }]);
|
|
197
|
+
});
|
|
198
|
+
it("gives Claude Code its aliases without running it, and nothing when a list can't be read", async () => {
|
|
199
|
+
const run = vi.fn();
|
|
200
|
+
expect((await listModels("claude", "/bin/claude", {}, run)).map((m) => m.id)).toEqual(["fable", "opus", "sonnet", "haiku"]);
|
|
201
|
+
expect(run).not.toHaveBeenCalled();
|
|
202
|
+
expect(await listModels("codex", "/bin/codex", {}, async () => { throw new Error("boom"); })).toEqual([]);
|
|
203
|
+
});
|
|
204
|
+
});
|
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.
|
|
6
|
+
export const VERSION = "2.3.0";
|
|
7
7
|
|
|
8
8
|
export async function mcp(flags) {
|
|
9
9
|
const [major, minor] = process.versions.node.split(".").map(Number);
|