@phren/cli 0.3.7 → 0.3.8
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/dist/bridge/agent-hooks.js +25 -5
- package/dist/bridge/codex-daemon.d.ts +59 -0
- package/dist/bridge/codex-daemon.js +194 -0
- package/dist/bridge/herdr.d.ts +4 -0
- package/dist/bridge/herdr.js +75 -3
- package/dist/bridge/terminal-tmux.d.ts +5 -3
- package/dist/bridge/terminal-tmux.js +5 -4
- package/dist/bridge-hook.mjs +868 -652
- package/package.json +1 -1
package/dist/bridge-hook.mjs
CHANGED
|
@@ -268,10 +268,10 @@ function mergeDefs(...defs) {
|
|
|
268
268
|
function cloneDef(schema) {
|
|
269
269
|
return mergeDefs(schema._zod.def);
|
|
270
270
|
}
|
|
271
|
-
function getElementAtPath(obj,
|
|
272
|
-
if (!
|
|
271
|
+
function getElementAtPath(obj, path85) {
|
|
272
|
+
if (!path85)
|
|
273
273
|
return obj;
|
|
274
|
-
return
|
|
274
|
+
return path85.reduce((acc, key2) => acc?.[key2], obj);
|
|
275
275
|
}
|
|
276
276
|
function promiseAllObject(promisesObj) {
|
|
277
277
|
const keys = Object.keys(promisesObj);
|
|
@@ -530,11 +530,11 @@ function explicitlyAborted(x, startIndex = 0) {
|
|
|
530
530
|
}
|
|
531
531
|
return false;
|
|
532
532
|
}
|
|
533
|
-
function prefixIssues(
|
|
533
|
+
function prefixIssues(path85, issues) {
|
|
534
534
|
return issues.map((iss) => {
|
|
535
535
|
var _a3;
|
|
536
536
|
(_a3 = iss).path ?? (_a3.path = []);
|
|
537
|
-
iss.path.unshift(
|
|
537
|
+
iss.path.unshift(path85);
|
|
538
538
|
return iss;
|
|
539
539
|
});
|
|
540
540
|
}
|
|
@@ -675,9 +675,9 @@ function hexToUint8Array(hex3) {
|
|
|
675
675
|
function uint8ArrayToHex(bytes) {
|
|
676
676
|
return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
677
677
|
}
|
|
678
|
-
function members(proto,
|
|
679
|
-
for (const key2 in
|
|
680
|
-
const desc = Object.getOwnPropertyDescriptor(
|
|
678
|
+
function members(proto, table2) {
|
|
679
|
+
for (const key2 in table2) {
|
|
680
|
+
const desc = Object.getOwnPropertyDescriptor(table2, key2);
|
|
681
681
|
if (desc.get)
|
|
682
682
|
Object.defineProperty(proto, key2, { ...desc, enumerable: false });
|
|
683
683
|
else
|
|
@@ -692,10 +692,10 @@ function hide(inst, key2, value2) {
|
|
|
692
692
|
return own(inst, key2, value2, false);
|
|
693
693
|
}
|
|
694
694
|
// @__NO_SIDE_EFFECTS__
|
|
695
|
-
function derived(computes,
|
|
695
|
+
function derived(computes, table2) {
|
|
696
696
|
for (const key2 in computes) {
|
|
697
697
|
const compute = computes[key2];
|
|
698
|
-
Object.defineProperty(
|
|
698
|
+
Object.defineProperty(table2, key2, {
|
|
699
699
|
configurable: true,
|
|
700
700
|
enumerable: true,
|
|
701
701
|
get() {
|
|
@@ -706,7 +706,7 @@ function derived(computes, table) {
|
|
|
706
706
|
}
|
|
707
707
|
});
|
|
708
708
|
}
|
|
709
|
-
return
|
|
709
|
+
return table2;
|
|
710
710
|
}
|
|
711
711
|
function defineBound(proto, key2, fn) {
|
|
712
712
|
Object.defineProperty(proto, key2, {
|
|
@@ -1055,16 +1055,16 @@ function flattenError(error62, mapper = (issue2) => issue2.message) {
|
|
|
1055
1055
|
}
|
|
1056
1056
|
function formatError(error62, mapper = (issue2) => issue2.message) {
|
|
1057
1057
|
const fieldErrors = { _errors: [] };
|
|
1058
|
-
const processError = (error63,
|
|
1058
|
+
const processError = (error63, path85 = []) => {
|
|
1059
1059
|
for (const issue2 of error63.issues) {
|
|
1060
1060
|
if (issue2.code === "invalid_union" && issue2.errors.length) {
|
|
1061
|
-
issue2.errors.map((issues) => processError({ issues }, [...
|
|
1061
|
+
issue2.errors.map((issues) => processError({ issues }, [...path85, ...issue2.path]));
|
|
1062
1062
|
} else if (issue2.code === "invalid_key") {
|
|
1063
|
-
processError({ issues: issue2.issues }, [...
|
|
1063
|
+
processError({ issues: issue2.issues }, [...path85, ...issue2.path]);
|
|
1064
1064
|
} else if (issue2.code === "invalid_element") {
|
|
1065
|
-
processError({ issues: issue2.issues }, [...
|
|
1065
|
+
processError({ issues: issue2.issues }, [...path85, ...issue2.path]);
|
|
1066
1066
|
} else {
|
|
1067
|
-
const fullpath = [...
|
|
1067
|
+
const fullpath = [...path85, ...issue2.path];
|
|
1068
1068
|
if (fullpath.length === 0) {
|
|
1069
1069
|
fieldErrors._errors.push(mapper(issue2));
|
|
1070
1070
|
} else {
|
|
@@ -1103,17 +1103,17 @@ function formatError(error62, mapper = (issue2) => issue2.message) {
|
|
|
1103
1103
|
}
|
|
1104
1104
|
function treeifyError(error62, mapper = (issue2) => issue2.message) {
|
|
1105
1105
|
const result = { errors: [] };
|
|
1106
|
-
const processError = (error63,
|
|
1106
|
+
const processError = (error63, path85 = []) => {
|
|
1107
1107
|
var _a3;
|
|
1108
1108
|
for (const issue2 of error63.issues) {
|
|
1109
1109
|
if (issue2.code === "invalid_union" && issue2.errors.length) {
|
|
1110
|
-
issue2.errors.map((issues) => processError({ issues }, [...
|
|
1110
|
+
issue2.errors.map((issues) => processError({ issues }, [...path85, ...issue2.path]));
|
|
1111
1111
|
} else if (issue2.code === "invalid_key") {
|
|
1112
|
-
processError({ issues: issue2.issues }, [...
|
|
1112
|
+
processError({ issues: issue2.issues }, [...path85, ...issue2.path]);
|
|
1113
1113
|
} else if (issue2.code === "invalid_element") {
|
|
1114
|
-
processError({ issues: issue2.issues }, [...
|
|
1114
|
+
processError({ issues: issue2.issues }, [...path85, ...issue2.path]);
|
|
1115
1115
|
} else {
|
|
1116
|
-
const fullpath = [...
|
|
1116
|
+
const fullpath = [...path85, ...issue2.path];
|
|
1117
1117
|
if (fullpath.length === 0) {
|
|
1118
1118
|
result.errors.push(mapper(issue2));
|
|
1119
1119
|
continue;
|
|
@@ -1152,8 +1152,8 @@ function treeifyError(error62, mapper = (issue2) => issue2.message) {
|
|
|
1152
1152
|
}
|
|
1153
1153
|
function toDotPath(_path) {
|
|
1154
1154
|
const segs = [];
|
|
1155
|
-
const
|
|
1156
|
-
for (const seg of
|
|
1155
|
+
const path85 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
|
|
1156
|
+
for (const seg of path85) {
|
|
1157
1157
|
if (typeof seg === "number")
|
|
1158
1158
|
segs.push(`[${seg}]`);
|
|
1159
1159
|
else if (typeof seg === "symbol")
|
|
@@ -19149,13 +19149,13 @@ function resolveRef(ref, ctx) {
|
|
|
19149
19149
|
if (!ref.startsWith("#")) {
|
|
19150
19150
|
throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
|
|
19151
19151
|
}
|
|
19152
|
-
const
|
|
19153
|
-
if (
|
|
19152
|
+
const path85 = ref.slice(1).split("/").filter(Boolean);
|
|
19153
|
+
if (path85.length === 0) {
|
|
19154
19154
|
return ctx.rootSchema;
|
|
19155
19155
|
}
|
|
19156
19156
|
const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
|
|
19157
|
-
if (
|
|
19158
|
-
const key2 =
|
|
19157
|
+
if (path85[0] === defsKey) {
|
|
19158
|
+
const key2 = path85[1] === void 0 ? void 0 : decodeJSONPointerSegment(path85[1]);
|
|
19159
19159
|
if (!key2 || !ctx.defs[key2]) {
|
|
19160
19160
|
throw new Error(`Reference not found: ${ref}`);
|
|
19161
19161
|
}
|
|
@@ -21380,10 +21380,10 @@ async function repositoryOf(target, cwd, home = homeDir(), signal) {
|
|
|
21380
21380
|
if (parent === existing) return void 0;
|
|
21381
21381
|
existing = parent;
|
|
21382
21382
|
}
|
|
21383
|
-
const
|
|
21383
|
+
const real2 = await realpath(existing);
|
|
21384
21384
|
home = await realpath(home);
|
|
21385
|
-
if (
|
|
21386
|
-
const dir = (await stat2(
|
|
21385
|
+
if (real2 !== home && !real2.startsWith(home + path5.sep)) return void 0;
|
|
21386
|
+
const dir = (await stat2(real2)).isDirectory() ? real2 : path5.dirname(real2);
|
|
21387
21387
|
try {
|
|
21388
21388
|
return await realpath((await git(dir, ["rev-parse", "--show-toplevel"], {}, signal)).trim());
|
|
21389
21389
|
} catch {
|
|
@@ -22137,9 +22137,9 @@ function resolveString(expression, source) {
|
|
|
22137
22137
|
const declaration = new RegExp(`\\b(?:const|let|var)\\s+${identifier}\\s*=\\s*("(?:\\\\.|[^"\\\\])*"|'(?:\\\\.|[^'\\\\])*'|\`(?:\\\\.|[^\`\\\\])*\`)`).exec(source);
|
|
22138
22138
|
return declaration ? unescapeJs(declaration[1].slice(1, -1)) : void 0;
|
|
22139
22139
|
}
|
|
22140
|
-
function callArguments(source,
|
|
22140
|
+
function callArguments(source, open17) {
|
|
22141
22141
|
let depth = 0, quote3 = "";
|
|
22142
|
-
for (let index2 =
|
|
22142
|
+
for (let index2 = open17; index2 < source.length; index2++) {
|
|
22143
22143
|
const character = source[index2];
|
|
22144
22144
|
if (quote3) {
|
|
22145
22145
|
if (character === "\\") index2++;
|
|
@@ -22152,7 +22152,7 @@ function callArguments(source, open16) {
|
|
|
22152
22152
|
}
|
|
22153
22153
|
if (character === "(" || character === "{" || character === "[") depth++;
|
|
22154
22154
|
else if (character === ")" || character === "}" || character === "]") {
|
|
22155
|
-
if (--depth === 0) return source.slice(
|
|
22155
|
+
if (--depth === 0) return source.slice(open17 + 1, index2);
|
|
22156
22156
|
}
|
|
22157
22157
|
}
|
|
22158
22158
|
return void 0;
|
|
@@ -26478,8 +26478,8 @@ function appendAuditLog(phrenPath, event, details) {
|
|
|
26478
26478
|
fs3.mkdirSync(path11.dirname(logPath), { recursive: true });
|
|
26479
26479
|
withFileLock(logPath, () => {
|
|
26480
26480
|
fs3.appendFileSync(logPath, line);
|
|
26481
|
-
const
|
|
26482
|
-
if (
|
|
26481
|
+
const stat27 = fs3.statSync(logPath);
|
|
26482
|
+
if (stat27.size > 1e6) {
|
|
26483
26483
|
const content = fs3.readFileSync(logPath, "utf8");
|
|
26484
26484
|
const lines = content.split("\n");
|
|
26485
26485
|
fs3.writeFileSync(logPath, lines.slice(-MAX_LOG_LINES).join("\n") + "\n");
|
|
@@ -26568,8 +26568,8 @@ ${Date.now()}`, { flag: "wx" });
|
|
|
26568
26568
|
} catch (err) {
|
|
26569
26569
|
logger.debug("acquireFileLock", `lockWrite: ${errorMessage(err)}`);
|
|
26570
26570
|
try {
|
|
26571
|
-
const
|
|
26572
|
-
if (Date.now() -
|
|
26571
|
+
const stat27 = fs5.statSync(lockPath);
|
|
26572
|
+
if (Date.now() - stat27.mtimeMs > staleThreshold) {
|
|
26573
26573
|
let ownerAlive = false;
|
|
26574
26574
|
try {
|
|
26575
26575
|
const content = fs5.readFileSync(lockPath, "utf-8");
|
|
@@ -28317,7 +28317,7 @@ var init_package_metadata = __esm({
|
|
|
28317
28317
|
__dirname = path24.dirname(fileURLToPath2(import.meta.url));
|
|
28318
28318
|
ROOT = path24.join(__dirname, "..");
|
|
28319
28319
|
PACKAGE_JSON_PATH = path24.join(ROOT, "package.json");
|
|
28320
|
-
BUNDLED_VERSION = true ? "0.3.
|
|
28320
|
+
BUNDLED_VERSION = true ? "0.3.8" : "0.0.0";
|
|
28321
28321
|
PACKAGE_JSON = readPackageJson();
|
|
28322
28322
|
PACKAGE_NAME = PACKAGE_JSON.name || "phren";
|
|
28323
28323
|
VERSION = PACKAGE_JSON.version || BUNDLED_VERSION;
|
|
@@ -31513,7 +31513,7 @@ var require_stream = __commonJS({
|
|
|
31513
31513
|
};
|
|
31514
31514
|
duplex._final = function(callback) {
|
|
31515
31515
|
if (ws.readyState === ws.CONNECTING) {
|
|
31516
|
-
ws.once("open", function
|
|
31516
|
+
ws.once("open", function open17() {
|
|
31517
31517
|
duplex._final(callback);
|
|
31518
31518
|
});
|
|
31519
31519
|
return;
|
|
@@ -31534,7 +31534,7 @@ var require_stream = __commonJS({
|
|
|
31534
31534
|
};
|
|
31535
31535
|
duplex._write = function(chunk, encoding, callback) {
|
|
31536
31536
|
if (ws.readyState === ws.CONNECTING) {
|
|
31537
|
-
ws.once("open", function
|
|
31537
|
+
ws.once("open", function open17() {
|
|
31538
31538
|
duplex._write(chunk, encoding, callback);
|
|
31539
31539
|
});
|
|
31540
31540
|
return;
|
|
@@ -32161,6 +32161,162 @@ var init_tab_activity = __esm({
|
|
|
32161
32161
|
}
|
|
32162
32162
|
});
|
|
32163
32163
|
|
|
32164
|
+
// src/bridge/codex-daemon.ts
|
|
32165
|
+
import { execFile as execFile3 } from "node:child_process";
|
|
32166
|
+
import { open as open5, readdir as readdir6, realpath as realpath6, stat as stat8 } from "node:fs/promises";
|
|
32167
|
+
import path32 from "node:path";
|
|
32168
|
+
import { promisify as promisify3 } from "node:util";
|
|
32169
|
+
function parseElapsed(text4) {
|
|
32170
|
+
const match = /^(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)$/.exec(text4.trim());
|
|
32171
|
+
if (!match) return void 0;
|
|
32172
|
+
const [, days = "0", hours = "0", minutes, seconds] = match;
|
|
32173
|
+
return (((Number(days) * 24 + Number(hours)) * 60 + Number(minutes)) * 60 + Number(seconds)) * 1e3;
|
|
32174
|
+
}
|
|
32175
|
+
function processTable(now = Date.now()) {
|
|
32176
|
+
if (table && now - table.at < CACHE_MS) return table.rows;
|
|
32177
|
+
countIdentity("ps");
|
|
32178
|
+
const rows = exec3("ps", ["-Aww", "-o", "pid=,ppid=,etime=,command="], { timeout: 3e3, maxBuffer: 8388608 }).then(({ stdout }) => {
|
|
32179
|
+
const out = [];
|
|
32180
|
+
for (const line of String(stdout).split("\n")) {
|
|
32181
|
+
const match = /^\s*(\d+)\s+(\d+)\s+(\S+)\s+(.*)$/.exec(line);
|
|
32182
|
+
const elapsed = match ? parseElapsed(match[3]) : void 0;
|
|
32183
|
+
if (match && elapsed !== void 0) out.push({ pid: Number(match[1]), ppid: Number(match[2]), startedAt: now - elapsed, command: match[4].slice(0, 4096) });
|
|
32184
|
+
}
|
|
32185
|
+
return out;
|
|
32186
|
+
}, () => []);
|
|
32187
|
+
table = { at: now, rows };
|
|
32188
|
+
return rows;
|
|
32189
|
+
}
|
|
32190
|
+
function isCodexDaemon(command) {
|
|
32191
|
+
return DAEMON_COMMAND.test(command);
|
|
32192
|
+
}
|
|
32193
|
+
function startedAt(rows, pids) {
|
|
32194
|
+
const times = rows.filter((row) => pids.includes(row.pid)).map((row) => row.startedAt);
|
|
32195
|
+
return times.length ? Math.min(...times) : void 0;
|
|
32196
|
+
}
|
|
32197
|
+
async function underCodexDaemon(env = process.env, pid = process.pid) {
|
|
32198
|
+
if (env.CODEX_INTERNAL_APP_SERVER_REMOTE_CONTROL_DISABLED !== void 0) return true;
|
|
32199
|
+
if (process.platform === "win32") return false;
|
|
32200
|
+
const rows = await processTable(), byPid = new Map(rows.map((row) => [row.pid, row]));
|
|
32201
|
+
let current2 = byPid.get(pid)?.ppid ?? process.ppid;
|
|
32202
|
+
for (let depth = 0; depth < 8 && current2 > 1; depth++) {
|
|
32203
|
+
const row = byPid.get(current2);
|
|
32204
|
+
if (!row) return false;
|
|
32205
|
+
if (isCodexDaemon(row.command)) return true;
|
|
32206
|
+
current2 = row.ppid;
|
|
32207
|
+
}
|
|
32208
|
+
return false;
|
|
32209
|
+
}
|
|
32210
|
+
async function rolloutMeta(file2) {
|
|
32211
|
+
const handle = await open5(file2, "r").catch(() => void 0);
|
|
32212
|
+
if (!handle) return void 0;
|
|
32213
|
+
let text4;
|
|
32214
|
+
try {
|
|
32215
|
+
const { buffer, bytesRead } = await handle.read(Buffer.alloc(META_BYTES), 0, META_BYTES, 0);
|
|
32216
|
+
text4 = buffer.subarray(0, bytesRead).toString("utf8");
|
|
32217
|
+
} catch {
|
|
32218
|
+
return void 0;
|
|
32219
|
+
} finally {
|
|
32220
|
+
await handle.close();
|
|
32221
|
+
}
|
|
32222
|
+
const newline = text4.indexOf("\n");
|
|
32223
|
+
let payload;
|
|
32224
|
+
if (newline >= 0) {
|
|
32225
|
+
try {
|
|
32226
|
+
const raw = object2(JSON.parse(text4.slice(0, newline)));
|
|
32227
|
+
if (raw.type !== "session_meta") return void 0;
|
|
32228
|
+
payload = object2(raw.payload);
|
|
32229
|
+
} catch {
|
|
32230
|
+
}
|
|
32231
|
+
}
|
|
32232
|
+
if (!payload) {
|
|
32233
|
+
if (!text4.slice(0, 256).includes('"type":"session_meta"')) return void 0;
|
|
32234
|
+
payload = {};
|
|
32235
|
+
for (const key2 of ["id", "session_id", "timestamp", "cwd", "thread_source"]) {
|
|
32236
|
+
const match = new RegExp(`"${key2}":("(?:[^"\\\\]|\\\\.)*")`).exec(text4);
|
|
32237
|
+
if (match) try {
|
|
32238
|
+
payload[key2] = JSON.parse(match[1]);
|
|
32239
|
+
} catch {
|
|
32240
|
+
}
|
|
32241
|
+
}
|
|
32242
|
+
if (/"source":\{"subagent"/.test(text4)) payload.source = { subagent: true };
|
|
32243
|
+
}
|
|
32244
|
+
const id2 = String(payload.id ?? payload.session_id ?? ""), fromName = ROLLOUT.exec(file2)?.[1];
|
|
32245
|
+
const at = Date.parse(String(payload.timestamp ?? ""));
|
|
32246
|
+
if (!sessionId.safeParse(id2).success || fromName && fromName.toLowerCase() !== id2.toLowerCase() || typeof payload.cwd !== "string" || !path32.isAbsolute(payload.cwd) || !Number.isFinite(at)) return void 0;
|
|
32247
|
+
const subagent = !!object2(payload.source).subagent || typeof payload.thread_source === "string" && /sub.?agent/i.test(payload.thread_source);
|
|
32248
|
+
return { id: id2, cwd: payload.cwd, startedAt: at, subagent };
|
|
32249
|
+
}
|
|
32250
|
+
async function recentRollouts(now) {
|
|
32251
|
+
const files = [];
|
|
32252
|
+
for (const offset of [0, 1]) {
|
|
32253
|
+
const day = new Date(now - offset * 864e5);
|
|
32254
|
+
const folder = path32.join(codexHome(), "sessions", String(day.getFullYear()), String(day.getMonth() + 1).padStart(2, "0"), String(day.getDate()).padStart(2, "0"));
|
|
32255
|
+
const names = (await readdir6(folder).catch(() => [])).filter((name) => ROLLOUT.test(name)).sort().reverse();
|
|
32256
|
+
files.push(...names.slice(0, MAX_ROLLOUTS).map((name) => path32.join(folder, name)));
|
|
32257
|
+
}
|
|
32258
|
+
return files.slice(0, MAX_ROLLOUTS);
|
|
32259
|
+
}
|
|
32260
|
+
function daemonRollouts(openFiles, now = Date.now()) {
|
|
32261
|
+
if (rollouts && now - rollouts.at < CACHE_MS) return rollouts.value;
|
|
32262
|
+
const value2 = (async () => {
|
|
32263
|
+
const daemons = (await processTable(now)).filter((row) => isCodexDaemon(row.command)).map((row) => row.pid).slice(0, MAX_DAEMONS);
|
|
32264
|
+
if (!daemons.length) return [];
|
|
32265
|
+
countIdentity("codex-daemon");
|
|
32266
|
+
const held = (await openFiles(daemons).catch(() => [])).filter((file2) => ROLLOUT.test(file2)).slice(0, MAX_ROLLOUTS);
|
|
32267
|
+
const files = held.length ? held : await recentRollouts(now);
|
|
32268
|
+
const out = [];
|
|
32269
|
+
for (const file2 of files) {
|
|
32270
|
+
const meta3 = await rolloutMeta(file2);
|
|
32271
|
+
if (!meta3 || meta3.subagent) continue;
|
|
32272
|
+
const info = await stat8(file2).catch(() => void 0);
|
|
32273
|
+
out.push({ id: meta3.id, cwd: meta3.cwd, startedAt: meta3.startedAt, activeAt: info?.mtimeMs ?? meta3.startedAt, held: held.length > 0 });
|
|
32274
|
+
}
|
|
32275
|
+
return out;
|
|
32276
|
+
})().catch(() => []);
|
|
32277
|
+
rollouts = { at: now, value: value2 };
|
|
32278
|
+
return value2;
|
|
32279
|
+
}
|
|
32280
|
+
async function sameDirectory(a, b) {
|
|
32281
|
+
if (typeof a !== "string" || typeof b !== "string" || !path32.isAbsolute(a) || !path32.isAbsolute(b)) return false;
|
|
32282
|
+
return path32.resolve(a) === path32.resolve(b) || await real(a) === await real(b);
|
|
32283
|
+
}
|
|
32284
|
+
function assignDaemonConversation(here, self, claimed, rivals, now = Date.now()) {
|
|
32285
|
+
const open17 = here.filter((r) => !claimed.has(r.id) && r.startedAt <= now + 6e4);
|
|
32286
|
+
const after = (from) => open17.filter((r) => r.startedAt >= from - START_SLACK_MS);
|
|
32287
|
+
if (!rivals.length) {
|
|
32288
|
+
const pool = after(self.start);
|
|
32289
|
+
const held = pool.filter((r) => r.held);
|
|
32290
|
+
return (held.length ? held : pool).sort((a, b) => b.activeAt - a.activeAt)[0]?.id;
|
|
32291
|
+
}
|
|
32292
|
+
const order = [...rivals, self].sort((a, b) => b.start - a.start || (a.key < b.key ? 1 : a.key > b.key ? -1 : 0));
|
|
32293
|
+
const taken = /* @__PURE__ */ new Set();
|
|
32294
|
+
for (const pane of order) {
|
|
32295
|
+
const pick3 = after(pane.start).filter((r) => !taken.has(r.id)).sort((a, b) => a.startedAt - b.startedAt)[0];
|
|
32296
|
+
if (pane === self) return pick3?.id;
|
|
32297
|
+
if (pick3) taken.add(pick3.id);
|
|
32298
|
+
}
|
|
32299
|
+
return void 0;
|
|
32300
|
+
}
|
|
32301
|
+
var exec3, DAEMON_COMMAND, ROLLOUT, CACHE_MS, META_BYTES, MAX_ROLLOUTS, MAX_DAEMONS, START_SLACK_MS, table, rollouts, real;
|
|
32302
|
+
var init_codex_daemon = __esm({
|
|
32303
|
+
"src/bridge/codex-daemon.ts"() {
|
|
32304
|
+
"use strict";
|
|
32305
|
+
init_home_paths();
|
|
32306
|
+
init_metrics();
|
|
32307
|
+
init_protocol();
|
|
32308
|
+
exec3 = promisify3(execFile3);
|
|
32309
|
+
DAEMON_COMMAND = /(?:^|\/)codex\s+app-server(?:\s|$)/;
|
|
32310
|
+
ROLLOUT = /rollout-[^/]*-([a-f0-9-]{36})\.jsonl$/i;
|
|
32311
|
+
CACHE_MS = 2e3;
|
|
32312
|
+
META_BYTES = 65536;
|
|
32313
|
+
MAX_ROLLOUTS = 32;
|
|
32314
|
+
MAX_DAEMONS = 4;
|
|
32315
|
+
START_SLACK_MS = 5e3;
|
|
32316
|
+
real = async (dir) => realpath6(dir).catch(() => path32.resolve(dir));
|
|
32317
|
+
}
|
|
32318
|
+
});
|
|
32319
|
+
|
|
32164
32320
|
// src/bridge/terminal-herdr.ts
|
|
32165
32321
|
function herdrPanes(server, s) {
|
|
32166
32322
|
return objects(s.panes).filter((p) => typeof p.pane_id === "string" && typeof p.tab_id === "string" && typeof p.workspace_id === "string").map((p) => {
|
|
@@ -32241,14 +32397,14 @@ var init_terminal_herdr = __esm({
|
|
|
32241
32397
|
});
|
|
32242
32398
|
|
|
32243
32399
|
// src/bridge/harness-status.ts
|
|
32244
|
-
import { open as
|
|
32400
|
+
import { open as open6, stat as stat9 } from "node:fs/promises";
|
|
32245
32401
|
import { homedir as homedir7 } from "node:os";
|
|
32246
|
-
import
|
|
32402
|
+
import path33 from "node:path";
|
|
32247
32403
|
async function opencodeProcessStatus(pids, root = phrenStoreRoot()) {
|
|
32248
|
-
const folder =
|
|
32404
|
+
const folder = path33.join(root, ".runtime", "sessions");
|
|
32249
32405
|
let current2, latest = -Infinity;
|
|
32250
32406
|
for (const pid of pids.slice(0, 16)) {
|
|
32251
|
-
const file2 = await
|
|
32407
|
+
const file2 = await open6(path33.join(folder, `opencode-status-${pid}.json`), "r").catch(() => void 0);
|
|
32252
32408
|
if (!file2) continue;
|
|
32253
32409
|
try {
|
|
32254
32410
|
if ((await file2.stat()).size > 4096) continue;
|
|
@@ -32320,15 +32476,15 @@ function copilotStatusFromEvents(lines) {
|
|
|
32320
32476
|
}
|
|
32321
32477
|
return status;
|
|
32322
32478
|
}
|
|
32323
|
-
async function copilotProcessStatus(pids, home = process.env.COPILOT_HOME ||
|
|
32479
|
+
async function copilotProcessStatus(pids, home = process.env.COPILOT_HOME || path33.join(homedir7(), ".copilot")) {
|
|
32324
32480
|
const session = await copilotForegroundSession(pids, home);
|
|
32325
32481
|
if (!session) return void 0;
|
|
32326
|
-
const file2 =
|
|
32327
|
-
const info = await
|
|
32482
|
+
const file2 = path33.join(home, "session-state", session, "events.jsonl");
|
|
32483
|
+
const info = await stat9(file2).catch(() => void 0);
|
|
32328
32484
|
if (!info?.isFile()) return void 0;
|
|
32329
32485
|
const cached2 = copilotCache.get(file2);
|
|
32330
32486
|
if (cached2 && cached2.size === info.size && cached2.mtime === info.mtimeMs) return cached2.status;
|
|
32331
|
-
const handle = await
|
|
32487
|
+
const handle = await open6(file2, "r");
|
|
32332
32488
|
let text4;
|
|
32333
32489
|
try {
|
|
32334
32490
|
const length = Math.min(info.size, TAIL_BYTES);
|
|
@@ -32933,11 +33089,11 @@ __export(terminal_tmux_exports, {
|
|
|
32933
33089
|
tmuxTerminal: () => tmuxTerminal,
|
|
32934
33090
|
toTmuxId: () => toTmuxId
|
|
32935
33091
|
});
|
|
32936
|
-
import { execFile as
|
|
33092
|
+
import { execFile as execFile4 } from "node:child_process";
|
|
32937
33093
|
import { accessSync, constants, existsSync as existsSync14, statSync as statSync9 } from "node:fs";
|
|
32938
|
-
import { lstat as lstat5, readdir as
|
|
33094
|
+
import { lstat as lstat5, readdir as readdir7 } from "node:fs/promises";
|
|
32939
33095
|
import { hostname as hostname4, userInfo } from "node:os";
|
|
32940
|
-
import
|
|
33096
|
+
import path34 from "node:path";
|
|
32941
33097
|
function tmuxSocketName(server) {
|
|
32942
33098
|
const match = /^tmux(?:-([A-Za-z0-9_][A-Za-z0-9_.-]{0,63}))?$/.exec(server);
|
|
32943
33099
|
return match ? match[1] ?? "default" : void 0;
|
|
@@ -32949,11 +33105,11 @@ function tmuxServerName(socket) {
|
|
|
32949
33105
|
function tmuxBinary() {
|
|
32950
33106
|
if (process.env.PHREN_TMUX === "off") return void 0;
|
|
32951
33107
|
if (cachedBinary && Date.now() - cachedBinary.at < 6e4) return cachedBinary.value;
|
|
32952
|
-
const folders = [...(process.env.PATH ?? "").split(
|
|
33108
|
+
const folders = [...(process.env.PATH ?? "").split(path34.delimiter), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/home/linuxbrew/.linuxbrew/bin"];
|
|
32953
33109
|
let value2;
|
|
32954
33110
|
for (const folder of folders) {
|
|
32955
|
-
if (!folder || !
|
|
32956
|
-
const candidate =
|
|
33111
|
+
if (!folder || !path34.isAbsolute(folder)) continue;
|
|
33112
|
+
const candidate = path34.join(folder, "tmux");
|
|
32957
33113
|
try {
|
|
32958
33114
|
if (statSync9(candidate).isFile()) {
|
|
32959
33115
|
accessSync(candidate, constants.X_OK);
|
|
@@ -32980,8 +33136,8 @@ function tmuxError(stderr, error62) {
|
|
|
32980
33136
|
function tmuxSocketFolders(env = process.env) {
|
|
32981
33137
|
const uid = process.getuid?.();
|
|
32982
33138
|
if (uid === void 0) return [];
|
|
32983
|
-
const base = env.TMUX_TMPDIR &&
|
|
32984
|
-
return [.../* @__PURE__ */ new Set([
|
|
33139
|
+
const base = env.TMUX_TMPDIR && path34.isAbsolute(env.TMUX_TMPDIR) ? env.TMUX_TMPDIR : "/tmp";
|
|
33140
|
+
return [.../* @__PURE__ */ new Set([path34.join(base, `tmux-${uid}`), path34.join("/tmp", `tmux-${uid}`)])];
|
|
32985
33141
|
}
|
|
32986
33142
|
function socketFlags(socket) {
|
|
32987
33143
|
const file2 = socketPaths.get(socket);
|
|
@@ -32989,15 +33145,15 @@ function socketFlags(socket) {
|
|
|
32989
33145
|
}
|
|
32990
33146
|
async function tmuxSocketsIn(folder) {
|
|
32991
33147
|
const uid = process.getuid?.(), primary = tmuxSocketFolders()[0];
|
|
32992
|
-
const names = (await
|
|
33148
|
+
const names = (await readdir7(folder).catch(() => [])).slice(0, 256);
|
|
32993
33149
|
const found = [];
|
|
32994
33150
|
for (const name of names) {
|
|
32995
33151
|
if (found.length >= 32) break;
|
|
32996
33152
|
if (!tmuxServerName(name)) continue;
|
|
32997
|
-
const info = await lstat5(
|
|
33153
|
+
const info = await lstat5(path34.join(folder, name)).catch(() => void 0);
|
|
32998
33154
|
if (!info?.isSocket() || uid !== void 0 && info.uid !== uid) continue;
|
|
32999
33155
|
found.push(name);
|
|
33000
|
-
if (folder !== primary && !socketPaths.has(name) && !existsSync14(
|
|
33156
|
+
if (folder !== primary && !socketPaths.has(name) && !existsSync14(path34.join(primary ?? folder, name))) socketPaths.set(name, path34.join(folder, name));
|
|
33001
33157
|
}
|
|
33002
33158
|
return found;
|
|
33003
33159
|
}
|
|
@@ -33024,7 +33180,7 @@ function toTmuxId(value2, kind) {
|
|
|
33024
33180
|
}
|
|
33025
33181
|
function agentFromCommand(command) {
|
|
33026
33182
|
const words = command.trim().split(/\s+/).filter(Boolean).slice(0, 4);
|
|
33027
|
-
const [first, second] = words, base = (word) => word ?
|
|
33183
|
+
const [first, second] = words, base = (word) => word ? path34.basename(word) : "";
|
|
33028
33184
|
const program = /^(node|nodejs|bun|deno)$/.test(base(first)) && second ? second : first;
|
|
33029
33185
|
if (!program) return void 0;
|
|
33030
33186
|
const name = base(program);
|
|
@@ -33172,14 +33328,14 @@ async function requireDirectExec() {
|
|
|
33172
33328
|
if (!match || Number(match[1]) < 3) throw new BridgeError(409, "Phren needs tmux 3.0 or later to start agents. Update tmux on the computer.");
|
|
33173
33329
|
}
|
|
33174
33330
|
function loginShell() {
|
|
33175
|
-
const shell = process.env.SHELL &&
|
|
33331
|
+
const shell = process.env.SHELL && path34.isAbsolute(process.env.SHELL) ? process.env.SHELL : (() => {
|
|
33176
33332
|
try {
|
|
33177
33333
|
return userInfo().shell ?? "";
|
|
33178
33334
|
} catch {
|
|
33179
33335
|
return "";
|
|
33180
33336
|
}
|
|
33181
33337
|
})();
|
|
33182
|
-
return shell && /^(sh|bash|zsh|ksh|dash)$/.test(
|
|
33338
|
+
return shell && /^(sh|bash|zsh|ksh|dash)$/.test(path34.basename(shell)) && existsSync14(shell) ? shell : "/bin/sh";
|
|
33183
33339
|
}
|
|
33184
33340
|
function sessionName(label2, taken) {
|
|
33185
33341
|
const base = (label2 ?? "phren").replace(/[.:\x00-\x1f\x7f]/g, "_").trim().slice(0, 60) || "phren";
|
|
@@ -33196,9 +33352,9 @@ async function ownerServers() {
|
|
|
33196
33352
|
const running2 = await Promise.all(names.map((name) => tmuxTerminal.ping(name).then(() => true, () => false)));
|
|
33197
33353
|
return names.filter((_, index2) => running2[index2]);
|
|
33198
33354
|
}
|
|
33199
|
-
async function tmuxServers() {
|
|
33355
|
+
async function tmuxServers(options = {}) {
|
|
33200
33356
|
if (!deps.binary()) return [];
|
|
33201
|
-
return [...await ownerServers(), TMUX_HIDDEN].map((name) => ({ id: `tmux:${name}`, kind: "herdr", terminal: "tmux", session: name, running: true }));
|
|
33357
|
+
return [...await ownerServers(), ...options.hidden ?? true ? [TMUX_HIDDEN] : []].map((name) => ({ id: `tmux:${name}`, kind: "herdr", terminal: "tmux", session: name, running: true }));
|
|
33202
33358
|
}
|
|
33203
33359
|
async function tmuxHealth() {
|
|
33204
33360
|
if (process.env.PHREN_TMUX === "off") return { state: "off" };
|
|
@@ -33213,13 +33369,13 @@ async function tmuxHealth() {
|
|
|
33213
33369
|
}
|
|
33214
33370
|
async function tmuxPaneFromEnv(env = process.env) {
|
|
33215
33371
|
const socket = env.TMUX?.split(",")[0], pane = env.TMUX_PANE;
|
|
33216
|
-
if (!socket || !
|
|
33217
|
-
const server = tmuxServerName(
|
|
33372
|
+
if (!socket || !path34.isAbsolute(socket) || !pane || !fromTmuxId(pane)) return void 0;
|
|
33373
|
+
const server = tmuxServerName(path34.basename(socket));
|
|
33218
33374
|
if (!server) return void 0;
|
|
33219
33375
|
const primary = tmuxSocketFolders(env)[0];
|
|
33220
|
-
if (primary &&
|
|
33376
|
+
if (primary && path34.dirname(socket) !== primary && !socketPaths.has(path34.basename(socket))) socketPaths.set(path34.basename(socket), socket);
|
|
33221
33377
|
try {
|
|
33222
|
-
const [session, window2] = (await deps.run(
|
|
33378
|
+
const [session, window2] = (await deps.run(path34.basename(socket), ["display-message", "-p", "-t", pane, "#{session_id} #{window_id}"], { timeoutMs: 1500 })).trim().split(" ");
|
|
33223
33379
|
const workspace = fromTmuxId(session ?? ""), tab = fromTmuxId(window2 ?? "");
|
|
33224
33380
|
return workspace && tab ? { server, workspace, tab, pane: fromTmuxId(pane) } : void 0;
|
|
33225
33381
|
} catch {
|
|
@@ -33254,7 +33410,7 @@ var init_terminal_tmux = __esm({
|
|
|
33254
33410
|
reject(new BridgeError(503, "tmux is not installed on this computer."));
|
|
33255
33411
|
return;
|
|
33256
33412
|
}
|
|
33257
|
-
const child =
|
|
33413
|
+
const child = execFile4(
|
|
33258
33414
|
binary,
|
|
33259
33415
|
[...socketFlags(socket), ...args],
|
|
33260
33416
|
{ timeout: options.timeoutMs ?? 5e3, maxBuffer: 4194304, env: tmuxEnvironment(), signal: options.signal },
|
|
@@ -33267,7 +33423,7 @@ var init_terminal_tmux = __esm({
|
|
|
33267
33423
|
else child.stdin?.end();
|
|
33268
33424
|
}),
|
|
33269
33425
|
processes: () => new Promise((resolve11) => {
|
|
33270
|
-
|
|
33426
|
+
execFile4(
|
|
33271
33427
|
"ps",
|
|
33272
33428
|
["-A", "-o", "pid=,pgid=,tpgid=,tty=,args="],
|
|
33273
33429
|
{ timeout: 3e3, maxBuffer: 8388608, env: { ...process.env, LC_ALL: "C" } },
|
|
@@ -33280,7 +33436,7 @@ var init_terminal_tmux = __esm({
|
|
|
33280
33436
|
resolve11("");
|
|
33281
33437
|
return;
|
|
33282
33438
|
}
|
|
33283
|
-
|
|
33439
|
+
execFile4(binary, ["-V"], { timeout: 3e3 }, (error62, stdout) => resolve11(error62 ? "" : String(stdout)));
|
|
33284
33440
|
}),
|
|
33285
33441
|
sockets: async () => (await Promise.all(tmuxSocketFolders().map(tmuxSocketsIn))).flat(),
|
|
33286
33442
|
sleep: (ms, signal) => new Promise((resolve11, reject) => {
|
|
@@ -33362,7 +33518,7 @@ var init_terminal_tmux = __esm({
|
|
|
33362
33518
|
await tmux(server, ["send-keys", "-t", target, "Enter"], { signal });
|
|
33363
33519
|
},
|
|
33364
33520
|
async create(server, { workspace, label: label2, cwd }) {
|
|
33365
|
-
const directory = cwd &&
|
|
33521
|
+
const directory = cwd && path34.isAbsolute(cwd) ? ["-c", cwd] : [];
|
|
33366
33522
|
const name = label2 ? ["-n", label2.replace(/[\x00-\x1f\x7f]/g, " ").slice(0, 100)] : [];
|
|
33367
33523
|
if (workspace) {
|
|
33368
33524
|
await tmux(server, ["new-window", "-d", "-t", `${toTmuxId(workspace, "s")}:`, ...directory, ...name]);
|
|
@@ -33512,6 +33668,7 @@ __export(herdr_exports, {
|
|
|
33512
33668
|
opencodePidSession: () => opencodePidSession,
|
|
33513
33669
|
paneAgentName: () => paneAgentName,
|
|
33514
33670
|
paneChatState: () => paneChatState,
|
|
33671
|
+
paneForCodexSession: () => paneForCodexSession,
|
|
33515
33672
|
paneIdentity: () => paneIdentity,
|
|
33516
33673
|
panes: () => panes,
|
|
33517
33674
|
recentServers: () => recentServers,
|
|
@@ -33527,26 +33684,26 @@ __export(herdr_exports, {
|
|
|
33527
33684
|
workspaceSnapshot: () => workspaceSnapshot
|
|
33528
33685
|
});
|
|
33529
33686
|
import { createHmac, randomBytes as randomBytes2 } from "node:crypto";
|
|
33530
|
-
import { execFile as
|
|
33687
|
+
import { execFile as execFile5 } from "node:child_process";
|
|
33531
33688
|
import { connect } from "node:net";
|
|
33532
33689
|
import { homedir as homedir8 } from "node:os";
|
|
33533
|
-
import { open as
|
|
33534
|
-
import
|
|
33535
|
-
import { promisify as
|
|
33690
|
+
import { open as open7, readdir as readdir8, readlink, realpath as realpath7, stat as stat10 } from "node:fs/promises";
|
|
33691
|
+
import path35 from "node:path";
|
|
33692
|
+
import { promisify as promisify4 } from "node:util";
|
|
33536
33693
|
function herdrRoot() {
|
|
33537
|
-
return process.env.PHREN_HERDR_HOME ||
|
|
33694
|
+
return process.env.PHREN_HERDR_HOME || path35.join(homedir8(), ".config/herdr");
|
|
33538
33695
|
}
|
|
33539
33696
|
function herdrSocketPath(server) {
|
|
33540
33697
|
return herdrSocket(server);
|
|
33541
33698
|
}
|
|
33542
33699
|
function herdrSocket(server) {
|
|
33543
33700
|
serverName.parse(server);
|
|
33544
|
-
return
|
|
33701
|
+
return path35.join(herdrRoot(), ...server === "default" ? [] : ["sessions", server], "herdr.sock");
|
|
33545
33702
|
}
|
|
33546
33703
|
function herdrPaneFromEnv(env = process.env) {
|
|
33547
33704
|
if (env.HERDR_ENV !== "1" || !env.HERDR_SOCKET_PATH) return void 0;
|
|
33548
|
-
const socket =
|
|
33549
|
-
const server = socket ===
|
|
33705
|
+
const socket = path35.resolve(env.HERDR_SOCKET_PATH), root = path35.resolve(herdrRoot());
|
|
33706
|
+
const server = socket === path35.join(root, "herdr.sock") ? "default" : socket.startsWith(path35.join(root, "sessions") + path35.sep) ? path35.basename(path35.dirname(socket)) : void 0;
|
|
33550
33707
|
const { HERDR_WORKSPACE_ID: workspace, HERDR_TAB_ID: tab, HERDR_PANE_ID: pane } = env;
|
|
33551
33708
|
if (!server || !workspace || !tab || !pane) return void 0;
|
|
33552
33709
|
return { server, workspace, tab, pane };
|
|
@@ -33568,7 +33725,7 @@ function noteOptionalReadFailure(what, key2, error62) {
|
|
|
33568
33725
|
async function rpc(server, method, params = {}, signal, timeoutMs = 1e4) {
|
|
33569
33726
|
const socket = herdrSocket(server);
|
|
33570
33727
|
countHerdr(method);
|
|
33571
|
-
const metadata = await
|
|
33728
|
+
const metadata = await stat10(socket).catch((error62) => {
|
|
33572
33729
|
throw herdrSocketError(error62);
|
|
33573
33730
|
});
|
|
33574
33731
|
if (!metadata.isSocket() || process.getuid && metadata.uid !== process.getuid()) throw new BridgeError(503, "The Herdr socket is unavailable.", { code: "herdr-permission" });
|
|
@@ -33625,7 +33782,7 @@ async function recentServers(maxAgeMs = SERVER_LIST_REUSE_MS) {
|
|
|
33625
33782
|
return value2;
|
|
33626
33783
|
}
|
|
33627
33784
|
async function servers() {
|
|
33628
|
-
const names = ["default", ...(await
|
|
33785
|
+
const names = ["default", ...(await readdir8(path35.join(herdrRoot(), "sessions")).catch(() => [])).filter((n) => serverName.safeParse(n).success)].slice(0, 64);
|
|
33629
33786
|
const results = await Promise.all(names.map(async (name) => {
|
|
33630
33787
|
try {
|
|
33631
33788
|
await rpc(name, "ping");
|
|
@@ -33635,7 +33792,7 @@ async function servers() {
|
|
|
33635
33792
|
}
|
|
33636
33793
|
}));
|
|
33637
33794
|
const running2 = results.filter((v) => v !== null);
|
|
33638
|
-
|
|
33795
|
+
running2.push(...await Promise.resolve().then(() => (init_terminal_tmux(), terminal_tmux_exports)).then((tmux2) => tmux2.tmuxServers({ hidden: !running2.length })).catch(() => []));
|
|
33639
33796
|
knownServers = running2.map((server) => String(server.session));
|
|
33640
33797
|
return running2;
|
|
33641
33798
|
}
|
|
@@ -33728,10 +33885,10 @@ async function processLogs(pids) {
|
|
|
33728
33885
|
if (process.platform === "linux") {
|
|
33729
33886
|
countIdentity("proc");
|
|
33730
33887
|
const base = `/proc/${pid}/fd`;
|
|
33731
|
-
return Promise.all((await
|
|
33888
|
+
return Promise.all((await readdir8(base).catch(() => [])).slice(0, 4096).map((fd) => readlink(path35.join(base, fd)).catch(() => "")));
|
|
33732
33889
|
}
|
|
33733
33890
|
countIdentity("lsof");
|
|
33734
|
-
const result = await
|
|
33891
|
+
const result = await exec4("/usr/sbin/lsof", ["-a", "-p", String(pid), "-Fn"], { timeout: 3e3, maxBuffer: 1048576 }).catch(() => ({ stdout: "" }));
|
|
33735
33892
|
return result.stdout.split("\n").filter((n) => n.startsWith("n/")).map((n) => n.slice(1));
|
|
33736
33893
|
}));
|
|
33737
33894
|
return [...new Set(paths.flat())].filter((p) => p.endsWith(".jsonl") || p.endsWith(".lock"));
|
|
@@ -33765,12 +33922,12 @@ async function paneIdentity(server, pane, fresh = false) {
|
|
|
33765
33922
|
}
|
|
33766
33923
|
async function copilotForegroundSession(pids, home = copilotHome()) {
|
|
33767
33924
|
if (!pids.length) return void 0;
|
|
33768
|
-
const folder =
|
|
33769
|
-
const names = await
|
|
33925
|
+
const folder = path35.join(home, "logs");
|
|
33926
|
+
const names = await readdir8(folder).catch(() => []);
|
|
33770
33927
|
const logs = names.filter((name) => pids.some((pid) => name.startsWith("process-") && name.endsWith(`-${pid}.log`)));
|
|
33771
33928
|
let current2, latest = -1;
|
|
33772
33929
|
for (const name of logs) {
|
|
33773
|
-
const file2 = await
|
|
33930
|
+
const file2 = await open7(path35.join(folder, name), "r").catch(() => void 0);
|
|
33774
33931
|
if (!file2) continue;
|
|
33775
33932
|
try {
|
|
33776
33933
|
const { size } = await file2.stat(), length = Math.min(size, 262144);
|
|
@@ -33789,10 +33946,10 @@ async function copilotForegroundSession(pids, home = copilotHome()) {
|
|
|
33789
33946
|
return current2;
|
|
33790
33947
|
}
|
|
33791
33948
|
async function opencodePidSession(pids, root = phrenStoreRoot()) {
|
|
33792
|
-
const folder =
|
|
33949
|
+
const folder = path35.join(root, ".runtime", "sessions");
|
|
33793
33950
|
let current2, latest = -Infinity;
|
|
33794
33951
|
for (const pid of pids) {
|
|
33795
|
-
const file2 = await
|
|
33952
|
+
const file2 = await open7(path35.join(folder, `opencode-pid-${pid}.json`), "r").catch(() => void 0);
|
|
33796
33953
|
if (!file2) continue;
|
|
33797
33954
|
try {
|
|
33798
33955
|
const { size } = await file2.stat();
|
|
@@ -33801,7 +33958,7 @@ async function opencodePidSession(pids, root = phrenStoreRoot()) {
|
|
|
33801
33958
|
const session = typeof value2.session === "string" && /^ses_[0-9A-Za-z]{1,64}$/.test(value2.session) ? value2.session : void 0;
|
|
33802
33959
|
const at = Date.parse(String(value2.at));
|
|
33803
33960
|
if (!session || !(at > latest)) continue;
|
|
33804
|
-
if (!await
|
|
33961
|
+
if (!await stat10(path35.join(folder, `opencode-${session}.events.jsonl`)).catch(() => void 0)) continue;
|
|
33805
33962
|
current2 = session;
|
|
33806
33963
|
latest = at;
|
|
33807
33964
|
} catch {
|
|
@@ -33819,7 +33976,7 @@ async function identityFromProcesses(server, pane, pids) {
|
|
|
33819
33976
|
}
|
|
33820
33977
|
if (pane.agent === "copilot") {
|
|
33821
33978
|
const current2 = await copilotForegroundSession(pids).catch(() => void 0);
|
|
33822
|
-
if (current2) return await
|
|
33979
|
+
if (current2) return await stat10(path35.join(copilotHome(), "session-state", current2, "events.jsonl")).then(() => ({ sessionId: current2, noTranscriptLogs: false }), () => ({ noTranscriptLogs: true }));
|
|
33823
33980
|
const reported = object2(pane.agent_session);
|
|
33824
33981
|
if (reported.kind === "id" && reported.agent === "copilot" && typeof reported.value === "string" && sessionId.safeParse(reported.value).success) return { sessionId: reported.value, noTranscriptLogs: false };
|
|
33825
33982
|
}
|
|
@@ -33829,9 +33986,51 @@ async function identityFromProcesses(server, pane, pids) {
|
|
|
33829
33986
|
return match ? [match[1]] : [];
|
|
33830
33987
|
});
|
|
33831
33988
|
if (new Set(candidates).size === 1) return { sessionId: candidates[0], noTranscriptLogs: false };
|
|
33989
|
+
if (pane.agent === "codex" && candidates.length === 0) {
|
|
33990
|
+
const daemon = await codexDaemonIdentity(server, pane, pids).catch(() => void 0);
|
|
33991
|
+
if (daemon?.sessionId) return { sessionId: daemon.sessionId, noTranscriptLogs: false };
|
|
33992
|
+
const recorded2 = await recordedSession(server, pane, pids);
|
|
33993
|
+
return { sessionId: recorded2 && !daemon?.known.has(recorded2) ? recorded2 : void 0, noTranscriptLogs: true };
|
|
33994
|
+
}
|
|
33832
33995
|
const recorded = await recordedSession(server, pane, pids);
|
|
33833
33996
|
return { sessionId: candidates.length === 0 || recorded && candidates.includes(recorded) ? recorded : void 0, noTranscriptLogs: candidates.length === 0 };
|
|
33834
33997
|
}
|
|
33998
|
+
async function codexDaemonIdentity(server, pane, pids) {
|
|
33999
|
+
const all = await daemonRollouts(processLogs);
|
|
34000
|
+
const known = new Set(all.map((r) => r.id));
|
|
34001
|
+
const cwd = paneCwd(pane);
|
|
34002
|
+
const here = [];
|
|
34003
|
+
for (const r of all) if (await sameDirectory(r.cwd, cwd)) here.push(r);
|
|
34004
|
+
if (!here.length) return { known };
|
|
34005
|
+
const rows = await processTable(), start = startedAt(rows, pids);
|
|
34006
|
+
if (start === void 0) return { known };
|
|
34007
|
+
const s = await (await terminal()).terminalProvider().snapshot(server).catch(() => ({}));
|
|
34008
|
+
const claimed = /* @__PURE__ */ new Set(), rivals = [];
|
|
34009
|
+
for (const peer of objects(s.panes).filter((p) => p.agent === "codex" && p.pane_id !== pane.pane_id).slice(0, 16)) {
|
|
34010
|
+
if (!await sameDirectory(paneCwd(peer), cwd)) continue;
|
|
34011
|
+
const peerPids = await foregroundPids(server, peer).catch(() => []);
|
|
34012
|
+
if (!peerPids.length) continue;
|
|
34013
|
+
const own2 = rolloutIds(await processLogs(peerPids));
|
|
34014
|
+
if (own2.length) {
|
|
34015
|
+
for (const id2 of own2) claimed.add(id2);
|
|
34016
|
+
continue;
|
|
34017
|
+
}
|
|
34018
|
+
const peerStart = startedAt(rows, peerPids);
|
|
34019
|
+
if (peerStart !== void 0) rivals.push({ key: String(peer.pane_id), start: peerStart });
|
|
34020
|
+
}
|
|
34021
|
+
return { sessionId: assignDaemonConversation(here, { key: String(pane.pane_id), start }, claimed, rivals), known };
|
|
34022
|
+
}
|
|
34023
|
+
async function paneForCodexSession(server, session, cwd) {
|
|
34024
|
+
const s = await snapshot(server);
|
|
34025
|
+
const codex2 = objects(s.panes).filter((p) => p.agent === "codex").slice(0, 32);
|
|
34026
|
+
const identities2 = await Promise.all(codex2.map((p) => paneIdentity(server, p).catch(() => void 0)));
|
|
34027
|
+
const index2 = identities2.indexOf(session);
|
|
34028
|
+
if (index2 >= 0) return codex2[index2];
|
|
34029
|
+
if (!cwd) return void 0;
|
|
34030
|
+
const same = [];
|
|
34031
|
+
for (const [i, p] of codex2.entries()) if (await sameDirectory(paneCwd(p), cwd)) same.push(i);
|
|
34032
|
+
return same.length === 1 && !identities2[same[0]] ? codex2[same[0]] : void 0;
|
|
34033
|
+
}
|
|
33835
34034
|
async function paneChatState(server, pane, options = {}) {
|
|
33836
34035
|
if (!provider.safeParse(pane.agent).success) return {};
|
|
33837
34036
|
const identity = await resolveIdentity(server, pane, false);
|
|
@@ -33895,10 +34094,10 @@ async function validateTarget(target, sending = false, refreshIdentity = sending
|
|
|
33895
34094
|
}
|
|
33896
34095
|
async function trustedDirectory(pane) {
|
|
33897
34096
|
const cwd = pane.foreground_cwd || pane.cwd;
|
|
33898
|
-
if (typeof cwd !== "string" || !
|
|
33899
|
-
return
|
|
34097
|
+
if (typeof cwd !== "string" || !path35.isAbsolute(cwd)) throw new BridgeError(409, "This pane has no project folder.");
|
|
34098
|
+
return realpath7(cwd);
|
|
33900
34099
|
}
|
|
33901
|
-
var terminal,
|
|
34100
|
+
var terminal, exec4, optionalReadFailures, SERVER_LIST_REUSE_MS, serverList, knownServers, SNAPSHOT_SHARE_MS, sharedSnapshots, inFlightSnapshots, IDENTITY_CACHE_MS, identities, identityKey, copilotHome, rolloutIds, paneCwd, startingKey, sharedIdentities;
|
|
33902
34101
|
var init_herdr = __esm({
|
|
33903
34102
|
"src/bridge/herdr.ts"() {
|
|
33904
34103
|
"use strict";
|
|
@@ -33909,8 +34108,9 @@ var init_herdr = __esm({
|
|
|
33909
34108
|
init_limits();
|
|
33910
34109
|
init_metrics();
|
|
33911
34110
|
init_transcripts();
|
|
34111
|
+
init_codex_daemon();
|
|
33912
34112
|
terminal = () => Promise.resolve().then(() => (init_terminal(), terminal_exports));
|
|
33913
|
-
|
|
34113
|
+
exec4 = promisify4(execFile5);
|
|
33914
34114
|
optionalReadFailures = /* @__PURE__ */ new Map();
|
|
33915
34115
|
SERVER_LIST_REUSE_MS = intervalFromEnv("PHREN_SERVER_LIST_REUSE_MS", 3e4, 0, 6e5);
|
|
33916
34116
|
SNAPSHOT_SHARE_MS = intervalFromEnv("PHREN_SNAPSHOT_SHARE_MS", 2500, 0, 1e4);
|
|
@@ -33919,7 +34119,9 @@ var init_herdr = __esm({
|
|
|
33919
34119
|
IDENTITY_CACHE_MS = intervalFromEnv("PHREN_IDENTITY_CACHE_MS", 2e3);
|
|
33920
34120
|
identities = /* @__PURE__ */ new Map();
|
|
33921
34121
|
identityKey = (server, pane, pids) => JSON.stringify([server, pane.pane_id, pane.terminal_id, pids, pane.agent]);
|
|
33922
|
-
copilotHome = () => process.env.COPILOT_HOME ||
|
|
34122
|
+
copilotHome = () => process.env.COPILOT_HOME || path35.join(homedir8(), ".copilot");
|
|
34123
|
+
rolloutIds = (files) => files.flatMap((file2) => /rollout-.*-([a-f0-9-]{36})\.jsonl$/i.exec(file2)?.[1] ?? []);
|
|
34124
|
+
paneCwd = (pane) => pane.foreground_cwd || pane.cwd;
|
|
33923
34125
|
startingKey = randomBytes2(32);
|
|
33924
34126
|
sharedIdentities = /* @__PURE__ */ new WeakMap();
|
|
33925
34127
|
}
|
|
@@ -33955,7 +34157,7 @@ var init_preferences = __esm({
|
|
|
33955
34157
|
// src/project-config.ts
|
|
33956
34158
|
import * as crypto4 from "crypto";
|
|
33957
34159
|
import * as fs23 from "fs";
|
|
33958
|
-
import * as
|
|
34160
|
+
import * as path43 from "path";
|
|
33959
34161
|
function parseProjectOwnershipMode(raw) {
|
|
33960
34162
|
if (!raw) return void 0;
|
|
33961
34163
|
const normalized = raw.trim().toLowerCase();
|
|
@@ -33970,7 +34172,7 @@ function resolveProjectConfigPath(phrenPath, project) {
|
|
|
33970
34172
|
return storeAwareProjectPath(phrenPath, project, "phren.project.yaml");
|
|
33971
34173
|
}
|
|
33972
34174
|
function writeProjectConfigFile(configPath, next) {
|
|
33973
|
-
fs23.mkdirSync(
|
|
34175
|
+
fs23.mkdirSync(path43.dirname(configPath), { recursive: true });
|
|
33974
34176
|
const tmpPath = `${configPath}.tmp-${crypto4.randomUUID()}`;
|
|
33975
34177
|
fs23.writeFileSync(tmpPath, dump(next, { lineWidth: 1e3 }));
|
|
33976
34178
|
fs23.renameSync(tmpPath, configPath);
|
|
@@ -34023,7 +34225,7 @@ function getProjectSourcePath(phrenPath, project, config3, machine = getMachineN
|
|
|
34023
34225
|
const resolved = config3 ?? readProjectConfig(phrenPath, project);
|
|
34024
34226
|
const perMachine = resolved.sourcePaths && typeof resolved.sourcePaths === "object" && !Array.isArray(resolved.sourcePaths) ? resolved.sourcePaths[machine] : void 0;
|
|
34025
34227
|
const raw = typeof perMachine === "string" && perMachine.trim() ? perMachine : resolved.sourcePath;
|
|
34026
|
-
return typeof raw === "string" && raw.trim() ?
|
|
34228
|
+
return typeof raw === "string" && raw.trim() ? path43.resolve(raw) : void 0;
|
|
34027
34229
|
}
|
|
34028
34230
|
function recordProjectSourcePath(phrenPath, project, sourceRoot, patch = {}, machine = getMachineName()) {
|
|
34029
34231
|
const current2 = readProjectConfig(phrenPath, project);
|
|
@@ -34066,11 +34268,11 @@ __export(agent_package_exports, {
|
|
|
34066
34268
|
import { execFileSync as execFileSync4, spawn as spawn4 } from "node:child_process";
|
|
34067
34269
|
import * as fs24 from "node:fs";
|
|
34068
34270
|
import { createRequire } from "node:module";
|
|
34069
|
-
import * as
|
|
34271
|
+
import * as path46 from "node:path";
|
|
34070
34272
|
import { fileURLToPath as fileURLToPath4 } from "node:url";
|
|
34071
34273
|
function readManifest(directory) {
|
|
34072
34274
|
try {
|
|
34073
|
-
return JSON.parse(fs24.readFileSync(
|
|
34275
|
+
return JSON.parse(fs24.readFileSync(path46.join(directory, "package.json"), "utf8"));
|
|
34074
34276
|
} catch {
|
|
34075
34277
|
return void 0;
|
|
34076
34278
|
}
|
|
@@ -34080,15 +34282,15 @@ function agentPackageAt(directory, source) {
|
|
|
34080
34282
|
if (manifest?.name !== "@phren/agent") return void 0;
|
|
34081
34283
|
const relative3 = typeof manifest.bin === "string" ? manifest.bin : manifest.bin?.["phren-agent"];
|
|
34082
34284
|
if (!relative3) return void 0;
|
|
34083
|
-
const bin =
|
|
34285
|
+
const bin = path46.join(directory, relative3);
|
|
34084
34286
|
return fs24.existsSync(bin) ? { directory, bin, version: manifest.version, source } : void 0;
|
|
34085
34287
|
}
|
|
34086
34288
|
function workspaceDirectory() {
|
|
34087
|
-
let directory =
|
|
34289
|
+
let directory = path46.dirname(fileURLToPath4(import.meta.url));
|
|
34088
34290
|
for (let depth = 0; depth < 8; depth++) {
|
|
34089
|
-
const candidate =
|
|
34090
|
-
if (fs24.existsSync(
|
|
34091
|
-
const parent =
|
|
34291
|
+
const candidate = path46.join(directory, "packages", "agent");
|
|
34292
|
+
if (fs24.existsSync(path46.join(candidate, "package.json"))) return candidate;
|
|
34293
|
+
const parent = path46.dirname(directory);
|
|
34092
34294
|
if (parent === directory) break;
|
|
34093
34295
|
directory = parent;
|
|
34094
34296
|
}
|
|
@@ -34096,7 +34298,7 @@ function workspaceDirectory() {
|
|
|
34096
34298
|
}
|
|
34097
34299
|
function resolvedDirectory() {
|
|
34098
34300
|
try {
|
|
34099
|
-
return
|
|
34301
|
+
return path46.dirname(createRequire(import.meta.url).resolve("@phren/agent/package.json"));
|
|
34100
34302
|
} catch {
|
|
34101
34303
|
return void 0;
|
|
34102
34304
|
}
|
|
@@ -34105,7 +34307,7 @@ function globalDirectory() {
|
|
|
34105
34307
|
try {
|
|
34106
34308
|
const options = { encoding: "utf8", timeout: 1e4, stdio: ["ignore", "pipe", "ignore"] };
|
|
34107
34309
|
const root = (process.platform === "win32" ? execFileSync4("npm.cmd", ["root", "-g"], { ...options, shell: true }) : execFileSync4("npm", ["root", "-g"], options)).trim();
|
|
34108
|
-
return root ?
|
|
34310
|
+
return root ? path46.join(root, "@phren", "agent") : void 0;
|
|
34109
34311
|
} catch {
|
|
34110
34312
|
return void 0;
|
|
34111
34313
|
}
|
|
@@ -34244,7 +34446,7 @@ var init_audit = __esm({
|
|
|
34244
34446
|
|
|
34245
34447
|
// src/governance/activity.ts
|
|
34246
34448
|
import * as fs25 from "fs";
|
|
34247
|
-
import * as
|
|
34449
|
+
import * as path56 from "path";
|
|
34248
34450
|
function clampSnippet(snippet) {
|
|
34249
34451
|
if (!snippet) return void 0;
|
|
34250
34452
|
const flat = snippet.replace(/\s+/g, " ").trim();
|
|
@@ -34255,7 +34457,7 @@ function recordLookupEvents(phrenPath, events) {
|
|
|
34255
34457
|
if (!events.length) return;
|
|
34256
34458
|
const logPath = lookupEventsLogFile(phrenPath);
|
|
34257
34459
|
try {
|
|
34258
|
-
fs25.mkdirSync(
|
|
34460
|
+
fs25.mkdirSync(path56.dirname(logPath), { recursive: true });
|
|
34259
34461
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
34260
34462
|
const lines = events.map(
|
|
34261
34463
|
(e) => JSON.stringify({
|
|
@@ -34277,8 +34479,8 @@ function recordLookupEvents(phrenPath, events) {
|
|
|
34277
34479
|
return;
|
|
34278
34480
|
}
|
|
34279
34481
|
try {
|
|
34280
|
-
const
|
|
34281
|
-
if (
|
|
34482
|
+
const stat27 = fs25.statSync(logPath);
|
|
34483
|
+
if (stat27.size > ROTATE_BYTES) {
|
|
34282
34484
|
const content = fs25.readFileSync(logPath, "utf8");
|
|
34283
34485
|
const kept = content.split("\n").filter(Boolean).slice(-MAX_LOG_LINES2);
|
|
34284
34486
|
fs25.writeFileSync(logPath, kept.join("\n") + "\n");
|
|
@@ -34540,7 +34742,7 @@ var init_metadata = __esm({
|
|
|
34540
34742
|
|
|
34541
34743
|
// src/governance/policy.ts
|
|
34542
34744
|
import * as fs26 from "fs";
|
|
34543
|
-
import * as
|
|
34745
|
+
import * as path57 from "path";
|
|
34544
34746
|
function assessSyncOutage(sync, nowMs = Date.now()) {
|
|
34545
34747
|
const consecutiveFailures = sync?.consecutiveFailures ?? 0;
|
|
34546
34748
|
const failingNow = sync?.lastPushStatus !== void 0 && FAILED_PUSH_STATUSES.has(sync.lastPushStatus);
|
|
@@ -34677,7 +34879,7 @@ function normalizeIndexPolicy(data) {
|
|
|
34677
34879
|
function readJsonFile(filePath, fallback) {
|
|
34678
34880
|
try {
|
|
34679
34881
|
if (!fs26.existsSync(filePath)) return fallback;
|
|
34680
|
-
const basename12 =
|
|
34882
|
+
const basename12 = path57.basename(filePath);
|
|
34681
34883
|
const schema = GOVERNANCE_FILE_SCHEMAS[basename12];
|
|
34682
34884
|
if (schema && !validateGovernanceJson(filePath, schema)) {
|
|
34683
34885
|
debugLog(`readJsonFile: ${filePath} failed validation, using defaults`);
|
|
@@ -35077,9 +35279,9 @@ import * as path23 from "node:path";
|
|
|
35077
35279
|
function gitDirectory(store) {
|
|
35078
35280
|
const dotGit = path23.join(store, ".git");
|
|
35079
35281
|
try {
|
|
35080
|
-
const
|
|
35081
|
-
if (
|
|
35082
|
-
if (!
|
|
35282
|
+
const stat27 = fs15.statSync(dotGit);
|
|
35283
|
+
if (stat27.isDirectory()) return dotGit;
|
|
35284
|
+
if (!stat27.isFile()) return void 0;
|
|
35083
35285
|
const match = /^gitdir:\s*(.+)\s*$/i.exec(fs15.readFileSync(dotGit, "utf8"));
|
|
35084
35286
|
if (!match) return void 0;
|
|
35085
35287
|
return path23.resolve(store, match[1]);
|
|
@@ -35114,7 +35316,7 @@ import * as fs17 from "node:fs";
|
|
|
35114
35316
|
import * as path25 from "node:path";
|
|
35115
35317
|
var core = (names) => names.map((name) => ({ name, profiles: ["core", "full"] }));
|
|
35116
35318
|
var full = (names) => names.map((name) => ({ name, profiles: ["full"] }));
|
|
35117
|
-
var routes = (method, paths) => paths.map((
|
|
35319
|
+
var routes = (method, paths) => paths.map((path85) => ({ method, path: path85 }));
|
|
35118
35320
|
var BUILTIN_MODULES = [
|
|
35119
35321
|
{
|
|
35120
35322
|
schemaVersion: 1,
|
|
@@ -35637,7 +35839,7 @@ import { chmod as chmod5, lstat as lstat20, mkdir as mkdir21, readFile as readFi
|
|
|
35637
35839
|
import { readFileSync as readFileSync32 } from "node:fs";
|
|
35638
35840
|
import { createServer as createServer2 } from "node:http";
|
|
35639
35841
|
import { cpus, hostname as hostname9, loadavg } from "node:os";
|
|
35640
|
-
import
|
|
35842
|
+
import path83 from "node:path";
|
|
35641
35843
|
|
|
35642
35844
|
// ../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/wrapper.mjs
|
|
35643
35845
|
var import_stream = __toESM(require_stream(), 1);
|
|
@@ -35903,11 +36105,12 @@ init_shared();
|
|
|
35903
36105
|
init_logger();
|
|
35904
36106
|
init_protocol();
|
|
35905
36107
|
init_herdr();
|
|
36108
|
+
init_codex_daemon();
|
|
35906
36109
|
init_terminal();
|
|
35907
36110
|
import { request, createServer } from "node:http";
|
|
35908
36111
|
import { mkdir as mkdir9, readFile as readFile14, chmod, unlink as unlink3, lstat as lstat7 } from "node:fs/promises";
|
|
35909
36112
|
import { watch } from "node:fs";
|
|
35910
|
-
import
|
|
36113
|
+
import path38 from "node:path";
|
|
35911
36114
|
import { randomUUID as randomUUID7 } from "node:crypto";
|
|
35912
36115
|
|
|
35913
36116
|
// src/bridge/pane-text.ts
|
|
@@ -35934,7 +36137,7 @@ init_js_yaml();
|
|
|
35934
36137
|
init_zod();
|
|
35935
36138
|
init_protocol();
|
|
35936
36139
|
import { lstat as lstat6, mkdir as mkdir8, readFile as readFile12 } from "node:fs/promises";
|
|
35937
|
-
import
|
|
36140
|
+
import path36 from "node:path";
|
|
35938
36141
|
var grantAction = external_exports.enum(["dispatch", "hand_off"]);
|
|
35939
36142
|
var grantScope = external_exports.union([
|
|
35940
36143
|
external_exports.literal("global"),
|
|
@@ -35946,7 +36149,7 @@ var grantSchema = external_exports.object({
|
|
|
35946
36149
|
computers: external_exports.array(computerName).min(1).max(32).optional().describe("Named verified peers; omitted means any."),
|
|
35947
36150
|
until: external_exports.string().datetime({ offset: true }).optional().describe("Expiry timestamp; omitted means until revoked.")
|
|
35948
36151
|
}).strict();
|
|
35949
|
-
var grantFile = (root = bridgeRoot()) =>
|
|
36152
|
+
var grantFile = (root = bridgeRoot()) => path36.join(root, "conductor.yaml");
|
|
35950
36153
|
var fileSchema = external_exports.object({ grants: external_exports.array(grantSchema).max(64) }).strict();
|
|
35951
36154
|
async function regularPrivateFile(file2) {
|
|
35952
36155
|
const info = await lstat6(file2).catch(() => void 0);
|
|
@@ -36007,7 +36210,7 @@ function grantLabel(grant) {
|
|
|
36007
36210
|
}
|
|
36008
36211
|
var mutations = /* @__PURE__ */ new Map();
|
|
36009
36212
|
async function mutateGrants(root, action) {
|
|
36010
|
-
const key2 =
|
|
36213
|
+
const key2 = path36.resolve(root);
|
|
36011
36214
|
const previous = mutations.get(key2) ?? Promise.resolve();
|
|
36012
36215
|
const pending = previous.catch(() => {
|
|
36013
36216
|
}).then(async () => {
|
|
@@ -36086,9 +36289,9 @@ async function removeGrant(input2, root = bridgeRoot()) {
|
|
|
36086
36289
|
init_zod();
|
|
36087
36290
|
init_protocol();
|
|
36088
36291
|
import { createCipheriv, createHmac as createHmac2, createPrivateKey, randomBytes as randomBytes3, sign } from "node:crypto";
|
|
36089
|
-
import { readFile as readFile13, stat as
|
|
36292
|
+
import { readFile as readFile13, stat as stat11 } from "node:fs/promises";
|
|
36090
36293
|
import { connect as connect2 } from "node:http2";
|
|
36091
|
-
import
|
|
36294
|
+
import path37 from "node:path";
|
|
36092
36295
|
var relaySchema = external_exports.object({
|
|
36093
36296
|
url: external_exports.string().url().refine(
|
|
36094
36297
|
(value2) => /^https:\/\//.test(value2) || /^http:\/\/(127\.0\.0\.1|localhost)(:\d+)?\//.test(`${value2}/`),
|
|
@@ -36160,7 +36363,7 @@ function schedulePushPayload(value2) {
|
|
|
36160
36363
|
}
|
|
36161
36364
|
async function secureJSON(file2, schema) {
|
|
36162
36365
|
try {
|
|
36163
|
-
const metadata = await
|
|
36366
|
+
const metadata = await stat11(file2);
|
|
36164
36367
|
if ((metadata.mode & 63) !== 0 || process.getuid && metadata.uid !== process.getuid()) return void 0;
|
|
36165
36368
|
return schema.parse(JSON.parse(await readFile13(file2, "utf8")));
|
|
36166
36369
|
} catch {
|
|
@@ -36169,14 +36372,14 @@ async function secureJSON(file2, schema) {
|
|
|
36169
36372
|
}
|
|
36170
36373
|
async function secureFile(file2) {
|
|
36171
36374
|
try {
|
|
36172
|
-
const metadata = await
|
|
36375
|
+
const metadata = await stat11(file2);
|
|
36173
36376
|
if (!metadata.isFile() || (metadata.mode & 63) !== 0 || process.getuid && metadata.uid !== process.getuid()) return void 0;
|
|
36174
36377
|
return await readFile13(file2, "utf8");
|
|
36175
36378
|
} catch {
|
|
36176
36379
|
return void 0;
|
|
36177
36380
|
}
|
|
36178
36381
|
}
|
|
36179
|
-
function apnsSetupSteps(configFile = process.env.PHREN_APNS_CONFIG ||
|
|
36382
|
+
function apnsSetupSteps(configFile = process.env.PHREN_APNS_CONFIG || path37.join(bridgeRoot(), "apns.json")) {
|
|
36180
36383
|
return [
|
|
36181
36384
|
"Approval push is not configured: the phone only alerts while Phren runs, and a registered phone gets nothing while suspended.",
|
|
36182
36385
|
"1. In your Apple developer account, create an APNs key (Keys, Apple Push Notifications service) and download AuthKey_<KEYID>.p8.",
|
|
@@ -36298,13 +36501,13 @@ var APNsSender = class {
|
|
|
36298
36501
|
var ApprovalPushService = class {
|
|
36299
36502
|
devices = [];
|
|
36300
36503
|
sender;
|
|
36301
|
-
devicesFile =
|
|
36504
|
+
devicesFile = path37.join(bridgeRoot(), "push-devices.json");
|
|
36302
36505
|
async start() {
|
|
36303
36506
|
this.devices = await secureJSON(this.devicesFile, external_exports.array(deviceSchema).max(16)) ?? [];
|
|
36304
|
-
const configFile = process.env.PHREN_APNS_CONFIG ||
|
|
36507
|
+
const configFile = process.env.PHREN_APNS_CONFIG || path37.join(bridgeRoot(), "apns.json");
|
|
36305
36508
|
const config3 = await secureJSON(configFile, configSchema2);
|
|
36306
36509
|
if (!config3) return;
|
|
36307
|
-
const keyPath =
|
|
36510
|
+
const keyPath = path37.isAbsolute(config3.privateKeyPath) ? config3.privateKeyPath : path37.resolve(path37.dirname(configFile), config3.privateKeyPath);
|
|
36308
36511
|
const key2 = await secureFile(keyPath);
|
|
36309
36512
|
if (key2) this.sender = new APNsSender(config3, key2);
|
|
36310
36513
|
}
|
|
@@ -36479,7 +36682,7 @@ var AgentHooks = class {
|
|
|
36479
36682
|
fanoutTimer;
|
|
36480
36683
|
fanoutArchiveTimer;
|
|
36481
36684
|
approvalsDirectory() {
|
|
36482
|
-
return
|
|
36685
|
+
return path38.join(phrenStoreRoot(), ".runtime", "approvals");
|
|
36483
36686
|
}
|
|
36484
36687
|
scheduleOpencodeSweep() {
|
|
36485
36688
|
if (this.closed || this.opencodeDebounce) return;
|
|
@@ -36548,13 +36751,13 @@ var AgentHooks = class {
|
|
|
36548
36751
|
/** A session's exact pane. A recorded binding carries the full target; when
|
|
36549
36752
|
* there is none, Herdr's explicit session identity names the pane. */
|
|
36550
36753
|
async resolveTarget(source, session) {
|
|
36551
|
-
const root =
|
|
36754
|
+
const root = path38.join(bridgeRoot(), "bindings");
|
|
36552
36755
|
for await (const folder of directoryNames(root, 64)) {
|
|
36553
|
-
for await (const name of directoryNames(
|
|
36756
|
+
for await (const name of directoryNames(path38.join(root, folder), 1024)) {
|
|
36554
36757
|
if (!name.endsWith(".json")) continue;
|
|
36555
36758
|
let value2;
|
|
36556
36759
|
try {
|
|
36557
|
-
const file2 =
|
|
36760
|
+
const file2 = path38.join(root, folder, name), info = await lstat7(file2);
|
|
36558
36761
|
if (!info.isFile() || info.size > 65536) continue;
|
|
36559
36762
|
value2 = object2(JSON.parse(await readFile14(file2, "utf8")));
|
|
36560
36763
|
} catch {
|
|
@@ -37296,18 +37499,29 @@ var AgentHooks = class {
|
|
|
37296
37499
|
if (size > 1048576) throw new Error("Oversized hook");
|
|
37297
37500
|
chunks.push(bytes);
|
|
37298
37501
|
}
|
|
37299
|
-
const body2 = object2(JSON.parse(Buffer.concat(chunks).toString()))
|
|
37502
|
+
const body2 = object2(JSON.parse(Buffer.concat(chunks).toString()));
|
|
37503
|
+
let target = targetSchema.parse(body2.target);
|
|
37300
37504
|
if (this.modules?.has("git") === false && ["PreToolUse", "PostToolUse"].includes(String(body2.event))) {
|
|
37301
37505
|
res.statusCode = 404;
|
|
37302
37506
|
res.end(JSON.stringify({ error: disabledHint("git") }));
|
|
37303
37507
|
return;
|
|
37304
37508
|
}
|
|
37509
|
+
const daemon = body2.daemon === true;
|
|
37510
|
+
if (daemon) {
|
|
37511
|
+
if (target.source !== "codex") throw new Error("Invalid callback");
|
|
37512
|
+
const placed = await paneForCodexSession(target.server, target.session, typeof body2.cwd === "string" && path38.isAbsolute(body2.cwd) ? body2.cwd : void 0);
|
|
37513
|
+
if (!placed) {
|
|
37514
|
+
res.end("{}");
|
|
37515
|
+
return;
|
|
37516
|
+
}
|
|
37517
|
+
target = targetSchema.parse({ ...target, workspace: placed.workspace_id, tab: placed.tab_id, pane: placed.pane_id });
|
|
37518
|
+
}
|
|
37305
37519
|
const s = await snapshot(target.server);
|
|
37306
37520
|
const pane = findPane(s, { workspace: target.workspace, tab: target.tab, pane: target.pane });
|
|
37307
37521
|
if (!pane || pane.agent && pane.agent !== target.source) throw new Error("The pane changed");
|
|
37308
37522
|
const pids = (await terminalProvider().processes(target.server, target.pane)).foregroundPids;
|
|
37309
37523
|
if (!pids.length) throw new Error("No foreground process");
|
|
37310
|
-
await atomicInPrivateDir(bindingPath(target.server, target.pane), JSON.stringify({
|
|
37524
|
+
if (!daemon) await atomicInPrivateDir(bindingPath(target.server, target.pane), JSON.stringify({
|
|
37311
37525
|
terminal: pane.terminal_id,
|
|
37312
37526
|
source: target.source,
|
|
37313
37527
|
session: target.session,
|
|
@@ -37332,7 +37546,7 @@ var AgentHooks = class {
|
|
|
37332
37546
|
}
|
|
37333
37547
|
if ((this.modules?.has("git") ?? true) && ["PreToolUse", "PostToolUse"].includes(String(body2.event)) && capturesChanges(String(body2.tool), input2)) {
|
|
37334
37548
|
const conversation = `${target.source}:${target.session}`, id2 = String(body2.toolUseId || "").slice(0, 200);
|
|
37335
|
-
if (body2.event === "PreToolUse") await this.changes.before(conversation, id2, typeof body2.cwd === "string" &&
|
|
37549
|
+
if (body2.event === "PreToolUse") await this.changes.before(conversation, id2, typeof body2.cwd === "string" && path38.isAbsolute(body2.cwd) ? body2.cwd : await trustedDirectory(pane), command ?? "", input2);
|
|
37336
37550
|
else await this.changes.after(conversation, id2);
|
|
37337
37551
|
res.end("{}");
|
|
37338
37552
|
return;
|
|
@@ -37503,9 +37717,11 @@ async function agentHook(source) {
|
|
|
37503
37717
|
const event = String(value2.hook_event_name || "SessionStart");
|
|
37504
37718
|
const modules = activateModules(defaultPhrenPath(), void 0, true);
|
|
37505
37719
|
if (!modules.has("hook") || event.endsWith("ToolUse") && !modules.has("git")) return;
|
|
37720
|
+
const daemon = source === "codex" && await underCodexDaemon().catch(() => false);
|
|
37506
37721
|
const data = JSON.stringify({
|
|
37507
37722
|
target,
|
|
37508
37723
|
event,
|
|
37724
|
+
...daemon ? { daemon: true } : {},
|
|
37509
37725
|
tool: value2.tool_name,
|
|
37510
37726
|
input: value2.tool_input,
|
|
37511
37727
|
toolUseId: value2.tool_use_id,
|
|
@@ -37547,27 +37763,27 @@ init_changes();
|
|
|
37547
37763
|
init_store_registry();
|
|
37548
37764
|
import { rm as rm4 } from "node:fs/promises";
|
|
37549
37765
|
import * as fs21 from "node:fs";
|
|
37550
|
-
import * as
|
|
37766
|
+
import * as path42 from "node:path";
|
|
37551
37767
|
|
|
37552
37768
|
// src/bridge/projects.ts
|
|
37553
37769
|
init_utils_helpers();
|
|
37554
37770
|
init_home_paths();
|
|
37555
37771
|
init_transcripts();
|
|
37556
|
-
import { execFile as
|
|
37557
|
-
import { promisify as
|
|
37772
|
+
import { execFile as execFile6 } from "node:child_process";
|
|
37773
|
+
import { promisify as promisify5 } from "node:util";
|
|
37558
37774
|
import { request as request2 } from "node:http";
|
|
37559
37775
|
import { userInfo as userInfo2 } from "node:os";
|
|
37560
|
-
import { readFile as readFile16, realpath as
|
|
37561
|
-
import
|
|
37776
|
+
import { readFile as readFile16, realpath as realpath8, stat as stat13 } from "node:fs/promises";
|
|
37777
|
+
import path40 from "node:path";
|
|
37562
37778
|
|
|
37563
37779
|
// src/bridge/locate.ts
|
|
37564
37780
|
init_protocol();
|
|
37565
37781
|
init_herdr();
|
|
37566
37782
|
init_transcripts();
|
|
37567
37783
|
import { realpathSync as realpathSync3 } from "node:fs";
|
|
37568
|
-
import { readFile as readFile15, stat as
|
|
37784
|
+
import { readFile as readFile15, stat as stat12 } from "node:fs/promises";
|
|
37569
37785
|
import { homedir as homedir9 } from "node:os";
|
|
37570
|
-
import
|
|
37786
|
+
import path39 from "node:path";
|
|
37571
37787
|
var PROJECT_NAME = /^[a-z0-9][a-z0-9-]*$/;
|
|
37572
37788
|
var SEARCH_ROOTS = ["", "Sites", "Projects", "projects", "Code", "code", "dev", "src", "repos", "workspace"];
|
|
37573
37789
|
async function locateProject(project, activity, env = process.env) {
|
|
@@ -37575,9 +37791,9 @@ async function locateProject(project, activity, env = process.env) {
|
|
|
37575
37791
|
const found = [];
|
|
37576
37792
|
const seen = /* @__PURE__ */ new Set();
|
|
37577
37793
|
const offer = async (directory, source, lastSeen) => {
|
|
37578
|
-
let dir =
|
|
37794
|
+
let dir = path39.resolve(directory);
|
|
37579
37795
|
try {
|
|
37580
|
-
if (!(await
|
|
37796
|
+
if (!(await stat12(dir)).isDirectory()) return;
|
|
37581
37797
|
dir = realpathSync3.native(dir);
|
|
37582
37798
|
} catch {
|
|
37583
37799
|
return;
|
|
@@ -37590,33 +37806,33 @@ async function locateProject(project, activity, env = process.env) {
|
|
|
37590
37806
|
const namesProject = (directory) => segments(directory).includes(project);
|
|
37591
37807
|
const trimmed = (directory) => {
|
|
37592
37808
|
const parts = segments(directory);
|
|
37593
|
-
return parts.slice(0, parts.lastIndexOf(project) + 1).join(
|
|
37809
|
+
return parts.slice(0, parts.lastIndexOf(project) + 1).join(path39.sep);
|
|
37594
37810
|
};
|
|
37595
37811
|
for (const event of [...activity].reverse()) {
|
|
37596
37812
|
const directory = typeof event.directory === "string" ? event.directory : void 0;
|
|
37597
|
-
if (directory &&
|
|
37813
|
+
if (directory && path39.isAbsolute(directory) && namesProject(directory)) {
|
|
37598
37814
|
await offer(trimmed(directory), "activity", typeof event.at === "string" ? event.at : void 0);
|
|
37599
37815
|
}
|
|
37600
37816
|
}
|
|
37601
37817
|
try {
|
|
37602
|
-
const session = JSON.parse(await readFile15(
|
|
37818
|
+
const session = JSON.parse(await readFile15(path39.join(herdrRoot(), "session.json"), "utf8"));
|
|
37603
37819
|
for (const match of JSON.stringify(session).matchAll(/"cwd":\s*"((?:\\.|[^"\\])*)"/g)) {
|
|
37604
37820
|
const directory = JSON.parse(`"${match[1]}"`);
|
|
37605
|
-
if (
|
|
37821
|
+
if (path39.isAbsolute(directory) && namesProject(directory)) {
|
|
37606
37822
|
await offer(trimmed(directory), "herdr");
|
|
37607
37823
|
}
|
|
37608
37824
|
}
|
|
37609
37825
|
} catch {
|
|
37610
37826
|
}
|
|
37611
37827
|
try {
|
|
37612
|
-
const config3 = await readFile15(
|
|
37828
|
+
const config3 = await readFile15(path39.join(phrenStoreRoot(env), project, "phren.project.yaml"), "utf8");
|
|
37613
37829
|
const match = /^sourcePath:\s*(.+)$/m.exec(config3);
|
|
37614
37830
|
if (match) await offer(match[1].trim().replace(/^['"]|['"]$/g, ""), "phren");
|
|
37615
37831
|
} catch {
|
|
37616
37832
|
}
|
|
37617
37833
|
const home = homedir9();
|
|
37618
|
-
for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS.map((r) =>
|
|
37619
|
-
await offer(
|
|
37834
|
+
for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS.map((r) => path39.join(home, r))]) {
|
|
37835
|
+
await offer(path39.join(root, project), "search");
|
|
37620
37836
|
}
|
|
37621
37837
|
return found.slice(0, 8);
|
|
37622
37838
|
}
|
|
@@ -37624,10 +37840,10 @@ async function locateProject(project, activity, env = process.env) {
|
|
|
37624
37840
|
// src/bridge/projects.ts
|
|
37625
37841
|
init_protocol();
|
|
37626
37842
|
init_metrics();
|
|
37627
|
-
var
|
|
37843
|
+
var exec5 = promisify5(execFile6);
|
|
37628
37844
|
async function git2(cwd, ...args) {
|
|
37629
37845
|
countGit("projects");
|
|
37630
|
-
return (await
|
|
37846
|
+
return (await exec5("git", ["-C", cwd, "--no-pager", ...args], {
|
|
37631
37847
|
timeout: 1e4,
|
|
37632
37848
|
maxBuffer: 4194304,
|
|
37633
37849
|
env: nonInteractiveGitEnv({ ...process.env, GIT_OPTIONAL_LOCKS: "0", GIT_CONFIG_NOSYSTEM: "1" })
|
|
@@ -37635,7 +37851,7 @@ async function git2(cwd, ...args) {
|
|
|
37635
37851
|
}
|
|
37636
37852
|
async function gitRoot(dir) {
|
|
37637
37853
|
try {
|
|
37638
|
-
return await
|
|
37854
|
+
return await realpath8((await git2(dir, "rev-parse", "--show-toplevel")).trim());
|
|
37639
37855
|
} catch {
|
|
37640
37856
|
return void 0;
|
|
37641
37857
|
}
|
|
@@ -37670,16 +37886,16 @@ async function committed(root, pathspec) {
|
|
|
37670
37886
|
async function resolveTouched(raw, cwd) {
|
|
37671
37887
|
if (typeof raw !== "string" || !raw || raw.length > 4096 || raw.includes("\0")) return void 0;
|
|
37672
37888
|
const home = homeDir();
|
|
37673
|
-
const absolute = raw === "~" || raw.startsWith("~/") ?
|
|
37889
|
+
const absolute = raw === "~" || raw.startsWith("~/") ? path40.join(home, raw.slice(1)) : path40.resolve(cwd, raw);
|
|
37674
37890
|
let existing = absolute, rest = [];
|
|
37675
|
-
while (!await
|
|
37676
|
-
const parent =
|
|
37891
|
+
while (!await stat13(existing).catch(() => void 0)) {
|
|
37892
|
+
const parent = path40.dirname(existing);
|
|
37677
37893
|
if (parent === existing) return void 0;
|
|
37678
|
-
rest.unshift(
|
|
37894
|
+
rest.unshift(path40.basename(existing));
|
|
37679
37895
|
existing = parent;
|
|
37680
37896
|
}
|
|
37681
|
-
const
|
|
37682
|
-
return
|
|
37897
|
+
const real2 = path40.join(await realpath8(existing), ...rest);
|
|
37898
|
+
return real2;
|
|
37683
37899
|
}
|
|
37684
37900
|
async function repositoryDiff(cwd, touched = [], allowedPaths = []) {
|
|
37685
37901
|
const root = await gitRoot(cwd);
|
|
@@ -37688,16 +37904,16 @@ async function repositoryDiff(cwd, touched = [], allowedPaths = []) {
|
|
|
37688
37904
|
const requested = [];
|
|
37689
37905
|
for (const raw of touched.slice(0, 24)) {
|
|
37690
37906
|
const file2 = await resolveTouched(raw, cwd);
|
|
37691
|
-
if (!file2 || !allowed.some((base) => file2 === base || file2.startsWith(base +
|
|
37907
|
+
if (!file2 || !allowed.some((base) => file2 === base || file2.startsWith(base + path40.sep))) throw new BridgeError(403, "This path is outside the conversation's recorded changes and commands.");
|
|
37692
37908
|
requested.push(file2);
|
|
37693
37909
|
}
|
|
37694
37910
|
const branch = (await git2(root, "branch", "--show-current")).trim();
|
|
37695
37911
|
const files = await statusFiles(root);
|
|
37696
37912
|
const byRoot = /* @__PURE__ */ new Map();
|
|
37697
37913
|
for (const file2 of requested) {
|
|
37698
|
-
const owner = await gitRoot((await
|
|
37914
|
+
const owner = await gitRoot((await stat13(file2).catch(() => void 0))?.isDirectory() ? file2 : path40.dirname(file2));
|
|
37699
37915
|
if (!owner) continue;
|
|
37700
|
-
const rel = (
|
|
37916
|
+
const rel = (path40.relative(owner, file2) || ".").split(path40.sep).join("/");
|
|
37701
37917
|
if (rel.startsWith(":")) throw new BridgeError(400, "Invalid diff pathspec.");
|
|
37702
37918
|
const list = byRoot.get(owner) ?? [];
|
|
37703
37919
|
if (!list.includes(rel)) list.push(rel);
|
|
@@ -37723,14 +37939,14 @@ async function repositoryDiff(cwd, touched = [], allowedPaths = []) {
|
|
|
37723
37939
|
async function headFile(cwd) {
|
|
37724
37940
|
let directory = cwd;
|
|
37725
37941
|
for (let depth = 0; depth < 64; depth++) {
|
|
37726
|
-
const dotGit =
|
|
37727
|
-
const info = await
|
|
37728
|
-
if (info?.isDirectory()) return
|
|
37942
|
+
const dotGit = path40.join(directory, ".git");
|
|
37943
|
+
const info = await stat13(dotGit).catch(() => void 0);
|
|
37944
|
+
if (info?.isDirectory()) return path40.join(dotGit, "HEAD");
|
|
37729
37945
|
if (info?.isFile()) {
|
|
37730
37946
|
const match = /^gitdir:\s*(.+)$/m.exec(await readFile16(dotGit, "utf8").catch(() => ""));
|
|
37731
|
-
return match ?
|
|
37947
|
+
return match ? path40.join(path40.resolve(directory, match[1].trim()), "HEAD") : void 0;
|
|
37732
37948
|
}
|
|
37733
|
-
const parent =
|
|
37949
|
+
const parent = path40.dirname(directory);
|
|
37734
37950
|
if (parent === directory) return void 0;
|
|
37735
37951
|
directory = parent;
|
|
37736
37952
|
}
|
|
@@ -37758,7 +37974,7 @@ async function repositoryBranch(cwd) {
|
|
|
37758
37974
|
let value2;
|
|
37759
37975
|
try {
|
|
37760
37976
|
countGit("branch");
|
|
37761
|
-
const { stdout } = await
|
|
37977
|
+
const { stdout } = await exec5("git", ["-C", cwd, "--no-pager", "branch", "--show-current"], {
|
|
37762
37978
|
timeout: 5e3,
|
|
37763
37979
|
maxBuffer: 65536,
|
|
37764
37980
|
env: nonInteractiveGitEnv({ ...process.env, GIT_OPTIONAL_LOCKS: "0", GIT_CONFIG_NOSYSTEM: "1" })
|
|
@@ -37817,7 +38033,7 @@ function addListener(ports, address, port, processName, pid) {
|
|
|
37817
38033
|
ports.set(`${host}:${port}`, { name: "", port, origin: `http://${host}:${port}`, process: processName, pid });
|
|
37818
38034
|
}
|
|
37819
38035
|
async function listenersFromLsof(ports) {
|
|
37820
|
-
const result = await
|
|
38036
|
+
const result = await exec5(
|
|
37821
38037
|
process.platform === "darwin" ? "/usr/sbin/lsof" : "lsof",
|
|
37822
38038
|
["-nP", "-a", "-u", userInfo2().username, "-iTCP", "-sTCP:LISTEN", "-Fpcn"],
|
|
37823
38039
|
{ timeout: 4e3, maxBuffer: 1048576 }
|
|
@@ -37833,7 +38049,7 @@ async function listenersFromLsof(ports) {
|
|
|
37833
38049
|
}
|
|
37834
38050
|
}
|
|
37835
38051
|
async function listenersFromSs(ports) {
|
|
37836
|
-
const result = await
|
|
38052
|
+
const result = await exec5("ss", ["-ltnpH"], { timeout: 4e3, maxBuffer: 1048576 });
|
|
37837
38053
|
for (const line of result.stdout.split("\n")) {
|
|
37838
38054
|
const columns = line.trim().split(/\s+/);
|
|
37839
38055
|
if (columns.length < 4) continue;
|
|
@@ -37869,24 +38085,24 @@ async function webServers() {
|
|
|
37869
38085
|
return found.sort((a, b) => a.port - b.port);
|
|
37870
38086
|
}
|
|
37871
38087
|
async function launchDirectory(raw, activity = [], located = []) {
|
|
37872
|
-
if (typeof raw !== "string" || raw.length > 4096 || !
|
|
38088
|
+
if (typeof raw !== "string" || raw.length > 4096 || !path40.isAbsolute(raw) || /[\x00-\x1f\x7f]/.test(raw)) throw new BridgeError(400, "Invalid workspace directory.");
|
|
37873
38089
|
let dir;
|
|
37874
38090
|
try {
|
|
37875
|
-
dir = await
|
|
37876
|
-
if (!(await
|
|
38091
|
+
dir = await realpath8(raw);
|
|
38092
|
+
if (!(await stat13(dir)).isDirectory()) throw new Error();
|
|
37877
38093
|
} catch {
|
|
37878
38094
|
throw new BridgeError(400, "Workspace directory does not exist.");
|
|
37879
38095
|
}
|
|
37880
|
-
const home = await
|
|
37881
|
-
if (dir === home || dir.startsWith(home +
|
|
38096
|
+
const home = await realpath8(homeDir());
|
|
38097
|
+
if (dir === home || dir.startsWith(home + path40.sep)) return dir;
|
|
37882
38098
|
for (const candidate of located) {
|
|
37883
|
-
const
|
|
37884
|
-
if (
|
|
38099
|
+
const real2 = await realpath8(candidate).catch(() => void 0);
|
|
38100
|
+
if (real2 && (dir === real2 || dir.startsWith(real2 + path40.sep))) return dir;
|
|
37885
38101
|
}
|
|
37886
|
-
const names = [...new Set(dir.split(
|
|
38102
|
+
const names = [...new Set(dir.split(path40.sep).filter((name) => /^[a-z0-9][a-z0-9-]{0,99}$/.test(name)))];
|
|
37887
38103
|
for (const name of names) {
|
|
37888
38104
|
for (const candidate of await locateProject(name, activity)) {
|
|
37889
|
-
if (dir === candidate.directory || dir.startsWith(candidate.directory +
|
|
38105
|
+
if (dir === candidate.directory || dir.startsWith(candidate.directory + path40.sep)) return dir;
|
|
37890
38106
|
}
|
|
37891
38107
|
}
|
|
37892
38108
|
throw new BridgeError(403, "Workspace directory must be under home or a located project.");
|
|
@@ -37900,7 +38116,7 @@ init_shared();
|
|
|
37900
38116
|
import { execFileSync as execFileSync3 } from "node:child_process";
|
|
37901
38117
|
import * as fs20 from "node:fs";
|
|
37902
38118
|
import { homedir as homedir10 } from "node:os";
|
|
37903
|
-
import * as
|
|
38119
|
+
import * as path41 from "node:path";
|
|
37904
38120
|
import { fileURLToPath as fileURLToPath3, pathToFileURL } from "node:url";
|
|
37905
38121
|
var CODE_PACKAGE_HINT = "phren code needs @phren/code: run phren modules enable code";
|
|
37906
38122
|
var loaded;
|
|
@@ -37909,13 +38125,13 @@ function loadedFrom() {
|
|
|
37909
38125
|
return resolvedFrom;
|
|
37910
38126
|
}
|
|
37911
38127
|
function bridgeRoot2() {
|
|
37912
|
-
return process.env.PHREN_BRIDGE_HOME ||
|
|
38128
|
+
return process.env.PHREN_BRIDGE_HOME || path41.join(homedir10(), ".local/share/phren/bridge");
|
|
37913
38129
|
}
|
|
37914
|
-
var EXTRA_PATH = [
|
|
38130
|
+
var EXTRA_PATH = [path41.join(homedir10(), ".local/share/mise/shims"), "/opt/homebrew/bin"];
|
|
37915
38131
|
function npmPath() {
|
|
37916
|
-
const entries2 = (process.env.PATH ?? "").split(
|
|
38132
|
+
const entries2 = (process.env.PATH ?? "").split(path41.delimiter).filter(Boolean);
|
|
37917
38133
|
for (const entry of EXTRA_PATH) if (!entries2.includes(entry) && fs20.existsSync(entry)) entries2.push(entry);
|
|
37918
|
-
return entries2.join(
|
|
38134
|
+
return entries2.join(path41.delimiter);
|
|
37919
38135
|
}
|
|
37920
38136
|
function npm(args, options) {
|
|
37921
38137
|
const env = { ...process.env, PATH: npmPath() };
|
|
@@ -37923,11 +38139,11 @@ function npm(args, options) {
|
|
|
37923
38139
|
return String(execFileSync3("npm.cmd", args.map((arg) => `"${arg}"`), { ...options, env, shell: true }) ?? "");
|
|
37924
38140
|
}
|
|
37925
38141
|
function packageEntry(directory) {
|
|
37926
|
-
const manifest = JSON.parse(fs20.readFileSync(
|
|
38142
|
+
const manifest = JSON.parse(fs20.readFileSync(path41.join(directory, "package.json"), "utf8"));
|
|
37927
38143
|
const exported = typeof manifest.exports === "object" && manifest.exports !== null && "." in manifest.exports ? manifest.exports["."] : manifest.exports;
|
|
37928
38144
|
const nested = typeof exported === "object" && exported !== null ? exported.default ?? exported.import : exported;
|
|
37929
38145
|
for (const candidate of [nested, manifest.module, manifest.main, "index.js", "index.mjs"]) {
|
|
37930
|
-
if (typeof candidate === "string") return
|
|
38146
|
+
if (typeof candidate === "string") return path41.join(directory, candidate);
|
|
37931
38147
|
}
|
|
37932
38148
|
throw new Error(`@phren/code has no entry point in ${directory}.`);
|
|
37933
38149
|
}
|
|
@@ -37937,7 +38153,7 @@ async function importDirectory(directory) {
|
|
|
37937
38153
|
function globalPackageDirectory() {
|
|
37938
38154
|
try {
|
|
37939
38155
|
const root = npm(["root", "-g"], { encoding: "utf8", timeout: 1e4 }).trim();
|
|
37940
|
-
return root ?
|
|
38156
|
+
return root ? path41.join(root, "@phren", "code") : void 0;
|
|
37941
38157
|
} catch {
|
|
37942
38158
|
return void 0;
|
|
37943
38159
|
}
|
|
@@ -37946,11 +38162,11 @@ async function loadCodePackage(store) {
|
|
|
37946
38162
|
if (loaded) return loaded;
|
|
37947
38163
|
const candidates = [];
|
|
37948
38164
|
if (process.env.PHREN_CODE_PACKAGE) candidates.push(process.env.PHREN_CODE_PACKAGE);
|
|
37949
|
-
candidates.push(
|
|
38165
|
+
candidates.push(path41.join(bridgeRoot2(), "node_modules", "@phren", "code"));
|
|
37950
38166
|
const root = store || process.env.PHREN_PATH;
|
|
37951
|
-
if (root) candidates.push(
|
|
38167
|
+
if (root) candidates.push(path41.join(root, ".runtime", "packages", "node_modules", "@phren", "code"));
|
|
37952
38168
|
for (const directory of candidates) {
|
|
37953
|
-
if (!fs20.existsSync(
|
|
38169
|
+
if (!fs20.existsSync(path41.join(directory, "package.json"))) continue;
|
|
37954
38170
|
try {
|
|
37955
38171
|
loaded = await importDirectory(directory);
|
|
37956
38172
|
resolvedFrom = directory;
|
|
@@ -37966,7 +38182,7 @@ async function loadCodePackage(store) {
|
|
|
37966
38182
|
if (error62.code !== "ERR_MODULE_NOT_FOUND") throw error62;
|
|
37967
38183
|
}
|
|
37968
38184
|
const global = globalPackageDirectory();
|
|
37969
|
-
if (global && fs20.existsSync(
|
|
38185
|
+
if (global && fs20.existsSync(path41.join(global, "package.json"))) {
|
|
37970
38186
|
try {
|
|
37971
38187
|
loaded = await importDirectory(global);
|
|
37972
38188
|
resolvedFrom = global;
|
|
@@ -38007,7 +38223,7 @@ var projectSchema = external_exports.string().min(1).max(100).refine((value2) =>
|
|
|
38007
38223
|
var querySchema = external_exports.string().max(500);
|
|
38008
38224
|
var symbolSchema = external_exports.string().min(1).max(4600);
|
|
38009
38225
|
var pathSchema = external_exports.string().min(1).max(4096).refine((value2) => !value2.includes("\0") && !value2.split("/").includes(".."), "Choose a valid file path.");
|
|
38010
|
-
var relativePathSchema = pathSchema.refine((value2) => !
|
|
38226
|
+
var relativePathSchema = pathSchema.refine((value2) => !path42.isAbsolute(value2) && !path42.win32.isAbsolute(value2) && !value2.includes("\\") && !value2.split("/").some((part) => part === "." || part === ""));
|
|
38011
38227
|
var optionalPath = (value2) => value2 ? relativePathSchema.parse(value2) : void 0;
|
|
38012
38228
|
var offsetSchema = external_exports.coerce.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
|
|
38013
38229
|
var kindSchema = external_exports.enum(KIND_VALUES);
|
|
@@ -38095,9 +38311,9 @@ var CodeRoutes = class {
|
|
|
38095
38311
|
};
|
|
38096
38312
|
const midnight = new Date(now);
|
|
38097
38313
|
midnight.setHours(0, 0, 0, 0);
|
|
38098
|
-
const dir =
|
|
38314
|
+
const dir = path42.join(bridgeRoot(), "changes");
|
|
38099
38315
|
const logs = fs21.existsSync(dir) ? fs21.readdirSync(dir).filter((name) => name.endsWith(".jsonl")) : [];
|
|
38100
|
-
const today = logs.map((name) => ({ file:
|
|
38316
|
+
const today = logs.map((name) => ({ file: path42.join(dir, name), at: fs21.statSync(path42.join(dir, name)).mtimeMs })).filter((entry) => entry.at >= midnight.getTime()).sort((a, b) => b.at - a.at);
|
|
38101
38317
|
for (const log2 of today) {
|
|
38102
38318
|
for (const line of fs21.readFileSync(log2.file, "utf8").split("\n")) {
|
|
38103
38319
|
if (!line.trim()) continue;
|
|
@@ -38158,7 +38374,7 @@ var CodeRoutes = class {
|
|
|
38158
38374
|
for (const file2 of untracked) {
|
|
38159
38375
|
let count2 = 0;
|
|
38160
38376
|
try {
|
|
38161
|
-
count2 = fs21.readFileSync(
|
|
38377
|
+
count2 = fs21.readFileSync(path42.join(root, file2), "utf8").split("\n").length;
|
|
38162
38378
|
} catch {
|
|
38163
38379
|
continue;
|
|
38164
38380
|
}
|
|
@@ -38188,7 +38404,7 @@ var CodeRoutes = class {
|
|
|
38188
38404
|
const project = projectSchema.parse(projectValue ?? "");
|
|
38189
38405
|
const { codeDatabasePath } = await requireCodePackage(this.store);
|
|
38190
38406
|
const file2 = codeDatabasePath(this.store, project);
|
|
38191
|
-
await Promise.all([file2, `${file2}-journal`, `${file2}-wal`, `${file2}-shm`].map((
|
|
38407
|
+
await Promise.all([file2, `${file2}-journal`, `${file2}-wal`, `${file2}-shm`].map((path85) => rm4(path85, { force: true })));
|
|
38192
38408
|
return { project, disabled: true };
|
|
38193
38409
|
}
|
|
38194
38410
|
async reindex(projectValue) {
|
|
@@ -38222,7 +38438,7 @@ var CodeRoutes = class {
|
|
|
38222
38438
|
} catch {
|
|
38223
38439
|
throw new BridgeError(400, "Choose valid paths.");
|
|
38224
38440
|
}
|
|
38225
|
-
const paths = external_exports.array(pathSchema.refine((value2) => !
|
|
38441
|
+
const paths = external_exports.array(pathSchema.refine((value2) => !path42.isAbsolute(value2) && !path42.win32.isAbsolute(value2) && !value2.split(/[\\/]/).includes(".."))).min(1).max(200).parse(raw);
|
|
38226
38442
|
const result = await (await requireCodePackage(this.store)).outlineSummary(this.store, project, [...new Set(paths)]);
|
|
38227
38443
|
if (!result.available) throw noIndex(project);
|
|
38228
38444
|
return { project, entries: result.value };
|
|
@@ -38297,7 +38513,7 @@ var CodeReindexer = class {
|
|
|
38297
38513
|
const { codeDatabasePath, resolveRepoRoot } = await requireCodePackage(this.store);
|
|
38298
38514
|
const result = [];
|
|
38299
38515
|
for (const directory of getProjectDirs(this.store)) {
|
|
38300
|
-
const project =
|
|
38516
|
+
const project = path42.basename(directory);
|
|
38301
38517
|
if (!fs21.existsSync(codeDatabasePath(this.store, project))) continue;
|
|
38302
38518
|
try {
|
|
38303
38519
|
result.push({ project, root: fs21.realpathSync(resolveRepoRoot(this.store, project)) });
|
|
@@ -38339,13 +38555,13 @@ var CodeReindexer = class {
|
|
|
38339
38555
|
};
|
|
38340
38556
|
function readHead(root) {
|
|
38341
38557
|
try {
|
|
38342
|
-
const dotGit =
|
|
38558
|
+
const dotGit = path42.join(root, ".git");
|
|
38343
38559
|
const gitDirectory2 = fs21.statSync(dotGit).isDirectory() ? dotGit : (() => {
|
|
38344
38560
|
const match = /^gitdir:\s*(.+)$/m.exec(fs21.readFileSync(dotGit, "utf8"));
|
|
38345
|
-
return match ?
|
|
38561
|
+
return match ? path42.resolve(root, match[1]) : void 0;
|
|
38346
38562
|
})();
|
|
38347
38563
|
if (!gitDirectory2) return void 0;
|
|
38348
|
-
return fs21.readFileSync(
|
|
38564
|
+
return fs21.readFileSync(path42.join(gitDirectory2, "HEAD"), "utf8").trim();
|
|
38349
38565
|
} catch {
|
|
38350
38566
|
return void 0;
|
|
38351
38567
|
}
|
|
@@ -38355,7 +38571,7 @@ function readHead(root) {
|
|
|
38355
38571
|
init_herdr();
|
|
38356
38572
|
init_protocol();
|
|
38357
38573
|
init_transcripts();
|
|
38358
|
-
import { open as
|
|
38574
|
+
import { open as open8 } from "node:fs/promises";
|
|
38359
38575
|
import { constants as constants2 } from "node:fs";
|
|
38360
38576
|
var MAX_TAIL_BYTES = 262144;
|
|
38361
38577
|
var MAX_SESSIONS = 32;
|
|
@@ -38388,15 +38604,15 @@ function codexContext(tail, startsAtBeginning) {
|
|
|
38388
38604
|
var ContextUsageReader = class {
|
|
38389
38605
|
cache = /* @__PURE__ */ new Map();
|
|
38390
38606
|
async read(file2, session) {
|
|
38391
|
-
const handle = await
|
|
38607
|
+
const handle = await open8(file2, constants2.O_RDONLY | constants2.O_NOFOLLOW | constants2.O_NONBLOCK);
|
|
38392
38608
|
try {
|
|
38393
38609
|
const metadata = await handle.stat();
|
|
38394
38610
|
if (!metadata.isFile()) return void 0;
|
|
38395
38611
|
const key2 = `codex:${session}:${file2}`;
|
|
38396
|
-
const
|
|
38612
|
+
const stat27 = `${metadata.dev}:${metadata.ino}:${metadata.size}:${metadata.mtimeMs}:${metadata.ctimeMs}`;
|
|
38397
38613
|
const cached2 = this.cache.get(key2);
|
|
38398
38614
|
this.cache.delete(key2);
|
|
38399
|
-
if (cached2?.stat ===
|
|
38615
|
+
if (cached2?.stat === stat27) {
|
|
38400
38616
|
this.cache.set(key2, cached2);
|
|
38401
38617
|
return cached2.percent;
|
|
38402
38618
|
}
|
|
@@ -38407,7 +38623,7 @@ var ContextUsageReader = class {
|
|
|
38407
38623
|
const after = await handle.stat();
|
|
38408
38624
|
if (after.size !== metadata.size || after.mtimeMs !== metadata.mtimeMs || after.ctimeMs !== metadata.ctimeMs) return void 0;
|
|
38409
38625
|
const percent = codexContext(tail, start === 0);
|
|
38410
|
-
this.cache.set(key2, { stat:
|
|
38626
|
+
this.cache.set(key2, { stat: stat27, percent });
|
|
38411
38627
|
while (this.cache.size > MAX_SESSIONS) this.cache.delete(this.cache.keys().next().value);
|
|
38412
38628
|
return percent;
|
|
38413
38629
|
} finally {
|
|
@@ -38484,33 +38700,33 @@ init_zod();
|
|
|
38484
38700
|
init_logger();
|
|
38485
38701
|
init_project_config();
|
|
38486
38702
|
import { randomUUID as randomUUID9 } from "node:crypto";
|
|
38487
|
-
import { lstat as lstat12, mkdir as mkdir12, readFile as readFile21, readdir as
|
|
38488
|
-
import
|
|
38703
|
+
import { lstat as lstat12, mkdir as mkdir12, readFile as readFile21, readdir as readdir10, realpath as realpath10, stat as stat15 } from "node:fs/promises";
|
|
38704
|
+
import path50 from "node:path";
|
|
38489
38705
|
|
|
38490
38706
|
// src/bridge/computers.ts
|
|
38491
|
-
import { execFile as
|
|
38707
|
+
import { execFile as execFile9 } from "node:child_process";
|
|
38492
38708
|
import { chmod as chmod3, lstat as lstat10, mkdir as mkdir11, mkdtemp as mkdtemp2, readFile as readFile19, rename as rename6, rm as rm5, writeFile as writeFile5 } from "node:fs/promises";
|
|
38493
38709
|
import { homedir as homedir14 } from "node:os";
|
|
38494
|
-
import
|
|
38495
|
-
import { promisify as
|
|
38710
|
+
import path48 from "node:path";
|
|
38711
|
+
import { promisify as promisify8 } from "node:util";
|
|
38496
38712
|
|
|
38497
38713
|
// src/bridge/install.ts
|
|
38498
38714
|
init_shared();
|
|
38499
|
-
import { execFile as
|
|
38715
|
+
import { execFile as execFile8 } from "node:child_process";
|
|
38500
38716
|
|
|
38501
38717
|
// src/bridge/usage.ts
|
|
38502
38718
|
init_home_paths();
|
|
38503
38719
|
init_fanouts();
|
|
38504
38720
|
init_protocol();
|
|
38505
38721
|
init_terminal_text();
|
|
38506
|
-
import { execFile as
|
|
38722
|
+
import { execFile as execFile7, spawn as spawn2 } from "node:child_process";
|
|
38507
38723
|
import { createHash as createHash9 } from "node:crypto";
|
|
38508
|
-
import { lstat as lstat8, open as
|
|
38724
|
+
import { lstat as lstat8, open as open9, readFile as readFile17, readdir as readdir9, realpath as realpath9, stat as stat14 } from "node:fs/promises";
|
|
38509
38725
|
import { homedir as homedir11 } from "node:os";
|
|
38510
|
-
import
|
|
38511
|
-
import { promisify as
|
|
38512
|
-
var
|
|
38513
|
-
var claudeFile = () =>
|
|
38726
|
+
import path44 from "node:path";
|
|
38727
|
+
import { promisify as promisify6 } from "node:util";
|
|
38728
|
+
var exec6 = promisify6(execFile7);
|
|
38729
|
+
var claudeFile = () => path44.join(bridgeRoot(), "usage", "claude.json");
|
|
38514
38730
|
var safeText = (v) => typeof v === "string" ? v.replace(/[\x00-\x1f\x7f]/g, "").slice(0, 100) : void 0;
|
|
38515
38731
|
function window(id2, name, percent, reset) {
|
|
38516
38732
|
if (typeof percent !== "number" || !Number.isFinite(percent) || percent < 0 || percent > 100) return;
|
|
@@ -38553,7 +38769,7 @@ function openCodeUsage(output2, now = /* @__PURE__ */ new Date()) {
|
|
|
38553
38769
|
}
|
|
38554
38770
|
async function readOpenCodeUsage(executable = "opencode", now = /* @__PURE__ */ new Date()) {
|
|
38555
38771
|
try {
|
|
38556
|
-
const { stdout } = await
|
|
38772
|
+
const { stdout } = await exec6(executable, ["stats", "--days", "7", "--pure"], { timeout: 12e3, maxBuffer: 1048576 });
|
|
38557
38773
|
return openCodeUsage(stdout, now);
|
|
38558
38774
|
} catch (error62) {
|
|
38559
38775
|
return { source: "opencode", windows: [], message: openCodeFailure(error62) };
|
|
@@ -38569,16 +38785,16 @@ function openCodeFailure(error62) {
|
|
|
38569
38785
|
const exit = typeof failure2?.code === "number" ? ` (exit ${failure2.code})` : "";
|
|
38570
38786
|
return `opencode stats --days 7 failed${exit}${said ? `: ${said}` : ""}. Run it on this computer to see why.`;
|
|
38571
38787
|
}
|
|
38572
|
-
var openCodeAuthFile = () =>
|
|
38573
|
-
process.env.OPENCODE_DATA_DIR ||
|
|
38788
|
+
var openCodeAuthFile = () => path44.join(
|
|
38789
|
+
process.env.OPENCODE_DATA_DIR || path44.join(process.env.XDG_DATA_HOME || path44.join(homedir11(), ".local", "share"), "opencode"),
|
|
38574
38790
|
"auth.json"
|
|
38575
38791
|
);
|
|
38576
38792
|
async function readOpenRouterKey() {
|
|
38577
38793
|
try {
|
|
38578
|
-
const handle = await
|
|
38794
|
+
const handle = await open9(openCodeAuthFile(), "r");
|
|
38579
38795
|
try {
|
|
38580
|
-
const
|
|
38581
|
-
if (!
|
|
38796
|
+
const stat27 = await handle.stat();
|
|
38797
|
+
if (!stat27.isFile() || stat27.size > 65536) return void 0;
|
|
38582
38798
|
const key2 = object2(object2(JSON.parse(await handle.readFile("utf8"))).openrouter).key;
|
|
38583
38799
|
return typeof key2 === "string" && key2.length >= 16 && key2.length <= 4096 && !/[\x00-\x1f\x7f]/.test(key2) ? key2 : void 0;
|
|
38584
38800
|
} finally {
|
|
@@ -38590,7 +38806,7 @@ async function readOpenRouterKey() {
|
|
|
38590
38806
|
}
|
|
38591
38807
|
async function readOpenCodeGoKey() {
|
|
38592
38808
|
try {
|
|
38593
|
-
const handle = await
|
|
38809
|
+
const handle = await open9(openCodeAuthFile(), "r");
|
|
38594
38810
|
try {
|
|
38595
38811
|
const metadata = await handle.stat();
|
|
38596
38812
|
if (!metadata.isFile() || metadata.size > 65536) return void 0;
|
|
@@ -38763,9 +38979,9 @@ async function containedRegularFile(root, candidate, maximum) {
|
|
|
38763
38979
|
try {
|
|
38764
38980
|
const link = await lstat8(candidate);
|
|
38765
38981
|
if (!link.isFile() || link.isSymbolicLink() || link.size > maximum) return void 0;
|
|
38766
|
-
const resolved = await
|
|
38767
|
-
if (!resolved.startsWith(root +
|
|
38768
|
-
const metadata = await
|
|
38982
|
+
const resolved = await realpath9(candidate);
|
|
38983
|
+
if (!resolved.startsWith(root + path44.sep)) return void 0;
|
|
38984
|
+
const metadata = await stat14(resolved);
|
|
38769
38985
|
return metadata.isFile() && metadata.size <= maximum ? resolved : void 0;
|
|
38770
38986
|
} catch {
|
|
38771
38987
|
return void 0;
|
|
@@ -38795,14 +39011,14 @@ async function readOpenCodeGoLedger(root = fanoutRoot(), now = /* @__PURE__ */ n
|
|
|
38795
39011
|
const totals = /* @__PURE__ */ new Map();
|
|
38796
39012
|
let directory;
|
|
38797
39013
|
try {
|
|
38798
|
-
directory = await
|
|
39014
|
+
directory = await realpath9(root);
|
|
38799
39015
|
} catch {
|
|
38800
39016
|
return totals;
|
|
38801
39017
|
}
|
|
38802
|
-
const names = (await
|
|
39018
|
+
const names = (await readdir9(directory).catch(() => [])).slice(0, MAX_GO_JOBS);
|
|
38803
39019
|
for (const name of names) {
|
|
38804
39020
|
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(name)) continue;
|
|
38805
|
-
const manifestFile = await containedRegularFile(directory,
|
|
39021
|
+
const manifestFile = await containedRegularFile(directory, path44.join(directory, name, "manifest.json"), MAX_GO_MANIFEST_BYTES);
|
|
38806
39022
|
if (!manifestFile) continue;
|
|
38807
39023
|
let manifest;
|
|
38808
39024
|
try {
|
|
@@ -38813,9 +39029,9 @@ async function readOpenCodeGoLedger(root = fanoutRoot(), now = /* @__PURE__ */ n
|
|
|
38813
39029
|
const model = goModel(manifest.model);
|
|
38814
39030
|
const eventLog = typeof manifest.eventLog === "string" && /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}\.jsonl$/.test(manifest.eventLog) ? manifest.eventLog : void 0;
|
|
38815
39031
|
if (manifest.provider !== "opencode" || !model || !eventLog) continue;
|
|
38816
|
-
const jobRoot = await
|
|
38817
|
-
if (!jobRoot || !jobRoot.startsWith(directory +
|
|
38818
|
-
const eventsFile = await containedRegularFile(jobRoot,
|
|
39032
|
+
const jobRoot = await realpath9(path44.join(directory, name)).catch(() => void 0);
|
|
39033
|
+
if (!jobRoot || !jobRoot.startsWith(directory + path44.sep)) continue;
|
|
39034
|
+
const eventsFile = await containedRegularFile(jobRoot, path44.join(jobRoot, eventLog), MAX_GO_EVENTS_BYTES);
|
|
38819
39035
|
if (!eventsFile) continue;
|
|
38820
39036
|
let events;
|
|
38821
39037
|
try {
|
|
@@ -38992,8 +39208,8 @@ function claudeScopedWindows(config3, now = /* @__PURE__ */ new Date()) {
|
|
|
38992
39208
|
}
|
|
38993
39209
|
return windows;
|
|
38994
39210
|
}
|
|
38995
|
-
var claudeConfigFile = () =>
|
|
38996
|
-
var claudeCredentialsFile = () =>
|
|
39211
|
+
var claudeConfigFile = () => path44.join(process.env.CLAUDE_CONFIG_DIR?.trim() ? claudeConfigDir() : homeDir(), ".claude.json");
|
|
39212
|
+
var claudeCredentialsFile = () => path44.join(claudeConfigDir(), ".credentials.json");
|
|
38997
39213
|
function claudeOAuthUsage(value2, now = /* @__PURE__ */ new Date()) {
|
|
38998
39214
|
const limits = object2(value2).limits;
|
|
38999
39215
|
const windows = [];
|
|
@@ -39024,7 +39240,7 @@ function claudeOAuthUsage(value2, now = /* @__PURE__ */ new Date()) {
|
|
|
39024
39240
|
...!windows.length ? { message: "Claude has not reported account limits on this computer." } : {}
|
|
39025
39241
|
};
|
|
39026
39242
|
}
|
|
39027
|
-
async function readClaudeToken(execSecurity =
|
|
39243
|
+
async function readClaudeToken(execSecurity = exec6, platform = process.platform) {
|
|
39028
39244
|
const parse4 = (raw) => {
|
|
39029
39245
|
if (raw.length > 16384) return void 0;
|
|
39030
39246
|
const oauth = object2(object2(JSON.parse(raw)).claudeAiOauth);
|
|
@@ -39200,10 +39416,10 @@ var AccountUsageReader = class {
|
|
|
39200
39416
|
async snapshotClaude() {
|
|
39201
39417
|
let claude2 = { source: "claude", windows: [], message: "Usage appears after Claude Code replies on this computer. Run phren bridge install if usage reporting is not set up yet." };
|
|
39202
39418
|
try {
|
|
39203
|
-
const handle = await
|
|
39419
|
+
const handle = await open9(claudeFile(), "r");
|
|
39204
39420
|
try {
|
|
39205
|
-
const
|
|
39206
|
-
if (!
|
|
39421
|
+
const stat27 = await handle.stat();
|
|
39422
|
+
if (!stat27.isFile() || stat27.size > 16384) throw new Error("Invalid usage snapshot");
|
|
39207
39423
|
const saved = object2(JSON.parse(await handle.readFile("utf8")));
|
|
39208
39424
|
const date5 = new Date(String(saved.updatedAt));
|
|
39209
39425
|
if (!Number.isFinite(date5.getTime()) || date5.getTime() > this.now() + 6e4) throw new Error("Invalid usage timestamp");
|
|
@@ -39214,10 +39430,10 @@ var AccountUsageReader = class {
|
|
|
39214
39430
|
} catch {
|
|
39215
39431
|
}
|
|
39216
39432
|
try {
|
|
39217
|
-
const handle = await
|
|
39433
|
+
const handle = await open9(claudeConfigFile(), "r");
|
|
39218
39434
|
try {
|
|
39219
|
-
const
|
|
39220
|
-
if (!
|
|
39435
|
+
const stat27 = await handle.stat();
|
|
39436
|
+
if (!stat27.isFile() || stat27.size > 16777216) throw new Error("Invalid Claude config");
|
|
39221
39437
|
const scoped = claudeScopedWindows(JSON.parse(await handle.readFile("utf8")), new Date(this.now())).filter((entry) => !claude2.windows.some((existing) => existing.id === entry.id));
|
|
39222
39438
|
if (scoped.length) claude2 = { ...claude2, windows: [...claude2.windows, ...scoped], message: void 0 };
|
|
39223
39439
|
} finally {
|
|
@@ -39277,11 +39493,11 @@ async function captureClaudeUsage(original) {
|
|
|
39277
39493
|
init_home_paths();
|
|
39278
39494
|
init_protocol();
|
|
39279
39495
|
init_herdr();
|
|
39280
|
-
import { chmod as chmod2, copyFile as copyFile2, mkdir as mkdir10, open as
|
|
39496
|
+
import { chmod as chmod2, copyFile as copyFile2, mkdir as mkdir10, open as open10, readFile as readFile18, rename as rename5, symlink, unlink as unlink4, lstat as lstat9, writeFile as writeFile4 } from "node:fs/promises";
|
|
39281
39497
|
import { homedir as homedir13 } from "node:os";
|
|
39282
|
-
import
|
|
39498
|
+
import path47 from "node:path";
|
|
39283
39499
|
import { fileURLToPath as fileURLToPath5 } from "node:url";
|
|
39284
|
-
import { promisify as
|
|
39500
|
+
import { promisify as promisify7 } from "node:util";
|
|
39285
39501
|
|
|
39286
39502
|
// src/bridge/transport.ts
|
|
39287
39503
|
init_shared();
|
|
@@ -39292,17 +39508,17 @@ import { connect as connect3 } from "node:net";
|
|
|
39292
39508
|
import { request as request3 } from "node:http";
|
|
39293
39509
|
import { spawn as spawn3 } from "node:child_process";
|
|
39294
39510
|
import { homedir as homedir12 } from "node:os";
|
|
39295
|
-
import
|
|
39511
|
+
import path45 from "node:path";
|
|
39296
39512
|
function decodeShellDirectory(encoded) {
|
|
39297
39513
|
if (!/^[A-Za-z0-9_-]{1,8192}$/.test(encoded)) return void 0;
|
|
39298
39514
|
const decoded = Buffer.from(encoded, "base64url");
|
|
39299
39515
|
if (decoded.toString("base64url") !== encoded) return void 0;
|
|
39300
39516
|
const dir = decoded.toString("utf8");
|
|
39301
|
-
return
|
|
39517
|
+
return path45.isAbsolute(dir) && !/[\x00-\x1f\x7f]/.test(dir) && !dir.includes("\uFFFD") ? dir : void 0;
|
|
39302
39518
|
}
|
|
39303
39519
|
function shellEnvironment(base = process.env) {
|
|
39304
39520
|
const env = Object.fromEntries(Object.entries(base).filter(([key2]) => !key2.startsWith("HERDR_") && key2 !== "TMUX" && key2 !== "TMUX_PANE"));
|
|
39305
|
-
env.PATH = [
|
|
39521
|
+
env.PATH = [path45.join(homedir12(), ".local/bin"), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin"].join(":");
|
|
39306
39522
|
return env;
|
|
39307
39523
|
}
|
|
39308
39524
|
async function health() {
|
|
@@ -39363,7 +39579,7 @@ async function dispatch(command) {
|
|
|
39363
39579
|
};
|
|
39364
39580
|
if (command === "phren-hook v1 pipe") {
|
|
39365
39581
|
requireHook();
|
|
39366
|
-
await pipe2({ path: socketPath() },
|
|
39582
|
+
await pipe2({ path: socketPath() }, path45.join(bridgeRoot(), "gateway.json"), true);
|
|
39367
39583
|
return;
|
|
39368
39584
|
}
|
|
39369
39585
|
const preview = /^phren-hook v1 web (127\.0\.0\.1|::1) ([1-9][0-9]{0,4})$/.exec(command);
|
|
@@ -39379,7 +39595,7 @@ async function dispatch(command) {
|
|
|
39379
39595
|
if (!raw) throw new BridgeError(403, "The shell folder is not a valid absolute path.");
|
|
39380
39596
|
const cwd = await launchDirectory(raw);
|
|
39381
39597
|
if (!process.stdin.isTTY || !process.stdout.isTTY) throw new Error("Request an SSH terminal first.");
|
|
39382
|
-
const login = process.env.SHELL &&
|
|
39598
|
+
const login = process.env.SHELL && path45.isAbsolute(process.env.SHELL) ? process.env.SHELL : "/bin/sh";
|
|
39383
39599
|
const [file2, args] = shell[2] ? [shell[2], []] : [login, ["-l"]];
|
|
39384
39600
|
await attach(file2, args, { cwd, env: shellEnvironment() }, shell[2] ? `${shell[2]} exited.` : "The shell exited.");
|
|
39385
39601
|
return;
|
|
@@ -39413,7 +39629,7 @@ async function attach(file2, args, options, failure2) {
|
|
|
39413
39629
|
}
|
|
39414
39630
|
|
|
39415
39631
|
// src/bridge/install.ts
|
|
39416
|
-
var
|
|
39632
|
+
var exec7 = promisify7(execFile8);
|
|
39417
39633
|
var label = "com.phren.hook";
|
|
39418
39634
|
var unit = "phren-hook.service";
|
|
39419
39635
|
var forcedCommand = 'command="sh ~/.local/share/phren/bridge/dispatch"';
|
|
@@ -39458,7 +39674,7 @@ var xml = (s) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, "&
|
|
|
39458
39674
|
var systemdQuote = (s) => '"' + s.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%") + '"';
|
|
39459
39675
|
async function commandOutput(file2, args, env) {
|
|
39460
39676
|
try {
|
|
39461
|
-
const { stdout, stderr } = await
|
|
39677
|
+
const { stdout, stderr } = await exec7(file2, args, { env, timeout: 2e3 });
|
|
39462
39678
|
return stdout + stderr || void 0;
|
|
39463
39679
|
} catch (error62) {
|
|
39464
39680
|
const value2 = error62;
|
|
@@ -39491,9 +39707,9 @@ ${pipe3}exec ${quote2(node2)} ${quote2(bundle)} ssh
|
|
|
39491
39707
|
}
|
|
39492
39708
|
async function activate(version3) {
|
|
39493
39709
|
const root = bridgeRoot();
|
|
39494
|
-
const next =
|
|
39495
|
-
await symlink(
|
|
39496
|
-
await rename5(next,
|
|
39710
|
+
const next = path47.join(root, `current-${process.pid}`);
|
|
39711
|
+
await symlink(path47.join("versions", version3), next);
|
|
39712
|
+
await rename5(next, path47.join(root, "current"));
|
|
39497
39713
|
}
|
|
39498
39714
|
function launchDomain(uid, guiSession2) {
|
|
39499
39715
|
return guiSession2 ? `gui/${uid}` : `user/${uid}`;
|
|
@@ -39501,15 +39717,15 @@ function launchDomain(uid, guiSession2) {
|
|
|
39501
39717
|
function launchCommands(domain2, plist) {
|
|
39502
39718
|
return [`launchctl bootout ${domain2}/${label}`, `launchctl bootstrap ${domain2} ${quote2(plist)}`, `launchctl kickstart -k ${domain2}/${label}`];
|
|
39503
39719
|
}
|
|
39504
|
-
var launchAgentPlist = () =>
|
|
39720
|
+
var launchAgentPlist = () => path47.join(homedir13(), "Library/LaunchAgents", `${label}.plist`);
|
|
39505
39721
|
async function guiSession(uid) {
|
|
39506
|
-
return
|
|
39722
|
+
return exec7("launchctl", ["print", `gui/${uid}`]).then(() => true, () => false);
|
|
39507
39723
|
}
|
|
39508
39724
|
async function stopService() {
|
|
39509
39725
|
if (process.platform === "darwin") {
|
|
39510
|
-
for (const gui of [true, false]) await
|
|
39726
|
+
for (const gui of [true, false]) await exec7("launchctl", ["bootout", `${launchDomain(process.getuid(), gui)}/${label}`]).catch(() => {
|
|
39511
39727
|
});
|
|
39512
|
-
} else await
|
|
39728
|
+
} else await exec7("systemctl", ["--user", "stop", unit]).catch(() => {
|
|
39513
39729
|
});
|
|
39514
39730
|
}
|
|
39515
39731
|
async function startService() {
|
|
@@ -39517,7 +39733,7 @@ async function startService() {
|
|
|
39517
39733
|
const uid = process.getuid(), gui = await guiSession(uid), domain2 = launchDomain(uid, gui);
|
|
39518
39734
|
for (let attempt = 0; ; attempt++) {
|
|
39519
39735
|
try {
|
|
39520
|
-
await
|
|
39736
|
+
await exec7("launchctl", ["bootstrap", domain2, launchAgentPlist()]);
|
|
39521
39737
|
break;
|
|
39522
39738
|
} catch (error62) {
|
|
39523
39739
|
const stderr = String(error62.stderr ?? "");
|
|
@@ -39530,12 +39746,12 @@ To start it by hand:
|
|
|
39530
39746
|
${launchCommands(domain2, launchAgentPlist()).join("\n ")}`);
|
|
39531
39747
|
}
|
|
39532
39748
|
}
|
|
39533
|
-
await
|
|
39749
|
+
await exec7("launchctl", ["kickstart", `${domain2}/${label}`]).catch(() => {
|
|
39534
39750
|
});
|
|
39535
39751
|
if (!gui) console.log(`No one is logged in at this Mac's screen, so the Phren Hook runs in ${domain2}. After a screen login, run phren bridge install again to move it into gui/${uid}.`);
|
|
39536
39752
|
} else {
|
|
39537
|
-
await
|
|
39538
|
-
await
|
|
39753
|
+
await exec7("systemctl", ["--user", "daemon-reload"]);
|
|
39754
|
+
await exec7("systemctl", ["--user", "enable", "--now", unit]);
|
|
39539
39755
|
}
|
|
39540
39756
|
}
|
|
39541
39757
|
async function install(version3, noService = false) {
|
|
@@ -39543,52 +39759,52 @@ async function install(version3, noService = false) {
|
|
|
39543
39759
|
if (!/^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(version3)) throw new Error("Invalid helper version.");
|
|
39544
39760
|
const modules = activateModules(defaultPhrenPath(), void 0, true);
|
|
39545
39761
|
if (!modules.has("hook")) throw new Error(disabledHint("hook"));
|
|
39546
|
-
const root = bridgeRoot(), herdr = herdrRoot(), versions =
|
|
39762
|
+
const root = bridgeRoot(), herdr = herdrRoot(), versions = path47.join(root, "versions");
|
|
39547
39763
|
await mkdir10(versions, { recursive: true, mode: 448 });
|
|
39548
39764
|
await chmod2(root, 448);
|
|
39549
|
-
const serviceLog =
|
|
39550
|
-
const log2 = await
|
|
39765
|
+
const serviceLog = path47.join(root, "service.log");
|
|
39766
|
+
const log2 = await open10(serviceLog, "a", 384);
|
|
39551
39767
|
try {
|
|
39552
39768
|
await log2.chmod(384);
|
|
39553
39769
|
} finally {
|
|
39554
39770
|
await log2.close();
|
|
39555
39771
|
}
|
|
39556
|
-
const hookEdits = await planAgentHooks(
|
|
39772
|
+
const hookEdits = await planAgentHooks(path47.join(root, "current/bridge-hook.mjs"), false, modules);
|
|
39557
39773
|
const own2 = fileURLToPath5(import.meta.url);
|
|
39558
|
-
const bundle = own2.endsWith("bridge-hook.mjs") ? own2 :
|
|
39559
|
-
const destination2 =
|
|
39774
|
+
const bundle = own2.endsWith("bridge-hook.mjs") ? own2 : path47.join(path47.dirname(own2), "..", "bridge-hook.mjs");
|
|
39775
|
+
const destination2 = path47.join(versions, version3);
|
|
39560
39776
|
await mkdir10(destination2, { recursive: true, mode: 448 });
|
|
39561
|
-
const installedBundle =
|
|
39777
|
+
const installedBundle = path47.join(destination2, "bridge-hook.mjs");
|
|
39562
39778
|
const previousBundle = await missingFile(readFile18(installedBundle));
|
|
39563
39779
|
const stagedBundle = installedBundle + `.phren-${process.pid}`;
|
|
39564
39780
|
await copyFile2(bundle, stagedBundle);
|
|
39565
39781
|
await rename5(stagedBundle, installedBundle);
|
|
39566
|
-
const previous = await readFile18(
|
|
39782
|
+
const previous = await readFile18(path47.join(root, "installed.json"), "utf8").then((v) => JSON.parse(v)).catch(() => null);
|
|
39567
39783
|
const gateway = await detectGateway();
|
|
39568
|
-
await atomic(
|
|
39784
|
+
await atomic(path47.join(root, "dispatch"), gatewayScript(gateway, {
|
|
39569
39785
|
root,
|
|
39570
39786
|
herdr,
|
|
39571
39787
|
store: modules.store,
|
|
39572
39788
|
profile: modules.profile,
|
|
39573
39789
|
node: process.execPath,
|
|
39574
|
-
bundle:
|
|
39790
|
+
bundle: path47.join(root, "current/bridge-hook.mjs"),
|
|
39575
39791
|
socket: socketPath(),
|
|
39576
|
-
timing:
|
|
39792
|
+
timing: path47.join(root, "gateway.json")
|
|
39577
39793
|
}), 448);
|
|
39578
|
-
const environmentPath = [
|
|
39579
|
-
const program =
|
|
39794
|
+
const environmentPath = [path47.dirname(process.execPath), path47.join(homedir13(), ".local/bin"), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin"].join(":");
|
|
39795
|
+
const program = path47.join(root, "current/bridge-hook.mjs");
|
|
39580
39796
|
if (!noService) {
|
|
39581
39797
|
if (process.platform === "darwin") {
|
|
39582
|
-
const folder =
|
|
39798
|
+
const folder = path47.join(homedir13(), "Library/LaunchAgents");
|
|
39583
39799
|
await mkdir10(folder, { recursive: true });
|
|
39584
|
-
await atomic(
|
|
39800
|
+
await atomic(path47.join(folder, `${label}.plist`), `<?xml version="1.0" encoding="UTF-8"?>
|
|
39585
39801
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
39586
|
-
<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>Umask</key><integer>63</integer><key>RunAtLoad</key><true/><key>KeepAlive</key><true/><key>ThrottleInterval</key><integer>5</integer><key>Nice</key><integer>-5</integer><key>EnvironmentVariables</key><dict><key>PATH</key><string>${xml(environmentPath)}</string><key>PHREN_BRIDGE_HOME</key><string>${xml(root)}</string><key>PHREN_HERDR_HOME</key><string>${xml(herdr)}</string><key>PHREN_PATH</key><string>${xml(modules.store)}</string><key>PHREN_PROFILE</key><string>${xml(modules.profile)}</string></dict><key>StandardErrorPath</key><string>${xml(
|
|
39802
|
+
<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>Umask</key><integer>63</integer><key>RunAtLoad</key><true/><key>KeepAlive</key><true/><key>ThrottleInterval</key><integer>5</integer><key>Nice</key><integer>-5</integer><key>EnvironmentVariables</key><dict><key>PATH</key><string>${xml(environmentPath)}</string><key>PHREN_BRIDGE_HOME</key><string>${xml(root)}</string><key>PHREN_HERDR_HOME</key><string>${xml(herdr)}</string><key>PHREN_PATH</key><string>${xml(modules.store)}</string><key>PHREN_PROFILE</key><string>${xml(modules.profile)}</string></dict><key>StandardErrorPath</key><string>${xml(path47.join(root, "service.log"))}</string></dict></plist>
|
|
39587
39803
|
`);
|
|
39588
39804
|
} else {
|
|
39589
|
-
const folder =
|
|
39805
|
+
const folder = path47.join(homedir13(), ".config/systemd/user");
|
|
39590
39806
|
await mkdir10(folder, { recursive: true });
|
|
39591
|
-
await atomic(
|
|
39807
|
+
await atomic(path47.join(folder, unit), `[Unit]
|
|
39592
39808
|
Description=Phren Hook
|
|
39593
39809
|
[Service]
|
|
39594
39810
|
ExecStart=${systemdQuote(process.execPath)} ${systemdQuote(program)} serve
|
|
@@ -39630,7 +39846,7 @@ WantedBy=default.target
|
|
|
39630
39846
|
if ((await Promise.resolve().then(() => (init_agent_package(), agent_package_exports))).agentInstalled()) {
|
|
39631
39847
|
console.log("phren-agent chat: found; it reports to this Hook itself, so restart any phren-agent session started before now.");
|
|
39632
39848
|
}
|
|
39633
|
-
const keys =
|
|
39849
|
+
const keys = path47.join(homedir13(), ".ssh/authorized_keys");
|
|
39634
39850
|
const keyStat = await lstat9(keys).catch(() => null);
|
|
39635
39851
|
if (keyStat && !keyStat.isSymbolicLink() && keyStat.isFile()) {
|
|
39636
39852
|
const before = await readFile18(keys, "utf8"), after = upgradeKeys(before);
|
|
@@ -39641,7 +39857,7 @@ WantedBy=default.target
|
|
|
39641
39857
|
}
|
|
39642
39858
|
console.log(`Updated ${after.changed} Phren iPhone key(s); other keys were preserved.`);
|
|
39643
39859
|
}
|
|
39644
|
-
await atomic(
|
|
39860
|
+
await atomic(path47.join(root, "installed.json"), JSON.stringify({ version: version3, previous: previous?.version === version3 ? previous.previous : previous?.version, node: process.execPath, gateway }, null, 2) + "\n");
|
|
39645
39861
|
console.log("Agent hooks installed. In Codex, review the new Phren entries in /hooks. Existing agents may need to resume before new hooks load.");
|
|
39646
39862
|
console.log(`SSH gateway: ${gateway}${gateway === "node" ? " (no socat or nc -U found)" : ""}.`);
|
|
39647
39863
|
console.log(`Phren Hook ${version3} installed${noService ? " (service not started)" : " and running"}. Run phren bridge doctor.`);
|
|
@@ -39664,14 +39880,14 @@ async function uninstall() {
|
|
|
39664
39880
|
if (process.platform === "darwin") await unlink4(launchAgentPlist()).catch(() => {
|
|
39665
39881
|
});
|
|
39666
39882
|
else {
|
|
39667
|
-
await
|
|
39883
|
+
await exec7("systemctl", ["--user", "disable", unit]).catch(() => {
|
|
39668
39884
|
});
|
|
39669
|
-
await unlink4(
|
|
39885
|
+
await unlink4(path47.join(homedir13(), ".config/systemd/user", unit)).catch(() => {
|
|
39670
39886
|
});
|
|
39671
|
-
await
|
|
39887
|
+
await exec7("systemctl", ["--user", "daemon-reload"]).catch(() => {
|
|
39672
39888
|
});
|
|
39673
39889
|
}
|
|
39674
|
-
await applyAgentHooks(await planAgentHooks(
|
|
39890
|
+
await applyAgentHooks(await planAgentHooks(path47.join(bridgeRoot(), "current/bridge-hook.mjs"), true));
|
|
39675
39891
|
await applyOpencodePlugin(true);
|
|
39676
39892
|
console.log("Phren Hook stopped and its background service removed. Remove phren-iphone, phren-android and phren-computer keys from authorized_keys to revoke device access. Local data remains in " + bridgeRoot());
|
|
39677
39893
|
}
|
|
@@ -39686,9 +39902,9 @@ async function missingFile(operation) {
|
|
|
39686
39902
|
async function planAgentHooks(program, remove = false, modules) {
|
|
39687
39903
|
const edits = [];
|
|
39688
39904
|
for (const [source, file2] of [
|
|
39689
|
-
["codex",
|
|
39690
|
-
["claude",
|
|
39691
|
-
["copilot",
|
|
39905
|
+
["codex", path47.join(codexHome(), "hooks.json")],
|
|
39906
|
+
["claude", path47.join(claudeConfigDir(), "settings.json")],
|
|
39907
|
+
["copilot", path47.join(process.env.COPILOT_HOME || path47.join(homedir13(), ".copilot"), "hooks/phren.json")]
|
|
39692
39908
|
]) {
|
|
39693
39909
|
const metadata = await missingFile(lstat9(file2));
|
|
39694
39910
|
if (metadata && (!metadata.isFile() || metadata.isSymbolicLink() || metadata.size > 2097152)) {
|
|
@@ -39738,7 +39954,7 @@ async function planAgentHooks(program, remove = false, modules) {
|
|
|
39738
39954
|
}
|
|
39739
39955
|
return edits;
|
|
39740
39956
|
}
|
|
39741
|
-
var opencodePluginsDir = () =>
|
|
39957
|
+
var opencodePluginsDir = () => path47.join(process.env.XDG_CONFIG_HOME || path47.join(homedir13(), ".config"), "opencode", "plugins");
|
|
39742
39958
|
var OPENCODE_PLUGIN_MARKER = "// Installed by Phren Hook";
|
|
39743
39959
|
function opencodePluginNeedsWrite(existing, source) {
|
|
39744
39960
|
if (existing === void 0) return true;
|
|
@@ -39747,10 +39963,10 @@ function opencodePluginNeedsWrite(existing, source) {
|
|
|
39747
39963
|
}
|
|
39748
39964
|
async function opencodePluginSource() {
|
|
39749
39965
|
if (true) return '// Installed by Phren Hook and replaced on every update. Copy it under another name to customize.\nimport { lstatSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";\nimport { homedir } from "node:os";\nimport path from "node:path";\n\nconst PHREN_STORE = "__PHREN_STORE__";\nconst FLUSH_MS = 250;\nconst MAX_TOOL_OUTPUT = 200_000;\n// OpenCode\'s read tool returns a picture as an inline data URL on the tool\n// part (`state.attachments`). The Hook serves images up to 8 MiB; the session\n// budget bounds what every flush rewrites.\nconst MAX_IMAGE_DATA = 4_000_000;\nconst MAX_SESSION_IMAGE_DATA = 24_000_000;\nconst IMAGE_DATA_URL = /^data:(image\\/(?:png|jpeg|gif|webp));base64,([A-Za-z0-9+/=]+)$/;\nconst STOP_REASONS = { stop: "end_turn", "tool-calls": "tool_use", length: "max_tokens" };\nconst OPENCODE_SESSION = /^ses_[0-9A-Za-z]{1,64}$/;\nconst APPROVAL_POLL_MS = 200;\nconst APPROVAL_DEADLINE_MS = 50_000;\n\nfunction storeRoot() {\n if (PHREN_STORE && !PHREN_STORE.startsWith("__")) return PHREN_STORE;\n const configured = process.env.PHREN_PATH?.trim();\n if (!configured) return path.join(homedir(), ".phren");\n const expanded = configured === "~" ? homedir() : configured.startsWith("~/") ? path.join(homedir(), configured.slice(2)) : configured;\n return path.resolve(expanded);\n}\n\nfunction text(value) {\n return typeof value === "string" ? value : "";\n}\n\nfunction approvalDirectory() {\n return path.join(storeRoot(), ".runtime", "approvals");\n}\n\nfunction fanoutDirectory() {\n const configured = process.env.PHREN_FANOUT_DIR?.trim();\n if (configured) return path.resolve(configured);\n return path.join(storeRoot(), ".runtime", "agent-fanouts", text(process.env.PHREN_FANOUT_JOB));\n}\n\nfunction fanoutPatterns(input) {\n const value = input?.pattern;\n if (Array.isArray(value)) return value.filter(entry => typeof entry === "string" && entry);\n return typeof value === "string" && value ? [value] : [];\n}\n\n/** The worktree\'s grandparent is the scratch root the fan-out launcher owns:\n * external reads and writes are allowed only inside it. */\nfunction underScratchRoot(value) {\n const scratch = path.dirname(path.dirname(path.resolve(process.cwd())));\n if (scratch === path.parse(scratch).root) return false;\n const resolved = path.resolve(scratch, value);\n return resolved === scratch || resolved.startsWith(scratch + path.sep);\n}\n\nfunction under(parent, value) {\n if (!parent || parent === path.parse(parent).root) return false;\n const root = path.resolve(parent), resolved = path.resolve(root, value);\n return resolved === root || resolved.startsWith(root + path.sep);\n}\n\n/** Beyond the scratch root, a worker legitimately reads its own machine: the\n * node_modules its worktree links into the main checkout, the store it was\n * briefed from, the toolchains a build shells out to, and the temporary\n * directories those builds write. Everything outside this set is refused. */\nfunction fanoutReadable(value) {\n if (underScratchRoot(value)) return true;\n const home = process.env.HOME || "";\n const roots = [home, storeRoot(), "/tmp", "/private/tmp", "/var/folders", "/private/var/folders",\n "/Applications/Xcode.app", "/Library/Developer"];\n return roots.some(root => under(root, value));\n}\n\n/** A headless fan-out worker may edit, run commands and fetch, and continue\n * when OpenCode\'s own loop detector asks (the launcher\'s watchdog stops a real\n * loop and says why, which is a clearer failure than a refused permission).\n * Anything else is refused outright. */\nfunction fanoutAllowed(input) {\n const kind = text(input?.type);\n if (kind === "edit" || kind === "bash" || kind === "webfetch" || kind === "doom_loop") return true;\n if (kind !== "external_directory") return false;\n const patterns = fanoutPatterns(input);\n return patterns.length > 0 && patterns.every(fanoutReadable);\n}\n\nfunction writeBlocked(input) {\n try {\n const directory = fanoutDirectory();\n mkdirSync(directory, { recursive: true });\n writeJsonAtomic(path.join(directory, "blocked.json"), {\n type: text(input?.type) || "action",\n pattern: fanoutPatterns(input).join(", "),\n message: permissionMessage(input),\n at: new Date().toISOString(),\n });\n } catch {}\n}\n\nfunction approvalPaths(sessionID) {\n const base = path.join(approvalDirectory(), `opencode-${sessionID}`);\n return { request: `${base}.request.json`, answer: `${base}.answer.json` };\n}\n\nfunction writeJsonAtomic(file, value) {\n const staging = `${file}.${process.pid}.tmp`;\n writeFileSync(staging, JSON.stringify(value), { mode: 0o600 });\n renameSync(staging, file);\n}\n\nfunction removeFile(file) {\n try { unlinkSync(file); } catch {}\n}\n\nfunction sleep(ms) {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n\nfunction setStatus(output, status) {\n if (output && typeof output === "object") output.status = status;\n}\n\nfunction permissionMessage(input) {\n const type = text(input?.type) || "action";\n const pattern = Array.isArray(input?.pattern)\n ? input.pattern.filter(value => typeof value === "string").join(", ")\n : text(input?.pattern);\n const metadata = input?.metadata && typeof input.metadata === "object" ? input.metadata : {};\n const detail = [pattern, text(metadata.command), text(metadata.description), text(metadata.path), text(metadata.url)].find(value => value);\n return (detail ? `${type}: ${detail}` : `opencode asks to use ${type}.`).slice(0, 2000);\n}\n\nfunction toolOutput(state) {\n if (!state || typeof state !== "object") return "";\n const output = state.output ?? state.metadata?.output ?? state.result ?? "";\n const value = typeof output === "string" ? output : JSON.stringify(output ?? "");\n return value.length > MAX_TOOL_OUTPUT ? value.slice(0, MAX_TOOL_OUTPUT) : value;\n}\n\nfunction blocksFor(message) {\n const blocks = [];\n for (const id of message.partOrder) {\n const part = message.parts.get(id);\n if (!part || typeof part !== "object") continue;\n if (part.type === "text" && typeof part.text === "string" && part.text.length) {\n blocks.push({ type: "text", text: part.text });\n } else if (part.type === "tool" && typeof part.callID === "string") {\n blocks.push({ type: "tool_use", id: part.callID, name: text(part.tool) || "tool", input: part.state?.input ?? {} });\n }\n }\n return blocks;\n}\n\n/** A tool\'s picture attachments as Anthropic-shaped image blocks, the form the\n * Hook\'s image route and the phone already read from Claude Code. Only inline\n * data URLs are carried; an image over the caps becomes a text marker. */\nfunction toolImages(state, budget) {\n const blocks = [];\n for (const attachment of Array.isArray(state?.attachments) ? state.attachments : []) {\n if (attachment?.type !== "file" || typeof attachment.url !== "string") continue;\n const match = IMAGE_DATA_URL.exec(attachment.url);\n if (!match) continue;\n const data = match[2];\n if (data.length > MAX_IMAGE_DATA || data.length > budget.remaining) {\n blocks.push({ type: "text", text: "[Image not included: too large to show on the phone]" });\n continue;\n }\n budget.remaining -= data.length;\n blocks.push({ type: "image", source: { type: "base64", media_type: match[1], data } });\n }\n return blocks;\n}\n\nfunction toolResults(message, budget) {\n const results = [];\n for (const id of message.partOrder) {\n const part = message.parts.get(id);\n if (!part || part.type !== "tool" || typeof part.callID !== "string") continue;\n const status = part.state?.status;\n if (status !== "completed" && status !== "error") continue;\n const output = toolOutput(part.state), images = toolImages(part.state, budget);\n const content = images.length ? [{ type: "text", text: output }, ...images] : output;\n results.push({ type: "tool_result", tool_use_id: part.callID, content, is_error: status === "error" });\n }\n return results;\n}\n\nfunction linesFor(session) {\n const messages = session.order\n .map(id => session.messages.get(id))\n .filter(Boolean)\n .sort((a, b) => (a.info?.time?.created ?? 0) - (b.info?.time?.created ?? 0) || String(a.info?.id).localeCompare(String(b.info?.id)));\n const lines = [];\n const budget = { remaining: MAX_SESSION_IMAGE_DATA };\n let seq = 0;\n const emit = (type, data, created) => {\n lines.push(JSON.stringify({ seq: seq++, time: new Date(created || Date.now()).toISOString(), type, data }));\n };\n for (const message of messages) {\n const info = message.info ?? {};\n if (info.role === "user") {\n const blocks = blocksFor(message);\n if (blocks.length) emit("user/message", { source: "user", message: { role: "user", content: blocks } }, info.time?.created);\n } else if (info.role === "assistant") {\n const complete = Boolean(info.time?.completed || info.finish);\n const blocks = blocksFor(message).filter(block => complete || block.type !== "text");\n const data = { stop_reason: STOP_REASONS[info.finish] || info.finish || "end_turn", message: { role: "assistant", content: blocks } };\n if (info.tokens && (typeof info.tokens.input === "number" || typeof info.tokens.output === "number")) {\n data.usage = { input_tokens: info.tokens.input ?? 0, output_tokens: info.tokens.output ?? 0 };\n }\n if (blocks.length) emit("assistant/message", data, info.time?.created);\n const results = toolResults(message, budget);\n if (results.length) emit("tool/results", { message: { role: "user", content: results } }, info.time?.updated ?? info.time?.created);\n }\n }\n return lines;\n}\n\n/** Which conversation this OpenCode process is showing, by PID: the Hook\n * reads it to bind a pane when Herdr reports no session for it. */\nconst pidBindingFile = () => path.join(storeRoot(), ".runtime", "sessions", `opencode-pid-${process.pid}.json`);\nfunction writePidBinding(sessionID) {\n mkdirSync(path.dirname(pidBindingFile()), { recursive: true });\n writeJsonAtomic(pidBindingFile(), { session: sessionID, at: new Date().toISOString() });\n}\n\n/** What this OpenCode process is doing, by PID: "working", "idle" or\n * "blocked" (a permission waits for an answer). The Hook reads it for a pane\n * whose terminal does not watch its agents (tmux); Herdr has its own. */\nconst statusFile = () => path.join(storeRoot(), ".runtime", "sessions", `opencode-status-${process.pid}.json`);\n\nexport const PhrenTranscriptPlugin = async () => {\n const sessions = new Map();\n // Subagent sessions run inside the same process; the pane shows their parent.\n const children = new Set();\n let boundSession;\n // A reused PID must not inherit an old process\'s conversation or state.\n try { removeFile(pidBindingFile()); removeFile(statusFile()); } catch {}\n let recordedStatus;\n // Permission asks still open, by id: while any is, the process is blocked.\n const asking = new Set();\n const recordStatus = (status, sessionID) => {\n // A fan-out worker runs headless, in no pane.\n if (process.env.PHREN_FANOUT_JOB) return;\n const next = asking.size && status === "working" ? "blocked" : status;\n if (next === recordedStatus) return;\n try {\n mkdirSync(path.dirname(statusFile()), { recursive: true });\n writeJsonAtomic(statusFile(), { status: next, ...(sessionID ? { session: sessionID } : {}), at: new Date().toISOString() });\n recordedStatus = next;\n } catch {}\n };\n const permissionId = properties => text(properties?.permissionID) || text(properties?.requestID) || text(properties?.id);\n const timers = new Map();\n const written = new Map();\n const pendingApprovals = new Set();\n\n const sessionState = sessionID => {\n let state = sessions.get(sessionID);\n if (!state) { state = { messages: new Map(), order: [], idle: false }; sessions.set(sessionID, state); }\n return state;\n };\n\n const messageState = (sessionID, messageID) => {\n const state = sessionState(sessionID);\n let message = state.messages.get(messageID);\n if (!message) { message = { info: { id: messageID }, parts: new Map(), partOrder: [] }; state.messages.set(messageID, message); state.order.push(messageID); }\n return message;\n };\n\n const flush = sessionID => {\n const state = sessions.get(sessionID);\n if (!state) return;\n const body = linesFor(state);\n const content = body.length ? body.join("\\n") + "\\n" : "";\n const directory = path.join(storeRoot(), ".runtime", "sessions");\n mkdirSync(directory, { recursive: true });\n const file = path.join(directory, `opencode-${sessionID}.events.jsonl`);\n const messages = state.order.map(id => state.messages.get(id));\n const latest = messages.at(-1), info = latest?.info;\n const user = messages.findLast(message => message.info?.role === "user");\n const preview = !state.idle && info?.role === "assistant" && !info.time?.completed && !info.finish\n ? blocksFor(latest).filter(block => block.type === "text").map(block => block.text).join("\\n").slice(0, 32_768) : "";\n if (preview && user?.info.time?.created) writeJsonAtomic(file + ".preview.json", {\n turnStartedAt: new Date(user.info.time.created).toISOString(), text: preview,\n });\n else removeFile(file + ".preview.json");\n if (written.get(sessionID) === content) return;\n const staging = `${file}.${process.pid}.tmp`;\n writeFileSync(staging, content, { mode: 0o600 });\n renameSync(staging, file);\n written.set(sessionID, content);\n };\n\n const schedule = sessionID => {\n if (!sessionID || timers.has(sessionID)) return;\n timers.set(sessionID, setTimeout(() => {\n timers.delete(sessionID);\n try { flush(sessionID); } catch {}\n }, FLUSH_MS));\n };\n\n const rememberInfo = (sessionID, info) => {\n if (!info || typeof info.id !== "string") return;\n const message = messageState(sessionID, info.id);\n message.info = { ...message.info, ...info };\n if (info.role === "user") sessionState(sessionID).idle = false;\n schedule(sessionID);\n };\n\n const rememberPart = (sessionID, messageID, part) => {\n if (!part || typeof part.id !== "string" || typeof messageID !== "string") return;\n const message = messageState(sessionID, messageID);\n if (!message.parts.has(part.id)) message.partOrder.push(part.id);\n message.parts.set(part.id, part);\n schedule(sessionID);\n };\n\n return {\n "chat.message": async (input, output) => {\n if (!OPENCODE_SESSION.test(text(input?.sessionID)) || !output?.message) return;\n if (!process.env.PHREN_FANOUT_JOB && !children.has(input.sessionID) && boundSession !== input.sessionID) {\n try { writePidBinding(input.sessionID); boundSession = input.sessionID; } catch {}\n }\n rememberInfo(input.sessionID, output.message);\n for (const part of output.parts ?? []) rememberPart(input.sessionID, output.message.id, part);\n if (!children.has(input.sessionID)) recordStatus("working", input.sessionID);\n },\n "permission.ask": async (input, output) => {\n // A fan-out worker runs headless in its own worktree with nobody watching\n // the phone\'s approval queue, so edits, commands and fetches inside that\n // worktree are granted here and anything else is refused outright rather\n // than waiting 50 seconds for an answer that never comes.\n if (process.env.PHREN_FANOUT_JOB) {\n if (fanoutAllowed(input)) { setStatus(output, "allow"); return; }\n // A worker the launcher drives through `opencode serve` relays the\n // ask to the phone and resumes on the owner\'s answer.\n if (process.env.PHREN_FANOUT_APPROVALS === "1") { setStatus(output, "ask"); return; }\n setStatus(output, "deny");\n // A denied permission aborts the turn; record what was refused so the\n // Hook can report the worker as blocked rather than finished.\n writeBlocked(input);\n return;\n }\n let request, answer, pendingSession, decision;\n // The ask blocks the process until it is answered: here from the\n // phone, or in the terminal (permission.replied below).\n const askId = text(input?.id);\n if (askId) { asking.add(askId); recordStatus("blocked", text(input?.sessionID)); }\n try {\n const sessionID = text(input?.sessionID), id = text(input?.id);\n if (!OPENCODE_SESSION.test(sessionID) || !id) { setStatus(output, "ask"); return; }\n // A second request for this session belongs in the terminal until\n // the existing phone request has finished.\n if (pendingApprovals.has(sessionID)) { setStatus(output, "ask"); return; }\n pendingApprovals.add(sessionID);\n pendingSession = sessionID;\n const paths = approvalPaths(sessionID);\n request = paths.request; answer = paths.answer;\n mkdirSync(approvalDirectory(), { recursive: true });\n removeFile(answer);\n const created = Date.now();\n writeJsonAtomic(request, { id, sessionID, type: text(input.type) || "action",\n title: text(input.title) || `Allow ${text(input.type) || "action"}?`, message: permissionMessage(input),\n createdAt: new Date(created).toISOString(), expiresAt: new Date(created + APPROVAL_DEADLINE_MS).toISOString() });\n const deadline = created + APPROVAL_DEADLINE_MS;\n while (Date.now() < deadline) {\n await sleep(APPROVAL_POLL_MS);\n try {\n const info = lstatSync(answer);\n if (!info.isFile() || info.size > 65_536) continue;\n const value = JSON.parse(readFileSync(answer, "utf8"));\n if (value && value.id === id) { decision = value.decision; break; }\n } catch {}\n }\n setStatus(output, decision === "approve" ? "allow" : decision === "deny" ? "deny" : "ask");\n } catch {\n setStatus(output, "ask");\n } finally {\n if (answer) removeFile(answer);\n if (request) removeFile(request);\n if (pendingSession) pendingApprovals.delete(pendingSession);\n // Answered from the phone: back to work. Otherwise the terminal asks.\n if (askId && (decision === "approve" || decision === "deny")) { asking.delete(askId); recordStatus("working", pendingSession); }\n }\n },\n event: async ({ event }) => {\n const properties = event?.properties ?? {};\n if ((event?.type === "session.created" || event?.type === "session.updated") && properties.info?.parentID\n && OPENCODE_SESSION.test(text(properties.info.id))) children.add(properties.info.id);\n const sessionID = typeof properties.sessionID === "string" ? properties.sessionID : properties.info?.sessionID ?? properties.part?.sessionID;\n // Permission events name the ask (permission.updated / permission.asked)\n // and its answer, which may come from the terminal.\n if (event?.type === "permission.updated" || event?.type === "permission.asked") {\n const id = permissionId(properties);\n if (id) { asking.add(id); recordStatus("blocked", text(sessionID)); }\n } else if (event?.type === "permission.replied") {\n const id = permissionId(properties);\n if (id) asking.delete(id); else asking.clear();\n recordStatus("working", text(sessionID));\n }\n if (!OPENCODE_SESSION.test(text(sessionID))) return;\n if (event.type === "message.updated") rememberInfo(sessionID, properties.info);\n else if (event.type === "message.part.updated") rememberPart(sessionID, properties.part?.messageID, properties.part);\n else if (event.type === "message.part.delta" && properties.field === "text" && typeof properties.delta === "string") {\n const message = messageState(sessionID, properties.messageID);\n const part = message.parts.get(properties.partID);\n if (part?.type === "text") rememberPart(sessionID, properties.messageID, { ...part, text: text(part.text) + properties.delta });\n }\n else if (event.type === "message.removed") {\n const state = sessions.get(sessionID);\n if (state && typeof properties.messageID === "string") {\n state.messages.delete(properties.messageID);\n state.order = state.order.filter(id => id !== properties.messageID);\n schedule(sessionID);\n }\n } else if (event.type === "session.idle" || event.type === "session.error") {\n sessionState(sessionID).idle = true;\n flush(sessionID);\n if (!children.has(sessionID)) { asking.clear(); recordStatus("idle", sessionID); }\n } else if (event.type === "session.status") {\n if (properties.status?.type === "busy") sessionState(sessionID).idle = false;\n // A subagent\'s session runs inside its parent\'s turn.\n if (!children.has(sessionID) && ["busy", "retry", "idle"].includes(properties.status?.type)) {\n if (properties.status.type === "idle") asking.clear();\n recordStatus(properties.status.type === "idle" ? "idle" : "working", sessionID);\n }\n }\n },\n };\n};\n';
|
|
39750
|
-
const here =
|
|
39966
|
+
const here = path47.dirname(fileURLToPath5(import.meta.url));
|
|
39751
39967
|
for (const candidate of [
|
|
39752
|
-
|
|
39753
|
-
|
|
39968
|
+
path47.join(here, "..", "..", "plugins", "opencode", "phren-transcript.js"),
|
|
39969
|
+
path47.join(here, "..", "plugins", "opencode", "phren-transcript.js")
|
|
39754
39970
|
]) {
|
|
39755
39971
|
const source = await missingFile(readFile18(candidate, "utf8"));
|
|
39756
39972
|
if (source !== void 0) return source;
|
|
@@ -39758,7 +39974,7 @@ async function opencodePluginSource() {
|
|
|
39758
39974
|
return void 0;
|
|
39759
39975
|
}
|
|
39760
39976
|
async function applyOpencodePlugin(remove = false) {
|
|
39761
|
-
const dir = opencodePluginsDir(), file2 =
|
|
39977
|
+
const dir = opencodePluginsDir(), file2 = path47.join(dir, "phren-transcript.js");
|
|
39762
39978
|
const source = await opencodePluginSource();
|
|
39763
39979
|
const existing = await missingFile(readFile18(file2, "utf8"));
|
|
39764
39980
|
if (remove) {
|
|
@@ -39766,14 +39982,14 @@ async function applyOpencodePlugin(remove = false) {
|
|
|
39766
39982
|
return false;
|
|
39767
39983
|
}
|
|
39768
39984
|
if (source === void 0 || !opencodePluginNeedsWrite(existing, source)) return false;
|
|
39769
|
-
if (!(await lstat9(
|
|
39985
|
+
if (!(await lstat9(path47.dirname(dir)).catch(() => null))?.isDirectory()) return false;
|
|
39770
39986
|
await mkdir10(dir, { recursive: true });
|
|
39771
39987
|
await atomic(file2, source, 420);
|
|
39772
39988
|
return true;
|
|
39773
39989
|
}
|
|
39774
39990
|
async function applyAgentHooks(edits) {
|
|
39775
39991
|
for (const { file: file2, before, after } of edits) {
|
|
39776
|
-
await mkdir10(
|
|
39992
|
+
await mkdir10(path47.dirname(file2), { recursive: true, mode: 448 });
|
|
39777
39993
|
if (await missingFile(readFile18(file2, "utf8")) !== before) throw new Error("Agent settings changed during installation. Run install again.");
|
|
39778
39994
|
if (before !== void 0) await copyFile2(file2, file2 + `.phren-hook-${Date.now()}.bak`);
|
|
39779
39995
|
await atomic(file2, after);
|
|
@@ -39787,18 +40003,18 @@ async function restoreAgentHooks(edits) {
|
|
|
39787
40003
|
}
|
|
39788
40004
|
}
|
|
39789
40005
|
async function rollback() {
|
|
39790
|
-
const config3 = JSON.parse(await readFile18(
|
|
40006
|
+
const config3 = JSON.parse(await readFile18(path47.join(bridgeRoot(), "installed.json"), "utf8"));
|
|
39791
40007
|
if (!config3.previous || !/^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(config3.previous)) throw new Error("No previous helper version is available.");
|
|
39792
40008
|
await stopService();
|
|
39793
40009
|
await activate(config3.previous);
|
|
39794
40010
|
await startService();
|
|
39795
|
-
await atomic(
|
|
40011
|
+
await atomic(path47.join(bridgeRoot(), "installed.json"), JSON.stringify({ version: config3.previous, previous: config3.version }) + "\n");
|
|
39796
40012
|
}
|
|
39797
40013
|
|
|
39798
40014
|
// src/bridge/computers.ts
|
|
39799
40015
|
init_protocol();
|
|
39800
|
-
var
|
|
39801
|
-
var dispatchKeyPath = (root = bridgeRoot()) =>
|
|
40016
|
+
var exec8 = promisify8(execFile9);
|
|
40017
|
+
var dispatchKeyPath = (root = bridgeRoot()) => path48.join(root, "id_ed25519_dispatch");
|
|
39802
40018
|
function publicComputerKey(value2) {
|
|
39803
40019
|
const match = /^ssh-ed25519 ([A-Za-z0-9+/]+={0,2})(?: [^\r\n]*)?$/.exec(value2.trim());
|
|
39804
40020
|
if (!match) throw new BridgeError(400, "Supply one ed25519 public key.");
|
|
@@ -39824,7 +40040,7 @@ async function enrollComputer(name, root = bridgeRoot()) {
|
|
|
39824
40040
|
computerName.parse(name);
|
|
39825
40041
|
await mkdir11(root, { recursive: true, mode: 448 });
|
|
39826
40042
|
await chmod3(root, 448);
|
|
39827
|
-
const lock =
|
|
40043
|
+
const lock = path48.join(root, "enroll-computer.lock");
|
|
39828
40044
|
try {
|
|
39829
40045
|
await mkdir11(lock, { mode: 448 });
|
|
39830
40046
|
} catch {
|
|
@@ -39833,23 +40049,23 @@ async function enrollComputer(name, root = bridgeRoot()) {
|
|
|
39833
40049
|
try {
|
|
39834
40050
|
const key2 = dispatchKeyPath(root);
|
|
39835
40051
|
if (!await regularFile(key2)) {
|
|
39836
|
-
const temporary = await mkdtemp2(
|
|
40052
|
+
const temporary = await mkdtemp2(path48.join(root, "enroll-"));
|
|
39837
40053
|
try {
|
|
39838
|
-
const generated =
|
|
39839
|
-
await
|
|
40054
|
+
const generated = path48.join(temporary, "key");
|
|
40055
|
+
await exec8("ssh-keygen", ["-q", "-t", "ed25519", "-N", "", "-C", "phren-computer", "-f", generated], { timeout: 1e4 });
|
|
39840
40056
|
await rename6(generated, key2);
|
|
39841
40057
|
} finally {
|
|
39842
40058
|
await rm5(temporary, { recursive: true, force: true });
|
|
39843
40059
|
}
|
|
39844
40060
|
}
|
|
39845
40061
|
await chmod3(key2, 384);
|
|
39846
|
-
const { stdout } = await
|
|
40062
|
+
const { stdout } = await exec8("ssh-keygen", ["-y", "-P", "", "-f", key2], { timeout: 1e4, maxBuffer: 4096 });
|
|
39847
40063
|
return computerKeyLine(name, stdout.trim());
|
|
39848
40064
|
} finally {
|
|
39849
40065
|
await rm5(lock, { recursive: true, force: true });
|
|
39850
40066
|
}
|
|
39851
40067
|
}
|
|
39852
|
-
async function acceptComputer(name, input2, sshDirectory =
|
|
40068
|
+
async function acceptComputer(name, input2, sshDirectory = path48.join(homedir14(), ".ssh")) {
|
|
39853
40069
|
computerName.parse(name);
|
|
39854
40070
|
const prefix = `restrict,pty,${forcedCommand} `;
|
|
39855
40071
|
const raw = input2.trim();
|
|
@@ -39863,19 +40079,19 @@ async function acceptComputer(name, input2, sshDirectory = path47.join(homedir14
|
|
|
39863
40079
|
sshDirectory
|
|
39864
40080
|
);
|
|
39865
40081
|
}
|
|
39866
|
-
async function appendAuthorizedKey(line, conflicts, conflictMessage, sshDirectory =
|
|
40082
|
+
async function appendAuthorizedKey(line, conflicts, conflictMessage, sshDirectory = path48.join(homedir14(), ".ssh")) {
|
|
39867
40083
|
const directory = await lstat10(sshDirectory).catch(() => void 0);
|
|
39868
40084
|
if (directory && (!directory.isDirectory() || directory.isSymbolicLink())) throw new BridgeError(409, "Refusing an unexpected SSH directory.");
|
|
39869
40085
|
await mkdir11(sshDirectory, { recursive: true, mode: 448 });
|
|
39870
40086
|
await chmod3(sshDirectory, 448);
|
|
39871
|
-
const lock =
|
|
40087
|
+
const lock = path48.join(sshDirectory, ".phren-enroll.lock");
|
|
39872
40088
|
try {
|
|
39873
40089
|
await mkdir11(lock, { mode: 448 });
|
|
39874
40090
|
} catch {
|
|
39875
40091
|
throw new BridgeError(409, "SSH enrollment is already running; inspect .phren-enroll.lock if interrupted.");
|
|
39876
40092
|
}
|
|
39877
|
-
const file2 =
|
|
39878
|
-
const temporary =
|
|
40093
|
+
const file2 = path48.join(sshDirectory, "authorized_keys");
|
|
40094
|
+
const temporary = path48.join(lock, "authorized_keys");
|
|
39879
40095
|
try {
|
|
39880
40096
|
const before = await regularFile(file2) ? await readFile19(file2, "utf8") : "";
|
|
39881
40097
|
const lines = before.split("\n").filter(Boolean);
|
|
@@ -39982,10 +40198,10 @@ function projectAgents(values, parent, receipt, fallbackComputer, fallbackTarget
|
|
|
39982
40198
|
for (const value2 of values.slice(0, 128)) {
|
|
39983
40199
|
if (state.count >= 128) break;
|
|
39984
40200
|
const raw = object2(value2), id2 = childID.safeParse(raw.id), source = provider.safeParse(raw.provider);
|
|
39985
|
-
const
|
|
40201
|
+
const path85 = publicLabel(raw.path);
|
|
39986
40202
|
const callId = typeof raw.callId === "string" && raw.callId.length > 0 && raw.callId.length <= 200 ? raw.callId : void 0;
|
|
39987
40203
|
const routed = destination(raw, fallbackComputer, fallbackTarget);
|
|
39988
|
-
if (!id2.success || !source.success || !
|
|
40204
|
+
if (!id2.success || !source.success || !path85 || !callId || !routed) continue;
|
|
39989
40205
|
const descendant = lineage ? `${lineage}/${id2.data}` : id2.data;
|
|
39990
40206
|
const nestedSession = sessionId.safeParse(raw.session);
|
|
39991
40207
|
const cycleIdentity = nestedSession.success ? nestedSession.data : routed.remote.child ?? routed.remote.target.session;
|
|
@@ -39998,7 +40214,7 @@ function projectAgents(values, parent, receipt, fallbackComputer, fallbackTarget
|
|
|
39998
40214
|
projected.push({
|
|
39999
40215
|
id: publicID(parent, routed.computer.id, receipt.id, descendant),
|
|
40000
40216
|
provider: source.data,
|
|
40001
|
-
path:
|
|
40217
|
+
path: path85,
|
|
40002
40218
|
callId,
|
|
40003
40219
|
state: raw.failed === true ? "failed" : childState,
|
|
40004
40220
|
...typeof raw.finishedAt === "string" && Number.isFinite(Date.parse(raw.finishedAt)) ? { finishedAt: raw.finishedAt } : {},
|
|
@@ -40060,7 +40276,7 @@ init_logger();
|
|
|
40060
40276
|
init_client();
|
|
40061
40277
|
import { spawn as spawn5 } from "node:child_process";
|
|
40062
40278
|
import { lstat as lstat11, mkdtemp as mkdtemp3, readFile as readFile20, rm as rm6, writeFile as writeFile6 } from "node:fs/promises";
|
|
40063
|
-
import
|
|
40279
|
+
import path49 from "node:path";
|
|
40064
40280
|
import { Duplex } from "node:stream";
|
|
40065
40281
|
init_protocol();
|
|
40066
40282
|
var peerSchema = external_exports.object({
|
|
@@ -40072,7 +40288,7 @@ var peerSchema = external_exports.object({
|
|
|
40072
40288
|
server: serverName.default("default")
|
|
40073
40289
|
}).strict();
|
|
40074
40290
|
async function hookPeers(root = bridgeRoot()) {
|
|
40075
|
-
const file2 =
|
|
40291
|
+
const file2 = path49.join(root, "hooks.yaml");
|
|
40076
40292
|
const info = await lstat11(file2).catch((error62) => {
|
|
40077
40293
|
if (error62.code === "ENOENT") return void 0;
|
|
40078
40294
|
throw new BridgeError(409, `hooks.yaml could not be read (${error62.code ?? "unknown error"}).`);
|
|
@@ -40094,7 +40310,7 @@ async function addHookPeer(input2, root = bridgeRoot()) {
|
|
|
40094
40310
|
const clash = existing.find((other) => other.name === peer.name || other.address === peer.address && other.port === peer.port && other.server === peer.server);
|
|
40095
40311
|
if (clash) throw new BridgeError(409, `hooks.yaml already has ${clash.name} at ${clash.address}; remove that entry first to link it differently.`);
|
|
40096
40312
|
if (existing.length >= 32) throw new BridgeError(409, "hooks.yaml already has 32 computers.");
|
|
40097
|
-
await atomic(
|
|
40313
|
+
await atomic(path49.join(root, "hooks.yaml"), dump({ version: 1, computers: [...existing, peer] }, { lineWidth: -1 }));
|
|
40098
40314
|
return { added: true, peer };
|
|
40099
40315
|
}
|
|
40100
40316
|
async function optionalHookPeers(root = bridgeRoot()) {
|
|
@@ -40175,10 +40391,10 @@ async function peerRequest(peer, route2, data, timeout) {
|
|
|
40175
40391
|
const root = bridgeRoot(), key2 = dispatchKeyPath(root);
|
|
40176
40392
|
const info = await lstat11(key2).catch(() => void 0);
|
|
40177
40393
|
if (!info?.isFile() || info.isSymbolicLink() || info.mode & 63) throw new BridgeError(409, "Run phren bridge enroll-computer on this computer first (private key mode 0600).", { code: "dispatch-key-missing" });
|
|
40178
|
-
const temporary = await mkdtemp3(
|
|
40394
|
+
const temporary = await mkdtemp3(path49.join(root, "peer-"));
|
|
40179
40395
|
let child, stream;
|
|
40180
40396
|
try {
|
|
40181
|
-
const knownHosts =
|
|
40397
|
+
const knownHosts = path49.join(temporary, "known_hosts");
|
|
40182
40398
|
await writeFile6(knownHosts, `phren-peer ${peer.hostKey}
|
|
40183
40399
|
`, { mode: 384 });
|
|
40184
40400
|
const ssh2 = spawn5("ssh", peerSSHArgs(peer, knownHosts, key2), { stdio: ["pipe", "pipe", "pipe"] });
|
|
@@ -40315,21 +40531,21 @@ var receiptSchema2 = dispatchSchema.omit({ prompt: true }).extend({
|
|
|
40315
40531
|
async function dispatchProjectDirectory(project) {
|
|
40316
40532
|
const name = projectName.parse(project);
|
|
40317
40533
|
const source = readProjectConfig(phrenStoreRoot(), name).sourcePath;
|
|
40318
|
-
if (typeof source !== "string" || !
|
|
40319
|
-
const directory = await
|
|
40320
|
-
if (!directory || !(await
|
|
40534
|
+
if (typeof source !== "string" || !path50.isAbsolute(source) || /[\x00-\x1f\x7f]/.test(source)) throw new BridgeError(404, "Project has no absolute sourcePath on this computer.");
|
|
40535
|
+
const directory = await realpath10(source).catch(() => void 0);
|
|
40536
|
+
if (!directory || !(await stat15(directory)).isDirectory()) throw new BridgeError(404, "Project is not on this computer.");
|
|
40321
40537
|
return directory;
|
|
40322
40538
|
}
|
|
40323
40539
|
async function save(receipt) {
|
|
40324
|
-
const root =
|
|
40540
|
+
const root = path50.join(bridgeRoot(), "dispatches");
|
|
40325
40541
|
await mkdir12(root, { recursive: true, mode: 448 });
|
|
40326
|
-
await atomic(
|
|
40542
|
+
await atomic(path50.join(root, `${receipt.id}.json`), receipt);
|
|
40327
40543
|
}
|
|
40328
40544
|
var MAX_RECEIPT_BYTES = 65536;
|
|
40329
40545
|
var receiptUpdates = Promise.resolve();
|
|
40330
40546
|
function updateReceipt(receiptID, change) {
|
|
40331
40547
|
const run = receiptUpdates.then(async () => {
|
|
40332
|
-
const file2 =
|
|
40548
|
+
const file2 = path50.join(bridgeRoot(), "dispatches", `${external_exports.string().uuid().parse(receiptID)}.json`);
|
|
40333
40549
|
const info = await lstat12(file2).catch(() => void 0);
|
|
40334
40550
|
if (!info?.isFile() || info.isSymbolicLink() || info.size > MAX_RECEIPT_BYTES) return void 0;
|
|
40335
40551
|
const receipt = receiptSchema2.parse(JSON.parse(await readFile21(file2, "utf8")));
|
|
@@ -40344,7 +40560,7 @@ function updateReceipt(receiptID, change) {
|
|
|
40344
40560
|
}
|
|
40345
40561
|
async function receiptNames(root) {
|
|
40346
40562
|
try {
|
|
40347
|
-
return await
|
|
40563
|
+
return await readdir10(root);
|
|
40348
40564
|
} catch (error62) {
|
|
40349
40565
|
if (error62.code !== "ENOENT") logger.warn("dispatch", `Could not list dispatch receipts: ${failureReason(error62)}`);
|
|
40350
40566
|
return [];
|
|
@@ -40357,12 +40573,12 @@ function failureReason(error62) {
|
|
|
40357
40573
|
return `${typeof code === "string" && !(error62 instanceof BridgeError) ? `${code}: ` : ""}${message}`.replace(/[\x00-\x1f\x7f]/g, " ").slice(0, 200);
|
|
40358
40574
|
}
|
|
40359
40575
|
async function dispatchStatus() {
|
|
40360
|
-
const root =
|
|
40576
|
+
const root = path50.join(bridgeRoot(), "dispatches");
|
|
40361
40577
|
const names = (await receiptNames(root)).filter((name) => /^[a-f0-9-]{36}\.json$/.test(name)).slice(0, 1024);
|
|
40362
40578
|
const receipts = [];
|
|
40363
40579
|
for (const name of names) {
|
|
40364
40580
|
try {
|
|
40365
|
-
const file2 =
|
|
40581
|
+
const file2 = path50.join(root, name);
|
|
40366
40582
|
const info = await lstat12(file2);
|
|
40367
40583
|
if (!info.isFile() || info.isSymbolicLink() || info.size > MAX_RECEIPT_BYTES) continue;
|
|
40368
40584
|
const receipt = receiptSchema2.parse(JSON.parse(await readFile21(file2, "utf8")));
|
|
@@ -40437,7 +40653,7 @@ var DispatchService = class {
|
|
|
40437
40653
|
if (!this.identity) throw new BridgeError(503, "This Hook cannot validate a dispatch parent.");
|
|
40438
40654
|
await validateDispatchParent(data, this.identity.computerID, this.identity.validateParentTarget);
|
|
40439
40655
|
}
|
|
40440
|
-
if ((await receiptNames(
|
|
40656
|
+
if ((await receiptNames(path50.join(bridgeRoot(), "dispatches"))).length >= 1024) throw new BridgeError(429, "Dispatch history is full. Archive old receipts before dispatching again.");
|
|
40441
40657
|
const here = this.local();
|
|
40442
40658
|
const toLocal = data.computer !== "anywhere" && isLocalComputer(data.computer, here.names);
|
|
40443
40659
|
const enrolled = await hookPeers().catch((error62) => {
|
|
@@ -40649,7 +40865,7 @@ init_protocol();
|
|
|
40649
40865
|
|
|
40650
40866
|
// src/bridge/schedule-watch.ts
|
|
40651
40867
|
init_herdr();
|
|
40652
|
-
import { open as
|
|
40868
|
+
import { open as open11, stat as stat16 } from "node:fs/promises";
|
|
40653
40869
|
init_protocol();
|
|
40654
40870
|
init_transcripts();
|
|
40655
40871
|
init_terminal_text();
|
|
@@ -40744,7 +40960,7 @@ async function readFinalTurn(source, sessionId2) {
|
|
|
40744
40960
|
if (!sessionId2) return void 0;
|
|
40745
40961
|
const file2 = await transcriptPath(source, sessionId2).catch(() => void 0);
|
|
40746
40962
|
if (!file2) return void 0;
|
|
40747
|
-
const handle = await
|
|
40963
|
+
const handle = await open11(file2, "r").catch(() => void 0);
|
|
40748
40964
|
if (!handle) return void 0;
|
|
40749
40965
|
try {
|
|
40750
40966
|
const { size } = await handle.stat();
|
|
@@ -40784,7 +41000,7 @@ function ownerQuestion(text4) {
|
|
|
40784
41000
|
async function realTranscriptStamp(source, sessionId2) {
|
|
40785
41001
|
if (!sessionId2) return void 0;
|
|
40786
41002
|
const file2 = await transcriptPath(source, sessionId2).catch(() => void 0);
|
|
40787
|
-
const metadata = file2 ? await
|
|
41003
|
+
const metadata = file2 ? await stat16(file2).catch(() => void 0) : void 0;
|
|
40788
41004
|
return metadata ? { size: metadata.size, mtimeMs: metadata.mtimeMs } : void 0;
|
|
40789
41005
|
}
|
|
40790
41006
|
async function watchHerdrRun(server, target, signal, startup, env = {}) {
|
|
@@ -41037,11 +41253,11 @@ var DispatchReturns = class {
|
|
|
41037
41253
|
/** Ask each peer, once, about every open dispatch placed on it. */
|
|
41038
41254
|
async poll() {
|
|
41039
41255
|
const now = this.now();
|
|
41040
|
-
const
|
|
41041
|
-
if (!
|
|
41256
|
+
const open17 = (await dispatchStatus()).filter((receipt) => (receipt.state === "accepted" || receipt.state === "uncertain") && receipt.target && receipt.worker?.state !== "gone" && now - Date.parse(receipt.createdAt) < WATCH_MS);
|
|
41257
|
+
if (!open17.length) return;
|
|
41042
41258
|
const peers = await this.peers().catch(() => []);
|
|
41043
41259
|
const byComputer = /* @__PURE__ */ new Map();
|
|
41044
|
-
for (const receipt of
|
|
41260
|
+
for (const receipt of open17) byComputer.set(receipt.computer, [...byComputer.get(receipt.computer) ?? [], receipt]);
|
|
41045
41261
|
await Promise.all([...byComputer].map(async ([computer, receipts]) => {
|
|
41046
41262
|
const peer = peers.find((candidate) => candidate.name === computer);
|
|
41047
41263
|
const local = !peer && this.isLocal(computer);
|
|
@@ -41113,12 +41329,12 @@ init_protocol();
|
|
|
41113
41329
|
init_herdr();
|
|
41114
41330
|
init_transcripts();
|
|
41115
41331
|
init_transcript_index();
|
|
41116
|
-
import { execFile as
|
|
41332
|
+
import { execFile as execFile10 } from "node:child_process";
|
|
41117
41333
|
import { createHash as createHash12 } from "node:crypto";
|
|
41118
|
-
import { mkdir as mkdir13, open as
|
|
41119
|
-
import
|
|
41120
|
-
import { promisify as
|
|
41121
|
-
var
|
|
41334
|
+
import { mkdir as mkdir13, open as open12, stat as stat17, readFile as readFile22, writeFile as writeFile7 } from "node:fs/promises";
|
|
41335
|
+
import path51 from "node:path";
|
|
41336
|
+
import { promisify as promisify9 } from "node:util";
|
|
41337
|
+
var exec9 = promisify9(execFile10);
|
|
41122
41338
|
var text3 = external_exports.string().trim().min(1).max(4e3).refine((t) => !/[\x00-\x08\x0b-\x1f\x7f]/.test(t));
|
|
41123
41339
|
var question = external_exports.object({ title: text3, options: external_exports.array(text3).max(12).nullable().optional() });
|
|
41124
41340
|
var questionSet = external_exports.array(question).min(1).max(8);
|
|
@@ -41217,7 +41433,7 @@ var CodexQuestions = class {
|
|
|
41217
41433
|
}
|
|
41218
41434
|
probe;
|
|
41219
41435
|
supported() {
|
|
41220
|
-
if (!this.probe || Date.now() - this.probe.at > 3e5) this.probe = { at: Date.now(), result:
|
|
41436
|
+
if (!this.probe || Date.now() - this.probe.at > 3e5) this.probe = { at: Date.now(), result: exec9(this.executable, ["queue", "--help"], { timeout: 5e3, maxBuffer: 65536 }).then(({ stdout }) => stdout.includes("--thread") && stdout.includes("--message")).catch(() => false).then((available) => {
|
|
41221
41437
|
this.inboxAvailable = available;
|
|
41222
41438
|
return available;
|
|
41223
41439
|
}) };
|
|
@@ -41230,7 +41446,7 @@ var CodexQuestions = class {
|
|
|
41230
41446
|
const cached2 = this.snapshots.get(target.session);
|
|
41231
41447
|
let pending = cached2?.pending;
|
|
41232
41448
|
if (!cached2 || Date.now() - cached2.at > 1e3) {
|
|
41233
|
-
const metadata = await
|
|
41449
|
+
const metadata = await stat17(file2), stamp = `${metadata.ino}:${metadata.size}:${metadata.mtimeMs}`;
|
|
41234
41450
|
pending = cached2?.stamp === stamp ? cached2.pending : await pendingAsyncQuestions(file2).catch((error62) => {
|
|
41235
41451
|
if (this.failedSnapshots.size >= 64) this.failedSnapshots.delete(this.failedSnapshots.keys().next().value);
|
|
41236
41452
|
this.failedSnapshots.set(target.session, Date.now());
|
|
@@ -41242,7 +41458,7 @@ var CodexQuestions = class {
|
|
|
41242
41458
|
}
|
|
41243
41459
|
return Promise.all((pending ?? []).map(async (p) => {
|
|
41244
41460
|
const key2 = createHash12("sha256").update(JSON.stringify([target.source, target.session, p.id])).digest("hex");
|
|
41245
|
-
const submitted = await readFile22(
|
|
41461
|
+
const submitted = await readFile22(path51.join(bridgeRoot(), "question-replies", key2), "utf8").then((value2) => value2 === "submitted").catch(() => false);
|
|
41246
41462
|
return { toolUseId: p.id, isAsync: true, submitted, questions: p.questions.map((q) => ({
|
|
41247
41463
|
question: q.title,
|
|
41248
41464
|
options: (q.options ?? []).map((label2) => ({ label: label2 })),
|
|
@@ -41258,17 +41474,17 @@ var CodexQuestions = class {
|
|
|
41258
41474
|
const reply = questionReply(questions, data.answers);
|
|
41259
41475
|
const pane = await validateTarget(target);
|
|
41260
41476
|
if (await paneIdentity(target.server, pane, true) !== target.session) throw new BridgeError(409, "This pane's conversation changed. Reopen the chat.");
|
|
41261
|
-
const directory =
|
|
41477
|
+
const directory = path51.join(bridgeRoot(), "question-replies");
|
|
41262
41478
|
await mkdir13(directory, { recursive: true, mode: 448 });
|
|
41263
41479
|
const key2 = createHash12("sha256").update(JSON.stringify([target.source, target.session, id2])).digest("hex");
|
|
41264
|
-
const receiptPath =
|
|
41265
|
-
const receipt = await
|
|
41480
|
+
const receiptPath = path51.join(directory, key2);
|
|
41481
|
+
const receipt = await open12(receiptPath, "wx", 384).catch((error62) => {
|
|
41266
41482
|
if (error62.code === "EEXIST") throw new BridgeError(409, "An answer was already submitted. Check the conversation before answering again.");
|
|
41267
41483
|
throw new BridgeError(503, "Phren could not record this answer. Nothing was sent.");
|
|
41268
41484
|
});
|
|
41269
41485
|
await receipt.close();
|
|
41270
41486
|
try {
|
|
41271
|
-
await
|
|
41487
|
+
await exec9(this.executable, ["queue", "--thread", target.session, "--message", reply], { timeout: 8e3, maxBuffer: 65536 });
|
|
41272
41488
|
await writeFile7(receiptPath, "submitted", { mode: 384 });
|
|
41273
41489
|
} catch {
|
|
41274
41490
|
throw new BridgeError(409, "Codex did not confirm the answer. Check the conversation; Phren has not retried it.");
|
|
@@ -41284,9 +41500,9 @@ init_transcripts();
|
|
|
41284
41500
|
init_home_paths();
|
|
41285
41501
|
init_protocol();
|
|
41286
41502
|
import { spawn as spawn6 } from "node:child_process";
|
|
41287
|
-
import { readdir as
|
|
41503
|
+
import { readdir as readdir11, readFile as readFile23, stat as stat18 } from "node:fs/promises";
|
|
41288
41504
|
import { homedir as homedir15 } from "node:os";
|
|
41289
|
-
import
|
|
41505
|
+
import path52 from "node:path";
|
|
41290
41506
|
function readCodexModels(executable = "codex") {
|
|
41291
41507
|
return new Promise((resolve11) => {
|
|
41292
41508
|
const child = spawn6(executable, ["app-server"], { cwd: homedir15(), stdio: ["pipe", "pipe", "ignore"] });
|
|
@@ -41365,12 +41581,12 @@ var CLAUDE_MENU = [
|
|
|
41365
41581
|
{ id: "claude-fable-5-1[1m]", name: "Fable 5.1 (1M context)", description: "Fable 5.1 with a 1M context window." }
|
|
41366
41582
|
];
|
|
41367
41583
|
async function readClaudeCatalog(configDir = claudeConfigDir(), installed) {
|
|
41368
|
-
const directory =
|
|
41584
|
+
const directory = path52.join(configDir, "cache", "model-catalog");
|
|
41369
41585
|
let newest;
|
|
41370
41586
|
try {
|
|
41371
|
-
for (const name of await
|
|
41587
|
+
for (const name of await readdir11(directory)) {
|
|
41372
41588
|
if (!name.endsWith("-cc.json")) continue;
|
|
41373
|
-
const file2 =
|
|
41589
|
+
const file2 = path52.join(directory, name), at = (await stat18(file2)).mtimeMs;
|
|
41374
41590
|
if (!newest || at > newest.at) newest = { file: file2, at };
|
|
41375
41591
|
}
|
|
41376
41592
|
} catch {
|
|
@@ -41451,7 +41667,7 @@ async function readClaudeModels(configDir, installed) {
|
|
|
41451
41667
|
const live = await readClaudeCatalog(configDir, version3).catch(() => []);
|
|
41452
41668
|
return live.length ? live : CLAUDE_MENU.map((model) => ({ ...model }));
|
|
41453
41669
|
}
|
|
41454
|
-
async function readOpenCodeModels(executable = "opencode", configDir =
|
|
41670
|
+
async function readOpenCodeModels(executable = "opencode", configDir = path52.join(homedir15(), ".config/opencode")) {
|
|
41455
41671
|
const listed2 = await new Promise((resolve11) => {
|
|
41456
41672
|
const child = spawn6(executable, ["models"], { cwd: homedir15(), stdio: ["ignore", "pipe", "ignore"] });
|
|
41457
41673
|
let out = "", done = false;
|
|
@@ -41478,7 +41694,7 @@ async function readOpenCodeModels(executable = "opencode", configDir = path51.jo
|
|
|
41478
41694
|
let configured;
|
|
41479
41695
|
for (const file2 of ["opencode.json", "opencode.jsonc"]) {
|
|
41480
41696
|
try {
|
|
41481
|
-
const text4 = await readFile23(
|
|
41697
|
+
const text4 = await readFile23(path52.join(configDir, file2), "utf8");
|
|
41482
41698
|
const model = /"model"\s*:\s*"([^"]+)"/.exec(text4)?.[1];
|
|
41483
41699
|
if (model) {
|
|
41484
41700
|
configured = model.slice(0, 200);
|
|
@@ -41948,14 +42164,14 @@ init_project_config();
|
|
|
41948
42164
|
init_shared();
|
|
41949
42165
|
import { randomUUID as randomUUID11 } from "node:crypto";
|
|
41950
42166
|
import { hostname as hostname6 } from "node:os";
|
|
41951
|
-
import
|
|
42167
|
+
import path55 from "node:path";
|
|
41952
42168
|
|
|
41953
42169
|
// src/bridge/schedule-format.ts
|
|
41954
42170
|
init_js_yaml();
|
|
41955
42171
|
init_zod();
|
|
41956
42172
|
init_protocol();
|
|
41957
42173
|
import { readFile as readFile24 } from "node:fs/promises";
|
|
41958
|
-
import
|
|
42174
|
+
import path53 from "node:path";
|
|
41959
42175
|
var SCHEDULE_EVERY = ["interval", "daily", "weekly", "once", "cron"];
|
|
41960
42176
|
var SCHEDULE_HARNESSES = ["claude", "codex", "opencode"];
|
|
41961
42177
|
var SCHEDULE_NOTIFY = ["start", "finish", "failure"];
|
|
@@ -41968,7 +42184,7 @@ var scheduleName = singleLine(80);
|
|
|
41968
42184
|
var timestamp3 = external_exports.string().datetime({ offset: true });
|
|
41969
42185
|
var localTimestamp = external_exports.string().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/);
|
|
41970
42186
|
var clockTime = external_exports.string().regex(/^(?:[01]\d|2[0-3]):[0-5]\d$/);
|
|
41971
|
-
var schedulePath = (projectDir) =>
|
|
42187
|
+
var schedulePath = (projectDir) => path53.join(projectDir, "schedules.yaml");
|
|
41972
42188
|
var runningStatuses = /* @__PURE__ */ new Set(["launched", "running", "blocked"]);
|
|
41973
42189
|
var MAX_SCHEDULES = 64;
|
|
41974
42190
|
var MAX_RUNS = 2e3;
|
|
@@ -42168,7 +42384,7 @@ async function writeScheduleRuns(file2, runs) {
|
|
|
42168
42384
|
await atomicInPrivateDir(file2, kept.map((run) => JSON.stringify(run)).join("\n") + (kept.length ? "\n" : ""));
|
|
42169
42385
|
}
|
|
42170
42386
|
function scheduleRunsFile() {
|
|
42171
|
-
return
|
|
42387
|
+
return path53.join(bridgeRoot(), "schedule-runs.jsonl");
|
|
42172
42388
|
}
|
|
42173
42389
|
|
|
42174
42390
|
// src/bridge/schedule-launch.ts
|
|
@@ -42181,8 +42397,8 @@ init_logger();
|
|
|
42181
42397
|
init_shared();
|
|
42182
42398
|
import { spawn as spawn7 } from "node:child_process";
|
|
42183
42399
|
import { createWriteStream } from "node:fs";
|
|
42184
|
-
import { mkdir as mkdir14, readFile as readFile25, stat as
|
|
42185
|
-
import
|
|
42400
|
+
import { mkdir as mkdir14, readFile as readFile25, stat as stat19 } from "node:fs/promises";
|
|
42401
|
+
import path54 from "node:path";
|
|
42186
42402
|
import { finished as streamFinished } from "node:stream/promises";
|
|
42187
42403
|
var CLAUDE_SCHEDULE_SETTINGS = JSON.stringify({ enableAllProjectMcpServers: true });
|
|
42188
42404
|
function createScheduleLauncher(launchHerdr, store = defaultPhrenPath()) {
|
|
@@ -42215,7 +42431,7 @@ async function resumeScheduleRun(run, schedule, signal, watch2 = watchHerdrRun)
|
|
|
42215
42431
|
);
|
|
42216
42432
|
}
|
|
42217
42433
|
if (launch2.mode === "headless" && launch2.jobDir) {
|
|
42218
|
-
const manifest = await readFile25(
|
|
42434
|
+
const manifest = await readFile25(path54.join(launch2.jobDir, "manifest.json"), "utf8").then((text4) => JSON.parse(text4)).catch(() => void 0);
|
|
42219
42435
|
if (manifest?.status === "completed") return { status: "finished" };
|
|
42220
42436
|
if (manifest?.status === "failed") {
|
|
42221
42437
|
return { status: "failed", reason: typeof manifest.exitCode === "number" ? `The scheduled agent exited with code ${manifest.exitCode}.` : "The scheduled agent failed." };
|
|
@@ -42263,7 +42479,7 @@ async function promptWhenReady(server, paneId, text4, signal, waitMs = 6e4) {
|
|
|
42263
42479
|
}
|
|
42264
42480
|
}
|
|
42265
42481
|
async function launchHeadless(context, store, started) {
|
|
42266
|
-
const root = fanoutRoot({ ...process.env, PHREN_PATH: store }), jobDir =
|
|
42482
|
+
const root = fanoutRoot({ ...process.env, PHREN_PATH: store }), jobDir = path54.join(root, context.runId);
|
|
42267
42483
|
await mkdir14(jobDir, { recursive: true, mode: 448 });
|
|
42268
42484
|
const eventLog = "events.jsonl", now = (/* @__PURE__ */ new Date()).toISOString();
|
|
42269
42485
|
const manifest = {
|
|
@@ -42283,7 +42499,7 @@ async function launchHeadless(context, store, started) {
|
|
|
42283
42499
|
};
|
|
42284
42500
|
await writeManifest2(jobDir, manifest);
|
|
42285
42501
|
const command = headlessCommand(context.schedule, context.cwd);
|
|
42286
|
-
if (context.schedule.harness === "codex") await ensureCodexDirTrusted(context.cwd).catch((error62) => logger.warn("schedule", `Could not mark ${
|
|
42502
|
+
if (context.schedule.harness === "codex") await ensureCodexDirTrusted(context.cwd).catch((error62) => logger.warn("schedule", `Could not mark ${path54.basename(context.cwd)} trusted for Codex (run ${context.runId}): ${error62 instanceof Error ? error62.message.split("\n")[0] : String(error62)}`));
|
|
42287
42503
|
let child;
|
|
42288
42504
|
try {
|
|
42289
42505
|
child = spawn7(command.file, command.args, { cwd: command.cwd, env: process.env, stdio: ["pipe", "pipe", "pipe"] });
|
|
@@ -42295,8 +42511,8 @@ async function launchHeadless(context, store, started) {
|
|
|
42295
42511
|
const closed = new Promise((resolve11) => {
|
|
42296
42512
|
child.once("close", (code, signal) => resolve11({ code, signal }));
|
|
42297
42513
|
});
|
|
42298
|
-
const output2 = createWriteStream(
|
|
42299
|
-
const errors = createWriteStream(
|
|
42514
|
+
const output2 = createWriteStream(path54.join(jobDir, eventLog), { flags: "a", mode: 384 });
|
|
42515
|
+
const errors = createWriteStream(path54.join(jobDir, "stderr.log"), { flags: "a", mode: 384 });
|
|
42300
42516
|
const streamsFinished = Promise.all([streamFinished(output2), streamFinished(errors)]).then(() => void 0).catch(() => void 0);
|
|
42301
42517
|
child.stdin?.on("error", () => {
|
|
42302
42518
|
});
|
|
@@ -42349,7 +42565,7 @@ function tomlQuote(value2) {
|
|
|
42349
42565
|
}
|
|
42350
42566
|
async function ensureCodexDirTrusted(cwd) {
|
|
42351
42567
|
const directory = codexHome();
|
|
42352
|
-
const file2 =
|
|
42568
|
+
const file2 = path54.join(directory, "config.toml");
|
|
42353
42569
|
let text4 = "";
|
|
42354
42570
|
try {
|
|
42355
42571
|
text4 = await readFile25(file2, "utf8");
|
|
@@ -42381,12 +42597,12 @@ ${trustLine}
|
|
|
42381
42597
|
`;
|
|
42382
42598
|
}
|
|
42383
42599
|
await mkdir14(directory, { recursive: true, mode: 448 });
|
|
42384
|
-
const metadata = await
|
|
42600
|
+
const metadata = await stat19(file2).catch(() => void 0);
|
|
42385
42601
|
const mode = metadata ? metadata.mode & 511 : 384;
|
|
42386
42602
|
await atomic(file2, next, mode);
|
|
42387
42603
|
}
|
|
42388
42604
|
async function writeManifest2(jobDir, manifest) {
|
|
42389
|
-
await atomicInPrivateDir(
|
|
42605
|
+
await atomicInPrivateDir(path54.join(jobDir, "manifest.json"), JSON.stringify(manifest, null, 2) + "\n");
|
|
42390
42606
|
}
|
|
42391
42607
|
|
|
42392
42608
|
// src/bridge/schedules.ts
|
|
@@ -42424,7 +42640,7 @@ var Scheduler = class {
|
|
|
42424
42640
|
return getProjectDirs(this.store);
|
|
42425
42641
|
}
|
|
42426
42642
|
projectDirectory(project) {
|
|
42427
|
-
const found = this.projectDirectories().find((directory) =>
|
|
42643
|
+
const found = this.projectDirectories().find((directory) => path55.basename(directory).toLowerCase() === project.toLowerCase());
|
|
42428
42644
|
if (!found) throw new BridgeError(404, `Unknown project "${project}".`);
|
|
42429
42645
|
return found;
|
|
42430
42646
|
}
|
|
@@ -42450,7 +42666,7 @@ var Scheduler = class {
|
|
|
42450
42666
|
} catch {
|
|
42451
42667
|
continue;
|
|
42452
42668
|
}
|
|
42453
|
-
const project =
|
|
42669
|
+
const project = path55.basename(directory);
|
|
42454
42670
|
for (const schedule of schedules) {
|
|
42455
42671
|
const matching = runs.filter((run) => run.project === project && run.scheduleId === schedule.id);
|
|
42456
42672
|
const last = matching.at(-1), running2 = matching.some((run) => runningStatuses.has(run.status));
|
|
@@ -42480,7 +42696,7 @@ var Scheduler = class {
|
|
|
42480
42696
|
}
|
|
42481
42697
|
async launchNow(projectName2, id2) {
|
|
42482
42698
|
const prepared = await this.exclusive(async () => {
|
|
42483
|
-
const projectDir = this.projectDirectory(projectName2), project =
|
|
42699
|
+
const projectDir = this.projectDirectory(projectName2), project = path55.basename(projectDir);
|
|
42484
42700
|
const file2 = await readScheduleDocument(projectDir), schedule = file2.schedules.find((item) => item.id === id2);
|
|
42485
42701
|
if (!schedule) throw new BridgeError(404, `Schedule "${id2}" was not found in ${project}.`);
|
|
42486
42702
|
if (!computerMatches(schedule.computer, this.computer())) throw new BridgeError(409, `${schedule.computer} owns this schedule; run it from that computer.`);
|
|
@@ -42594,8 +42810,8 @@ var Scheduler = class {
|
|
|
42594
42810
|
const resume = this.launch.resume;
|
|
42595
42811
|
if (this.recovered || !resume) return;
|
|
42596
42812
|
this.recovered = true;
|
|
42597
|
-
const
|
|
42598
|
-
for (const run of
|
|
42813
|
+
const open17 = (await readScheduleRuns(this.runsFile)).filter((run) => runningStatuses.has(run.status) && !this.own.has(run.id));
|
|
42814
|
+
for (const run of open17) {
|
|
42599
42815
|
this.own.add(run.id);
|
|
42600
42816
|
let schedule;
|
|
42601
42817
|
try {
|
|
@@ -42639,23 +42855,23 @@ var Scheduler = class {
|
|
|
42639
42855
|
|
|
42640
42856
|
// src/bridge/canary.ts
|
|
42641
42857
|
init_phren_paths();
|
|
42642
|
-
import { lstat as lstat14, mkdtemp as mkdtemp4, realpath as
|
|
42858
|
+
import { lstat as lstat14, mkdtemp as mkdtemp4, realpath as realpath11, rm as rm7 } from "node:fs/promises";
|
|
42643
42859
|
import { hostname as hostname8, tmpdir } from "node:os";
|
|
42644
|
-
import
|
|
42860
|
+
import path59 from "node:path";
|
|
42645
42861
|
|
|
42646
42862
|
// src/bridge/health.ts
|
|
42647
42863
|
init_policy();
|
|
42648
42864
|
init_phren_paths();
|
|
42649
42865
|
init_store_registry();
|
|
42650
|
-
import { execFile as
|
|
42866
|
+
import { execFile as execFile11, spawn as spawn8 } from "node:child_process";
|
|
42651
42867
|
import { lstat as lstat13, readFile as readFile26 } from "node:fs/promises";
|
|
42652
42868
|
import { homedir as homedir16, hostname as hostname7 } from "node:os";
|
|
42653
|
-
import
|
|
42654
|
-
import { promisify as
|
|
42869
|
+
import path58 from "node:path";
|
|
42870
|
+
import { promisify as promisify10 } from "node:util";
|
|
42655
42871
|
init_protocol();
|
|
42656
42872
|
init_metrics();
|
|
42657
42873
|
init_terminal_tmux();
|
|
42658
|
-
var
|
|
42874
|
+
var exec10 = promisify10(execFile11);
|
|
42659
42875
|
async function terminalHealth() {
|
|
42660
42876
|
const [{ servers: servers2 }, tmux2] = await Promise.all([Promise.resolve().then(() => (init_herdr(), herdr_exports)), tmuxHealth()]);
|
|
42661
42877
|
const running2 = (await servers2().catch(() => [])).map((server) => ({
|
|
@@ -42716,7 +42932,7 @@ function plainError(value2) {
|
|
|
42716
42932
|
async function git3(cwd, args) {
|
|
42717
42933
|
try {
|
|
42718
42934
|
countGit("health");
|
|
42719
|
-
const { stdout } = await
|
|
42935
|
+
const { stdout } = await exec10("git", args, { cwd, timeout: 5e3, maxBuffer: 65536, env: { ...process.env, GIT_TERMINAL_PROMPT: "0" } });
|
|
42720
42936
|
return stdout.trim();
|
|
42721
42937
|
} catch {
|
|
42722
42938
|
return void 0;
|
|
@@ -42764,7 +42980,7 @@ async function lastScheduledRun(store, runsFile = scheduleRunsFile()) {
|
|
|
42764
42980
|
const last = runs.reduce((newest, run) => !newest || run.startedAt >= newest.startedAt ? run : newest, void 0);
|
|
42765
42981
|
if (!last) return null;
|
|
42766
42982
|
let name;
|
|
42767
|
-
const directory = getProjectDirs(store).find((dir) =>
|
|
42983
|
+
const directory = getProjectDirs(store).find((dir) => path58.basename(dir).toLowerCase() === last.project.toLowerCase());
|
|
42768
42984
|
if (directory) name = (await readScheduleDocument(directory).catch(() => void 0))?.schedules.find((item) => item.id === last.scheduleId)?.name;
|
|
42769
42985
|
return {
|
|
42770
42986
|
...name ? { name } : {},
|
|
@@ -42818,7 +43034,7 @@ async function probePeer(peer, caller) {
|
|
|
42818
43034
|
}
|
|
42819
43035
|
}
|
|
42820
43036
|
function canaryFile(root = bridgeRoot()) {
|
|
42821
|
-
return
|
|
43037
|
+
return path58.join(root, "canary.json");
|
|
42822
43038
|
}
|
|
42823
43039
|
async function readCanary(root = bridgeRoot()) {
|
|
42824
43040
|
try {
|
|
@@ -42831,7 +43047,7 @@ async function readCanary(root = bridgeRoot()) {
|
|
|
42831
43047
|
}
|
|
42832
43048
|
}
|
|
42833
43049
|
async function pushConfigured() {
|
|
42834
|
-
const file2 = process.env.PHREN_APNS_CONFIG ||
|
|
43050
|
+
const file2 = process.env.PHREN_APNS_CONFIG || path58.join(bridgeRoot(), "apns.json");
|
|
42835
43051
|
const info = await lstat13(file2).catch(() => void 0);
|
|
42836
43052
|
return { configured: !!info?.isFile() };
|
|
42837
43053
|
}
|
|
@@ -42920,7 +43136,7 @@ async function closeCanaryWorkspaces(server, before, created) {
|
|
|
42920
43136
|
}
|
|
42921
43137
|
async function conductorStep(options, server) {
|
|
42922
43138
|
const before = new Set(objects((await snapshot(server)).workspaces).map((workspace) => String(workspace.workspace_id)));
|
|
42923
|
-
const folder = await
|
|
43139
|
+
const folder = await realpath11(await mkdtemp4(path59.join(tmpdir(), "phren-canary-")));
|
|
42924
43140
|
let created, failure2, detail;
|
|
42925
43141
|
try {
|
|
42926
43142
|
const launched = await options.launch(server, { role: "conductor", kind: "claude", label: CANARY_LABEL, cwd: folder, timeoutMs: 45e3 });
|
|
@@ -42941,12 +43157,12 @@ async function scheduleStep(options) {
|
|
|
42941
43157
|
let count2 = 0;
|
|
42942
43158
|
const broken = [];
|
|
42943
43159
|
for (const directory of getProjectDirs(options.store)) {
|
|
42944
|
-
const present2 = await lstat14(
|
|
43160
|
+
const present2 = await lstat14(path59.join(directory, "schedules.yaml")).catch(() => void 0);
|
|
42945
43161
|
if (!present2) continue;
|
|
42946
43162
|
try {
|
|
42947
43163
|
count2 += (await readScheduleDocument(directory)).schedules.length;
|
|
42948
43164
|
} catch (error62) {
|
|
42949
|
-
broken.push(`${
|
|
43165
|
+
broken.push(`${path59.basename(directory)}: ${reason(error62)}`);
|
|
42950
43166
|
}
|
|
42951
43167
|
}
|
|
42952
43168
|
const tick = options.scheduler.lastTickAt;
|
|
@@ -43016,7 +43232,7 @@ function runCanary(options) {
|
|
|
43016
43232
|
}
|
|
43017
43233
|
async function dailyCanaryEnabled(root = bridgeRoot()) {
|
|
43018
43234
|
if (process.env.PHREN_CANARY_DAILY === "1") return true;
|
|
43019
|
-
return !!(await lstat14(
|
|
43235
|
+
return !!(await lstat14(path59.join(root, "canary-daily")).catch(() => void 0))?.isFile();
|
|
43020
43236
|
}
|
|
43021
43237
|
async function dailyCanaryDue(root = bridgeRoot(), now = Date.now()) {
|
|
43022
43238
|
if (running || !await dailyCanaryEnabled(root)) return false;
|
|
@@ -43029,11 +43245,11 @@ init_shared();
|
|
|
43029
43245
|
|
|
43030
43246
|
// src/bridge/server-routes.ts
|
|
43031
43247
|
init_zod();
|
|
43032
|
-
import
|
|
43248
|
+
import path82 from "node:path";
|
|
43033
43249
|
|
|
43034
43250
|
// src/bridge/code-note.ts
|
|
43035
43251
|
init_zod();
|
|
43036
|
-
import * as
|
|
43252
|
+
import * as path65 from "node:path";
|
|
43037
43253
|
|
|
43038
43254
|
// src/content/validate.ts
|
|
43039
43255
|
init_utils_helpers();
|
|
@@ -43047,7 +43263,7 @@ init_store_routing();
|
|
|
43047
43263
|
init_locks();
|
|
43048
43264
|
init_data_utils();
|
|
43049
43265
|
import * as fs28 from "fs";
|
|
43050
|
-
import * as
|
|
43266
|
+
import * as path61 from "path";
|
|
43051
43267
|
import * as crypto7 from "crypto";
|
|
43052
43268
|
|
|
43053
43269
|
// src/project-topics.ts
|
|
@@ -43059,7 +43275,7 @@ init_data_utils();
|
|
|
43059
43275
|
init_filenames();
|
|
43060
43276
|
import * as crypto6 from "crypto";
|
|
43061
43277
|
import * as fs27 from "fs";
|
|
43062
|
-
import * as
|
|
43278
|
+
import * as path60 from "path";
|
|
43063
43279
|
var TOPIC_CONFIG_FILENAME = "topic-config.json";
|
|
43064
43280
|
var SOFTWARE_TOPICS = [
|
|
43065
43281
|
{
|
|
@@ -43597,7 +43813,7 @@ function topicDocHeader(project, topic) {
|
|
|
43597
43813
|
}
|
|
43598
43814
|
function appendArchivedEntriesToTopicDoc(filePath, project, topic, entries2) {
|
|
43599
43815
|
if (entries2.length === 0) return;
|
|
43600
|
-
fs27.mkdirSync(
|
|
43816
|
+
fs27.mkdirSync(path60.dirname(filePath), { recursive: true });
|
|
43601
43817
|
withFileLock(filePath, () => {
|
|
43602
43818
|
let existing = "";
|
|
43603
43819
|
if (fs27.existsSync(filePath)) existing = fs27.readFileSync(filePath, "utf8");
|
|
@@ -43716,7 +43932,7 @@ function autoArchiveToReference(phrenPath, project, keepCount) {
|
|
|
43716
43932
|
if (!isValidProjectName(project)) return phrenErr(`Invalid project name: "${project}".`, PhrenError.INVALID_PROJECT_NAME);
|
|
43717
43933
|
const resolvedDir = storeAwareProjectPath(phrenPath, project);
|
|
43718
43934
|
if (!resolvedDir || !fs28.existsSync(resolvedDir)) return phrenErr(`Project "${project}" not found in phren.`, PhrenError.PROJECT_NOT_FOUND);
|
|
43719
|
-
const learningsPath =
|
|
43935
|
+
const learningsPath = path61.join(resolvedDir, FINDINGS_FILENAME);
|
|
43720
43936
|
if (!fs28.existsSync(learningsPath)) return phrenOk(0);
|
|
43721
43937
|
const STALE_LOCK_MS = 6e5;
|
|
43722
43938
|
const lockFile = runtimeFile(phrenPath, `consolidation-${project}.lock`);
|
|
@@ -43725,8 +43941,8 @@ function autoArchiveToReference(phrenPath, project, keepCount) {
|
|
|
43725
43941
|
} catch (e) {
|
|
43726
43942
|
if (e.code === "EEXIST") {
|
|
43727
43943
|
try {
|
|
43728
|
-
const
|
|
43729
|
-
if (Date.now() -
|
|
43944
|
+
const stat27 = fs28.statSync(lockFile);
|
|
43945
|
+
if (Date.now() - stat27.mtimeMs < STALE_LOCK_MS) {
|
|
43730
43946
|
return phrenErr("Consolidation already running", PhrenError.LOCK_TIMEOUT);
|
|
43731
43947
|
}
|
|
43732
43948
|
tryUnlink(lockFile);
|
|
@@ -43752,7 +43968,7 @@ function autoArchiveToReference(phrenPath, project, keepCount) {
|
|
|
43752
43968
|
const entries2 = parseActiveEntries(content);
|
|
43753
43969
|
if (entries2.length <= keepCount) return phrenOk(0);
|
|
43754
43970
|
const toArchive = entries2.slice(0, entries2.length - keepCount);
|
|
43755
|
-
const referenceDir =
|
|
43971
|
+
const referenceDir = path61.join(resolvedDir, "reference");
|
|
43756
43972
|
const { topics } = readProjectTopics(phrenPath, project);
|
|
43757
43973
|
const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
|
|
43758
43974
|
const archivedSet = buildArchivedBulletSet(referenceDir);
|
|
@@ -44316,7 +44532,7 @@ var DEFAULT_DECAY = {
|
|
|
44316
44532
|
var DEFAULT_UNDATED_CONFIDENCE = DEFAULT_DECAY.d120;
|
|
44317
44533
|
|
|
44318
44534
|
// src/content/dedup.ts
|
|
44319
|
-
import * as
|
|
44535
|
+
import * as path62 from "path";
|
|
44320
44536
|
init_shared();
|
|
44321
44537
|
init_utils();
|
|
44322
44538
|
init_store_routing();
|
|
@@ -44440,7 +44656,7 @@ function resolveCoref(text4, context) {
|
|
|
44440
44656
|
result = result.replace(/\bthe project\b/gi, context.project);
|
|
44441
44657
|
}
|
|
44442
44658
|
if (context.file) {
|
|
44443
|
-
const basename12 =
|
|
44659
|
+
const basename12 = path62.basename(context.file);
|
|
44444
44660
|
result = result.replace(/\b(this file|the file)\b/gi, basename12);
|
|
44445
44661
|
}
|
|
44446
44662
|
if (context.project && /\b(it|this|that|they|them)\b/i.test(result)) {
|
|
@@ -44457,7 +44673,7 @@ init_shared();
|
|
|
44457
44673
|
init_shared();
|
|
44458
44674
|
init_governance();
|
|
44459
44675
|
import * as fs30 from "fs";
|
|
44460
|
-
import * as
|
|
44676
|
+
import * as path64 from "path";
|
|
44461
44677
|
import * as crypto8 from "crypto";
|
|
44462
44678
|
|
|
44463
44679
|
// src/finding-graph-id.ts
|
|
@@ -44492,7 +44708,7 @@ init_store_routing();
|
|
|
44492
44708
|
// src/finding/context.ts
|
|
44493
44709
|
init_utils();
|
|
44494
44710
|
import * as fs29 from "fs";
|
|
44495
|
-
import * as
|
|
44711
|
+
import * as path63 from "path";
|
|
44496
44712
|
|
|
44497
44713
|
// src/session/utils.ts
|
|
44498
44714
|
init_utils();
|
|
@@ -44574,14 +44790,14 @@ function resolveFindingTaskReference(phrenPath, project, match) {
|
|
|
44574
44790
|
const projectDir = safeProjectPath(phrenPath, project);
|
|
44575
44791
|
if (!projectDir) return { error: `Invalid project name: "${project}".` };
|
|
44576
44792
|
const taskPath = resolveTaskFilePath(phrenPath, project);
|
|
44577
|
-
const items = parseTaskItems(taskPath ??
|
|
44793
|
+
const items = parseTaskItems(taskPath ?? path63.join(projectDir, "tasks.md"));
|
|
44578
44794
|
return resolveTaskItemMatch(items, match);
|
|
44579
44795
|
}
|
|
44580
44796
|
function resolveAutoFindingTaskItem(phrenPath, project) {
|
|
44581
44797
|
const projectDir = safeProjectPath(phrenPath, project);
|
|
44582
44798
|
if (!projectDir) return void 0;
|
|
44583
44799
|
const taskPath = resolveTaskFilePath(phrenPath, project);
|
|
44584
|
-
const active = parseTaskItems(taskPath ??
|
|
44800
|
+
const active = parseTaskItems(taskPath ?? path63.join(projectDir, "tasks.md")).filter(
|
|
44585
44801
|
(item) => item.section === "Active" && item.stableId
|
|
44586
44802
|
);
|
|
44587
44803
|
if (active.length === 1) return active[0].stableId;
|
|
@@ -44621,7 +44837,7 @@ function buildFindingCitation(citationInput, nowIso, inferredRepo, headCommit) {
|
|
|
44621
44837
|
function resolveInferredCitationRepo(citationInput) {
|
|
44622
44838
|
if (citationInput?.repo) return citationInput.repo;
|
|
44623
44839
|
if (citationInput?.file) {
|
|
44624
|
-
const fileDir =
|
|
44840
|
+
const fileDir = path64.dirname(citationInput.file);
|
|
44625
44841
|
return getRepoRoot(fileDir);
|
|
44626
44842
|
}
|
|
44627
44843
|
return void 0;
|
|
@@ -44756,7 +44972,7 @@ function addFindingToFile(phrenPath, project, learning, citationInput, opts) {
|
|
|
44756
44972
|
if (!isValidProjectName(project)) return phrenErr(`Invalid project name: "${project}".`, PhrenError.INVALID_PROJECT_NAME);
|
|
44757
44973
|
const resolvedDir = storeAwareProjectPath(phrenPath, project);
|
|
44758
44974
|
if (!resolvedDir) return phrenErr(`Invalid project name: "${project}".`, PhrenError.INVALID_PROJECT_NAME);
|
|
44759
|
-
const learningsPath =
|
|
44975
|
+
const learningsPath = path64.join(resolvedDir, FINDINGS_FILENAME);
|
|
44760
44976
|
const nowIso = (opts?.now ?? /* @__PURE__ */ new Date()).toISOString();
|
|
44761
44977
|
const today = nowIso.slice(0, 10);
|
|
44762
44978
|
const resolvedCitationInputResult = resolveFindingCitationInput(phrenPath, project, citationInput);
|
|
@@ -44938,7 +45154,7 @@ var codeNoteSchema = external_exports.object({
|
|
|
44938
45154
|
// phone's spelling, accepted until 0.3.1.
|
|
44939
45155
|
name: external_exports.string().min(1).max(4600).optional(),
|
|
44940
45156
|
symbol: external_exports.string().min(1).max(4600).optional(),
|
|
44941
|
-
file: external_exports.string().min(1).max(4096).refine((file2) => !
|
|
45157
|
+
file: external_exports.string().min(1).max(4096).refine((file2) => !path65.isAbsolute(file2) && !file2.includes("\0") && !file2.split(/[\\/]/).includes("..")),
|
|
44942
45158
|
line: external_exports.number().int().positive(),
|
|
44943
45159
|
text: external_exports.string().trim().min(1).max(4500).refine((text4) => !/[\x00-\x08\x0b-\x1f\x7f]/.test(text4)),
|
|
44944
45160
|
target: external_exports.union([external_exports.object({ session: sessionId }).strict(), external_exports.object({ harness: external_exports.enum(["codex", "claude", "opencode"]) }).strict()]).optional()
|
|
@@ -44988,29 +45204,29 @@ init_utils_helpers();
|
|
|
44988
45204
|
init_protocol();
|
|
44989
45205
|
init_herdr();
|
|
44990
45206
|
init_transcripts();
|
|
44991
|
-
import { execFile as
|
|
44992
|
-
import { promisify as
|
|
45207
|
+
import { execFile as execFile12 } from "node:child_process";
|
|
45208
|
+
import { promisify as promisify11 } from "node:util";
|
|
44993
45209
|
import { realpathSync as realpathSync5 } from "node:fs";
|
|
44994
|
-
import { readdir as
|
|
45210
|
+
import { readdir as readdir12, readFile as readFile27, stat as stat20, mkdir as mkdir15 } from "node:fs/promises";
|
|
44995
45211
|
import { homedir as homedir17 } from "node:os";
|
|
44996
|
-
import
|
|
45212
|
+
import path70 from "node:path";
|
|
44997
45213
|
|
|
44998
45214
|
// src/core/project.ts
|
|
44999
45215
|
init_shared();
|
|
45000
|
-
import * as
|
|
45216
|
+
import * as path68 from "path";
|
|
45001
45217
|
|
|
45002
45218
|
// src/core/project-registry.ts
|
|
45003
45219
|
init_phren_paths();
|
|
45004
45220
|
import * as fs32 from "fs";
|
|
45005
|
-
import * as
|
|
45221
|
+
import * as path67 from "path";
|
|
45006
45222
|
|
|
45007
45223
|
// src/git-worktree.ts
|
|
45008
45224
|
import * as fs31 from "fs";
|
|
45009
|
-
import * as
|
|
45225
|
+
import * as path66 from "path";
|
|
45010
45226
|
var WORKTREE_CONTAINER_NAMES = /* @__PURE__ */ new Set(["worktrees", ".worktrees"]);
|
|
45011
|
-
var LINKED_WORKTREE_SEGMENT = `${
|
|
45227
|
+
var LINKED_WORKTREE_SEGMENT = `${path66.sep}.git${path66.sep}worktrees${path66.sep}`;
|
|
45012
45228
|
function resolveWorktreeParent(dir) {
|
|
45013
|
-
const resolved =
|
|
45229
|
+
const resolved = path66.resolve(dir);
|
|
45014
45230
|
const agentParent = parentFromAgentWorktreePath(resolved);
|
|
45015
45231
|
if (agentParent) return { repoRoot: agentParent, reason: "agent-worktree-dir" };
|
|
45016
45232
|
const linkedParent = parentFromLinkedWorktree(resolved);
|
|
@@ -45018,23 +45234,23 @@ function resolveWorktreeParent(dir) {
|
|
|
45018
45234
|
return null;
|
|
45019
45235
|
}
|
|
45020
45236
|
function parentFromAgentWorktreePath(resolved) {
|
|
45021
|
-
const segments = resolved.split(
|
|
45237
|
+
const segments = resolved.split(path66.sep);
|
|
45022
45238
|
for (let i = 1; i < segments.length; i++) {
|
|
45023
45239
|
if (!WORKTREE_CONTAINER_NAMES.has(segments[i])) continue;
|
|
45024
45240
|
let j = i - 1;
|
|
45025
45241
|
if (!segments[j]?.startsWith(".")) continue;
|
|
45026
45242
|
while (j >= 1 && segments[j].startsWith(".")) j--;
|
|
45027
45243
|
if (j < 1) continue;
|
|
45028
|
-
return segments.slice(0, j + 1).join(
|
|
45244
|
+
return segments.slice(0, j + 1).join(path66.sep) || path66.sep;
|
|
45029
45245
|
}
|
|
45030
45246
|
return null;
|
|
45031
45247
|
}
|
|
45032
45248
|
function parentFromLinkedWorktree(resolved) {
|
|
45033
45249
|
let current2 = resolved;
|
|
45034
45250
|
while (true) {
|
|
45035
|
-
const parent = repoRootFromGitFile(
|
|
45251
|
+
const parent = repoRootFromGitFile(path66.join(current2, ".git"));
|
|
45036
45252
|
if (parent) return parent;
|
|
45037
|
-
const next =
|
|
45253
|
+
const next = path66.dirname(current2);
|
|
45038
45254
|
if (next === current2) return null;
|
|
45039
45255
|
current2 = next;
|
|
45040
45256
|
}
|
|
@@ -45049,7 +45265,7 @@ function repoRootFromGitFile(gitPath) {
|
|
|
45049
45265
|
}
|
|
45050
45266
|
const match = raw.match(/^\s*gitdir:\s*(.+?)\s*$/m);
|
|
45051
45267
|
if (!match) return null;
|
|
45052
|
-
const gitDir =
|
|
45268
|
+
const gitDir = path66.resolve(path66.dirname(gitPath), match[1].replace(/[/\\]/g, path66.sep));
|
|
45053
45269
|
const idx = gitDir.indexOf(LINKED_WORKTREE_SEGMENT);
|
|
45054
45270
|
if (idx === -1) return null;
|
|
45055
45271
|
return gitDir.slice(0, idx);
|
|
@@ -45202,8 +45418,8 @@ function addTermCount(terms, rawText, weight = 1) {
|
|
|
45202
45418
|
}
|
|
45203
45419
|
function maybeReadUtf8(filePath, maxBytes = 256e3) {
|
|
45204
45420
|
try {
|
|
45205
|
-
const
|
|
45206
|
-
if (!
|
|
45421
|
+
const stat27 = fs32.statSync(filePath);
|
|
45422
|
+
if (!stat27.isFile() || stat27.size > maxBytes) return "";
|
|
45207
45423
|
return fs32.readFileSync(filePath, "utf8");
|
|
45208
45424
|
} catch {
|
|
45209
45425
|
return "";
|
|
@@ -45262,7 +45478,7 @@ function scoreTopicsFromTerms(domain2, terms, docsText) {
|
|
|
45262
45478
|
return topics;
|
|
45263
45479
|
}
|
|
45264
45480
|
function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
|
|
45265
|
-
const resolvedRoot =
|
|
45481
|
+
const resolvedRoot = path67.resolve(repoRoot);
|
|
45266
45482
|
if (!fs32.existsSync(resolvedRoot)) return null;
|
|
45267
45483
|
const signal = {
|
|
45268
45484
|
domainScores: { software: 0, music: 0, game: 0, research: 0, writing: 0, creative: 0, other: 0 },
|
|
@@ -45273,7 +45489,7 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
|
|
|
45273
45489
|
usefulSignals: 0
|
|
45274
45490
|
};
|
|
45275
45491
|
const skipDirs = /* @__PURE__ */ new Set([".git", ".phren", "node_modules", "dist", "build", "coverage", ".next", ".turbo", "target"]);
|
|
45276
|
-
const packageJsonPath =
|
|
45492
|
+
const packageJsonPath = path67.join(resolvedRoot, "package.json");
|
|
45277
45493
|
if (fs32.existsSync(packageJsonPath)) {
|
|
45278
45494
|
signal.usefulSignals++;
|
|
45279
45495
|
addDomainScores(signal.domainScores, DOMAIN_CONFIG_HINTS["package.json"]);
|
|
@@ -45303,33 +45519,33 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
|
|
|
45303
45519
|
debugLog(`inferInitScaffoldFromRepo package.json parse failed: ${errorMessage(err)}`);
|
|
45304
45520
|
}
|
|
45305
45521
|
}
|
|
45306
|
-
const topLevelConfigs = Object.keys(DOMAIN_CONFIG_HINTS).filter((fileName) => fs32.existsSync(
|
|
45522
|
+
const topLevelConfigs = Object.keys(DOMAIN_CONFIG_HINTS).filter((fileName) => fs32.existsSync(path67.join(resolvedRoot, fileName)));
|
|
45307
45523
|
for (const configName of topLevelConfigs) {
|
|
45308
45524
|
signal.usefulSignals++;
|
|
45309
45525
|
const configScore = DOMAIN_CONFIG_HINTS[configName];
|
|
45310
45526
|
if (configScore) addDomainScores(signal.domainScores, configScore);
|
|
45311
45527
|
}
|
|
45312
45528
|
const readmeCandidates = [
|
|
45313
|
-
|
|
45314
|
-
|
|
45529
|
+
path67.join(resolvedRoot, "README.md"),
|
|
45530
|
+
path67.join(resolvedRoot, "readme.md")
|
|
45315
45531
|
];
|
|
45316
45532
|
for (const readmePath of readmeCandidates) {
|
|
45317
45533
|
if (!fs32.existsSync(readmePath)) continue;
|
|
45318
45534
|
const content = maybeReadUtf8(readmePath);
|
|
45319
45535
|
if (!content) continue;
|
|
45320
45536
|
signal.usefulSignals++;
|
|
45321
|
-
signal.referenceHints.push(
|
|
45537
|
+
signal.referenceHints.push(path67.relative(resolvedRoot, readmePath));
|
|
45322
45538
|
addTermCount(signal.terms, content, 2);
|
|
45323
45539
|
signal.docsText += ` ${content.toLowerCase()}`;
|
|
45324
45540
|
break;
|
|
45325
45541
|
}
|
|
45326
|
-
const docsDir =
|
|
45542
|
+
const docsDir = path67.join(resolvedRoot, "docs");
|
|
45327
45543
|
if (fs32.existsSync(docsDir) && fs32.statSync(docsDir).isDirectory()) {
|
|
45328
45544
|
signal.referenceHints.push("docs/");
|
|
45329
45545
|
for (const entry of fs32.readdirSync(docsDir, { withFileTypes: true })) {
|
|
45330
45546
|
if (!entry.isFile()) continue;
|
|
45331
45547
|
if (!/\.(md|txt|rst)$/i.test(entry.name)) continue;
|
|
45332
|
-
const docsContent = maybeReadUtf8(
|
|
45548
|
+
const docsContent = maybeReadUtf8(path67.join(docsDir, entry.name));
|
|
45333
45549
|
if (!docsContent) continue;
|
|
45334
45550
|
signal.usefulSignals++;
|
|
45335
45551
|
addTermCount(signal.terms, docsContent, 1);
|
|
@@ -45337,7 +45553,7 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
|
|
|
45337
45553
|
}
|
|
45338
45554
|
}
|
|
45339
45555
|
for (const folderName of ["reference", "specs", "design", "architecture", "src", "packages", "apps"]) {
|
|
45340
|
-
const fullPath =
|
|
45556
|
+
const fullPath = path67.join(resolvedRoot, folderName);
|
|
45341
45557
|
if (fs32.existsSync(fullPath)) {
|
|
45342
45558
|
signal.referenceHints.push(`${folderName}/`);
|
|
45343
45559
|
}
|
|
@@ -45348,14 +45564,14 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
|
|
|
45348
45564
|
if (scannedFiles >= maxFiles) return;
|
|
45349
45565
|
for (const entry of fs32.readdirSync(dir, { withFileTypes: true })) {
|
|
45350
45566
|
if (scannedFiles >= maxFiles) return;
|
|
45351
|
-
const fullPath =
|
|
45567
|
+
const fullPath = path67.join(dir, entry.name);
|
|
45352
45568
|
if (entry.isDirectory()) {
|
|
45353
45569
|
if (skipDirs.has(entry.name)) continue;
|
|
45354
45570
|
walk(fullPath);
|
|
45355
45571
|
continue;
|
|
45356
45572
|
}
|
|
45357
45573
|
scannedFiles++;
|
|
45358
|
-
const ext =
|
|
45574
|
+
const ext = path67.extname(entry.name).toLowerCase();
|
|
45359
45575
|
if (!ext) continue;
|
|
45360
45576
|
const extScore = EXTENSION_DOMAIN_HINTS[ext];
|
|
45361
45577
|
if (extScore) {
|
|
@@ -45529,7 +45745,7 @@ function findExistingProjectForSource(phrenPath, sourceRoot, derivedName) {
|
|
|
45529
45745
|
return null;
|
|
45530
45746
|
}
|
|
45531
45747
|
};
|
|
45532
|
-
const resolvedSource =
|
|
45748
|
+
const resolvedSource = path67.resolve(sourceRoot);
|
|
45533
45749
|
for (const project of candidates) {
|
|
45534
45750
|
if (sourceOf(project) === resolvedSource) return project;
|
|
45535
45751
|
}
|
|
@@ -45543,7 +45759,7 @@ function findExistingProjectForSource(phrenPath, sourceRoot, derivedName) {
|
|
|
45543
45759
|
function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
|
|
45544
45760
|
const profile = typeof opts === "string" ? opts : opts.profile;
|
|
45545
45761
|
const profilePhrenPath = typeof opts === "string" ? phrenPath : opts.profilePhrenPath ?? phrenPath;
|
|
45546
|
-
const resolvedPath =
|
|
45762
|
+
const resolvedPath = path67.resolve(projectPath);
|
|
45547
45763
|
if (!fs32.existsSync(resolvedPath)) {
|
|
45548
45764
|
throw new Error(`Path does not exist: ${resolvedPath}`);
|
|
45549
45765
|
}
|
|
@@ -45554,17 +45770,17 @@ function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
|
|
|
45554
45770
|
if (worktreeRepoRoot) {
|
|
45555
45771
|
debugLog(`bootstrapFromExisting: ${resolvedPath} is a ${worktree.reason}; attributing to ${worktreeRepoRoot}`);
|
|
45556
45772
|
}
|
|
45557
|
-
const sourceRoot = isProjectLocal ?
|
|
45773
|
+
const sourceRoot = isProjectLocal ? path67.resolve(manifest.workspaceRoot || resolvedPath) : worktreeRepoRoot ?? resolvedPath;
|
|
45558
45774
|
if (isProjectLocal) {
|
|
45559
|
-
const matchesWorkspace = resolvedPath === sourceRoot || resolvedPath.startsWith(sourceRoot +
|
|
45775
|
+
const matchesWorkspace = resolvedPath === sourceRoot || resolvedPath.startsWith(sourceRoot + path67.sep);
|
|
45560
45776
|
if (!matchesWorkspace) {
|
|
45561
45777
|
throw new Error(`Project-local phren can only enroll the owning workspace: ${sourceRoot}`);
|
|
45562
45778
|
}
|
|
45563
45779
|
}
|
|
45564
45780
|
let claudeMdPath = null;
|
|
45565
45781
|
const candidates = [
|
|
45566
|
-
|
|
45567
|
-
|
|
45782
|
+
path67.join(sourceRoot, "AGENTS.md"),
|
|
45783
|
+
path67.join(sourceRoot, ".claude", "CLAUDE.md")
|
|
45568
45784
|
];
|
|
45569
45785
|
for (const c of candidates) {
|
|
45570
45786
|
if (fs32.existsSync(c)) {
|
|
@@ -45584,12 +45800,12 @@ function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
|
|
|
45584
45800
|
`Project "${existingProject}" already exists with different casing. Refusing to bootstrap "${projectName2}" because it would split the same project on case-sensitive filesystems.`
|
|
45585
45801
|
);
|
|
45586
45802
|
}
|
|
45587
|
-
const projDir =
|
|
45803
|
+
const projDir = path67.join(phrenPath, projectName2);
|
|
45588
45804
|
fs32.mkdirSync(projDir, { recursive: true });
|
|
45589
45805
|
const inferredScaffold = inferInitScaffoldFromRepo(sourceRoot);
|
|
45590
45806
|
const existingConfig = readProjectConfig(phrenPath, projectName2);
|
|
45591
45807
|
const ownership = typeof opts === "string" ? parseProjectOwnershipMode(existingConfig.ownership) ?? getProjectOwnershipDefault(phrenPath) : opts.ownership ?? parseProjectOwnershipMode(existingConfig.ownership) ?? getProjectOwnershipDefault(phrenPath);
|
|
45592
|
-
const claudePath =
|
|
45808
|
+
const claudePath = path67.join(projDir, "AGENTS.md");
|
|
45593
45809
|
if (ownership !== "repo-managed") {
|
|
45594
45810
|
if (claudeContent) {
|
|
45595
45811
|
if (!fs32.existsSync(claudePath)) {
|
|
@@ -45624,7 +45840,7 @@ function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
|
|
|
45624
45840
|
}
|
|
45625
45841
|
}
|
|
45626
45842
|
const sourceInfo = claudeMdPath ? `**Source AGENTS.md:** ${claudeMdPath}` : `**Source:** ${sourceRoot}`;
|
|
45627
|
-
const summaryPath =
|
|
45843
|
+
const summaryPath = path67.join(projDir, "summary.md");
|
|
45628
45844
|
if (!fs32.existsSync(summaryPath)) {
|
|
45629
45845
|
atomicWriteText(
|
|
45630
45846
|
summaryPath,
|
|
@@ -45637,18 +45853,18 @@ ${summaryLines.length > 1 ? summaryLines.slice(1).join("\n") : ""}
|
|
|
45637
45853
|
`
|
|
45638
45854
|
);
|
|
45639
45855
|
}
|
|
45640
|
-
if (!fs32.existsSync(
|
|
45856
|
+
if (!fs32.existsSync(path67.join(projDir, FINDINGS_FILENAME))) {
|
|
45641
45857
|
atomicWriteText(
|
|
45642
|
-
|
|
45858
|
+
path67.join(projDir, FINDINGS_FILENAME),
|
|
45643
45859
|
`# ${projectName2} FINDINGS
|
|
45644
45860
|
|
|
45645
45861
|
<!-- Bootstrapped from ${sourceRoot} -->
|
|
45646
45862
|
`
|
|
45647
45863
|
);
|
|
45648
45864
|
}
|
|
45649
|
-
if (moduleEnabled(phrenPath, "tasks") && !fs32.existsSync(
|
|
45865
|
+
if (moduleEnabled(phrenPath, "tasks") && !fs32.existsSync(path67.join(projDir, TASKS_FILENAME))) {
|
|
45650
45866
|
atomicWriteText(
|
|
45651
|
-
|
|
45867
|
+
path67.join(projDir, TASKS_FILENAME),
|
|
45652
45868
|
`# ${projectName2} tasks
|
|
45653
45869
|
|
|
45654
45870
|
## Active
|
|
@@ -45659,11 +45875,11 @@ ${summaryLines.length > 1 ? summaryLines.slice(1).join("\n") : ""}
|
|
|
45659
45875
|
`
|
|
45660
45876
|
);
|
|
45661
45877
|
}
|
|
45662
|
-
if (!fs32.existsSync(
|
|
45878
|
+
if (!fs32.existsSync(path67.join(projDir, "topic-config.json"))) {
|
|
45663
45879
|
const inferredDomain = normalizeBuiltinTopicDomain(inferredScaffold?.domain ?? "software");
|
|
45664
45880
|
const inferredTopics = inferredScaffold?.topics?.length ? inferredScaffold.topics : getBuiltinTopicConfig(inferredDomain);
|
|
45665
45881
|
atomicWriteText(
|
|
45666
|
-
|
|
45882
|
+
path67.join(projDir, "topic-config.json"),
|
|
45667
45883
|
JSON.stringify({ version: 1, domain: inferredDomain, topics: inferredTopics }, null, 2) + "\n"
|
|
45668
45884
|
);
|
|
45669
45885
|
}
|
|
@@ -45695,10 +45911,10 @@ function addProjectFromPath(phrenPath, targetPath, requestedProfile, ownership,
|
|
|
45695
45911
|
if (!activeProfile.ok) return activeProfile;
|
|
45696
45912
|
const writePhrenPath = options.writeToPath ?? phrenPath;
|
|
45697
45913
|
const manifest = readRootManifest(phrenPath);
|
|
45698
|
-
const resolvedPath =
|
|
45914
|
+
const resolvedPath = path68.resolve(targetPath);
|
|
45699
45915
|
if (manifest?.installMode === "project-local") {
|
|
45700
|
-
const workspaceRoot =
|
|
45701
|
-
const matchesWorkspace = resolvedPath === workspaceRoot || resolvedPath.startsWith(workspaceRoot +
|
|
45916
|
+
const workspaceRoot = path68.resolve(manifest.workspaceRoot || "");
|
|
45917
|
+
const matchesWorkspace = resolvedPath === workspaceRoot || resolvedPath.startsWith(workspaceRoot + path68.sep);
|
|
45702
45918
|
if (!matchesWorkspace) {
|
|
45703
45919
|
return phrenErr(`Project-local phren can only add the owning workspace: ${workspaceRoot}`);
|
|
45704
45920
|
}
|
|
@@ -45716,9 +45932,9 @@ function addProjectFromPath(phrenPath, targetPath, requestedProfile, ownership,
|
|
|
45716
45932
|
ownership: added.ownership,
|
|
45717
45933
|
files: {
|
|
45718
45934
|
claude: added.claudePath,
|
|
45719
|
-
summary:
|
|
45720
|
-
findings:
|
|
45721
|
-
task:
|
|
45935
|
+
summary: path68.join(writePhrenPath, added.project, "summary.md"),
|
|
45936
|
+
findings: path68.join(writePhrenPath, added.project, FINDINGS_FILENAME),
|
|
45937
|
+
task: path68.join(writePhrenPath, added.project, TASKS_FILENAME)
|
|
45722
45938
|
}
|
|
45723
45939
|
});
|
|
45724
45940
|
}
|
|
@@ -45744,7 +45960,7 @@ import { execFileSync as execFileSync6, spawnSync as spawnSync2 } from "child_pr
|
|
|
45744
45960
|
import * as crypto9 from "crypto";
|
|
45745
45961
|
import * as fs33 from "fs";
|
|
45746
45962
|
import * as os3 from "os";
|
|
45747
|
-
import * as
|
|
45963
|
+
import * as path69 from "path";
|
|
45748
45964
|
|
|
45749
45965
|
// src/content/summarize.ts
|
|
45750
45966
|
init_phren_dotenv();
|
|
@@ -45905,7 +46121,7 @@ function mergeTasksByBid(base, ours, theirs) {
|
|
|
45905
46121
|
// src/sync/conflict-resolve.ts
|
|
45906
46122
|
function conflictStrategy(relFile) {
|
|
45907
46123
|
const file2 = relFile.replace(/\\/g, "/");
|
|
45908
|
-
const name =
|
|
46124
|
+
const name = path69.posix.basename(file2).toLowerCase();
|
|
45909
46125
|
if (isTaskFileName(name)) return "tasks";
|
|
45910
46126
|
if (name === "findings.md") return "findings";
|
|
45911
46127
|
if (/^\.config\/task-archive\/[^/]+\.md$/i.test(file2)) return "archive";
|
|
@@ -45940,9 +46156,9 @@ function splitBlock(content, start, end) {
|
|
|
45940
46156
|
function mergeText(base, ours, theirs) {
|
|
45941
46157
|
if (ours === theirs || ours === base) return theirs;
|
|
45942
46158
|
if (theirs === base) return ours;
|
|
45943
|
-
const dir = fs33.mkdtempSync(
|
|
46159
|
+
const dir = fs33.mkdtempSync(path69.join(os3.tmpdir(), "phren-merge-"));
|
|
45944
46160
|
try {
|
|
45945
|
-
const [o, b, t] = ["ours", "base", "theirs"].map((name) =>
|
|
46161
|
+
const [o, b, t] = ["ours", "base", "theirs"].map((name) => path69.join(dir, name));
|
|
45946
46162
|
fs33.writeFileSync(o, ours);
|
|
45947
46163
|
fs33.writeFileSync(b, base);
|
|
45948
46164
|
fs33.writeFileSync(t, theirs);
|
|
@@ -45955,9 +46171,9 @@ function mergeText(base, ours, theirs) {
|
|
|
45955
46171
|
function unionText(base, ours, theirs) {
|
|
45956
46172
|
const clean2 = mergeText(base, ours, theirs);
|
|
45957
46173
|
if (clean2 !== null) return clean2;
|
|
45958
|
-
const dir = fs33.mkdtempSync(
|
|
46174
|
+
const dir = fs33.mkdtempSync(path69.join(os3.tmpdir(), "phren-merge-"));
|
|
45959
46175
|
try {
|
|
45960
|
-
const [o, b, t] = ["ours", "base", "theirs"].map((name) =>
|
|
46176
|
+
const [o, b, t] = ["ours", "base", "theirs"].map((name) => path69.join(dir, name));
|
|
45961
46177
|
fs33.writeFileSync(o, ours);
|
|
45962
46178
|
fs33.writeFileSync(b, base);
|
|
45963
46179
|
fs33.writeFileSync(t, theirs);
|
|
@@ -46017,7 +46233,7 @@ function resolveStoreConflicts(cwd) {
|
|
|
46017
46233
|
const base = stage(cwd, 1, relFile) ?? "";
|
|
46018
46234
|
const ours = stage(cwd, 2, relFile);
|
|
46019
46235
|
const theirs = stage(cwd, 3, relFile);
|
|
46020
|
-
const fullPath =
|
|
46236
|
+
const fullPath = path69.join(cwd, relFile);
|
|
46021
46237
|
if (ours === null && theirs === null) {
|
|
46022
46238
|
unresolved.push(relFile);
|
|
46023
46239
|
continue;
|
|
@@ -46028,7 +46244,7 @@ function resolveStoreConflicts(cwd) {
|
|
|
46028
46244
|
continue;
|
|
46029
46245
|
}
|
|
46030
46246
|
const tmp = `${fullPath}.tmp-${crypto9.randomUUID()}`;
|
|
46031
|
-
fs33.mkdirSync(
|
|
46247
|
+
fs33.mkdirSync(path69.dirname(fullPath), { recursive: true });
|
|
46032
46248
|
fs33.writeFileSync(tmp, merged);
|
|
46033
46249
|
fs33.renameSync(tmp, fullPath);
|
|
46034
46250
|
git4(cwd, ["add", "--", relFile]);
|
|
@@ -46295,7 +46511,7 @@ async function runBestEffortGit(args, cwd) {
|
|
|
46295
46511
|
// src/bridge/enroll.ts
|
|
46296
46512
|
init_metrics();
|
|
46297
46513
|
init_machine_identity();
|
|
46298
|
-
var
|
|
46514
|
+
var exec11 = promisify11(execFile12);
|
|
46299
46515
|
var runEnrollStoreGit = async (cwd, args) => {
|
|
46300
46516
|
const result = await runBestEffortGit(args, cwd);
|
|
46301
46517
|
return { ok: result.ok, output: result.output ?? "", error: result.error };
|
|
@@ -46308,7 +46524,7 @@ function repoName(url2) {
|
|
|
46308
46524
|
}
|
|
46309
46525
|
async function isRepository(directory) {
|
|
46310
46526
|
try {
|
|
46311
|
-
await
|
|
46527
|
+
await stat20(path70.join(directory, ".git"));
|
|
46312
46528
|
return true;
|
|
46313
46529
|
} catch {
|
|
46314
46530
|
return false;
|
|
@@ -46319,7 +46535,7 @@ async function registeredSources(env) {
|
|
|
46319
46535
|
const paths = /* @__PURE__ */ new Set(), names = /* @__PURE__ */ new Set();
|
|
46320
46536
|
let entries2 = [];
|
|
46321
46537
|
try {
|
|
46322
|
-
entries2 = (await
|
|
46538
|
+
entries2 = (await readdir12(store, { withFileTypes: true })).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => e.name);
|
|
46323
46539
|
} catch {
|
|
46324
46540
|
return { paths, names };
|
|
46325
46541
|
}
|
|
@@ -46328,7 +46544,7 @@ async function registeredSources(env) {
|
|
|
46328
46544
|
const source = readProjectConfig(store, project).sourcePath;
|
|
46329
46545
|
if (typeof source === "string" && source) {
|
|
46330
46546
|
try {
|
|
46331
|
-
paths.add(realpathSync5.native(
|
|
46547
|
+
paths.add(realpathSync5.native(path70.resolve(source)));
|
|
46332
46548
|
} catch {
|
|
46333
46549
|
}
|
|
46334
46550
|
}
|
|
@@ -46340,9 +46556,9 @@ async function candidateRepos(activity, env = process.env) {
|
|
|
46340
46556
|
const found = [];
|
|
46341
46557
|
const seen = /* @__PURE__ */ new Set();
|
|
46342
46558
|
const offer = async (directory, source, lastSeen) => {
|
|
46343
|
-
let dir =
|
|
46559
|
+
let dir = path70.resolve(directory);
|
|
46344
46560
|
try {
|
|
46345
|
-
if (!(await
|
|
46561
|
+
if (!(await stat20(dir)).isDirectory()) return;
|
|
46346
46562
|
dir = realpathSync5.native(dir);
|
|
46347
46563
|
} catch {
|
|
46348
46564
|
return;
|
|
@@ -46354,39 +46570,39 @@ async function candidateRepos(activity, env = process.env) {
|
|
|
46354
46570
|
};
|
|
46355
46571
|
const toplevel = async (directory) => {
|
|
46356
46572
|
let existing = directory;
|
|
46357
|
-
while (!await
|
|
46358
|
-
const parent =
|
|
46573
|
+
while (!await stat20(existing).catch(() => void 0)) {
|
|
46574
|
+
const parent = path70.dirname(existing);
|
|
46359
46575
|
if (parent === existing) return void 0;
|
|
46360
46576
|
existing = parent;
|
|
46361
46577
|
}
|
|
46362
46578
|
try {
|
|
46363
46579
|
countGit("enroll");
|
|
46364
|
-
return (await
|
|
46580
|
+
return (await exec11("git", ["-C", existing, "rev-parse", "--show-toplevel"], { env: nonInteractiveGitEnv(), timeout: 5e3 })).stdout.trim() || void 0;
|
|
46365
46581
|
} catch {
|
|
46366
46582
|
return void 0;
|
|
46367
46583
|
}
|
|
46368
46584
|
};
|
|
46369
46585
|
for (const event of [...activity].reverse()) {
|
|
46370
46586
|
const directory = typeof event.directory === "string" ? event.directory : void 0;
|
|
46371
|
-
if (!directory || !
|
|
46587
|
+
if (!directory || !path70.isAbsolute(directory)) continue;
|
|
46372
46588
|
const root = await toplevel(directory);
|
|
46373
46589
|
if (root) await offer(root, "activity", typeof event.at === "string" ? event.at : void 0);
|
|
46374
46590
|
}
|
|
46375
46591
|
try {
|
|
46376
|
-
const session = JSON.parse(await readFile27(
|
|
46592
|
+
const session = JSON.parse(await readFile27(path70.join(herdrRoot(), "session.json"), "utf8"));
|
|
46377
46593
|
for (const match of JSON.stringify(session).matchAll(/"cwd":\s*"((?:\\.|[^"\\])*)"/g)) {
|
|
46378
46594
|
const directory = JSON.parse(`"${match[1]}"`);
|
|
46379
|
-
if (!
|
|
46595
|
+
if (!path70.isAbsolute(directory)) continue;
|
|
46380
46596
|
const root = await toplevel(directory);
|
|
46381
46597
|
if (root) await offer(root, "herdr");
|
|
46382
46598
|
}
|
|
46383
46599
|
} catch {
|
|
46384
46600
|
}
|
|
46385
46601
|
const home = homedir17();
|
|
46386
|
-
for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.map((r) =>
|
|
46602
|
+
for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.map((r) => path70.join(home, r))]) {
|
|
46387
46603
|
let children = [];
|
|
46388
46604
|
try {
|
|
46389
|
-
children = (await
|
|
46605
|
+
children = (await readdir12(root, { withFileTypes: true })).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => path70.join(root, e.name));
|
|
46390
46606
|
} catch {
|
|
46391
46607
|
continue;
|
|
46392
46608
|
}
|
|
@@ -46396,13 +46612,13 @@ async function candidateRepos(activity, env = process.env) {
|
|
|
46396
46612
|
}
|
|
46397
46613
|
async function cloneRoot(env) {
|
|
46398
46614
|
const home = homedir17();
|
|
46399
|
-
for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.filter((r) => r !== "Sites").map((r) =>
|
|
46615
|
+
for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.filter((r) => r !== "Sites").map((r) => path70.join(home, r))]) {
|
|
46400
46616
|
try {
|
|
46401
|
-
if ((await
|
|
46617
|
+
if ((await stat20(root)).isDirectory()) return root;
|
|
46402
46618
|
} catch {
|
|
46403
46619
|
}
|
|
46404
46620
|
}
|
|
46405
|
-
const fallback =
|
|
46621
|
+
const fallback = path70.join(home, "Projects");
|
|
46406
46622
|
await mkdir15(fallback, { recursive: true });
|
|
46407
46623
|
return fallback;
|
|
46408
46624
|
}
|
|
@@ -46424,7 +46640,7 @@ async function publishStore(store, project) {
|
|
|
46424
46640
|
async function enrollProject(input2, env = process.env) {
|
|
46425
46641
|
const store = phrenStoreRoot(env);
|
|
46426
46642
|
try {
|
|
46427
|
-
if (!(await
|
|
46643
|
+
if (!(await stat20(path70.join(store, ".config"))).isDirectory()) throw new Error();
|
|
46428
46644
|
} catch {
|
|
46429
46645
|
throw new BridgeError(409, "phren is not set up on this computer. Run phren init there.");
|
|
46430
46646
|
}
|
|
@@ -46435,16 +46651,16 @@ async function enrollProject(input2, env = process.env) {
|
|
|
46435
46651
|
if (url2.length > 512 || !CLONE_URL.test(url2)) throw new BridgeError(400, "Enter a GitHub repository URL (https://github.com/owner/repo).");
|
|
46436
46652
|
const name = repoName(url2);
|
|
46437
46653
|
if (!name || name === "." || name === "..") throw new BridgeError(400, "That URL has no repository name.");
|
|
46438
|
-
directory =
|
|
46654
|
+
directory = path70.join(await cloneRoot(env), name);
|
|
46439
46655
|
try {
|
|
46440
|
-
await
|
|
46656
|
+
await stat20(directory);
|
|
46441
46657
|
throw new BridgeError(409, `${directory} already exists on this computer. Add that folder instead.`);
|
|
46442
46658
|
} catch (error62) {
|
|
46443
46659
|
if (error62 instanceof BridgeError) throw error62;
|
|
46444
46660
|
}
|
|
46445
46661
|
try {
|
|
46446
46662
|
countGit("enroll");
|
|
46447
|
-
await
|
|
46663
|
+
await exec11("git", ["clone", "--", url2, directory], { timeout: 18e4, maxBuffer: 4194304, env: nonInteractiveGitEnv(env) });
|
|
46448
46664
|
} catch (error62) {
|
|
46449
46665
|
const detail = error62 instanceof Error && "stderr" in error62 ? String(error62.stderr ?? "").trim().split("\n").pop() : void 0;
|
|
46450
46666
|
throw new BridgeError(502, `git clone failed${detail ? `: ${detail}` : ""}.`);
|
|
@@ -46452,10 +46668,10 @@ async function enrollProject(input2, env = process.env) {
|
|
|
46452
46668
|
cloned = true;
|
|
46453
46669
|
} else if (typeof input2.directory === "string" && input2.directory) {
|
|
46454
46670
|
const raw = input2.directory;
|
|
46455
|
-
if (raw.length > 4096 || raw.includes("\0") || !
|
|
46671
|
+
if (raw.length > 4096 || raw.includes("\0") || !path70.isAbsolute(raw)) throw new BridgeError(400, "Enter the full folder path on this computer.");
|
|
46456
46672
|
try {
|
|
46457
46673
|
directory = realpathSync5.native(raw);
|
|
46458
|
-
if (!(await
|
|
46674
|
+
if (!(await stat20(directory)).isDirectory()) throw new Error();
|
|
46459
46675
|
} catch {
|
|
46460
46676
|
throw new BridgeError(404, "That folder is not on this computer.");
|
|
46461
46677
|
}
|
|
@@ -46468,33 +46684,33 @@ async function enrollProject(input2, env = process.env) {
|
|
|
46468
46684
|
// src/bridge/files.ts
|
|
46469
46685
|
init_protocol();
|
|
46470
46686
|
import { constants as constants3 } from "node:fs";
|
|
46471
|
-
import { lstat as lstat15, open as
|
|
46472
|
-
import
|
|
46687
|
+
import { lstat as lstat15, open as open13, readdir as readdir13, realpath as realpath12 } from "node:fs/promises";
|
|
46688
|
+
import path71 from "node:path";
|
|
46473
46689
|
var MAX_BYTES = 2097152;
|
|
46474
46690
|
async function browseFiles(root, relative3) {
|
|
46475
|
-
if (relative3.length > 4096 || relative3.includes("\0") || relative3.includes("\\") ||
|
|
46691
|
+
if (relative3.length > 4096 || relative3.includes("\0") || relative3.includes("\\") || path71.isAbsolute(relative3) || relative3.split("/").some((part) => part === ".." || part === ".git")) {
|
|
46476
46692
|
throw new BridgeError(400, "Invalid repository path.");
|
|
46477
46693
|
}
|
|
46478
|
-
const base = await
|
|
46694
|
+
const base = await realpath12(root);
|
|
46479
46695
|
let file2 = base;
|
|
46480
46696
|
for (const part of relative3.split("/").filter((part2) => part2 && part2 !== ".")) {
|
|
46481
|
-
file2 =
|
|
46697
|
+
file2 = path71.join(file2, part);
|
|
46482
46698
|
if ((await lstat15(file2)).isSymbolicLink()) throw new BridgeError(403, "Symbolic links cannot be browsed.");
|
|
46483
46699
|
}
|
|
46484
|
-
const resolved = await
|
|
46485
|
-
if (resolved !== base && !resolved.startsWith(base +
|
|
46700
|
+
const resolved = await realpath12(file2);
|
|
46701
|
+
if (resolved !== base && !resolved.startsWith(base + path71.sep)) throw new BridgeError(403, "The path is outside this repository.");
|
|
46486
46702
|
const metadata = await lstat15(resolved);
|
|
46487
46703
|
if (metadata.isDirectory()) {
|
|
46488
|
-
const entries2 = (await
|
|
46704
|
+
const entries2 = (await readdir13(resolved, { withFileTypes: true })).filter((entry) => entry.name !== ".git" && (entry.isDirectory() || entry.isFile())).sort((a, b) => Number(b.isDirectory()) - Number(a.isDirectory()) || a.name.localeCompare(b.name));
|
|
46489
46705
|
return {
|
|
46490
46706
|
path: relative3,
|
|
46491
46707
|
kind: "directory",
|
|
46492
46708
|
truncated: entries2.length > 500,
|
|
46493
|
-
entries: entries2.slice(0, 500).map((entry) => ({ name: entry.name, path:
|
|
46709
|
+
entries: entries2.slice(0, 500).map((entry) => ({ name: entry.name, path: path71.posix.join(relative3, entry.name), kind: entry.isDirectory() ? "directory" : "file" }))
|
|
46494
46710
|
};
|
|
46495
46711
|
}
|
|
46496
46712
|
if (!metadata.isFile()) throw new BridgeError(400, "Only regular files can be viewed.");
|
|
46497
|
-
const handle = await
|
|
46713
|
+
const handle = await open13(resolved, constants3.O_RDONLY | constants3.O_NOFOLLOW | constants3.O_NONBLOCK);
|
|
46498
46714
|
try {
|
|
46499
46715
|
const current2 = await handle.stat();
|
|
46500
46716
|
if (!current2.isFile() || current2.ino !== metadata.ino || current2.dev !== metadata.dev) throw new BridgeError(409, "The file changed. Refresh and try again.");
|
|
@@ -46516,8 +46732,8 @@ async function browseFiles(root, relative3) {
|
|
|
46516
46732
|
// src/bridge/file-range.ts
|
|
46517
46733
|
init_protocol();
|
|
46518
46734
|
import { constants as constants4 } from "node:fs";
|
|
46519
|
-
import { lstat as lstat16, open as
|
|
46520
|
-
import
|
|
46735
|
+
import { lstat as lstat16, open as open14, realpath as realpath13 } from "node:fs/promises";
|
|
46736
|
+
import path72 from "node:path";
|
|
46521
46737
|
var MAX_FILE_RANGE = 4 * 1024 * 1024;
|
|
46522
46738
|
var types = {
|
|
46523
46739
|
mp4: "video/mp4",
|
|
@@ -46554,11 +46770,11 @@ var types = {
|
|
|
46554
46770
|
xml: "text/xml"
|
|
46555
46771
|
};
|
|
46556
46772
|
function fileContentType(file2) {
|
|
46557
|
-
const ext =
|
|
46773
|
+
const ext = path72.extname(file2).slice(1).toLowerCase();
|
|
46558
46774
|
return types[ext] ?? (/^(ts|tsx|js|jsx|swift|py|rs|go|rb|sh|bash|zsh|c|h|cpp|hpp|cs|java|kt|html|css|scss|sql|toml|ini)$/.test(ext) ? "text/plain" : "application/octet-stream");
|
|
46559
46775
|
}
|
|
46560
|
-
function version2(
|
|
46561
|
-
return `${
|
|
46776
|
+
function version2(stat27) {
|
|
46777
|
+
return `${stat27.dev}:${stat27.ino}:${stat27.size}:${stat27.mtimeMs}:${stat27.ctimeMs}`;
|
|
46562
46778
|
}
|
|
46563
46779
|
function rangeInteger(value2, fallback) {
|
|
46564
46780
|
if (value2 === null) return fallback;
|
|
@@ -46571,22 +46787,22 @@ async function readFileRange(root, requested, offset, length, expectedVersion) {
|
|
|
46571
46787
|
throw new BridgeError(400, "File ranges must be between 0 and 4 MiB.");
|
|
46572
46788
|
}
|
|
46573
46789
|
try {
|
|
46574
|
-
const base = await
|
|
46575
|
-
const relative3 =
|
|
46576
|
-
if (relative3 === ".." || relative3.startsWith(`..${
|
|
46790
|
+
const base = await realpath13(root);
|
|
46791
|
+
const relative3 = path72.isAbsolute(requested) ? path72.relative(base, requested) : requested;
|
|
46792
|
+
if (relative3 === ".." || relative3.startsWith(`..${path72.sep}`) || path72.isAbsolute(relative3)) throw new BridgeError(403, "This file is outside the allowed folder.");
|
|
46577
46793
|
let file2 = base;
|
|
46578
|
-
for (const part of relative3.split(
|
|
46579
|
-
file2 =
|
|
46794
|
+
for (const part of relative3.split(path72.sep).filter((part2) => part2 && part2 !== ".")) {
|
|
46795
|
+
file2 = path72.join(file2, part);
|
|
46580
46796
|
if ((await lstat16(file2)).isSymbolicLink()) throw new BridgeError(403, "Symbolic links cannot be opened.");
|
|
46581
46797
|
}
|
|
46582
|
-
const resolved = await
|
|
46583
|
-
if (!resolved.startsWith(base +
|
|
46798
|
+
const resolved = await realpath13(file2);
|
|
46799
|
+
if (!resolved.startsWith(base + path72.sep)) throw new BridgeError(403, "This file is outside the allowed folder.");
|
|
46584
46800
|
const metadata = await lstat16(resolved);
|
|
46585
46801
|
if (!metadata.isFile()) throw new BridgeError(400, "Only regular files can be opened.");
|
|
46586
|
-
const handle = await
|
|
46802
|
+
const handle = await open14(resolved, constants4.O_RDONLY | constants4.O_NOFOLLOW | constants4.O_NONBLOCK);
|
|
46587
46803
|
try {
|
|
46588
46804
|
const current2 = await handle.stat();
|
|
46589
|
-
if (!current2.isFile() || version2(current2) !== version2(metadata) || await
|
|
46805
|
+
if (!current2.isFile() || version2(current2) !== version2(metadata) || await realpath13(file2) !== resolved) {
|
|
46590
46806
|
throw new BridgeError(409, "The file changed. Open it again.");
|
|
46591
46807
|
}
|
|
46592
46808
|
const revision = version2(current2);
|
|
@@ -46622,12 +46838,12 @@ async function readFileRange(root, requested, offset, length, expectedVersion) {
|
|
|
46622
46838
|
// src/bridge/memory-store.ts
|
|
46623
46839
|
init_zod();
|
|
46624
46840
|
init_protocol();
|
|
46625
|
-
import { execFile as
|
|
46841
|
+
import { execFile as execFile13 } from "node:child_process";
|
|
46626
46842
|
import { createHash as createHash15 } from "node:crypto";
|
|
46627
|
-
import { lstat as lstat17, mkdir as mkdir16, readFile as readFile28, realpath as
|
|
46628
|
-
import
|
|
46629
|
-
import { promisify as
|
|
46630
|
-
var
|
|
46843
|
+
import { lstat as lstat17, mkdir as mkdir16, readFile as readFile28, realpath as realpath14, rename as rename7, rm as rm8, writeFile as writeFile8 } from "node:fs/promises";
|
|
46844
|
+
import path73 from "node:path";
|
|
46845
|
+
import { promisify as promisify12 } from "node:util";
|
|
46846
|
+
var exec12 = promisify12(execFile13);
|
|
46631
46847
|
var SHA = /^[0-9a-f]{40}$/;
|
|
46632
46848
|
var MAX_FILE = 4 * 1024 * 1024;
|
|
46633
46849
|
var queue = Promise.resolve();
|
|
@@ -46638,7 +46854,7 @@ function serialized(work) {
|
|
|
46638
46854
|
}
|
|
46639
46855
|
async function git5(store, args, env = {}) {
|
|
46640
46856
|
try {
|
|
46641
|
-
const { stdout } = await
|
|
46857
|
+
const { stdout } = await exec12("git", ["-C", store, ...args], {
|
|
46642
46858
|
env: { ...process.env, ...env, GIT_TERMINAL_PROMPT: "0" },
|
|
46643
46859
|
maxBuffer: 64 * 1024 * 1024,
|
|
46644
46860
|
timeout: 6e4
|
|
@@ -46653,12 +46869,12 @@ function blobSha(content) {
|
|
|
46653
46869
|
return createHash15("sha1").update(`blob ${content.length}\0`).update(content).digest("hex");
|
|
46654
46870
|
}
|
|
46655
46871
|
async function isRepository2(store) {
|
|
46656
|
-
return await lstat17(
|
|
46872
|
+
return await lstat17(path73.join(store, ".git")).catch(() => void 0) !== void 0;
|
|
46657
46873
|
}
|
|
46658
|
-
function storeHead(store, indexFile =
|
|
46874
|
+
function storeHead(store, indexFile = path73.join(bridgeRoot(), "store-snapshot.index")) {
|
|
46659
46875
|
return serialized(async () => {
|
|
46660
46876
|
if (!await isRepository2(store)) throw new BridgeError(409, "This computer's phren store is not a git repository. Run phren init.");
|
|
46661
|
-
await mkdir16(
|
|
46877
|
+
await mkdir16(path73.dirname(indexFile), { recursive: true, mode: 448 });
|
|
46662
46878
|
const env = { GIT_INDEX_FILE: indexFile };
|
|
46663
46879
|
if (!await lstat17(indexFile).catch(() => void 0)) {
|
|
46664
46880
|
const head = await git5(store, ["rev-parse", "--verify", "--quiet", "HEAD"]).catch(() => "");
|
|
@@ -46681,25 +46897,25 @@ async function storeTree(store, sha) {
|
|
|
46681
46897
|
async function storeBlob(store, sha) {
|
|
46682
46898
|
if (!SHA.test(sha)) throw new BridgeError(400, "Invalid blob sha.");
|
|
46683
46899
|
if ((await git5(store, ["cat-file", "-t", sha]).catch(() => "")).trim() !== "blob") throw new BridgeError(404, "Unknown blob.");
|
|
46684
|
-
const { stdout } = await
|
|
46900
|
+
const { stdout } = await exec12("git", ["-C", store, "cat-file", "blob", sha], { encoding: "buffer", maxBuffer: MAX_FILE * 4 });
|
|
46685
46901
|
return { sha, encoding: "base64", content: stdout.toString("base64") };
|
|
46686
46902
|
}
|
|
46687
46903
|
async function storeFile(store, relative3) {
|
|
46688
|
-
const normalized =
|
|
46689
|
-
if (!relative3 || relative3 !== normalized || normalized.startsWith("../") || normalized === ".." ||
|
|
46904
|
+
const normalized = path73.posix.normalize(relative3);
|
|
46905
|
+
if (!relative3 || relative3 !== normalized || normalized.startsWith("../") || normalized === ".." || path73.posix.isAbsolute(normalized) || normalized.split("/").some((part) => part === ".git" || part === "" || part === ".") || /[\0\r\n]/.test(normalized)) {
|
|
46690
46906
|
throw new BridgeError(400, "Invalid store path.");
|
|
46691
46907
|
}
|
|
46692
|
-
const root = await
|
|
46693
|
-
let parent =
|
|
46908
|
+
const root = await realpath14(store);
|
|
46909
|
+
let parent = path73.dirname(path73.join(root, normalized));
|
|
46694
46910
|
for (; ; ) {
|
|
46695
|
-
const
|
|
46696
|
-
if (
|
|
46697
|
-
if (
|
|
46911
|
+
const real2 = await realpath14(parent).catch(() => void 0);
|
|
46912
|
+
if (real2) {
|
|
46913
|
+
if (real2 !== root && !real2.startsWith(root + path73.sep)) throw new BridgeError(400, "Invalid store path.");
|
|
46698
46914
|
break;
|
|
46699
46915
|
}
|
|
46700
|
-
parent =
|
|
46916
|
+
parent = path73.dirname(parent);
|
|
46701
46917
|
}
|
|
46702
|
-
const file2 =
|
|
46918
|
+
const file2 = path73.join(root, normalized);
|
|
46703
46919
|
const info = await lstat17(file2).catch(() => void 0);
|
|
46704
46920
|
if (info && !info.isFile()) throw new BridgeError(400, "Invalid store path.");
|
|
46705
46921
|
return file2;
|
|
@@ -46720,7 +46936,7 @@ function putStoreFile(store, data) {
|
|
|
46720
46936
|
return serialized(async () => {
|
|
46721
46937
|
const file2 = await storeFile(store, input2.path);
|
|
46722
46938
|
if (await currentSha(file2) !== (input2.sha ?? null)) throw new BridgeError(409, `${input2.path} changed on this computer.`);
|
|
46723
|
-
await mkdir16(
|
|
46939
|
+
await mkdir16(path73.dirname(file2), { recursive: true });
|
|
46724
46940
|
const temporary = `${file2}.phren-${process.pid}-${Date.now()}`;
|
|
46725
46941
|
await writeFile8(temporary, content, { flag: "wx" });
|
|
46726
46942
|
await rename7(temporary, file2);
|
|
@@ -46752,17 +46968,17 @@ init_protocol();
|
|
|
46752
46968
|
|
|
46753
46969
|
// src/bridge/simulators.ts
|
|
46754
46970
|
init_protocol();
|
|
46755
|
-
import { execFile as
|
|
46756
|
-
import { chmod as chmod4, mkdir as mkdir17, readFile as readFile29, rename as rename8, stat as
|
|
46971
|
+
import { execFile as execFile14 } from "node:child_process";
|
|
46972
|
+
import { chmod as chmod4, mkdir as mkdir17, readFile as readFile29, rename as rename8, stat as stat21, unlink as unlink5, writeFile as writeFile9 } from "node:fs/promises";
|
|
46757
46973
|
import { tmpdir as tmpdir3 } from "node:os";
|
|
46758
|
-
import
|
|
46974
|
+
import path74 from "node:path";
|
|
46759
46975
|
import { createHash as createHash16, randomUUID as randomUUID17 } from "node:crypto";
|
|
46760
|
-
import { promisify as
|
|
46761
|
-
var
|
|
46976
|
+
import { promisify as promisify13 } from "node:util";
|
|
46977
|
+
var exec13 = promisify13(execFile14);
|
|
46762
46978
|
var UDID = /^[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}$/i;
|
|
46763
46979
|
async function bootedSimulators() {
|
|
46764
46980
|
if (process.platform !== "darwin") return [];
|
|
46765
|
-
const { stdout } = await
|
|
46981
|
+
const { stdout } = await exec13("/usr/bin/xcrun", ["simctl", "list", "devices", "booted", "-j"], { timeout: 8e3, maxBuffer: 4194304 }).catch(() => ({ stdout: "{}" }));
|
|
46766
46982
|
let parsed = {};
|
|
46767
46983
|
try {
|
|
46768
46984
|
parsed = JSON.parse(stdout);
|
|
@@ -46783,9 +46999,9 @@ async function bootedSimulators() {
|
|
|
46783
46999
|
async function simulatorScreenshot(udid) {
|
|
46784
47000
|
if (!UDID.test(udid)) throw new BridgeError(400, "Invalid simulator identifier.");
|
|
46785
47001
|
if (process.platform !== "darwin") throw new BridgeError(404, "Simulators run on macOS only.");
|
|
46786
|
-
const file2 =
|
|
47002
|
+
const file2 = path74.join(tmpdir3(), `phren-sim-${randomUUID17()}.png`);
|
|
46787
47003
|
try {
|
|
46788
|
-
await
|
|
47004
|
+
await exec13("/usr/bin/xcrun", ["simctl", "io", udid, "screenshot", "--type=png", file2], { timeout: 15e3 });
|
|
46789
47005
|
return await readFile29(file2);
|
|
46790
47006
|
} catch (error62) {
|
|
46791
47007
|
if (error62 instanceof BridgeError) throw error62;
|
|
@@ -46802,18 +47018,18 @@ function helper() {
|
|
|
46802
47018
|
return building;
|
|
46803
47019
|
}
|
|
46804
47020
|
async function buildHelper() {
|
|
46805
|
-
const dir =
|
|
46806
|
-
const binary =
|
|
47021
|
+
const dir = path74.join(bridgeRoot(), "native");
|
|
47022
|
+
const binary = path74.join(dir, "simtap");
|
|
46807
47023
|
const code = true ? '// Touches and keys for the iOS Simulator, without AppleScript: the window\n// is found through the Accessibility API and events are posted with CGEvent,\n// so one Accessibility grant for this helper is all macOS asks for.\n// Built on demand by Phren Hook with swiftc; see simulators.ts.\nimport ApplicationServices\nimport Cocoa\n\nfunc fail(_ code: Int32, _ message: String) -> Never { FileHandle.standardError.write((message + "\\n").data(using: .utf8)!); exit(code) }\n\nlet args = CommandLine.arguments\nguard args.count >= 3 else { fail(2, "usage: simtap <window-title-prefix> tap <fx> <fy> | key <keycode> [cmd] [shift] | type <text> | raise") }\nlet prefix = args[1], command = args[2]\n\nguard AXIsProcessTrusted() else { fail(3, "accessibility") }\nguard let app = NSRunningApplication.runningApplications(withBundleIdentifier: "com.apple.iphonesimulator").first else { fail(4, "Simulator is not running") }\nlet element = AXUIElementCreateApplication(app.processIdentifier)\nvar windowsRef: CFTypeRef?\nAXUIElementCopyAttributeValue(element, kAXWindowsAttribute as CFString, &windowsRef)\nlet windows = (windowsRef as? [AXUIElement]) ?? []\nvar target: AXUIElement?\nfor window in windows {\n var titleRef: CFTypeRef?\n AXUIElementCopyAttributeValue(window, kAXTitleAttribute as CFString, &titleRef)\n if let title = titleRef as? String, title.hasPrefix(prefix + " ") || title == prefix { target = window; break }\n}\nguard let window = target else { fail(5, "no window for \\(prefix)") }\n\nfunc frame(_ window: AXUIElement) -> CGRect {\n var posRef: CFTypeRef?, sizeRef: CFTypeRef?\n AXUIElementCopyAttributeValue(window, kAXPositionAttribute as CFString, &posRef)\n AXUIElementCopyAttributeValue(window, kAXSizeAttribute as CFString, &sizeRef)\n var pos = CGPoint.zero, size = CGSize.zero\n if let p = posRef { AXValueGetValue(p as! AXValue, .cgPoint, &pos) }\n if let s = sizeRef { AXValueGetValue(s as! AXValue, .cgSize, &size) }\n return CGRect(origin: pos, size: size)\n}\nfunc raise() {\n app.activate(options: [])\n AXUIElementPerformAction(window, kAXRaiseAction as CFString)\n usleep(120_000)\n}\nfunc post(_ event: CGEvent?) {\n guard NSWorkspace.shared.frontmostApplication?.processIdentifier == app.processIdentifier else { fail(6, "focus lost") }\n event?.postToPid(app.processIdentifier)\n usleep(40_000)\n}\n\nswitch command {\ncase "raise": raise()\ncase "tap":\n guard args.count >= 5, let fx = Double(args[3]), let fy = Double(args[4]) else { fail(2, "tap needs fx fy") }\n raise()\n let f = frame(window)\n // The device screen fills the window below its title bar.\n let titleBar: CGFloat = 28\n let point = CGPoint(x: f.origin.x + CGFloat(fx) * f.width, y: f.origin.y + titleBar + CGFloat(fy) * (f.height - titleBar))\n post(CGEvent(mouseEventSource: nil, mouseType: .mouseMoved, mouseCursorPosition: point, mouseButton: .left))\n post(CGEvent(mouseEventSource: nil, mouseType: .leftMouseDown, mouseCursorPosition: point, mouseButton: .left))\n post(CGEvent(mouseEventSource: nil, mouseType: .leftMouseUp, mouseCursorPosition: point, mouseButton: .left))\ncase "key":\n guard args.count >= 4, let code = UInt16(args[3]) else { fail(2, "key needs a keycode") }\n raise()\n var flags: CGEventFlags = []\n if args.contains("cmd") { flags.insert(.maskCommand) }\n if args.contains("shift") { flags.insert(.maskShift) }\n let down = CGEvent(keyboardEventSource: nil, virtualKey: code, keyDown: true), up = CGEvent(keyboardEventSource: nil, virtualKey: code, keyDown: false)\n down?.flags = flags; up?.flags = flags\n post(down); post(up)\ncase "type":\n guard args.count >= 4, !args[3].isEmpty, args[3].utf16.count <= 500 else { fail(2, "type needs at most 500 characters") }\n let submit = args.count == 5 && args[4] == "submit"\n guard args[3].unicodeScalars.allSatisfy({ scalar in\n (scalar.value >= 32 && scalar.value != 127) || (scalar.value == 10 && submit)\n }) else { fail(2, "invalid type controls; newline needs submit") }\n raise()\n for scalar in args[3].unicodeScalars {\n var chars = Array(String(scalar).utf16)\n let down = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: true), up = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: false)\n down?.keyboardSetUnicodeString(stringLength: chars.count, unicodeString: &chars)\n up?.keyboardSetUnicodeString(stringLength: chars.count, unicodeString: &chars)\n post(down); post(up)\n }\ndefault: fail(2, "unknown command \\(command)")\n}\n' : await readFile29(new URL("./native/simtap.swift", import.meta.url), "utf8");
|
|
46808
47024
|
const digest2 = createHash16("sha256").update(code).digest("hex");
|
|
46809
47025
|
const saved = await readFile29(binary + ".sha256", "utf8").then(JSON.parse).catch(() => void 0);
|
|
46810
|
-
if (await
|
|
47026
|
+
if (await stat21(binary).catch(() => void 0) && saved?.sourceSha === digest2) return binary;
|
|
46811
47027
|
await mkdir17(dir, { recursive: true, mode: 448 });
|
|
46812
|
-
const temporary =
|
|
47028
|
+
const temporary = path74.join(dir, `simtap.${randomUUID17()}`), source = temporary + ".swift";
|
|
46813
47029
|
const sidecar = temporary + ".sha256";
|
|
46814
47030
|
try {
|
|
46815
47031
|
await writeFile9(source, code, { mode: 384, flag: "wx" });
|
|
46816
|
-
await
|
|
47032
|
+
await exec13("/usr/bin/swiftc", ["-O", "-o", temporary, source], { timeout: 18e4 }).catch(() => {
|
|
46817
47033
|
throw new BridgeError(409, "Couldn't build the simulator input helper (needs Xcode's swiftc).");
|
|
46818
47034
|
});
|
|
46819
47035
|
await chmod4(temporary, 448);
|
|
@@ -46839,7 +47055,7 @@ async function executeSimtap(name, ...args) {
|
|
|
46839
47055
|
const binarySha = createHash16("sha256").update(await readFile29(binary)).digest("hex");
|
|
46840
47056
|
if (!saved || saved.binarySha !== binarySha) throw new BridgeError(409, "Simulator input helper integrity check failed.");
|
|
46841
47057
|
try {
|
|
46842
|
-
await
|
|
47058
|
+
await exec13(binary, [name, ...args], { timeout: 6e4 });
|
|
46843
47059
|
} catch (error62) {
|
|
46844
47060
|
const failure2 = error62;
|
|
46845
47061
|
const message = String(failure2?.stderr ?? failure2?.message ?? "");
|
|
@@ -46855,7 +47071,7 @@ async function simulatorAct(udid, request6) {
|
|
|
46855
47071
|
if (!UDID.test(udid)) throw new BridgeError(400, "Invalid simulator identifier.");
|
|
46856
47072
|
if (!["boot", "shutdown", "launch", "openurl", "home", "lock", "type", "tap", "screenshot-ready"].includes(request6.action)) throw new BridgeError(400, "Unknown simulator action.");
|
|
46857
47073
|
if (process.platform !== "darwin") throw new BridgeError(404, "Simulators run on macOS only.");
|
|
46858
|
-
const simctl = (...args) =>
|
|
47074
|
+
const simctl = (...args) => exec13("/usr/bin/xcrun", ["simctl", ...args], { timeout: 3e4 }).catch(() => {
|
|
46859
47075
|
throw new BridgeError(409, `simctl ${args[0]} failed for that simulator.`);
|
|
46860
47076
|
});
|
|
46861
47077
|
switch (request6.action) {
|
|
@@ -46904,7 +47120,7 @@ async function deviceName(udid) {
|
|
|
46904
47120
|
async function simulatorApps(udid) {
|
|
46905
47121
|
if (!UDID.test(udid)) throw new BridgeError(400, "Invalid simulator identifier.");
|
|
46906
47122
|
if (process.platform !== "darwin") return [];
|
|
46907
|
-
const { stdout } = await
|
|
47123
|
+
const { stdout } = await exec13("/usr/bin/xcrun", ["simctl", "listapps", udid], { timeout: 15e3, maxBuffer: 4194304 }).catch(() => ({ stdout: "" }));
|
|
46908
47124
|
const apps = [];
|
|
46909
47125
|
const blocks = stdout.split(/\n(?=\s{4}"[^"]+" =\s+\{)/);
|
|
46910
47126
|
for (const block of blocks) {
|
|
@@ -46920,8 +47136,8 @@ init_transcripts();
|
|
|
46920
47136
|
|
|
46921
47137
|
// src/bridge/uploads.ts
|
|
46922
47138
|
init_protocol();
|
|
46923
|
-
import { mkdir as mkdir18, readdir as
|
|
46924
|
-
import
|
|
47139
|
+
import { mkdir as mkdir18, readdir as readdir14, lstat as lstat18, realpath as realpath15, readFile as readFile30, stat as stat22, unlink as unlink6, writeFile as writeFile10 } from "node:fs/promises";
|
|
47140
|
+
import path75 from "node:path";
|
|
46925
47141
|
import { randomUUID as randomUUID18 } from "node:crypto";
|
|
46926
47142
|
function imageBytes(bytes) {
|
|
46927
47143
|
return bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])) || bytes.subarray(0, 3).equals(Buffer.from([255, 216, 255])) || /^GIF8[79]a/.test(bytes.subarray(0, 6).toString()) || bytes.subarray(0, 4).toString() === "RIFF" && bytes.subarray(8, 12).toString() === "WEBP";
|
|
@@ -46934,24 +47150,24 @@ async function saveUpload(session, name, bytes) {
|
|
|
46934
47150
|
let saved = "";
|
|
46935
47151
|
const task = uploadQueue.catch(() => {
|
|
46936
47152
|
}).then(async () => {
|
|
46937
|
-
const root =
|
|
47153
|
+
const root = path75.join(bridgeRoot(), "uploads");
|
|
46938
47154
|
await mkdir18(root, { recursive: true, mode: 448 });
|
|
46939
47155
|
let used = 0;
|
|
46940
|
-
const directories = await
|
|
47156
|
+
const directories = await readdir14(root, { withFileTypes: true });
|
|
46941
47157
|
for (const dir of directories) {
|
|
46942
47158
|
if (!dir.isDirectory()) continue;
|
|
46943
|
-
const folder2 =
|
|
46944
|
-
for (const entry of await
|
|
47159
|
+
const folder2 = path75.join(root, dir.name);
|
|
47160
|
+
for (const entry of await readdir14(folder2, { withFileTypes: true })) {
|
|
46945
47161
|
if (!entry.isFile()) continue;
|
|
46946
|
-
const file2 =
|
|
47162
|
+
const file2 = path75.join(folder2, entry.name), metadata = await lstat18(file2);
|
|
46947
47163
|
if (Date.now() - metadata.mtimeMs > 14 * 864e5) await unlink6(file2);
|
|
46948
47164
|
else used += metadata.size;
|
|
46949
47165
|
}
|
|
46950
47166
|
}
|
|
46951
47167
|
if (used + bytes.length > 268435456) throw new BridgeError(413, "Phren's image storage is full. Remove older uploads on the computer.");
|
|
46952
|
-
const folder =
|
|
47168
|
+
const folder = path75.join(root, session);
|
|
46953
47169
|
await mkdir18(folder, { recursive: true, mode: 448 });
|
|
46954
|
-
saved =
|
|
47170
|
+
saved = path75.join(folder, `${randomUUID18()}-${name}`);
|
|
46955
47171
|
await writeFile10(saved, bytes, { flag: "wx", mode: 384 });
|
|
46956
47172
|
});
|
|
46957
47173
|
uploadQueue = task;
|
|
@@ -46959,23 +47175,23 @@ async function saveUpload(session, name, bytes) {
|
|
|
46959
47175
|
return saved;
|
|
46960
47176
|
}
|
|
46961
47177
|
async function listUploads(session) {
|
|
46962
|
-
const folder =
|
|
46963
|
-
const entries2 = await
|
|
47178
|
+
const folder = path75.join(bridgeRoot(), "uploads", session);
|
|
47179
|
+
const entries2 = await readdir14(folder, { withFileTypes: true }).catch(() => []);
|
|
46964
47180
|
const files = [];
|
|
46965
47181
|
for (const entry of entries2) {
|
|
46966
47182
|
if (!entry.isFile()) continue;
|
|
46967
|
-
const file2 =
|
|
47183
|
+
const file2 = path75.join(folder, entry.name), metadata = await stat22(file2);
|
|
46968
47184
|
files.push({ name: entry.name.replace(/^[0-9a-f-]{36}-/, ""), path: file2, size: metadata.size, modified: metadata.mtime.toISOString() });
|
|
46969
47185
|
}
|
|
46970
47186
|
return files.sort((a, b) => b.modified.localeCompare(a.modified)).slice(0, 200);
|
|
46971
47187
|
}
|
|
46972
47188
|
async function uploadImage(requested) {
|
|
46973
47189
|
const missing = new BridgeError(404, "This image is not one of the phone's uploads.");
|
|
46974
|
-
if (!requested || requested.length > 4096 || !
|
|
46975
|
-
const root = await
|
|
46976
|
-
const file2 = await
|
|
46977
|
-
if (!root || !file2 || !file2.startsWith(root +
|
|
46978
|
-
const metadata = await
|
|
47190
|
+
if (!requested || requested.length > 4096 || !path75.isAbsolute(requested)) throw missing;
|
|
47191
|
+
const root = await realpath15(path75.join(bridgeRoot(), "uploads")).catch(() => void 0);
|
|
47192
|
+
const file2 = await realpath15(requested).catch(() => void 0);
|
|
47193
|
+
if (!root || !file2 || !file2.startsWith(root + path75.sep)) throw missing;
|
|
47194
|
+
const metadata = await stat22(file2);
|
|
46979
47195
|
if (!metadata.isFile()) throw missing;
|
|
46980
47196
|
if (metadata.size > 8388608) throw new BridgeError(413, "This image is too large.");
|
|
46981
47197
|
const bytes = await readFile30(file2);
|
|
@@ -46988,7 +47204,7 @@ async function uploadImage(requested) {
|
|
|
46988
47204
|
init_transcript_index();
|
|
46989
47205
|
init_transcripts();
|
|
46990
47206
|
import { homedir as homedir18, tmpdir as tmpdir4 } from "node:os";
|
|
46991
|
-
import
|
|
47207
|
+
import path76 from "node:path";
|
|
46992
47208
|
init_protocol();
|
|
46993
47209
|
var cache = /* @__PURE__ */ new Map();
|
|
46994
47210
|
var modelCache = /* @__PURE__ */ new Map();
|
|
@@ -47126,7 +47342,7 @@ function describe3(tool, args) {
|
|
|
47126
47342
|
return "";
|
|
47127
47343
|
};
|
|
47128
47344
|
const firstLine = (v) => v.split(/\r?\n/).map((l) => l.trim()).find((l) => l) ?? "";
|
|
47129
|
-
const base = (v) =>
|
|
47345
|
+
const base = (v) => path76.basename(v.split(" \xB7 ")[0].trim()) || "file";
|
|
47130
47346
|
const name = tool.toLowerCase();
|
|
47131
47347
|
let value2;
|
|
47132
47348
|
if (["bash", "shell", "exec_command", "exec", "parallel", "tools", "write_stdin", "container.exec"].includes(name)) {
|
|
@@ -47161,17 +47377,17 @@ init_shared();
|
|
|
47161
47377
|
|
|
47162
47378
|
// src/bridge/server-pane-routes.ts
|
|
47163
47379
|
init_zod();
|
|
47164
|
-
import
|
|
47380
|
+
import path79 from "node:path";
|
|
47165
47381
|
import { setTimeout as sleep2 } from "node:timers/promises";
|
|
47166
47382
|
|
|
47167
47383
|
// src/bridge/git.ts
|
|
47168
47384
|
init_protocol();
|
|
47169
47385
|
import { createHash as createHash17 } from "node:crypto";
|
|
47170
|
-
import { execFile as
|
|
47171
|
-
import { lstat as lstat19, readdir as
|
|
47172
|
-
import
|
|
47173
|
-
import { promisify as
|
|
47174
|
-
var
|
|
47386
|
+
import { execFile as execFile15 } from "node:child_process";
|
|
47387
|
+
import { lstat as lstat19, readdir as readdir15, readFile as readFile31, realpath as realpath16, stat as stat23 } from "node:fs/promises";
|
|
47388
|
+
import path77 from "node:path";
|
|
47389
|
+
import { promisify as promisify14 } from "node:util";
|
|
47390
|
+
var exec14 = promisify14(execFile15);
|
|
47175
47391
|
function statusLetter(code) {
|
|
47176
47392
|
const letter = code[0];
|
|
47177
47393
|
return ["M", "A", "D", "R", "C", "U"].includes(letter) ? letter : "M";
|
|
@@ -47215,8 +47431,8 @@ function parseNumstat(out) {
|
|
|
47215
47431
|
}
|
|
47216
47432
|
async function countLines(root, rel) {
|
|
47217
47433
|
try {
|
|
47218
|
-
const abs =
|
|
47219
|
-
if ((await
|
|
47434
|
+
const abs = path77.join(root, await repositoryPath(root, rel));
|
|
47435
|
+
if ((await stat23(abs)).size > 5e6) return 0;
|
|
47220
47436
|
const bytes = await readFile31(abs);
|
|
47221
47437
|
if (!bytes.length || bytes.includes(0)) return 0;
|
|
47222
47438
|
let lines = 0;
|
|
@@ -47383,7 +47599,7 @@ function checkRollup(items) {
|
|
|
47383
47599
|
}
|
|
47384
47600
|
async function currentPull(root, branch) {
|
|
47385
47601
|
try {
|
|
47386
|
-
const { stdout } = await
|
|
47602
|
+
const { stdout } = await exec14("gh", ["pr", "view", "--json", "number,title,url,state,isDraft,headRefName,baseRefName,statusCheckRollup"], {
|
|
47387
47603
|
cwd: root,
|
|
47388
47604
|
timeout: 15e3,
|
|
47389
47605
|
maxBuffer: 4194304,
|
|
@@ -47410,7 +47626,7 @@ async function gitPulls(cwd) {
|
|
|
47410
47626
|
const branch = (await git2(root, "branch", "--show-current").catch(() => "")).trim();
|
|
47411
47627
|
try {
|
|
47412
47628
|
const [{ stdout }, current2] = await Promise.all([
|
|
47413
|
-
|
|
47629
|
+
exec14("gh", ["pr", "list", "--json", "number,title,headRefName,baseRefName,author,url,isDraft,state,updatedAt", "--limit", "50"], {
|
|
47414
47630
|
cwd: root,
|
|
47415
47631
|
timeout: 15e3,
|
|
47416
47632
|
maxBuffer: 4194304,
|
|
@@ -47439,13 +47655,13 @@ async function gitPulls(cwd) {
|
|
|
47439
47655
|
}
|
|
47440
47656
|
}
|
|
47441
47657
|
async function repositoryPath(root, raw, allowRoot = false) {
|
|
47442
|
-
if (typeof raw !== "string" || raw.length > 4096 || raw.includes("\0") ||
|
|
47658
|
+
if (typeof raw !== "string" || raw.length > 4096 || raw.includes("\0") || path77.isAbsolute(raw) || path77.win32.isAbsolute(raw) || raw.startsWith("\\")) throw new BridgeError(400, "Invalid path.");
|
|
47443
47659
|
const segments = raw.split(/[\\/]/);
|
|
47444
47660
|
if (segments.includes("..")) throw new BridgeError(400, "Invalid path.");
|
|
47445
47661
|
const clean2 = segments.filter((part) => part && part !== ".").join("/");
|
|
47446
47662
|
if (!clean2 && !allowRoot || clean2.startsWith("-")) throw new BridgeError(400, "Invalid path.");
|
|
47447
|
-
const abs =
|
|
47448
|
-
if (abs !== root && !abs.startsWith(root +
|
|
47663
|
+
const abs = path77.resolve(root, clean2);
|
|
47664
|
+
if (abs !== root && !abs.startsWith(root + path77.sep)) throw new BridgeError(403, "This path is outside the repository.");
|
|
47449
47665
|
let existing = abs;
|
|
47450
47666
|
while (true) {
|
|
47451
47667
|
try {
|
|
@@ -47453,16 +47669,16 @@ async function repositoryPath(root, raw, allowRoot = false) {
|
|
|
47453
47669
|
break;
|
|
47454
47670
|
} catch (error62) {
|
|
47455
47671
|
if (error62.code !== "ENOENT" || existing === root) throw new BridgeError(400, "Invalid path.");
|
|
47456
|
-
existing =
|
|
47672
|
+
existing = path77.dirname(existing);
|
|
47457
47673
|
}
|
|
47458
47674
|
}
|
|
47459
47675
|
let resolved;
|
|
47460
47676
|
try {
|
|
47461
|
-
resolved = await
|
|
47677
|
+
resolved = await realpath16(existing);
|
|
47462
47678
|
} catch {
|
|
47463
47679
|
throw new BridgeError(403, "This path cannot be resolved inside the repository.");
|
|
47464
47680
|
}
|
|
47465
|
-
if (resolved !== root && !resolved.startsWith(root +
|
|
47681
|
+
if (resolved !== root && !resolved.startsWith(root + path77.sep)) throw new BridgeError(403, "This path is outside the repository.");
|
|
47466
47682
|
return clean2;
|
|
47467
47683
|
}
|
|
47468
47684
|
var treeCache = /* @__PURE__ */ new Map();
|
|
@@ -47544,7 +47760,7 @@ async function ignoredEntries(root, prefix, shown) {
|
|
|
47544
47760
|
const entries2 = /* @__PURE__ */ new Map();
|
|
47545
47761
|
const inside = prefix && listing.some((item) => item.endsWith("/") && (prefix + "/").startsWith(item));
|
|
47546
47762
|
if (inside) {
|
|
47547
|
-
const dirents = await
|
|
47763
|
+
const dirents = await readdir15(path77.join(root, prefix), { withFileTypes: true }).catch(() => []);
|
|
47548
47764
|
for (const dirent of dirents) {
|
|
47549
47765
|
if (dirent.name === ".git" || taken.has(dirent.name) || entries2.size >= MAX_IGNORED_ENTRIES) continue;
|
|
47550
47766
|
entries2.set(dirent.name, { name: dirent.name, path: `${prefix}/${dirent.name}`, kind: dirent.isDirectory() ? "dir" : "file", ignored: true });
|
|
@@ -47641,9 +47857,9 @@ init_fanouts();
|
|
|
47641
47857
|
// src/bridge/git-worktrees.ts
|
|
47642
47858
|
init_protocol();
|
|
47643
47859
|
import { createHash as createHash18 } from "node:crypto";
|
|
47644
|
-
import { realpath as
|
|
47860
|
+
import { realpath as realpath17, stat as stat24 } from "node:fs/promises";
|
|
47645
47861
|
import { homedir as homedir19 } from "node:os";
|
|
47646
|
-
import
|
|
47862
|
+
import path78 from "node:path";
|
|
47647
47863
|
var MAX_WORKTREES = 64;
|
|
47648
47864
|
var worktreeIdPattern = /^[a-f0-9]{32}$/;
|
|
47649
47865
|
function worktreeId(abs) {
|
|
@@ -47671,8 +47887,8 @@ async function listed(root) {
|
|
|
47671
47887
|
let main;
|
|
47672
47888
|
for (const [index2, block] of blocks.entries()) {
|
|
47673
47889
|
if (block.bare !== void 0 || block.prunable !== void 0) continue;
|
|
47674
|
-
const abs = await
|
|
47675
|
-
if (!abs || !(await
|
|
47890
|
+
const abs = await realpath17(block.worktree).catch(() => void 0);
|
|
47891
|
+
if (!abs || !(await stat24(abs).catch(() => void 0))?.isDirectory()) continue;
|
|
47676
47892
|
if (index2 === 0) main = abs;
|
|
47677
47893
|
const branch = block.branch?.startsWith("refs/heads/") ? block.branch.slice("refs/heads/".length) : null;
|
|
47678
47894
|
worktrees.push({ abs, head: block.HEAD ?? "", branch, locked: block.locked !== void 0 });
|
|
@@ -47682,11 +47898,11 @@ async function listed(root) {
|
|
|
47682
47898
|
}
|
|
47683
47899
|
function displayPath(abs, roots) {
|
|
47684
47900
|
for (const root of roots) {
|
|
47685
|
-
const rel =
|
|
47686
|
-
if (rel && !rel.startsWith("..") && !
|
|
47901
|
+
const rel = path78.relative(root, abs);
|
|
47902
|
+
if (rel && !rel.startsWith("..") && !path78.isAbsolute(rel)) return rel.split(path78.sep).join("/");
|
|
47687
47903
|
}
|
|
47688
47904
|
const home = homedir19();
|
|
47689
|
-
return abs === home ? "~" : abs.startsWith(home +
|
|
47905
|
+
return abs === home ? "~" : abs.startsWith(home + path78.sep) ? "~/" + path78.relative(home, abs).split(path78.sep).join("/") : abs;
|
|
47690
47906
|
}
|
|
47691
47907
|
function uncommitted(status) {
|
|
47692
47908
|
const tokens = status.split("\0");
|
|
@@ -47700,12 +47916,12 @@ function uncommitted(status) {
|
|
|
47700
47916
|
return count2;
|
|
47701
47917
|
}
|
|
47702
47918
|
async function workerFor(abs, workers, all = []) {
|
|
47703
|
-
const nested = all.filter((other) => other.startsWith(abs +
|
|
47919
|
+
const nested = all.filter((other) => other.startsWith(abs + path78.sep));
|
|
47704
47920
|
let best;
|
|
47705
47921
|
for (const worker of workers) {
|
|
47706
|
-
const cwd = await
|
|
47707
|
-
if (cwd !== abs && !cwd.startsWith(abs +
|
|
47708
|
-
if (nested.some((inner) => cwd === inner || cwd.startsWith(inner +
|
|
47922
|
+
const cwd = await realpath17(worker.cwd).catch(() => path78.resolve(worker.cwd));
|
|
47923
|
+
if (cwd !== abs && !cwd.startsWith(abs + path78.sep)) continue;
|
|
47924
|
+
if (nested.some((inner) => cwd === inner || cwd.startsWith(inner + path78.sep))) continue;
|
|
47709
47925
|
const score = (cwd === abs ? 2 : 0) + (worker.child ? 1 : 0);
|
|
47710
47926
|
if (!best || score > best.score) best = { worker, score };
|
|
47711
47927
|
}
|
|
@@ -47898,11 +48114,11 @@ init_terminal();
|
|
|
47898
48114
|
init_protocol();
|
|
47899
48115
|
init_herdr();
|
|
47900
48116
|
init_terminal();
|
|
47901
|
-
import { execFile as
|
|
47902
|
-
import { open as
|
|
47903
|
-
import { promisify as
|
|
48117
|
+
import { execFile as execFile16 } from "node:child_process";
|
|
48118
|
+
import { open as open15, stat as stat25 } from "node:fs/promises";
|
|
48119
|
+
import { promisify as promisify15 } from "node:util";
|
|
47904
48120
|
init_transcripts();
|
|
47905
|
-
var
|
|
48121
|
+
var exec15 = promisify15(execFile16);
|
|
47906
48122
|
var MAX_DEPTH = 64;
|
|
47907
48123
|
var TRANSCRIPT_TAIL_BYTES = 1048576;
|
|
47908
48124
|
var MAX_OTHER_PANES = 48;
|
|
@@ -47933,8 +48149,8 @@ function attributeServers(input2) {
|
|
|
47933
48149
|
}
|
|
47934
48150
|
return result.sort((a, b) => Number(a.source === "mentioned") - Number(b.source === "mentioned") || a.port - b.port);
|
|
47935
48151
|
}
|
|
47936
|
-
async function
|
|
47937
|
-
const { stdout } = await
|
|
48152
|
+
async function processTable2(session) {
|
|
48153
|
+
const { stdout } = await exec15("ps", ["-axo", "pid=,ppid=,args="], { timeout: 4e3, maxBuffer: 16777216 });
|
|
47938
48154
|
const parents = /* @__PURE__ */ new Map();
|
|
47939
48155
|
const runners = [];
|
|
47940
48156
|
const flag = `--session-id ${session}`;
|
|
@@ -47955,12 +48171,12 @@ async function paneRoots(server, paneId) {
|
|
|
47955
48171
|
}
|
|
47956
48172
|
async function transcriptHolders(file2) {
|
|
47957
48173
|
const lsof = process.platform === "darwin" ? "/usr/sbin/lsof" : "lsof";
|
|
47958
|
-
const { stdout } = await
|
|
48174
|
+
const { stdout } = await exec15(lsof, ["-t", "--", file2], { timeout: 3e3 }).catch(() => ({ stdout: "" }));
|
|
47959
48175
|
return stdout.split("\n").map(Number).filter((pid) => Number.isSafeInteger(pid) && pid > 1 && pid !== process.pid);
|
|
47960
48176
|
}
|
|
47961
48177
|
async function transcriptTail(file2) {
|
|
47962
|
-
const size = (await
|
|
47963
|
-
const handle = await
|
|
48178
|
+
const size = (await stat25(file2)).size;
|
|
48179
|
+
const handle = await open15(file2, "r");
|
|
47964
48180
|
try {
|
|
47965
48181
|
const length = Math.min(size, TRANSCRIPT_TAIL_BYTES);
|
|
47966
48182
|
const buffer = Buffer.alloc(length);
|
|
@@ -47971,14 +48187,14 @@ async function transcriptTail(file2) {
|
|
|
47971
48187
|
}
|
|
47972
48188
|
}
|
|
47973
48189
|
async function sessionWebServers(target, pane) {
|
|
47974
|
-
const [servers2,
|
|
48190
|
+
const [servers2, table2, own2, file2] = await Promise.all([
|
|
47975
48191
|
webServers(),
|
|
47976
|
-
|
|
48192
|
+
processTable2(target.session),
|
|
47977
48193
|
paneRoots(target.server, pane.pane_id),
|
|
47978
48194
|
transcriptPath(target.source, target.session).catch(() => void 0)
|
|
47979
48195
|
]);
|
|
47980
|
-
const parents =
|
|
47981
|
-
const ownRoots = /* @__PURE__ */ new Set([...own2, ...
|
|
48196
|
+
const parents = table2.parents;
|
|
48197
|
+
const ownRoots = /* @__PURE__ */ new Set([...own2, ...table2.runners]);
|
|
47982
48198
|
let mentioned = /* @__PURE__ */ new Set();
|
|
47983
48199
|
if (file2) {
|
|
47984
48200
|
for (const pid of await transcriptHolders(file2)) ownRoots.add(pid);
|
|
@@ -48089,7 +48305,7 @@ function herdrWorktreeWorkers(s) {
|
|
|
48089
48305
|
const workers = [];
|
|
48090
48306
|
for (const pane of objects(s.panes)) {
|
|
48091
48307
|
const cwd = pane.foreground_cwd || pane.cwd;
|
|
48092
|
-
if (typeof pane.agent !== "string" || typeof cwd !== "string" || !
|
|
48308
|
+
if (typeof pane.agent !== "string" || typeof cwd !== "string" || !path79.isAbsolute(cwd)) continue;
|
|
48093
48309
|
const name = paneAgentName(s, pane);
|
|
48094
48310
|
workers.push({
|
|
48095
48311
|
cwd,
|
|
@@ -48408,7 +48624,7 @@ async function paneRouteOnce(ctx, url2, data, response, typing) {
|
|
|
48408
48624
|
|
|
48409
48625
|
// src/bridge/server-launch.ts
|
|
48410
48626
|
import { mkdir as mkdir20, readFile as readFile32 } from "node:fs/promises";
|
|
48411
|
-
import
|
|
48627
|
+
import path81 from "node:path";
|
|
48412
48628
|
init_zod();
|
|
48413
48629
|
init_home_paths();
|
|
48414
48630
|
init_herdr();
|
|
@@ -48418,15 +48634,15 @@ init_terminal();
|
|
|
48418
48634
|
init_zod();
|
|
48419
48635
|
init_utils_helpers();
|
|
48420
48636
|
init_metrics();
|
|
48421
|
-
import { execFile as
|
|
48422
|
-
import { mkdir as mkdir19, realpath as
|
|
48423
|
-
import
|
|
48424
|
-
import { promisify as
|
|
48637
|
+
import { execFile as execFile17 } from "node:child_process";
|
|
48638
|
+
import { mkdir as mkdir19, realpath as realpath18, rm as rm9, stat as stat26 } from "node:fs/promises";
|
|
48639
|
+
import path80 from "node:path";
|
|
48640
|
+
import { promisify as promisify16 } from "node:util";
|
|
48425
48641
|
init_protocol();
|
|
48426
|
-
var
|
|
48642
|
+
var exec16 = promisify16(execFile17);
|
|
48427
48643
|
async function git6(cwd, ...args) {
|
|
48428
48644
|
countGit("launch-worktree");
|
|
48429
|
-
return (await
|
|
48645
|
+
return (await exec16("git", ["-C", cwd, "--no-pager", ...args], {
|
|
48430
48646
|
timeout: 12e4,
|
|
48431
48647
|
maxBuffer: 1048576,
|
|
48432
48648
|
env: nonInteractiveGitEnv({ ...process.env, GIT_CONFIG_NOSYSTEM: "1" })
|
|
@@ -48449,21 +48665,21 @@ async function createLaunchWorktree(cwd, request6) {
|
|
|
48449
48665
|
if (await git6(root, "show-ref", "--verify", "--quiet", `refs/heads/${branch}`).then(() => true, () => false)) {
|
|
48450
48666
|
throw new BridgeError(409, `A branch named "${branch}" already exists in this repository. Choose another branch name.`);
|
|
48451
48667
|
}
|
|
48452
|
-
const worktree =
|
|
48453
|
-
if (await
|
|
48668
|
+
const worktree = path80.join(root, ".claude", "worktrees", worktreeFolderName(branch));
|
|
48669
|
+
if (await stat26(worktree).then(() => true, () => false)) {
|
|
48454
48670
|
throw new BridgeError(409, `The folder .claude/worktrees/${worktreeFolderName(branch)} already exists. Choose another branch name.`);
|
|
48455
48671
|
}
|
|
48456
|
-
await mkdir19(
|
|
48672
|
+
await mkdir19(path80.dirname(worktree), { recursive: true });
|
|
48457
48673
|
try {
|
|
48458
48674
|
await git6(root, "worktree", "add", "-b", branch, worktree, head);
|
|
48459
48675
|
} catch (error62) {
|
|
48460
48676
|
const detail = error62 instanceof Error && "stderr" in error62 ? String(error62.stderr ?? "").trim().split("\n").at(-1) : "";
|
|
48461
48677
|
throw new BridgeError(409, `Git could not create the worktree${detail ? `: ${detail.replace(/^fatal:\s*/, "")}` : "."}`);
|
|
48462
48678
|
}
|
|
48463
|
-
const abs = await
|
|
48464
|
-
const inside =
|
|
48465
|
-
const start = inside && !inside.startsWith("..") ?
|
|
48466
|
-
const startDir = await
|
|
48679
|
+
const abs = await realpath18(worktree);
|
|
48680
|
+
const inside = path80.relative(root, await realpath18(cwd));
|
|
48681
|
+
const start = inside && !inside.startsWith("..") ? path80.join(abs, inside) : abs;
|
|
48682
|
+
const startDir = await stat26(start).then((value2) => value2.isDirectory(), () => false) ? start : abs;
|
|
48467
48683
|
return {
|
|
48468
48684
|
cwd: startDir,
|
|
48469
48685
|
path: abs,
|
|
@@ -48505,10 +48721,10 @@ async function conductorBrief() {
|
|
|
48505
48721
|
let source;
|
|
48506
48722
|
if (true) source = "---\nname: conductor\ndescription: Coordinate independent Phren tasks across every project in the store and every enrolled computer, supervise their local agent fanout, and integrate verified returns in a concise dispatcher voice.\n---\n\n# Conductor\n\nYou are the owner's dispatcher for the whole store, not one project. You start\nin the phren store itself; that folder is not a project and not your work.\n\nFirst, before trusting your tools, check which phren you are running:\n`phren --version` and `command -v phren`. If the version is older than the one\nthe store or the owner expects, or the path is not the install you expect (a\nstale global package, an old checkout), tell the owner in one line and say\nwhich tools may be missing or behave differently.\n\nThen read the relevant projects' summaries and Phren tasks\n(`get_project_summary`, `get_tasks`) before selecting work.\n\nYour tools, use these instead of exploring the CLI or the Hook's files:\n\n- `live_sessions` (CLI `phren dispatch sessions`): every live agent on this\n computer and each enrolled one, with project, harness, status, `idleFor`\n (seconds since it last changed) and the target `hand_off` takes. Start here\n when asked what is running. Computers it could not reach are listed; say so\n rather than guessing. Computers in `notLinked` are registered in the store\n but have no Hook link here: say they were not checked, never that nothing is\n running there.\n- `hand_off`: send a prompt to one of those sessions.\n- `dispatch`: start a new worker on a computer (or `anywhere`).\n- `dispatch_returns` (CLI `phren dispatch returns`): what your workers sent\n back since you last asked: done with the final reply, needs-you with the\n question, failed with the error (a usage limit), blocked, or gone. Reading them marks them read. In core use\n `phren_admin(action: \"dispatch_returns\")`.\n- `phren dispatch status`: receipts of what you dispatched.\n- `get_tasks`, `get_project_summary`, `search_knowledge`: the store's memory.\n\nKeep engineering detail in worker briefs, Phren tasks and findings, and review\nartifacts, not in the owner's chat.\n\n## Voice and pace\n\nThe owner talks to you from the phone, often in talk mode, where your replies\nare read aloud in their voice. Sound like a good dispatcher: short, quick and\nconversational.\n\n- Lead with the outcome in one sentence. Keep the whole reply to one to four\n short sentences unless the owner asks for detail.\n- No tables, file paths, SHAs, PR numbers or run IDs in a reply unless the\n owner asks for them. Record them in Phren tasks and findings instead.\n- One short line per dispatch or return: who, what, result. A routine watcher\n or monitor event where nothing changed gets silence or a single line.\n- When the owner gives you a task, dispatch an engineer for it right away and\n say so in one line. That is the owner's standing rule; do not ask first.\n- Ask at most one question at a time, and name the options.\n- Delegate reading and analysis to workers instead of running long\n investigations yourself, so your own turns stay fast.\n- A message that begins with `[voice]` was spoken in talk mode, and your reply\n will be read aloud. Answer in one or two spoken sentences with no markdown,\n lists, symbols or code, written to sound natural read aloud: \"back in about\n twenty minutes\", not \"ETA ~20m\".\n\n```text\nLinuxbox has the parser checks on Codex, back around two twenty.\nDesk finished the navigation checks: tests passed, not merged yet.\n```\n\nIf a result or return time is unknown, say so. Surface a worker's question in\nthe same short voice, with the worker's own choices.\n\n## Dispatching\n\nPick five to ten independent tasks when that many are available and capacity\npermits. Do not manufacture tasks to fill the batch. Separate dependencies and\nfile ownership; give each remote lead a base revision, acceptance checks, local\nfanout limit, report time and integration instructions. Every brief repeats the\nowner's repository constraints, including any prohibition on commits, pushes,\nbranches or particular tests. Dispatch never expands the owner's authorization.\n\nYou are the one conductor for this computer and every computer linked with\nit; a second conductor in the group is refused at launch. Conductors on\ncomputers that are not linked share only the store, so claim a task before you\ndispatch it: `claim_task` (in core, `manage_task` with `action: \"claim\"`).\nSkip tasks marked `[claimed: <computer>]` by another computer. A claim that\ncomes back not claimed, with `heldBy`, means another conductor got there first:\nmove on. Completing a task clears its claim; release one you will not do. Start\nworkers with `dispatch` or `hand_off`, never as tabs in your own Herdr\nworkspace. When a computer shows up in `notLinked`, tell the owner that\n`phren bridge link <host>` can link it; never link a computer yourself.\n\nPrefer Codex. Use OpenCode Go when its account and harness are connected. Use\nOpenRouter only when the owner explicitly requests it; an unavailable account\ndoes not authorize another paid provider. Name an explicit model when instructed,\notherwise use and report the remote configured default. Each remote lead owns\nits local checkouts, fanout and provider rate limits. Where installed, local\nworkers use the fanout wrapper's `scripts/run.sh --provider codex|opencode\n--label --worktree [--model] [--mode]` contract and parent-bound manifests.\n\nPrefer handing work to a session that already owns the project and is idle or\ndoing related work; call `hand_off` in full or `phren_admin(action: \"hand_off\",\ncomputer?, target|session, text)` in core. Otherwise dispatch a new worker.\nWrite one short line either way. Call `dispatch` in full or\n`phren_admin(action: \"dispatch\", computer, project, harness, model?, prompt, label)`\nin core. The CLI equivalent is `phren dispatch <computer|anywhere> <project>\n--harness <harness> --label <label> --prompt <brief> [--model <model>]`.\n`anywhere` chooses the connected computer with the fewest working agents. Place\nbriefs sequentially, respecting busy/rate-limit responses. Keep their dispatch\nIDs. Do not send local filesystem paths as remote project names.\n\n`accepted` on a receipt is prompt acceptance, not worker completion. Returns\narrive on their own: the Hook follows every worker you dispatch, and when you\nare idle it types one line into this session, such as `Return: Linuxbox parser\nchecks done, tests passed (dispatch <id>). Call dispatch_returns.` When you see\none, call `dispatch_returns` and report each return in one short line. You may\nalso call it whenever you want the current state; do not poll it in a loop, and\ndo not read remote transcripts by hand to learn whether a worker finished. Tell\nthe owner a return time as an expectation, not a promise.\n\nFor a `needs-you` return, surface the worker's question in the owner's chat\nwith its choices as the worker wrote them; do not rewrite or answer it for the\nowner unless the owner already decided. Send the answer back with `hand_off`\nto the row's `target`. A `blocked` worker waits on terminal input, such as a\npermission prompt: say so and point the owner to the phone or the terminal. A\n`gone` worker's pane closed or was taken over: say so, and decide with the\nowner before giving its work to another agent. A `done` reply is the worker's\nown account; check its evidence before saying tests passed or work merged.\n\nAn uncertain delivery is never retried automatically. Inspect its known target\nor status before deciding with the owner whether a replacement is needed. Keep\nunavailable workers visible instead of giving their work to another agent\nwhile the original may still be running.\n\nIntegrate returned changes in dependency order within the owner's allowed\nworkflow. Run a cleanup pass across the combined result and the affected checks.\nRequire evidence before saying tests passed or merged. Ship only within existing\nauthorization; if publication is not authorized, return the reviewable result.\nUpdate Phren tasks when verified complete and save durable decisions. A worker's\nfinished turn alone does not complete the owner's task.\n";
|
|
48507
48723
|
else {
|
|
48508
|
-
const here =
|
|
48724
|
+
const here = path81.dirname(fileURLToPath(import.meta.url));
|
|
48509
48725
|
for (const candidate of [
|
|
48510
|
-
|
|
48511
|
-
|
|
48726
|
+
path81.join(here, "..", "starter", "global", "skills", "conductor", "SKILL.md"),
|
|
48727
|
+
path81.join(here, "..", "..", "starter", "global", "skills", "conductor", "SKILL.md")
|
|
48512
48728
|
]) {
|
|
48513
48729
|
source = await readFile32(candidate, "utf8").catch(() => void 0);
|
|
48514
48730
|
if (source !== void 0) break;
|
|
@@ -48529,15 +48745,15 @@ function effortArgs(kind, effort) {
|
|
|
48529
48745
|
}
|
|
48530
48746
|
async function prepareConductor(kind, effort, model) {
|
|
48531
48747
|
const brief = await conductorBrief();
|
|
48532
|
-
const briefDirectory =
|
|
48748
|
+
const briefDirectory = path81.join(bridgeRoot(), "conductor");
|
|
48533
48749
|
await mkdir20(briefDirectory, { recursive: true, mode: 448 });
|
|
48534
|
-
const briefFile =
|
|
48750
|
+
const briefFile = path81.join(briefDirectory, "brief.md");
|
|
48535
48751
|
if (await readFile32(briefFile, "utf8").catch(() => void 0) !== brief + "\n") await atomic(briefFile, brief + "\n");
|
|
48536
48752
|
if (kind === "claude") return [...model ? ["--model", model] : [], "--append-system-prompt-file", briefFile, "--effort", effort];
|
|
48537
48753
|
if (kind === "codex") return [...model ? ["--model", model] : [], "-c", `model_reasoning_effort=${effort}`, "-c", `developer_instructions=${JSON.stringify(brief)}`];
|
|
48538
48754
|
if (kind === "opencode") {
|
|
48539
|
-
const directory =
|
|
48540
|
-
const file2 =
|
|
48755
|
+
const directory = path81.join(process.env.XDG_CONFIG_HOME || path81.join(homeDir(), ".config"), "opencode", "agents");
|
|
48756
|
+
const file2 = path81.join(directory, "conductor.md");
|
|
48541
48757
|
const definition = `---
|
|
48542
48758
|
description: Coordinate the owner's work across agent sessions.
|
|
48543
48759
|
mode: primary
|
|
@@ -48574,7 +48790,7 @@ function herdrAgentName(label2) {
|
|
|
48574
48790
|
}
|
|
48575
48791
|
async function launchSession(server, data, options = {}) {
|
|
48576
48792
|
const role = external_exports.enum(["agent", "conductor"]).default("agent").parse(data.role);
|
|
48577
|
-
const projectDirectory = external_exports.string().min(1).max(4096).refine((t) =>
|
|
48793
|
+
const projectDirectory = external_exports.string().min(1).max(4096).refine((t) => path81.isAbsolute(t) && !/[\x00-\x1f\x7f]/.test(t)).parse(data.cwd);
|
|
48578
48794
|
const worktreeRequest = data.worktree === void 0 || data.worktree === null ? void 0 : launchWorktreeSchema.parse(data.worktree);
|
|
48579
48795
|
if (worktreeRequest && role === "conductor") throw new BridgeError(400, "A conductor works across projects, so it cannot start in a worktree.");
|
|
48580
48796
|
const label2 = plainText(200).parse(data.label);
|
|
@@ -48666,7 +48882,7 @@ async function workspaceAction(server, operation, data) {
|
|
|
48666
48882
|
if (tab && !objects(s.tabs).some((t) => t.tab_id === tab && (!workspace || t.workspace_id === workspace))) throw new BridgeError(409, "The tab changed.");
|
|
48667
48883
|
if (pane && !objects(s.panes).some((p) => p.pane_id === pane && (!tab || p.tab_id === tab) && (!workspace || p.workspace_id === workspace))) throw new BridgeError(409, "The pane changed.");
|
|
48668
48884
|
const label2 = data.label === void 0 ? void 0 : external_exports.string().min(1).max(200).refine((t) => !/[\x00-\x1f\x7f]/.test(t)).parse(data.label);
|
|
48669
|
-
const cwd = data.cwd === void 0 ? void 0 : external_exports.string().max(4096).refine((t) =>
|
|
48885
|
+
const cwd = data.cwd === void 0 ? void 0 : external_exports.string().max(4096).refine((t) => path81.isAbsolute(t) && !/[\x00-\x1f\x7f]/.test(t)).parse(data.cwd);
|
|
48670
48886
|
if (operation === "create") await terminalProvider().create(server, { workspace, label: label2, cwd });
|
|
48671
48887
|
else if (!workspace && !tab && !pane) throw new BridgeError(400, "Choose a Herdr destination.");
|
|
48672
48888
|
else if (pane && operation === "focus") await terminalProvider().focusPane(server, pane);
|
|
@@ -49038,7 +49254,7 @@ function createRouteHandler(ctx) {
|
|
|
49038
49254
|
case "/v1/files/range": {
|
|
49039
49255
|
let root;
|
|
49040
49256
|
if (url2.searchParams.get("scope") === "uploads") {
|
|
49041
|
-
root =
|
|
49257
|
+
root = path82.join(bridgeRoot(), "uploads");
|
|
49042
49258
|
} else if (url2.searchParams.has("session")) {
|
|
49043
49259
|
const target = targetFromURL(url2), pane = await validateTarget(target);
|
|
49044
49260
|
const cwd = await gitRepository(pane, target, url2.searchParams.get("child") ?? void 0, url2.searchParams.get("worktree") ?? void 0);
|
|
@@ -49345,7 +49561,7 @@ init_protocol();
|
|
|
49345
49561
|
// src/bridge/transcript-preview.ts
|
|
49346
49562
|
init_codex_threads();
|
|
49347
49563
|
import { constants as constants5 } from "node:fs";
|
|
49348
|
-
import { open as
|
|
49564
|
+
import { open as open16 } from "node:fs/promises";
|
|
49349
49565
|
init_protocol();
|
|
49350
49566
|
init_transcript_index();
|
|
49351
49567
|
init_terminal_text();
|
|
@@ -49575,11 +49791,11 @@ async function readDeltaPreview(target, file2, rollout) {
|
|
|
49575
49791
|
if (target.source === "codex") return await codexThreadPreview(target.session) ?? (file2 && rollout ? await rollout.read(file2).catch(() => null) : null);
|
|
49576
49792
|
if (target.source !== "opencode" || !file2) return null;
|
|
49577
49793
|
try {
|
|
49578
|
-
const handle = await
|
|
49794
|
+
const handle = await open16(file2 + ".preview.json", constants5.O_RDONLY | constants5.O_NOFOLLOW | constants5.O_NONBLOCK);
|
|
49579
49795
|
let bytes;
|
|
49580
49796
|
try {
|
|
49581
|
-
const
|
|
49582
|
-
if (!
|
|
49797
|
+
const stat27 = await handle.stat();
|
|
49798
|
+
if (!stat27.isFile() || stat27.size > MAX_PREVIEW_BYTES) return null;
|
|
49583
49799
|
const buffer = Buffer.alloc(MAX_PREVIEW_BYTES + 1);
|
|
49584
49800
|
const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
|
|
49585
49801
|
if (bytesRead > MAX_PREVIEW_BYTES) return null;
|
|
@@ -50010,7 +50226,7 @@ async function serve(version3) {
|
|
|
50010
50226
|
await mkdir21(root, { recursive: true, mode: 448 });
|
|
50011
50227
|
await chmod5(root, 448);
|
|
50012
50228
|
let computerID2;
|
|
50013
|
-
const identityFile =
|
|
50229
|
+
const identityFile = path83.join(root, "computer-id");
|
|
50014
50230
|
try {
|
|
50015
50231
|
computerID2 = (await readFile33(identityFile, "utf8")).trim();
|
|
50016
50232
|
} catch {
|
|
@@ -50060,7 +50276,7 @@ async function serve(version3) {
|
|
|
50060
50276
|
if (codeReindexer) agentHooks.changes.onRecord = (files) => codeReindexer.record(files);
|
|
50061
50277
|
function gatewayTiming() {
|
|
50062
50278
|
try {
|
|
50063
|
-
const parsed = JSON.parse(readFileSync32(
|
|
50279
|
+
const parsed = JSON.parse(readFileSync32(path83.join(root, "gateway.json"), "utf8"));
|
|
50064
50280
|
if (typeof parsed.ms === "number" && Number.isFinite(parsed.ms) && parsed.ms >= 0) return Math.round(parsed.ms);
|
|
50065
50281
|
} catch {
|
|
50066
50282
|
}
|
|
@@ -50106,7 +50322,7 @@ async function serve(version3) {
|
|
|
50106
50322
|
}
|
|
50107
50323
|
const stopRetention = modules.has("git") ? await startChangeRetention() : () => {
|
|
50108
50324
|
};
|
|
50109
|
-
if (modules.has("git")) await rm10(
|
|
50325
|
+
if (modules.has("git")) await rm10(path83.join(root, "changes-scratch"), { recursive: true, force: true });
|
|
50110
50326
|
const streams = transcriptStreams({ modules, agentHooks, codexQuestions, sideQuestions, info, activeCapabilities });
|
|
50111
50327
|
const { stream } = streams;
|
|
50112
50328
|
const overview = overviewStream({
|
|
@@ -50253,13 +50469,13 @@ init_protocol();
|
|
|
50253
50469
|
// src/bridge/link.ts
|
|
50254
50470
|
init_profile_store();
|
|
50255
50471
|
init_phren_paths();
|
|
50256
|
-
import { execFile as
|
|
50472
|
+
import { execFile as execFile18 } from "node:child_process";
|
|
50257
50473
|
import { readFile as readFile34 } from "node:fs/promises";
|
|
50258
50474
|
import { homedir as homedir20, hostname as hostname10, userInfo as userInfo3 } from "node:os";
|
|
50259
|
-
import
|
|
50260
|
-
import { promisify as
|
|
50475
|
+
import path84 from "node:path";
|
|
50476
|
+
import { promisify as promisify17 } from "node:util";
|
|
50261
50477
|
init_protocol();
|
|
50262
|
-
var
|
|
50478
|
+
var exec17 = promisify17(execFile18);
|
|
50263
50479
|
var REMOTE_PATH = 'PATH="$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin:$PATH"';
|
|
50264
50480
|
var GIT_HOSTS = /(^|\.)(github\.com|gitlab\.com|bitbucket\.org)$/i;
|
|
50265
50481
|
function sshConfigHosts(text4) {
|
|
@@ -50284,7 +50500,7 @@ function sshConfigHosts(text4) {
|
|
|
50284
50500
|
}
|
|
50285
50501
|
async function ssh(host, command, input2, timeout = 2e4) {
|
|
50286
50502
|
return new Promise((resolve11, reject) => {
|
|
50287
|
-
const child =
|
|
50503
|
+
const child = execFile18(
|
|
50288
50504
|
"ssh",
|
|
50289
50505
|
["-o", "BatchMode=yes", "-o", "ConnectTimeout=5", "--", host, command],
|
|
50290
50506
|
{ timeout, maxBuffer: 1048576 },
|
|
@@ -50303,11 +50519,11 @@ async function probe2(host) {
|
|
|
50303
50519
|
return computerId ? { host, computerId, user: field("user") ?? "", client: field("client") } : void 0;
|
|
50304
50520
|
}
|
|
50305
50521
|
async function discoverComputers(options = {}) {
|
|
50306
|
-
const config3 = options.sshConfig ?? await readFile34(
|
|
50522
|
+
const config3 = options.sshConfig ?? await readFile34(path84.join(homedir20(), ".ssh", "config"), "utf8").catch(() => "");
|
|
50307
50523
|
const store = options.store !== void 0 ? options.store : findPhrenPath();
|
|
50308
50524
|
const machines = store ? listMachines(store) : void 0;
|
|
50309
50525
|
const { peers } = await optionalHookPeers();
|
|
50310
|
-
const own2 = (await readFile34(
|
|
50526
|
+
const own2 = (await readFile34(path84.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
|
|
50311
50527
|
const known = new Set([...localNames(), ...peers.flatMap((peer) => [peer.name, peer.address])].map(computerLabel));
|
|
50312
50528
|
const candidates = [.../* @__PURE__ */ new Set([...sshConfigHosts(config3), ...machines?.ok ? Object.keys(machines.data) : []])].filter((host) => !known.has(computerLabel(host))).slice(0, 32);
|
|
50313
50529
|
const [found, peerIds] = await Promise.all([
|
|
@@ -50329,13 +50545,13 @@ function slugName(value2) {
|
|
|
50329
50545
|
async function linkComputer(host, options = {}) {
|
|
50330
50546
|
const remote = await probe2(host);
|
|
50331
50547
|
if (!remote) throw new BridgeError(409, `${host} answers over ssh but Phren Hook is not installed there. Run phren bridge install on it first.`);
|
|
50332
|
-
const own2 = (await readFile34(
|
|
50548
|
+
const own2 = (await readFile34(path84.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
|
|
50333
50549
|
if (remote.computerId === own2) throw new BridgeError(409, `${host} is this computer.`);
|
|
50334
50550
|
const name = computerName.parse(options.name ?? slugName(host));
|
|
50335
50551
|
const as = computerName.parse(options.as ?? slugName(hostname10()));
|
|
50336
50552
|
const backAddress = options.backAddress ?? remote.client;
|
|
50337
50553
|
if (!backAddress) throw new BridgeError(409, `${host} did not report this computer's address; pass --back-address.`);
|
|
50338
|
-
const resolved = Object.fromEntries((await
|
|
50554
|
+
const resolved = Object.fromEntries((await exec17("ssh", ["-G", "--", host], { timeout: 5e3 })).stdout.split("\n").map((line) => line.split(" ")).filter((parts) => parts.length >= 2).map(([key2, ...rest]) => [key2, rest.join(" ")]));
|
|
50339
50555
|
const remoteHostKey = publicComputerKey((await ssh(host, "cat /etc/ssh/ssh_host_ed25519_key.pub")).trim().split(/\s+/).slice(0, 2).join(" "));
|
|
50340
50556
|
const localHostKey = publicComputerKey((await readFile34("/etc/ssh/ssh_host_ed25519_key.pub", "utf8")).trim().split(/\s+/).slice(0, 2).join(" "));
|
|
50341
50557
|
const remoteLine = (await ssh(host, `${REMOTE_PATH} phren bridge enroll-computer ${name}`)).trim();
|
|
@@ -50530,7 +50746,7 @@ async function readSecret(prompt) {
|
|
|
50530
50746
|
// src/bridge/hook-main.ts
|
|
50531
50747
|
init_utils_helpers();
|
|
50532
50748
|
Object.assign(process.env, nonInteractiveGitEnv());
|
|
50533
|
-
runBridge(process.argv.slice(2), "0.3.
|
|
50749
|
+
runBridge(process.argv.slice(2), "0.3.8").then((code) => {
|
|
50534
50750
|
process.exitCode = code;
|
|
50535
50751
|
}).catch((error62) => {
|
|
50536
50752
|
console.error(error62 instanceof Error ? error62.message : "Phren Hook failed.");
|