@phren/cli 0.2.10 → 0.2.11

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 (52) hide show
  1. package/README.md +3 -0
  2. package/dist/bridge/activity.d.ts +8 -0
  3. package/dist/bridge/activity.js +43 -0
  4. package/dist/bridge/agent-hooks.d.ts +15 -0
  5. package/dist/bridge/agent-hooks.js +160 -0
  6. package/dist/bridge/command.d.ts +1 -0
  7. package/dist/bridge/command.js +42 -0
  8. package/dist/bridge/herdr.d.ts +12 -0
  9. package/dist/bridge/herdr.js +147 -0
  10. package/dist/bridge/hook-main.d.ts +1 -0
  11. package/dist/bridge/hook-main.js +7 -0
  12. package/dist/bridge/install.d.ts +15 -0
  13. package/dist/bridge/install.js +264 -0
  14. package/dist/bridge/projects.d.ts +10 -0
  15. package/dist/bridge/projects.js +89 -0
  16. package/dist/bridge/protocol.d.ts +35 -0
  17. package/dist/bridge/protocol.js +34 -0
  18. package/dist/bridge/server.d.ts +16 -0
  19. package/dist/bridge/server.js +291 -0
  20. package/dist/bridge/transcripts.d.ts +30 -0
  21. package/dist/bridge/transcripts.js +177 -0
  22. package/dist/bridge/transport.d.ts +4 -0
  23. package/dist/bridge/transport.js +64 -0
  24. package/dist/bridge/uploads.d.ts +2 -0
  25. package/dist/bridge/uploads.js +45 -0
  26. package/dist/bridge-hook.mjs +22571 -0
  27. package/dist/cli/config.js +27 -0
  28. package/dist/cli/namespaces-skills.js +2 -2
  29. package/dist/cli/session-git.d.ts +6 -0
  30. package/dist/cli/session-git.js +26 -0
  31. package/dist/cli/session-start.js +3 -3
  32. package/dist/cli/session-stop.js +54 -52
  33. package/dist/cli-registry.d.ts +1 -1
  34. package/dist/cli-registry.js +11 -0
  35. package/dist/generated/memory-ui-graph.browser.js +86 -86
  36. package/dist/governance/locks.d.ts +2 -0
  37. package/dist/governance/locks.js +45 -0
  38. package/dist/index.js +38 -2
  39. package/dist/init/preferences.d.ts +2 -0
  40. package/dist/link/refresh.d.ts +1 -0
  41. package/dist/link/refresh.js +47 -0
  42. package/dist/memory-ui-graph.runtime.js +86 -86
  43. package/dist/shared/index.d.ts +3 -1
  44. package/dist/shared/index.js +3 -2
  45. package/dist/skill/state.d.ts +10 -0
  46. package/dist/skill/state.js +41 -17
  47. package/dist/sync/pull.d.ts +29 -0
  48. package/dist/sync/pull.js +225 -0
  49. package/dist/tools/finding.js +4 -2
  50. package/dist/tools/skills.js +3 -3
  51. package/dist/ui/server.js +1 -1
  52. package/package.json +3 -1
package/README.md CHANGED
@@ -4,6 +4,8 @@ MCP server that indexes your personal phren and exposes it to AI agents via full
4
4
 
5
5
  On startup it walks your phren directory, reads all `.md` files, and builds an in-memory SQLite FTS5 index.
6
6
 
7
+ Periodic remote checks are off by default. Enable them with `phren config pull-interval 60` to check shared Git stores every minute while running, coordinated across MCP clients using the same store. Changed refs are fetched and applied only as clean fast-forwards; dirty or diverged stores are deferred. Pulled changes refresh the index and existing managed skill/instruction mirrors. Configure this machine with `phren config pull-interval 600` (ten minutes) or `phren config pull-interval off`. Periodic checks are disabled for project-local stores and the manual preset; existing lifecycle hooks are configured separately.
8
+
7
9
  Public surface: 59 MCP tools across 13 modules (search, tasks, findings, notes, memory, data, graph, sessions, ops/review, skills, hooks, config, extraction).
8
10
 
9
11
  Notable shipped capabilities:
@@ -39,6 +41,7 @@ claude mcp add phren -- phren ~/.phren
39
41
  |----------|---------|-------------|
40
42
  | `PHREN_PATH` | `~/.phren` | Path to your phren instance |
41
43
  | `PHREN_PROFILE` | *(none)* | Active profile name. When unset, phren uses `machines.yaml` when available and otherwise falls back to an unscoped view |
44
+ | `PHREN_PULL_INTERVAL_SECONDS` | `0` (off) | Overrides the machine-local pull interval. Whole seconds from 30–86400, or `0`/`off` to disable periodic MCP checks. |
42
45
  | `PHREN_ACTOR` | OS user / env | Actor identity used in governance/audit RBAC checks |
43
46
 
44
47
  ## Tools
@@ -0,0 +1,8 @@
1
+ import { type Json } from "./protocol.js";
2
+ /** Local bounded journal. No prompts, transcript bodies, credentials, or cloud upload. */
3
+ export declare class ActivityJournal {
4
+ private pending;
5
+ private previous;
6
+ record(server: string, panes: Json[]): Promise<void>;
7
+ recent(): Promise<Json[]>;
8
+ }
@@ -0,0 +1,43 @@
1
+ import { appendFile, mkdir, readFile, rename, stat } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { bridgeRoot } from "./protocol.js";
4
+ /** Local bounded journal. No prompts, transcript bodies, credentials, or cloud upload. */
5
+ export class ActivityJournal {
6
+ pending = Promise.resolve();
7
+ previous = new Map();
8
+ record(server, panes) {
9
+ this.pending = this.pending.catch(() => { }).then(async () => {
10
+ const changes = [];
11
+ for (const pane of panes) {
12
+ if (!pane.agent)
13
+ continue;
14
+ const key = `${server}:${pane.pane_id}`;
15
+ const state = JSON.stringify([pane.agent, pane.agent_status, pane.terminal_id]);
16
+ if (this.previous.get(key) === state)
17
+ continue;
18
+ this.previous.set(key, state);
19
+ changes.push({ at: new Date().toISOString(), source: "herdr", server, workspace: pane.workspace_id,
20
+ tab: pane.tab_id, pane: pane.pane_id, provider: pane.agent, state: pane.agent_status, directory: pane.foreground_cwd || pane.cwd });
21
+ }
22
+ if (!changes.length)
23
+ return;
24
+ const root = bridgeRoot(), file = path.join(root, "activity.jsonl");
25
+ await mkdir(root, { recursive: true, mode: 0o700 });
26
+ if ((await stat(file).catch(() => null))?.size && (await stat(file)).size > 2_097_152)
27
+ await rename(file, file + ".previous");
28
+ await appendFile(file, changes.map(row => JSON.stringify(row)).join("\n") + "\n", { mode: 0o600 });
29
+ if (this.previous.size > 4096)
30
+ this.previous.clear();
31
+ });
32
+ return this.pending;
33
+ }
34
+ async recent() {
35
+ const text = await readFile(path.join(bridgeRoot(), "activity.jsonl"), "utf8").catch(() => "");
36
+ return text.trim().split("\n").slice(-500).flatMap(line => { try {
37
+ return [JSON.parse(line)];
38
+ }
39
+ catch {
40
+ return [];
41
+ } });
42
+ }
43
+ }
@@ -0,0 +1,15 @@
1
+ import { type Json, type Provider, type Target } from "./protocol.js";
2
+ export declare function recordedSession(server: string, pane: Json, pids: number[]): Promise<string | undefined>;
3
+ /** This socket is deliberately separate from the phone's HTTP pipe. Only local
4
+ * agent callbacks can register identities or create an approval request. */
5
+ export declare class AgentHooks {
6
+ private pending;
7
+ private watching;
8
+ private server?;
9
+ watch(target: Target): () => void;
10
+ approval(target: Target): Json | undefined;
11
+ answer(target: Target, id: string, decision: unknown): Promise<void>;
12
+ start(): Promise<void>;
13
+ close(): void;
14
+ }
15
+ export declare function agentHook(source: Provider): Promise<void>;
@@ -0,0 +1,160 @@
1
+ import { request, createServer } from "node:http";
2
+ import { mkdir, writeFile, readFile, rename, chmod, unlink, lstat } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { randomUUID } from "node:crypto";
5
+ import { z } from "zod";
6
+ import { BridgeError, bridgeRoot, object, objects, provider, targetSchema } from "./protocol.js";
7
+ import { herdrRoot, rpc, snapshot, validateTarget } from "./herdr.js";
8
+ const localSocket = () => path.join(bridgeRoot(), "agent.sock");
9
+ const bindingPath = (server, pane) => path.join(bridgeRoot(), "bindings", server, encodeURIComponent(pane) + ".json");
10
+ export async function recordedSession(server, pane, pids) {
11
+ try {
12
+ const value = object(JSON.parse(await readFile(bindingPath(server, String(pane.pane_id)), "utf8")));
13
+ if (value.terminal !== pane.terminal_id || value.source !== pane.agent || !Array.isArray(value.pids) || !value.pids.some(p => pids.includes(Number(p))))
14
+ return undefined;
15
+ return z.string().uuid().parse(value.session);
16
+ }
17
+ catch {
18
+ return undefined;
19
+ }
20
+ }
21
+ /** This socket is deliberately separate from the phone's HTTP pipe. Only local
22
+ * agent callbacks can register identities or create an approval request. */
23
+ export class AgentHooks {
24
+ pending = new Map();
25
+ watching = new Map();
26
+ server;
27
+ watch(target) {
28
+ const key = JSON.stringify(target);
29
+ this.watching.set(key, (this.watching.get(key) || 0) + 1);
30
+ return () => { const n = (this.watching.get(key) || 1) - 1; if (n)
31
+ this.watching.set(key, n);
32
+ else
33
+ this.watching.delete(key); };
34
+ }
35
+ approval(target) {
36
+ const pending = [...this.pending.entries()].find(([, p]) => JSON.stringify(p.target) === JSON.stringify(target));
37
+ return pending ? { actionId: pending[0], toolName: pending[1].tool, title: `Allow ${pending[1].tool}?`, message: pending[1].message } : undefined;
38
+ }
39
+ async answer(target, id, decision) {
40
+ const entry = this.pending.get(id);
41
+ if (!entry || JSON.stringify(entry.target) !== JSON.stringify(target) || !["approve", "deny"].includes(String(decision)))
42
+ throw new BridgeError(409, "This approval is no longer pending.");
43
+ await validateTarget(target);
44
+ if (this.pending.get(id) !== entry || entry.response.destroyed)
45
+ throw new BridgeError(409, "This approval is no longer pending.");
46
+ this.pending.delete(id);
47
+ clearTimeout(entry.timer);
48
+ entry.response.end(JSON.stringify({ hookSpecificOutput: { hookEventName: "PermissionRequest", decision: {
49
+ behavior: decision === "approve" ? "allow" : "deny", ...(decision === "deny" ? { message: "Declined in Phren." } : {}),
50
+ } } }));
51
+ }
52
+ async start() {
53
+ // The public helper singleton was already checked before this is called.
54
+ const previous = await lstat(localSocket()).catch(() => undefined);
55
+ if (previous) {
56
+ if (!previous.isSocket() || previous.uid !== process.getuid?.())
57
+ throw new Error("Unexpected agent callback socket.");
58
+ await unlink(localSocket());
59
+ }
60
+ this.server = createServer(async (req, res) => {
61
+ res.setHeader("Content-Type", "application/json");
62
+ try {
63
+ if (req.method !== "POST" || req.url !== "/hook")
64
+ throw new Error("Invalid callback");
65
+ let size = 0;
66
+ const chunks = [];
67
+ for await (const bytes of req) {
68
+ size += bytes.length;
69
+ if (size > 1_048_576)
70
+ throw new Error("Oversized hook");
71
+ chunks.push(bytes);
72
+ }
73
+ const body = object(JSON.parse(Buffer.concat(chunks).toString())), target = targetSchema.parse(body.target);
74
+ const s = await snapshot(target.server);
75
+ const pane = objects(s.panes).find(p => p.pane_id === target.pane && p.tab_id === target.tab && p.workspace_id === target.workspace);
76
+ if (!pane || (pane.agent && pane.agent !== target.source))
77
+ throw new Error("The pane changed");
78
+ const info = object((await rpc(target.server, "pane.process_info", { pane_id: target.pane })).process_info);
79
+ const pids = objects(info.foreground_processes).map(p => p.pid).filter(p => Number.isSafeInteger(p));
80
+ if (!pids.length)
81
+ throw new Error("No foreground process");
82
+ const file = bindingPath(target.server, target.pane);
83
+ await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
84
+ const temporary = file + "." + randomUUID();
85
+ await writeFile(temporary, JSON.stringify({ terminal: pane.terminal_id, source: target.source, session: target.session, pids }), { mode: 0o600, flag: "wx" });
86
+ await rename(temporary, file);
87
+ if (body.event !== "PermissionRequest" || target.source === "copilot" || !this.watching.has(JSON.stringify(target))) {
88
+ res.end("{}");
89
+ return;
90
+ }
91
+ // Only wait while a phone is watching this exact session; otherwise the
92
+ // agent's ordinary terminal permission prompt remains immediate.
93
+ if (this.pending.size >= 64) {
94
+ res.end("{}");
95
+ return;
96
+ }
97
+ const action = randomUUID();
98
+ const timer = setTimeout(() => { this.pending.delete(action); res.end("{}"); }, 55_000);
99
+ this.pending.set(action, { target, response: res, tool: String(body.tool || "action").slice(0, 200),
100
+ message: JSON.stringify(body.input || {}, null, 2).slice(0, 32_768), timer });
101
+ res.on("close", () => { clearTimeout(timer); this.pending.delete(action); });
102
+ }
103
+ catch {
104
+ if (!res.headersSent)
105
+ res.statusCode = 400;
106
+ res.end("{}");
107
+ }
108
+ });
109
+ this.server.requestTimeout = 65_000;
110
+ await new Promise((resolve, reject) => { this.server.once("error", reject); this.server.listen(localSocket(), () => resolve()); });
111
+ await chmod(localSocket(), 0o600);
112
+ }
113
+ close() {
114
+ for (const pending of this.pending.values()) {
115
+ clearTimeout(pending.timer);
116
+ pending.response.end("{}");
117
+ }
118
+ this.pending.clear();
119
+ this.server?.close();
120
+ this.server?.closeAllConnections();
121
+ }
122
+ }
123
+ export async function agentHook(source) {
124
+ provider.parse(source);
125
+ // A missing helper must never prevent the coding agent from running.
126
+ if (process.env.HERDR_ENV !== "1" || !process.env.HERDR_SOCKET_PATH)
127
+ return;
128
+ const socket = path.resolve(process.env.HERDR_SOCKET_PATH), root = path.resolve(herdrRoot());
129
+ const server = socket === path.join(root, "herdr.sock") ? "default"
130
+ : socket.startsWith(path.join(root, "sessions") + path.sep) ? path.basename(path.dirname(socket)) : undefined;
131
+ if (!server)
132
+ return;
133
+ let input = "";
134
+ for await (const chunk of process.stdin) {
135
+ input += chunk.toString();
136
+ if (input.length > 1_048_576)
137
+ return;
138
+ }
139
+ const value = object(JSON.parse(input));
140
+ if (value.agent_id || value.agentId || value.isSidechain || value.is_sidechain)
141
+ return;
142
+ const target = targetSchema.parse({ server, workspace: process.env.HERDR_WORKSPACE_ID, tab: process.env.HERDR_TAB_ID,
143
+ pane: process.env.HERDR_PANE_ID, source, session: value.session_id || value.sessionId });
144
+ const event = String(value.hook_event_name || "SessionStart");
145
+ const data = JSON.stringify({ target, event, tool: value.tool_name, input: value.tool_input });
146
+ await new Promise(resolve => {
147
+ const req = request({ socketPath: localSocket(), path: "/hook", method: "POST", timeout: event === "PermissionRequest" ? 58_000 : 1500,
148
+ headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(data) } }, res => {
149
+ let result = "";
150
+ res.on("data", chunk => { result += chunk.toString(); if (result.length > 16_384)
151
+ req.destroy(); });
152
+ res.on("end", () => { if (res.statusCode === 200 && event === "PermissionRequest")
153
+ process.stdout.write(result); resolve(); });
154
+ res.on("error", () => resolve());
155
+ });
156
+ req.on("error", () => resolve());
157
+ req.on("timeout", () => { req.destroy(); resolve(); });
158
+ req.end(data);
159
+ });
160
+ }
@@ -0,0 +1 @@
1
+ export declare function runBridge(args: string[], version: string): Promise<number>;
@@ -0,0 +1,42 @@
1
+ import { serve } from "./server.js";
2
+ import { dispatch, health } from "./transport.js";
3
+ import { install, rollback, uninstall } from "./install.js";
4
+ import { servers } from "./herdr.js";
5
+ import { agentHook } from "./agent-hooks.js";
6
+ import { provider } from "./protocol.js";
7
+ export async function runBridge(args, version) {
8
+ switch (args[0]) {
9
+ case "hook":
10
+ await agentHook(provider.parse(args[1])).catch(() => { });
11
+ break;
12
+ case "serve":
13
+ await serve(version);
14
+ break;
15
+ case "ssh":
16
+ await dispatch(process.env.SSH_ORIGINAL_COMMAND || "");
17
+ break;
18
+ case "install":
19
+ case "update":
20
+ await install(version, args.includes("--no-service"));
21
+ break;
22
+ case "uninstall":
23
+ await uninstall();
24
+ break;
25
+ case "rollback":
26
+ await rollback();
27
+ break;
28
+ case "status":
29
+ console.log(JSON.stringify(await health(), null, 2));
30
+ break;
31
+ case "doctor": {
32
+ const helper = await health(), muxes = await servers();
33
+ console.log(JSON.stringify({ ok: muxes.length > 0, helper, herdr: muxes, checks: {
34
+ privateSocket: true, protocol: true, independentHelper: true,
35
+ herdrRunning: muxes.length > 0, terminal: "SSH PTY; authorize the Phren device key with pty",
36
+ } }, null, 2));
37
+ return muxes.length > 0 ? 0 : 1;
38
+ }
39
+ default: throw new Error("Usage: phren bridge <install|status|doctor|update|rollback|uninstall>");
40
+ }
41
+ return 0;
42
+ }
@@ -0,0 +1,12 @@
1
+ import { type Json, type Target } from "./protocol.js";
2
+ export declare function herdrRoot(): string;
3
+ export declare function herdrSocket(server: string): string;
4
+ /** Herdr's documented newline JSON socket API. No shell, UI focus, or inherited caller context. */
5
+ export declare function rpc(server: string, method: string, params?: Json, signal?: AbortSignal): Promise<Json>;
6
+ export declare function servers(): Promise<Json[]>;
7
+ export declare function snapshot(server: string): Promise<Json>;
8
+ export declare function workspaceSnapshot(s: Json): Json;
9
+ export declare function paneIdentity(server: string, pane: Json): Promise<string | undefined>;
10
+ export declare function panes(server: string, workspace: string, tab: string): Promise<Json>;
11
+ export declare function validateTarget(target: Target, sending?: boolean): Promise<Json>;
12
+ export declare function trustedDirectory(pane: Json): Promise<string>;
@@ -0,0 +1,147 @@
1
+ import { execFile } from "node:child_process";
2
+ import { connect } from "node:net";
3
+ import { homedir } from "node:os";
4
+ import { readdir, readlink, realpath, stat } from "node:fs/promises";
5
+ import path from "node:path";
6
+ import { promisify } from "node:util";
7
+ import { BridgeError, id, object, objects, requestID, serverName } from "./protocol.js";
8
+ import { recordedSession } from "./agent-hooks.js";
9
+ const exec = promisify(execFile);
10
+ export function herdrRoot() { return process.env.PHREN_HERDR_HOME || path.join(homedir(), ".config/herdr"); }
11
+ export function herdrSocket(server) {
12
+ serverName.parse(server);
13
+ return path.join(herdrRoot(), ...(server === "default" ? [] : ["sessions", server]), "herdr.sock");
14
+ }
15
+ /** Herdr's documented newline JSON socket API. No shell, UI focus, or inherited caller context. */
16
+ export async function rpc(server, method, params = {}, signal) {
17
+ const socket = herdrSocket(server);
18
+ const metadata = await stat(socket);
19
+ if (!metadata.isSocket() || (process.getuid && metadata.uid !== process.getuid()))
20
+ throw new BridgeError(503, "The Herdr socket is unavailable.");
21
+ return new Promise((resolve, reject) => {
22
+ const client = connect(socket);
23
+ const key = requestID();
24
+ let pending = Buffer.alloc(0);
25
+ const finish = (error, result) => {
26
+ signal?.removeEventListener("abort", abort);
27
+ client.destroy();
28
+ if (error)
29
+ reject(error);
30
+ else
31
+ resolve(result);
32
+ };
33
+ const abort = () => finish(new BridgeError(499, "Request cancelled."));
34
+ if (signal?.aborted) {
35
+ abort();
36
+ return;
37
+ }
38
+ signal?.addEventListener("abort", abort, { once: true });
39
+ client.setTimeout(10_000, () => finish(new BridgeError(504, "Herdr did not answer. Refresh before trying again.")));
40
+ client.on("error", () => finish(new BridgeError(503, "Herdr is not reachable on this computer.")));
41
+ client.on("end", () => finish(new BridgeError(503, "Herdr closed the request before confirming it.")));
42
+ client.on("connect", () => client.write(JSON.stringify({ id: key, method, params }) + "\n"));
43
+ client.on("data", bytes => {
44
+ pending = Buffer.concat([pending, typeof bytes === "string" ? Buffer.from(bytes) : bytes]);
45
+ if (pending.length > 4_194_304) {
46
+ finish(new BridgeError(413, "Herdr response is too large."));
47
+ return;
48
+ }
49
+ const end = pending.indexOf(10);
50
+ if (end < 0)
51
+ return;
52
+ try {
53
+ const value = object(JSON.parse(pending.subarray(0, end).toString()));
54
+ if (value.id !== key)
55
+ throw new Error("Mismatched response");
56
+ if (value.error)
57
+ throw new BridgeError(409, "Herdr could not perform this action. Refresh the session before trying again.");
58
+ finish(undefined, object(value.result));
59
+ }
60
+ catch (error) {
61
+ finish(error instanceof Error ? error : new Error("Invalid Herdr response"));
62
+ }
63
+ });
64
+ });
65
+ }
66
+ export async function servers() {
67
+ const names = ["default", ...(await readdir(path.join(herdrRoot(), "sessions")).catch(() => [])).filter(n => serverName.safeParse(n).success)].slice(0, 64);
68
+ const results = await Promise.all(names.map(async (name) => {
69
+ try {
70
+ await rpc(name, "ping");
71
+ return { id: `herdr:${name}`, kind: "herdr", session: name, running: true };
72
+ }
73
+ catch {
74
+ return null;
75
+ }
76
+ }));
77
+ return results.filter((v) => v !== null);
78
+ }
79
+ export async function snapshot(server) { return object((await rpc(server, "session.snapshot")).snapshot); }
80
+ export function workspaceSnapshot(s) {
81
+ return { kind: "herdr", groups: objects(s.workspaces).map(w => ({ id: w.workspace_id, label: w.label,
82
+ children: objects(s.tabs).filter(t => t.workspace_id === w.workspace_id).map(t => {
83
+ const panes = objects(s.panes).filter(p => p.tab_id === t.tab_id);
84
+ const agent = panes.find(p => p.agent);
85
+ return { id: t.tab_id, label: t.label, title: agent?.title || agent?.terminal_title_stripped,
86
+ agent: agent?.agent, agentStatus: t.agent_status, cwd: agent?.foreground_cwd || agent?.cwd,
87
+ agentPaneCount: panes.filter(p => p.agent).length, paneCount: panes.length };
88
+ }) })) };
89
+ }
90
+ /** Only file descriptors held by this pane's foreground processes establish identity.
91
+ * A directory match, latest log, or focused tab must never select a conversation. */
92
+ async function processLogs(server, pane) {
93
+ const info = object((await rpc(server, "pane.process_info", { pane_id: pane.pane_id })).process_info);
94
+ const pids = objects(info.foreground_processes).map(p => p.pid).filter((p) => Number.isSafeInteger(p) && Number(p) > 0).slice(0, 16);
95
+ const paths = await Promise.all(pids.map(async (pid) => {
96
+ if (process.platform === "linux") {
97
+ const base = `/proc/${pid}/fd`;
98
+ return Promise.all((await readdir(base).catch(() => [])).slice(0, 4096).map(fd => readlink(path.join(base, fd)).catch(() => "")));
99
+ }
100
+ const result = await exec("/usr/sbin/lsof", ["-a", "-p", String(pid), "-Fn"], { timeout: 3000, maxBuffer: 1_048_576 }).catch(() => ({ stdout: "" }));
101
+ return result.stdout.split("\n").filter(n => n.startsWith("n/")).map(n => n.slice(1));
102
+ }));
103
+ return { files: [...new Set(paths.flat())].filter(p => p.endsWith(".jsonl")), pids };
104
+ }
105
+ export async function paneIdentity(server, pane) {
106
+ const reported = object(pane.agent_session);
107
+ if (reported.kind === "id" && reported.agent === pane.agent && typeof reported.value === "string" && /^[a-f0-9-]{36}$/i.test(reported.value))
108
+ return reported.value;
109
+ const { files, pids } = await processLogs(server, pane);
110
+ const candidates = files.flatMap(file => {
111
+ const match = pane.agent === "codex" ? /rollout-.*-([a-f0-9-]{36})\.jsonl$/i.exec(file)
112
+ : pane.agent === "claude" ? /\/([a-f0-9-]{36})\.jsonl$/i.exec(file)
113
+ : /\/session-state\/([a-f0-9-]{36})\/events\.jsonl$/i.exec(file);
114
+ return match ? [match[1]] : [];
115
+ });
116
+ if (new Set(candidates).size === 1)
117
+ return candidates[0];
118
+ // A lifecycle callback is bound to the process and terminal, never just cwd.
119
+ return candidates.length === 0 ? recordedSession(server, pane, pids) : undefined;
120
+ }
121
+ export async function panes(server, workspace, tab) {
122
+ id.parse(workspace);
123
+ id.parse(tab);
124
+ const s = await snapshot(server);
125
+ if (!objects(s.tabs).some(t => t.tab_id === tab && t.workspace_id === workspace))
126
+ throw new BridgeError(409, "This Herdr tab has changed. Refresh the computer.");
127
+ return { kind: "herdr", groupId: workspace, childId: tab, panes: await Promise.all(objects(s.panes)
128
+ .filter(p => p.workspace_id === workspace && p.tab_id === tab).map(async (p) => ({ id: p.pane_id,
129
+ label: p.label || p.pane_id, agent: p.agent, agentStatus: p.agent_status,
130
+ title: p.title || p.terminal_title_stripped, cwd: p.foreground_cwd || p.cwd,
131
+ sessionId: p.agent ? await paneIdentity(server, p) : undefined }))) };
132
+ }
133
+ export async function validateTarget(target, sending = false) {
134
+ const s = await snapshot(target.server);
135
+ const pane = objects(s.panes).find(p => p.pane_id === target.pane && p.tab_id === target.tab && p.workspace_id === target.workspace && p.agent === target.source);
136
+ if (!pane || await paneIdentity(target.server, pane) !== target.session)
137
+ throw new BridgeError(409, "This pane's conversation changed. Reopen the chat.");
138
+ if (sending && ["blocked", "waiting", "unknown"].includes(String(pane.agent_status)))
139
+ throw new BridgeError(409, "This agent needs input in the terminal first.");
140
+ return pane;
141
+ }
142
+ export async function trustedDirectory(pane) {
143
+ const cwd = pane.foreground_cwd || pane.cwd;
144
+ if (typeof cwd !== "string" || !path.isAbsolute(cwd))
145
+ throw new BridgeError(409, "This pane has no project folder.");
146
+ return realpath(cwd);
147
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,7 @@
1
+ import { runBridge } from "./command.js";
2
+ runBridge(process.argv.slice(2), PHREN_HOOK_VERSION).then(code => {
3
+ process.exitCode = code;
4
+ }).catch(error => {
5
+ console.error(error instanceof Error ? error.message : "Phren Hook failed.");
6
+ process.exitCode = 1;
7
+ });
@@ -0,0 +1,15 @@
1
+ export declare const forcedCommand = "command=\"sh ~/.local/share/phren/bridge/dispatch\"";
2
+ export declare function upgradeKeys(text: string): {
3
+ text: string;
4
+ changed: number;
5
+ };
6
+ export declare function install(version: string, noService?: boolean): Promise<void>;
7
+ export declare function uninstall(): Promise<void>;
8
+ interface SettingsEdit {
9
+ file: string;
10
+ before?: string;
11
+ after: string;
12
+ }
13
+ export declare function planAgentHooks(program: string, remove?: boolean): Promise<SettingsEdit[]>;
14
+ export declare function rollback(): Promise<void>;
15
+ export {};