@futuvara/connect 0.3.4 → 0.4.0
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 +4 -5
- package/bin/connect.js +183 -3
- package/lib/worktree-dashboard.mjs +1554 -0
- package/package.json +4 -2
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
|
|
83
|
-
`
|
|
84
|
-
|
|
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
|
@@ -4,9 +4,10 @@
|
|
|
4
4
|
// environment (FUTUVARA_KEY_<PROJECT>) and never written to a file.
|
|
5
5
|
import { parseArgs as nodeParseArgs } from "node:util";
|
|
6
6
|
import { spawnSync } from "node:child_process";
|
|
7
|
-
import {
|
|
7
|
+
import { createHash } from "node:crypto";
|
|
8
|
+
import { mkdirSync, writeFileSync, readFileSync, existsSync, realpathSync, rmSync, chmodSync, readdirSync, statSync } from "node:fs";
|
|
8
9
|
import { homedir, tmpdir } from "node:os";
|
|
9
|
-
import { join, dirname } from "node:path";
|
|
10
|
+
import { basename, join, dirname } from "node:path";
|
|
10
11
|
import { fileURLToPath } from "node:url";
|
|
11
12
|
|
|
12
13
|
export const SERVER_NAME = "futuvara";
|
|
@@ -93,13 +94,176 @@ export function mergeMcpServers(existing, entry) {
|
|
|
93
94
|
return JSON.stringify(config, null, 2) + "\n";
|
|
94
95
|
}
|
|
95
96
|
|
|
96
|
-
//
|
|
97
|
+
// What Hub › Projects › Terminals lists a session by: its worktree's folder name (never the
|
|
98
|
+
// full path, which names the person) and its branch, printable ASCII only (a header must be).
|
|
99
|
+
// One JS snippet for the .mcp.json headersHelper and the session hooks, which run under bash
|
|
100
|
+
// and cmd alike: no `$`, `%`, `!`, backtick or backslash in it.
|
|
101
|
+
const WHERE_JS =
|
|
102
|
+
"const g=a=>{try{return require('child_process').execFileSync('git',a.split(' '),{encoding:'utf8',stdio:['ignore','pipe','ignore']}).trim().replace(/[^ -~]/g,'')}catch(e){return ''}};" +
|
|
103
|
+
"const where={'X-Futuvara-Worktree':require('path').basename(g('rev-parse --show-toplevel')),'X-Futuvara-Branch':g('branch --show-current')};";
|
|
104
|
+
|
|
105
|
+
/** Claude Code runs it at session start in the repository and adds its JSON to the headers. */
|
|
106
|
+
export const HEADERS_HELPER = `node -e "${WHERE_JS}console.log(JSON.stringify(where))"`;
|
|
107
|
+
|
|
108
|
+
/** The same headers for a call made from this process (`connect call`). */
|
|
109
|
+
export function sessionHeaders(cwd = process.cwd()) {
|
|
110
|
+
const g = (args) => {
|
|
111
|
+
const r = spawnSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 10_000 });
|
|
112
|
+
return r.status === 0 ? r.stdout.trim().replace(/[^ -~]/g, "") : "";
|
|
113
|
+
};
|
|
114
|
+
return { "X-Futuvara-Worktree": basename(g(["rev-parse", "--show-toplevel"])), "X-Futuvara-Branch": g(["branch", "--show-current"]) };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export const SESSION_PATH = "/api/connect/session";
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* A SessionStart / SessionEnd hook: tells Futuvara the session started or ended, so it shows
|
|
121
|
+
* on Terminals from its first second and leaves when it closes. It sends Claude Code's own
|
|
122
|
+
* session id, so a second session in the same worktree keeps the row, and prints the reply's
|
|
123
|
+
* `context` (Claude Code adds a SessionStart hook's output to the session: the report_session
|
|
124
|
+
* reminder). Never blocking: no key, no network or a slow server (5 s) and it simply exits.
|
|
125
|
+
*/
|
|
126
|
+
export const sessionHook = (base, variable, event) =>
|
|
127
|
+
`node -e "const k=process.env.${variable};if(k){let i={};try{i=JSON.parse(require('fs').readFileSync(0,'utf8'))}catch(e){}${WHERE_JS}` +
|
|
128
|
+
`fetch('${base}${SESSION_PATH}',{method:'POST',headers:{...where,'content-type':'application/json',authorization:'Bearer '+k},` +
|
|
129
|
+
`body:JSON.stringify({event:'${event}',source:i.source,reason:i.reason,session:i.session_id}),signal:AbortSignal.timeout(5000)})` +
|
|
130
|
+
`.then(r=>r.json()).then(j=>{if(j.context)console.log(j.context)}).catch(()=>{})}"`;
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* A PostToolUse hook on Write / Edit: sends the markdown file the session just wrote (a plan,
|
|
134
|
+
* a design, notes) with its repository path (both sides resolved: Windows short names, macOS
|
|
135
|
+
* /var links), so Terminals' Docs tab shows it. Other files,
|
|
136
|
+
* no key or a file over 2 MB and it exits; never blocking, like the session hooks.
|
|
137
|
+
*/
|
|
138
|
+
export const docHook = (base, variable) =>
|
|
139
|
+
`node -e "const k=process.env.${variable};if(k){let i={};try{i=JSON.parse(require('fs').readFileSync(0,'utf8'))}catch(e){}` +
|
|
140
|
+
`const f=String((i.tool_input||{}).file_path||'');if(/[.]md$|[.]markdown$/i.test(f)){${WHERE_JS}` +
|
|
141
|
+
`let c='',p='';try{const fs=require('fs'),r=fs.realpathSync.native;c=fs.readFileSync(f,'utf8');` +
|
|
142
|
+
`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){}` +
|
|
143
|
+
`if(c&&p&&c.length<2e6)fetch('${base}${SESSION_PATH}',{method:'POST',headers:{...where,'content-type':'application/json',authorization:'Bearer '+k},` +
|
|
144
|
+
`body:JSON.stringify({event:'doc',path:p,content:c}),signal:AbortSignal.timeout(5000)}).catch(()=>{})}}"`;
|
|
145
|
+
|
|
146
|
+
/** `report` runs at most this often per worktree and branch, except at a session's start. */
|
|
147
|
+
export const REPORT_EVERY_MS = 60_000;
|
|
148
|
+
/** In every report file's name, so `futuvaraSettings` knows its own report hooks. */
|
|
149
|
+
const REPORT_MARK = "futuvara-report-";
|
|
150
|
+
const REPORT_RUNNER = "npx -y @futuvara/connect@latest";
|
|
151
|
+
|
|
152
|
+
/** The file `report` and its hook share for one worktree and branch: touched at each send, it holds each markdown file's last-sent hash. */
|
|
153
|
+
export const reportStamp = (top, branch, dir = tmpdir()) =>
|
|
154
|
+
join(dir, `${REPORT_MARK}${createHash("sha1").update(`${top}|${branch}`).digest("hex").slice(0, 16)}.json`);
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* A Stop hook (after each turn, at most once a minute) and a second SessionStart hook (`now`): start
|
|
158
|
+
* `report` in the background, so the worktree's facts — the local worktree dashboard's — and markdown
|
|
159
|
+
* changed outside Write/Edit reach Terminals (docs/plans/2026-11-10-terminals-mcp-sessions.md, 6.2).
|
|
160
|
+
* It only decides and spawns, so a turn never waits on git; no key, no repository and it exits.
|
|
161
|
+
*/
|
|
162
|
+
export const reportHook = (base, variable, now = false, runner = REPORT_RUNNER) =>
|
|
163
|
+
`node -e "const k=process.env.${variable};if(k){${WHERE_JS}const fs=require('fs'),t=g('rev-parse --show-toplevel');` +
|
|
164
|
+
`const f=require('path').join(require('os').tmpdir(),'${REPORT_MARK}'+require('crypto').createHash('sha1').update(t+'|'+where['X-Futuvara-Branch']).digest('hex').slice(0,16)+'.json');` +
|
|
165
|
+
`let m=0;try{m=fs.statSync(f).mtimeMs}catch(e){}if(t&&(${now}||Date.now()-m>${REPORT_EVERY_MS})){try{fs.utimesSync(f,new Date(),new Date())}catch(e){fs.writeFileSync(f,'{}')}` +
|
|
166
|
+
`require('child_process').spawn('${runner} report --url ${base} --key-var ${variable}',{shell:true,detached:true,stdio:'ignore',windowsHide:true}).unref()}}"`;
|
|
167
|
+
|
|
168
|
+
/** The branch's markdown: changed since `base` (committed or not) and untracked, newest first, at most 30, each under 2 MB. */
|
|
169
|
+
export function changedMarkdown(top, base) {
|
|
170
|
+
const git = (args) => {
|
|
171
|
+
const r = spawnSync("git", ["-c", "core.quotepath=off", ...args], { cwd: top, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 20_000 });
|
|
172
|
+
return r.status === 0 ? r.stdout.split("\n").map((l) => l.trim()).filter(Boolean) : [];
|
|
173
|
+
};
|
|
174
|
+
const names = [...(base ? git(["diff", "--name-only", "--diff-filter=AMR", base]) : []), ...git(["ls-files", "--others", "--exclude-standard"])];
|
|
175
|
+
return [...new Set(names)]
|
|
176
|
+
.filter((p) => /\.(md|markdown)$/i.test(p))
|
|
177
|
+
.map((p) => {
|
|
178
|
+
try {
|
|
179
|
+
const st = statSync(join(top, p));
|
|
180
|
+
return st.isFile() && st.size < 2e6 ? { p, t: st.mtimeMs } : null;
|
|
181
|
+
} catch {
|
|
182
|
+
return null;
|
|
183
|
+
}
|
|
184
|
+
})
|
|
185
|
+
.filter(Boolean)
|
|
186
|
+
.sort((a, b) => b.t - a.t)
|
|
187
|
+
.slice(0, 30)
|
|
188
|
+
.map((x) => x.p);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** The worktree dashboard's collector: bundled into the package on publish (`prepack`), else this repository's own. */
|
|
192
|
+
function dashboardModule() {
|
|
193
|
+
const bundled = new URL("../lib/worktree-dashboard.mjs", import.meta.url);
|
|
194
|
+
return existsSync(fileURLToPath(bundled)) ? bundled.href : new URL("../../../tools/worktree-dashboard/server.mjs", import.meta.url).href;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* `report --url U --key-var V`: this worktree's facts (the worktree dashboard's `collectOne`) and its
|
|
199
|
+
* markdown changed since the last send, posted to the session on Hub › Projects › Terminals. Run by
|
|
200
|
+
* `reportHook` in the background. No key or no repository and it does nothing.
|
|
201
|
+
*/
|
|
202
|
+
export async function reportMain(argv, { env = process.env, cwd = process.cwd(), fetchImpl = fetch, collect = null, stampDir = tmpdir() } = {}) {
|
|
203
|
+
const { values } = nodeParseArgs({ args: argv, options: { url: { type: "string", default: DEFAULT_URL }, "key-var": { type: "string", default: "" } } });
|
|
204
|
+
const key = values["key-var"] ? env[values["key-var"]] : "";
|
|
205
|
+
const top = gitRoot(cwd);
|
|
206
|
+
if (!key || !top) return 0;
|
|
207
|
+
const headers = { ...sessionHeaders(top), "content-type": "application/json", authorization: `Bearer ${key}` };
|
|
208
|
+
const post = (body) =>
|
|
209
|
+
fetchImpl(`${values.url.replace(/\/+$/, "")}${SESSION_PATH}`, { method: "POST", headers, body: JSON.stringify(body), signal: AbortSignal.timeout(15_000) });
|
|
210
|
+
const report = await (collect ?? (await import(dashboardModule())).collectOne)(top);
|
|
211
|
+
await post({ event: "worktree", report });
|
|
212
|
+
const stamp = reportStamp(top, headers["X-Futuvara-Branch"], stampDir);
|
|
213
|
+
let sent = {};
|
|
214
|
+
try {
|
|
215
|
+
sent = JSON.parse(readFileSync(stamp, "utf8")).docs ?? {};
|
|
216
|
+
} catch {
|
|
217
|
+
// first send from this worktree and branch
|
|
218
|
+
}
|
|
219
|
+
for (const path of changedMarkdown(top, report.mergeBase)) {
|
|
220
|
+
const content = readFileSync(join(top, path), "utf8");
|
|
221
|
+
const hash = createHash("sha1").update(content).digest("hex");
|
|
222
|
+
if (sent[path] === hash) continue;
|
|
223
|
+
if ((await post({ event: "doc", path, content })).ok) sent[path] = hash;
|
|
224
|
+
}
|
|
225
|
+
writeFileSync(stamp, JSON.stringify({ docs: sent }));
|
|
226
|
+
return 0;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// https://code.claude.com/docs/en/mcp — .mcp.json expands ${VAR} in url and headers; headersHelper adds headers at connect.
|
|
97
230
|
export const claudeEntry = (mcpUrl, variable) => ({
|
|
98
231
|
type: "http",
|
|
99
232
|
url: mcpUrl,
|
|
100
233
|
headers: { Authorization: `Bearer \${${variable}}` },
|
|
234
|
+
headersHelper: HEADERS_HELPER,
|
|
101
235
|
});
|
|
102
236
|
|
|
237
|
+
/**
|
|
238
|
+
* The repository's committed `.claude/settings.json`, every other setting kept: our `.mcp.json`
|
|
239
|
+
* server approved (`enabledMcpjsonServers`), so every session in every worktree connects it at
|
|
240
|
+
* start with no prompt, the session start/end hooks and the doc hook (ours replaced, never doubled).
|
|
241
|
+
* @param {string | null} existing current file text, or null when there is no file
|
|
242
|
+
*/
|
|
243
|
+
export function futuvaraSettings(existing, base, variable) {
|
|
244
|
+
const settings = existing?.trim() ? JSON.parse(existing) : {};
|
|
245
|
+
const approved = Array.isArray(settings.enabledMcpjsonServers) ? settings.enabledMcpjsonServers : [];
|
|
246
|
+
if (!approved.includes(SERVER_NAME)) settings.enabledMcpjsonServers = [...approved, SERVER_NAME];
|
|
247
|
+
settings.hooks = settings.hooks ?? {};
|
|
248
|
+
const ours = {
|
|
249
|
+
SessionStart: {
|
|
250
|
+
hooks: [
|
|
251
|
+
{ type: "command", command: sessionHook(base, variable, "start"), timeout: 10 },
|
|
252
|
+
{ type: "command", command: reportHook(base, variable, true), timeout: 10 },
|
|
253
|
+
],
|
|
254
|
+
},
|
|
255
|
+
SessionEnd: { hooks: [{ type: "command", command: sessionHook(base, variable, "end"), timeout: 10 }] },
|
|
256
|
+
PostToolUse: { matcher: "Write|Edit|MultiEdit", hooks: [{ type: "command", command: docHook(base, variable), timeout: 10 }] },
|
|
257
|
+
Stop: { hooks: [{ type: "command", command: reportHook(base, variable), timeout: 10 }] },
|
|
258
|
+
};
|
|
259
|
+
const isOurs = (g) => JSON.stringify(g).includes(SESSION_PATH) || JSON.stringify(g).includes(REPORT_MARK);
|
|
260
|
+
for (const [name, group] of Object.entries(ours)) {
|
|
261
|
+
const others = (Array.isArray(settings.hooks[name]) ? settings.hooks[name] : []).filter((g) => !isOurs(g));
|
|
262
|
+
settings.hooks[name] = [...others, group];
|
|
263
|
+
}
|
|
264
|
+
return JSON.stringify(settings, null, 2) + "\n";
|
|
265
|
+
}
|
|
266
|
+
|
|
103
267
|
// https://cursor.com/docs/context/mcp — ${env:NAME} is resolved in url and headers.
|
|
104
268
|
export const cursorEntry = (mcpUrl, variable) => ({
|
|
105
269
|
url: mcpUrl,
|
|
@@ -137,6 +301,7 @@ export async function callTool(mcpUrl, key, name, args = {}, fetchImpl = fetch)
|
|
|
137
301
|
"Content-Type": "application/json",
|
|
138
302
|
Accept: "application/json, text/event-stream",
|
|
139
303
|
Authorization: `Bearer ${key}`,
|
|
304
|
+
...sessionHeaders(),
|
|
140
305
|
},
|
|
141
306
|
body: JSON.stringify({ jsonrpc: "2.0", id, method: "tools/call", params: { name, arguments: args } }),
|
|
142
307
|
signal: AbortSignal.timeout(60_000),
|
|
@@ -272,6 +437,10 @@ function configureMcp(agent, mcpUrl, repo, variable) {
|
|
|
272
437
|
if (path) {
|
|
273
438
|
const entry = agent === "cursor" ? cursorEntry(mcpUrl, variable) : claudeEntry(mcpUrl, variable);
|
|
274
439
|
put(path, Buffer.from(mergeMcpServers(existsSync(path) ? readFileSync(path, "utf8") : null, entry)));
|
|
440
|
+
if (agent === "claude-code") {
|
|
441
|
+
const settings = join(repo, ".claude", "settings.json");
|
|
442
|
+
put(settings, Buffer.from(futuvaraSettings(existsSync(settings) ? readFileSync(settings, "utf8") : null, mcpUrl.slice(0, -"/api/connect/mcp".length), variable)));
|
|
443
|
+
}
|
|
275
444
|
return console.log(`Added "${SERVER_NAME}" to ${path} (reads ${variable} at runtime).`);
|
|
276
445
|
}
|
|
277
446
|
switch (agent) {
|
|
@@ -433,6 +602,16 @@ export function verify(opts, names, { home = homedir(), cwd = process.cwd(), rep
|
|
|
433
602
|
? { status: "ok", label: `"${SERVER_NAME}" MCP server in ${config} reads ${variable}` }
|
|
434
603
|
: { status: "fail", label: `"${SERVER_NAME}" MCP server in ${config} does not read ${variable}`, fix: rerun },
|
|
435
604
|
);
|
|
605
|
+
if (opts.agent === "claude-code") {
|
|
606
|
+
const read = (p) => (existsSync(p) ? readFileSync(p, "utf8") : "");
|
|
607
|
+
const settings = read(join(repo, ".claude", "settings.json"));
|
|
608
|
+
const current = read(config).includes("headersHelper") && settings.includes("enabledMcpjsonServers") && settings.includes("event:'doc'") && settings.includes("session:i.session_id") && settings.includes(REPORT_MARK);
|
|
609
|
+
checks.push(
|
|
610
|
+
current
|
|
611
|
+
? { status: "ok", label: "sessions report their worktree, branch, start, end and worktree facts to Futuvara (Terminals)" }
|
|
612
|
+
: { status: "warn", label: "sessions here do not report their worktree, branch, start, end and worktree facts to Futuvara — connected before 0.4.0", fix: rerun },
|
|
613
|
+
);
|
|
614
|
+
}
|
|
436
615
|
}
|
|
437
616
|
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) });
|
|
438
617
|
return checks;
|
|
@@ -479,6 +658,7 @@ export async function callMain(argv, env = process.env, fetchImpl = fetch) {
|
|
|
479
658
|
/** @returns {Promise<number>} the exit code */
|
|
480
659
|
export async function main(argv = process.argv.slice(2)) {
|
|
481
660
|
if (argv[0] === "call") return callMain(argv.slice(1));
|
|
661
|
+
if (argv[0] === "report") return reportMain(argv.slice(1));
|
|
482
662
|
let opts;
|
|
483
663
|
try {
|
|
484
664
|
opts = parseArgs(argv);
|