@futuvara/connect 0.4.0 → 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 +163 -15
- package/package.json +1 -1
package/bin/connect.js
CHANGED
|
@@ -5,9 +5,9 @@
|
|
|
5
5
|
import { parseArgs as nodeParseArgs } from "node:util";
|
|
6
6
|
import { spawnSync } from "node:child_process";
|
|
7
7
|
import { createHash } from "node:crypto";
|
|
8
|
-
import { mkdirSync, writeFileSync, readFileSync, existsSync, realpathSync, rmSync, chmodSync, readdirSync, statSync } from "node:fs";
|
|
8
|
+
import { mkdirSync, writeFileSync, readFileSync, existsSync, realpathSync, rmSync, chmodSync, readdirSync, statSync, openSync, readSync, fstatSync, closeSync } from "node:fs";
|
|
9
9
|
import { homedir, tmpdir } from "node:os";
|
|
10
|
-
import { basename, join, dirname } from "node:path";
|
|
10
|
+
import { basename, join, dirname, relative, isAbsolute, sep } from "node:path";
|
|
11
11
|
import { fileURLToPath } from "node:url";
|
|
12
12
|
|
|
13
13
|
export const SERVER_NAME = "futuvara";
|
|
@@ -143,6 +143,29 @@ export const docHook = (base, variable) =>
|
|
|
143
143
|
`if(c&&p&&c.length<2e6)fetch('${base}${SESSION_PATH}',{method:'POST',headers:{...where,'content-type':'application/json',authorization:'Bearer '+k},` +
|
|
144
144
|
`body:JSON.stringify({event:'doc',path:p,content:c}),signal:AbortSignal.timeout(5000)}).catch(()=>{})}}"`;
|
|
145
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
|
+
|
|
146
169
|
/** `report` runs at most this often per worktree and branch, except at a session's start. */
|
|
147
170
|
export const REPORT_EVERY_MS = 60_000;
|
|
148
171
|
/** In every report file's name, so `futuvaraSettings` knows its own report hooks. */
|
|
@@ -154,16 +177,129 @@ export const reportStamp = (top, branch, dir = tmpdir()) =>
|
|
|
154
177
|
join(dir, `${REPORT_MARK}${createHash("sha1").update(`${top}|${branch}`).digest("hex").slice(0, 16)}.json`);
|
|
155
178
|
|
|
156
179
|
/**
|
|
157
|
-
* A Stop hook (after each turn
|
|
158
|
-
*
|
|
159
|
-
* changed outside Write/Edit reach
|
|
160
|
-
*
|
|
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.
|
|
161
189
|
*/
|
|
162
190
|
export const reportHook = (base, variable, now = false, runner = REPORT_RUNNER) =>
|
|
163
|
-
`node -e "const k=process.env.${variable};if(k){
|
|
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||'');` +
|
|
164
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');` +
|
|
165
|
-
`let m=0;try{m=fs.statSync(f).mtimeMs}catch(e){}
|
|
166
|
-
`require('child_process').spawn('
|
|
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
|
+
}
|
|
167
303
|
|
|
168
304
|
/** The branch's markdown: changed since `base` (committed or not) and untracked, newest first, at most 30, each under 2 MB. */
|
|
169
305
|
export function changedMarkdown(top, base) {
|
|
@@ -195,18 +331,24 @@ function dashboardModule() {
|
|
|
195
331
|
}
|
|
196
332
|
|
|
197
333
|
/**
|
|
198
|
-
* `report --url U --key-var V`: this worktree's facts (the worktree dashboard's `collectOne`) and its
|
|
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
|
|
199
335
|
* markdown changed since the last send, posted to the session on Hub › Projects › Terminals. Run by
|
|
200
336
|
* `reportHook` in the background. No key or no repository and it does nothing.
|
|
201
337
|
*/
|
|
202
338
|
export async function reportMain(argv, { env = process.env, cwd = process.cwd(), fetchImpl = fetch, collect = null, stampDir = tmpdir() } = {}) {
|
|
203
|
-
const { values } = nodeParseArgs({
|
|
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
|
+
});
|
|
204
343
|
const key = values["key-var"] ? env[values["key-var"]] : "";
|
|
205
344
|
const top = gitRoot(cwd);
|
|
206
345
|
if (!key || !top) return 0;
|
|
207
346
|
const headers = { ...sessionHeaders(top), "content-type": "application/json", authorization: `Bearer ${key}` };
|
|
208
347
|
const post = (body) =>
|
|
209
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;
|
|
210
352
|
const report = await (collect ?? (await import(dashboardModule())).collectOne)(top);
|
|
211
353
|
await post({ event: "worktree", report });
|
|
212
354
|
const stamp = reportStamp(top, headers["X-Futuvara-Branch"], stampDir);
|
|
@@ -253,8 +395,14 @@ export function futuvaraSettings(existing, base, variable) {
|
|
|
253
395
|
],
|
|
254
396
|
},
|
|
255
397
|
SessionEnd: { hooks: [{ type: "command", command: sessionHook(base, variable, "end"), timeout: 10 }] },
|
|
398
|
+
PreToolUse: { hooks: [{ type: "command", command: activityHook(base, variable), timeout: 5 }] },
|
|
256
399
|
PostToolUse: { matcher: "Write|Edit|MultiEdit", hooks: [{ type: "command", command: docHook(base, variable), timeout: 10 }] },
|
|
257
|
-
Stop: {
|
|
400
|
+
Stop: {
|
|
401
|
+
hooks: [
|
|
402
|
+
{ type: "command", command: reportHook(base, variable), timeout: 10 },
|
|
403
|
+
{ type: "command", command: activityHook(base, variable), timeout: 5 },
|
|
404
|
+
],
|
|
405
|
+
},
|
|
258
406
|
};
|
|
259
407
|
const isOurs = (g) => JSON.stringify(g).includes(SESSION_PATH) || JSON.stringify(g).includes(REPORT_MARK);
|
|
260
408
|
for (const [name, group] of Object.entries(ours)) {
|
|
@@ -605,11 +753,11 @@ export function verify(opts, names, { home = homedir(), cwd = process.cwd(), rep
|
|
|
605
753
|
if (opts.agent === "claude-code") {
|
|
606
754
|
const read = (p) => (existsSync(p) ? readFileSync(p, "utf8") : "");
|
|
607
755
|
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);
|
|
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");
|
|
609
757
|
checks.push(
|
|
610
758
|
current
|
|
611
|
-
? { status: "ok", label: "sessions report their worktree, branch, start, end
|
|
612
|
-
: { status: "warn", label: "sessions here do not report their worktree, branch, start, end
|
|
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 },
|
|
613
761
|
);
|
|
614
762
|
}
|
|
615
763
|
}
|
package/package.json
CHANGED