@futuvara/connect 0.3.3 → 0.3.5

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
@@ -67,7 +67,7 @@ is `C:`. Fixed in 0.3.1 (plugin 0.17.6).
67
67
 
68
68
  | `--agent` | Skills land in (default) | MCP server, per repository |
69
69
  | --- | --- | --- |
70
- | `claude-code` | `~/.claude/skills` | merges `.mcp.json` with `Authorization: Bearer ${FUTUVARA_KEY_<PROJECT>}` |
70
+ | `claude-code` | `~/.claude/skills` | merges `.mcp.json` with `Authorization: Bearer ${FUTUVARA_KEY_<PROJECT>}`, and a `headersHelper` that sends the session's worktree folder and branch (Hub › Projects › Terminals) |
71
71
  | `cursor` | `~/.agents/skills` | merges `.cursor/mcp.json` with `Authorization: Bearer ${env:FUTUVARA_KEY_<PROJECT>}` |
72
72
  | `codex` | `~/.agents/skills` | prints a `.codex/config.toml` snippet using `bearer_token_env_var = "FUTUVARA_KEY_<PROJECT>"` |
73
73
  | `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` |
@@ -79,7 +79,6 @@ later. Tests: `npm test`.
79
79
  The old `futuvara-context` skill (0.1.x) is retired in favour of `futu-mcp-context`,
80
80
  `futu-mcp-progress` and `futu-mcp-signoff`; remove an old copy with `npx skills remove futuvara-context`.
81
81
 
82
- **Releasing:** bump `version` in `package.json` and merge to `main`. The
83
- `publish-connect.yml` workflow tests and publishes it through npm trusted
84
- publishing — no token. The first version was published by hand, because npm
85
- cannot trust a publisher for a package that does not exist yet.
82
+ **Releasing:** bump `version` in `package.json`, merge to `main`, then run
83
+ `bash scripts/ship.sh connect` from the repo root. It tests and publishes the
84
+ version when it is new, with the npm login on that machine (`npm login` once).
package/bin/connect.js CHANGED
@@ -6,11 +6,11 @@ import { parseArgs as nodeParseArgs } from "node:util";
6
6
  import { spawnSync } from "node:child_process";
7
7
  import { mkdirSync, writeFileSync, readFileSync, existsSync, realpathSync, rmSync, chmodSync, readdirSync } from "node:fs";
8
8
  import { homedir, tmpdir } from "node:os";
9
- import { join, dirname } from "node:path";
9
+ import { basename, join, dirname } from "node:path";
10
10
  import { fileURLToPath } from "node:url";
11
11
 
12
12
  export const SERVER_NAME = "futuvara";
13
- const DEFAULT_URL = "https://www.futuvara.com";
13
+ const DEFAULT_URL = "https://app.futuvara.com";
14
14
 
15
15
  /**
16
16
  * The environment variable holding one project's key: FUTUVARA_KEY_ + the project name upper-cased, every
@@ -93,13 +93,83 @@ export function mergeMcpServers(existing, entry) {
93
93
  return JSON.stringify(config, null, 2) + "\n";
94
94
  }
95
95
 
96
- // https://code.claude.com/docs/en/mcp — .mcp.json expands ${VAR} in url and headers.
96
+ // What Hub › Projects › Terminals lists a session by: its worktree's folder name (never the
97
+ // full path, which names the person) and its branch, printable ASCII only (a header must be).
98
+ // One JS snippet for the .mcp.json headersHelper and the session hooks, which run under bash
99
+ // and cmd alike: no `$`, `%`, `!`, backtick or backslash in it.
100
+ const WHERE_JS =
101
+ "const g=a=>{try{return require('child_process').execFileSync('git',a.split(' '),{encoding:'utf8',stdio:['ignore','pipe','ignore']}).trim().replace(/[^ -~]/g,'')}catch(e){return ''}};" +
102
+ "const where={'X-Futuvara-Worktree':require('path').basename(g('rev-parse --show-toplevel')),'X-Futuvara-Branch':g('branch --show-current')};";
103
+
104
+ /** Claude Code runs it at session start in the repository and adds its JSON to the headers. */
105
+ export const HEADERS_HELPER = `node -e "${WHERE_JS}console.log(JSON.stringify(where))"`;
106
+
107
+ /** The same headers for a call made from this process (`connect call`). */
108
+ export function sessionHeaders(cwd = process.cwd()) {
109
+ const g = (args) => {
110
+ const r = spawnSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 10_000 });
111
+ return r.status === 0 ? r.stdout.trim().replace(/[^ -~]/g, "") : "";
112
+ };
113
+ return { "X-Futuvara-Worktree": basename(g(["rev-parse", "--show-toplevel"])), "X-Futuvara-Branch": g(["branch", "--show-current"]) };
114
+ }
115
+
116
+ export const SESSION_PATH = "/api/connect/session";
117
+
118
+ /**
119
+ * A SessionStart / SessionEnd hook: tells Futuvara the session started or ended, so it shows
120
+ * on Terminals from its first second and leaves when it closes. Silent and never blocking:
121
+ * no key, no network or a slow server (5 s) and it simply exits.
122
+ */
123
+ export const sessionHook = (base, variable, event) =>
124
+ `node -e "const k=process.env.${variable};if(k){let i={};try{i=JSON.parse(require('fs').readFileSync(0,'utf8'))}catch(e){}${WHERE_JS}` +
125
+ `fetch('${base}${SESSION_PATH}',{method:'POST',headers:{...where,'content-type':'application/json',authorization:'Bearer '+k},` +
126
+ `body:JSON.stringify({event:'${event}',source:i.source,reason:i.reason}),signal:AbortSignal.timeout(5000)}).catch(()=>{})}"`;
127
+
128
+ /**
129
+ * A PostToolUse hook on Write / Edit: sends the markdown file the session just wrote (a plan,
130
+ * a design, notes) with its repository path (both sides resolved: Windows short names, macOS
131
+ * /var links), so Terminals' Docs tab shows it. Other files,
132
+ * no key or a file over 2 MB and it exits; never blocking, like the session hooks.
133
+ */
134
+ export const docHook = (base, variable) =>
135
+ `node -e "const k=process.env.${variable};if(k){let i={};try{i=JSON.parse(require('fs').readFileSync(0,'utf8'))}catch(e){}` +
136
+ `const f=String((i.tool_input||{}).file_path||'');if(/[.]md$|[.]markdown$/i.test(f)){${WHERE_JS}` +
137
+ `let c='',p='';try{const fs=require('fs'),r=fs.realpathSync.native;c=fs.readFileSync(f,'utf8');` +
138
+ `p=require('path').relative(r(require('child_process').execFileSync('git',['rev-parse','--show-toplevel'],{encoding:'utf8',stdio:['ignore','pipe','ignore']}).trim()),r(f))}catch(e){}` +
139
+ `if(c&&p&&c.length<2e6)fetch('${base}${SESSION_PATH}',{method:'POST',headers:{...where,'content-type':'application/json',authorization:'Bearer '+k},` +
140
+ `body:JSON.stringify({event:'doc',path:p,content:c}),signal:AbortSignal.timeout(5000)}).catch(()=>{})}}"`;
141
+
142
+ // https://code.claude.com/docs/en/mcp — .mcp.json expands ${VAR} in url and headers; headersHelper adds headers at connect.
97
143
  export const claudeEntry = (mcpUrl, variable) => ({
98
144
  type: "http",
99
145
  url: mcpUrl,
100
146
  headers: { Authorization: `Bearer \${${variable}}` },
147
+ headersHelper: HEADERS_HELPER,
101
148
  });
102
149
 
150
+ /**
151
+ * The repository's committed `.claude/settings.json`, every other setting kept: our `.mcp.json`
152
+ * server approved (`enabledMcpjsonServers`), so every session in every worktree connects it at
153
+ * start with no prompt, the session start/end hooks and the doc hook (ours replaced, never doubled).
154
+ * @param {string | null} existing current file text, or null when there is no file
155
+ */
156
+ export function futuvaraSettings(existing, base, variable) {
157
+ const settings = existing?.trim() ? JSON.parse(existing) : {};
158
+ const approved = Array.isArray(settings.enabledMcpjsonServers) ? settings.enabledMcpjsonServers : [];
159
+ if (!approved.includes(SERVER_NAME)) settings.enabledMcpjsonServers = [...approved, SERVER_NAME];
160
+ settings.hooks = settings.hooks ?? {};
161
+ const ours = {
162
+ SessionStart: { hooks: [{ type: "command", command: sessionHook(base, variable, "start"), timeout: 10 }] },
163
+ SessionEnd: { hooks: [{ type: "command", command: sessionHook(base, variable, "end"), timeout: 10 }] },
164
+ PostToolUse: { matcher: "Write|Edit|MultiEdit", hooks: [{ type: "command", command: docHook(base, variable), timeout: 10 }] },
165
+ };
166
+ for (const [name, group] of Object.entries(ours)) {
167
+ const others = (Array.isArray(settings.hooks[name]) ? settings.hooks[name] : []).filter((g) => !JSON.stringify(g).includes(SESSION_PATH));
168
+ settings.hooks[name] = [...others, group];
169
+ }
170
+ return JSON.stringify(settings, null, 2) + "\n";
171
+ }
172
+
103
173
  // https://cursor.com/docs/context/mcp — ${env:NAME} is resolved in url and headers.
104
174
  export const cursorEntry = (mcpUrl, variable) => ({
105
175
  url: mcpUrl,
@@ -137,6 +207,7 @@ export async function callTool(mcpUrl, key, name, args = {}, fetchImpl = fetch)
137
207
  "Content-Type": "application/json",
138
208
  Accept: "application/json, text/event-stream",
139
209
  Authorization: `Bearer ${key}`,
210
+ ...sessionHeaders(),
140
211
  },
141
212
  body: JSON.stringify({ jsonrpc: "2.0", id, method: "tools/call", params: { name, arguments: args } }),
142
213
  signal: AbortSignal.timeout(60_000),
@@ -145,6 +216,17 @@ export async function callTool(mcpUrl, key, name, args = {}, fetchImpl = fetch)
145
216
  if (!res.ok) throw new Error(`Futuvara MCP server answered ${res.status} ${res.statusText} at ${mcpUrl}`);
146
217
  const msg = readRpcResponse(res.headers.get("content-type"), await res.text(), id);
147
218
  if (msg.error) throw new Error(`Futuvara MCP server error: ${msg.error.message}`);
219
+ // An image (get_image) has no text to print: save it and answer with where it is, so the agent can open it.
220
+ const images = (msg.result?.content ?? []).filter((c) => c.type === "image" && c.data);
221
+ if (images.length && !msg.result?.isError) {
222
+ const dir = join(tmpdir(), "futuvara-images");
223
+ mkdirSync(dir, { recursive: true });
224
+ return images.map((c, i) => {
225
+ const file = join(dir, `${name}-${Date.now()}-${i}.${(c.mimeType ?? "image/png").split("/")[1].replace("jpeg", "jpg")}`);
226
+ writeFileSync(file, Buffer.from(c.data, "base64"));
227
+ return { image: file, mimeType: c.mimeType };
228
+ });
229
+ }
148
230
  const text = msg.result?.content?.[0]?.text ?? "";
149
231
  if (msg.result?.isError) throw new Error(`Futuvara ${name}: ${text}`);
150
232
  try {
@@ -261,6 +343,10 @@ function configureMcp(agent, mcpUrl, repo, variable) {
261
343
  if (path) {
262
344
  const entry = agent === "cursor" ? cursorEntry(mcpUrl, variable) : claudeEntry(mcpUrl, variable);
263
345
  put(path, Buffer.from(mergeMcpServers(existsSync(path) ? readFileSync(path, "utf8") : null, entry)));
346
+ if (agent === "claude-code") {
347
+ const settings = join(repo, ".claude", "settings.json");
348
+ put(settings, Buffer.from(futuvaraSettings(existsSync(settings) ? readFileSync(settings, "utf8") : null, mcpUrl.slice(0, -"/api/connect/mcp".length), variable)));
349
+ }
264
350
  return console.log(`Added "${SERVER_NAME}" to ${path} (reads ${variable} at runtime).`);
265
351
  }
266
352
  switch (agent) {
@@ -422,6 +508,16 @@ export function verify(opts, names, { home = homedir(), cwd = process.cwd(), rep
422
508
  ? { status: "ok", label: `"${SERVER_NAME}" MCP server in ${config} reads ${variable}` }
423
509
  : { status: "fail", label: `"${SERVER_NAME}" MCP server in ${config} does not read ${variable}`, fix: rerun },
424
510
  );
511
+ if (opts.agent === "claude-code") {
512
+ const read = (p) => (existsSync(p) ? readFileSync(p, "utf8") : "");
513
+ const settings = read(join(repo, ".claude", "settings.json"));
514
+ const current = read(config).includes("headersHelper") && settings.includes("enabledMcpjsonServers") && settings.includes("event:'doc'");
515
+ checks.push(
516
+ current
517
+ ? { status: "ok", label: "sessions report their worktree, branch, start and end to Futuvara (Terminals)" }
518
+ : { status: "warn", label: "sessions here do not report their worktree, branch, start and end to Futuvara — connected before 0.3.5", fix: rerun },
519
+ );
520
+ }
425
521
  }
426
522
  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) });
427
523
  return checks;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@futuvara/connect",
3
- "version": "0.3.3",
3
+ "version": "0.3.5",
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": {