@futuvara/connect 0.3.0 → 0.3.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.
Files changed (3) hide show
  1. package/README.md +56 -37
  2. package/bin/connect.js +330 -92
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -1,54 +1,73 @@
1
1
  # @futuvara/connect
2
2
 
3
- Connect a coding agent to one Futuvara project in one step: adds the Futuvara MCP server to the
4
- agent, installs every Futuvara skill (fetched from that server), and configures the project. Run it
5
- in the root of the project's repository.
3
+ The one Futuvara installer. It gives this machine every Futuvara skill and the end-of-turn check
4
+ (once — every project and worktree then has them), and connects a repository to one Futuvara
5
+ project. Run it inside the project's repository, once per repository:
6
6
 
7
7
  ```sh
8
- export FUTUVARA_KEY=<project key from Futuvara > Coding agent access>
8
+ export FUTUVARA_KEY_LUXURY_FRONTIERS_PLATFORM=<key from Futuvara > Coding agent access>
9
9
  npx @futuvara/connect --project Luxury-Frontiers-Platform --agent claude-code
10
10
  ```
11
11
 
12
- What it does, in order:
13
-
14
- 1. **MCP server** — per agent, below. The key is never written to a file.
15
- 2. **Skills** — `list_skills`, then `get_skill` for each, over the MCP server (the set lives in
16
- `sdk/futu-skills/` in the Futuvara repo, published to the knowledge base on each deploy). They are
17
- written in plugin layout to a fixed temp folder and installed with
18
- `npx skills add <folder> -s '*' -a <agent> -y --copy`; the shared `lib/` the scripts source goes
19
- beside them (`.claude/lib` or `.agents/lib`).
20
- 3. **Project config** — `bash <skills>/futu-setup/futu-setup.sh apply`: the `docs/` skeleton, the
21
- `AGENTS.md` rules block, `.futu/` (ESLint `futu` rules and scanners), `eslint.config.mjs` wiring and
22
- `.github/workflows/futu.yml`. It writes no plugin marketplace into `.claude/settings.json`. Needs
23
- bash (Git Bash on Windows) and python3; skipped with a message when bash is missing, or with
24
- `--no-config`.
12
+ **One key variable per project**, so several projects work on one machine: `FUTUVARA_KEY_` + the
13
+ project name upper-cased, every run of other characters as `_` (Futuvara-Platform →
14
+ `FUTUVARA_KEY_FUTUVARA_PLATFORM`). Put the `export` line in your shell profile so your agent sees
15
+ it too. The old plain `FUTUVARA_KEY` alone is not enough: the repository's agent config reads the
16
+ project variable, so the installer stops with a `[FAIL]` and the exact `export` line. Futuvara › Coding
17
+ agent access shows both lines filled in when a key is made.
25
18
 
26
- Re-running changes nothing that is already current; a newer skill set is picked up by re-running.
19
+ What it does, in order:
27
20
 
28
- **Once per machine — `--scope user`** (0.3.0). The build-pack lifecycle starts with it:
21
+ 0. **Preflight** — before anything is written: Node 20+, git, bash (Git Bash on Windows) and a
22
+ real Python 3 (not the Microsoft Store stub) for the project config, `gh` (a warning only —
23
+ agents need it for pull requests) and the key. Each line is `[ ok ]` or `[FAIL]` with the fix;
24
+ any `[FAIL]` exits 1 with nothing installed. The key is then checked against the server before
25
+ any file is touched.
26
+ 1. **MCP server — per repository.** Inside a git repository the `futuvara` server goes into the
27
+ repository's own, committed config (table below), reading the project's variable. Outside a git
28
+ repository nothing is connected: "run again inside the project's repo to connect it". Nothing goes
29
+ into the agent's user config; a machine-wide `futuvara` entry left by 0.3.0 in `~/.claude.json` or
30
+ `~/.cursor/mcp.json` is removed (only that entry), and the output says so.
31
+ 2. **Skills — once per machine** (`--scope user`, the default): `list_skills`, then `get_skill` for
32
+ each, over the MCP server (the set lives in `sdk/futu-skills/` in the Futuvara repo, published to
33
+ the knowledge base on each deploy), written in plugin layout to a fixed temp folder and installed
34
+ with `npx skills add <folder> -s '*' -a <agent> -y --copy -g`: `~/.claude/skills` for Claude Code,
35
+ `~/.agents/skills` for Cursor, Codex, Copilot and the other agents that read `.agents/skills`;
36
+ the shared `lib/` the scripts source goes beside them. `--scope project` installs into this
37
+ folder instead (`.claude/skills` or `.agents/skills`), as before 0.3.1.
38
+ 3. **Config** — `bash <skills>/futu-setup/futu-setup.sh apply` (with `FUTU_SETUP_SCOPE=user` by
39
+ default): the end-of-turn check in `~/.claude/settings.json`, pointing at the installed
40
+ `futu-setup/references/stop-check.sh`, so it runs in every project and does nothing where
41
+ `.futu/ci.sh` is absent; inside a git repository also the `docs/` skeleton, the `AGENTS.md` rules
42
+ block, `.futu/` (ESLint `futu` rules and scanners), `eslint.config.mjs` wiring and
43
+ `.github/workflows/futu.yml`. Skip it with `--no-config`.
44
+ 4. **Verify** — every skill the server lists is where it was installed, the end-of-turn check is in
45
+ the settings it was written to (Claude Code), the repository's `futuvara` entry reads the
46
+ project's variable, and that variable is set. A `[FAIL]` exits 1 with the exact fix.
29
47
 
30
- ```sh
31
- npx @futuvara/connect --project <Project> --agent claude-code --scope user
32
- ```
48
+ **Staying current.** Each install writes the live version to `<skills dir>/.futuvara-version`.
49
+ A re-run reads the live version with one `list_skills` call: when the marker matches and verify
50
+ passes it prints `[ ok ] skills up to date (vX)` and finishes in seconds — no download, no restart;
51
+ when the platform has a newer version it reinstalls and says "Updated the skills to vX". Agents run
52
+ `npx -y @futuvara/connect@latest …` at the start of every build pack, so every machine stays current.
53
+ `--check` on an older install reports `[FAIL] skills out of date` and writes nothing.
33
54
 
34
- - Skills install globally (`npx skills add … -g`): `~/.claude/skills` for Claude Code,
35
- `~/.cursor/skills`, `~/.codex/skills`, `~/.copilot/skills`, else `~/.agents/skills`; `lib/` beside them.
36
- - The MCP server goes into the agent's user config: `~/.claude.json` (Claude Code), `~/.cursor/mcp.json`
37
- (Cursor); Codex and Copilot print their snippet as before.
38
- - `futu-setup.sh apply` runs with `FUTU_SETUP_SCOPE=user`: the end-of-turn check goes into
39
- `~/.claude/settings.json`, pointing at the installed `futu-setup/references/stop-check.sh`, so it runs
40
- in every project and does nothing where `.futu/ci.sh` is absent. Inside a git repository the
41
- project config (ESLint, CI, `AGENTS.md`, `docs/`) is applied too; anywhere else nothing project-side
42
- is touched.
55
+ **Is this machine set up?** Add `--check`: preflight + verify only, nothing installed, exit 0 or 1.
43
56
 
44
- The default, `--scope project`, is unchanged.
57
+ **Unattended (agents, CI, scripts).** It always exits on its own: no child process reads stdin
58
+ (`stdio: ignore`), each runs with `CI=1`, `npm_config_yes=true` and `GIT_TERMINAL_PROMPT=0` and a
59
+ time limit (npx skills 5 min, futu-setup 3 min), and every server call times out after 60 s. npx is
60
+ started as `node npx-cli.js` — no shell. **Windows:** run it from Git Bash. 0.3.0 could hang there
61
+ from a folder outside any git repository (such as the home folder): Git Bash hands Node the
62
+ working folder as `C:/…`, and futu-setup's walk up to `/` never ended, because the parent of `C:`
63
+ is `C:`. Fixed in 0.3.1 (plugin 0.17.6).
45
64
 
46
- | `--agent` | Skills land in | MCP server |
65
+ | `--agent` | Skills land in (default) | MCP server, per repository |
47
66
  | --- | --- | --- |
48
- | `claude-code` | `.claude/skills` | merges `.mcp.json` with `Authorization: Bearer ${FUTUVARA_KEY}` |
49
- | `cursor` | `.agents/skills` | merges `.cursor/mcp.json` with `Authorization: Bearer ${env:FUTUVARA_KEY}` |
50
- | `codex` | `.agents/skills` | prints a `config.toml` snippet using `bearer_token_env_var = "FUTUVARA_KEY"` |
51
- | `copilot` | `.agents/skills` (`-a github-copilot`) | prints the repo-settings JSON with `Authorization: Bearer $COPILOT_MCP_FUTUVARA_KEY`; add the key as the Agents secret `COPILOT_MCP_FUTUVARA_KEY` |
67
+ | `claude-code` | `~/.claude/skills` | merges `.mcp.json` with `Authorization: Bearer ${FUTUVARA_KEY_<PROJECT>}` |
68
+ | `cursor` | `~/.agents/skills` | merges `.cursor/mcp.json` with `Authorization: Bearer ${env:FUTUVARA_KEY_<PROJECT>}` |
69
+ | `codex` | `~/.agents/skills` | prints a `.codex/config.toml` snippet using `bearer_token_env_var = "FUTUVARA_KEY_<PROJECT>"` |
70
+ | `copilot` | `~/.agents/skills` (`-a github-copilot`) | prints the repo-settings JSON with `Authorization: Bearer $COPILOT_MCP_FUTUVARA_KEY`; add the key as the Agents secret `COPILOT_MCP_FUTUVARA_KEY` |
52
71
  | other | `-a <agent>` | prints the server URL and header |
53
72
 
54
73
  `--url` points at another Futuvara host (default `https://www.futuvara.com`). Needs Node 20 or
package/bin/connect.js CHANGED
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
- // @futuvara/connect — give a coding agent the Futuvara skills, MCP server and project config for one project.
3
- // Zero dependencies: Node >= 20 stdlib only. The key is read from FUTUVARA_KEY and never written to a file.
2
+ // @futuvara/connect — give a coding agent the Futuvara skills (once per machine) and connect a repository
3
+ // to one Futuvara project. Zero dependencies: Node >= 20 stdlib only. The key is read from the
4
+ // environment (FUTUVARA_KEY_<PROJECT>) and never written to a file.
4
5
  import { parseArgs as nodeParseArgs } from "node:util";
5
6
  import { spawnSync } from "node:child_process";
6
7
  import { mkdirSync, writeFileSync, readFileSync, existsSync, realpathSync, rmSync, chmodSync, readdirSync } from "node:fs";
@@ -11,54 +12,71 @@ import { fileURLToPath } from "node:url";
11
12
  export const SERVER_NAME = "futuvara";
12
13
  const DEFAULT_URL = "https://www.futuvara.com";
13
14
 
15
+ /**
16
+ * The environment variable holding one project's key: FUTUVARA_KEY_ + the project name upper-cased, every
17
+ * run of non-alphanumerics turned into "_" (Futuvara-Platform → FUTUVARA_KEY_FUTUVARA_PLATFORM). One per
18
+ * project, so several projects work on one machine. Same function: src/lib/connect/key-var.ts.
19
+ */
20
+ export const keyVar = (project) => `FUTUVARA_KEY_${project.toUpperCase().replace(/[^A-Z0-9]+/g, "_")}`;
21
+
14
22
  // Agent ids accepted by `npx skills add -a` — https://github.com/vercel-labs/skills
15
23
  const SKILLS_AGENT_ID = { copilot: "github-copilot" };
16
24
 
17
- export const HELP = `Usage: npx @futuvara/connect --project <Project> --agent <agent> [--scope project|user] [--url ${DEFAULT_URL}] [--no-config]
25
+ export const HELP = `Usage: npx @futuvara/connect --project <Project> --agent <agent> [--scope user|project] [--url ${DEFAULT_URL}] [--no-config] [--check]
18
26
 
19
- Adds the Futuvara MCP server to your coding agent, installs every Futuvara skill (fetched from
20
- that server), then configures the project with futu-setup. Run it in the root of the project repository.
27
+ Installs every Futuvara skill (fetched from the Futuvara MCP server) and the end-of-turn check once
28
+ for this machine, then — run inside a project's git repository — connects that repository to the
29
+ Futuvara project: the MCP server goes into the repository's own agent config, reading the key from
30
+ FUTUVARA_KEY_<PROJECT>, and futu-setup applies the project config. Run it once per repository.
21
31
 
22
- --project Futuvara project folder name, e.g. Luxury-Frontiers-Platform
32
+ --project Futuvara project folder name, e.g. Futuvara-Platform (key: FUTUVARA_KEY_FUTUVARA_PLATFORM)
23
33
  --agent claude-code | cursor | codex | copilot | any agent id "npx skills" knows
24
- --scope project (default): skills, MCP server and end-of-turn check in this project
25
- user: once per machine — skills installed globally (npx skills -g), the MCP server
26
- in the agent's user config, the end-of-turn check in ~/.claude/settings.json (it runs
27
- in any project and does nothing where .futu/ci.sh is absent); project config is
28
- still applied when run inside a git repository
34
+ --scope user (default): skills installed globally (npx skills -g), the end-of-turn check in
35
+ ~/.claude/settings.json (it runs in any project and does nothing where .futu/ci.sh is absent)
36
+ project: skills and the end-of-turn check in this folder only (the old per-folder install)
29
37
  --url Futuvara base URL (default ${DEFAULT_URL})
30
- --no-config install the skills only; skip "futu-setup.sh apply" (ESLint futu rules, .futu/,
31
- .github/workflows/futu.yml, the AGENTS.md rules block, docs/ skeleton)
32
-
33
- Needs env FUTUVARA_KEY: the project key made in Futuvara > Coding agent access.
34
- The key is never written to a file; the agent's config reads it from the environment.
35
- The project config step needs bash (Git Bash on Windows) and python3; it is skipped without bash.
36
-
37
- claude-code merges .mcp.json (Authorization: Bearer \${FUTUVARA_KEY}); skills in .claude/skills
38
- cursor merges .cursor/mcp.json (Authorization: Bearer \${env:FUTUVARA_KEY}); skills in .agents/skills
39
- codex prints a config.toml snippet (bearer_token_env_var = "FUTUVARA_KEY"); skills in .agents/skills
40
- copilot prints the repo-settings JSON and the secret to add; skills in .agents/skills
41
-
42
- Re-running changes nothing that is already current.`;
43
-
44
- /** @param {string[]} argv @returns {{project: string, agent: string, scope: "project" | "user", url: string, config: boolean, help: boolean}} */
38
+ --no-config skip "futu-setup.sh apply" (ESLint futu rules, .futu/, .github/workflows/futu.yml,
39
+ the AGENTS.md rules block, docs/ skeleton, the end-of-turn check)
40
+ --check install nothing: run the preflight and verify that the skills, the end-of-turn
41
+ check and this repository's MCP connection are in place and the skills are the live
42
+ version ("is this machine set up and current?")
43
+
44
+ The key: export FUTUVARA_KEY_<PROJECT>=<key from Futuvara > Coding agent access>, in your shell
45
+ profile so your agent sees it too. Plain FUTUVARA_KEY alone fails: the agent's config reads the
46
+ project variable. The key is never written to a file; the agent's config names the variable.
47
+ Preflight, before anything is written: Node 20+, git, bash (Git Bash on Windows) and a real
48
+ Python 3 for the project config, gh (warning only), the key. Any [FAIL] exits 1. After installing,
49
+ a verify step checks what landed and exits 1 with the fix when something is missing.
50
+ Children never read stdin and are time-limited, so it runs unattended (CI, agents, scripts).
51
+
52
+ claude-code merges .mcp.json (Authorization: Bearer \${FUTUVARA_KEY_<PROJECT>}); skills in ~/.claude/skills
53
+ cursor merges .cursor/mcp.json (Authorization: Bearer \${env:FUTUVARA_KEY_<PROJECT>}); skills in ~/.agents/skills
54
+ codex prints a config.toml snippet (bearer_token_env_var = "FUTUVARA_KEY_<PROJECT>"); skills in ~/.agents/skills
55
+ copilot prints the repo-settings JSON and the secret to add; skills in ~/.agents/skills
56
+
57
+ Re-running changes nothing that is already current: when the installed skills (<skills dir>/.futuvara-version)
58
+ match the live version and verify passes, it skips the download and finishes in seconds — run it
59
+ at the start of every pack (npx -y @futuvara/connect@latest …); restart only when it says it updated.`;
60
+
61
+ /** @param {string[]} argv @returns {{project: string, agent: string, scope: "project" | "user", url: string, config: boolean, check: boolean, help: boolean}} */
45
62
  export function parseArgs(argv) {
46
63
  const { values } = nodeParseArgs({
47
64
  args: argv,
48
65
  options: {
49
66
  project: { type: "string" },
50
67
  agent: { type: "string" },
51
- scope: { type: "string", default: "project" },
68
+ scope: { type: "string", default: "user" },
52
69
  url: { type: "string", default: DEFAULT_URL },
53
70
  "no-config": { type: "boolean", default: false },
71
+ check: { type: "boolean", default: false },
54
72
  help: { type: "boolean", short: "h", default: false },
55
73
  },
56
74
  });
57
- if (values.help) return { project: "", agent: "", scope: "project", url: DEFAULT_URL, config: true, help: true };
75
+ if (values.help) return { project: "", agent: "", scope: "user", url: DEFAULT_URL, config: true, check: false, help: true };
58
76
  if (!values.project) throw new Error("--project is required");
59
77
  if (!values.agent) throw new Error("--agent is required");
60
- if (values.scope !== "project" && values.scope !== "user") throw new Error("--scope is project or user");
61
- return { project: values.project, agent: values.agent.toLowerCase(), scope: values.scope, url: values.url.replace(/\/+$/, ""), config: !values["no-config"], help: false };
78
+ if (values.scope !== "project" && values.scope !== "user") throw new Error("--scope is user or project");
79
+ return { project: values.project, agent: values.agent.toLowerCase(), scope: values.scope, url: values.url.replace(/\/+$/, ""), config: !values["no-config"], check: values.check, help: false };
62
80
  }
63
81
 
64
82
  /**
@@ -73,16 +91,16 @@ export function mergeMcpServers(existing, entry) {
73
91
  }
74
92
 
75
93
  // https://code.claude.com/docs/en/mcp — .mcp.json expands ${VAR} in url and headers.
76
- export const claudeEntry = (mcpUrl) => ({
94
+ export const claudeEntry = (mcpUrl, variable) => ({
77
95
  type: "http",
78
96
  url: mcpUrl,
79
- headers: { Authorization: "Bearer ${FUTUVARA_KEY}" },
97
+ headers: { Authorization: `Bearer \${${variable}}` },
80
98
  });
81
99
 
82
100
  // https://cursor.com/docs/context/mcp — ${env:NAME} is resolved in url and headers.
83
- export const cursorEntry = (mcpUrl) => ({
101
+ export const cursorEntry = (mcpUrl, variable) => ({
84
102
  url: mcpUrl,
85
- headers: { Authorization: "Bearer ${env:FUTUVARA_KEY}" },
103
+ headers: { Authorization: `Bearer \${env:${variable}}` },
86
104
  });
87
105
 
88
106
  /** Parse a JSON-RPC response from either a JSON body or an SSE stream body. */
@@ -118,6 +136,7 @@ export async function callTool(mcpUrl, key, name, args = {}, fetchImpl = fetch)
118
136
  Authorization: `Bearer ${key}`,
119
137
  },
120
138
  body: JSON.stringify({ jsonrpc: "2.0", id, method: "tools/call", params: { name, arguments: args } }),
139
+ signal: AbortSignal.timeout(60_000),
121
140
  });
122
141
  if (res.status === 401 || res.status === 403) throw new Error("Futuvara refused the key (revoked, or for another project?).");
123
142
  if (!res.ok) throw new Error(`Futuvara MCP server answered ${res.status} ${res.statusText} at ${mcpUrl}`);
@@ -128,9 +147,9 @@ export async function callTool(mcpUrl, key, name, args = {}, fetchImpl = fetch)
128
147
  return JSON.parse(text);
129
148
  }
130
149
 
131
- /** Every skill, every file: `list_skills`, then `get_skill` for each. */
132
- export async function fetchSkills(mcpUrl, key, fetchImpl = fetch) {
133
- const list = await callTool(mcpUrl, key, "list_skills", {}, fetchImpl);
150
+ /** Every skill, every file: `list_skills` (unless already fetched), then `get_skill` for each. */
151
+ export async function fetchSkills(mcpUrl, key, fetchImpl = fetch, list = null) {
152
+ list ??= await callTool(mcpUrl, key, "list_skills", {}, fetchImpl);
134
153
  const skills = [];
135
154
  for (const s of list) skills.push(await callTool(mcpUrl, key, "get_skill", { name: s.name }, fetchImpl));
136
155
  return skills;
@@ -162,11 +181,12 @@ export function writePlugin(root, skills) {
162
181
  */
163
182
  export const agentBase = (agent) => (agent === "claude-code" ? ".claude" : ".agents");
164
183
 
165
- // Where `npx skills add -g` puts each agent's skills (its globalSkillsDir), under the home folder.
166
- const USER_BASE = { "claude-code": ".claude", codex: ".codex", cursor: ".cursor", copilot: ".copilot" };
167
-
168
- /** The folder the skills and `lib/` land in: relative to the project, or absolute under the home folder for user scope. */
169
- export const skillsBase = (agent, scope, home = homedir()) => (scope === "user" ? join(home, USER_BASE[agent] ?? ".agents") : agentBase(agent));
184
+ /**
185
+ * The folder the skills and `lib/` land in: relative to the project, or absolute under the home folder for
186
+ * user scope. `npx skills add -g` puts every agent that reads `.agents/skills` (cursor, codex, copilot…)
187
+ * in the shared ~/.agents/skills, not in its own globalSkillsDir (skills 1.7: getAgentBaseDir).
188
+ */
189
+ export const skillsBase = (agent, scope, home = homedir()) => (scope === "user" ? join(home, agentBase(agent)) : agentBase(agent));
170
190
 
171
191
  /** `npx skills add` arguments: every skill in the folder (-s '*'), copied, no prompts; -g installs for the user. */
172
192
  export const skillsAddArgs = (root, agent, scope) => [
@@ -181,31 +201,66 @@ export function installLib(root, base) {
181
201
  for (const src of walk(lib)) put(join(base, "lib", src.slice(lib.length + 1)), readFileSync(src), src.endsWith(".sh"));
182
202
  }
183
203
 
184
- function run(cmd, args) {
185
- // Windows needs a shell to run npx.cmd / claude.cmd; quote args there so paths with spaces survive.
186
- const win = process.platform === "win32";
187
- const r = spawnSync(cmd, win ? args.map((a) => `"${a}"`) : args, { stdio: "inherit", shell: win });
188
- if (r.status !== 0) throw new Error(`${cmd} ${args.join(" ")} failed (exit ${r.status ?? r.error?.message}).`);
204
+ /**
205
+ * How to start npx without a shell: npm's own npx-cli.js under this Node. `npm_execpath` is set when we
206
+ * run under npx/npm; otherwise npm sits beside node (Windows) or in ../lib (macOS, Linux).
207
+ * @returns {{cmd: string | null, pre: string[]}} `cmd: null` when only a PATH lookup is left on Windows
208
+ */
209
+ export function npxCommand(env = process.env, execPath = process.execPath, platform = process.platform, exists = existsSync) {
210
+ const candidates = [
211
+ env.npm_execpath && join(dirname(env.npm_execpath), "npx-cli.js"),
212
+ join(dirname(execPath), "node_modules", "npm", "bin", "npx-cli.js"),
213
+ join(dirname(execPath), "..", "lib", "node_modules", "npm", "bin", "npx-cli.js"),
214
+ ];
215
+ const cli = candidates.find((c) => c && exists(c));
216
+ if (cli) return { cmd: execPath, pre: [cli] };
217
+ return { cmd: platform === "win32" ? null : "npx", pre: [] };
189
218
  }
190
219
 
191
- function writeJson(path, entry) {
192
- mkdirSync(dirname(path), { recursive: true });
193
- writeFileSync(path, mergeMcpServers(existsSync(path) ? readFileSync(path, "utf8") : null, entry));
194
- console.log(`Added "${SERVER_NAME}" to ${path} (key read from FUTUVARA_KEY at runtime).`);
220
+ /**
221
+ * Every child: stdin closed (never waits on a prompt), output shown, non-interactive env, a time limit.
222
+ * Exported for the tests; `spawn` is injectable so they can see the options.
223
+ */
224
+ export const CHILD_ENV = { CI: "1", npm_config_yes: "true", GIT_TERMINAL_PROMPT: "0" };
225
+ export function runChild(cmd, args, { timeoutMs, env = {}, spawn = spawnSync } = {}) {
226
+ const opts = { stdio: ["ignore", "inherit", "inherit"], env: { ...process.env, ...CHILD_ENV, ...env }, timeout: timeoutMs, killSignal: "SIGKILL" };
227
+ if (cmd !== null) return spawn(cmd, args, opts);
228
+ // Windows with no npx-cli.js found: npx.cmd needs cmd.exe. One command string, never shell + an args array (DEP0190).
229
+ return spawn(["npx", ...args].map((a) => `"${a}"`).join(" "), { ...opts, shell: true });
230
+ }
231
+
232
+ function run(cmd, args, label, timeoutMs) {
233
+ const r = runChild(cmd, args, { timeoutMs });
234
+ if (r.error?.code === "ETIMEDOUT") throw new Error(`${label} did not finish within ${timeoutMs / 1000} s and was stopped.`);
235
+ if (r.status !== 0) throw new Error(`${label} failed (exit ${r.status ?? r.error?.message}).`);
236
+ }
237
+
238
+ /** The repository's top folder, or null outside a git repository. */
239
+ export function gitRoot(cwd = process.cwd()) {
240
+ const r = spawnSync("git", ["rev-parse", "--show-toplevel"], { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 10_000 });
241
+ return r.status === 0 && r.stdout.trim() ? r.stdout.trim() : null;
242
+ }
243
+
244
+ /** The repository file an agent's MCP entry is merged into, or null when the agent's config is printed instead. */
245
+ export function mcpConfigPath(agent, repo) {
246
+ if (agent === "claude-code") return join(repo, ".mcp.json");
247
+ if (agent === "cursor") return join(repo, ".cursor", "mcp.json");
248
+ return null;
195
249
  }
196
250
 
197
- function configureMcp(agent, mcpUrl, scope) {
198
- const user = scope === "user";
251
+ /** Connect one repository: the MCP entry in its committed config, naming the project's key variable. */
252
+ function configureMcp(agent, mcpUrl, repo, variable) {
253
+ const path = mcpConfigPath(agent, repo);
254
+ if (path) {
255
+ const entry = agent === "cursor" ? cursorEntry(mcpUrl, variable) : claudeEntry(mcpUrl, variable);
256
+ put(path, Buffer.from(mergeMcpServers(existsSync(path) ? readFileSync(path, "utf8") : null, entry)));
257
+ return console.log(`Added "${SERVER_NAME}" to ${path} (reads ${variable} at runtime).`);
258
+ }
199
259
  switch (agent) {
200
- case "claude-code":
201
- // User scope: Claude Code keeps user MCP servers in ~/.claude.json's top-level mcpServers.
202
- return writeJson(user ? join(homedir(), ".claude.json") : join(process.cwd(), ".mcp.json"), claudeEntry(mcpUrl));
203
- case "cursor":
204
- return writeJson(join(user ? homedir() : process.cwd(), ".cursor", "mcp.json"), cursorEntry(mcpUrl));
205
260
  case "codex":
206
- // https://learn.chatgpt.com/docs/extend/mcp?surface=cli — ~/.codex/config.toml or .codex/config.toml
261
+ // https://learn.chatgpt.com/docs/extend/mcp?surface=cli — .codex/config.toml (trusted project) or ~/.codex/config.toml
207
262
  return console.log(
208
- `Add to ~/.codex/config.toml (or .codex/config.toml in a trusted project):\n\n[mcp_servers.${SERVER_NAME}]\nurl = "${mcpUrl}"\nbearer_token_env_var = "FUTUVARA_KEY"\n`,
263
+ `Add to .codex/config.toml in this repository (a trusted project):\n\n[mcp_servers.${SERVER_NAME}]\nurl = "${mcpUrl}"\nbearer_token_env_var = "${variable}"\n`,
209
264
  );
210
265
  case "copilot":
211
266
  // https://docs.github.com/en/copilot/how-tos/use-copilot-agents/coding-agent/extend-coding-agent-with-mcp
@@ -218,55 +273,238 @@ function configureMcp(agent, mcpUrl, scope) {
218
273
  )}\n\nThen add the key as an Agents secret named COPILOT_MCP_FUTUVARA_KEY.\n`,
219
274
  );
220
275
  default:
221
- return console.log(`Add an HTTP MCP server named "${SERVER_NAME}" at ${mcpUrl} with header Authorization: Bearer $FUTUVARA_KEY.`);
276
+ return console.log(`Add an HTTP MCP server named "${SERVER_NAME}" at ${mcpUrl} with header Authorization: Bearer $${variable}.`);
277
+ }
278
+ }
279
+
280
+ /**
281
+ * 0.3.0 `--scope user` put one machine-wide "futuvara" server in the agent's user config, which pins every
282
+ * project to one key. Remove just that entry; every other server and setting stays.
283
+ */
284
+ export function removeUserServer(home = homedir()) {
285
+ for (const path of [join(home, ".claude.json"), join(home, ".cursor", "mcp.json")]) {
286
+ if (!existsSync(path)) continue;
287
+ let config;
288
+ try {
289
+ config = JSON.parse(readFileSync(path, "utf8"));
290
+ } catch {
291
+ continue; // not ours to repair
292
+ }
293
+ if (!config.mcpServers?.[SERVER_NAME]) continue;
294
+ delete config.mcpServers[SERVER_NAME];
295
+ writeFileSync(path, JSON.stringify(config, null, 2) + "\n");
296
+ console.log(`Removed the machine-wide "${SERVER_NAME}" server from ${path} — each repository now has its own, per project.`);
222
297
  }
223
298
  }
224
299
 
300
+ /** The key: the project's variable, else plain FUTUVARA_KEY (backwards compatible). */
301
+ export function readKey(project, env = process.env) {
302
+ const variable = keyVar(project);
303
+ if (env[variable]) return { key: env[variable], from: variable };
304
+ if (env.FUTUVARA_KEY) return { key: env.FUTUVARA_KEY, from: "FUTUVARA_KEY" };
305
+ return { key: "", from: null };
306
+ }
307
+
308
+ /** A command answers (exit 0) within 10 s, stdin closed. */
309
+ const answers = (cmd, args) => spawnSync(cmd, args, { stdio: "ignore", timeout: 10_000 }).status === 0;
310
+
311
+ // A real Python 3, found the way lib/portable.sh finds it (the Windows Store stub fails `import sys`).
312
+ const PYTHON_PROBE = 'for c in python3 python "py -3"; do $c -c "import sys" >/dev/null 2>&1 && exit 0; done; exit 1';
313
+
314
+ const exportLine = (variable) => `export ${variable}=<key from Futuvara > Coding agent access>`;
315
+
316
+ /**
317
+ * Everything the install needs, checked before anything is written.
318
+ * @returns {{status: "ok" | "fail" | "warn", label: string, fix?: string}[]}
319
+ */
320
+ export function preflight(opts, env = process.env, has = answers, nodeVersion = process.versions.node) {
321
+ const line = (pass, label, fix, status = pass ? "ok" : "fail") => ({ status, label, ...(pass ? {} : { fix }) });
322
+ const win = process.platform === "win32";
323
+ const checks = [
324
+ line(Number(nodeVersion.split(".")[0]) >= 20, `Node ${nodeVersion} (20 or later)`, "install Node 20 or later: https://nodejs.org"),
325
+ line(has("git", ["--version"]), "git", "install git: https://git-scm.com"),
326
+ ];
327
+ // bash and Python run the project config (futu-setup.sh); --no-config does not need them.
328
+ if (opts.config) {
329
+ const bash = has("bash", ["--version"]);
330
+ checks.push(line(bash, "bash", win ? "run this from Git Bash (https://git-scm.com)" : "install bash"));
331
+ checks.push(
332
+ line(bash && has("bash", ["-c", PYTHON_PROBE]), "Python 3", win ? "install Python 3 from python.org (not the Microsoft Store stub)" : "install Python 3"),
333
+ );
334
+ }
335
+ const gh = has("gh", ["--version"]);
336
+ checks.push(line(gh, "GitHub CLI (gh)", "agents need gh to open and merge pull requests: https://cli.github.com", gh ? "ok" : "warn"));
337
+ const variable = keyVar(opts.project);
338
+ const { from } = readKey(opts.project, env);
339
+ if (from === variable) checks.push(line(true, `${variable} is set`));
340
+ // A fail, not a warning: the repository's MCP config reads ${variable}, so with only plain
341
+ // FUTUVARA_KEY set the install would "succeed" and every agent call would then be refused.
342
+ else if (from) checks.push(line(false, `${variable} is not set (only the old FUTUVARA_KEY is) — the project's agent config reads ${variable}`, exportLine(variable)));
343
+ else checks.push(line(false, `${variable} is set (in your shell profile, so your agent sees it too)`, exportLine(variable)));
344
+ return checks;
345
+ }
346
+
347
+ /** Was it installed where it should be? Skills, the end-of-turn check (Claude Code), the repository's MCP entry. */
348
+ export function verify(opts, names, { home = homedir(), cwd = process.cwd(), repo = gitRoot(cwd), env = process.env } = {}) {
349
+ const base = skillsBase(opts.agent, opts.scope, home);
350
+ const where = opts.scope === "user" ? base : join(cwd, base);
351
+ const rerun = `re-run: npx @futuvara/connect --project ${opts.project} --agent ${opts.agent}${opts.scope === "project" ? " --scope project" : ""}`;
352
+ const missing = names.filter((n) => !existsSync(join(where, "skills", n, "SKILL.md")));
353
+ const checks = [
354
+ missing.length
355
+ ? { status: "fail", label: `${missing.length} of ${names.length} Futuvara skills missing from ${join(where, "skills")} (${missing.slice(0, 3).join(", ")}…)`, fix: rerun }
356
+ : { status: "ok", label: `${names.length} Futuvara skills in ${join(where, "skills")}` },
357
+ ];
358
+ if (opts.config && opts.agent === "claude-code") {
359
+ const settings = join(opts.scope === "user" ? home : (repo ?? cwd), ".claude", "settings.json");
360
+ const hooked = existsSync(settings) && readFileSync(settings, "utf8").includes("stop-check.sh");
361
+ checks.push(
362
+ hooked
363
+ ? { status: "ok", label: `end-of-turn check in ${settings}` }
364
+ : { status: "fail", label: `end-of-turn check missing from ${settings}`, fix: `${opts.scope === "user" ? "FUTU_SETUP_SCOPE=user " : ""}bash ${join(where, "skills", "futu-setup", "futu-setup.sh")} apply` },
365
+ );
366
+ }
367
+ const variable = keyVar(opts.project);
368
+ if (!repo) {
369
+ checks.push({ status: "warn", label: "not inside a git repository — no project connected here", fix: "run again inside the project's repo to connect it" });
370
+ return checks;
371
+ }
372
+ const config = mcpConfigPath(opts.agent, repo);
373
+ if (config) {
374
+ let header = "";
375
+ try {
376
+ header = JSON.parse(readFileSync(config, "utf8")).mcpServers?.[SERVER_NAME]?.headers?.Authorization ?? "";
377
+ } catch {
378
+ // missing or unreadable: reported below
379
+ }
380
+ checks.push(
381
+ header.includes(variable)
382
+ ? { status: "ok", label: `"${SERVER_NAME}" MCP server in ${config} reads ${variable}` }
383
+ : { status: "fail", label: `"${SERVER_NAME}" MCP server in ${config} does not read ${variable}`, fix: rerun },
384
+ );
385
+ }
386
+ checks.push(env[variable] ? { status: "ok", label: `${variable} is set for your agent` } : { status: "warn", label: `${variable} is not set — your agent reads it`, fix: exportLine(variable) });
387
+ return checks;
388
+ }
389
+
390
+ /** Print [ ok ] / [warn] / [FAIL] lines; true when nothing failed. */
391
+ export function report(title, checks) {
392
+ console.log(`\n${title}`);
393
+ for (const c of checks) {
394
+ console.log(` [${{ ok: " ok ", warn: "warn", fail: "FAIL" }[c.status]}] ${c.label}`);
395
+ if (c.fix) console.log(` ${c.status === "fail" ? "fix" : "note"}: ${c.fix}`);
396
+ }
397
+ return checks.every((c) => c.status !== "fail");
398
+ }
399
+
400
+ /** @returns {Promise<number>} the exit code */
225
401
  export async function main(argv = process.argv.slice(2)) {
226
- const opts = parseArgs(argv);
227
- if (opts.help) return console.log(HELP);
228
- const key = process.env.FUTUVARA_KEY;
229
- if (!key) throw new Error("FUTUVARA_KEY is not set. Make a project key in Futuvara > Coding agent access, then: export FUTUVARA_KEY=<key>");
402
+ let opts;
403
+ try {
404
+ opts = parseArgs(argv);
405
+ } catch (err) {
406
+ throw new Error(`${err.message}\n\n${HELP}`);
407
+ }
408
+ if (opts.help) return console.log(HELP), 0;
409
+ console.log(`Futuvara connect — project ${opts.project}, agent ${opts.agent}, ${opts.scope} scope${opts.check ? " (check only)" : ""}`);
410
+ if (!report("Preflight", preflight(opts))) {
411
+ console.log(`\nFix the [FAIL] lines above, then run this again. Nothing was ${opts.check ? "checked further" : "installed"}.`);
412
+ return 1;
413
+ }
414
+ const { key, from } = readKey(opts.project);
415
+ console.log(`\nKey: read from ${from}.`);
230
416
  const mcpUrl = `${opts.url}/api/connect/mcp`;
417
+ const variable = keyVar(opts.project);
418
+ const repo = gitRoot();
419
+
420
+ // One request: proves the key is accepted, says which skills should be present and the live version.
421
+ const list = await callTool(mcpUrl, key, "list_skills");
422
+ const names = list.map((s) => s.name);
423
+ const live = list[0]?.version ?? "";
424
+ const marker = versionMarker(opts);
425
+ const installed = existsSync(marker) ? readFileSync(marker, "utf8").trim() : "";
426
+ const fresh = live
427
+ ? installed === live
428
+ ? { status: "ok", label: `skills up to date (v${live})` }
429
+ : { status: "fail", label: `skills out of date (installed v${installed || "?"}, live v${live}) — run without --check` }
430
+ : null;
431
+ let checks = verify(opts, names, { repo });
432
+ // Current and in place: nothing to download, nothing to restart.
433
+ const current = fresh?.status === "ok" && checks.every((c) => c.status !== "fail");
434
+
435
+ if (!opts.check && !current) {
436
+ console.log("\nInstalling");
437
+ // Fetch first: a refused key or an unreachable server fails before anything is written.
438
+ const skills = await fetchSkills(mcpUrl, key, fetch, list);
439
+ removeUserServer();
440
+ if (repo) configureMcp(opts.agent, mcpUrl, repo, variable);
441
+ // A fixed folder, not a fresh temp one: npx skills records it in skills-lock.json, so a re-run leaves the lock unchanged.
442
+ const root = join(tmpdir(), "futuvara-connect", "plugin");
443
+ writePlugin(root, skills);
444
+ // https://github.com/vercel-labs/skills
445
+ const npx = npxCommand();
446
+ run(npx.cmd, [...npx.pre, ...skillsAddArgs(root, opts.agent, opts.scope)], "npx skills add", 300_000);
447
+ const base = skillsBase(opts.agent, opts.scope);
448
+ installLib(root, base);
449
+ console.log(`Installed ${skills.length} Futuvara skills (v${skills[0]?.version ?? "?"}) into ${base}/skills.`);
450
+ if (!opts.config) console.log("Project config skipped (--no-config).");
451
+ else applyConfig(base, root, opts.scope);
452
+ if (live) put(marker, Buffer.from(`${live}\n`));
453
+ checks = verify(opts, names, { repo });
454
+ } else if (fresh && (opts.check || current)) {
455
+ checks = [fresh, ...checks];
456
+ }
231
457
 
232
- configureMcp(opts.agent, mcpUrl, opts.scope);
233
-
234
- const skills = await fetchSkills(mcpUrl, key);
235
- // A fixed folder, not a fresh temp one: npx skills records it in skills-lock.json, so a re-run leaves the lock unchanged.
236
- const root = join(tmpdir(), "futuvara-connect", "plugin");
237
- writePlugin(root, skills);
238
- // https://github.com/vercel-labs/skills
239
- run("npx", skillsAddArgs(root, opts.agent, opts.scope));
240
- const base = skillsBase(opts.agent, opts.scope);
241
- installLib(root, base);
242
- console.log(`Installed ${skills.length} Futuvara skills (v${skills[0]?.version ?? "?"}) into ${base}/skills.`);
243
-
244
- if (!opts.config) console.log("Project config skipped (--no-config).");
245
- else applyConfig(base, root, opts.scope);
246
- console.log(`Done. Keep FUTUVARA_KEY set in the environment your agent runs in (project ${opts.project}).`);
458
+ if (!report("Verify", checks)) {
459
+ console.log("\nNot complete — fix the [FAIL] lines above, then run this again.");
460
+ return 1;
461
+ }
462
+ console.log(
463
+ repo
464
+ ? `\n${repo} is connected to Futuvara project ${opts.project}; your agent reads ${variable}.`
465
+ : `\nNot inside a git repository: skills and the end-of-turn check only — run again inside the project's repo to connect it.`,
466
+ );
467
+ if (opts.check || current) return console.log("Done. Nothing was updated — no restart needed."), 0;
468
+ console.log(
469
+ opts.scope === "user"
470
+ ? `Done. Updated the skills to v${live || "?"}. Restart your coding agent — every project and worktree on this machine now has the skills.`
471
+ : `Done. Updated the skills to v${live || "?"}. Restart your coding agent — this project now has the skills.`,
472
+ );
473
+ return 0;
247
474
  }
248
475
 
476
+ /** `<skills dir>/.futuvara-version`: the version connect last installed there, so a current run skips the download. */
477
+ export const versionMarker = (opts, home = homedir(), cwd = process.cwd()) => {
478
+ const base = skillsBase(opts.agent, opts.scope, home);
479
+ return join(opts.scope === "user" ? base : join(cwd, base), "skills", ".futuvara-version");
480
+ };
481
+
249
482
  /**
250
483
  * `futu-setup.sh apply` from the installed copy: ESLint futu rules, .futu/, the CI job, the AGENTS.md block,
251
484
  * the end-of-turn check. Idempotent. User scope (FUTU_SETUP_SCOPE=user): the check goes into
252
- * ~/.claude/settings.json, and outside a git repository nothing else is touched.
485
+ * ~/.claude/settings.json, and outside a git repository nothing else is touched. Preflight has checked bash.
253
486
  */
254
487
  function applyConfig(base, root, scope) {
255
- if (spawnSync("bash", ["--version"], { stdio: "ignore" }).status !== 0) {
256
- return console.log("Project config skipped: bash not found (on Windows, run from Git Bash). Re-run, or run futu-setup.sh apply later.");
257
- }
488
+ const script = join(base, "skills", "futu-setup", "futu-setup.sh");
489
+ if (!existsSync(script)) throw new Error(`futu-setup.sh is not where npx skills was expected to put it (${script}). Run it from where the skills landed: bash <skills>/futu-setup/futu-setup.sh apply`);
258
490
  // Forward slashes: bash on Windows reads C:/… but not C:\… (the user base is absolute).
259
- const r = spawnSync("bash", [`${base.replace(/\\/g, "/")}/skills/futu-setup/futu-setup.sh`, "apply"], {
260
- stdio: "inherit",
261
- env: { ...process.env, FUTU_PLUGIN_DIR: root, FUTU_SKILLS_FROM_CONNECT: "1", ...(scope === "user" ? { FUTU_SETUP_SCOPE: "user" } : {}) },
491
+ const r = runChild("bash", [script.replace(/\\/g, "/"), "apply"], {
492
+ timeoutMs: 180_000,
493
+ env: { FUTU_PLUGIN_DIR: root, FUTU_SKILLS_FROM_CONNECT: "1", ...(scope === "user" ? { FUTU_SETUP_SCOPE: "user" } : {}) },
262
494
  });
495
+ if (r.error?.code === "ETIMEDOUT") throw new Error("futu-setup.sh apply did not finish within 180 s and was stopped.");
263
496
  // futu-setup exits 1 for work it leaves to you (stray docs, a TODO line) — reported above, not a failed install.
264
- if (r.status === 2 || r.status === null) throw new Error(`futu-setup.sh apply failed (exit ${r.status ?? r.error?.message}).`);
497
+ if (r.status !== 0 && r.status !== 1) throw new Error(`futu-setup.sh apply failed (exit ${r.status ?? r.error?.message}).`);
265
498
  }
266
499
 
267
500
  if (process.argv[1] && fileURLToPath(import.meta.url) === realpathSync(process.argv[1])) {
268
- main().catch((err) => {
269
- console.error(`futuvara-connect: ${err.message}\n\n${HELP}`);
270
- process.exit(1);
271
- });
501
+ // exitCode, not process.exit(): output is flushed, and nothing is left open (every child is synchronous
502
+ // and time-limited, fetch has a timeout), so Node ends by itself.
503
+ main().then(
504
+ (code) => (process.exitCode = code),
505
+ (err) => {
506
+ console.error(`futuvara-connect: ${err.message}`);
507
+ process.exitCode = 1;
508
+ },
509
+ );
272
510
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@futuvara/connect",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
4
4
  "description": "Connect a coding agent to a Futuvara project: adds the Futuvara MCP server, installs every Futuvara skill and applies the project config.",
5
5
  "type": "module",
6
6
  "bin": {