@phren/cli 0.2.9 → 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.
- package/README.md +3 -0
- package/dist/bridge/activity.d.ts +8 -0
- package/dist/bridge/activity.js +43 -0
- package/dist/bridge/agent-hooks.d.ts +15 -0
- package/dist/bridge/agent-hooks.js +160 -0
- package/dist/bridge/command.d.ts +1 -0
- package/dist/bridge/command.js +42 -0
- package/dist/bridge/herdr.d.ts +12 -0
- package/dist/bridge/herdr.js +147 -0
- package/dist/bridge/hook-main.d.ts +1 -0
- package/dist/bridge/hook-main.js +7 -0
- package/dist/bridge/install.d.ts +15 -0
- package/dist/bridge/install.js +264 -0
- package/dist/bridge/projects.d.ts +10 -0
- package/dist/bridge/projects.js +89 -0
- package/dist/bridge/protocol.d.ts +35 -0
- package/dist/bridge/protocol.js +34 -0
- package/dist/bridge/server.d.ts +16 -0
- package/dist/bridge/server.js +291 -0
- package/dist/bridge/transcripts.d.ts +30 -0
- package/dist/bridge/transcripts.js +177 -0
- package/dist/bridge/transport.d.ts +4 -0
- package/dist/bridge/transport.js +64 -0
- package/dist/bridge/uploads.d.ts +2 -0
- package/dist/bridge/uploads.js +45 -0
- package/dist/bridge-hook.mjs +22571 -0
- package/dist/cli/config.js +27 -0
- package/dist/cli/namespaces-skills.js +2 -2
- package/dist/cli/session-git.d.ts +6 -0
- package/dist/cli/session-git.js +26 -0
- package/dist/cli/session-start.js +3 -3
- package/dist/cli/session-stop.js +54 -52
- package/dist/cli-registry.d.ts +1 -1
- package/dist/cli-registry.js +11 -0
- package/dist/generated/memory-ui-graph.browser.js +86 -86
- package/dist/governance/locks.d.ts +2 -0
- package/dist/governance/locks.js +45 -0
- package/dist/index.js +38 -2
- package/dist/init/preferences.d.ts +2 -0
- package/dist/link/refresh.d.ts +1 -0
- package/dist/link/refresh.js +47 -0
- package/dist/memory-ui-graph.runtime.js +86 -86
- package/dist/shared/index.d.ts +3 -1
- package/dist/shared/index.js +3 -2
- package/dist/skill/state.d.ts +10 -0
- package/dist/skill/state.js +41 -17
- package/dist/sync/pull.d.ts +29 -0
- package/dist/sync/pull.js +225 -0
- package/dist/tools/finding.js +4 -2
- package/dist/tools/skills.js +3 -3
- package/dist/ui/server.js +1 -1
- package/package.json +3 -1
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { chmod, copyFile, mkdir, readFile, rename, symlink, unlink, lstat, writeFile } from "node:fs/promises";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { promisify } from "node:util";
|
|
7
|
+
import { bridgeRoot, object, objects } from "./protocol.js";
|
|
8
|
+
import { health } from "./transport.js";
|
|
9
|
+
const exec = promisify(execFile);
|
|
10
|
+
const label = "com.phren.hook";
|
|
11
|
+
const unit = "phren-hook.service";
|
|
12
|
+
export const forcedCommand = 'command="sh ~/.local/share/phren/bridge/dispatch"';
|
|
13
|
+
export function upgradeKeys(text) {
|
|
14
|
+
let changed = 0;
|
|
15
|
+
const result = text.split(/(?<=\n)/).map(line => {
|
|
16
|
+
if (!/ ssh-ed25519 [A-Za-z0-9+/=]+ phren-iphone\s*$/.test(line) || !line.startsWith("restrict,") || !line.includes('permitopen="127.0.0.1:'))
|
|
17
|
+
return line;
|
|
18
|
+
const old = /command="(?:\/usr\/bin\/false|python3 ~\/\.local\/share\/phren\/chat-progress\.py|sh ~\/\.local\/share\/phren\/bridge\/dispatch)"/;
|
|
19
|
+
if (!old.test(line))
|
|
20
|
+
return line;
|
|
21
|
+
let next = line.replace(old, forcedCommand);
|
|
22
|
+
if (!/(^|,)pty,/.test(next))
|
|
23
|
+
next = next.replace(/^restrict,/, "restrict,pty,");
|
|
24
|
+
if (next !== line)
|
|
25
|
+
changed++;
|
|
26
|
+
return next;
|
|
27
|
+
}).join("");
|
|
28
|
+
return { text: result, changed };
|
|
29
|
+
}
|
|
30
|
+
const quote = (s) => "'" + s.replace(/'/g, "'\\''") + "'";
|
|
31
|
+
const xml = (s) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
32
|
+
const systemdQuote = (s) => '"' + s.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%") + '"';
|
|
33
|
+
async function atomic(file, text, mode = 0o600) {
|
|
34
|
+
const temporary = file + `.phren-${process.pid}`;
|
|
35
|
+
await writeFile(temporary, text, { mode, flag: "wx" });
|
|
36
|
+
try {
|
|
37
|
+
await rename(temporary, file);
|
|
38
|
+
}
|
|
39
|
+
finally {
|
|
40
|
+
await unlink(temporary).catch(() => { });
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
async function activate(version) {
|
|
44
|
+
const root = bridgeRoot();
|
|
45
|
+
const next = path.join(root, `current-${process.pid}`);
|
|
46
|
+
await symlink(path.join("versions", version), next);
|
|
47
|
+
await rename(next, path.join(root, "current"));
|
|
48
|
+
}
|
|
49
|
+
async function stopService() {
|
|
50
|
+
if (process.platform === "darwin")
|
|
51
|
+
await exec("launchctl", ["bootout", `gui/${process.getuid()}/${label}`]).catch(() => { });
|
|
52
|
+
else
|
|
53
|
+
await exec("systemctl", ["--user", "stop", unit]).catch(() => { });
|
|
54
|
+
}
|
|
55
|
+
async function startService() {
|
|
56
|
+
if (process.platform === "darwin") {
|
|
57
|
+
// bootout returns before launchd finishes releasing the old job. A valid
|
|
58
|
+
// immediate bootstrap can transiently fail with EIO during an update.
|
|
59
|
+
for (let attempt = 0;; attempt++) {
|
|
60
|
+
try {
|
|
61
|
+
await exec("launchctl", ["bootstrap", `gui/${process.getuid()}`, path.join(homedir(), "Library/LaunchAgents", `${label}.plist`)]);
|
|
62
|
+
break;
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
if (attempt >= 5 || !String(error.stderr).includes("Bootstrap failed: 5:"))
|
|
66
|
+
throw error;
|
|
67
|
+
await new Promise(resolve => setTimeout(resolve, 200 * (attempt + 1)));
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
else {
|
|
72
|
+
await exec("systemctl", ["--user", "daemon-reload"]);
|
|
73
|
+
await exec("systemctl", ["--user", "enable", "--now", unit]);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
export async function install(version, noService = false) {
|
|
77
|
+
if (!["darwin", "linux"].includes(process.platform))
|
|
78
|
+
throw new Error("Phren Hook supports macOS and Linux.");
|
|
79
|
+
if (!/^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(version))
|
|
80
|
+
throw new Error("Invalid helper version.");
|
|
81
|
+
const root = bridgeRoot(), versions = path.join(root, "versions");
|
|
82
|
+
await mkdir(versions, { recursive: true, mode: 0o700 });
|
|
83
|
+
await chmod(root, 0o700);
|
|
84
|
+
const hookEdits = await planAgentHooks(path.join(root, "current/bridge-hook.mjs"));
|
|
85
|
+
const own = fileURLToPath(import.meta.url);
|
|
86
|
+
const bundle = own.endsWith("bridge-hook.mjs") ? own : path.join(path.dirname(own), "..", "bridge-hook.mjs");
|
|
87
|
+
const destination = path.join(versions, version);
|
|
88
|
+
await mkdir(destination, { recursive: true, mode: 0o700 });
|
|
89
|
+
const installedBundle = path.join(destination, "bridge-hook.mjs");
|
|
90
|
+
const previousBundle = await missingFile(readFile(installedBundle));
|
|
91
|
+
const stagedBundle = installedBundle + `.phren-${process.pid}`;
|
|
92
|
+
await copyFile(bundle, stagedBundle);
|
|
93
|
+
await rename(stagedBundle, installedBundle);
|
|
94
|
+
const previous = await readFile(path.join(root, "installed.json"), "utf8").then(v => JSON.parse(v)).catch(() => null);
|
|
95
|
+
await atomic(path.join(root, "dispatch"), `#!/bin/sh\nexec ${quote(process.execPath)} ${quote(path.join(root, "current/bridge-hook.mjs"))} ssh\n`, 0o700);
|
|
96
|
+
const environmentPath = [path.dirname(process.execPath), path.join(homedir(), ".local/bin"), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin"].join(":");
|
|
97
|
+
const program = path.join(root, "current/bridge-hook.mjs");
|
|
98
|
+
if (!noService) {
|
|
99
|
+
if (process.platform === "darwin") {
|
|
100
|
+
const folder = path.join(homedir(), "Library/LaunchAgents");
|
|
101
|
+
await mkdir(folder, { recursive: true });
|
|
102
|
+
await atomic(path.join(folder, `${label}.plist`), `<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0"><dict><key>Label</key><string>${label}</string><key>ProgramArguments</key><array><string>${xml(process.execPath)}</string><string>${xml(program)}</string><string>serve</string></array><key>RunAtLoad</key><true/><key>KeepAlive</key><true/><key>ThrottleInterval</key><integer>5</integer><key>EnvironmentVariables</key><dict><key>PATH</key><string>${xml(environmentPath)}</string><key>PHREN_BRIDGE_HOME</key><string>${xml(root)}</string></dict><key>StandardErrorPath</key><string>${xml(path.join(root, "service.log"))}</string></dict></plist>\n`);
|
|
103
|
+
}
|
|
104
|
+
else {
|
|
105
|
+
const folder = path.join(homedir(), ".config/systemd/user");
|
|
106
|
+
await mkdir(folder, { recursive: true });
|
|
107
|
+
await atomic(path.join(folder, unit), `[Unit]\nDescription=Phren Hook\n[Service]\nExecStart=${systemdQuote(process.execPath)} ${systemdQuote(program)} serve\nEnvironment=${systemdQuote("PATH=" + environmentPath)} ${systemdQuote("PHREN_BRIDGE_HOME=" + root)}\nRestart=on-failure\nRestartSec=3\nUMask=0077\n[Install]\nWantedBy=default.target\n`);
|
|
108
|
+
}
|
|
109
|
+
await stopService();
|
|
110
|
+
}
|
|
111
|
+
await activate(version);
|
|
112
|
+
try {
|
|
113
|
+
if (!noService) {
|
|
114
|
+
await startService();
|
|
115
|
+
let ready = false;
|
|
116
|
+
for (let i = 0; i < 30; i++) {
|
|
117
|
+
try {
|
|
118
|
+
const status = await health();
|
|
119
|
+
ready = status.version === version;
|
|
120
|
+
}
|
|
121
|
+
catch { /* bounded readiness check */ }
|
|
122
|
+
if (ready)
|
|
123
|
+
break;
|
|
124
|
+
await new Promise(resolve => setTimeout(resolve, 200));
|
|
125
|
+
}
|
|
126
|
+
if (!ready)
|
|
127
|
+
throw new Error("The new Phren Hook did not become ready.");
|
|
128
|
+
}
|
|
129
|
+
await applyAgentHooks(hookEdits);
|
|
130
|
+
const keys = path.join(homedir(), ".ssh/authorized_keys");
|
|
131
|
+
const keyStat = await lstat(keys).catch(() => null);
|
|
132
|
+
if (keyStat && !keyStat.isSymbolicLink() && keyStat.isFile()) {
|
|
133
|
+
const before = await readFile(keys, "utf8"), after = upgradeKeys(before);
|
|
134
|
+
if (after.changed) {
|
|
135
|
+
await copyFile(keys, keys + `.phren-hook-${Date.now()}.bak`);
|
|
136
|
+
if (await readFile(keys, "utf8") !== before)
|
|
137
|
+
throw new Error("authorized_keys changed during installation. Run install again.");
|
|
138
|
+
await atomic(keys, after.text, keyStat.mode & 0o777);
|
|
139
|
+
}
|
|
140
|
+
console.log(`Updated ${after.changed} Phren iPhone key(s); other keys were preserved.`);
|
|
141
|
+
}
|
|
142
|
+
await atomic(path.join(root, "installed.json"), JSON.stringify({ version, previous: previous?.version === version ? previous.previous : previous?.version, node: process.execPath }, null, 2) + "\n");
|
|
143
|
+
console.log("Agent hooks installed. In Codex, review the new Phren entries in /hooks. Existing agents may need to resume before new hooks load.");
|
|
144
|
+
console.log(`Phren Hook ${version} installed${noService ? " (service not started)" : " and running"}. Run phren bridge doctor.`);
|
|
145
|
+
}
|
|
146
|
+
catch (error) {
|
|
147
|
+
await restoreAgentHooks(hookEdits);
|
|
148
|
+
if (!noService)
|
|
149
|
+
await stopService();
|
|
150
|
+
if (previous?.version) {
|
|
151
|
+
if (previous.version === version && previousBundle) {
|
|
152
|
+
await writeFile(stagedBundle, previousBundle);
|
|
153
|
+
await rename(stagedBundle, installedBundle);
|
|
154
|
+
}
|
|
155
|
+
await activate(previous.version);
|
|
156
|
+
if (!noService)
|
|
157
|
+
await startService();
|
|
158
|
+
}
|
|
159
|
+
throw error;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
export async function uninstall() {
|
|
163
|
+
await stopService();
|
|
164
|
+
if (process.platform === "darwin")
|
|
165
|
+
await unlink(path.join(homedir(), "Library/LaunchAgents", `${label}.plist`)).catch(() => { });
|
|
166
|
+
else {
|
|
167
|
+
await exec("systemctl", ["--user", "disable", unit]).catch(() => { });
|
|
168
|
+
await unlink(path.join(homedir(), ".config/systemd/user", unit)).catch(() => { });
|
|
169
|
+
await exec("systemctl", ["--user", "daemon-reload"]).catch(() => { });
|
|
170
|
+
}
|
|
171
|
+
await applyAgentHooks(await planAgentHooks(path.join(bridgeRoot(), "current/bridge-hook.mjs"), true));
|
|
172
|
+
// Preserve journal, settings, uploaded images, rollback version and SSH backups.
|
|
173
|
+
console.log("Phren Hook stopped and its background service removed. Remove phren-iphone keys from authorized_keys to revoke iPhone access. Local data remains in " + bridgeRoot());
|
|
174
|
+
}
|
|
175
|
+
async function missingFile(operation) {
|
|
176
|
+
try {
|
|
177
|
+
return await operation;
|
|
178
|
+
}
|
|
179
|
+
catch (error) {
|
|
180
|
+
if (error.code === "ENOENT")
|
|
181
|
+
return undefined;
|
|
182
|
+
throw error;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
export async function planAgentHooks(program, remove = false) {
|
|
186
|
+
const edits = [];
|
|
187
|
+
for (const [source, file] of [
|
|
188
|
+
["codex", path.join(process.env.CODEX_HOME || path.join(homedir(), ".codex"), "hooks.json")],
|
|
189
|
+
["claude", path.join(process.env.CLAUDE_CONFIG_DIR || path.join(homedir(), ".claude"), "settings.json")],
|
|
190
|
+
["copilot", path.join(process.env.COPILOT_HOME || path.join(homedir(), ".copilot"), "hooks/phren.json")],
|
|
191
|
+
]) {
|
|
192
|
+
const metadata = await missingFile(lstat(file));
|
|
193
|
+
if (metadata && (!metadata.isFile() || metadata.isSymbolicLink() || metadata.size > 2_097_152)) {
|
|
194
|
+
throw new Error(`Agent settings require a manual update: ${file}`);
|
|
195
|
+
}
|
|
196
|
+
const before = await missingFile(readFile(file, "utf8"));
|
|
197
|
+
if (remove && before === undefined)
|
|
198
|
+
continue;
|
|
199
|
+
const parsed = before === undefined ? {} : JSON.parse(before);
|
|
200
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
201
|
+
throw new Error(`Invalid agent settings: ${file}`);
|
|
202
|
+
const config = object(parsed);
|
|
203
|
+
if (config.hooks !== undefined && (!config.hooks || typeof config.hooks !== "object" || Array.isArray(config.hooks)))
|
|
204
|
+
throw new Error(`Invalid hook configuration: ${file}`);
|
|
205
|
+
const hooks = object(config.hooks);
|
|
206
|
+
const command = `${quote(process.execPath)} ${quote(program)} hook ${source}`;
|
|
207
|
+
const ownHook = (entry) => typeof entry === "string" && entry.endsWith(` ${quote(program)} hook ${source}`);
|
|
208
|
+
for (const event of ["SessionStart", "UserPromptSubmit", "Stop", "PermissionRequest"]) {
|
|
209
|
+
if (hooks[event] !== undefined && (!Array.isArray(hooks[event]) || hooks[event].some(v => !v || typeof v !== "object" || Array.isArray(v))))
|
|
210
|
+
throw new Error(`Invalid ${event} hooks: ${file}`);
|
|
211
|
+
if (source !== "copilot" && objects(hooks[event]).some(g => !Array.isArray(g.hooks)))
|
|
212
|
+
throw new Error(`Invalid ${event} hook group: ${file}`);
|
|
213
|
+
}
|
|
214
|
+
if (source === "copilot") {
|
|
215
|
+
config.version = 1;
|
|
216
|
+
for (const event of ["SessionStart", "UserPromptSubmit"]) {
|
|
217
|
+
const entries = objects(hooks[event]).filter(h => !ownHook(h.bash) && !ownHook(h.command));
|
|
218
|
+
hooks[event] = remove ? entries : [...entries, { type: "command", bash: command, timeoutSec: 3 }];
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
else {
|
|
222
|
+
for (const event of ["SessionStart", "UserPromptSubmit", "Stop", "PermissionRequest"]) {
|
|
223
|
+
const groups = objects(hooks[event]).map(group => ({ ...group, hooks: objects(group.hooks).filter(h => !ownHook(h.command)) })).filter(group => group.hooks.length);
|
|
224
|
+
hooks[event] = remove ? groups : [...groups, { hooks: [{ type: "command", command, timeout: event === "PermissionRequest" ? 60 : 3 }] }];
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
config.hooks = hooks;
|
|
228
|
+
const after = JSON.stringify(config, null, 2) + "\n";
|
|
229
|
+
if (after === before)
|
|
230
|
+
continue;
|
|
231
|
+
edits.push({ file, before, after });
|
|
232
|
+
}
|
|
233
|
+
return edits;
|
|
234
|
+
}
|
|
235
|
+
async function applyAgentHooks(edits) {
|
|
236
|
+
for (const { file, before, after } of edits) {
|
|
237
|
+
await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
238
|
+
if (await missingFile(readFile(file, "utf8")) !== before)
|
|
239
|
+
throw new Error("Agent settings changed during installation. Run install again.");
|
|
240
|
+
if (before !== undefined)
|
|
241
|
+
await copyFile(file, file + `.phren-hook-${Date.now()}.bak`);
|
|
242
|
+
await atomic(file, after);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
async function restoreAgentHooks(edits) {
|
|
246
|
+
for (const { file, before, after } of edits) {
|
|
247
|
+
// A concurrent user edit always wins over rollback.
|
|
248
|
+
if (await missingFile(readFile(file, "utf8")) !== after)
|
|
249
|
+
continue;
|
|
250
|
+
if (before === undefined)
|
|
251
|
+
await unlink(file);
|
|
252
|
+
else
|
|
253
|
+
await atomic(file, before);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
export async function rollback() {
|
|
257
|
+
const config = JSON.parse(await readFile(path.join(bridgeRoot(), "installed.json"), "utf8"));
|
|
258
|
+
if (!config.previous || !/^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(config.previous))
|
|
259
|
+
throw new Error("No previous helper version is available.");
|
|
260
|
+
await stopService();
|
|
261
|
+
await activate(config.previous);
|
|
262
|
+
await startService();
|
|
263
|
+
await atomic(path.join(bridgeRoot(), "installed.json"), JSON.stringify({ version: config.previous, previous: config.version }) + "\n");
|
|
264
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { type Json } from "./protocol.js";
|
|
2
|
+
export declare function repositoryDiff(cwd: string): Promise<Json>;
|
|
3
|
+
export interface LocalServer {
|
|
4
|
+
name: string;
|
|
5
|
+
port: number;
|
|
6
|
+
origin: string;
|
|
7
|
+
process?: string;
|
|
8
|
+
pid?: number;
|
|
9
|
+
}
|
|
10
|
+
export declare function webServers(): Promise<LocalServer[]>;
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { promisify } from "node:util";
|
|
3
|
+
import { request } from "node:http";
|
|
4
|
+
import { userInfo } from "node:os";
|
|
5
|
+
import { BridgeError } from "./protocol.js";
|
|
6
|
+
const exec = promisify(execFile);
|
|
7
|
+
export async function repositoryDiff(cwd) {
|
|
8
|
+
const git = async (...args) => (await exec("git", ["-C", cwd, "--no-pager", ...args], {
|
|
9
|
+
timeout: 10_000, maxBuffer: 4_194_304, env: { ...process.env, GIT_OPTIONAL_LOCKS: "0", GIT_CONFIG_NOSYSTEM: "1" },
|
|
10
|
+
})).stdout;
|
|
11
|
+
let root;
|
|
12
|
+
try {
|
|
13
|
+
root = (await git("rev-parse", "--show-toplevel")).trim();
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
throw new BridgeError(409, "This pane is not in a Git repository.");
|
|
17
|
+
}
|
|
18
|
+
const branch = (await git("branch", "--show-current")).trim();
|
|
19
|
+
const status = (await git("status", "--porcelain=v1", "-z", "--untracked-files=normal")).split("\0");
|
|
20
|
+
const files = [];
|
|
21
|
+
for (let index = 0; index < status.length && files.length < 500; index++) {
|
|
22
|
+
const record = status[index];
|
|
23
|
+
if (!record)
|
|
24
|
+
continue;
|
|
25
|
+
const code = record.slice(0, 2), file = record.slice(3);
|
|
26
|
+
if (/[RC]/.test(code))
|
|
27
|
+
index++; // porcelain -z carries a second pathname.
|
|
28
|
+
const sections = [];
|
|
29
|
+
for (const [kind, staged] of [["staged", true], ["unstaged", false]]) {
|
|
30
|
+
if (code === "??")
|
|
31
|
+
continue;
|
|
32
|
+
const patch = await git("diff", "--no-ext-diff", "--no-textconv", ...(staged ? ["--cached"] : []), "--", file);
|
|
33
|
+
if (patch)
|
|
34
|
+
sections.push({ id: `${kind}:${file}`, kind, binary: patch.includes("Binary files"), loadState: "loaded", patch });
|
|
35
|
+
}
|
|
36
|
+
files.push({ path: file, status: code, sections });
|
|
37
|
+
}
|
|
38
|
+
return { branch, root, launchPath: cwd, files };
|
|
39
|
+
}
|
|
40
|
+
function probe(port, host) {
|
|
41
|
+
return new Promise(resolve => {
|
|
42
|
+
let settled = false;
|
|
43
|
+
const finish = (value) => { if (!settled) {
|
|
44
|
+
settled = true;
|
|
45
|
+
resolve(value);
|
|
46
|
+
} };
|
|
47
|
+
const req = request({ hostname: host, port, path: "/", method: "GET", timeout: 1200, headers: { Host: `localhost:${port}` } }, res => {
|
|
48
|
+
let body = "";
|
|
49
|
+
res.on("data", data => { body += data.toString(); if (body.length > 32_768)
|
|
50
|
+
res.destroy(); });
|
|
51
|
+
const end = () => finish(/<title[^>]*>([^<]{1,300})<\/title>/i.exec(body)?.[1]?.trim() || `Web server on port ${port}`);
|
|
52
|
+
res.on("end", end);
|
|
53
|
+
res.on("close", end);
|
|
54
|
+
res.on("error", () => finish(null));
|
|
55
|
+
});
|
|
56
|
+
req.on("error", () => finish(null));
|
|
57
|
+
req.on("timeout", () => { req.destroy(); finish(null); });
|
|
58
|
+
req.end();
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
export async function webServers() {
|
|
62
|
+
const result = await exec(process.platform === "darwin" ? "/usr/sbin/lsof" : "lsof", ["-nP", "-a", "-u", userInfo().username, "-iTCP", "-sTCP:LISTEN", "-Fpcn"], { timeout: 4000, maxBuffer: 1_048_576 }).catch(() => ({ stdout: "" }));
|
|
63
|
+
let pid, processName;
|
|
64
|
+
const ports = new Map();
|
|
65
|
+
for (const line of result.stdout.split("\n")) {
|
|
66
|
+
if (line.startsWith("p"))
|
|
67
|
+
pid = Number(line.slice(1));
|
|
68
|
+
if (line.startsWith("c"))
|
|
69
|
+
processName = line.slice(1);
|
|
70
|
+
if (!line.startsWith("n"))
|
|
71
|
+
continue;
|
|
72
|
+
const match = /^(?:n)(\*|127\.0\.0\.1|localhost|0\.0\.0\.0|\[::\]|\[::1\]):(\d+)$/.exec(line);
|
|
73
|
+
if (!match)
|
|
74
|
+
continue;
|
|
75
|
+
const port = Number(match[2]);
|
|
76
|
+
const host = match[1].includes(":") ? "[::1]" : "127.0.0.1";
|
|
77
|
+
ports.set(`${host}:${port}`, { name: "", port, origin: `http://${host}:${port}`, process: processName, pid });
|
|
78
|
+
}
|
|
79
|
+
const candidates = [...ports.values()].slice(0, 64);
|
|
80
|
+
const found = [];
|
|
81
|
+
for (let i = 0; i < candidates.length; i += 8) {
|
|
82
|
+
await Promise.all(candidates.slice(i, i + 8).map(async (server) => {
|
|
83
|
+
const name = await probe(server.port, server.origin.includes("[::1]") ? "::1" : "127.0.0.1");
|
|
84
|
+
if (name !== null)
|
|
85
|
+
found.push({ ...server, name });
|
|
86
|
+
}));
|
|
87
|
+
}
|
|
88
|
+
return found.sort((a, b) => a.port - b.port);
|
|
89
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
export declare const PROTOCOL = 1;
|
|
3
|
+
export declare const MAX_FRAME: number;
|
|
4
|
+
export declare const id: z.ZodString;
|
|
5
|
+
export declare const serverName: z.ZodString;
|
|
6
|
+
export declare const provider: z.ZodEnum<{
|
|
7
|
+
claude: "claude";
|
|
8
|
+
codex: "codex";
|
|
9
|
+
copilot: "copilot";
|
|
10
|
+
}>;
|
|
11
|
+
export type Provider = z.infer<typeof provider>;
|
|
12
|
+
export declare const targetSchema: z.ZodObject<{
|
|
13
|
+
server: z.ZodString;
|
|
14
|
+
workspace: z.ZodString;
|
|
15
|
+
tab: z.ZodString;
|
|
16
|
+
pane: z.ZodString;
|
|
17
|
+
source: z.ZodEnum<{
|
|
18
|
+
claude: "claude";
|
|
19
|
+
codex: "codex";
|
|
20
|
+
copilot: "copilot";
|
|
21
|
+
}>;
|
|
22
|
+
session: z.ZodString;
|
|
23
|
+
}, z.core.$strip>;
|
|
24
|
+
export type Target = z.infer<typeof targetSchema>;
|
|
25
|
+
export type Json = Record<string, unknown>;
|
|
26
|
+
export declare function object(value: unknown): Json;
|
|
27
|
+
export declare function objects(value: unknown): Json[];
|
|
28
|
+
export declare function bridgeRoot(): string;
|
|
29
|
+
export declare function socketPath(): string;
|
|
30
|
+
export declare class BridgeError extends Error {
|
|
31
|
+
status: number;
|
|
32
|
+
constructor(status: number, message: string);
|
|
33
|
+
}
|
|
34
|
+
export declare const requestID: () => `${string}-${string}-${string}-${string}-${string}`;
|
|
35
|
+
export declare function targetFromURL(url: URL): Target;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
export const PROTOCOL = 1;
|
|
6
|
+
export const MAX_FRAME = 8 * 1024 * 1024;
|
|
7
|
+
export const id = z.string().regex(/^[A-Za-z0-9_%:.-]{1,200}$/);
|
|
8
|
+
export const serverName = z.string().regex(/^[A-Za-z0-9_.-]{1,100}$/);
|
|
9
|
+
export const provider = z.enum(["codex", "claude", "copilot"]);
|
|
10
|
+
export const targetSchema = z.object({
|
|
11
|
+
server: serverName,
|
|
12
|
+
workspace: id,
|
|
13
|
+
tab: id,
|
|
14
|
+
pane: id,
|
|
15
|
+
source: provider,
|
|
16
|
+
session: z.string().uuid(),
|
|
17
|
+
});
|
|
18
|
+
export function object(value) {
|
|
19
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
20
|
+
}
|
|
21
|
+
export function objects(value) { return Array.isArray(value) ? value.map(object) : []; }
|
|
22
|
+
export function bridgeRoot() { return process.env.PHREN_BRIDGE_HOME || path.join(homedir(), ".local/share/phren/bridge"); }
|
|
23
|
+
export function socketPath() { return path.join(bridgeRoot(), "hook.sock"); }
|
|
24
|
+
export class BridgeError extends Error {
|
|
25
|
+
status;
|
|
26
|
+
constructor(status, message) {
|
|
27
|
+
super(message);
|
|
28
|
+
this.status = status;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
export const requestID = () => randomUUID();
|
|
32
|
+
export function targetFromURL(url) {
|
|
33
|
+
return targetSchema.parse(Object.fromEntries(["server", "workspace", "tab", "pane", "source", "session"].map(k => [k, url.searchParams.get(k)])));
|
|
34
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export declare const capabilities: {
|
|
2
|
+
transcript: boolean;
|
|
3
|
+
progress: boolean;
|
|
4
|
+
images: boolean;
|
|
5
|
+
prompt: boolean;
|
|
6
|
+
stop: boolean;
|
|
7
|
+
terminal: string;
|
|
8
|
+
herdr: boolean;
|
|
9
|
+
diff: boolean;
|
|
10
|
+
webServers: boolean;
|
|
11
|
+
activity: boolean;
|
|
12
|
+
approvals: boolean;
|
|
13
|
+
questions: boolean;
|
|
14
|
+
providers: string[];
|
|
15
|
+
};
|
|
16
|
+
export declare function serve(version: string): Promise<void>;
|