@futuvara/connect 0.3.5 → 0.5.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/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 { mkdirSync, writeFileSync, readFileSync, existsSync, realpathSync, rmSync, chmodSync, readdirSync } from "node:fs";
7
+ import { createHash } from "node:crypto";
8
+ import { mkdirSync, writeFileSync, readFileSync, existsSync, realpathSync, rmSync, chmodSync, readdirSync, statSync, openSync, readSync, fstatSync, closeSync } from "node:fs";
8
9
  import { homedir, tmpdir } from "node:os";
9
- import { basename, join, dirname } from "node:path";
10
+ import { basename, join, dirname, relative, isAbsolute, sep } from "node:path";
10
11
  import { fileURLToPath } from "node:url";
11
12
 
12
13
  export const SERVER_NAME = "futuvara";
@@ -117,13 +118,16 @@ export const SESSION_PATH = "/api/connect/session";
117
118
 
118
119
  /**
119
120
  * 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.
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.
122
125
  */
123
126
  export const sessionHook = (base, variable, event) =>
124
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}` +
125
128
  `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(()=>{})}"`;
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(()=>{})}"`;
127
131
 
128
132
  /**
129
133
  * A PostToolUse hook on Write / Edit: sends the markdown file the session just wrote (a plan,
@@ -139,6 +143,231 @@ export const docHook = (base, variable) =>
139
143
  `if(c&&p&&c.length<2e6)fetch('${base}${SESSION_PATH}',{method:'POST',headers:{...where,'content-type':'application/json',authorization:'Bearer '+k},` +
140
144
  `body:JSON.stringify({event:'doc',path:p,content:c}),signal:AbortSignal.timeout(5000)}).catch(()=>{})}}"`;
141
145
 
146
+ /**
147
+ * A PreToolUse hook on every tool (and on Stop, `idle`): what the session is doing now — planning,
148
+ * coding, testing, asking, committing, merging or deploying — from the tool it is about to use and, for
149
+ * a shell, its command, so Terminals shows it as it happens and counts its active time (owner,
150
+ * 2026-11-16). A tool that says nothing keeps the last activity (planning after idle). Sent when it
151
+ * changes, else at most once a minute (a stamp per Claude session): the minute heartbeat is the clock.
152
+ * Never blocking: no key, no network or a slow server (3 s) and it exits. No `$`, `%`, `!`, backtick or
153
+ * backslash, like the other hooks.
154
+ */
155
+ export const activityHook = (base, variable) =>
156
+ `node -e "const k=process.env.${variable};if(k){let i={};try{i=JSON.parse(require('fs').readFileSync(0,'utf8'))}catch(e){}` +
157
+ `const n=String(i.tool_name||''),t=i.tool_input||{},c=' '+String(t.command||'').toLowerCase()+' ',f=String(t.file_path||t.notebook_path||'').split(String.fromCharCode(92)).join('/').toLowerCase();` +
158
+ `const fs=require('fs'),F=require('path').join(require('os').tmpdir(),'futuvara-activity-'+String(i.session_id||'x').replace(/[^a-z0-9-]/gi,'')+'.json');` +
159
+ `let o={};try{o=JSON.parse(fs.readFileSync(F,'utf8'))}catch(e){}const last=o.kind==='idle'?'':String(o.kind||'');` +
160
+ `const kind=(i.hook_event_name==='Stop'?'idle':n==='AskUserQuestion'?'asking':/PlanMode/.test(n)?'planning'` +
161
+ `:['Write','Edit','MultiEdit','NotebookEdit'].includes(n)?(/[/]plans[/]|plan[^/]*[.]md/.test(f)?'planning':'coding')` +
162
+ `:['Bash','PowerShell'].includes(n)?(/ship[.]sh|[^a-z-]deploy[^a-z]|npm +publish/.test(c)?'deploying'` +
163
+ `:/[^a-z-]git +(merge|rebase|cherry-pick|pull)[^a-z-]/.test(c)?'merging':/[^a-z-]git +(commit|push)[^a-z-]/.test(c)?'committing'` +
164
+ `:/vitest|playwright|pytest|jest|eslint|typecheck|[^a-z-]tsc[^a-z]|npm +(run +)?(test|lint)[^a-z]|ci[.]sh/.test(c)?'testing':''):'')||last||'planning';` +
165
+ `if(o.kind===kind&&Date.now()-o.t<60000){}else{try{fs.writeFileSync(F,JSON.stringify({kind:kind,t:Date.now()}))}catch(e){}${WHERE_JS}` +
166
+ `fetch('${base}${SESSION_PATH}',{method:'POST',headers:{...where,'content-type':'application/json',authorization:'Bearer '+k},` +
167
+ `body:JSON.stringify({event:'activity',kind:kind,session:i.session_id}),signal:AbortSignal.timeout(3000)}).catch(()=>{})}}"`;
168
+
169
+ /** `report` runs at most this often per worktree and branch, except at a session's start. */
170
+ export const REPORT_EVERY_MS = 60_000;
171
+ /** In every report file's name, so `futuvaraSettings` knows its own report hooks. */
172
+ const REPORT_MARK = "futuvara-report-";
173
+ const REPORT_RUNNER = "npx -y @futuvara/connect@latest";
174
+
175
+ /** 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. */
176
+ export const reportStamp = (top, branch, dir = tmpdir()) =>
177
+ join(dir, `${REPORT_MARK}${createHash("sha1").update(`${top}|${branch}`).digest("hex").slice(0, 16)}.json`);
178
+
179
+ /**
180
+ * A Stop hook (after each turn) and a second SessionStart hook (`now`): start `report` in the background,
181
+ * so the turn's conversation (from Claude Code's transcript, every turn) and — at most once a minute —
182
+ * the worktree's facts, the local worktree dashboard's, and markdown changed outside Write/Edit reach
183
+ * Terminals (docs/plans/2026-11-10-terminals-mcp-sessions.md, 6.2 and 9.1). It only decides and spawns,
184
+ * so a turn never waits on git; no key, no repository and it exits. The transcript's path goes in the
185
+ * environment, so a path with spaces needs no quoting. Two steps, for Windows: a detached process has no
186
+ * console and ignores windowsHide, so the npx under it opened a visible window every turn. The detached
187
+ * node starts the shell non-detached, which gives it a hidden console that npx and its children share.
188
+ * The inner step takes its strings as arguments, so the hook needs no nested quotes or backslashes.
189
+ */
190
+ export const reportHook = (base, variable, now = false, runner = REPORT_RUNNER) =>
191
+ `node -e "const k=process.env.${variable};if(k){let i={};try{i=JSON.parse(require('fs').readFileSync(0,'utf8'))}catch(e){}${WHERE_JS}` +
192
+ `const fs=require('fs'),t=g('rev-parse --show-toplevel'),x=String(i.transcript_path||'');` +
193
+ `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');` +
194
+ `let m=0;try{m=fs.statSync(f).mtimeMs}catch(e){}const w=${now}||Date.now()-m>${REPORT_EVERY_MS};if(t&&w){try{fs.utimesSync(f,new Date(),new Date())}catch(e){fs.writeFileSync(f,'{}')}}` +
195
+ `if(t&&(w||x))require('child_process').spawn(process.execPath,['-e','require(process.argv[1]).spawn(process.argv[2],{shell:true,stdio:process.argv[3],windowsHide:true,env:{...process.env,FUTUVARA_TRANSCRIPT:process.argv[4]}})',` +
196
+ `'child_process','${runner} report --url ${base} --key-var ${variable}'+(w?'':' --turn-only'),'ignore',x],{detached:true,stdio:'ignore',windowsHide:true}).unref()}"`;
197
+
198
+ /** At most this many lines go up per send, each at most `TURN_LINE_MAX` characters (the plan's default 2). */
199
+ export const TURN_MAX_LINES = 200;
200
+ const TURN_LINE_MAX = 4000;
201
+
202
+ /**
203
+ * A tool call in plain words, as the terminal host's `toolLabel` (services/terminal-host/lib.mjs) says it,
204
+ * but for someone's own computer: paths from the repository's top, and never a command — its description or nothing.
205
+ */
206
+ export function toolLabel(name, input, top) {
207
+ const i = input ?? {};
208
+ const one = (s) => String(s ?? "").split("\n")[0].trim().slice(0, 160);
209
+ const file = (p) => {
210
+ const r = relative(top, String(p ?? ""));
211
+ return r && !r.startsWith("..") && !isAbsolute(r) ? r.split(sep).join("/") : basename(String(p ?? ""));
212
+ };
213
+ const ran = () => (i.description ? `Ran a command: ${one(i.description)}` : "Ran a command");
214
+ const plain = {
215
+ Bash: ran,
216
+ PowerShell: ran,
217
+ Read: () => `Read ${file(i.file_path)}`,
218
+ Edit: () => `Edited ${file(i.file_path)}`,
219
+ MultiEdit: () => `Edited ${file(i.file_path)}`,
220
+ Write: () => `Wrote ${file(i.file_path)}`,
221
+ NotebookEdit: () => `Edited ${file(i.notebook_path)}`,
222
+ Grep: () => `Searched the code for “${one(i.pattern)}”`,
223
+ Glob: () => `Looked for files matching ${one(i.pattern)}`,
224
+ Agent: () => `Handed a helper agent: ${one(i.description)}`,
225
+ Task: () => `Handed a helper agent: ${one(i.description)}`,
226
+ TodoWrite: () => "Updated its to-do list",
227
+ // Never the query string: it can carry a token.
228
+ WebFetch: () => `Opened ${one(i.url).replace(/[?#].*/, "")}`,
229
+ WebSearch: () => `Searched the web for “${one(i.query)}”`,
230
+ ToolSearch: () => "Loaded its tools",
231
+ }[name];
232
+ if (plain) return plain();
233
+ const mcp = /^mcp__(.+?)__(.+)$/.exec(String(name));
234
+ if (!mcp) return String(name ?? "tool");
235
+ const what = ["message", "question", "section", "task", "query", "q"].map((k) => i[k]).find((v) => typeof v === "string" && v);
236
+ return `${mcp[1]}: ${mcp[2].replace(/_/g, " ")}${what ? ` — ${one(what)}` : ""}`;
237
+ }
238
+
239
+ /**
240
+ * Claude Code transcript entries (JSONL) as Terminal lines: what the person typed (`you`), the agent's words
241
+ * (`text`) and one plain line per tool call (`tool`). Never a tool's output or its raw input — either can hold
242
+ * a secret — and never a helper agent's own turns, the app's own messages (`<task-notification>`…) or a summary.
243
+ */
244
+ export function turnLines(jsonl, top) {
245
+ const out = [];
246
+ const clip = (s) => (s.length > TURN_LINE_MAX ? `${s.slice(0, TURN_LINE_MAX)}…` : s);
247
+ const said = (c) => (typeof c === "string" ? c : Array.isArray(c) ? c.filter((p) => p?.type === "text").map((p) => p.text).join("\n") : "").trim();
248
+ for (const raw of jsonl.split("\n")) {
249
+ let e;
250
+ try {
251
+ e = JSON.parse(raw);
252
+ } catch {
253
+ continue;
254
+ }
255
+ if (!e || e.isSidechain || e.isMeta || e.isCompactSummary) continue;
256
+ // A prompt typed while the agent works arrives as a queued command; a slash command as its tags.
257
+ const typed = e.type === "user" ? said(e.message?.content) : e.type === "attachment" && e.attachment?.type === "queued_command" ? said(e.attachment.prompt) : "";
258
+ const command = /<command-name>([^<]+)<\/command-name>(?:[\s\S]*<command-args>([^<]*)<\/command-args>)?/.exec(typed);
259
+ const you = command ? `${command[1]} ${command[2] ?? ""}`.trim() : typed.startsWith("<") ? "" : typed;
260
+ if (you) out.push({ kind: "you", text: clip(`› ${you}`) });
261
+ if (e.type !== "assistant" || !Array.isArray(e.message?.content)) continue;
262
+ for (const p of e.message.content) {
263
+ if (p?.type === "text" && p.text?.trim()) out.push({ kind: "text", text: clip(p.text.trim()) });
264
+ if (p?.type === "tool_use") out.push({ kind: "tool", text: `▸ ${toolLabel(p.name, p.input, top)}` });
265
+ }
266
+ }
267
+ return out.slice(-TURN_MAX_LINES);
268
+ }
269
+
270
+ /**
271
+ * The transcript's lines since the last send from it (a byte offset kept beside the report stamps), posted as one
272
+ * `turn`. A failed send keeps the offset, so the next turn carries both. Complete lines only: one still being
273
+ * written waits for the next send.
274
+ */
275
+ export async function sendTurn(transcript, top, post, dir = tmpdir()) {
276
+ const mark = join(dir, `futuvara-turn-${createHash("sha1").update(transcript).digest("hex").slice(0, 16)}.json`);
277
+ let from = 0;
278
+ try {
279
+ from = Number(JSON.parse(readFileSync(mark, "utf8")).offset) || 0;
280
+ } catch {
281
+ // the session's first send
282
+ }
283
+ let buf;
284
+ try {
285
+ const fd = openSync(transcript, "r");
286
+ try {
287
+ const size = fstatSync(fd).size;
288
+ if (from > size) from = 0;
289
+ buf = Buffer.alloc(size - from);
290
+ readSync(fd, buf, 0, buf.length, from);
291
+ } finally {
292
+ closeSync(fd);
293
+ }
294
+ } catch {
295
+ return;
296
+ }
297
+ const end = buf.lastIndexOf(10) + 1;
298
+ if (!end) return;
299
+ const lines = turnLines(buf.subarray(0, end).toString("utf8"), top);
300
+ if (lines.length && !(await post({ event: "turn", lines })).ok) return;
301
+ writeFileSync(mark, JSON.stringify({ offset: from + end }));
302
+ }
303
+
304
+ /** The branch's markdown: changed since `base` (committed or not) and untracked, newest first, at most 30, each under 2 MB. */
305
+ export function changedMarkdown(top, base) {
306
+ const git = (args) => {
307
+ const r = spawnSync("git", ["-c", "core.quotepath=off", ...args], { cwd: top, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 20_000 });
308
+ return r.status === 0 ? r.stdout.split("\n").map((l) => l.trim()).filter(Boolean) : [];
309
+ };
310
+ const names = [...(base ? git(["diff", "--name-only", "--diff-filter=AMR", base]) : []), ...git(["ls-files", "--others", "--exclude-standard"])];
311
+ return [...new Set(names)]
312
+ .filter((p) => /\.(md|markdown)$/i.test(p))
313
+ .map((p) => {
314
+ try {
315
+ const st = statSync(join(top, p));
316
+ return st.isFile() && st.size < 2e6 ? { p, t: st.mtimeMs } : null;
317
+ } catch {
318
+ return null;
319
+ }
320
+ })
321
+ .filter(Boolean)
322
+ .sort((a, b) => b.t - a.t)
323
+ .slice(0, 30)
324
+ .map((x) => x.p);
325
+ }
326
+
327
+ /** The worktree dashboard's collector: bundled into the package on publish (`prepack`), else this repository's own. */
328
+ function dashboardModule() {
329
+ const bundled = new URL("../lib/worktree-dashboard.mjs", import.meta.url);
330
+ return existsSync(fileURLToPath(bundled)) ? bundled.href : new URL("../../../tools/worktree-dashboard/server.mjs", import.meta.url).href;
331
+ }
332
+
333
+ /**
334
+ * `report --url U --key-var V [--turn-only]`: the turn's conversation (`FUTUVARA_TRANSCRIPT`, `sendTurn`), then this worktree's facts (the worktree dashboard's `collectOne`) and its
335
+ * markdown changed since the last send, posted to the session on Hub › Projects › Terminals. Run by
336
+ * `reportHook` in the background. No key or no repository and it does nothing.
337
+ */
338
+ export async function reportMain(argv, { env = process.env, cwd = process.cwd(), fetchImpl = fetch, collect = null, stampDir = tmpdir() } = {}) {
339
+ const { values } = nodeParseArgs({
340
+ args: argv,
341
+ options: { url: { type: "string", default: DEFAULT_URL }, "key-var": { type: "string", default: "" }, "turn-only": { type: "boolean", default: false } },
342
+ });
343
+ const key = values["key-var"] ? env[values["key-var"]] : "";
344
+ const top = gitRoot(cwd);
345
+ if (!key || !top) return 0;
346
+ const headers = { ...sessionHeaders(top), "content-type": "application/json", authorization: `Bearer ${key}` };
347
+ const post = (body) =>
348
+ fetchImpl(`${values.url.replace(/\/+$/, "")}${SESSION_PATH}`, { method: "POST", headers, body: JSON.stringify(body), signal: AbortSignal.timeout(15_000) });
349
+ // The conversation first: it is what the Terminal tab waits on. The worktree's facts only once a minute (the hook says).
350
+ if (env.FUTUVARA_TRANSCRIPT) await sendTurn(env.FUTUVARA_TRANSCRIPT, top, post, stampDir);
351
+ if (values["turn-only"]) return 0;
352
+ const report = await (collect ?? (await import(dashboardModule())).collectOne)(top);
353
+ await post({ event: "worktree", report });
354
+ const stamp = reportStamp(top, headers["X-Futuvara-Branch"], stampDir);
355
+ let sent = {};
356
+ try {
357
+ sent = JSON.parse(readFileSync(stamp, "utf8")).docs ?? {};
358
+ } catch {
359
+ // first send from this worktree and branch
360
+ }
361
+ for (const path of changedMarkdown(top, report.mergeBase)) {
362
+ const content = readFileSync(join(top, path), "utf8");
363
+ const hash = createHash("sha1").update(content).digest("hex");
364
+ if (sent[path] === hash) continue;
365
+ if ((await post({ event: "doc", path, content })).ok) sent[path] = hash;
366
+ }
367
+ writeFileSync(stamp, JSON.stringify({ docs: sent }));
368
+ return 0;
369
+ }
370
+
142
371
  // https://code.claude.com/docs/en/mcp — .mcp.json expands ${VAR} in url and headers; headersHelper adds headers at connect.
143
372
  export const claudeEntry = (mcpUrl, variable) => ({
144
373
  type: "http",
@@ -159,12 +388,25 @@ export function futuvaraSettings(existing, base, variable) {
159
388
  if (!approved.includes(SERVER_NAME)) settings.enabledMcpjsonServers = [...approved, SERVER_NAME];
160
389
  settings.hooks = settings.hooks ?? {};
161
390
  const ours = {
162
- SessionStart: { hooks: [{ type: "command", command: sessionHook(base, variable, "start"), timeout: 10 }] },
391
+ SessionStart: {
392
+ hooks: [
393
+ { type: "command", command: sessionHook(base, variable, "start"), timeout: 10 },
394
+ { type: "command", command: reportHook(base, variable, true), timeout: 10 },
395
+ ],
396
+ },
163
397
  SessionEnd: { hooks: [{ type: "command", command: sessionHook(base, variable, "end"), timeout: 10 }] },
398
+ PreToolUse: { hooks: [{ type: "command", command: activityHook(base, variable), timeout: 5 }] },
164
399
  PostToolUse: { matcher: "Write|Edit|MultiEdit", hooks: [{ type: "command", command: docHook(base, variable), timeout: 10 }] },
400
+ Stop: {
401
+ hooks: [
402
+ { type: "command", command: reportHook(base, variable), timeout: 10 },
403
+ { type: "command", command: activityHook(base, variable), timeout: 5 },
404
+ ],
405
+ },
165
406
  };
407
+ const isOurs = (g) => JSON.stringify(g).includes(SESSION_PATH) || JSON.stringify(g).includes(REPORT_MARK);
166
408
  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));
409
+ const others = (Array.isArray(settings.hooks[name]) ? settings.hooks[name] : []).filter((g) => !isOurs(g));
168
410
  settings.hooks[name] = [...others, group];
169
411
  }
170
412
  return JSON.stringify(settings, null, 2) + "\n";
@@ -511,11 +753,11 @@ export function verify(opts, names, { home = homedir(), cwd = process.cwd(), rep
511
753
  if (opts.agent === "claude-code") {
512
754
  const read = (p) => (existsSync(p) ? readFileSync(p, "utf8") : "");
513
755
  const settings = read(join(repo, ".claude", "settings.json"));
514
- const current = read(config).includes("headersHelper") && settings.includes("enabledMcpjsonServers") && settings.includes("event:'doc'");
756
+ const current = read(config).includes("headersHelper") && settings.includes("enabledMcpjsonServers") && settings.includes("event:'doc'") && settings.includes("session:i.session_id") && settings.includes(REPORT_MARK) && settings.includes("FUTUVARA_TRANSCRIPT");
515
757
  checks.push(
516
758
  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 },
759
+ ? { status: "ok", label: "sessions report their worktree, branch, start, end, worktree facts and conversation to Futuvara (Terminals)" }
760
+ : { status: "warn", label: "sessions here do not report their worktree, branch, start, end, worktree facts and conversation to Futuvara — connected before 0.5.0", fix: rerun },
519
761
  );
520
762
  }
521
763
  }
@@ -564,6 +806,7 @@ export async function callMain(argv, env = process.env, fetchImpl = fetch) {
564
806
  /** @returns {Promise<number>} the exit code */
565
807
  export async function main(argv = process.argv.slice(2)) {
566
808
  if (argv[0] === "call") return callMain(argv.slice(1));
809
+ if (argv[0] === "report") return reportMain(argv.slice(1));
567
810
  let opts;
568
811
  try {
569
812
  opts = parseArgs(argv);