yats-toolkit 0.4.2 → 0.5.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/src/connect.js CHANGED
@@ -6,11 +6,18 @@
6
6
  * yats connect <agent> Show config for specific agent
7
7
  * yats connect --install Place files in current directory
8
8
  * yats connect --link Show GitHub links
9
+ *
10
+ * Install behavior (never breaks the user's files):
11
+ * - File does not exist → create it
12
+ * - JSON files → merge `mcpServers` (existing entries preserved)
13
+ * - TOML/Codex config → append only the `[mcp_servers.yats]` section
14
+ * - Text/Skill files → warn, show what will be added, ask, then append
9
15
  */
10
16
  import { writeFileSync, readFileSync, existsSync, mkdirSync } from "node:fs";
11
17
  import { join, dirname } from "node:path";
12
18
  import { createInterface } from "node:readline";
13
19
  import { homedir } from "node:os";
20
+ import { spawnSync } from "node:child_process";
14
21
 
15
22
  const B = "\x1b[1m";
16
23
  const D = "\x1b[2m";
@@ -28,8 +35,8 @@ const AGENTS = {
28
35
  name: "Claude Code",
29
36
  transport: "stdio bridge",
30
37
  files: [
31
- { src: "connect/claude/yats/SKILL.md", dest: ".claude/skills/yats/SKILL.md", type: "skill" },
32
- { src: "connect/claude/.mcp.json", dest: ".mcp.json", type: "json" },
38
+ { src: "connect/claude/SKILL.md", dest: ".claude/skills/yats/SKILL.md", type: "skill" },
39
+ { src: "connect/claude/mcp.json", dest: ".mcp.json", type: "json" },
33
40
  ],
34
41
  url: "https://github.com/fvinciarelli/yats.ai/tree/main/connect/claude",
35
42
  },
@@ -46,7 +53,7 @@ const AGENTS = {
46
53
  name: "GitHub Copilot",
47
54
  transport: "stdio bridge",
48
55
  files: [
49
- { src: "connect/copilot/instructions.md", dest: ".github/instructions.md", type: "text" },
56
+ { src: "connect/copilot/instructions.md", dest: ".github/copilot-instructions.md", type: "text" },
50
57
  { src: "connect/copilot/mcp.json", dest: ".copilot/mcp.json", type: "json" },
51
58
  ],
52
59
  url: "https://github.com/fvinciarelli/yats.ai/tree/main/connect/copilot",
@@ -79,6 +86,51 @@ function getYatsMcpConfig() {
79
86
  }
80
87
  }
81
88
 
89
+ function getFileContent(srcPath) {
90
+ // Templates ship inside the package (connect/ dir) — resolves from src/ → ../connect/
91
+ try {
92
+ const pkgDir = dirname(new URL(import.meta.url).pathname);
93
+ const installedPath = join(pkgDir, "..", srcPath);
94
+ if (existsSync(installedPath)) {
95
+ return readFileSync(installedPath, "utf-8");
96
+ }
97
+ } catch { /* not installed as npm package */ }
98
+ return null;
99
+ }
100
+
101
+ // ============================================================
102
+ // Render / template helpers
103
+ // ============================================================
104
+
105
+ function renderContent(srcPath) {
106
+ const content = getFileContent(srcPath);
107
+ if (content === null) {
108
+ console.log(` ${RED}✗${R} Missing template ${srcPath} — reinstall yats-toolkit`);
109
+ return null;
110
+ }
111
+ // YATS identifies repos by their full rootPath — instruct the full path,
112
+ // not the basename, so the server matches by path and never by name.
113
+ return content.replaceAll("__REPO_PATH__", process.cwd());
114
+ }
115
+
116
+ // Split YAML frontmatter from the body (only meaningful at the top of a file)
117
+ function splitFrontmatter(content) {
118
+ if (content.startsWith("---")) {
119
+ const end = content.indexOf("\n---", 3);
120
+ if (end !== -1) {
121
+ return {
122
+ frontmatter: content.slice(0, end + 4),
123
+ body: content.slice(end + 5),
124
+ };
125
+ }
126
+ }
127
+ return { frontmatter: "", body: content };
128
+ }
129
+
130
+ function appendMarker(agentKey) {
131
+ return `\n---\n\n<!-- Added by \`yats connect ${agentKey}\` — YATS code intelligence. Remove this block if you don't need it. -->\n\n`;
132
+ }
133
+
82
134
  // ============================================================
83
135
  // Install helpers
84
136
  // ============================================================
@@ -93,7 +145,60 @@ function safeMergeJson(existingPath, newEntry) {
93
145
  return JSON.stringify(obj, null, 2) + "\n";
94
146
  }
95
147
 
96
- async function installFiles(agentKey) {
148
+ // Single shared readline so piped stdin keeps working across multiple prompts
149
+ // Prompt helper that works both interactively (TTY) and with piped stdin
150
+ // (e.g. `printf 'y\n' | yats connect --install codex`). readline.question()
151
+ // hangs on a finished pipe stream, so piped input is collected upfront.
152
+ // Always call close() when done — an open readline keeps the process alive.
153
+ function makePrompter() {
154
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
155
+ if (process.stdin.isTTY) {
156
+ return {
157
+ ask: (question) => new Promise((resolve) => rl.question(question, resolve)),
158
+ close: () => rl.close(),
159
+ };
160
+ }
161
+ const all = (async () => {
162
+ const lines = [];
163
+ for await (const line of rl) lines.push(line);
164
+ return lines;
165
+ })();
166
+ let idx = 0;
167
+ return {
168
+ ask: async (question) => {
169
+ process.stdout.write(question);
170
+ const lines = await all;
171
+ return idx < lines.length ? lines[idx++] : "";
172
+ },
173
+ close: () => rl.close(),
174
+ };
175
+ }
176
+
177
+ function previewBlock(label, content) {
178
+ console.log(` ${D}${label}:${R}`);
179
+ for (const line of content.trimEnd().split("\n")) {
180
+ console.log(` ${D} │ ${line}${R}`);
181
+ }
182
+ console.log("");
183
+ }
184
+
185
+ function tomlHasMcpYats(content) {
186
+ return /\[mcp_servers\.yats\]/.test(content);
187
+ }
188
+
189
+ // Append the [mcp_servers.yats] section (+ multi_agent=false if [features] exists without it)
190
+ function tomlAppendYats(content) {
191
+ let out = content.trimEnd();
192
+ if (!/^\[features\]/m.test(out)) {
193
+ out += `\n\n[features]\nmulti_agent = false # REQUIRED: force direct MCP tool usage\n`;
194
+ } else if (!/^multi_agent\s*=/m.test(out)) {
195
+ out = out.replace(/^\[features\]/m, "[features]\nmulti_agent = false # REQUIRED: force direct MCP tool usage");
196
+ }
197
+ out += `\n\n# Added by \`yats connect codex\` — YATS MCP stdio bridge\n[mcp_servers.yats]\ncommand = "yats"\nargs = ["bridge"]\n`;
198
+ return out;
199
+ }
200
+
201
+ async function installFiles(agentKey, prompter) {
97
202
  const agent = AGENTS[agentKey];
98
203
  if (!agent) {
99
204
  console.error(`Unknown agent: ${agentKey}`);
@@ -101,17 +206,13 @@ async function installFiles(agentKey) {
101
206
  }
102
207
 
103
208
  console.log("");
104
- console.log(` ${Y}${B}⚠️ Before installing, back up your existing config files.${R}`);
105
- console.log(` ${D}This will modify or create files in your current directory.${R}`);
209
+ console.log(` ${Y}${B}⚠️ This will add YATS config files to your current directory.${R}`);
210
+ console.log(` ${D}Existing files are never overwritten — YATS content is merged or appended.${R}`);
106
211
  console.log("");
107
212
 
108
- const rl = createInterface({ input: process.stdin, output: process.stdout });
109
- const answer = await new Promise((resolve) => {
110
- rl.question(` ${B}Proceed with install for ${agent.name}? [y/N]${R} `, resolve);
111
- });
112
- rl.close();
113
-
114
- if (answer.toLowerCase() !== "y") {
213
+ const proceed = (await prompter.ask(` ${B}Proceed with install for ${agent.name}? [y/N]${R} `)).toLowerCase() === "y";
214
+ if (!proceed) {
215
+ prompter.close();
115
216
  console.log("");
116
217
  console.log(" Cancelled.");
117
218
  console.log("");
@@ -127,45 +228,69 @@ async function installFiles(agentKey) {
127
228
  const mcpConfig = getYatsMcpConfig();
128
229
 
129
230
  if (file.type === "json") {
130
- const merged = safeMergeJson(destPath, mcpConfig);
131
231
  const exists = existsSync(destPath);
232
+ const merged = safeMergeJson(destPath, mcpConfig);
132
233
  mkdirSync(dirname(destPath), { recursive: true });
133
234
  writeFileSync(destPath, merged);
134
235
  if (exists) {
135
236
  console.log(` ${Y}↻${R} Merged YATS into existing ${destPath}`);
237
+ const entry = mcpConfig.mcpServers.yats;
238
+ console.log(` ${D} Added: mcpServers.yats → ${JSON.stringify(entry)}${R}`);
239
+ console.log(` ${D} Your existing entries are preserved.${R}`);
136
240
  } else {
137
241
  console.log(` ${G}✓${R} Created ${destPath}`);
138
242
  }
139
243
  installed++;
140
- } else if (file.type === "text" || file.type === "skill") {
141
- if (existsSync(destPath)) {
142
- console.log(` ${Y}⚠${R} ${destPath} already exists — skipped (backup and remove to replace)`);
143
- skipped++;
244
+ } else if (file.type === "toml") {
245
+ const exists = existsSync(destPath);
246
+ mkdirSync(dirname(destPath), { recursive: true });
247
+ if (!exists) {
248
+ const content = renderContent(file.src);
249
+ if (content === null) { skipped++; continue; }
250
+ writeFileSync(destPath, content);
251
+ console.log(` ${G}✓${R} Created ${destPath}`);
252
+ installed++;
144
253
  } else {
145
- const content = getFileContent(file.src);
146
- if (content) {
147
- mkdirSync(dirname(destPath), { recursive: true });
148
- writeFileSync(destPath, content);
149
- console.log(` ${G}✓${R} Created ${destPath}`);
150
- installed++;
151
- } else {
152
- console.log(` ${RED}✗${R} Could not read ${file.src} — download from GitHub`);
254
+ const existing = readFileSync(destPath, "utf-8");
255
+ if (tomlHasMcpYats(existing)) {
256
+ console.log(` ${Y}✓${R} ${destPath} already has [mcp_servers.yats] — nothing to add.`);
153
257
  skipped++;
258
+ } else {
259
+ console.log(` ${Y}⚠${R} ${destPath} exists without YATS config.`);
260
+ const addition = tomlAppendYats(existing);
261
+ previewBlock("Will append", addition.replace(existing, "").trimStart());
262
+ if ((await prompter.ask(` ${B}Append YATS section to ${destPath}? [y/N]${R} `)).toLowerCase() === "y") {
263
+ writeFileSync(destPath, addition);
264
+ console.log(` ${G}✓${R} Appended YATS section to ${destPath}`);
265
+ installed++;
266
+ } else {
267
+ console.log(` ${Y}—${R} Skipped ${destPath}`);
268
+ skipped++;
269
+ }
154
270
  }
155
271
  }
156
- } else if (file.type === "toml") {
157
- if (existsSync(destPath)) {
158
- console.log(` ${Y}⚠${R} ${destPath} already exists — skipped (backup and remove to replace)`);
159
- skipped++;
272
+ } else { // text / skill
273
+ const destExists = existsSync(destPath);
274
+ mkdirSync(dirname(destPath), { recursive: true });
275
+ if (!destExists) {
276
+ const content = renderContent(file.src);
277
+ if (content === null) { skipped++; continue; }
278
+ writeFileSync(destPath, content);
279
+ console.log(` ${G}✓${R} Created ${destPath}`);
280
+ installed++;
160
281
  } else {
161
- const content = getFileContent(file.src);
162
- if (content) {
163
- mkdirSync(dirname(destPath), { recursive: true });
164
- writeFileSync(destPath, content);
165
- console.log(` ${G}✓${R} Created ${destPath}`);
282
+ console.log(` ${Y}⚠${R} ${destPath} already exists — your content is preserved.`);
283
+ const content = renderContent(file.src);
284
+ if (content === null) { skipped++; continue; }
285
+ // Skills have YAML frontmatter that only makes sense at the top → append the body only
286
+ const block = file.type === "skill" ? splitFrontmatter(content).body : content;
287
+ previewBlock("Will append", appendMarker(agentKey) + "\n" + block.trimStart());
288
+ if ((await prompter.ask(` ${B}Append YATS block to ${destPath}? [y/N]${R} `)).toLowerCase() === "y") {
289
+ writeFileSync(destPath, readFileSync(destPath, "utf-8").trimEnd() + "\n" + appendMarker(agentKey) + block.trimStart() + "\n");
290
+ console.log(` ${G}✓${R} Appended YATS block to ${destPath}`);
166
291
  installed++;
167
292
  } else {
168
- console.log(` ${RED}✗${R} Could not read ${file.src} — download from GitHub`);
293
+ console.log(` ${Y}—${R} Skipped ${destPath}`);
169
294
  skipped++;
170
295
  }
171
296
  }
@@ -178,16 +303,53 @@ async function installFiles(agentKey) {
178
303
  console.log("");
179
304
  }
180
305
 
181
- function getFileContent(srcPath) {
182
- // Try from node_modules first (when installed via npm)
183
- try {
184
- const pkgDir = dirname(new URL(import.meta.url).pathname);
185
- const installedPath = join(pkgDir, "..", srcPath);
186
- if (existsSync(installedPath)) {
187
- return readFileSync(installedPath, "utf-8");
188
- }
189
- } catch { /* not installed as npm package */ }
190
- return null;
306
+ // ============================================================
307
+ // Claude Code MCP activation
308
+ // ============================================================
309
+
310
+ /**
311
+ * After installing Claude config files, ask how to activate the YATS MCP
312
+ * server. Claude Code doesn't load project-scoped servers (.mcp.json)
313
+ * without explicit approval, so offer the two no-approval scopes (local /
314
+ * user) or leaving activation to the user (/mcp or session restart).
315
+ */
316
+ async function claudeMcpActivation(prompter) {
317
+ const mcpConfig = getYatsMcpConfig();
318
+ const yatsUrl = mcpConfig?.mcpServers?.yats?.url;
319
+ if (!yatsUrl) return;
320
+
321
+ console.log("");
322
+ console.log(` ${Y}${B}⚠️ Claude Code doesn't load project MCP servers without approval.${R}`);
323
+ console.log(` ${D}Activate the YATS MCP server now (local/user scopes need no approval):${R}`);
324
+ console.log("");
325
+ console.log(` ${B}1${R}. This project only (--scope local)`);
326
+ console.log(` ${B}2${R}. All your projects (--scope user)`);
327
+ console.log(` ${B}3${R}. Do nothing (activate later with /mcp or by restarting the session)`);
328
+ console.log("");
329
+ const choice = await prompter.ask(` ${B}Pick [1-3]:${R} `);
330
+
331
+ const scope = choice === "1" ? "local" : choice === "2" ? "user" : null;
332
+ if (!scope) {
333
+ console.log("");
334
+ console.log(` ${Y}—${R} Skipped. Remember: restart the Claude session and approve yats (${D}/mcp${R}) to load YATS tools.`);
335
+ return;
336
+ }
337
+
338
+ const args = ["mcp", "add", "--scope", scope, "--transport", "sse", "yats", yatsUrl];
339
+ console.log(` ${D}Running: claude ${args.join(" ")}${R}`);
340
+ console.log("");
341
+ const res = spawnSync("claude", args, { stdio: "inherit" });
342
+ if (res.error) {
343
+ console.error(` ${RED}✗${R} Could not run 'claude' (${res.error.message}).`);
344
+ } else if (res.status !== 0) {
345
+ console.error(` ${RED}✗${R} 'claude mcp add' failed (exit ${res.status}).`);
346
+ } else {
347
+ console.log(` ${G}✓${R} YATS MCP activated with scope '${scope}'. Restart the Claude session to load it.`);
348
+ }
349
+ if (res.error || res.status !== 0) {
350
+ console.error(` ${RED} Run it manually: claude mcp add --scope ${scope} --transport sse yats ${yatsUrl}${R}`);
351
+ }
352
+ console.log("");
191
353
  }
192
354
 
193
355
  // ============================================================
@@ -214,12 +376,12 @@ function showConfig(agentKey) {
214
376
  if (file.type === "json") {
215
377
  console.log(` ${D}${safeMergeJson("", mcpConfig).replace(/\n/g, "\n ")}${R}`);
216
378
  } else {
217
- const content = getFileContent(file.src);
379
+ const content = renderContent(file.src);
218
380
  if (content) {
219
381
  const preview = content.split("\n").slice(0, 8).join("\n");
220
382
  console.log(` ${D}${preview}${D}...${R}`);
221
383
  } else {
222
- console.log(` ${D}(download from GitHub)${R}`);
384
+ console.log(` ${RED}(missing template)${R}`);
223
385
  }
224
386
  }
225
387
  console.log("");
@@ -243,9 +405,9 @@ function showLink(agentKey) {
243
405
  }
244
406
 
245
407
  async function ask(question) {
246
- const rl = createInterface({ input: process.stdin, output: process.stdout });
247
- const answer = await new Promise((resolve) => rl.question(question, resolve));
248
- rl.close();
408
+ const prompter = makePrompter();
409
+ const answer = await prompter.ask(question);
410
+ prompter.close();
249
411
  return answer;
250
412
  }
251
413
 
@@ -284,7 +446,12 @@ export default async function connect(args) {
284
446
  console.error(` Agents: ${Object.keys(AGENTS).join(", ")}`);
285
447
  process.exit(1);
286
448
  }
287
- await installFiles(agentKey);
449
+ const prompter = makePrompter();
450
+ await installFiles(agentKey, prompter);
451
+ if (agentKey === "claude") {
452
+ await claudeMcpActivation(prompter);
453
+ }
454
+ prompter.close();
288
455
  return;
289
456
  }
290
457