seerepo 1.2.1 → 1.2.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/lib/changes.js ADDED
@@ -0,0 +1,65 @@
1
+ // What the CLI changes, with a key that writes (conector-escribe 2.4): ignore, false, snooze and accept
2
+ import { createInterface } from "node:readline/promises";
3
+ import { claim } from "./claim.js";
4
+ import { BASE, die, flag, get, post, rest, whichRepo } from "./core.js";
5
+ import { changes, health } from "./read.js";
6
+
7
+ // The changes (conector-escribe 2.4): prepare, say what will happen, ask, and only then apply. Without a terminal to answer
8
+ // in, nothing is applied: the person says yes here, or through their agent's MCP
9
+ const MARK = { false: "marked false", snooze: "put off", accept: "accepted" };
10
+ export const markSaid = (m) => `${MARK[m.kind]}${m.until ? ` until ${m.until.slice(0, 10)}` : ""}${m.why ? ` ("${m.why}")` : ""}${m.by ? ` by ${m.by}` : ""}`;
11
+ export function said(name, p, title) {
12
+ const task = `the task "${title}"`;
13
+ if (p.kind === "ignore") return `This will ignore ${p.paths.join(", ")} in ${name}: ${p.leaving} product ${p.leaving === 1 ? "file leaves" : "files leave"} the map${p.examples.length ? ` (${p.examples.join(", ")}${p.leaving > p.examples.length ? ", …" : ""})` : ""}, and SeeRepo reads the repo again without them.`;
14
+ if (p.kind === "false") return `This will mark ${p.files ? `${p.files.join(", ")} of ${task}` : task} false, because "${p.why}": ${p.files ? "those files leave it" : "it leaves the list"} and takes no points.`;
15
+ if (p.kind === "snooze") return `This will put off ${task} until ${p.until.slice(0, 10)}: it leaves the list and takes no points until then.`;
16
+ if (p.kind === "claim") {
17
+ const kept = [p.corrects ? `${p.corrects === p.commits ? (p.corrects === 1 ? "it is" : "they are") : `${p.corrects} of them ${p.corrects === 1 ? "is" : "are"}`} signed by ${(p.from || []).join(" and ")} and will count for ${p.agent} instead, by its session's proof (what each signature says is kept)` : "", p.signed ? (p.corrects ? `${p.signed} more already ${p.signed === 1 ? "carries" : "carry"} ${p.agent}'s signature and ${p.signed === 1 ? "stays" : "stay"} as ${p.signed === 1 ? "it is" : "they are"}` : `${p.signed} already ${p.signed === 1 ? "carries" : "carry"} a signature, which wins`) : "", p.older ? (p.corrects ? `${p.older} more ${p.older === 1 ? "is" : "are"} older than the 90 days SeeRepo keeps and ${p.older === 1 ? "stays" : "stay"} out: it can't see ${p.older === 1 ? "its signature" : "their signatures"}` : `${p.older} ${p.older === 1 ? "is" : "are"} older than the 90 days SeeRepo keeps and ${p.older === 1 ? "counts" : "count"} at the next reading`) : "", p.claimed ? `${p.claimed} ${p.claimed === 1 ? "was" : "were"} claimed already` : ""].filter(Boolean);
18
+ return `This will count ${p.commits} ${p.commits === 1 ? "commit" : "commits"} of ${name} as made by ${p.agent}${kept.length ? `; ${kept.join("; ")}` : ""}. SeeRepo reads the repo again to count them.${p.corrects ? ` Say no if ${p.agent} only moved or amended ${p.corrects === 1 ? "a commit" : "commits"} another agent wrote.` : ""}`;
19
+ }
20
+ return `This will accept ${task}, because "${p.why}": it leaves the list and takes no points until it's undone.`;
21
+ }
22
+ export async function change(repo, ask, quiet = []) {
23
+ const prepared = await post(`/repos/${repo.id}/changes`, ask, undefined, quiet);
24
+ if (!prepared) return null;
25
+ const p = prepared.preview;
26
+ // A correction asked of a SeeRepo that doesn't know them yet, or with nothing to correct: nothing is asked
27
+ if (ask.correct && !p.corrects) return;
28
+ let title = null;
29
+ if (p.task) {
30
+ const h = await get(`/repos/${repo.id}/health`);
31
+ title = [...h.tasks, ...(h.marked || [])].find((x) => x.key === p.task.key)?.title || p.task.key;
32
+ }
33
+ console.log(said(repo.fullName, p, title));
34
+ if (!process.stdin.isTTY) die("Nothing changed: run it in a terminal to answer, or apply it through your agent's MCP.");
35
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
36
+ const answer = (await rl.question("Apply? (y/N) ")).trim().toLowerCase();
37
+ rl.close();
38
+ if (answer !== "y" && answer !== "yes") return console.log("Nothing changed.");
39
+ const c = await post("/changes/apply", { handle: prepared.handle });
40
+ console.log(`Done. Change ${c.id}: undo it in Settings → API (${BASE}/dashboard/settings?tab=api) or with POST /changes/${c.id}/undo.`);
41
+ }
42
+ export async function ignore() {
43
+ const repo = await whichRepo();
44
+ if (!rest.length) die("Name the paths to ignore, like: seerepo ignore experiments/ generated/");
45
+ await change(repo, { kind: "ignore", paths: rest });
46
+ }
47
+ export async function markFalse() {
48
+ const why = flag("why");
49
+ const files = flag("files");
50
+ const repo = await whichRepo();
51
+ if (!rest[0] || !why) die('Name the task and why, like: seerepo false 3 --why "Next renders it by its name"');
52
+ await change(repo, { kind: "false", task: rest[0], why, ...(files ? { files: files.split(",").map((f) => f.trim()).filter(Boolean) } : {}) });
53
+ }
54
+ export async function snooze() {
55
+ const days = Number(flag("days") || 7);
56
+ const repo = await whichRepo();
57
+ if (!rest[0]) die("Name the task, like: seerepo snooze 3 --days 7");
58
+ await change(repo, { kind: "snooze", task: rest[0], days });
59
+ }
60
+ export async function accept() {
61
+ const why = flag("why");
62
+ const repo = await whichRepo();
63
+ if (!rest[0] || !why) die('Name the task and why, like: seerepo accept 3 --why "kept on purpose"');
64
+ await change(repo, { kind: "accept", task: rest[0], why });
65
+ }
package/lib/claim.js ADDED
@@ -0,0 +1,106 @@
1
+ // seerepo claim: the commits the agents made here without signing, found in their sessions on this machine
2
+ import { execFileSync } from "node:child_process";
3
+ import { createReadStream, existsSync, readdirSync, statSync } from "node:fs";
4
+ import { homedir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { createInterface as lineReader } from "node:readline";
7
+ import * as zlib from "node:zlib";
8
+ import { change, ignore, said } from "./changes.js";
9
+ import { die, flag, whichRepo } from "./core.js";
10
+ import { found } from "./read.js";
11
+
12
+ // Who wrote each commit, even unsigned (atribucion-por-sesion 1.1, decision 47). Codex and Claude Code keep, on this machine,
13
+ // what each `git commit` answered: «[branch hash] subject». A commit of this folder's repo found there, with the same subject,
14
+ // was made by that agent. Only Codex's day folders inside the window are read (its sessions weigh gigabytes), and Claude
15
+ // Code's sessions changed inside it. Nothing of a session leaves the machine: only the commit and the agent
16
+ // Codex compresses its older sessions (.jsonl.zst): measured on 2026-11-08, 528 of 789 on one machine, the 17 commits of
17
+ // decision 47 among them, and claim found none. Read with Node's zstd (22.15 and later); an older Node skips them and says so
18
+ const ZSTD = typeof zlib.createZstdDecompress === "function";
19
+ const SESSIONS = [
20
+ { agent: "Codex", root: join(homedir(), ".codex", "sessions"), byDay: true },
21
+ { agent: "Claude", root: join(homedir(), ".claude", "projects"), byDay: false },
22
+ ];
23
+ const R_COMMITTED = /\[([^\]\s]+)(?: \(root-commit\))? ([0-9a-f]{7,40})\] ((?:[^"\\]|\\.){1,120})/g;
24
+ function sessionFiles(root, byDay, since) {
25
+ const out = [];
26
+ if (!existsSync(root)) return out;
27
+ const walk = (dir, depth) => {
28
+ for (const name of readdirSync(dir)) {
29
+ const at = join(dir, name);
30
+ const st = statSync(at);
31
+ if (st.isDirectory()) {
32
+ // Codex's folders are year/month/day: a day before the window is skipped whole
33
+ if (byDay && depth === 2 && `${dir.slice(-7).replace("/", "-")}-${name}` < since) continue;
34
+ walk(at, depth + 1);
35
+ } else if ((name.endsWith(".jsonl") || name.endsWith(".jsonl.zst")) && st.mtimeMs >= Date.parse(since)) out.push(at);
36
+ }
37
+ };
38
+ walk(root, 0);
39
+ return out;
40
+ }
41
+ async function localClaims(days) {
42
+ const since = new Date(Date.now() - days * 86_400_000).toISOString().slice(0, 10);
43
+ let log;
44
+ try {
45
+ log = execFileSync("git", ["log", "--all", `--since=${since}`, "--format=%H%x1f%s%x1f%ad%x1f%b%x1e", "--date=short"], { stdio: ["ignore", "pipe", "ignore"], maxBuffer: 64 * 1024 * 1024 }).toString();
46
+ } catch {
47
+ die("This folder isn't a git repo. Run it in your project's folder.");
48
+ }
49
+ const commits = new Map();
50
+ for (const row of log.split("\x1e").map((x) => x.trim()).filter(Boolean)) {
51
+ const [sha, subject, day, body] = row.split("\x1f");
52
+ commits.set(sha.slice(0, 7), { sha, subject, day, signed: /co-authored-by:|assisted-by:|made-with:/i.test(body || "") });
53
+ }
54
+ const found = new Map();
55
+ let skipped = 0;
56
+ for (const { agent, root, byDay } of SESSIONS) {
57
+ for (const file of sessionFiles(root, byDay, since)) {
58
+ // Line by line: one session can weigh more than a string holds
59
+ if (file.endsWith(".zst") && !ZSTD) {
60
+ skipped++;
61
+ continue;
62
+ }
63
+ const input = file.endsWith(".zst") ? createReadStream(file).pipe(zlib.createZstdDecompress()) : createReadStream(file, "utf8");
64
+ for await (const line of lineReader({ input, crlfDelay: Infinity })) {
65
+ if (!line.includes("] ")) continue;
66
+ for (const m of line.matchAll(R_COMMITTED)) {
67
+ const c = commits.get(m[2].slice(0, 7));
68
+ // The same commit by its subject too: a short hash alone could be another repo's
69
+ const said = m[3].replace(/\\"/g, '"').replace(/\\n.*/s, "");
70
+ if (!c || !c.sha.startsWith(m[2]) || !said.startsWith(c.subject.slice(0, Math.min(30, c.subject.length)))) continue;
71
+ if (!found.has(c.sha)) found.set(c.sha, { ...c, agent });
72
+ }
73
+ }
74
+ }
75
+ }
76
+ if (skipped) process.stderr.write(`${skipped} compressed ${skipped === 1 ? "session" : "sessions"} of Codex need Node 22.15 or later to be read: they were left out.\n`);
77
+ return [...found.values()];
78
+ }
79
+ export async function claim() {
80
+ const days = Math.min(365, Math.max(1, Number(flag("days") || 90)));
81
+ process.stderr.write(`Reading Codex's and Claude Code's sessions on this machine (the last ${days} days)…\n`);
82
+ const claims = await localClaims(days);
83
+ const unsigned = claims.filter((c) => !c.signed);
84
+ if (!claims.length) return console.log(`No commit of this repo in the last ${days} days was found in Codex's or Claude Code's sessions on this machine.`);
85
+ const by = new Map();
86
+ for (const c of unsigned) by.set(c.agent, [...(by.get(c.agent) || []), c]);
87
+ const lines = [`Found in your agents' sessions on this machine, in the last ${days} days:`];
88
+ for (const [agent, list] of by) {
89
+ const daysOf = list.map((c) => c.day).sort();
90
+ lines.push(` ${agent.padEnd(8)} ${String(list.length).padStart(4)} ${list.length === 1 ? "commit " : "commits"} without its signature (${daysOf[0] === daysOf.at(-1) ? daysOf[0] : `${daysOf[0]} to ${daysOf.at(-1)}`})`);
91
+ }
92
+ const signed = claims.filter((c) => c.signed);
93
+ if (signed.length) lines.push(` ${signed.length} more already carry an agent's signature: SeeRepo counts them already, and asks below about any that names another agent than the session's.`);
94
+ if (!unsigned.length) lines.push("", "Nothing to claim: every one is signed.");
95
+ else lines.push("", "Only each commit's hash and its agent leave this machine.");
96
+ console.log(lines.join("\n"));
97
+ // Then each agent's, as a change (atribucion-por-sesion 1.2): what will count, a question, and only then the claim
98
+ const repo = await whichRepo();
99
+ for (const [agent, list] of by) if ((await change(repo, { kind: "claim", agent, shas: list.map((c) => c.sha) }, ["claimed"])) === null) console.log(`${agent}'s ${list.length === 1 ? "was" : "were"} claimed already.`);
100
+ // And the signed ones whose signature names another agent (decision 185, atribucion-por-sesion 1.7): a skill made for one
101
+ // agent has any other sign with its name, and the session is who ran the commit. SeeRepo says which they are; a question of
102
+ // its own, apart from the claim above
103
+ const bySigned = new Map();
104
+ for (const c of signed) bySigned.set(c.agent, [...(bySigned.get(c.agent) || []), c]);
105
+ for (const [agent, list] of bySigned) await change(repo, { kind: "claim", agent, shas: list.map((c) => c.sha), correct: true }, ["nothing_to_correct", "claimed"]);
106
+ }
package/lib/connect.js ADDED
@@ -0,0 +1,120 @@
1
+ // seerepo connect: the agent's MCP and the project's rule, each step said and asked
2
+ import { execFileSync } from "node:child_process";
3
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
4
+ import { homedir } from "node:os";
5
+ import { dirname, join } from "node:path";
6
+ import { createInterface } from "node:readline/promises";
7
+ import { change, ignore, said } from "./changes.js";
8
+ import { BASE, CONFIG, VERSION, command, die, flag, get, rest, whichRepo } from "./core.js";
9
+ import { forward, mcp } from "./mcp.js";
10
+ import { docs, found, open } from "./read.js";
11
+
12
+ // `seerepo connect` (conectar-guiado 2.1): the agent's MCP and the project's rule, each step said and asked before it's done
13
+ // (D-8), ending with a real call through the same bridge the agent will use. Nothing here carries the key: the agent's config
14
+ // gets the bridge's line. Claude Code and Codex by their own commands, for all the person's projects; Cursor by its file
15
+ const BRIDGE = ["npx", "-y", "seerepo", "mcp"];
16
+ const RULE_START = "<!-- seerepo:start -->";
17
+ const RULE_END = "<!-- seerepo:end -->";
18
+ // The words, the marks, the bridge and the three questions are app/libs/agent-rule.ts's: scripts/check-agent-rule.ts fails when they differ
19
+ const RULE = `${RULE_START}\n## SeeRepo\n\nSeeRepo (the MCP server named seerepo) has this repo mapped. Ask it first, before searching or opening files, and then read only what you need to confirm what it says.\n${RULE_END}\n`;
20
+ const AGENTS = {
21
+ claude: { name: "Claude Code", bin: "claude", add: ["mcp", "add", "--scope", "user", "seerepo", "--", ...BRIDGE] },
22
+ codex: { name: "Codex", bin: "codex", add: ["mcp", "add", "seerepo", "--", ...BRIDGE] },
23
+ cursor: { name: "Cursor", file: () => join(homedir(), ".cursor", "mcp.json") },
24
+ };
25
+ const runs = (bin, args) => {
26
+ try {
27
+ return execFileSync(bin, args, { stdio: ["ignore", "pipe", "ignore"] }).toString();
28
+ } catch {
29
+ return null;
30
+ }
31
+ };
32
+ // The file's text with the rule between its marks: put in place of an older one, or added at the end
33
+ const withRule = (text) => {
34
+ const a = text.indexOf(RULE_START);
35
+ const b = text.indexOf(RULE_END);
36
+ if (a >= 0 && b > a) return text.slice(0, a) + RULE.trimEnd() + text.slice(b + RULE_END.length);
37
+ return `${text}${text && !text.endsWith("\n") ? "\n" : ""}${text ? "\n" : ""}${RULE}`;
38
+ };
39
+ // Which of the project's files take the rule: the one each agent already reads. Claude Code reads its CLAUDE.md, and only when
40
+ // there's none an AGENTS.md (since 2.1.277): a CLAUDE.md made beside an AGENTS.md would hide that AGENTS.md from it, so none is
41
+ // made. Codex and Cursor read AGENTS.md
42
+ function ruleFiles(root, agents) {
43
+ const claudeFile = ["CLAUDE.md", ".claude/CLAUDE.md"].find((f) => existsSync(join(root, f)));
44
+ const files = [];
45
+ if (agents.includes("claude") && claudeFile) files.push(claudeFile);
46
+ if (agents.some((a) => a !== "claude") || (agents.includes("claude") && !claudeFile)) files.push("AGENTS.md");
47
+ return files;
48
+ }
49
+ export async function connect() {
50
+ const all = rest.includes("--yes") && Boolean(rest.splice(rest.indexOf("--yes"), 1));
51
+ const wanted = flag("agent")?.split(",").map((a) => a.trim().toLowerCase()).filter(Boolean);
52
+ for (const a of wanted || []) if (!AGENTS[a]) die(`SeeRepo connects Claude Code, Codex and Cursor: --agent ${Object.keys(AGENTS).join(",")}`);
53
+ // The rule goes in the folder's project: with --repo there's no folder to write it in
54
+ const elsewhere = rest.includes("--repo");
55
+ const repo = await whichRepo();
56
+ const root = elsewhere ? null : runs("git", ["rev-parse", "--show-toplevel"])?.trim() || null;
57
+ const found = Object.keys(AGENTS).filter((a) => (AGENTS[a].bin ? runs(AGENTS[a].bin, ["--version"]) !== null : existsSync(join(homedir(), ".cursor"))));
58
+ const agents = wanted || found;
59
+ if (!agents.length) die(`No agent found on this machine (Claude Code, Codex or Cursor). Install one, or name it: seerepo connect --agent claude\nBy hand: ${BASE}/docs/mcp`);
60
+ const yes = async (question) => {
61
+ if (all) return true;
62
+ if (!process.stdin.isTTY) die("Nothing changed: run it in a terminal to answer each step, or add --yes to do them all.");
63
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
64
+ const answer = (await rl.question(`${question} (y/N) `)).trim().toLowerCase();
65
+ rl.close();
66
+ return answer === "y" || answer === "yes";
67
+ };
68
+ console.log(`Connecting ${agents.map((a) => AGENTS[a].name).join(", ")} to SeeRepo for ${repo.fullName}. The key stays in ${CONFIG}: nothing written here carries it.`);
69
+ const did = [];
70
+ for (const a of agents) {
71
+ const agent = AGENTS[a];
72
+ if (agent.bin) {
73
+ if (runs(agent.bin, ["--version"]) === null) did.push(`- ${agent.name}: it isn't installed on this machine, nothing done`);
74
+ else if (runs(agent.bin, ["mcp", "get", "seerepo"]) !== null) did.push(`= ${agent.name}: it already has a server named seerepo, left as it is`);
75
+ else if (!(await yes(`Add SeeRepo to ${agent.name}, for all your projects? It runs: ${agent.bin} ${agent.add.join(" ")}`))) did.push(`- ${agent.name}: you said no, nothing done`);
76
+ else did.push(runs(agent.bin, agent.add) === null ? `! ${agent.name}: its own command failed. Run it yourself: ${agent.bin} ${agent.add.join(" ")}` : `+ ${agent.name}: the server seerepo (${BRIDGE.join(" ")}), for all your projects`);
77
+ continue;
78
+ }
79
+ const file = agent.file();
80
+ const before = existsSync(file) ? readFileSync(file, "utf8") : "";
81
+ let config;
82
+ try {
83
+ config = before.trim() ? JSON.parse(before) : {};
84
+ } catch {
85
+ did.push(`! ${agent.name}: ${file} isn't valid JSON, so it wasn't touched. Add to its mcpServers: "seerepo": { "command": "npx", "args": ["-y", "seerepo", "mcp"] }`);
86
+ continue;
87
+ }
88
+ if (config.mcpServers?.seerepo) did.push(`= ${agent.name}: ${file} already has a server named seerepo, left as it is`);
89
+ else if (!(await yes(`Add SeeRepo to ${agent.name}? It adds the server seerepo (${BRIDGE.join(" ")}) to ${file}`))) did.push(`- ${agent.name}: you said no, nothing done`);
90
+ else {
91
+ mkdirSync(dirname(file), { recursive: true });
92
+ writeFileSync(file, `${JSON.stringify({ ...config, mcpServers: { ...(config.mcpServers || {}), seerepo: { command: BRIDGE[0], args: BRIDGE.slice(1) } } }, null, 2)}\n`);
93
+ did.push(`+ ${agent.name}: the server seerepo in ${file}`);
94
+ }
95
+ }
96
+ // The rule, in the project's own file
97
+ if (!root) did.push("- The rule: run seerepo connect inside the project's folder to write it in its file");
98
+ else
99
+ for (const name of ruleFiles(root, agents)) {
100
+ const file = join(root, name);
101
+ const before = existsSync(file) ? readFileSync(file, "utf8") : "";
102
+ const after = withRule(before);
103
+ if (after === before) did.push(`= ${name}: the rule is already there`);
104
+ else if (!(await yes(`${before ? (before.includes(RULE_START) ? "Update the rule in" : "Add the rule to") : "Create"} ${name}? It tells your agent to ask SeeRepo first, between two marks, and touches nothing else in the file`))) did.push(`- ${name}: you said no, nothing done`);
105
+ else {
106
+ mkdirSync(dirname(file), { recursive: true });
107
+ writeFileSync(file, after);
108
+ did.push(`+ ${name}: the rule, between ${RULE_START} and ${RULE_END}`);
109
+ }
110
+ }
111
+ // A real call, by the way the agent will make it
112
+ const state = { version: null };
113
+ await forward({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "seerepo-connect", version: VERSION } } }, state);
114
+ // list_projects: it answers while a repo's first read is still going, which explain wouldn't
115
+ const [answer] = await forward({ jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "list_projects", arguments: {} } }, state);
116
+ const said = answer?.result?.content?.[0]?.text;
117
+ const works = Boolean(said) && !answer.result.isError;
118
+ console.log(["", ...did.map((d) => ` ${d}`), "", works ? `SeeRepo answers through the bridge: «${said.split("\n")[0].slice(0, 120)}»` : `SeeRepo didn't answer through the bridge: ${answer?.error?.message || said || "no answer"}`, ...(works ? ["", "Now open your agent in this folder (a new session, so it loads the server) and ask it:", " What does this project do, module by module?", " What breaks if I change one of its files?", " What changed since yesterday?", `Settings shows it connected after its first call: ${BASE}/dashboard/settings?tab=api`] : [])].join("\n"));
119
+ if (!works) process.exit(1);
120
+ }
package/lib/core.js ADDED
@@ -0,0 +1,99 @@
1
+ // The CLI's common ground: its settings, the flags, the API with the saved key, and which repo the folder is (cli/bin/seerepo.js)
2
+ import { execFileSync } from "node:child_process";
3
+ import { readFileSync } from "node:fs";
4
+ import { homedir } from "node:os";
5
+ import { dirname, join } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { change, ignore, said } from "./changes.js";
8
+ import { found, map } from "./read.js";
9
+
10
+ export const VERSION = JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), "..", "package.json"), "utf8")).version;
11
+ export const CONFIG = join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "seerepo", "config.json");
12
+ export const BASE = (process.env.SEEREPO_URL || "https://seerepo.com").replace(/\/$/, "");
13
+ // The command and what follows it: one array for every module, so a flag a command takes out (splice) is out for all
14
+ export const [, , command, ...rest] = process.argv;
15
+ export const flag = (name) => {
16
+ const i = rest.indexOf(`--${name}`);
17
+ return i >= 0 ? rest.splice(i, 2)[1] : undefined;
18
+ };
19
+ export const die = (message) => {
20
+ console.error(message);
21
+ process.exit(1);
22
+ };
23
+
24
+ export function readConfig() {
25
+ try {
26
+ return JSON.parse(readFileSync(CONFIG, "utf8"));
27
+ } catch {
28
+ return {};
29
+ }
30
+ }
31
+
32
+ export async function get(path, key = readConfig().key) {
33
+ if (!key) die(`You're not logged in. Run: seerepo login`);
34
+ let res;
35
+ try {
36
+ res = await fetch(`${BASE}/api/v1${path}`, { headers: { authorization: `Bearer ${key}`, "user-agent": `seerepo-cli/${VERSION}` } });
37
+ } catch {
38
+ die(`Can't reach ${BASE}. Check your connection.`);
39
+ }
40
+ const body = await res.json().catch(() => null);
41
+ if (res.status === 401) die("Your key doesn't work (revoked or mistyped). Run: seerepo login");
42
+ if (!res.ok || body?.status !== "success") die(body?.error?.message || `SeeRepo answered ${res.status}.`);
43
+ return body.data;
44
+ }
45
+
46
+ // A change (conector-escribe 2.4): POST with the same key, said to come from the CLI. `quiet`: the refusals the caller takes
47
+ // as «nothing to do» instead of an error (their codes)
48
+ export async function post(path, body, key = readConfig().key, quiet = []) {
49
+ if (!key) die(`You're not logged in. Run: seerepo login`);
50
+ let res;
51
+ try {
52
+ res = await fetch(`${BASE}/api/v1${path}`, { method: "POST", headers: { authorization: `Bearer ${key}`, "content-type": "application/json", "x-seerepo-client": "cli", "user-agent": `seerepo-cli/${VERSION}` }, body: JSON.stringify(body) });
53
+ } catch {
54
+ die(`Can't reach ${BASE}. Check your connection.`);
55
+ }
56
+ const data = await res.json().catch(() => null);
57
+ if (res.status === 401) die("Your key doesn't work (revoked or mistyped). Run: seerepo login");
58
+ if (quiet.includes(data?.error?.code)) return null;
59
+ if (!res.ok || data?.status !== "success") die(data?.error?.message || `SeeRepo answered ${res.status}.`);
60
+ return data.data;
61
+ }
62
+
63
+ // The folder's repo on GitHub, as owner/name, from its git remote
64
+ function folderRepo() {
65
+ try {
66
+ const url = execFileSync("git", ["remote", "get-url", "origin"], { stdio: ["ignore", "pipe", "ignore"] }).toString().trim();
67
+ const m = /github\.com[:/]([\w.-]+\/[\w.-]+?)(?:\.git)?$/.exec(url);
68
+ return m ? m[1] : null;
69
+ } catch {
70
+ return null;
71
+ }
72
+ }
73
+
74
+ // The branch the folder is on, when it's a git folder
75
+ function folderBranch() {
76
+ try {
77
+ return execFileSync("git", ["rev-parse", "--abbrev-ref", "HEAD"], { stdio: ["ignore", "pipe", "ignore"] }).toString().trim() || null;
78
+ } catch {
79
+ return null;
80
+ }
81
+ }
82
+
83
+ // The repo to read: --repo, or the folder's, if it's one of the account's maps. And its branch (ramas M5): --branch, or the
84
+ // folder's when SeeRepo follows it too; otherwise the main map. A second branch's map is read by its own id
85
+ export async function whichRepo() {
86
+ const asked = flag("repo");
87
+ const askedBranch = flag("branch");
88
+ const name = asked || folderRepo();
89
+ if (!name) die(`This folder isn't a GitHub repo. Run it in your project's folder, or add --repo owner/name.`);
90
+ const repos = await get("/repos");
91
+ const found = repos.find((r) => r.fullName.toLowerCase() === name.toLowerCase() || r.id === name);
92
+ if (!found) die(`${name} isn't connected to SeeRepo.\nConnect it at ${BASE}/dashboard, then run this again.`);
93
+ const want = askedBranch || (asked ? null : folderBranch());
94
+ if (!want || want === found.branch) return found;
95
+ const second = (found.branches || []).find((b) => b.branch === want);
96
+ if (second) return { ...found, id: second.id, fullName: `${found.fullName} (${second.branch})` };
97
+ if (askedBranch) die(`${found.fullName} doesn't follow the branch ${want}. SeeRepo follows: ${[found.branch, ...(found.branches || []).map((b) => b.branch)].filter(Boolean).join(", ")}.\nAdd a branch in the project's settings at ${BASE}/dashboard/${found.id}/settings.`);
98
+ return found;
99
+ }
package/lib/mcp.js ADDED
@@ -0,0 +1,62 @@
1
+ // seerepo mcp: SeeRepo's MCP over stdio, a bridge for any agent
2
+ import { createInterface as lineReader } from "node:readline";
3
+ import { accept, said } from "./changes.js";
4
+ import { BASE, VERSION, readConfig } from "./core.js";
5
+ import { found } from "./read.js";
6
+
7
+ // `seerepo mcp` (conectar-guiado; the director chose it on 2026-11-14): SeeRepo's MCP over stdio, for any agent, with the key
8
+ // `seerepo login` saved. The agent's config carries one line and no key (`npx -y seerepo mcp`), so it can be committed, and a
9
+ // new key touches no agent. A bridge and nothing else: each JSON-RPC line from the agent is posted to SeeRepo's MCP as it is,
10
+ // and the answer goes back as it came. It speaks what every agent speaks over stdio, the 2025 protocol with its initialize;
11
+ // the probe of a newer one (server/discover) is told the method doesn't exist, which is what any server of that era answers
12
+ // and how a client knows to fall back. What goes wrong is said to the agent in words it can pass on to the person
13
+ export async function forward(message, state) {
14
+ const asked = Boolean(message) && typeof message === "object" && !Array.isArray(message) && "id" in message && "method" in message;
15
+ const refuse = (code, text) => (asked ? [{ jsonrpc: "2.0", id: message.id, error: { code, message: text } }] : []);
16
+ if (asked && message.method === "server/discover") return refuse(-32601, "Method not found");
17
+ const key = readConfig().key;
18
+ if (!key) return refuse(-32001, "SeeRepo isn't connected on this machine yet. Ask the person to run: npx seerepo login");
19
+ let res;
20
+ try {
21
+ res = await fetch(`${BASE}/api/mcp`, { method: "POST", headers: { authorization: `Bearer ${key}`, "content-type": "application/json", accept: "application/json, text/event-stream", "user-agent": `seerepo-cli/${VERSION} mcp`, ...(state.version ? { "mcp-protocol-version": state.version } : {}) }, body: JSON.stringify(message) });
22
+ } catch {
23
+ return refuse(-32000, `Can't reach ${BASE}. Check the connection and try again.`);
24
+ }
25
+ const text = await res.text().catch(() => "");
26
+ // One JSON body; or, should the server ever stream, each event's
27
+ const bodies = (res.headers.get("content-type") || "").includes("text/event-stream") ? text.split(/\r?\n/).filter((l) => l.startsWith("data:")).map((l) => l.slice(5).trim()) : [text];
28
+ const out = bodies.flatMap((b) => {
29
+ try {
30
+ return b ? [JSON.parse(b)] : [];
31
+ } catch {
32
+ return [];
33
+ }
34
+ });
35
+ if (res.status === 401) return refuse(-32001, "SeeRepo's key on this machine doesn't work (revoked or mistyped). Ask the person to run: npx seerepo login");
36
+ // A refusal of the protocol's own comes back as it is; one of SeeRepo's (the limit per minute), in its words
37
+ if (!res.ok) return out[0]?.jsonrpc ? out : refuse(-32000, out[0]?.error?.message || `SeeRepo answered ${res.status}.`);
38
+ if (asked && message.method === "initialize" && out[0]?.result?.protocolVersion) state.version = out[0].result.protocolVersion;
39
+ return out;
40
+ }
41
+ export async function mcp() {
42
+ const state = { version: null };
43
+ const say = (lines) => {
44
+ for (const o of lines) process.stdout.write(`${JSON.stringify(o)}\n`);
45
+ };
46
+ const pending = new Set();
47
+ for await (const line of lineReader({ input: process.stdin, crlfDelay: Infinity })) {
48
+ if (!line.trim()) continue;
49
+ let message;
50
+ try {
51
+ message = JSON.parse(line);
52
+ } catch {
53
+ say([{ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } }]);
54
+ continue;
55
+ }
56
+ const p = forward(message, state).then(say).finally(() => pending.delete(p));
57
+ pending.add(p);
58
+ // The first exchange alone: the version it settles goes with every request after it
59
+ if (message?.method === "initialize") await p;
60
+ }
61
+ await Promise.all(pending);
62
+ }