@duom/cli 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,21 @@
1
- # Temporary Holding Version
1
+ # @duom/cli
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Install MCP servers, agent skills, rules and stacks from [DuoM](https://duom.cloud) into your AI coding tool, checked for risk first, with a backup and undo.
4
+
5
+ ```sh
6
+ npx @duom/cli@1 add io.github.github/github-mcp-server --client claude-code
7
+ npx @duom/cli@1 add skill/anthropics/skills/pdf --client cursor
8
+ npx @duom/cli@1 undo
9
+ ```
10
+
11
+ Clients: Claude Code, Cursor, VS Code (Copilot), Codex, Gemini CLI, LM Studio, Grok.
12
+
13
+ - Before writing anything, `duom` shows the item's risk signals and asks; high ones always ask again unless you pass `--allow-high`.
14
+ - Your existing config is backed up to `~/.duom`; `undo` restores it.
15
+ - Skills are pinned to the commit DuoM checked and installed with their license.
16
+
17
+ ## Let your agent find and use tools (duom-local)
18
+
19
+ `duom mcp` runs a local MCP server. Your agent can search the catalog, and start a server only after you approve it. Keys stay in `~/.duom/keys.env` and never pass through the agent.
20
+
21
+ Docs: https://duom.cloud/docs · Contact: studo.doum@gmail.com
package/bin/duom.mjs ADDED
@@ -0,0 +1,100 @@
1
+ #!/usr/bin/env node
2
+ import { homedir } from "node:os";
3
+ import { createInterface } from "node:readline/promises";
4
+ import { parseArgs } from "node:util";
5
+ import { removeItem, undoLast } from "../src/files.mjs";
6
+ import { prepare } from "../src/items.mjs";
7
+
8
+ const CLIENTS = ["cursor", "vscode", "lmstudio", "claude-code", "codex", "grok", "gemini"];
9
+ const USAGE = `duom: install MCP servers, skills, rules and stacks with a risk check, backup and undo
10
+
11
+ duom add <name> [--client <${CLIENTS.join("|")}>] [--global] [--option N] [--yes] [--allow-high]
12
+
13
+ <name> is what the item's DuoM page shows, for example:
14
+ io.github.owner/repo MCP server (needs --client)
15
+ skill/owner/repo/skill-name skill -> the tool's skills folder (.claude/skills, .cursor/skills,
16
+ .github/skills, .gemini/skills; .agents/skills for codex or no --client)
17
+ rule/nextjs rule -> one marked block in AGENTS.md (CLAUDE.md for claude-code,
18
+ GEMINI.md for gemini); the rest of the file is left alone
19
+ stack/nextjs-supabase stack -> every member above (needs --client if it has MCP servers)
20
+
21
+ --global skills: install into your home folder, for every project
22
+ --option N MCP servers: pick another install option (npx, Docker, remote ...)
23
+ --yes skip the "Install?" question (high risk signals still ask)
24
+ --allow-high install despite high risk signals without asking
25
+
26
+ duom remove <name> take out one item you added (a stack name removes its members);
27
+ rules and MCP entries come out of the file, the rest of it stays as it is now
28
+ duom undo remove whatever the last add put in (a whole stack at once)
29
+ duom mcp run the local MCP server (stdio) so an agent can install, or run a server and use it
30
+ right away, with your approval (keys for those: ~/.duom/keys.env, NAME=value)
31
+
32
+ DUOM_API_URL another DuoM site, e.g. a self-hosted one (http://localhost:3000 while developing)
33
+ DUOM_API_KEY optional API key for higher rate limits`;
34
+
35
+ async function ask(question) {
36
+ if (!process.stdin.isTTY) return "";
37
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
38
+ const a = await rl.question(question);
39
+ rl.close();
40
+ return a.trim().toLowerCase();
41
+ }
42
+
43
+ async function add(args) {
44
+ const { values, positionals } = parseArgs({
45
+ args,
46
+ allowPositionals: true,
47
+ options: {
48
+ client: { type: "string" },
49
+ global: { type: "boolean" },
50
+ option: { type: "string", default: "0" },
51
+ yes: { type: "boolean" },
52
+ "allow-high": { type: "boolean" },
53
+ },
54
+ });
55
+ const [name] = positionals;
56
+ if (!name || (values.client && !CLIENTS.includes(values.client))) throw new Error(USAGE);
57
+ const steps = await prepare(name, values.client ?? "", { cwd: process.cwd(), home: homedir(), global: values.global, option: Number(values.option) });
58
+ console.log(steps.map((s) => s.text).join("\n\n"));
59
+ console.log("");
60
+
61
+ // High signals always need a typed "yes"; --yes alone does not skip them.
62
+ const high = steps.flatMap((s) => s.high);
63
+ if (high.length && !values["allow-high"]) {
64
+ if ((await ask(`HIGH risk signals above (${high.length}). Type "yes" to install anyway: `)) !== "yes") throw new Error("Cancelled.");
65
+ } else if (!values.yes && (await ask(`Install${steps.length > 1 ? ` ${steps.length} items` : ""}? [y/N] `)) !== "y") {
66
+ throw new Error(process.stdin.isTTY ? "Cancelled." : "No terminal to confirm in. Re-run with --yes after reading the details above.");
67
+ }
68
+
69
+ const group = `${name}@${Date.now()}`;
70
+ let failed = 0;
71
+ for (const s of steps) {
72
+ try {
73
+ const where = await s.apply({ item: s.info.name, version: s.info.version, client: values.client ?? null, group });
74
+ console.log(`Added ${s.info.title} -> ${where}`);
75
+ if (s.blanks?.length) console.log(` Fill in ${s.blanks.join(", ")} in that file.`);
76
+ } catch (e) {
77
+ failed++;
78
+ console.log(`Skipped ${s.info.title}: ${e.message}`);
79
+ }
80
+ }
81
+ if (failed === steps.length) throw new Error("Nothing was installed.");
82
+ console.log(`Undo with: npx @duom/cli@1 undo (or later: npx @duom/cli@1 remove ${name})`);
83
+ }
84
+
85
+ const [cmd, ...rest] = process.argv.slice(2);
86
+ try {
87
+ if (cmd === "add") await add(rest);
88
+ else if (cmd === "undo") {
89
+ const done = undoLast();
90
+ console.log(done ? done.map((e) => `Undid ${e.item ?? e.server}: ${e.result}`).join("\n") : "Nothing to undo.");
91
+ } else if (cmd === "remove") {
92
+ if (!rest[0]) throw new Error("Usage: duom remove <name>");
93
+ const done = removeItem(rest[0]);
94
+ console.log(done.length ? done.map((e) => `Removed ${e.item}: ${e.result}`).join("\n") : `duom has no record of adding ${rest[0]} on this computer.`);
95
+ } else if (cmd === "mcp") await (await import("../src/mcp.mjs")).serve();
96
+ else console.log(USAGE);
97
+ } catch (e) {
98
+ console.error(e.message);
99
+ process.exit(1);
100
+ }
package/package.json CHANGED
@@ -1,6 +1,43 @@
1
- {
2
- "name": "@duom/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "@duom/cli",
3
+ "version": "1.0.1",
4
+ "description": "Install MCP servers, skills, rules and stacks into Claude Code, Cursor, VS Code, Codex, Gemini CLI and more, checked for risk first, with undo.",
5
+ "homepage": "https://duom.cloud",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/studodoum-sys/DuoM.git",
9
+ "directory": "packages/cli"
10
+ },
11
+ "keywords": [
12
+ "mcp",
13
+ "model-context-protocol",
14
+ "agent-skills",
15
+ "claude-code",
16
+ "cursor",
17
+ "codex",
18
+ "gemini-cli"
19
+ ],
20
+ "type": "module",
21
+ "bin": {
22
+ "duom": "bin/duom.mjs"
23
+ },
24
+ "files": [
25
+ "bin",
26
+ "src",
27
+ "!src/*.test.mjs"
28
+ ],
29
+ "engines": {
30
+ "node": ">=20"
31
+ },
32
+ "scripts": {
33
+ "test": "node --test src/files.test.mjs src/gateway.test.mjs",
34
+ "prepublishOnly": "node -e \"import('./src/api.mjs').then(m => { if (!m.DEFAULT_API) { console.error('Set DEFAULT_API in src/api.mjs to the production URL first.'); process.exit(1) } })\""
35
+ },
36
+ "dependencies": {
37
+ "@modelcontextprotocol/sdk": "1.32.2",
38
+ "zod": "4.6.7"
39
+ },
40
+ "publishConfig": {
41
+ "access": "public"
42
+ }
43
+ }
package/src/api.mjs ADDED
@@ -0,0 +1,41 @@
1
+ // The production site. The vercel.app address, not duom.cloud: if the domain ever lapsed, whoever bought it would be
2
+ // answering every installed CLI (supply-chain risk), while the vercel.app name stays ours.
3
+ // Never localhost: a published CLI pointing there would talk to whatever happens to run on the user's port 3000.
4
+ export const DEFAULT_API = "https://duom-brown.vercel.app";
5
+ const base = process.env.DUOM_API_URL || DEFAULT_API;
6
+ export const API = base.replace(/\/$/, "");
7
+
8
+ export async function api(path) {
9
+ if (!API) throw new Error("No DuoM site set. For a self-hosted or local DuoM, set DUOM_API_URL (for example http://localhost:3000).");
10
+ const headers = process.env.DUOM_API_KEY ? { authorization: `Bearer ${process.env.DUOM_API_KEY}` } : {};
11
+ const res = await fetch(API + path, { headers });
12
+ const body = await res.json().catch(() => ({}));
13
+ if (!res.ok) throw new Error(body.error === "not_found" ? "Not found in DuoM. Check the name on the item's page." : `DuoM API error ${res.status}: ${body.error ?? "unknown"}`);
14
+ return body;
15
+ }
16
+
17
+ export const installInfo = (name, client = "") =>
18
+ api(`/api/v1/install/${name.split("/").map(encodeURIComponent).join("/")}${client ? `?client=${encodeURIComponent(client)}` : ""}`);
19
+
20
+ // What will change on disk for one install option; shared by the CLI and the local MCP server.
21
+ export function plan(info, optionIndex = 0) {
22
+ const o = info.options[optionIndex];
23
+ if (!o) throw new Error(`No install option ${optionIndex}. Options: ${info.options.map((x, i) => `${i}=${x.option}`).join(", ")}`);
24
+ const name = info.name.split("/").pop().replace(/[^\w-]/g, "-");
25
+ const high = info.signals.filter((s) => s.severity === "high");
26
+ const blanks = o.launch.type === "stdio" ? o.launch.env : o.launch.headers;
27
+ return { o, name, high, blanks };
28
+ }
29
+
30
+ export function describe(info, p) {
31
+ const lines = [
32
+ `${info.title} (${info.name}) v${info.version}`,
33
+ `Install option: ${p.o.option}`,
34
+ `Will run on your machine: ${p.o.runs}`,
35
+ `Config file: ${p.o.file.path.default}`,
36
+ info.signals.length ? "Risk signals:" : "Risk signals: none found in registry metadata (code not scanned; not a safety guarantee)",
37
+ ...info.signals.map((s) => ` [${s.severity}] ${s.message} (${s.evidence})`),
38
+ ];
39
+ if (p.blanks.length) lines.push(`You will need to fill in: ${p.blanks.join(", ")}`);
40
+ return lines.join("\n");
41
+ }
package/src/files.mjs ADDED
@@ -0,0 +1,148 @@
1
+ // Config file editing with backup and undo. Pure helpers are exported for tests.
2
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { dirname, join } from "node:path";
5
+
6
+ export function resolvePath(path, { platform = process.platform, home = homedir(), env = process.env } = {}) {
7
+ const p = path[platform] ?? path.default;
8
+ return p.replace(/^~(?=\/|$)/, home).replace(/%(\w+)%/g, (_, k) => env[k] ?? `%${k}%`);
9
+ }
10
+
11
+ // Adds `name` under `key` in a JSON config. Refuses rather than guessing: invalid JSON (e.g. comments) or an existing entry.
12
+ export function addJson(text, key, name, entry) {
13
+ let doc = {};
14
+ if (text && text.trim()) {
15
+ try {
16
+ doc = JSON.parse(text);
17
+ } catch {
18
+ throw new Error("The config file is not plain JSON (it may contain comments). Add the server by hand with the snippet from duom.");
19
+ }
20
+ }
21
+ if (typeof doc !== "object" || doc === null || Array.isArray(doc)) throw new Error("The config file does not hold a JSON object.");
22
+ const table = (doc[key] ??= {});
23
+ if (table[name]) throw new Error(`A server named "${name}" is already configured there. Remove it first.`);
24
+ table[name] = entry;
25
+ return JSON.stringify(doc, null, 2) + "\n";
26
+ }
27
+
28
+ export function addToml(text, name, snippet) {
29
+ // name is already limited to [A-Za-z0-9_-], so it is safe inside a pattern.
30
+ const header = new RegExp('^\\[mcp_servers\\."?' + name + '"?\\]', "m");
31
+ if (text && header.test(text)) throw new Error(`A server named "${name}" is already configured there. Remove it first.`);
32
+ const base = text ? text.replace(/\s*$/, "\n\n") : "";
33
+ return base + snippet + "\n";
34
+ }
35
+
36
+ // The reverse of addJson / addToml / mergeRule: take out only what duom added, keep everything else as it is now.
37
+ export function removeJson(text, key, name) {
38
+ const doc = JSON.parse(text);
39
+ if (!doc?.[key]?.[name]) return text;
40
+ delete doc[key][name];
41
+ if (!Object.keys(doc[key]).length) delete doc[key];
42
+ return JSON.stringify(doc, null, 2) + "\n";
43
+ }
44
+
45
+ // Drops [mcp_servers.<name>] and its sub-tables ([mcp_servers.<name>.env] ...), up to the next other table.
46
+ export function removeToml(text, name) {
47
+ const heads = [`[mcp_servers.${name}`, `[mcp_servers."${name}"`];
48
+ const own = (l) => heads.some((h) => l.startsWith(h + "]") || l.startsWith(h + "."));
49
+ const lines = text.split("\n");
50
+ const start = lines.findIndex(own);
51
+ if (start < 0) return text;
52
+ let end = start + 1;
53
+ while (end < lines.length && !(lines[end].startsWith("[") && !own(lines[end]))) end++;
54
+ lines.splice(start, end - start);
55
+ return lines.join("\n").replace(/\n{3,}/g, "\n\n").replace(/^\n+/, "");
56
+ }
57
+
58
+ export function removeRule(text, name) {
59
+ const open = `<!-- duom:${name} -->`;
60
+ const close = `<!-- /duom:${name} -->`;
61
+ const a = text.indexOf(open);
62
+ const b = text.indexOf(close, a);
63
+ if (a < 0 || b < 0) return text;
64
+ return (text.slice(0, a) + text.slice(b + close.length)).replace(/\n{3,}/g, "\n\n").replace(/^\n+/, "");
65
+ }
66
+
67
+ const stateDir = (home) => join(home, ".duom");
68
+ const historyFile = (home) => join(stateDir(home), "history.json");
69
+ const readHistory = (home) => (existsSync(historyFile(home)) ? JSON.parse(readFileSync(historyFile(home), "utf8")) : []);
70
+
71
+ // Writes `next` to `file`, keeping a backup of the old file and a history entry for undo.
72
+ // `entry` says what was added ({kind: "json", key, name} | {kind: "toml", name} | {kind: "rule", name}), so undo
73
+ // removes just that and keeps any edits made to the file since. The backup is a safety copy, not what undo uses.
74
+ export function writeWithBackup(file, next, meta, home = homedir(), entry = null) {
75
+ const existed = existsSync(file);
76
+ let backup = null;
77
+ if (existed) {
78
+ const dir = join(stateDir(home), "backups");
79
+ mkdirSync(dir, { recursive: true });
80
+ backup = join(dir, `${Date.now()}-${file.replace(/[^\w.-]+/g, "_").slice(-80)}`);
81
+ copyFileSync(file, backup);
82
+ }
83
+ mkdirSync(dirname(file), { recursive: true });
84
+ writeFileSync(file, next);
85
+ const history = readHistory(home);
86
+ history.push({ ...meta, file, backup, entry, created: !existed, at: new Date().toISOString() });
87
+ mkdirSync(stateDir(home), { recursive: true });
88
+ writeFileSync(historyFile(home), JSON.stringify(history, null, 2));
89
+ return backup;
90
+ }
91
+
92
+ // Records a folder duom created (a skill), so undo can remove it.
93
+ export function recordDir(dir, meta, home = homedir()) {
94
+ const history = readHistory(home);
95
+ history.push({ ...meta, dir, at: new Date().toISOString() });
96
+ mkdirSync(stateDir(home), { recursive: true });
97
+ writeFileSync(historyFile(home), JSON.stringify(history, null, 2));
98
+ }
99
+
100
+ // Returns what was done, for the message.
101
+ function undoOne(e) {
102
+ if (e.dir) {
103
+ rmSync(e.dir, { recursive: true, force: true });
104
+ return `removed ${e.dir}`;
105
+ }
106
+ if (!existsSync(e.file)) return `${e.file} is already gone`;
107
+ if (!e.entry) {
108
+ // History written by duom 0.x: no entry record, so the whole-file backup is all there is.
109
+ if (e.backup) copyFileSync(e.backup, e.file);
110
+ else rmSync(e.file, { force: true });
111
+ return e.backup ? `restored ${e.file}` : `removed ${e.file}`;
112
+ }
113
+ const text = readFileSync(e.file, "utf8");
114
+ const { kind, key, name } = e.entry;
115
+ const next = kind === "json" ? removeJson(text, key, name) : kind === "toml" ? removeToml(text, name) : removeRule(text, name);
116
+ // A file duom created and that now holds nothing else (an @AGENTS.md line counts as nothing) goes away.
117
+ const leftover = kind === "json" ? Object.keys(JSON.parse(next)).length : next.replace(/^@AGENTS\.md\s*$/m, "").trim().length;
118
+ if (e.created && !leftover) {
119
+ rmSync(e.file, { force: true });
120
+ return `removed ${e.file}`;
121
+ }
122
+ if (next !== text) writeFileSync(e.file, next);
123
+ return next === text ? `nothing of it left in ${e.file}` : `took it out of ${e.file}`;
124
+ }
125
+
126
+ // Undoes the last add: restores backups, removes files and folders duom created.
127
+ // Entries from one add share a group (a stack writes several), and are undone together. Returns them, newest first.
128
+ export function undoLast(home = homedir()) {
129
+ const history = readHistory(home);
130
+ const last = history.at(-1);
131
+ if (!last) return null;
132
+ const done = [];
133
+ while (history.length && (done.length === 0 || (last.group && history.at(-1).group === last.group))) {
134
+ const e = history.pop();
135
+ done.push({ ...e, result: undoOne(e) });
136
+ }
137
+ writeFileSync(historyFile(home), JSON.stringify(history, null, 2));
138
+ return done;
139
+ }
140
+
141
+ // Removes one item by name, however long ago it was added. A stack name removes every member that add put in.
142
+ export function removeItem(name, home = homedir()) {
143
+ const history = readHistory(home);
144
+ const hit = (e) => e.item === name || e.group?.startsWith(`${name}@`);
145
+ const done = history.filter(hit).reverse().map((e) => ({ ...e, result: undoOne(e) }));
146
+ writeFileSync(historyFile(home), JSON.stringify(history.filter((e) => !hit(e)), null, 2));
147
+ return done;
148
+ }
@@ -0,0 +1,113 @@
1
+ // Runs catalog MCP servers for the local MCP server (mcp.mjs), so an agent can use one mid-conversation.
2
+ // Approval happens in mcp.mjs; this file only turns a launch into a process or connection and forwards calls.
3
+ // Key values stay on this machine: they come from ~/.duom/keys.env or the environment and are never returned.
4
+ import { spawnSync } from "node:child_process";
5
+ import { existsSync, readFileSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
8
+ import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
9
+ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
10
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
11
+
12
+ export const KEYS_FILE = "~/.duom/keys.env";
13
+ const MAX_RUNNING = 5;
14
+ const TIMEOUT = 120_000;
15
+
16
+ export function parseKeys(text) {
17
+ const out = {};
18
+ for (const line of text.split(/\r?\n/)) {
19
+ const m = line.match(/^\s*([\w.-]+)\s*=\s*(.*?)\s*$/);
20
+ if (m && !line.trimStart().startsWith("#")) out[m[1]] = m[2].replace(/^(["'])(.*)\1$/, "$2");
21
+ }
22
+ return out;
23
+ }
24
+
25
+ export const loadKeys = (home) => {
26
+ const file = join(home, ".duom", "keys.env");
27
+ return existsSync(file) ? parseKeys(readFileSync(file, "utf8")) : {};
28
+ };
29
+
30
+ // `key` scopes a value to one server ("github-mcp-server.Authorization"), for names two servers share.
31
+ export function resolveLaunch(launch, key, keys, env = process.env) {
32
+ const missing = [];
33
+ const get = (name) => {
34
+ const v = keys[`${key}.${name}`] ?? keys[name] ?? env[name];
35
+ if (v === undefined || v === "") missing.push(name);
36
+ return v;
37
+ };
38
+ const pick = (names) => Object.fromEntries(names.map((n) => [n, get(n)]));
39
+ if (launch.type === "stdio") {
40
+ const envOut = pick(launch.env);
41
+ const args = launch.args.map((a) => {
42
+ const hint = a.match(/<[^>]+>/);
43
+ if (hint) {
44
+ missing.push(`argument ${hint[0]}`);
45
+ return a;
46
+ }
47
+ return a.replace(/\{([\w.-]+)\}/g, (_, n) => get(n) ?? "");
48
+ });
49
+ return { ready: !missing.length, missing, spec: { type: "stdio", command: launch.command, args, env: envOut } };
50
+ }
51
+ const headers = pick(launch.headers);
52
+ return { ready: !missing.length, missing, spec: { type: launch.type, url: launch.url, headers } };
53
+ }
54
+
55
+ export const hasCommand = (cmd) => spawnSync(process.platform === "win32" ? "where" : "which", [cmd], { stdio: "ignore" }).status === 0;
56
+
57
+ export class Gateway {
58
+ #running = new Map(); // id -> { client, transport }
59
+
60
+ has = (id) => this.#running.has(id);
61
+
62
+ async start(id, spec) {
63
+ if (this.#running.size >= MAX_RUNNING) throw new Error(`At most ${MAX_RUNNING} servers at once. Stop one with stop_server first.`);
64
+ const transport =
65
+ spec.type === "stdio"
66
+ ? new StdioClientTransport({ command: spec.command, args: spec.args, env: spec.env, stderr: "ignore" })
67
+ : spec.type === "sse"
68
+ ? new SSEClientTransport(new URL(spec.url), { requestInit: { headers: spec.headers } })
69
+ : new StreamableHTTPClientTransport(new URL(spec.url), { requestInit: { headers: spec.headers } });
70
+ const client = new Client({ name: "duom-local", version: "1.0.0" });
71
+ try {
72
+ await client.connect(transport, { timeout: TIMEOUT });
73
+ this.#running.set(id, { client, transport });
74
+ return (await client.listTools(undefined, { timeout: TIMEOUT })).tools;
75
+ } catch (e) {
76
+ this.#running.delete(id);
77
+ await client.close().catch(() => {});
78
+ throw e;
79
+ }
80
+ }
81
+
82
+ async tools(id) {
83
+ return (await this.#get(id).client.listTools(undefined, { timeout: TIMEOUT })).tools;
84
+ }
85
+
86
+ call(id, tool, args) {
87
+ try {
88
+ return this.#get(id).client.callTool({ name: tool, arguments: args ?? {} }, undefined, { timeout: TIMEOUT });
89
+ } catch (e) {
90
+ return Promise.reject(e);
91
+ }
92
+ }
93
+
94
+ async stop(id) {
95
+ const r = this.#running.get(id);
96
+ this.#running.delete(id);
97
+ await r?.client.close().catch(() => {});
98
+ return !!r;
99
+ }
100
+
101
+ closeAll = () => Promise.all([...this.#running.keys()].map((id) => this.stop(id)));
102
+
103
+ // Synchronous, for process "exit": kill children that would otherwise outlive this process.
104
+ killAll() {
105
+ for (const { transport } of this.#running.values()) if (transport.pid) try { process.kill(transport.pid); } catch {}
106
+ }
107
+
108
+ #get(id) {
109
+ const r = this.#running.get(id);
110
+ if (!r) throw new Error(`${id} is not running. Call use_server with this name first.`);
111
+ return r;
112
+ }
113
+ }
@@ -0,0 +1,12 @@
1
+ import { readFileSync, existsSync } from "node:fs";
2
+ import { addJson, addToml, resolvePath, writeWithBackup } from "./files.mjs";
3
+
4
+ // Writes the planned entry into the client's config file. Returns the file path.
5
+ export function apply(info, p, client, meta = { item: info.name, version: info.version, client }) {
6
+ const file = resolvePath(p.o.file.path);
7
+ const text = existsSync(file) ? readFileSync(file, "utf8") : null;
8
+ const next = p.o.file.format === "json" ? addJson(text, p.o.file.key, p.name, p.o.entry) : addToml(text, p.name, p.o.snippet);
9
+ const entry = p.o.file.format === "json" ? { kind: "json", key: p.o.file.key, name: p.name } : { kind: "toml", name: p.name };
10
+ writeWithBackup(file, next, meta, undefined, entry);
11
+ return file;
12
+ }
package/src/items.mjs ADDED
@@ -0,0 +1,116 @@
1
+ // Turns any DuoM item (MCP server, skill, rule, stack) into install steps: what will change, its risk signals, and apply().
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { dirname, join, resolve, sep } from "node:path";
4
+ import { describe, installInfo, plan } from "./api.mjs";
5
+ import { apply as applyMcp } from "./install.mjs";
6
+ import { recordDir, writeWithBackup } from "./files.mjs";
7
+
8
+ const RAW = "https://raw.githubusercontent.com/";
9
+ const MAX_SKILL = 10 * 1024 * 1024;
10
+
11
+ // File paths come from the API: each must stay inside the skill folder.
12
+ export function safeJoin(root, rel) {
13
+ const base = resolve(root);
14
+ const full = resolve(base, rel);
15
+ if (rel.includes("\0") || !full.startsWith(base + sep)) throw new Error(`Refusing a file path outside the skill folder: ${rel}`);
16
+ return full;
17
+ }
18
+
19
+ // Appends a rule block once; the duom markers make a second add fail instead of duplicating it.
20
+ export function mergeRule(text, name, block) {
21
+ if (text?.includes(`<!-- duom:${name} -->`)) throw new Error(`${name} is already in that file. Remove its duom block first.`);
22
+ return (text && text.trim() ? text.replace(/\s*$/, "\n\n") : "") + block + "\n";
23
+ }
24
+
25
+ const signalLines = (info, note) => [
26
+ info.signals.length ? "Risk signals:" : `Risk signals: none found (${note}; not a safety guarantee)`,
27
+ ...info.signals.map((s) => ` [${s.severity}] ${s.message} (${s.evidence})`),
28
+ ];
29
+ const highOf = (info) => info.signals.filter((s) => s.severity === "high");
30
+
31
+ // The chosen tool has no documented place for this type: shown, then skipped, while the rest of a stack goes ahead.
32
+ const refused = (info, why) => ({ info, high: [], text: `${info.title} (${info.name}): skipped. ${why}`, apply: async () => { throw new Error(why); } });
33
+
34
+ function skillStep(info, opts) {
35
+ if (info.skill.error) return refused(info, info.skill.error);
36
+ const dir = opts.global ? join(opts.home, info.skill.folder) : resolve(opts.cwd, info.skill.folder);
37
+ const total = info.skill.files.reduce((n, f) => n + f.size, 0);
38
+ if (total > MAX_SKILL) throw new Error(`${info.name} is ${Math.round(total / 1e6)} MB, over the ${MAX_SKILL / 1e6} MB limit.`);
39
+ return {
40
+ info,
41
+ high: highOf(info),
42
+ text: [`${info.title} (${info.name}) @${info.version}`, `Skill folder: ${dir}`, `Files: ${info.skill.files.length} from GitHub at the checked commit (license included), plus a source notice`, ...signalLines(info, "skill files read by DuoM")].join("\n"),
43
+ async apply(meta) {
44
+ if (existsSync(dir)) throw new Error(`${dir} already exists. Remove it first.`);
45
+ // Download everything before writing anything, so a failed download leaves no half-installed skill.
46
+ const files = await Promise.all(
47
+ info.skill.files.map(async (f) => {
48
+ if (!f.url.startsWith(RAW)) throw new Error(`Unexpected file source: ${f.url}`);
49
+ const res = await fetch(f.url);
50
+ if (!res.ok) throw new Error(`Download failed (${res.status}): ${f.path}`);
51
+ return [safeJoin(dir, f.path), Buffer.from(await res.arrayBuffer())];
52
+ }),
53
+ );
54
+ mkdirSync(dir, { recursive: true });
55
+ recordDir(dir, meta, opts.home);
56
+ for (const [path, body] of files) {
57
+ mkdirSync(dirname(path), { recursive: true });
58
+ writeFileSync(path, body);
59
+ }
60
+ // Where it came from and under which license: the license asks that this travels with the copy.
61
+ if (info.skill.notice) writeFileSync(safeJoin(dir, info.skill.notice.path), info.skill.notice.text);
62
+ return dir;
63
+ },
64
+ };
65
+ }
66
+
67
+ // Claude Code reads CLAUDE.md, and reads AGENTS.md only while there is no CLAUDE.md. So a CLAUDE.md duom creates
68
+ // next to an existing AGENTS.md starts with @AGENTS.md (Anthropic's documented import), or AGENTS.md would stop being read.
69
+ // And a rule already in AGENTS.md that CLAUDE.md imports is not added again: Claude would read it twice.
70
+ export function claudeStart(text, agentsText, name) {
71
+ const imports = text === null ? agentsText !== null : /^@AGENTS\.md\s*$/m.test(text);
72
+ if (imports && agentsText?.includes(`<!-- duom:${name} -->`))
73
+ throw new Error(`${name} is already in AGENTS.md, which CLAUDE.md imports, so Claude Code reads it already.`);
74
+ return text === null && agentsText !== null ? "@AGENTS.md\n" : text;
75
+ }
76
+
77
+ function ruleStep(info, opts) {
78
+ if (info.rule.error) return refused(info, info.rule.error);
79
+ const file = resolve(opts.cwd, info.rule.file);
80
+ const claude = info.rule.file === "CLAUDE.md";
81
+ const agents = resolve(opts.cwd, "AGENTS.md");
82
+ return {
83
+ info,
84
+ high: [],
85
+ text: [`${info.title} (${info.name})`, `Adds one marked block to: ${file} (nothing else in the file changes)`].join("\n"),
86
+ async apply(meta) {
87
+ let text = existsSync(file) ? readFileSync(file, "utf8") : null;
88
+ if (claude) text = claudeStart(text, existsSync(agents) ? readFileSync(agents, "utf8") : null, info.name);
89
+ writeWithBackup(file, mergeRule(text, info.name, info.rule.block), meta, opts.home, { kind: "rule", name: info.name });
90
+ return file;
91
+ },
92
+ };
93
+ }
94
+
95
+ function mcpStep(info, client, opts) {
96
+ const p = plan(info, opts.option ?? 0);
97
+ return { info, high: p.high, blanks: p.blanks, text: describe(info, p), apply: async (meta) => applyMcp(info, p, client, meta) };
98
+ }
99
+
100
+ async function step(name, client, opts) {
101
+ const info = await installInfo(name, client);
102
+ if (info.type === "skill") return skillStep(info, opts);
103
+ if (info.type === "rule") return ruleStep(info, opts);
104
+ if (info.type === "mcp" || info.options) return mcpStep(info, client, opts);
105
+ throw new Error(`${name}: DuoM cannot install this type (${info.type}) yet.`);
106
+ }
107
+
108
+ // One step per item; a stack expands to its members.
109
+ export async function prepare(name, client, opts) {
110
+ if (!name.startsWith("stack/")) return [await step(name, client, opts)];
111
+ const info = await installInfo(name, client);
112
+ const members = info.members.filter((m) => m.available);
113
+ if (!client && members.some((m) => m.type === "mcp"))
114
+ throw new Error(`${info.title} includes MCP servers, which need a client: add --client <cursor|vscode|claude-code|codex|grok|gemini>.`);
115
+ return Promise.all(members.map((m) => step(m.name, client, opts)));
116
+ }
package/src/mcp.mjs ADDED
@@ -0,0 +1,186 @@
1
+ // Local MCP server (stdio): lets an agent search DuoM and install an item (MCP server, skill, rule, stack) on this machine.
2
+ // Every install needs the user's approval through MCP elicitation; without it the tool refuses and hands back the CLI command.
3
+ // use_server/call_tool: the agent can also run a catalog server right away; the user approves each server once per session.
4
+ import { homedir } from "node:os";
5
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
6
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
7
+ import { z } from "zod";
8
+ import { api, installInfo } from "./api.mjs";
9
+ import { Gateway, hasCommand, KEYS_FILE, loadKeys, resolveLaunch } from "./gateway.mjs";
10
+ import { prepare } from "./items.mjs";
11
+
12
+ const CLIENTS = ["cursor", "vscode", "lmstudio", "claude-code", "codex", "grok", "gemini"];
13
+ const text = (t) => ({ content: [{ type: "text", text: typeof t === "string" ? t : JSON.stringify(t) }] });
14
+ // No high signals: Accept alone approves (the box starts checked). High signals: the box must be ticked on purpose.
15
+ const approval = (high, title) => ({
16
+ type: "object",
17
+ properties: { approve: { type: "boolean", title, default: !high } },
18
+ ...(high ? { required: ["approve"] } : {}),
19
+ });
20
+ const approved = (answer, high) => answer.action === "accept" && (answer.content?.approve === true || (!high && answer.content?.approve !== false));
21
+ // Only what an agent needs to pick an item; empty values left out. Icons, dates and score internals cost tokens and help no one.
22
+ export const brief = ({ total, hasMore, items }) => ({
23
+ total,
24
+ hasMore,
25
+ items: items.map((r) =>
26
+ Object.fromEntries(
27
+ Object.entries({
28
+ name: r.name, title: r.title, description: r.description, runs: r.kinds?.join(","), auth: r.auth,
29
+ signals: r.signalCount || undefined, highestSignal: r.signalLevel, popularity: r.popularity,
30
+ stars: r.stars, weeklyDownloads: r.weeklyDownloads, installs: r.installs,
31
+ }).filter(([, v]) => v != null && v !== ""),
32
+ ),
33
+ ),
34
+ });
35
+ const path = (name) => name.split("/").map(encodeURIComponent).join("/");
36
+
37
+ export async function serve() {
38
+ const server = new McpServer({ name: "duom-local", version: "1.0.1" });
39
+
40
+ server.registerTool(
41
+ "search_catalog",
42
+ {
43
+ description: "Search DuoM: MCP servers, skills, stacks and rules, ranked by popularity.",
44
+ inputSchema: { query: z.string().max(100), type: z.enum(["all", "mcp", "skill", "stack", "rule"]).optional() },
45
+ annotations: { readOnlyHint: true },
46
+ },
47
+ async ({ query, type }) => text(brief(await api(`/api/v1/items?q=${encodeURIComponent(query)}${type ? `&type=${type}` : ""}`))),
48
+ );
49
+
50
+ server.registerTool(
51
+ "get_item",
52
+ { description: "Details and risk signals of one DuoM item.", inputSchema: { name: z.string().max(300) }, annotations: { readOnlyHint: true } },
53
+ async ({ name }) => text(await api(`/api/v1/items/${path(name)}`)),
54
+ );
55
+
56
+ server.registerTool(
57
+ "install_item",
58
+ {
59
+ description:
60
+ "Install a DuoM item on this machine: an MCP server into a client's config, a skill into the project's skills folder, " +
61
+ "a rule into AGENTS.md (or CLAUDE.md/GEMINI.md), or every member of a stack. The user must approve in their client; " +
62
+ "changed files are backed up and `npx @duom/cli@1 undo` reverts the whole install.",
63
+ inputSchema: {
64
+ name: z.string().max(300).describe("Item name, e.g. io.github.owner/repo, skill/owner/repo/name, rule/nextjs, stack/nextjs-supabase"),
65
+ client: z.enum(CLIENTS).optional().describe("Required for MCP servers and stacks that include them"),
66
+ global: z.boolean().optional().describe("Skills: install for every project (home folder) instead of this project"),
67
+ option: z.number().int().min(0).max(10).optional().describe("MCP install option index (0 = first)"),
68
+ },
69
+ annotations: { destructiveHint: false, openWorldHint: true },
70
+ },
71
+ async ({ name, client, global, option }) => {
72
+ const steps = await prepare(name, client ?? "", { cwd: process.cwd(), home: homedir(), global, option: option ?? 0 });
73
+ const details = steps.map((s) => s.text).join("\n\n");
74
+ const high = steps.flatMap((s) => s.high);
75
+ const cli = `npx @duom/cli@1 add ${name}${client ? ` --client ${client}` : ""}${global ? " --global" : ""}${option ? ` --option ${option}` : ""}`;
76
+ if (!server.server.getClientCapabilities()?.elicitation)
77
+ return text(`Not installed: this client cannot ask the user for approval.\n\n${details}\n\nAsk the user to run it themselves:\n${cli}`);
78
+ const answer = await server.server.elicitInput({
79
+ message: `Install this?\n\n${details}${high.length ? "\n\nWARNING: high risk signals above." : ""}`,
80
+ requestedSchema: approval(high.length > 0, high.length ? "I read the high risk signals and want to install" : "Install it"),
81
+ });
82
+ if (!approved(answer, high.length > 0)) return text("Not installed: the user did not approve.");
83
+ const group = `${name}@${Date.now()}`;
84
+ const lines = [];
85
+ for (const s of steps) {
86
+ try {
87
+ lines.push(`Added ${s.info.title} -> ${await s.apply({ item: s.info.name, version: s.info.version, client: client ?? null, group })}`);
88
+ if (s.blanks?.length) lines.push(` The user must fill in: ${s.blanks.join(", ")}`);
89
+ } catch (e) {
90
+ lines.push(`Skipped ${s.info.title}: ${e.message}`);
91
+ }
92
+ }
93
+ return text(`${lines.join("\n")}\nUndo with: npx @duom/cli@1 undo (or npx @duom/cli@1 remove <name>)`);
94
+ },
95
+ );
96
+
97
+ const gateway = new Gateway();
98
+ process.on("exit", () => gateway.killAll());
99
+ const where = (spec) => (spec.type === "stdio" ? [spec.command, ...spec.args].join(" ") : `connects to ${spec.url}`);
100
+
101
+ server.registerTool(
102
+ "use_server",
103
+ {
104
+ description:
105
+ "Start a DuoM MCP server on this machine so you can use its tools now, with call_tool. The user approves each server once " +
106
+ "per session (they see the exact command, the keys it reads and its risk signals). Returns the server's tools. " +
107
+ `API keys are never passed through you: the user puts them in ${KEYS_FILE} (NAME=value) or their environment.`,
108
+ inputSchema: {
109
+ name: z.string().max(300).describe("MCP server name from search_catalog, e.g. io.github.owner/repo"),
110
+ option: z.number().int().min(0).max(10).optional().describe("Launch option index; default: the first one that can run here"),
111
+ },
112
+ annotations: { openWorldHint: true },
113
+ },
114
+ async ({ name, option }) => {
115
+ if (gateway.has(name)) return text({ server: name, tools: await gateway.tools(name) });
116
+ const info = await installInfo(name, "claude-code"); // the launch is the same for every client; the API just needs one
117
+ if (!info.options?.length) return text(`${name} has no way to run it (type ${info.type}). Only MCP servers can be used with use_server.`);
118
+ const key = name.split("/").pop().replace(/[^\w-]/g, "-");
119
+ const keys = loadKeys(homedir());
120
+ const tried = (option === undefined ? info.options.map((o, i) => [o, i]) : [[info.options[option], option]]).map(([o, i]) => {
121
+ if (!o) return { i, why: [`no option ${i}`] };
122
+ const r = resolveLaunch(o.launch, key, keys);
123
+ if (o.launch.type === "stdio" && !hasCommand(o.launch.command)) r.missing.push(`the "${o.launch.command}" command on this machine`);
124
+ return { i, o, r, why: r.missing };
125
+ });
126
+ const pick = tried.find((t) => t.o && !t.why.length);
127
+ if (!pick)
128
+ return text(
129
+ `Not started: no launch option of ${name} can run yet.\n` +
130
+ tried.map((t) => ` option ${t.i}${t.o ? ` (${t.o.option})` : ""}: needs ${t.why.join(", ")}`).join("\n") +
131
+ `\nAsk the user to add the missing keys to ${KEYS_FILE} as NAME=value (or ${key}.NAME=value for this server only), ` +
132
+ "or to install the missing command. Never ask them to paste key values into the chat.",
133
+ );
134
+ if (!server.server.getClientCapabilities()?.elicitation)
135
+ return text("Not started: this client cannot ask the user for approval, and DuoM never runs a server without it.");
136
+ const high = info.signals.filter((s) => s.severity === "high");
137
+ const used = pick.o.launch.type === "stdio" ? pick.o.launch.env : pick.o.launch.headers;
138
+ const details = [
139
+ `${info.title} (${info.name}) v${info.version}`,
140
+ `Will run: ${where(pick.r.spec)}`,
141
+ used.length ? `Reads these keys from ${KEYS_FILE} or your environment: ${used.join(", ")}` : "Reads no keys",
142
+ info.signals.length ? "Risk signals:" : "Risk signals: none found in registry metadata (code not scanned; not a safety guarantee)",
143
+ ...info.signals.map((s) => ` [${s.severity}] ${s.message} (${s.evidence})`),
144
+ "Approval lasts until this session ends.",
145
+ ].join("\n");
146
+ const answer = await server.server.elicitInput({
147
+ message: `Start this MCP server for the agent to use?\n\n${details}${high.length ? "\n\nWARNING: high risk signals above." : ""}`,
148
+ requestedSchema: approval(high.length > 0, high.length ? "I read the high risk signals and want to run it" : "Run it"),
149
+ });
150
+ if (!approved(answer, high.length > 0)) return text("Not started: the user did not approve.");
151
+ try {
152
+ return text({ server: name, tools: await gateway.start(name, pick.r.spec) });
153
+ } catch (e) {
154
+ return text(`Could not start ${name}: ${e.message}`);
155
+ }
156
+ },
157
+ );
158
+
159
+ server.registerTool(
160
+ "call_tool",
161
+ {
162
+ description: "Call a tool of a server started with use_server. Returns that tool's result as is.",
163
+ inputSchema: {
164
+ server: z.string().max(300),
165
+ tool: z.string().max(200),
166
+ arguments: z.record(z.string(), z.unknown()).optional(),
167
+ },
168
+ annotations: { openWorldHint: true },
169
+ },
170
+ async ({ server: id, tool, arguments: args }) => {
171
+ try {
172
+ return await gateway.call(id, tool, args);
173
+ } catch (e) {
174
+ return { ...text(e.message), isError: true };
175
+ }
176
+ },
177
+ );
178
+
179
+ server.registerTool(
180
+ "stop_server",
181
+ { description: "Stop a server started with use_server.", inputSchema: { server: z.string().max(300) } },
182
+ async ({ server: id }) => text((await gateway.stop(id)) ? `Stopped ${id}.` : `${id} was not running.`),
183
+ );
184
+
185
+ await server.connect(new StdioServerTransport());
186
+ }