@phren/cli 0.3.21 → 0.3.23
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 +48 -8
- package/dist/bridge/conductor-context.d.ts +7 -0
- package/dist/bridge/conductor-context.js +48 -0
- package/dist/bridge/hook-fast.d.ts +2 -0
- package/dist/bridge/hook-fast.js +20 -1
- package/dist/bridge/memory-store.js +4 -1
- package/dist/bridge/server-launch.js +3 -30
- package/dist/bridge/server-routes.js +67 -45
- package/dist/bridge-hook.mjs +495 -402
- package/dist/data/tasks.js +6 -1
- package/dist/init/init-uninstall.js +1 -0
- package/dist/init/setup.js +11 -0
- package/dist/init/teardown.js +1 -0
- package/dist/link/link.js +2 -0
- package/dist/link/refresh.js +1 -1
- package/dist/modules/registry.js +1 -1
- package/dist/skill/files.js +7 -1
- package/package.json +1 -1
- package/plugins/opencode/phren-transcript.js +28 -0
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, path116) {
|
|
272
|
+
if (!path116)
|
|
273
273
|
return obj;
|
|
274
|
-
return
|
|
274
|
+
return path116.reduce((acc, key3) => acc?.[key3], 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(path116, 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(path116);
|
|
538
538
|
return iss;
|
|
539
539
|
});
|
|
540
540
|
}
|
|
@@ -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, path116 = []) => {
|
|
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 }, [...path116, ...issue2.path]));
|
|
1062
1062
|
} else if (issue2.code === "invalid_key") {
|
|
1063
|
-
processError({ issues: issue2.issues }, [...
|
|
1063
|
+
processError({ issues: issue2.issues }, [...path116, ...issue2.path]);
|
|
1064
1064
|
} else if (issue2.code === "invalid_element") {
|
|
1065
|
-
processError({ issues: issue2.issues }, [...
|
|
1065
|
+
processError({ issues: issue2.issues }, [...path116, ...issue2.path]);
|
|
1066
1066
|
} else {
|
|
1067
|
-
const fullpath = [...
|
|
1067
|
+
const fullpath = [...path116, ...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, path116 = []) => {
|
|
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 }, [...path116, ...issue2.path]));
|
|
1111
1111
|
} else if (issue2.code === "invalid_key") {
|
|
1112
|
-
processError({ issues: issue2.issues }, [...
|
|
1112
|
+
processError({ issues: issue2.issues }, [...path116, ...issue2.path]);
|
|
1113
1113
|
} else if (issue2.code === "invalid_element") {
|
|
1114
|
-
processError({ issues: issue2.issues }, [...
|
|
1114
|
+
processError({ issues: issue2.issues }, [...path116, ...issue2.path]);
|
|
1115
1115
|
} else {
|
|
1116
|
-
const fullpath = [...
|
|
1116
|
+
const fullpath = [...path116, ...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 path116 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
|
|
1156
|
+
for (const seg of path116) {
|
|
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 path116 = ref.slice(1).split("/").filter(Boolean);
|
|
19153
|
+
if (path116.length === 0) {
|
|
19154
19154
|
return ctx.rootSchema;
|
|
19155
19155
|
}
|
|
19156
19156
|
const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
|
|
19157
|
-
if (
|
|
19158
|
-
const key3 =
|
|
19157
|
+
if (path116[0] === defsKey) {
|
|
19158
|
+
const key3 = path116[1] === void 0 ? void 0 : decodeJSONPointerSegment(path116[1]);
|
|
19159
19159
|
if (!key3 || !ctx.defs[key3]) {
|
|
19160
19160
|
throw new Error(`Reference not found: ${ref}`);
|
|
19161
19161
|
}
|
|
@@ -25352,7 +25352,7 @@ var init_package_metadata = __esm({
|
|
|
25352
25352
|
__dirname = path15.dirname(fileURLToPath2(import.meta.url));
|
|
25353
25353
|
ROOT = path15.join(__dirname, "..");
|
|
25354
25354
|
PACKAGE_JSON_PATH = path15.join(ROOT, "package.json");
|
|
25355
|
-
BUNDLED_VERSION = true ? "0.3.
|
|
25355
|
+
BUNDLED_VERSION = true ? "0.3.23" : "0.0.0";
|
|
25356
25356
|
PACKAGE_JSON = readPackageJson();
|
|
25357
25357
|
PACKAGE_NAME = PACKAGE_JSON.name || "phren";
|
|
25358
25358
|
VERSION = PACKAGE_JSON.version || BUNDLED_VERSION;
|
|
@@ -36938,7 +36938,7 @@ var init_types = __esm({
|
|
|
36938
36938
|
});
|
|
36939
36939
|
|
|
36940
36940
|
// src/fanout/adapters/codex.ts
|
|
36941
|
-
import * as
|
|
36941
|
+
import * as path82 from "node:path";
|
|
36942
36942
|
var codex;
|
|
36943
36943
|
var init_codex = __esm({
|
|
36944
36944
|
"src/fanout/adapters/codex.ts"() {
|
|
@@ -36952,7 +36952,7 @@ var init_codex = __esm({
|
|
|
36952
36952
|
"--json",
|
|
36953
36953
|
...!o.resume ? ["--sandbox", o.review ? "read-only" : "workspace-write", "-C", o.worktree] : [],
|
|
36954
36954
|
"-o",
|
|
36955
|
-
|
|
36955
|
+
path82.join(o.job, "final.txt"),
|
|
36956
36956
|
...o.model ? ["-m", o.model] : [],
|
|
36957
36957
|
...o.extra ?? [],
|
|
36958
36958
|
...o.resume ? [o.resume] : [],
|
|
@@ -36965,7 +36965,7 @@ var init_codex = __esm({
|
|
|
36965
36965
|
|
|
36966
36966
|
// src/fanout/opencode-serve.ts
|
|
36967
36967
|
import * as fs24 from "node:fs";
|
|
36968
|
-
import * as
|
|
36968
|
+
import * as path83 from "node:path";
|
|
36969
36969
|
function approvalWindow() {
|
|
36970
36970
|
const value2 = Number(process.env.PHREN_FANOUT_APPROVAL_MS);
|
|
36971
36971
|
return Number.isFinite(value2) && value2 >= 100 && value2 <= 24 * 36e5 ? Math.floor(value2) : 36e5;
|
|
@@ -37092,8 +37092,8 @@ ${message}` : message;
|
|
|
37092
37092
|
return error62 ? 1 : 0;
|
|
37093
37093
|
}
|
|
37094
37094
|
async function relay(o, session, asked, signal) {
|
|
37095
|
-
const directory =
|
|
37096
|
-
const request9 =
|
|
37095
|
+
const directory = path83.join(o.store, ".runtime", "approvals");
|
|
37096
|
+
const request9 = path83.join(directory, `opencode-${session}.request.json`), answer = path83.join(directory, `opencode-${session}.answer.json`);
|
|
37097
37097
|
fs24.mkdirSync(directory, { recursive: true, mode: 448 });
|
|
37098
37098
|
fs24.rmSync(answer, { force: true });
|
|
37099
37099
|
const created = Date.now(), deadline = created + approvalWindow(), pattern = asked.patterns.join(", ");
|
|
@@ -37232,15 +37232,15 @@ __export(launcher_exports, {
|
|
|
37232
37232
|
import { spawn as spawn11, execFileSync as execFileSync4 } from "node:child_process";
|
|
37233
37233
|
import { randomBytes as randomBytes5 } from "node:crypto";
|
|
37234
37234
|
import * as fs25 from "node:fs";
|
|
37235
|
-
import * as
|
|
37235
|
+
import * as path84 from "node:path";
|
|
37236
37236
|
function jobsRoot(store) {
|
|
37237
|
-
return
|
|
37237
|
+
return path84.join(store, ".runtime", "agent-fanouts");
|
|
37238
37238
|
}
|
|
37239
37239
|
function readJob(store, id2) {
|
|
37240
37240
|
if (!/^[a-z0-9][a-z0-9._-]{0,127}$/i.test(id2)) throw new Error("Invalid job id.");
|
|
37241
|
-
const root = fs25.realpathSync(jobsRoot(store)), job =
|
|
37241
|
+
const root = fs25.realpathSync(jobsRoot(store)), job = path84.join(root, id2);
|
|
37242
37242
|
if (!fs25.lstatSync(job).isDirectory() || fs25.realpathSync(job) !== job) throw new Error("Invalid job directory.");
|
|
37243
|
-
const file3 =
|
|
37243
|
+
const file3 = path84.join(job, "manifest.json"), info = fs25.lstatSync(file3);
|
|
37244
37244
|
if (!info.isFile() || info.isSymbolicLink() || info.size > 65536) throw new Error("Invalid job manifest.");
|
|
37245
37245
|
const result = manifestSchema.parse(JSON.parse(fs25.readFileSync(file3, "utf8")));
|
|
37246
37246
|
if (result.id !== id2) throw new Error("Job id does not match its manifest.");
|
|
@@ -37258,7 +37258,7 @@ function listJobs(store) {
|
|
|
37258
37258
|
}
|
|
37259
37259
|
function swiftBuildCount() {
|
|
37260
37260
|
const output2 = execFileSync4("ps", ["-axo", "comm="], { encoding: "utf8", timeout: 5e3 });
|
|
37261
|
-
return output2.split("\n").filter((line) =>
|
|
37261
|
+
return output2.split("\n").filter((line) => path84.basename(line.trim()) === "xcodebuild").length;
|
|
37262
37262
|
}
|
|
37263
37263
|
function nearestAgent(pid = process.ppid) {
|
|
37264
37264
|
if (process.platform === "win32") return void 0;
|
|
@@ -37271,7 +37271,7 @@ function nearestAgent(pid = process.ppid) {
|
|
|
37271
37271
|
}
|
|
37272
37272
|
const match = /^(\d+)\s+(.+)$/.exec(row);
|
|
37273
37273
|
if (!match) return void 0;
|
|
37274
|
-
const name =
|
|
37274
|
+
const name = path84.basename(match[2].trim());
|
|
37275
37275
|
if (name === "claude") return "claude";
|
|
37276
37276
|
if (name === "codex" || name.startsWith("codex-")) return "codex";
|
|
37277
37277
|
pid = Number(match[1]);
|
|
@@ -37279,15 +37279,15 @@ function nearestAgent(pid = process.ppid) {
|
|
|
37279
37279
|
return void 0;
|
|
37280
37280
|
}
|
|
37281
37281
|
function writeManifest2(job, manifest) {
|
|
37282
|
-
atomicWriteText(
|
|
37283
|
-
fs25.chmodSync(
|
|
37282
|
+
atomicWriteText(path84.join(job, "manifest.json"), JSON.stringify(manifestSchema.parse(manifest)) + "\n");
|
|
37283
|
+
fs25.chmodSync(path84.join(job, "manifest.json"), 384);
|
|
37284
37284
|
}
|
|
37285
37285
|
function createJob(options, env = process.env, nearest = nearestAgent) {
|
|
37286
37286
|
if (!options.label.trim() || options.label.length > 200) throw new Error("Choose a label of 1 to 200 characters.");
|
|
37287
37287
|
const worktree = fs25.realpathSync(options.worktree);
|
|
37288
37288
|
if (!fs25.statSync(worktree).isDirectory()) throw new Error("Choose a worktree directory.");
|
|
37289
37289
|
const id2 = `${options.provider}-${randomBytes5(12).toString("hex")}`;
|
|
37290
|
-
const root = jobsRoot(options.store), job =
|
|
37290
|
+
const root = jobsRoot(options.store), job = path84.join(root, id2);
|
|
37291
37291
|
fs25.mkdirSync(job, { recursive: true, mode: 448 });
|
|
37292
37292
|
fs25.chmodSync(root, 448);
|
|
37293
37293
|
const claudeParent = uuid3(env.CLAUDE_CODE_SESSION_ID);
|
|
@@ -37311,14 +37311,14 @@ function createJob(options, env = process.env, nearest = nearestAgent) {
|
|
|
37311
37311
|
...options.resume ? { resumes: options.resume } : {},
|
|
37312
37312
|
...codexParent ? { parent: { provider: "codex", session: codexParent } } : claudeParent ? { parent: { provider: "claude", session: claudeParent } } : {}
|
|
37313
37313
|
};
|
|
37314
|
-
for (const [file3, content] of Object.entries({ "prompt.txt": options.prompt, "events.jsonl": "", "stderr.log": "" })) fs25.writeFileSync(
|
|
37314
|
+
for (const [file3, content] of Object.entries({ "prompt.txt": options.prompt, "events.jsonl": "", "stderr.log": "" })) fs25.writeFileSync(path84.join(job, file3), content, { mode: 384 });
|
|
37315
37315
|
writeManifest2(job, manifest);
|
|
37316
37316
|
return { job, manifest };
|
|
37317
37317
|
}
|
|
37318
37318
|
async function launch(options, reservation = createJob(options)) {
|
|
37319
37319
|
const { job, manifest } = reservation, adapter = adapters[options.provider];
|
|
37320
37320
|
console.log(job);
|
|
37321
|
-
const out = fs25.openSync(
|
|
37321
|
+
const out = fs25.openSync(path84.join(job, manifest.eventLog), "a"), err = fs25.openSync(path84.join(job, "stderr.log"), "a");
|
|
37322
37322
|
const password = randomBytes5(24).toString("hex");
|
|
37323
37323
|
const child = spawn11("nice", ["-n", "15", adapter.command, ...adapter.argv({ ...options, job })], {
|
|
37324
37324
|
cwd: manifest.worktree,
|
|
@@ -37388,8 +37388,8 @@ async function launch(options, reservation = createJob(options)) {
|
|
|
37388
37388
|
const timer = setInterval(() => {
|
|
37389
37389
|
const reason2 = watchdog.reason();
|
|
37390
37390
|
if (!reason2) return;
|
|
37391
|
-
fs25.writeFileSync(
|
|
37392
|
-
atomicWriteText(
|
|
37391
|
+
fs25.writeFileSync(path84.join(job, "looped.txt"), reason2 + "\n", { mode: 384 });
|
|
37392
|
+
atomicWriteText(path84.join(job, "blocked.json"), JSON.stringify({ type: "tool_loop", pattern: "", message: reason2, at: (/* @__PURE__ */ new Date()).toISOString() }));
|
|
37393
37393
|
kill();
|
|
37394
37394
|
}, 3e4);
|
|
37395
37395
|
let exitCode;
|
|
@@ -37410,11 +37410,11 @@ async function launch(options, reservation = createJob(options)) {
|
|
|
37410
37410
|
for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) process.off(signal, cancel);
|
|
37411
37411
|
fs25.closeSync(out);
|
|
37412
37412
|
fs25.closeSync(err);
|
|
37413
|
-
const blockedFile =
|
|
37413
|
+
const blockedFile = path84.join(job, "blocked.json"), refusal = refused ?? stderrRefusal(stderr);
|
|
37414
37414
|
if (refusal && !fs25.existsSync(blockedFile)) atomicWriteText(blockedFile, JSON.stringify({ ...refusal, at: (/* @__PURE__ */ new Date()).toISOString() }));
|
|
37415
37415
|
const blocked = fs25.existsSync(blockedFile);
|
|
37416
37416
|
if (blocked) console.error(`blocked: ${fs25.readFileSync(blockedFile, "utf8").slice(0, 4e3)}`);
|
|
37417
|
-
fs25.writeFileSync(
|
|
37417
|
+
fs25.writeFileSync(path84.join(job, "exit.txt"), `${exitCode}
|
|
37418
37418
|
`, { mode: 384 });
|
|
37419
37419
|
writeManifest2(job, {
|
|
37420
37420
|
...manifest,
|
|
@@ -37441,7 +37441,7 @@ var init_launcher = __esm({
|
|
|
37441
37441
|
});
|
|
37442
37442
|
|
|
37443
37443
|
// src/bridge/command.ts
|
|
37444
|
-
import { readFile as
|
|
37444
|
+
import { readFile as readFile54 } from "node:fs/promises";
|
|
37445
37445
|
|
|
37446
37446
|
// src/bridge/owner-inbox.ts
|
|
37447
37447
|
init_zod();
|
|
@@ -37556,7 +37556,7 @@ import * as fs17 from "node:fs";
|
|
|
37556
37556
|
import * as path16 from "node:path";
|
|
37557
37557
|
var core = (names) => names.map((name) => ({ name, profiles: ["core", "full"] }));
|
|
37558
37558
|
var full = (names) => names.map((name) => ({ name, profiles: ["full"] }));
|
|
37559
|
-
var routes = (method, paths) => paths.map((
|
|
37559
|
+
var routes = (method, paths) => paths.map((path116) => ({ method, path: path116 }));
|
|
37560
37560
|
var BUILTIN_MODULES = [
|
|
37561
37561
|
{
|
|
37562
37562
|
schemaVersion: 1,
|
|
@@ -37944,7 +37944,7 @@ var BUILTIN_MODULES = [
|
|
|
37944
37944
|
],
|
|
37945
37945
|
capabilities: ["dispatch", "conductorSets", "ownerInbox", "workerReports", "queuedHandOff"],
|
|
37946
37946
|
storeFiles: ["global/skills/conductor/**"],
|
|
37947
|
-
localFiles: ["<bridge>/hooks.yaml", "<bridge>/conductor.yaml", "<bridge>/conductor-role.json", "<bridge>/authority.yaml", "<bridge>/authority-confirmations.json", "<bridge>/dispatches/*.json", "<bridge>/hand-offs/*.json", "<bridge>/worker-reports/*.json", "<bridge>/closed-workers/*.json", "<bridge>/owner-inbox.json", "<bridge>/integrator.json"],
|
|
37947
|
+
localFiles: ["<bridge>/hooks.yaml", "<bridge>/conductor.yaml", "<bridge>/conductor-role.json", "<bridge>/conductor/brief.md", "<bridge>/authority.yaml", "<bridge>/authority-confirmations.json", "<bridge>/dispatches/*.json", "<bridge>/hand-offs/*.json", "<bridge>/worker-reports/*.json", "<bridge>/closed-workers/*.json", "<bridge>/owner-inbox.json", "<bridge>/integrator.json"],
|
|
37948
37948
|
phoneScreens: [],
|
|
37949
37949
|
skills: ["conductor"]
|
|
37950
37950
|
},
|
|
@@ -39639,12 +39639,27 @@ import path45 from "node:path";
|
|
|
39639
39639
|
var FAST_HOOK_FILE = "claude-hook.mjs";
|
|
39640
39640
|
var fastHookPath = (versionDir) => path45.join(versionDir, FAST_HOOK_FILE);
|
|
39641
39641
|
var TOOL_HOOK_BUDGET_MS = 5e3;
|
|
39642
|
+
function hookOutput(event, result) {
|
|
39643
|
+
if (event === "PermissionRequest") return result;
|
|
39644
|
+
if (event !== "SessionStart" && event !== "UserPromptSubmit") return "";
|
|
39645
|
+
try {
|
|
39646
|
+
const reply = JSON.parse(result);
|
|
39647
|
+
if (event === "UserPromptSubmit" && reply?.decision === "block") return result;
|
|
39648
|
+
const output2 = reply?.hookSpecificOutput;
|
|
39649
|
+
if (output2?.hookEventName === event && typeof output2.additionalContext === "string" && output2.additionalContext.trim()) {
|
|
39650
|
+
return JSON.stringify({ hookSpecificOutput: { hookEventName: event, additionalContext: output2.additionalContext } });
|
|
39651
|
+
}
|
|
39652
|
+
} catch {
|
|
39653
|
+
}
|
|
39654
|
+
return "";
|
|
39655
|
+
}
|
|
39642
39656
|
var fastHookSource = (toolBudgetMs = TOOL_HOOK_BUDGET_MS) => `// Installed by Phren Hook: Claude Code's hook events, forwarded to the running Hook.
|
|
39643
39657
|
import { request } from "node:http";
|
|
39644
39658
|
import { homedir } from "node:os";
|
|
39645
39659
|
import path from "node:path";
|
|
39646
39660
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
39647
39661
|
const env = process.env, source = process.argv[2];
|
|
39662
|
+
const hookOutput = ${hookOutput.toString()};
|
|
39648
39663
|
async function full() {
|
|
39649
39664
|
const bundle = path.join(path.dirname(fileURLToPath(import.meta.url)), "bridge-hook.mjs");
|
|
39650
39665
|
process.argv = [process.argv[0], bundle, "hook", source];
|
|
@@ -39683,7 +39698,7 @@ async function forward(place) {
|
|
|
39683
39698
|
headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(data) } }, res => {
|
|
39684
39699
|
let result = "";
|
|
39685
39700
|
res.on("data", chunk => { result += chunk.toString(); if (result.length > 16_384) req.destroy(); });
|
|
39686
|
-
res.on("end", () => { if (res.statusCode === 200
|
|
39701
|
+
res.on("end", () => { if (res.statusCode === 200) process.stdout.write(hookOutput(event, result)); resolve(); });
|
|
39687
39702
|
res.on("error", () => resolve());
|
|
39688
39703
|
});
|
|
39689
39704
|
req.on("error", () => resolve()); req.on("timeout", () => { req.destroy(); resolve(); }); req.end(data);
|
|
@@ -40897,7 +40912,7 @@ function opencodePluginNeedsWrite(existing, source) {
|
|
|
40897
40912
|
return existing.startsWith(OPENCODE_PLUGIN_MARKER);
|
|
40898
40913
|
}
|
|
40899
40914
|
async function opencodePluginSource() {
|
|
40900
|
-
if (true) return '// Installed by Phren Hook and replaced on every update. Copy it under another name to customize.\nimport { execFileSync } from "node:child_process";\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// An ask relayed from its event blocks nothing: the TUI keeps its own prompt,\n// so the phone\'s card can wait as long as the ask does.\nconst RELAYED_DEADLINE_MS = 30 * 60_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\n/** Started by Phren Hook with a port of its own (`opencode --port N`, with\n * PHREN_OPENCODE_PORT=N and a server password in its environment): the Hook\n * lists and answers this process\'s permission asks over its HTTP API, so no\n * request file is written for them. The port must be on this process\'s own\n * command line, so an OpenCode started by hand in the same shell keeps the\n * file path. Plugins run in a worker whose `process.argv` is the worker\'s,\n * so the command line comes from `ps`, once. */\nlet served;\nfunction servedByHook() {\n if (served !== undefined) return served;\n const port = text(process.env.PHREN_OPENCODE_PORT);\n served = false;\n if (!/^\\d{1,5}$/.test(port) || !text(process.env.OPENCODE_SERVER_PASSWORD)) return served;\n try {\n const command = execFileSync("ps", ["-ww", "-o", "command=", "-p", String(process.pid)], { encoding: "utf8", timeout: 2_000 });\n served = new RegExp(`(?:^|\\\\s)--port(?:\\\\s+|=)${port}(?:\\\\s|$)`).test(command.trim());\n } catch {}\n return served;\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 input => {\n // The process\'s own API, bound to its in-process server (no port needed).\n const client = input?.client;\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 // The session\'s last turn: when it went busy, and when it went idle after\n // that. Dispatch returns read these as the turn\'s start and Stop.\n let turn = {};\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 const at = new Date().toISOString();\n if (sessionID && turn.session !== sessionID) turn = { session: sessionID };\n if (next !== "idle" && (recordedStatus === undefined || recordedStatus === "idle")) { turn.busyAt = at; delete turn.idleAt; }\n else if (next === "idle" && turn.busyAt) turn.idleAt = at;\n mkdirSync(path.dirname(statusFile()), { recursive: true });\n writeJsonAtomic(statusFile(), { status: next, ...(sessionID ? { session: sessionID } : {}), at,\n ...(turn.session === sessionID && turn.busyAt ? { busyAt: turn.busyAt } : {}), ...(turn.session === sessionID && turn.idleAt ? { idleAt: turn.idleAt } : {}) });\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 // Asks the permission.ask hook took (OpenCode before 1.18), and asks relayed\n // from their event, by id; `done` once the terminal answered one.\n const hookAsks = new Set();\n const relayed = new Map();\n\n /** OpenCode 1.18 never calls the permission.ask hook: its TUI draws the ask\n * from the `permission.asked` event. For an OpenCode started by hand the ask\n * goes to the phone through the same request file, and the phone\'s answer\n * is replied through this process\'s own API. Whichever answers first wins;\n * an answer in the terminal (`permission.replied`) withdraws the card. */\n const relayAsk = async ask => {\n const id = text(ask?.id), sessionID = text(ask?.sessionID);\n if (process.env.PHREN_FANOUT_JOB || !id || hookAsks.has(id) || relayed.has(id) || !OPENCODE_SESSION.test(sessionID)\n || typeof client?.postSessionIdPermissionsPermissionId !== "function" || servedByHook() || pendingApprovals.has(sessionID)) return;\n const shown = { type: text(ask.permission) || text(ask.type), pattern: Array.isArray(ask.patterns) ? ask.patterns : ask.pattern,\n metadata: ask.metadata, title: ask.title };\n const state = { done: false };\n relayed.set(id, state); pendingApprovals.add(sessionID);\n const { request, answer } = approvalPaths(sessionID);\n try {\n mkdirSync(approvalDirectory(), { recursive: true });\n removeFile(answer);\n const created = Date.now();\n writeJsonAtomic(request, { id, sessionID, type: shown.type || "action",\n title: text(shown.title) || `Allow ${shown.type || "action"}?`, message: permissionMessage(shown),\n createdAt: new Date(created).toISOString(), expiresAt: new Date(created + RELAYED_DEADLINE_MS).toISOString() });\n let decision;\n while (!state.done && Date.now() < created + RELAYED_DEADLINE_MS) {\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 && (value.decision === "approve" || value.decision === "deny" || value.decision === "always")) { decision = value.decision; break; }\n } catch {}\n }\n if (decision && !state.done) {\n await client.postSessionIdPermissionsPermissionId({ path: { id: sessionID, permissionID: id },\n body: { response: decision === "approve" ? "once" : decision === "always" ? "always" : "reject" } });\n }\n } catch {} finally {\n removeFile(answer); removeFile(request);\n pendingApprovals.delete(sessionID); relayed.delete(id);\n }\n };\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) { hookAsks.add(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 || servedByHook()) { 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" || decision === "always" ? "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" || decision === "always")) { asking.delete(askId); recordStatus("working", pendingSession); }\n if (askId) hookAsks.delete(askId);\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 if (event.type === "permission.asked") void relayAsk(properties).catch(() => {});\n } else if (event?.type === "permission.replied") {\n const id = permissionId(properties);\n if (id) asking.delete(id); else asking.clear();\n const relay = id && relayed.get(id);\n if (relay) relay.done = true;\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';
|
|
40915
|
+
if (true) return '// Installed by Phren Hook and replaced on every update. Copy it under another name to customize.\nimport { request } from "node:http";\nimport { execFileSync } from "node:child_process";\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// An ask relayed from its event blocks nothing: the TUI keeps its own prompt,\n// so the phone\'s card can wait as long as the ask does.\nconst RELAYED_DEADLINE_MS = 30 * 60_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\n/** Started by Phren Hook with a port of its own (`opencode --port N`, with\n * PHREN_OPENCODE_PORT=N and a server password in its environment): the Hook\n * lists and answers this process\'s permission asks over its HTTP API, so no\n * request file is written for them. The port must be on this process\'s own\n * command line, so an OpenCode started by hand in the same shell keeps the\n * file path. Plugins run in a worker whose `process.argv` is the worker\'s,\n * so the command line comes from `ps`, once. */\nlet served;\nfunction servedByHook() {\n if (served !== undefined) return served;\n const port = text(process.env.PHREN_OPENCODE_PORT);\n served = false;\n if (!/^\\d{1,5}$/.test(port) || !text(process.env.OPENCODE_SERVER_PASSWORD)) return served;\n try {\n const command = execFileSync("ps", ["-ww", "-o", "command=", "-p", String(process.pid)], { encoding: "utf8", timeout: 2_000 });\n served = new RegExp(`(?:^|\\\\s)--port(?:\\\\s+|=)${port}(?:\\\\s|$)`).test(command.trim());\n } catch {}\n return served;\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\n/** Context reads never hold up a model request when the Hook is unavailable. */\nfunction conductorContext(session) {\n return new Promise(resolve => {\n const socketPath = path.join(process.env.PHREN_BRIDGE_HOME || path.join(homedir(), ".local/share/phren/bridge"), "agent.sock");\n const data = JSON.stringify({ pid: process.pid, session });\n const req = request({ socketPath, path: "/conductor-context", method: "POST",\n headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(data) } }, res => {\n let body = "";\n res.on("data", chunk => { body += chunk; if (body.length > 16_384) req.destroy(); });\n res.on("end", () => {\n try { const value = JSON.parse(body); finish(res.statusCode === 200 && typeof value.context === "string" ? value.context : undefined); }\n catch { finish(); }\n });\n res.on("error", () => finish());\n });\n const timer = setTimeout(() => { req.destroy(); finish(); }, 1_000);\n function finish(value) { clearTimeout(timer); resolve(value); }\n req.on("error", () => finish()); req.end(data);\n });\n}\n\nexport const PhrenTranscriptPlugin = async input => {\n // The process\'s own API, bound to its in-process server (no port needed).\n const client = input?.client;\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 // The session\'s last turn: when it went busy, and when it went idle after\n // that. Dispatch returns read these as the turn\'s start and Stop.\n let turn = {};\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 const at = new Date().toISOString();\n if (sessionID && turn.session !== sessionID) turn = { session: sessionID };\n if (next !== "idle" && (recordedStatus === undefined || recordedStatus === "idle")) { turn.busyAt = at; delete turn.idleAt; }\n else if (next === "idle" && turn.busyAt) turn.idleAt = at;\n mkdirSync(path.dirname(statusFile()), { recursive: true });\n writeJsonAtomic(statusFile(), { status: next, ...(sessionID ? { session: sessionID } : {}), at,\n ...(turn.session === sessionID && turn.busyAt ? { busyAt: turn.busyAt } : {}), ...(turn.session === sessionID && turn.idleAt ? { idleAt: turn.idleAt } : {}) });\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 // Asks the permission.ask hook took (OpenCode before 1.18), and asks relayed\n // from their event, by id; `done` once the terminal answered one.\n const hookAsks = new Set();\n const relayed = new Map();\n\n /** OpenCode 1.18 never calls the permission.ask hook: its TUI draws the ask\n * from the `permission.asked` event. For an OpenCode started by hand the ask\n * goes to the phone through the same request file, and the phone\'s answer\n * is replied through this process\'s own API. Whichever answers first wins;\n * an answer in the terminal (`permission.replied`) withdraws the card. */\n const relayAsk = async ask => {\n const id = text(ask?.id), sessionID = text(ask?.sessionID);\n if (process.env.PHREN_FANOUT_JOB || !id || hookAsks.has(id) || relayed.has(id) || !OPENCODE_SESSION.test(sessionID)\n || typeof client?.postSessionIdPermissionsPermissionId !== "function" || servedByHook() || pendingApprovals.has(sessionID)) return;\n const shown = { type: text(ask.permission) || text(ask.type), pattern: Array.isArray(ask.patterns) ? ask.patterns : ask.pattern,\n metadata: ask.metadata, title: ask.title };\n const state = { done: false };\n relayed.set(id, state); pendingApprovals.add(sessionID);\n const { request, answer } = approvalPaths(sessionID);\n try {\n mkdirSync(approvalDirectory(), { recursive: true });\n removeFile(answer);\n const created = Date.now();\n writeJsonAtomic(request, { id, sessionID, type: shown.type || "action",\n title: text(shown.title) || `Allow ${shown.type || "action"}?`, message: permissionMessage(shown),\n createdAt: new Date(created).toISOString(), expiresAt: new Date(created + RELAYED_DEADLINE_MS).toISOString() });\n let decision;\n while (!state.done && Date.now() < created + RELAYED_DEADLINE_MS) {\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 && (value.decision === "approve" || value.decision === "deny" || value.decision === "always")) { decision = value.decision; break; }\n } catch {}\n }\n if (decision && !state.done) {\n await client.postSessionIdPermissionsPermissionId({ path: { id: sessionID, permissionID: id },\n body: { response: decision === "approve" ? "once" : decision === "always" ? "always" : "reject" } });\n }\n } catch {} finally {\n removeFile(answer); removeFile(request);\n pendingApprovals.delete(sessionID); relayed.delete(id);\n }\n };\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 "experimental.chat.system.transform": async (input, output) => {\n const sessionID = text(input?.sessionID);\n if (process.env.PHREN_FANOUT_JOB || !OPENCODE_SESSION.test(sessionID) || sessionID !== boundSession || children.has(sessionID) || !Array.isArray(output?.system)) return;\n const context = await conductorContext(sessionID);\n if (context) output.system.push(context);\n },\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) { hookAsks.add(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 || servedByHook()) { 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" || decision === "always" ? "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" || decision === "always")) { asking.delete(askId); recordStatus("working", pendingSession); }\n if (askId) hookAsks.delete(askId);\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 if (event.type === "permission.asked") void relayAsk(properties).catch(() => {});\n } else if (event?.type === "permission.replied") {\n const id = permissionId(properties);\n if (id) asking.delete(id); else asking.clear();\n const relay = id && relayed.get(id);\n if (relay) relay.done = true;\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';
|
|
40901
40916
|
const here = path50.dirname(fileURLToPath4(import.meta.url));
|
|
40902
40917
|
for (const candidate of [
|
|
40903
40918
|
path50.join(here, "..", "..", "plugins", "opencode", "phren-transcript.js"),
|
|
@@ -41139,10 +41154,10 @@ function projectAgents(values, parent, receipt, fallbackComputer, fallbackTarget
|
|
|
41139
41154
|
for (const value2 of values.slice(0, 128)) {
|
|
41140
41155
|
if (state.count >= 128) break;
|
|
41141
41156
|
const raw = object2(value2), id2 = childID.safeParse(raw.id), source = provider.safeParse(raw.provider);
|
|
41142
|
-
const
|
|
41157
|
+
const path116 = publicLabel(raw.path);
|
|
41143
41158
|
const callId = typeof raw.callId === "string" && raw.callId.length > 0 && raw.callId.length <= 200 ? raw.callId : void 0;
|
|
41144
41159
|
const routed = destination(raw, fallbackComputer, fallbackTarget);
|
|
41145
|
-
if (!id2.success || !source.success || !
|
|
41160
|
+
if (!id2.success || !source.success || !path116 || !callId || !routed) continue;
|
|
41146
41161
|
const descendant = lineage ? `${lineage}/${id2.data}` : id2.data;
|
|
41147
41162
|
const nestedSession = sessionId.safeParse(raw.session);
|
|
41148
41163
|
const cycleIdentity = nestedSession.success ? nestedSession.data : routed.remote.child ?? routed.remote.target.session;
|
|
@@ -41155,7 +41170,7 @@ function projectAgents(values, parent, receipt, fallbackComputer, fallbackTarget
|
|
|
41155
41170
|
projected.push({
|
|
41156
41171
|
id: publicID(parent, routed.computer.id, receipt.id, descendant),
|
|
41157
41172
|
provider: source.data,
|
|
41158
|
-
path:
|
|
41173
|
+
path: path116,
|
|
41159
41174
|
callId,
|
|
41160
41175
|
state: raw.failed === true ? "failed" : childState,
|
|
41161
41176
|
...typeof raw.finishedAt === "string" && Number.isFinite(Date.parse(raw.finishedAt)) ? { finishedAt: raw.finishedAt } : {},
|
|
@@ -45773,7 +45788,7 @@ var HandOffQueue = class {
|
|
|
45773
45788
|
|
|
45774
45789
|
// src/bridge/server-pane-routes.ts
|
|
45775
45790
|
init_zod();
|
|
45776
|
-
import
|
|
45791
|
+
import path81 from "node:path";
|
|
45777
45792
|
import { setTimeout as sleep4 } from "node:timers/promises";
|
|
45778
45793
|
|
|
45779
45794
|
// src/bridge/git.ts
|
|
@@ -46511,26 +46526,65 @@ init_codex_servers();
|
|
|
46511
46526
|
// src/bridge/model-switch.ts
|
|
46512
46527
|
init_zod();
|
|
46513
46528
|
|
|
46529
|
+
// src/bridge/conductor-context.ts
|
|
46530
|
+
import { readFile as readFile37 } from "node:fs/promises";
|
|
46531
|
+
import path72 from "node:path";
|
|
46532
|
+
init_protocol();
|
|
46533
|
+
async function conductorBrief() {
|
|
46534
|
+
let source;
|
|
46535
|
+
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- `account_usage` (CLI `phren dispatch usage`): every computer\'s agent usage\n merged by account (each Claude login, Codex, OpenCode Go and the rest): percent\n left on each window, when it resets, whether the numbers are fresh, and the\n computers where it is signed in. In core use\n `phren_admin(action: "account_usage")`.\n- `hand_off`: send a prompt to one of those sessions. A busy session queues it\n durably in its Hook. Keep its `deliveryId`; `queued` means waiting, `delivered`\n means confirmed. Check with `hand_off(target|session, computer?, deliveryId,\n status:true)` and no text. Never resend with a new id because it is busy.\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, stalled with an unchanged screen and transcript, 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- `dispatch_report`: workers record `prs`, an array of `{url, repo, branch,\n tests, notes?}`, on their own Hook before ending the turn. The done return\n carries that evidence, and the Hook queues it to the configured integrator.\n In core use `phren_admin(action: "dispatch_report", prs)`.\n- `owner_inbox` (CLI `phren owner-inbox`): list what waits on the owner across\n linked computers, add a title with optional project, or resolve an id with\n optional resolution. In core use `phren_admin(action: "owner_inbox", ...)`.\n Use an item\'s `inboxComputer` as `computer` when resolving a remote item;\n omit it for `local`. Say which computers were unreachable.\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.\nA worker that needs root runs `sudo -A <command>`: its launch sets\n`SUDO_ASKPASS`, and the owner approves the exact command and types the\npassword on the phone. Plain `sudo` fails without a terminal.\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.\nTell every lead the same: a worker started any other way (its own `opencode\nrun` or `codex exec`, a launch script, nohup) has no manifest, so the phone and\nyou cannot see, resume or review it. Workers that exist only as processes do\nnot count as dispatched.\n\nCheck `account_usage` before you dispatch, once per batch. The one hard rule:\nnever dispatch to an account that is `exhausted` (a window at 100%, or\nrefusing requests), until its `availableIn` passes. Low quota is information,\nnot a reason to steer away: `nearLimit` (under 20% left) is still usable, and\nthe owner often wants quota used up before it resets, so an account with quota\nleft that resets soon is a good pick; use it before it resets. For Claude, pass\nthe `account` id the row\'s `computers` list gives for the computer you pick. A\n`stale` row\'s numbers may be out of date, and a window marked `reset` has\nrolled over with no new number yet: say so rather than quoting them. Name the\nchoice in the dispatch line, such as "Desk has the parser checks on Codex,\nusing its last 15% before the week resets tomorrow." When every account is\nexhausted, tell the owner before dispatching. The owner\'s explicit choice of\nharness or account always wins. Usage on `unreachable` and `notLinked`\ncomputers is unknown, not zero.\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?, effort?, permissionMode?, prompt, label)`\nin core. The CLI equivalent is `phren dispatch <computer|anywhere> <project>\n--harness <harness> --label <label> --prompt <brief> [--model <model>] [--effort <effort>]\n[--permission-mode supervised|auto-edits|auto|full-access]`. `permissionMode` sets how the\nworker starts (Claude, Codex and Copilot; not OpenCode). `harness` is codex,\nclaude, opencode or copilot.\nFor release work (merge, publish, deploy, app-store, github-admin), read the\nowner\'s release authority policy first with `authority` in full or\n`phren_admin(action: "authority", project)` in core (CLI: `phren authority show\n<project>`), quote its `line` in the brief, and list the actions in\n`releaseActions`. An ask-first action is refused until the owner confirms it:\nask them, and never confirm or change the policy yourself. The policy only\nrestricts; when a worker\'s own harness still refuses release work, only the\nowner\'s own harness settings can allow it.\n`anywhere` chooses the connected computer with the fewest working agents, and\nskips one whose account for that harness is exhausted. Place\nbriefs sequentially, respecting busy/rate-limit responses. Keep their dispatch\nIDs. Do not send local filesystem paths as remote project names.\n\nConfigure the integrator once with `phren conductor integrator --session <id>\n[--computer <name>]`; list with `phren conductor integrator`, clear with\n`--clear`. A dispatch can override it with `integrator: {computer?, target}`.\nThe integrator\'s full target is bound to that conversation. Workers report\nstructured PR evidence with `dispatch_report(prs)` in full or\n`phren_admin(action:"dispatch_report", prs)` in core before finishing; they do not\nneed direct messaging or a GitHub comment to reach it. Inspect `prs` and\n`integratorDelivery` in receipts and verify the evidence before integration.\n\nFinished worker panes close after their done return is read. Use\n`closeOnFinish:false` (`--keep-open` in the CLI) for a worker you will reuse.\nThe Hook rechecks its ended turn and skips a pane with new work, background\ntasks, queued messages or uncertain delivery. Intentional closes do not return\n`gone`. Reading returns can close panes, so record any follow-up first.\n\nKeep one owner inbox item for each decision or action that waits on the owner.\nNeeds-you returns and blocked prompts appear automatically, even if their\nreturns were read. Add other actions such as restarting the router with\n`owner_inbox(operation:"add", title, project?, id?)` in full or\n`phren_admin(action:"owner_inbox", operation:"add", title, project?, id?)` in\ncore; keep the id on retries.\nResolve an item only once the owner decided or completed the action. Resolution\ndoes not send an answer, approve a prompt, or mark a task complete. Send an\nowner\'s answer separately with queued `hand_off`. A source that stopped waiting\nis retained as `live:false` until resolved; a resolved source stays resolved.\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\nA return with an `approval` is a permission request a worker is waiting on.\nAnswer it with `dispatch_approve` when it is plainly what the brief asked for;\ndeny when unsure and ask the owner. Standing grants already answer `dispatch`\nand `hand_off` requests they cover.\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\nA `stalled` return or `live_sessions` row with `stalled:true` means both the\nscreen and transcript have stopped changing while working. Check it and report\nwhat is known; do not launch a duplicate or interrupt it just because of the flag.\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';
|
|
46536
|
+
else {
|
|
46537
|
+
const here = path72.dirname(fileURLToPath(import.meta.url));
|
|
46538
|
+
for (const candidate of [
|
|
46539
|
+
path72.join(here, "..", "starter", "global", "skills", "conductor", "SKILL.md"),
|
|
46540
|
+
path72.join(here, "..", "..", "starter", "global", "skills", "conductor", "SKILL.md")
|
|
46541
|
+
]) {
|
|
46542
|
+
source = await readFile37(candidate, "utf8").catch(() => void 0);
|
|
46543
|
+
if (source !== void 0) break;
|
|
46544
|
+
}
|
|
46545
|
+
}
|
|
46546
|
+
if (source === void 0) throw new BridgeError(503, "The shipped conductor brief is unavailable. Reinstall Phren Hook.");
|
|
46547
|
+
const match = /^---\r?\n[\s\S]*?\r?\n---\r?\n([\s\S]*)$/.exec(source);
|
|
46548
|
+
const brief = (match?.[1] ?? source).trim();
|
|
46549
|
+
if (!brief) throw new BridgeError(503, "The shipped conductor brief is empty. Reinstall Phren Hook.");
|
|
46550
|
+
return brief;
|
|
46551
|
+
}
|
|
46552
|
+
async function ensureConductorBrief(brief) {
|
|
46553
|
+
const file3 = path72.join(bridgeRoot(), "conductor", "brief.md");
|
|
46554
|
+
const content = (brief ?? await conductorBrief()) + "\n";
|
|
46555
|
+
if (await readFile37(file3, "utf8").catch(() => void 0) !== content) await atomicInPrivateDir(file3, content);
|
|
46556
|
+
return file3;
|
|
46557
|
+
}
|
|
46558
|
+
async function conductorContext(target, snapshot2) {
|
|
46559
|
+
const pane = await conductorPane(target.server, snapshot2);
|
|
46560
|
+
if (!runsAgent(pane) || pane.pane_id !== target.pane || pane.agent !== target.source) return void 0;
|
|
46561
|
+
const file3 = await ensureConductorBrief();
|
|
46562
|
+
await noteConductorSession(target.server, target.pane, target.session);
|
|
46563
|
+
return `Phren role for this turn: conductor. Your role is attached to this live terminal and applies after startup, resume, model changes and compaction. Read the conductor brief at ${JSON.stringify(file3)} before coordinating work if it is not already in context.
|
|
46564
|
+
For questions about running work, start with Phren live_sessions (core: phren_admin action live_sessions; CLI: phren dispatch sessions). It includes linked computers and their sessions. Report unreachable and unlinked computers explicitly. Consult get_tasks and get_project_summary for the relevant projects, and dispatch_returns for worker outcomes.
|
|
46565
|
+
Use dispatch for a new worker and hand_off for an existing session; preserve delivery IDs and check queued delivery status before retrying. Respect the owner's current limits on delegation, permissions and releases. Verify returns and tests before integrating or marking tasks done. Keep owner replies short and put detailed evidence in tasks. The role grants no additional permissions.`;
|
|
46566
|
+
}
|
|
46567
|
+
|
|
46514
46568
|
// src/bridge/agent-hooks.ts
|
|
46515
46569
|
init_shared();
|
|
46516
46570
|
init_logger();
|
|
46517
46571
|
init_protocol();
|
|
46518
46572
|
init_herdr();
|
|
46519
46573
|
import { request as request6, createServer as createServer2 } from "node:http";
|
|
46520
|
-
import { mkdir as mkdir20, readFile as
|
|
46574
|
+
import { mkdir as mkdir20, readFile as readFile40, chmod as chmod4, unlink as unlink7, lstat as lstat25 } from "node:fs/promises";
|
|
46521
46575
|
import { watch } from "node:fs";
|
|
46522
|
-
import
|
|
46576
|
+
import path78 from "node:path";
|
|
46523
46577
|
import { createHash as createHash23, randomUUID as randomUUID17 } from "node:crypto";
|
|
46524
46578
|
import { hostname as hostname10 } from "node:os";
|
|
46525
46579
|
init_codex_daemon();
|
|
46526
46580
|
|
|
46527
46581
|
// src/bridge/codex-review-mode.ts
|
|
46528
46582
|
import { open as open16 } from "node:fs/promises";
|
|
46529
|
-
import
|
|
46583
|
+
import path73 from "node:path";
|
|
46530
46584
|
var SCAN_LIMIT = 64 * 1048576;
|
|
46531
46585
|
var CHUNK = 1048576;
|
|
46532
46586
|
async function codexAutoReview(transcriptPath2) {
|
|
46533
|
-
if (typeof transcriptPath2 !== "string" || !
|
|
46587
|
+
if (typeof transcriptPath2 !== "string" || !path73.isAbsolute(transcriptPath2) || !/^rollout-.*\.jsonl$/.test(path73.basename(transcriptPath2))) return false;
|
|
46534
46588
|
const file3 = await open16(transcriptPath2, "r").catch(() => void 0);
|
|
46535
46589
|
if (!file3) return false;
|
|
46536
46590
|
try {
|
|
@@ -46585,9 +46639,9 @@ init_fanouts();
|
|
|
46585
46639
|
init_zod();
|
|
46586
46640
|
init_protocol();
|
|
46587
46641
|
import { createCipheriv, createHmac as createHmac2, createPrivateKey, randomBytes as randomBytes3, sign } from "node:crypto";
|
|
46588
|
-
import { readFile as
|
|
46642
|
+
import { readFile as readFile38, stat as stat19 } from "node:fs/promises";
|
|
46589
46643
|
import { connect as connect3 } from "node:http2";
|
|
46590
|
-
import
|
|
46644
|
+
import path74 from "node:path";
|
|
46591
46645
|
var relaySchema = external_exports.object({
|
|
46592
46646
|
url: external_exports.string().url().refine(
|
|
46593
46647
|
(value2) => /^https:\/\//.test(value2) || /^http:\/\/(127\.0\.0\.1|localhost)(:\d+)?\//.test(`${value2}/`),
|
|
@@ -46680,7 +46734,7 @@ async function secureJSON(file3, schema) {
|
|
|
46680
46734
|
try {
|
|
46681
46735
|
const metadata = await stat19(file3);
|
|
46682
46736
|
if ((metadata.mode & 63) !== 0 || process.getuid && metadata.uid !== process.getuid()) return void 0;
|
|
46683
|
-
return schema.parse(JSON.parse(await
|
|
46737
|
+
return schema.parse(JSON.parse(await readFile38(file3, "utf8")));
|
|
46684
46738
|
} catch {
|
|
46685
46739
|
return void 0;
|
|
46686
46740
|
}
|
|
@@ -46689,12 +46743,12 @@ async function secureFile(file3) {
|
|
|
46689
46743
|
try {
|
|
46690
46744
|
const metadata = await stat19(file3);
|
|
46691
46745
|
if (!metadata.isFile() || (metadata.mode & 63) !== 0 || process.getuid && metadata.uid !== process.getuid()) return void 0;
|
|
46692
|
-
return await
|
|
46746
|
+
return await readFile38(file3, "utf8");
|
|
46693
46747
|
} catch {
|
|
46694
46748
|
return void 0;
|
|
46695
46749
|
}
|
|
46696
46750
|
}
|
|
46697
|
-
function apnsSetupSteps(configFile = process.env.PHREN_APNS_CONFIG ||
|
|
46751
|
+
function apnsSetupSteps(configFile = process.env.PHREN_APNS_CONFIG || path74.join(bridgeRoot(), "apns.json")) {
|
|
46698
46752
|
return [
|
|
46699
46753
|
"Approval push is not configured: the phone only alerts while Phren runs, and a registered phone gets nothing while suspended.",
|
|
46700
46754
|
"1. In your Apple developer account, create an APNs key (Keys, Apple Push Notifications service) and download AuthKey_<KEYID>.p8.",
|
|
@@ -46816,13 +46870,13 @@ var APNsSender = class {
|
|
|
46816
46870
|
var ApprovalPushService = class {
|
|
46817
46871
|
devices = [];
|
|
46818
46872
|
sender;
|
|
46819
|
-
devicesFile =
|
|
46873
|
+
devicesFile = path74.join(bridgeRoot(), "push-devices.json");
|
|
46820
46874
|
async start() {
|
|
46821
46875
|
this.devices = await secureJSON(this.devicesFile, external_exports.array(deviceSchema).max(16)) ?? [];
|
|
46822
|
-
const configFile = process.env.PHREN_APNS_CONFIG ||
|
|
46876
|
+
const configFile = process.env.PHREN_APNS_CONFIG || path74.join(bridgeRoot(), "apns.json");
|
|
46823
46877
|
const config3 = await secureJSON(configFile, configSchema2);
|
|
46824
46878
|
if (!config3) return;
|
|
46825
|
-
const keyPath =
|
|
46879
|
+
const keyPath = path74.isAbsolute(config3.privateKeyPath) ? config3.privateKeyPath : path74.resolve(path74.dirname(configFile), config3.privateKeyPath);
|
|
46826
46880
|
const key3 = await secureFile(keyPath);
|
|
46827
46881
|
if (key3) this.sender = new APNsSender(config3, key3);
|
|
46828
46882
|
}
|
|
@@ -46938,10 +46992,10 @@ init_locks();
|
|
|
46938
46992
|
init_home_paths();
|
|
46939
46993
|
init_protocol();
|
|
46940
46994
|
import { randomUUID as randomUUID16 } from "node:crypto";
|
|
46941
|
-
import { lstat as lstat24, mkdir as mkdir19, readFile as
|
|
46942
|
-
import
|
|
46995
|
+
import { lstat as lstat24, mkdir as mkdir19, readFile as readFile39, rename as rename6, unlink as unlink6, writeFile as writeFile6 } from "node:fs/promises";
|
|
46996
|
+
import path75 from "node:path";
|
|
46943
46997
|
function opencodeConfigPath(env = process.env, home = homeDir(env)) {
|
|
46944
|
-
return
|
|
46998
|
+
return path75.join(env.XDG_CONFIG_HOME || path75.join(home, ".config"), "opencode", "opencode.json");
|
|
46945
46999
|
}
|
|
46946
47000
|
function opencodeToolName(value2) {
|
|
46947
47001
|
if (typeof value2 !== "string") return void 0;
|
|
@@ -46951,7 +47005,7 @@ function opencodeToolName(value2) {
|
|
|
46951
47005
|
async function readConfig2(file3) {
|
|
46952
47006
|
let text4;
|
|
46953
47007
|
try {
|
|
46954
|
-
text4 = await
|
|
47008
|
+
text4 = await readFile39(file3, "utf8");
|
|
46955
47009
|
} catch (error62) {
|
|
46956
47010
|
if (error62.code === "ENOENT") return {};
|
|
46957
47011
|
throw new BridgeError(409, "Could not read ~/.config/opencode/opencode.json.");
|
|
@@ -46989,7 +47043,7 @@ async function allowOpencodeToolEverywhere(tool, file3 = opencodeConfigPath()) {
|
|
|
46989
47043
|
try {
|
|
46990
47044
|
const config3 = withAllowedTool(await readConfig2(file3), name);
|
|
46991
47045
|
const mode = (await lstat24(file3).catch(() => void 0))?.mode;
|
|
46992
|
-
await mkdir19(
|
|
47046
|
+
await mkdir19(path75.dirname(file3), { recursive: true, mode: 448 });
|
|
46993
47047
|
const temporary = `${file3}.${randomUUID16()}.tmp`;
|
|
46994
47048
|
await writeFile6(temporary, `${JSON.stringify(config3, null, 2)}
|
|
46995
47049
|
`, { mode: mode === void 0 ? 384 : mode & 511, flag: "wx" });
|
|
@@ -47017,7 +47071,7 @@ init_codex_servers();
|
|
|
47017
47071
|
// src/bridge/opencode-panes.ts
|
|
47018
47072
|
init_limits();
|
|
47019
47073
|
import { execFile as execFile15 } from "node:child_process";
|
|
47020
|
-
import
|
|
47074
|
+
import path77 from "node:path";
|
|
47021
47075
|
import { promisify as promisify14 } from "node:util";
|
|
47022
47076
|
|
|
47023
47077
|
// src/bridge/opencode-pane-server.ts
|
|
@@ -47025,7 +47079,7 @@ init_phren_paths();
|
|
|
47025
47079
|
import * as crypto6 from "node:crypto";
|
|
47026
47080
|
import * as fs23 from "node:fs";
|
|
47027
47081
|
import * as net from "node:net";
|
|
47028
|
-
import * as
|
|
47082
|
+
import * as path76 from "node:path";
|
|
47029
47083
|
var MAX_PASSWORD = 200;
|
|
47030
47084
|
var REQUEST_TIMEOUT_MS = 1e4;
|
|
47031
47085
|
var PROMPT_POLL_MS = 200;
|
|
@@ -47050,7 +47104,7 @@ function alive(pid) {
|
|
|
47050
47104
|
}
|
|
47051
47105
|
}
|
|
47052
47106
|
function paneServerFile(dir, server, pane) {
|
|
47053
|
-
return
|
|
47107
|
+
return path76.join(dir, `${encodeURIComponent(`${server}/${pane}`)}.json`);
|
|
47054
47108
|
}
|
|
47055
47109
|
function registerPaneServer(dir, entry2) {
|
|
47056
47110
|
if (!validEntry(entry2)) throw new Error("Invalid OpenCode pane server entry.");
|
|
@@ -47088,7 +47142,7 @@ function listPaneServers(dir) {
|
|
|
47088
47142
|
const entries2 = [];
|
|
47089
47143
|
for (const name of names.slice(0, 1024)) {
|
|
47090
47144
|
if (!name.endsWith(".json")) continue;
|
|
47091
|
-
const file3 =
|
|
47145
|
+
const file3 = path76.join(dir, name);
|
|
47092
47146
|
let parsed;
|
|
47093
47147
|
try {
|
|
47094
47148
|
const info = fs23.lstatSync(file3);
|
|
@@ -47294,7 +47348,7 @@ var READY_MS = 2e4;
|
|
|
47294
47348
|
var PID_MS = intervalFromEnv("PHREN_OPENCODE_PID_MS", 2e3);
|
|
47295
47349
|
var BRIEF_CONFIRM_MS = 1e4;
|
|
47296
47350
|
function paneServersDir() {
|
|
47297
|
-
return
|
|
47351
|
+
return path77.join(bridgeRoot(), "opencode-panes");
|
|
47298
47352
|
}
|
|
47299
47353
|
function servedPane(server, pane) {
|
|
47300
47354
|
return readPaneServer(paneServersDir(), server, pane);
|
|
@@ -47694,7 +47748,7 @@ var AgentHooks = class {
|
|
|
47694
47748
|
/** sudo -A requests from askpass, answered from the phone (sudo.ts). */
|
|
47695
47749
|
sudo;
|
|
47696
47750
|
approvalsDirectory() {
|
|
47697
|
-
return
|
|
47751
|
+
return path78.join(phrenStoreRoot(), ".runtime", "approvals");
|
|
47698
47752
|
}
|
|
47699
47753
|
scheduleOpencodeSweep() {
|
|
47700
47754
|
if (this.closed || this.opencodeDebounce) return;
|
|
@@ -47832,7 +47886,7 @@ var AgentHooks = class {
|
|
|
47832
47886
|
provider: "opencode",
|
|
47833
47887
|
question: false,
|
|
47834
47888
|
expiresAt: String(request9.expiresAt),
|
|
47835
|
-
project:
|
|
47889
|
+
project: path78.basename(entry2.directory),
|
|
47836
47890
|
computer: this.computerName,
|
|
47837
47891
|
...summary
|
|
47838
47892
|
}).then((delivered) => {
|
|
@@ -47961,15 +48015,15 @@ var AgentHooks = class {
|
|
|
47961
48015
|
/** A session's exact pane. A recorded binding carries the full target; when
|
|
47962
48016
|
* there is none, Herdr's explicit session identity names the pane. */
|
|
47963
48017
|
async resolveTarget(source, session) {
|
|
47964
|
-
const root =
|
|
48018
|
+
const root = path78.join(bridgeRoot(), "bindings");
|
|
47965
48019
|
for await (const folder of directoryNames(root, 64)) {
|
|
47966
|
-
for await (const name of directoryNames(
|
|
48020
|
+
for await (const name of directoryNames(path78.join(root, folder), 1024)) {
|
|
47967
48021
|
if (!name.endsWith(".json")) continue;
|
|
47968
48022
|
let value2;
|
|
47969
48023
|
try {
|
|
47970
|
-
const file3 =
|
|
48024
|
+
const file3 = path78.join(root, folder, name), info = await lstat25(file3);
|
|
47971
48025
|
if (!info.isFile() || info.size > 65536) continue;
|
|
47972
|
-
value2 = object2(JSON.parse(await
|
|
48026
|
+
value2 = object2(JSON.parse(await readFile40(file3, "utf8")));
|
|
47973
48027
|
} catch {
|
|
47974
48028
|
continue;
|
|
47975
48029
|
}
|
|
@@ -48973,7 +49027,7 @@ ${target.source}`) ?? 0) > Date.now();
|
|
|
48973
49027
|
})()).hookSpecificOutput).decision).behavior;
|
|
48974
49028
|
if (behavior === "allow" || behavior === "deny") held.answer(appServerDecision(request9, behavior === "allow"));
|
|
48975
49029
|
} };
|
|
48976
|
-
const cwd = typeof request9.params.cwd === "string" &&
|
|
49030
|
+
const cwd = typeof request9.params.cwd === "string" && path78.isAbsolute(request9.params.cwd) ? request9.params.cwd : void 0;
|
|
48977
49031
|
const summary = approvalSummary({ tool: shown.tool, input: shown.input, cwd });
|
|
48978
49032
|
const expiresAt = Date.now() + DIALOG_PUSH_MS;
|
|
48979
49033
|
this.pending.set(action, {
|
|
@@ -49027,7 +49081,7 @@ ${target.source}`) ?? 0) > Date.now();
|
|
|
49027
49081
|
await this.sudo.handle(req, res);
|
|
49028
49082
|
return;
|
|
49029
49083
|
}
|
|
49030
|
-
if (req.method !== "POST" || req.url
|
|
49084
|
+
if (req.method !== "POST" || !["/hook", "/conductor-context"].includes(req.url ?? "")) throw new Error("Invalid callback");
|
|
49031
49085
|
let size = 0;
|
|
49032
49086
|
const chunks = [];
|
|
49033
49087
|
for await (const bytes of req) {
|
|
@@ -49036,6 +49090,40 @@ ${target.source}`) ?? 0) > Date.now();
|
|
|
49036
49090
|
chunks.push(bytes);
|
|
49037
49091
|
}
|
|
49038
49092
|
const body2 = object2(JSON.parse(Buffer.concat(chunks).toString()));
|
|
49093
|
+
if (req.url === "/conductor-context") {
|
|
49094
|
+
if (this.modules?.has("conductor") === false) {
|
|
49095
|
+
res.end("{}");
|
|
49096
|
+
return;
|
|
49097
|
+
}
|
|
49098
|
+
if (!Number.isSafeInteger(body2.pid) || Number(body2.pid) <= 0 || typeof body2.session !== "string") throw new Error("Invalid context callback");
|
|
49099
|
+
const role = await recordedConductor();
|
|
49100
|
+
if (!role) {
|
|
49101
|
+
res.end("{}");
|
|
49102
|
+
return;
|
|
49103
|
+
}
|
|
49104
|
+
const s2 = await snapshot(role.server);
|
|
49105
|
+
const pane2 = objects(s2.panes).find((p) => p.pane_id === role.pane);
|
|
49106
|
+
if (!pane2 || pane2.agent !== "opencode" || role.terminal && pane2.terminal_id !== role.terminal) {
|
|
49107
|
+
res.end("{}");
|
|
49108
|
+
return;
|
|
49109
|
+
}
|
|
49110
|
+
const pids2 = (await terminalProvider().processes(role.server, role.pane)).foregroundPids;
|
|
49111
|
+
if (!pids2.includes(Number(body2.pid)) || await paneIdentity(role.server, pane2, true) !== body2.session) {
|
|
49112
|
+
res.end("{}");
|
|
49113
|
+
return;
|
|
49114
|
+
}
|
|
49115
|
+
const target2 = targetSchema.parse({
|
|
49116
|
+
server: role.server,
|
|
49117
|
+
workspace: pane2.workspace_id,
|
|
49118
|
+
tab: pane2.tab_id,
|
|
49119
|
+
pane: role.pane,
|
|
49120
|
+
source: "opencode",
|
|
49121
|
+
session: body2.session
|
|
49122
|
+
});
|
|
49123
|
+
const context = await conductorContext(target2, s2);
|
|
49124
|
+
res.end(JSON.stringify(context ? { context } : {}));
|
|
49125
|
+
return;
|
|
49126
|
+
}
|
|
49039
49127
|
let target = targetSchema.parse(body2.target);
|
|
49040
49128
|
if (this.modules?.has("git") === false && ["PreToolUse", "PostToolUse"].includes(String(body2.event))) {
|
|
49041
49129
|
res.statusCode = 404;
|
|
@@ -49045,7 +49133,7 @@ ${target.source}`) ?? 0) > Date.now();
|
|
|
49045
49133
|
const daemon = body2.daemon === true;
|
|
49046
49134
|
if (daemon) {
|
|
49047
49135
|
if (target.source !== "codex") throw new Error("Invalid callback");
|
|
49048
|
-
const placed = await paneForCodexSession(target.server, target.session, typeof body2.cwd === "string" &&
|
|
49136
|
+
const placed = await paneForCodexSession(target.server, target.session, typeof body2.cwd === "string" && path78.isAbsolute(body2.cwd) ? body2.cwd : void 0);
|
|
49049
49137
|
if (!placed) {
|
|
49050
49138
|
res.end("{}");
|
|
49051
49139
|
return;
|
|
@@ -49091,15 +49179,21 @@ ${target.source}`) ?? 0) > Date.now();
|
|
|
49091
49179
|
if (body2.event === "UserPromptSubmit") {
|
|
49092
49180
|
const answer = typeof body2.prompt === "string" ? this.submitted(target, body2.prompt.slice(0, 65536)) : {};
|
|
49093
49181
|
if (answer.decision !== "block") await this.recordTurn(target, pane, body2, dispatch2);
|
|
49094
|
-
|
|
49182
|
+
const context = answer.decision === "block" || this.modules?.has("conductor") === false ? void 0 : await conductorContext(target, s).catch(() => void 0);
|
|
49183
|
+
res.end(JSON.stringify({ ...answer, ...context ? { hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: context } } : {} }));
|
|
49095
49184
|
return;
|
|
49096
49185
|
}
|
|
49097
49186
|
if (body2.event === "SessionStart" || body2.event === "Stop") await this.recordTurn(target, pane, body2, dispatch2);
|
|
49187
|
+
if (body2.event === "SessionStart") {
|
|
49188
|
+
const context = this.modules?.has("conductor") === false ? void 0 : await conductorContext(target, s).catch(() => void 0);
|
|
49189
|
+
res.end(JSON.stringify(context ? { hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: context } } : {}));
|
|
49190
|
+
return;
|
|
49191
|
+
}
|
|
49098
49192
|
if ((this.modules?.has("git") ?? true) && ["PreToolUse", "PostToolUse"].includes(String(body2.event)) && capturesChanges(String(body2.tool), input2)) {
|
|
49099
49193
|
const conversation = `${target.source}:${target.session}`, id2 = String(body2.toolUseId || "").slice(0, 200);
|
|
49100
49194
|
if (body2.event === "PreToolUse") {
|
|
49101
49195
|
const hungUp = watchHangUp(res);
|
|
49102
|
-
await this.changes.before(conversation, id2, typeof body2.cwd === "string" &&
|
|
49196
|
+
await this.changes.before(conversation, id2, typeof body2.cwd === "string" && path78.isAbsolute(body2.cwd) ? body2.cwd : await trustedDirectory(pane), command ?? "", input2);
|
|
49103
49197
|
if (hungUp()) this.changes.drop(conversation, id2);
|
|
49104
49198
|
} else await this.changes.after(conversation, id2);
|
|
49105
49199
|
res.end("{}");
|
|
@@ -49141,7 +49235,7 @@ ${target.source}`) ?? 0) > Date.now();
|
|
|
49141
49235
|
this.dialogReads.delete(JSON.stringify(target));
|
|
49142
49236
|
const conductor = body2.event === "PermissionRequest" ? conductorCall(String(body2.tool || "action"), body2.input) : void 0;
|
|
49143
49237
|
const locallyWatched = this.watching.has(JSON.stringify(target)) || this.overview.has(target.server) || this.dispatchLeased(target);
|
|
49144
|
-
const cwd = typeof body2.cwd === "string" &&
|
|
49238
|
+
const cwd = typeof body2.cwd === "string" && path78.isAbsolute(body2.cwd) ? body2.cwd : await trustedDirectory(pane).catch(() => void 0);
|
|
49145
49239
|
let released = false;
|
|
49146
49240
|
const timer = setTimeout(() => {
|
|
49147
49241
|
released = true;
|
|
@@ -49346,7 +49440,7 @@ async function forwardHook(source, target, event, value2, left) {
|
|
|
49346
49440
|
if (result.length > 16384) req.destroy();
|
|
49347
49441
|
});
|
|
49348
49442
|
res.on("end", () => {
|
|
49349
|
-
if (res.statusCode === 200
|
|
49443
|
+
if (res.statusCode === 200) process.stdout.write(hookOutput(event, result));
|
|
49350
49444
|
resolve11();
|
|
49351
49445
|
});
|
|
49352
49446
|
res.on("error", () => resolve11());
|
|
@@ -49370,9 +49464,9 @@ init_protocol();
|
|
|
49370
49464
|
init_claude_accounts();
|
|
49371
49465
|
init_codex_binary();
|
|
49372
49466
|
import { spawn as spawn10 } from "node:child_process";
|
|
49373
|
-
import { readdir as readdir15, readFile as
|
|
49467
|
+
import { readdir as readdir15, readFile as readFile41, stat as stat20 } from "node:fs/promises";
|
|
49374
49468
|
import { homedir as homedir17 } from "node:os";
|
|
49375
|
-
import
|
|
49469
|
+
import path79 from "node:path";
|
|
49376
49470
|
function readCodexModels(executable2 = codexExecutable()) {
|
|
49377
49471
|
return new Promise((resolve11) => {
|
|
49378
49472
|
const child = spawn10(executable2, ["app-server"], { cwd: homedir17(), stdio: ["pipe", "pipe", "ignore"] });
|
|
@@ -49451,12 +49545,12 @@ var CLAUDE_MENU = [
|
|
|
49451
49545
|
{ id: "claude-fable-5-1[1m]", name: "Fable 5.1 (1M context)", description: "Fable 5.1 with a 1M context window." }
|
|
49452
49546
|
];
|
|
49453
49547
|
async function readClaudeCatalog(configDir = claudeConfigDir(), installed) {
|
|
49454
|
-
const directory =
|
|
49548
|
+
const directory = path79.join(configDir, "cache", "model-catalog");
|
|
49455
49549
|
let newest2;
|
|
49456
49550
|
try {
|
|
49457
49551
|
for (const name of await readdir15(directory)) {
|
|
49458
49552
|
if (!name.endsWith("-cc.json")) continue;
|
|
49459
|
-
const file3 =
|
|
49553
|
+
const file3 = path79.join(directory, name), at = (await stat20(file3)).mtimeMs;
|
|
49460
49554
|
if (!newest2 || at > newest2.at) newest2 = { file: file3, at };
|
|
49461
49555
|
}
|
|
49462
49556
|
} catch {
|
|
@@ -49465,7 +49559,7 @@ async function readClaudeCatalog(configDir = claudeConfigDir(), installed) {
|
|
|
49465
49559
|
if (!newest2) return [];
|
|
49466
49560
|
let parsed;
|
|
49467
49561
|
try {
|
|
49468
|
-
parsed = JSON.parse(await
|
|
49562
|
+
parsed = JSON.parse(await readFile41(newest2.file, "utf8"));
|
|
49469
49563
|
} catch {
|
|
49470
49564
|
return [];
|
|
49471
49565
|
}
|
|
@@ -49537,7 +49631,7 @@ async function readClaudeModels(configDir, installed) {
|
|
|
49537
49631
|
const live = await readClaudeCatalog(configDir, version3).catch(() => []);
|
|
49538
49632
|
return live.length ? live : CLAUDE_MENU.map((model) => ({ ...model }));
|
|
49539
49633
|
}
|
|
49540
|
-
async function readOpenCodeModels(executable2 = "opencode", configDir =
|
|
49634
|
+
async function readOpenCodeModels(executable2 = "opencode", configDir = path79.join(homedir17(), ".config/opencode")) {
|
|
49541
49635
|
const listed2 = await new Promise((resolve11) => {
|
|
49542
49636
|
const child = spawn10(executable2, ["models"], { cwd: homedir17(), stdio: ["ignore", "pipe", "ignore"] });
|
|
49543
49637
|
let out = "", done = false;
|
|
@@ -49564,7 +49658,7 @@ async function readOpenCodeModels(executable2 = "opencode", configDir = path78.j
|
|
|
49564
49658
|
let configured;
|
|
49565
49659
|
for (const file3 of ["opencode.json", "opencode.jsonc"]) {
|
|
49566
49660
|
try {
|
|
49567
|
-
const text4 = await
|
|
49661
|
+
const text4 = await readFile41(path79.join(configDir, file3), "utf8");
|
|
49568
49662
|
const model = /"model"\s*:\s*"([^"]+)"/.exec(text4)?.[1];
|
|
49569
49663
|
if (model) {
|
|
49570
49664
|
configured = model.slice(0, 200);
|
|
@@ -50303,8 +50397,8 @@ init_transcripts();
|
|
|
50303
50397
|
|
|
50304
50398
|
// src/bridge/uploads.ts
|
|
50305
50399
|
init_protocol();
|
|
50306
|
-
import { mkdir as mkdir21, readdir as readdir16, lstat as lstat26, realpath as realpath13, readFile as
|
|
50307
|
-
import
|
|
50400
|
+
import { mkdir as mkdir21, readdir as readdir16, lstat as lstat26, realpath as realpath13, readFile as readFile42, stat as stat22, unlink as unlink8, writeFile as writeFile7 } from "node:fs/promises";
|
|
50401
|
+
import path80 from "node:path";
|
|
50308
50402
|
import { randomUUID as randomUUID19 } from "node:crypto";
|
|
50309
50403
|
function imageBytes(bytes) {
|
|
50310
50404
|
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";
|
|
@@ -50317,24 +50411,24 @@ async function saveUpload(session, name, bytes) {
|
|
|
50317
50411
|
let saved = "";
|
|
50318
50412
|
const task = uploadQueue.catch(() => {
|
|
50319
50413
|
}).then(async () => {
|
|
50320
|
-
const root =
|
|
50414
|
+
const root = path80.join(bridgeRoot(), "uploads");
|
|
50321
50415
|
await mkdir21(root, { recursive: true, mode: 448 });
|
|
50322
50416
|
let used = 0;
|
|
50323
50417
|
const directories = await readdir16(root, { withFileTypes: true });
|
|
50324
50418
|
for (const dir of directories) {
|
|
50325
50419
|
if (!dir.isDirectory()) continue;
|
|
50326
|
-
const folder2 =
|
|
50420
|
+
const folder2 = path80.join(root, dir.name);
|
|
50327
50421
|
for (const entry2 of await readdir16(folder2, { withFileTypes: true })) {
|
|
50328
50422
|
if (!entry2.isFile()) continue;
|
|
50329
|
-
const file3 =
|
|
50423
|
+
const file3 = path80.join(folder2, entry2.name), metadata = await lstat26(file3);
|
|
50330
50424
|
if (Date.now() - metadata.mtimeMs > 14 * 864e5) await unlink8(file3);
|
|
50331
50425
|
else used += metadata.size;
|
|
50332
50426
|
}
|
|
50333
50427
|
}
|
|
50334
50428
|
if (used + bytes.length > 268435456) throw new BridgeError(413, "Phren's image storage is full. Remove older uploads on the computer.");
|
|
50335
|
-
const folder =
|
|
50429
|
+
const folder = path80.join(root, session);
|
|
50336
50430
|
await mkdir21(folder, { recursive: true, mode: 448 });
|
|
50337
|
-
saved =
|
|
50431
|
+
saved = path80.join(folder, `${randomUUID19()}-${name}`);
|
|
50338
50432
|
await writeFile7(saved, bytes, { flag: "wx", mode: 384 });
|
|
50339
50433
|
});
|
|
50340
50434
|
uploadQueue = task;
|
|
@@ -50342,36 +50436,36 @@ async function saveUpload(session, name, bytes) {
|
|
|
50342
50436
|
return saved;
|
|
50343
50437
|
}
|
|
50344
50438
|
async function listUploads(session) {
|
|
50345
|
-
const folder =
|
|
50439
|
+
const folder = path80.join(bridgeRoot(), "uploads", session);
|
|
50346
50440
|
const entries2 = await readdir16(folder, { withFileTypes: true }).catch(() => []);
|
|
50347
50441
|
const files = [];
|
|
50348
50442
|
for (const entry2 of entries2) {
|
|
50349
50443
|
if (!entry2.isFile()) continue;
|
|
50350
|
-
const file3 =
|
|
50444
|
+
const file3 = path80.join(folder, entry2.name), metadata = await stat22(file3);
|
|
50351
50445
|
files.push({ name: entry2.name.replace(/^[0-9a-f-]{36}-/, ""), path: file3, size: metadata.size, modified: metadata.mtime.toISOString() });
|
|
50352
50446
|
}
|
|
50353
50447
|
return files.sort((a, b) => b.modified.localeCompare(a.modified)).slice(0, 200);
|
|
50354
50448
|
}
|
|
50355
50449
|
async function uploadImage(requested) {
|
|
50356
50450
|
const missing = new BridgeError(404, "This image is not one of the phone's uploads.");
|
|
50357
|
-
if (!requested || requested.length > 4096 || !
|
|
50358
|
-
const root = await realpath13(
|
|
50451
|
+
if (!requested || requested.length > 4096 || !path80.isAbsolute(requested)) throw missing;
|
|
50452
|
+
const root = await realpath13(path80.join(bridgeRoot(), "uploads")).catch(() => void 0);
|
|
50359
50453
|
const file3 = await realpath13(requested).catch(() => void 0);
|
|
50360
|
-
if (!root || !file3 || !file3.startsWith(root +
|
|
50454
|
+
if (!root || !file3 || !file3.startsWith(root + path80.sep)) throw missing;
|
|
50361
50455
|
const metadata = await stat22(file3);
|
|
50362
50456
|
if (!metadata.isFile()) throw missing;
|
|
50363
50457
|
if (metadata.size > 8388608) throw new BridgeError(413, "This image is too large.");
|
|
50364
|
-
const bytes = await
|
|
50458
|
+
const bytes = await readFile42(file3);
|
|
50365
50459
|
if (bytes.length > 8388608) throw new BridgeError(413, "This image is too large.");
|
|
50366
50460
|
if (!imageBytes(bytes)) throw missing;
|
|
50367
50461
|
return bytes;
|
|
50368
50462
|
}
|
|
50369
50463
|
async function sessionUpload(session, requested) {
|
|
50370
50464
|
const refused = new BridgeError(400, "An attachment is not one of this conversation's uploads. Attach it again.");
|
|
50371
|
-
if (!requested || requested.length > 4096 || !
|
|
50372
|
-
const folder = await realpath13(
|
|
50465
|
+
if (!requested || requested.length > 4096 || !path80.isAbsolute(requested)) throw refused;
|
|
50466
|
+
const folder = await realpath13(path80.join(bridgeRoot(), "uploads", session)).catch(() => void 0);
|
|
50373
50467
|
const file3 = await realpath13(requested).catch(() => void 0);
|
|
50374
|
-
if (!folder || !file3 || !file3.startsWith(folder +
|
|
50468
|
+
if (!folder || !file3 || !file3.startsWith(folder + path80.sep)) throw refused;
|
|
50375
50469
|
if (!(await stat22(file3)).isFile()) throw refused;
|
|
50376
50470
|
return file3;
|
|
50377
50471
|
}
|
|
@@ -50432,7 +50526,7 @@ function herdrWorktreeWorkers(s) {
|
|
|
50432
50526
|
const workers = [];
|
|
50433
50527
|
for (const pane of objects(s.panes)) {
|
|
50434
50528
|
const cwd = pane.foreground_cwd || pane.cwd;
|
|
50435
|
-
if (typeof pane.agent !== "string" || typeof cwd !== "string" || !
|
|
50529
|
+
if (typeof pane.agent !== "string" || typeof cwd !== "string" || !path81.isAbsolute(cwd)) continue;
|
|
50436
50530
|
const name = paneAgentName(s, pane);
|
|
50437
50531
|
workers.push({
|
|
50438
50532
|
cwd,
|
|
@@ -50844,8 +50938,8 @@ init_protocol();
|
|
|
50844
50938
|
init_transcripts();
|
|
50845
50939
|
init_metrics();
|
|
50846
50940
|
import { randomUUID as randomUUID20 } from "node:crypto";
|
|
50847
|
-
import { appendFile as appendFile2, lstat as lstat27, mkdir as mkdir22, readdir as readdir17, readFile as
|
|
50848
|
-
import
|
|
50941
|
+
import { appendFile as appendFile2, lstat as lstat27, mkdir as mkdir22, readdir as readdir17, readFile as readFile43, realpath as realpath14, rename as rename7, rm as rm10, writeFile as writeFile8 } from "node:fs/promises";
|
|
50942
|
+
import path85 from "node:path";
|
|
50849
50943
|
var fanoutMessageSchema = external_exports.object({
|
|
50850
50944
|
target: targetSchema,
|
|
50851
50945
|
child: external_exports.string().regex(/^[a-f0-9]{32}$/),
|
|
@@ -50884,12 +50978,12 @@ var FanoutMessages = class {
|
|
|
50884
50978
|
if (!root) return [];
|
|
50885
50979
|
const jobs = [];
|
|
50886
50980
|
for (const name of (await readdir17(root)).slice(0, 1024)) {
|
|
50887
|
-
const directory =
|
|
50981
|
+
const directory = path85.join(root, name);
|
|
50888
50982
|
try {
|
|
50889
50983
|
if (!(await lstat27(directory)).isDirectory() || await realpath14(directory) !== directory) continue;
|
|
50890
|
-
const file3 =
|
|
50984
|
+
const file3 = path85.join(directory, "manifest.json"), info = await lstat27(file3);
|
|
50891
50985
|
if (!info.isFile() || info.isSymbolicLink() || info.size > 65536) continue;
|
|
50892
|
-
const manifest = manifestSchema.parse(JSON.parse(await
|
|
50986
|
+
const manifest = manifestSchema.parse(JSON.parse(await readFile43(file3, "utf8")));
|
|
50893
50987
|
if (manifest.id === name) jobs.push({ directory, manifest });
|
|
50894
50988
|
} catch {
|
|
50895
50989
|
}
|
|
@@ -50914,7 +51008,7 @@ var FanoutMessages = class {
|
|
|
50914
51008
|
const message = { id: randomUUID20(), text: data.text, status: "queued", createdAt: (/* @__PURE__ */ new Date()).toISOString() };
|
|
50915
51009
|
const pending = (await this.records(job)).filter((row) => row.message.status === "queued");
|
|
50916
51010
|
if (pending.length >= 32) throw new BridgeError(429, "This worker already has 32 queued messages.");
|
|
50917
|
-
const file3 =
|
|
51011
|
+
const file3 = path85.join(directory, `${message.createdAt.replace(/[:.]/g, "-")}-${message.id}.queued.json`);
|
|
50918
51012
|
await atomic(file3, JSON.stringify(message));
|
|
50919
51013
|
await this.drain(job);
|
|
50920
51014
|
const fresh = (await this.records(job)).find((row) => row.message.id === message.id)?.message;
|
|
@@ -50935,13 +51029,13 @@ var FanoutMessages = class {
|
|
|
50935
51029
|
return { messages: (await this.records(job)).map((row) => row.message) };
|
|
50936
51030
|
}
|
|
50937
51031
|
async messageDirectory(job) {
|
|
50938
|
-
const directory =
|
|
51032
|
+
const directory = path85.join(job.directory, "messages");
|
|
50939
51033
|
await mkdir22(directory, { recursive: true, mode: 448 });
|
|
50940
51034
|
if (await realpath14(directory) !== directory) throw new BridgeError(400, "Invalid worker message directory.");
|
|
50941
51035
|
return directory;
|
|
50942
51036
|
}
|
|
50943
51037
|
async records(job) {
|
|
50944
|
-
const directory =
|
|
51038
|
+
const directory = path85.join(job.directory, "messages");
|
|
50945
51039
|
const info = await lstat27(directory).catch(() => void 0);
|
|
50946
51040
|
if (!info) return [];
|
|
50947
51041
|
if (!info.isDirectory() || info.isSymbolicLink() || await realpath14(directory) !== directory) {
|
|
@@ -50950,10 +51044,10 @@ var FanoutMessages = class {
|
|
|
50950
51044
|
const rows = [];
|
|
50951
51045
|
for (const name of (await readdir17(directory)).sort().slice(-512)) {
|
|
50952
51046
|
if (!/^[0-9TZ-]+-[a-f0-9-]+\.(queued|sent)\.json$/.test(name)) continue;
|
|
50953
|
-
const file3 =
|
|
51047
|
+
const file3 = path85.join(directory, name), info2 = await lstat27(file3);
|
|
50954
51048
|
if (!info2.isFile() || info2.isSymbolicLink() || info2.size > 262144) continue;
|
|
50955
51049
|
try {
|
|
50956
|
-
rows.push({ file: file3, message: receiptSchema2.parse(JSON.parse(await
|
|
51050
|
+
rows.push({ file: file3, message: receiptSchema2.parse(JSON.parse(await readFile43(file3, "utf8"))) });
|
|
50957
51051
|
} catch {
|
|
50958
51052
|
}
|
|
50959
51053
|
}
|
|
@@ -50973,7 +51067,7 @@ var FanoutMessages = class {
|
|
|
50973
51067
|
}
|
|
50974
51068
|
}
|
|
50975
51069
|
async drain(job) {
|
|
50976
|
-
const lock =
|
|
51070
|
+
const lock = path85.join(job.directory, "message-lock");
|
|
50977
51071
|
try {
|
|
50978
51072
|
await mkdir22(lock, { mode: 448 });
|
|
50979
51073
|
} catch {
|
|
@@ -50991,21 +51085,21 @@ var FanoutMessages = class {
|
|
|
50991
51085
|
pending = next;
|
|
50992
51086
|
if (!(await lstat27(fresh.manifest.worktree)).isDirectory()) throw new BridgeError(409, "The worker's original worktree is unavailable.");
|
|
50993
51087
|
for (const name of [fresh.manifest.eventLog, "events.jsonl", "stderr.log", "final.txt", "exit.txt", "blocked.json", "prompt.txt"]) {
|
|
50994
|
-
const info = await lstat27(
|
|
51088
|
+
const info = await lstat27(path85.join(fresh.directory, name)).catch(() => void 0);
|
|
50995
51089
|
if (info && (!info.isFile() || info.isSymbolicLink())) throw new BridgeError(400, "Invalid worker output file.");
|
|
50996
51090
|
}
|
|
50997
|
-
const round =
|
|
51091
|
+
const round = path85.join(fresh.directory, "rounds");
|
|
50998
51092
|
await mkdir22(round, { recursive: true, mode: 448 });
|
|
50999
51093
|
if (await realpath14(round) !== round) throw new BridgeError(400, "Invalid worker round directory.");
|
|
51000
|
-
const roundDir =
|
|
51094
|
+
const roundDir = path85.join(round, next.message.id);
|
|
51001
51095
|
await mkdir22(roundDir, { mode: 448 });
|
|
51002
|
-
await writeFile8(
|
|
51096
|
+
await writeFile8(path85.join(roundDir, "prompt.txt"), next.message.text, { mode: 384 });
|
|
51003
51097
|
for (const name of ["stderr.log", "final.txt", "exit.txt", "blocked.json", "prompt.txt"]) {
|
|
51004
|
-
await rename7(
|
|
51098
|
+
await rename7(path85.join(fresh.directory, name), path85.join(roundDir, `previous-${name}`)).catch((error62) => {
|
|
51005
51099
|
if (error62.code !== "ENOENT") throw error62;
|
|
51006
51100
|
});
|
|
51007
51101
|
}
|
|
51008
|
-
await writeFile8(
|
|
51102
|
+
await writeFile8(path85.join(fresh.directory, "prompt.txt"), next.message.text, { mode: 384 });
|
|
51009
51103
|
const sentFile = next.file.replace(/\.queued\.json$/, ".sent.json");
|
|
51010
51104
|
const message = { ...next.message, status: "running" };
|
|
51011
51105
|
await atomic(next.file, JSON.stringify(message));
|
|
@@ -51021,9 +51115,9 @@ var FanoutMessages = class {
|
|
|
51021
51115
|
finishedAt: void 0,
|
|
51022
51116
|
exitCode: void 0
|
|
51023
51117
|
};
|
|
51024
|
-
await atomic(
|
|
51118
|
+
await atomic(path85.join(fresh.directory, "manifest.json"), JSON.stringify(manifest));
|
|
51025
51119
|
started = manifest;
|
|
51026
|
-
await appendFile2(
|
|
51120
|
+
await appendFile2(path85.join(fresh.directory, manifest.eventLog), JSON.stringify({
|
|
51027
51121
|
type: "phren/fanout-message",
|
|
51028
51122
|
timestamp: now,
|
|
51029
51123
|
id: message.id,
|
|
@@ -51047,7 +51141,7 @@ var FanoutMessages = class {
|
|
|
51047
51141
|
await atomic(sentFile, JSON.stringify({ ...message, status: code === 0 ? "completed" : "failed" }));
|
|
51048
51142
|
}).catch(async () => {
|
|
51049
51143
|
await atomic(sentFile, JSON.stringify({ ...message, status: "failed" }));
|
|
51050
|
-
await atomic(
|
|
51144
|
+
await atomic(path85.join(fresh.directory, "manifest.json"), JSON.stringify({ ...manifest, status: "failed", finishedAt: (/* @__PURE__ */ new Date()).toISOString() }));
|
|
51051
51145
|
}).finally(async () => {
|
|
51052
51146
|
await rm10(lock, { recursive: true, force: true });
|
|
51053
51147
|
}).catch(() => {
|
|
@@ -51056,7 +51150,7 @@ var FanoutMessages = class {
|
|
|
51056
51150
|
if (!pending) throw error62;
|
|
51057
51151
|
await atomic(pending.file, JSON.stringify({ ...pending.message, status: "failed" }));
|
|
51058
51152
|
if (pending.file.endsWith(".queued.json")) await rename7(pending.file, pending.file.replace(/\.queued\.json$/, ".sent.json"));
|
|
51059
|
-
if (started) await atomic(
|
|
51153
|
+
if (started) await atomic(path85.join(job.directory, "manifest.json"), JSON.stringify({
|
|
51060
51154
|
...started,
|
|
51061
51155
|
status: "failed",
|
|
51062
51156
|
finishedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
@@ -51070,11 +51164,11 @@ var FanoutMessages = class {
|
|
|
51070
51164
|
// src/bridge/server.ts
|
|
51071
51165
|
init_wrapper();
|
|
51072
51166
|
import { randomUUID as randomUUID26 } from "node:crypto";
|
|
51073
|
-
import { chmod as chmod6, lstat as lstat32, mkdir as mkdir30, readFile as
|
|
51167
|
+
import { chmod as chmod6, lstat as lstat32, mkdir as mkdir30, readFile as readFile52, rm as rm15, unlink as unlink10, writeFile as writeFile12 } from "node:fs/promises";
|
|
51074
51168
|
import { readFileSync as readFileSync37 } from "node:fs";
|
|
51075
51169
|
import { createServer as createServer3 } from "node:http";
|
|
51076
51170
|
import { cpus as cpus2, hostname as hostname12, loadavg as loadavg2 } from "node:os";
|
|
51077
|
-
import
|
|
51171
|
+
import path114 from "node:path";
|
|
51078
51172
|
|
|
51079
51173
|
// src/bridge/speech-live.ts
|
|
51080
51174
|
init_wrapper();
|
|
@@ -51537,8 +51631,8 @@ function relayLiveSpeech(client, query, options = {}) {
|
|
|
51537
51631
|
params.set("auto_mode", "true");
|
|
51538
51632
|
params.set("inactivity_timeout", "180");
|
|
51539
51633
|
}
|
|
51540
|
-
const
|
|
51541
|
-
const socket = connect4(`${origin}${
|
|
51634
|
+
const path116 = endpoint === "dialogue" ? "/v1/text-to-dialogue/stream-input" : `/v1/text-to-speech/${encodeURIComponent(voice)}/stream-input`;
|
|
51635
|
+
const socket = connect4(`${origin}${path116}?${params}`, key3);
|
|
51542
51636
|
upstream = socket;
|
|
51543
51637
|
const current2 = () => upstream === socket && !closed;
|
|
51544
51638
|
let voiced = false, firstAudio;
|
|
@@ -51835,8 +51929,8 @@ function relayTranscription(client, query, options = {}) {
|
|
|
51835
51929
|
|
|
51836
51930
|
// src/bridge/activity.ts
|
|
51837
51931
|
init_protocol();
|
|
51838
|
-
import { appendFile as appendFile3, mkdir as mkdir23, readFile as
|
|
51839
|
-
import
|
|
51932
|
+
import { appendFile as appendFile3, mkdir as mkdir23, readFile as readFile44, rename as rename8, stat as stat23 } from "node:fs/promises";
|
|
51933
|
+
import path86 from "node:path";
|
|
51840
51934
|
var ActivityJournal = class {
|
|
51841
51935
|
pending = Promise.resolve();
|
|
51842
51936
|
previous = /* @__PURE__ */ new Map();
|
|
@@ -51863,7 +51957,7 @@ var ActivityJournal = class {
|
|
|
51863
51957
|
});
|
|
51864
51958
|
}
|
|
51865
51959
|
if (!changes.length) return;
|
|
51866
|
-
const root = bridgeRoot(), file3 =
|
|
51960
|
+
const root = bridgeRoot(), file3 = path86.join(root, "activity.jsonl");
|
|
51867
51961
|
await mkdir23(root, { recursive: true, mode: 448 });
|
|
51868
51962
|
if ((await stat23(file3).catch(() => null))?.size && (await stat23(file3)).size > 2097152) await rename8(file3, file3 + ".previous");
|
|
51869
51963
|
await appendFile3(file3, changes.map((row) => JSON.stringify(row)).join("\n") + "\n", { mode: 384 });
|
|
@@ -51872,7 +51966,7 @@ var ActivityJournal = class {
|
|
|
51872
51966
|
return this.pending;
|
|
51873
51967
|
}
|
|
51874
51968
|
async recent() {
|
|
51875
|
-
const text4 = await
|
|
51969
|
+
const text4 = await readFile44(path86.join(bridgeRoot(), "activity.jsonl"), "utf8").catch(() => "");
|
|
51876
51970
|
return text4.trim().split("\n").slice(-500).flatMap((line) => {
|
|
51877
51971
|
try {
|
|
51878
51972
|
return [JSON.parse(line)];
|
|
@@ -51891,7 +51985,7 @@ init_changes();
|
|
|
51891
51985
|
init_store_registry();
|
|
51892
51986
|
import { rm as rm11 } from "node:fs/promises";
|
|
51893
51987
|
import * as fs27 from "node:fs";
|
|
51894
|
-
import * as
|
|
51988
|
+
import * as path88 from "node:path";
|
|
51895
51989
|
init_zod();
|
|
51896
51990
|
init_shared();
|
|
51897
51991
|
|
|
@@ -51899,7 +51993,7 @@ init_shared();
|
|
|
51899
51993
|
import { execFileSync as execFileSync5 } from "node:child_process";
|
|
51900
51994
|
import * as fs26 from "node:fs";
|
|
51901
51995
|
import { homedir as homedir18 } from "node:os";
|
|
51902
|
-
import * as
|
|
51996
|
+
import * as path87 from "node:path";
|
|
51903
51997
|
import { fileURLToPath as fileURLToPath5, pathToFileURL } from "node:url";
|
|
51904
51998
|
var CODE_PACKAGE_HINT = "phren code needs @phren/code: run phren modules enable code";
|
|
51905
51999
|
var loaded;
|
|
@@ -51908,13 +52002,13 @@ function loadedFrom() {
|
|
|
51908
52002
|
return resolvedFrom;
|
|
51909
52003
|
}
|
|
51910
52004
|
function bridgeRoot2() {
|
|
51911
|
-
return process.env.PHREN_BRIDGE_HOME ||
|
|
52005
|
+
return process.env.PHREN_BRIDGE_HOME || path87.join(homedir18(), ".local/share/phren/bridge");
|
|
51912
52006
|
}
|
|
51913
|
-
var EXTRA_PATH = [
|
|
52007
|
+
var EXTRA_PATH = [path87.join(homedir18(), ".local/share/mise/shims"), "/opt/homebrew/bin"];
|
|
51914
52008
|
function npmPath() {
|
|
51915
|
-
const entries2 = (process.env.PATH ?? "").split(
|
|
52009
|
+
const entries2 = (process.env.PATH ?? "").split(path87.delimiter).filter(Boolean);
|
|
51916
52010
|
for (const entry2 of EXTRA_PATH) if (!entries2.includes(entry2) && fs26.existsSync(entry2)) entries2.push(entry2);
|
|
51917
|
-
return entries2.join(
|
|
52011
|
+
return entries2.join(path87.delimiter);
|
|
51918
52012
|
}
|
|
51919
52013
|
function npm(args, options) {
|
|
51920
52014
|
const env = { ...process.env, PATH: npmPath() };
|
|
@@ -51922,11 +52016,11 @@ function npm(args, options) {
|
|
|
51922
52016
|
return String(execFileSync5("npm.cmd", args.map((arg) => `"${arg}"`), { ...options, env, shell: true }) ?? "");
|
|
51923
52017
|
}
|
|
51924
52018
|
function packageEntry(directory) {
|
|
51925
|
-
const manifest = JSON.parse(fs26.readFileSync(
|
|
52019
|
+
const manifest = JSON.parse(fs26.readFileSync(path87.join(directory, "package.json"), "utf8"));
|
|
51926
52020
|
const exported = typeof manifest.exports === "object" && manifest.exports !== null && "." in manifest.exports ? manifest.exports["."] : manifest.exports;
|
|
51927
52021
|
const nested = typeof exported === "object" && exported !== null ? exported.default ?? exported.import : exported;
|
|
51928
52022
|
for (const candidate of [nested, manifest.module, manifest.main, "index.js", "index.mjs"]) {
|
|
51929
|
-
if (typeof candidate === "string") return
|
|
52023
|
+
if (typeof candidate === "string") return path87.join(directory, candidate);
|
|
51930
52024
|
}
|
|
51931
52025
|
throw new Error(`@phren/code has no entry point in ${directory}.`);
|
|
51932
52026
|
}
|
|
@@ -51936,7 +52030,7 @@ async function importDirectory(directory) {
|
|
|
51936
52030
|
function globalPackageDirectory() {
|
|
51937
52031
|
try {
|
|
51938
52032
|
const root = npm(["root", "-g"], { encoding: "utf8", timeout: 1e4 }).trim();
|
|
51939
|
-
return root ?
|
|
52033
|
+
return root ? path87.join(root, "@phren", "code") : void 0;
|
|
51940
52034
|
} catch {
|
|
51941
52035
|
return void 0;
|
|
51942
52036
|
}
|
|
@@ -51945,13 +52039,13 @@ async function loadCodePackage(store) {
|
|
|
51945
52039
|
if (loaded) return loaded;
|
|
51946
52040
|
const candidates = [];
|
|
51947
52041
|
if (process.env.PHREN_CODE_PACKAGE) candidates.push(process.env.PHREN_CODE_PACKAGE);
|
|
51948
|
-
candidates.push(
|
|
52042
|
+
candidates.push(path87.join(bridgeRoot2(), "node_modules", "@phren", "code"));
|
|
51949
52043
|
const root = store || process.env.PHREN_PATH;
|
|
51950
|
-
if (root) candidates.push(
|
|
52044
|
+
if (root) candidates.push(path87.join(root, ".runtime", "packages", "node_modules", "@phren", "code"));
|
|
51951
52045
|
const workspace = workspaceCodeDirectory();
|
|
51952
52046
|
if (workspace && builtEntryExists(workspace)) candidates.push(workspace);
|
|
51953
52047
|
for (const directory of candidates) {
|
|
51954
|
-
if (!fs26.existsSync(
|
|
52048
|
+
if (!fs26.existsSync(path87.join(directory, "package.json"))) continue;
|
|
51955
52049
|
try {
|
|
51956
52050
|
loaded = await importDirectory(directory);
|
|
51957
52051
|
resolvedFrom = directory;
|
|
@@ -51967,7 +52061,7 @@ async function loadCodePackage(store) {
|
|
|
51967
52061
|
if (error62.code !== "ERR_MODULE_NOT_FOUND") throw error62;
|
|
51968
52062
|
}
|
|
51969
52063
|
const global = globalPackageDirectory();
|
|
51970
|
-
if (global && fs26.existsSync(
|
|
52064
|
+
if (global && fs26.existsSync(path87.join(global, "package.json"))) {
|
|
51971
52065
|
try {
|
|
51972
52066
|
loaded = await importDirectory(global);
|
|
51973
52067
|
resolvedFrom = global;
|
|
@@ -51978,11 +52072,11 @@ async function loadCodePackage(store) {
|
|
|
51978
52072
|
return void 0;
|
|
51979
52073
|
}
|
|
51980
52074
|
function workspaceCodeDirectory() {
|
|
51981
|
-
let directory =
|
|
52075
|
+
let directory = path87.dirname(fileURLToPath5(import.meta.url));
|
|
51982
52076
|
for (let depth = 0; depth < 8; depth++) {
|
|
51983
|
-
const candidate =
|
|
51984
|
-
if (fs26.existsSync(
|
|
51985
|
-
const parent =
|
|
52077
|
+
const candidate = path87.join(directory, "packages", "code");
|
|
52078
|
+
if (fs26.existsSync(path87.join(candidate, "package.json"))) return candidate;
|
|
52079
|
+
const parent = path87.dirname(directory);
|
|
51986
52080
|
if (parent === directory) break;
|
|
51987
52081
|
directory = parent;
|
|
51988
52082
|
}
|
|
@@ -51997,7 +52091,7 @@ function builtEntryExists(directory) {
|
|
|
51997
52091
|
}
|
|
51998
52092
|
function codePackageHint(store) {
|
|
51999
52093
|
const root = store || process.env.PHREN_PATH;
|
|
52000
|
-
const linked = root &&
|
|
52094
|
+
const linked = root && path87.join(root, ".runtime", "packages", "node_modules", "@phren", "code");
|
|
52001
52095
|
const workspace = workspaceCodeDirectory();
|
|
52002
52096
|
let workspaceLink;
|
|
52003
52097
|
try {
|
|
@@ -52005,7 +52099,7 @@ function codePackageHint(store) {
|
|
|
52005
52099
|
} catch {
|
|
52006
52100
|
}
|
|
52007
52101
|
for (const directory of [workspace, workspaceLink]) {
|
|
52008
|
-
if (!directory || !fs26.existsSync(
|
|
52102
|
+
if (!directory || !fs26.existsSync(path87.join(directory, "package.json")) || builtEntryExists(directory)) continue;
|
|
52009
52103
|
return `${CODE_PACKAGE_HINT}. @phren/code at ${directory} has no built entry. From the source checkout root run: pnpm --filter @phren/code build`;
|
|
52010
52104
|
}
|
|
52011
52105
|
return `${CODE_PACKAGE_HINT}. For a source checkout, from its root run pnpm --filter @phren/code build, then node packages/cli/dist/index.js modules enable code and restart the Hook.`;
|
|
@@ -52041,7 +52135,7 @@ var projectSchema = external_exports.string().min(1).max(100).refine((value2) =>
|
|
|
52041
52135
|
var querySchema = external_exports.string().max(500);
|
|
52042
52136
|
var symbolSchema = external_exports.string().min(1).max(4600);
|
|
52043
52137
|
var pathSchema = external_exports.string().min(1).max(4096).refine((value2) => !value2.includes("\0") && !value2.split("/").includes(".."), "Choose a valid file path.");
|
|
52044
|
-
var relativePathSchema = pathSchema.refine((value2) => !
|
|
52138
|
+
var relativePathSchema = pathSchema.refine((value2) => !path88.isAbsolute(value2) && !path88.win32.isAbsolute(value2) && !value2.includes("\\") && !value2.split("/").some((part) => part === "." || part === ""));
|
|
52045
52139
|
var optionalPath = (value2) => value2 ? relativePathSchema.parse(value2) : void 0;
|
|
52046
52140
|
var offsetSchema = external_exports.coerce.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
|
|
52047
52141
|
var kindSchema = external_exports.enum(KIND_VALUES);
|
|
@@ -52129,9 +52223,9 @@ var CodeRoutes = class {
|
|
|
52129
52223
|
};
|
|
52130
52224
|
const midnight = new Date(now);
|
|
52131
52225
|
midnight.setHours(0, 0, 0, 0);
|
|
52132
|
-
const dir =
|
|
52226
|
+
const dir = path88.join(bridgeRoot(), "changes");
|
|
52133
52227
|
const logs = fs27.existsSync(dir) ? fs27.readdirSync(dir).filter((name) => name.endsWith(".jsonl")) : [];
|
|
52134
|
-
const today = logs.map((name) => ({ file:
|
|
52228
|
+
const today = logs.map((name) => ({ file: path88.join(dir, name), at: fs27.statSync(path88.join(dir, name)).mtimeMs })).filter((entry2) => entry2.at >= midnight.getTime()).sort((a, b) => b.at - a.at);
|
|
52135
52229
|
for (const log2 of today) {
|
|
52136
52230
|
for (const line of fs27.readFileSync(log2.file, "utf8").split("\n")) {
|
|
52137
52231
|
if (!line.trim()) continue;
|
|
@@ -52192,7 +52286,7 @@ var CodeRoutes = class {
|
|
|
52192
52286
|
for (const file3 of untracked) {
|
|
52193
52287
|
let count2 = 0;
|
|
52194
52288
|
try {
|
|
52195
|
-
count2 = fs27.readFileSync(
|
|
52289
|
+
count2 = fs27.readFileSync(path88.join(root, file3), "utf8").split("\n").length;
|
|
52196
52290
|
} catch {
|
|
52197
52291
|
continue;
|
|
52198
52292
|
}
|
|
@@ -52222,7 +52316,7 @@ var CodeRoutes = class {
|
|
|
52222
52316
|
const project = projectSchema.parse(projectValue ?? "");
|
|
52223
52317
|
const { codeDatabasePath } = await requireCodePackage(this.store);
|
|
52224
52318
|
const file3 = codeDatabasePath(this.store, project);
|
|
52225
|
-
await Promise.all([file3, `${file3}-journal`, `${file3}-wal`, `${file3}-shm`].map((
|
|
52319
|
+
await Promise.all([file3, `${file3}-journal`, `${file3}-wal`, `${file3}-shm`].map((path116) => rm11(path116, { force: true })));
|
|
52226
52320
|
return { project, disabled: true };
|
|
52227
52321
|
}
|
|
52228
52322
|
async reindex(projectValue) {
|
|
@@ -52256,7 +52350,7 @@ var CodeRoutes = class {
|
|
|
52256
52350
|
} catch {
|
|
52257
52351
|
throw new BridgeError(400, "Choose valid paths.");
|
|
52258
52352
|
}
|
|
52259
|
-
const paths = external_exports.array(pathSchema.refine((value2) => !
|
|
52353
|
+
const paths = external_exports.array(pathSchema.refine((value2) => !path88.isAbsolute(value2) && !path88.win32.isAbsolute(value2) && !value2.split(/[\\/]/).includes(".."))).min(1).max(200).parse(raw);
|
|
52260
52354
|
const result = await (await requireCodePackage(this.store)).outlineSummary(this.store, project, [...new Set(paths)]);
|
|
52261
52355
|
if (!result.available) throw noIndex(project);
|
|
52262
52356
|
return { project, entries: result.value };
|
|
@@ -52331,7 +52425,7 @@ var CodeReindexer = class {
|
|
|
52331
52425
|
const { codeDatabasePath, resolveRepoRoot } = await requireCodePackage(this.store);
|
|
52332
52426
|
const result = [];
|
|
52333
52427
|
for (const directory of getProjectDirs(this.store)) {
|
|
52334
|
-
const project =
|
|
52428
|
+
const project = path88.basename(directory);
|
|
52335
52429
|
if (!fs27.existsSync(codeDatabasePath(this.store, project))) continue;
|
|
52336
52430
|
try {
|
|
52337
52431
|
result.push({ project, root: fs27.realpathSync(resolveRepoRoot(this.store, project)) });
|
|
@@ -52373,13 +52467,13 @@ var CodeReindexer = class {
|
|
|
52373
52467
|
};
|
|
52374
52468
|
function readHead(root) {
|
|
52375
52469
|
try {
|
|
52376
|
-
const dotGit =
|
|
52470
|
+
const dotGit = path88.join(root, ".git");
|
|
52377
52471
|
const gitDirectory2 = fs27.statSync(dotGit).isDirectory() ? dotGit : (() => {
|
|
52378
52472
|
const match = /^gitdir:\s*(.+)$/m.exec(fs27.readFileSync(dotGit, "utf8"));
|
|
52379
|
-
return match ?
|
|
52473
|
+
return match ? path88.resolve(root, match[1]) : void 0;
|
|
52380
52474
|
})();
|
|
52381
52475
|
if (!gitDirectory2) return void 0;
|
|
52382
|
-
return fs27.readFileSync(
|
|
52476
|
+
return fs27.readFileSync(path88.join(gitDirectory2, "HEAD"), "utf8").trim();
|
|
52383
52477
|
} catch {
|
|
52384
52478
|
return void 0;
|
|
52385
52479
|
}
|
|
@@ -52528,8 +52622,8 @@ init_transcript_index();
|
|
|
52528
52622
|
init_codex_question_reply();
|
|
52529
52623
|
import { execFile as execFile17 } from "node:child_process";
|
|
52530
52624
|
import { createHash as createHash24 } from "node:crypto";
|
|
52531
|
-
import { mkdir as mkdir24, open as open19, stat as stat24, readFile as
|
|
52532
|
-
import
|
|
52625
|
+
import { mkdir as mkdir24, open as open19, stat as stat24, readFile as readFile45, writeFile as writeFile9 } from "node:fs/promises";
|
|
52626
|
+
import path89 from "node:path";
|
|
52533
52627
|
import { promisify as promisify16 } from "node:util";
|
|
52534
52628
|
var exec16 = promisify16(execFile17);
|
|
52535
52629
|
var text3 = external_exports.string().trim().min(1).max(4e3).refine((t) => !/[\x00-\x08\x0b-\x1f\x7f]/.test(t));
|
|
@@ -52756,7 +52850,7 @@ var CodexQuestions = class {
|
|
|
52756
52850
|
}
|
|
52757
52851
|
return Promise.all((pending ?? []).map(async (p) => {
|
|
52758
52852
|
const key3 = createHash24("sha256").update(JSON.stringify([target.source, target.session, p.id])).digest("hex");
|
|
52759
|
-
const submitted = await
|
|
52853
|
+
const submitted = await readFile45(path89.join(bridgeRoot(), "question-replies", key3), "utf8").then((value2) => value2 === "submitted").catch(() => false);
|
|
52760
52854
|
return { toolUseId: p.id, isAsync: true, submitted, questions: asPrompt(p.questions) };
|
|
52761
52855
|
})).then((prompts) => prompts.filter((p) => !p.submitted));
|
|
52762
52856
|
}
|
|
@@ -52789,10 +52883,10 @@ var CodexQuestions = class {
|
|
|
52789
52883
|
] : [];
|
|
52790
52884
|
const pane = await validateTarget(target);
|
|
52791
52885
|
if (await paneIdentity(target.server, pane, true) !== target.session) throw new BridgeError(409, "This pane's conversation changed. Reopen the chat.");
|
|
52792
|
-
const directory =
|
|
52886
|
+
const directory = path89.join(bridgeRoot(), "question-replies");
|
|
52793
52887
|
await mkdir24(directory, { recursive: true, mode: 448 });
|
|
52794
52888
|
const key3 = createHash24("sha256").update(JSON.stringify([target.source, target.session, id2])).digest("hex");
|
|
52795
|
-
const receiptPath =
|
|
52889
|
+
const receiptPath = path89.join(directory, key3);
|
|
52796
52890
|
const receipt = await open19(receiptPath, "wx", 384).catch((error62) => {
|
|
52797
52891
|
if (error62.code === "EEXIST") throw new BridgeError(409, "An answer was already submitted. Check the conversation before answering again.");
|
|
52798
52892
|
throw new BridgeError(503, "Phren could not record this answer. Nothing was sent.");
|
|
@@ -53103,16 +53197,16 @@ var SettingsSwitcher = class {
|
|
|
53103
53197
|
init_home_paths();
|
|
53104
53198
|
init_herdr();
|
|
53105
53199
|
import { execFile as execFile18 } from "node:child_process";
|
|
53106
|
-
import { readdir as readdir18, readFile as
|
|
53200
|
+
import { readdir as readdir18, readFile as readFile46, statfs } from "node:fs/promises";
|
|
53107
53201
|
import { cpus, loadavg, totalmem, uptime } from "node:os";
|
|
53108
|
-
import
|
|
53202
|
+
import path91 from "node:path";
|
|
53109
53203
|
import { promisify as promisify17 } from "node:util";
|
|
53110
53204
|
|
|
53111
53205
|
// src/bridge/job-registry.ts
|
|
53112
53206
|
init_zod();
|
|
53113
53207
|
init_protocol();
|
|
53114
53208
|
import { readFileSync as readFileSync29 } from "node:fs";
|
|
53115
|
-
import
|
|
53209
|
+
import path90 from "node:path";
|
|
53116
53210
|
var paneSchema = external_exports.object({
|
|
53117
53211
|
server: external_exports.string().min(1).max(200),
|
|
53118
53212
|
workspace: external_exports.string().max(200).optional(),
|
|
@@ -53167,7 +53261,7 @@ var CLEANUP_LEASE_MS = 5 * 6e4;
|
|
|
53167
53261
|
var LEADER_START_TOLERANCE_MS = 3e3;
|
|
53168
53262
|
var CLEANUP_RETAIN_MS = 24 * 60 * 6e4;
|
|
53169
53263
|
function commandMatches(job, row) {
|
|
53170
|
-
return
|
|
53264
|
+
return path90.basename(row.command) === path90.basename(job.command) || row.args.includes(job.command);
|
|
53171
53265
|
}
|
|
53172
53266
|
function planCleanup(jobs, rows, live, options = {}) {
|
|
53173
53267
|
const now = options.now ?? Date.now(), leaseMs = options.leaseMs ?? CLEANUP_LEASE_MS, retainMs = options.retainMs ?? CLEANUP_RETAIN_MS;
|
|
@@ -53236,7 +53330,7 @@ function planCleanup(jobs, rows, live, options = {}) {
|
|
|
53236
53330
|
}
|
|
53237
53331
|
return { kill, keep, forget };
|
|
53238
53332
|
}
|
|
53239
|
-
var defaultFile = () =>
|
|
53333
|
+
var defaultFile = () => path90.join(bridgeRoot(), "jobs.json");
|
|
53240
53334
|
var JobRegistry = class {
|
|
53241
53335
|
constructor(file3 = defaultFile(), now = Date.now) {
|
|
53242
53336
|
this.file = file3;
|
|
@@ -53336,7 +53430,7 @@ function parsePs(stats, args) {
|
|
|
53336
53430
|
return rows;
|
|
53337
53431
|
}
|
|
53338
53432
|
function heavyKind(row) {
|
|
53339
|
-
const base =
|
|
53433
|
+
const base = path91.basename(row.command);
|
|
53340
53434
|
const args = row.args;
|
|
53341
53435
|
if (base === "launchd_sim") {
|
|
53342
53436
|
return { kind: "simulator", name: /XCTestDevices|Clone \d+ of /.test(args) ? "Simulator test clone" : "Simulator" };
|
|
@@ -53365,7 +53459,7 @@ function heavyProcesses(rows, owners = /* @__PURE__ */ new Map(), jobs = [], lim
|
|
|
53365
53459
|
}
|
|
53366
53460
|
for (const row of rows) {
|
|
53367
53461
|
const parent = byPid.get(row.ppid);
|
|
53368
|
-
if (kinds.get(row.pid)?.kind === "codex" && parent &&
|
|
53462
|
+
if (kinds.get(row.pid)?.kind === "codex" && parent && path91.basename(parent.command) === "node" && kinds.get(parent.pid)?.kind === "codex") {
|
|
53369
53463
|
kinds.set(parent.pid, kinds.get(row.pid));
|
|
53370
53464
|
kinds.delete(row.pid);
|
|
53371
53465
|
}
|
|
@@ -53399,7 +53493,7 @@ function heavyProcesses(rows, owners = /* @__PURE__ */ new Map(), jobs = [], lim
|
|
|
53399
53493
|
const root = claim2(row);
|
|
53400
53494
|
const tracked = jobsByPgid.has(row.pgid) || root !== void 0 && trackedRoots.has(root);
|
|
53401
53495
|
if (root === void 0) {
|
|
53402
|
-
const name =
|
|
53496
|
+
const name = path91.basename(row.command).slice(0, 60);
|
|
53403
53497
|
const key3 = tracked ? `job:${row.pgid}\0${name}` : name;
|
|
53404
53498
|
const group = busy.get(key3);
|
|
53405
53499
|
if (!group) busy.set(key3, { kind: "busy", name, pid: row.pid, processes: 1, cpuPercent: row.cpu, memoryBytes: row.rssKB * 1024, top: row.cpu, row, ...tracked ? { tracked: true } : {} });
|
|
@@ -53518,7 +53612,7 @@ async function linuxBattery() {
|
|
|
53518
53612
|
const names = await readdir18(root).catch(() => []);
|
|
53519
53613
|
const battery = names.find((name) => /^BAT/.test(name));
|
|
53520
53614
|
if (!battery) return void 0;
|
|
53521
|
-
const read = (name, field) =>
|
|
53615
|
+
const read = (name, field) => readFile46(path91.join(root, name, field), "utf8").then((text4) => text4.trim()).catch(() => "");
|
|
53522
53616
|
const [capacity2, status] = await Promise.all([read(battery, "capacity"), read(battery, "status")]);
|
|
53523
53617
|
const online = await Promise.all(names.filter((name) => !/^BAT/.test(name)).map((name) => read(name, "online")));
|
|
53524
53618
|
const percent = Number(capacity2);
|
|
@@ -53588,7 +53682,7 @@ async function collectResources(deps2) {
|
|
|
53588
53682
|
const platform = deps2.platform;
|
|
53589
53683
|
const registry2 = deps2.jobs ?? new JobRegistry();
|
|
53590
53684
|
const [memory, disk, battery, rows, registered] = await Promise.all([
|
|
53591
|
-
platform === "darwin" ? darwinMemory() : platform === "linux" ?
|
|
53685
|
+
platform === "darwin" ? darwinMemory() : platform === "linux" ? readFile46("/proc/meminfo", "utf8").then(parseMeminfo).catch(() => ({ totalBytes: totalmem() })) : Promise.resolve({ totalBytes: totalmem() }),
|
|
53592
53686
|
statfs(deps2.home()).then((info) => ({ path: "~", totalBytes: info.blocks * info.bsize, freeBytes: info.bavail * info.bsize })).catch(() => void 0),
|
|
53593
53687
|
platform === "darwin" ? run("/usr/bin/pmset", ["-g", "batt"]).then(parsePmset).catch(() => void 0) : platform === "linux" ? linuxBattery() : Promise.resolve(void 0),
|
|
53594
53688
|
deps2.processes().catch(() => []),
|
|
@@ -53655,7 +53749,7 @@ var ResourceMonitor = class {
|
|
|
53655
53749
|
init_phren_paths();
|
|
53656
53750
|
import { lstat as lstat28, mkdtemp as mkdtemp5, realpath as realpath15, rm as rm12 } from "node:fs/promises";
|
|
53657
53751
|
import { hostname as hostname11, tmpdir as tmpdir2 } from "node:os";
|
|
53658
|
-
import
|
|
53752
|
+
import path92 from "node:path";
|
|
53659
53753
|
init_herdr();
|
|
53660
53754
|
init_terminal();
|
|
53661
53755
|
init_terminal_tmux();
|
|
@@ -53697,7 +53791,7 @@ async function closeCanaryWorkspaces(server, before, created) {
|
|
|
53697
53791
|
}
|
|
53698
53792
|
async function conductorStep(options, server) {
|
|
53699
53793
|
const before = new Set(objects((await snapshot(server)).workspaces).map((workspace) => String(workspace.workspace_id)));
|
|
53700
|
-
const folder = await realpath15(await mkdtemp5(
|
|
53794
|
+
const folder = await realpath15(await mkdtemp5(path92.join(tmpdir2(), "phren-canary-")));
|
|
53701
53795
|
let created, failure2, detail;
|
|
53702
53796
|
try {
|
|
53703
53797
|
const launched = await options.launch(server, { role: "conductor", kind: "claude", label: CANARY_LABEL, cwd: folder, timeoutMs: 45e3 });
|
|
@@ -53718,12 +53812,12 @@ async function scheduleStep(options) {
|
|
|
53718
53812
|
let count2 = 0;
|
|
53719
53813
|
const broken = [];
|
|
53720
53814
|
for (const directory of getProjectDirs(options.store)) {
|
|
53721
|
-
const present2 = await lstat28(
|
|
53815
|
+
const present2 = await lstat28(path92.join(directory, "schedules.yaml")).catch(() => void 0);
|
|
53722
53816
|
if (!present2) continue;
|
|
53723
53817
|
try {
|
|
53724
53818
|
count2 += (await readScheduleDocument(directory)).schedules.length;
|
|
53725
53819
|
} catch (error62) {
|
|
53726
|
-
broken.push(`${
|
|
53820
|
+
broken.push(`${path92.basename(directory)}: ${reason(error62)}`);
|
|
53727
53821
|
}
|
|
53728
53822
|
}
|
|
53729
53823
|
const tick = options.scheduler.lastTickAt;
|
|
@@ -53793,7 +53887,7 @@ function runCanary(options) {
|
|
|
53793
53887
|
}
|
|
53794
53888
|
async function dailyCanaryEnabled(root = bridgeRoot()) {
|
|
53795
53889
|
if (process.env.PHREN_CANARY_DAILY === "1") return true;
|
|
53796
|
-
return !!(await lstat28(
|
|
53890
|
+
return !!(await lstat28(path92.join(root, "canary-daily")).catch(() => void 0))?.isFile();
|
|
53797
53891
|
}
|
|
53798
53892
|
async function dailyCanaryDue(root = bridgeRoot(), now = Date.now()) {
|
|
53799
53893
|
if (running || !await dailyCanaryEnabled(root)) return false;
|
|
@@ -53831,11 +53925,11 @@ async function ownerInboxView(inbox, input2, localOnly = false) {
|
|
|
53831
53925
|
|
|
53832
53926
|
// src/bridge/server-routes.ts
|
|
53833
53927
|
init_zod();
|
|
53834
|
-
import
|
|
53928
|
+
import path112 from "node:path";
|
|
53835
53929
|
|
|
53836
53930
|
// src/bridge/code-note.ts
|
|
53837
53931
|
init_zod();
|
|
53838
|
-
import * as
|
|
53932
|
+
import * as path98 from "node:path";
|
|
53839
53933
|
|
|
53840
53934
|
// src/content/validate.ts
|
|
53841
53935
|
init_utils_helpers();
|
|
@@ -53849,7 +53943,7 @@ init_store_routing();
|
|
|
53849
53943
|
init_locks();
|
|
53850
53944
|
init_data_utils();
|
|
53851
53945
|
import * as fs29 from "fs";
|
|
53852
|
-
import * as
|
|
53946
|
+
import * as path94 from "path";
|
|
53853
53947
|
import * as crypto8 from "crypto";
|
|
53854
53948
|
|
|
53855
53949
|
// src/project-topics.ts
|
|
@@ -53861,7 +53955,7 @@ init_data_utils();
|
|
|
53861
53955
|
init_filenames();
|
|
53862
53956
|
import * as crypto7 from "crypto";
|
|
53863
53957
|
import * as fs28 from "fs";
|
|
53864
|
-
import * as
|
|
53958
|
+
import * as path93 from "path";
|
|
53865
53959
|
var TOPIC_CONFIG_FILENAME = "topic-config.json";
|
|
53866
53960
|
var SOFTWARE_TOPICS = [
|
|
53867
53961
|
{
|
|
@@ -54399,7 +54493,7 @@ function topicDocHeader(project, topic) {
|
|
|
54399
54493
|
}
|
|
54400
54494
|
function appendArchivedEntriesToTopicDoc(filePath, project, topic, entries2) {
|
|
54401
54495
|
if (entries2.length === 0) return;
|
|
54402
|
-
fs28.mkdirSync(
|
|
54496
|
+
fs28.mkdirSync(path93.dirname(filePath), { recursive: true });
|
|
54403
54497
|
withFileLock(filePath, () => {
|
|
54404
54498
|
let existing = "";
|
|
54405
54499
|
if (fs28.existsSync(filePath)) existing = fs28.readFileSync(filePath, "utf8");
|
|
@@ -54518,7 +54612,7 @@ function autoArchiveToReference(phrenPath, project, keepCount) {
|
|
|
54518
54612
|
if (!isValidProjectName(project)) return phrenErr(`Invalid project name: "${project}".`, PhrenError.INVALID_PROJECT_NAME);
|
|
54519
54613
|
const resolvedDir = storeAwareProjectPath(phrenPath, project);
|
|
54520
54614
|
if (!resolvedDir || !fs29.existsSync(resolvedDir)) return phrenErr(`Project "${project}" not found in phren.`, PhrenError.PROJECT_NOT_FOUND);
|
|
54521
|
-
const learningsPath =
|
|
54615
|
+
const learningsPath = path94.join(resolvedDir, FINDINGS_FILENAME);
|
|
54522
54616
|
if (!fs29.existsSync(learningsPath)) return phrenOk(0);
|
|
54523
54617
|
const STALE_LOCK_MS = 6e5;
|
|
54524
54618
|
const lockFile = runtimeFile(phrenPath, `consolidation-${project}.lock`);
|
|
@@ -54554,7 +54648,7 @@ function autoArchiveToReference(phrenPath, project, keepCount) {
|
|
|
54554
54648
|
const entries2 = parseActiveEntries(content);
|
|
54555
54649
|
if (entries2.length <= keepCount) return phrenOk(0);
|
|
54556
54650
|
const toArchive = entries2.slice(0, entries2.length - keepCount);
|
|
54557
|
-
const referenceDir =
|
|
54651
|
+
const referenceDir = path94.join(resolvedDir, "reference");
|
|
54558
54652
|
const { topics } = readProjectTopics(phrenPath, project);
|
|
54559
54653
|
const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
|
|
54560
54654
|
const archivedSet = buildArchivedBulletSet(referenceDir);
|
|
@@ -55124,7 +55218,7 @@ var DEFAULT_DECAY = {
|
|
|
55124
55218
|
var DEFAULT_UNDATED_CONFIDENCE = DEFAULT_DECAY.d120;
|
|
55125
55219
|
|
|
55126
55220
|
// src/content/dedup.ts
|
|
55127
|
-
import * as
|
|
55221
|
+
import * as path95 from "path";
|
|
55128
55222
|
init_shared();
|
|
55129
55223
|
init_utils();
|
|
55130
55224
|
init_store_routing();
|
|
@@ -55248,7 +55342,7 @@ function resolveCoref(text4, context) {
|
|
|
55248
55342
|
result = result.replace(/\bthe project\b/gi, context.project);
|
|
55249
55343
|
}
|
|
55250
55344
|
if (context.file) {
|
|
55251
|
-
const basename12 =
|
|
55345
|
+
const basename12 = path95.basename(context.file);
|
|
55252
55346
|
result = result.replace(/\b(this file|the file)\b/gi, basename12);
|
|
55253
55347
|
}
|
|
55254
55348
|
if (context.project && /\b(it|this|that|they|them)\b/i.test(result)) {
|
|
@@ -55265,7 +55359,7 @@ init_shared();
|
|
|
55265
55359
|
init_shared();
|
|
55266
55360
|
init_governance();
|
|
55267
55361
|
import * as fs31 from "fs";
|
|
55268
|
-
import * as
|
|
55362
|
+
import * as path97 from "path";
|
|
55269
55363
|
import * as crypto9 from "crypto";
|
|
55270
55364
|
|
|
55271
55365
|
// src/finding-graph-id.ts
|
|
@@ -55300,7 +55394,7 @@ init_store_routing();
|
|
|
55300
55394
|
// src/finding/context.ts
|
|
55301
55395
|
init_utils();
|
|
55302
55396
|
import * as fs30 from "fs";
|
|
55303
|
-
import * as
|
|
55397
|
+
import * as path96 from "path";
|
|
55304
55398
|
|
|
55305
55399
|
// src/session/utils.ts
|
|
55306
55400
|
init_utils();
|
|
@@ -55382,14 +55476,14 @@ function resolveFindingTaskReference(phrenPath, project, match) {
|
|
|
55382
55476
|
const projectDir = safeProjectPath(phrenPath, project);
|
|
55383
55477
|
if (!projectDir) return { error: `Invalid project name: "${project}".` };
|
|
55384
55478
|
const taskPath = resolveTaskFilePath(phrenPath, project);
|
|
55385
|
-
const items = parseTaskItems(taskPath ??
|
|
55479
|
+
const items = parseTaskItems(taskPath ?? path96.join(projectDir, "tasks.md"));
|
|
55386
55480
|
return resolveTaskItemMatch(items, match);
|
|
55387
55481
|
}
|
|
55388
55482
|
function resolveAutoFindingTaskItem(phrenPath, project) {
|
|
55389
55483
|
const projectDir = safeProjectPath(phrenPath, project);
|
|
55390
55484
|
if (!projectDir) return void 0;
|
|
55391
55485
|
const taskPath = resolveTaskFilePath(phrenPath, project);
|
|
55392
|
-
const active = parseTaskItems(taskPath ??
|
|
55486
|
+
const active = parseTaskItems(taskPath ?? path96.join(projectDir, "tasks.md")).filter(
|
|
55393
55487
|
(item) => item.section === "Active" && item.stableId
|
|
55394
55488
|
);
|
|
55395
55489
|
if (active.length === 1) return active[0].stableId;
|
|
@@ -55429,7 +55523,7 @@ function buildFindingCitation(citationInput, nowIso, inferredRepo, headCommit) {
|
|
|
55429
55523
|
function resolveInferredCitationRepo(citationInput) {
|
|
55430
55524
|
if (citationInput?.repo) return citationInput.repo;
|
|
55431
55525
|
if (citationInput?.file) {
|
|
55432
|
-
const fileDir =
|
|
55526
|
+
const fileDir = path97.dirname(citationInput.file);
|
|
55433
55527
|
return getRepoRoot(fileDir);
|
|
55434
55528
|
}
|
|
55435
55529
|
return void 0;
|
|
@@ -55564,7 +55658,7 @@ function addFindingToFile(phrenPath, project, learning, citationInput, opts) {
|
|
|
55564
55658
|
if (!isValidProjectName(project)) return phrenErr(`Invalid project name: "${project}".`, PhrenError.INVALID_PROJECT_NAME);
|
|
55565
55659
|
const resolvedDir = storeAwareProjectPath(phrenPath, project);
|
|
55566
55660
|
if (!resolvedDir) return phrenErr(`Invalid project name: "${project}".`, PhrenError.INVALID_PROJECT_NAME);
|
|
55567
|
-
const learningsPath =
|
|
55661
|
+
const learningsPath = path97.join(resolvedDir, FINDINGS_FILENAME);
|
|
55568
55662
|
const nowIso = (opts?.now ?? /* @__PURE__ */ new Date()).toISOString();
|
|
55569
55663
|
const today = nowIso.slice(0, 10);
|
|
55570
55664
|
const resolvedCitationInputResult = resolveFindingCitationInput(phrenPath, project, citationInput);
|
|
@@ -55746,7 +55840,7 @@ var codeNoteSchema = external_exports.object({
|
|
|
55746
55840
|
// phone's spelling, accepted until 0.3.1.
|
|
55747
55841
|
name: external_exports.string().min(1).max(4600).optional(),
|
|
55748
55842
|
symbol: external_exports.string().min(1).max(4600).optional(),
|
|
55749
|
-
file: external_exports.string().min(1).max(4096).refine((file3) => !
|
|
55843
|
+
file: external_exports.string().min(1).max(4096).refine((file3) => !path98.isAbsolute(file3) && !file3.includes("\0") && !file3.split(/[\\/]/).includes("..")),
|
|
55750
55844
|
line: external_exports.number().int().positive(),
|
|
55751
55845
|
text: external_exports.string().trim().min(1).max(4500).refine((text4) => !/[\x00-\x08\x0b-\x1f\x7f]/.test(text4)),
|
|
55752
55846
|
target: external_exports.union([external_exports.object({ session: sessionId }).strict(), external_exports.object({ harness: external_exports.enum(DISPATCH_HARNESSES) }).strict()]).optional()
|
|
@@ -55800,26 +55894,26 @@ init_transcripts();
|
|
|
55800
55894
|
import { execFile as execFile19 } from "node:child_process";
|
|
55801
55895
|
import { promisify as promisify18 } from "node:util";
|
|
55802
55896
|
import { realpathSync as realpathSync5 } from "node:fs";
|
|
55803
|
-
import { readdir as readdir19, readFile as
|
|
55897
|
+
import { readdir as readdir19, readFile as readFile47, stat as stat26, mkdir as mkdir25 } from "node:fs/promises";
|
|
55804
55898
|
import { homedir as homedir19 } from "node:os";
|
|
55805
|
-
import
|
|
55899
|
+
import path103 from "node:path";
|
|
55806
55900
|
|
|
55807
55901
|
// src/core/project.ts
|
|
55808
55902
|
init_shared();
|
|
55809
|
-
import * as
|
|
55903
|
+
import * as path101 from "path";
|
|
55810
55904
|
|
|
55811
55905
|
// src/core/project-registry.ts
|
|
55812
55906
|
init_phren_paths();
|
|
55813
55907
|
import * as fs33 from "fs";
|
|
55814
|
-
import * as
|
|
55908
|
+
import * as path100 from "path";
|
|
55815
55909
|
|
|
55816
55910
|
// src/git-worktree.ts
|
|
55817
55911
|
import * as fs32 from "fs";
|
|
55818
|
-
import * as
|
|
55912
|
+
import * as path99 from "path";
|
|
55819
55913
|
var WORKTREE_CONTAINER_NAMES = /* @__PURE__ */ new Set(["worktrees", ".worktrees"]);
|
|
55820
|
-
var LINKED_WORKTREE_SEGMENT = `${
|
|
55914
|
+
var LINKED_WORKTREE_SEGMENT = `${path99.sep}.git${path99.sep}worktrees${path99.sep}`;
|
|
55821
55915
|
function resolveWorktreeParent(dir) {
|
|
55822
|
-
const resolved =
|
|
55916
|
+
const resolved = path99.resolve(dir);
|
|
55823
55917
|
const agentParent = parentFromAgentWorktreePath(resolved);
|
|
55824
55918
|
if (agentParent) return { repoRoot: agentParent, reason: "agent-worktree-dir" };
|
|
55825
55919
|
const linkedParent = parentFromLinkedWorktree(resolved);
|
|
@@ -55827,23 +55921,23 @@ function resolveWorktreeParent(dir) {
|
|
|
55827
55921
|
return null;
|
|
55828
55922
|
}
|
|
55829
55923
|
function parentFromAgentWorktreePath(resolved) {
|
|
55830
|
-
const segments = resolved.split(
|
|
55924
|
+
const segments = resolved.split(path99.sep);
|
|
55831
55925
|
for (let i = 1; i < segments.length; i++) {
|
|
55832
55926
|
if (!WORKTREE_CONTAINER_NAMES.has(segments[i])) continue;
|
|
55833
55927
|
let j = i - 1;
|
|
55834
55928
|
if (!segments[j]?.startsWith(".")) continue;
|
|
55835
55929
|
while (j >= 1 && segments[j].startsWith(".")) j--;
|
|
55836
55930
|
if (j < 1) continue;
|
|
55837
|
-
return segments.slice(0, j + 1).join(
|
|
55931
|
+
return segments.slice(0, j + 1).join(path99.sep) || path99.sep;
|
|
55838
55932
|
}
|
|
55839
55933
|
return null;
|
|
55840
55934
|
}
|
|
55841
55935
|
function parentFromLinkedWorktree(resolved) {
|
|
55842
55936
|
let current2 = resolved;
|
|
55843
55937
|
while (true) {
|
|
55844
|
-
const parent = repoRootFromGitFile(
|
|
55938
|
+
const parent = repoRootFromGitFile(path99.join(current2, ".git"));
|
|
55845
55939
|
if (parent) return parent;
|
|
55846
|
-
const next =
|
|
55940
|
+
const next = path99.dirname(current2);
|
|
55847
55941
|
if (next === current2) return null;
|
|
55848
55942
|
current2 = next;
|
|
55849
55943
|
}
|
|
@@ -55858,7 +55952,7 @@ function repoRootFromGitFile(gitPath) {
|
|
|
55858
55952
|
}
|
|
55859
55953
|
const match = raw.match(/^\s*gitdir:\s*(.+?)\s*$/m);
|
|
55860
55954
|
if (!match) return null;
|
|
55861
|
-
const gitDir =
|
|
55955
|
+
const gitDir = path99.resolve(path99.dirname(gitPath), match[1].replace(/[/\\]/g, path99.sep));
|
|
55862
55956
|
const idx = gitDir.indexOf(LINKED_WORKTREE_SEGMENT);
|
|
55863
55957
|
if (idx === -1) return null;
|
|
55864
55958
|
return gitDir.slice(0, idx);
|
|
@@ -56071,7 +56165,7 @@ function scoreTopicsFromTerms(domain2, terms, docsText) {
|
|
|
56071
56165
|
return topics;
|
|
56072
56166
|
}
|
|
56073
56167
|
function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
|
|
56074
|
-
const resolvedRoot =
|
|
56168
|
+
const resolvedRoot = path100.resolve(repoRoot);
|
|
56075
56169
|
if (!fs33.existsSync(resolvedRoot)) return null;
|
|
56076
56170
|
const signal = {
|
|
56077
56171
|
domainScores: { software: 0, music: 0, game: 0, research: 0, writing: 0, creative: 0, other: 0 },
|
|
@@ -56082,7 +56176,7 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
|
|
|
56082
56176
|
usefulSignals: 0
|
|
56083
56177
|
};
|
|
56084
56178
|
const skipDirs = /* @__PURE__ */ new Set([".git", ".phren", "node_modules", "dist", "build", "coverage", ".next", ".turbo", "target"]);
|
|
56085
|
-
const packageJsonPath =
|
|
56179
|
+
const packageJsonPath = path100.join(resolvedRoot, "package.json");
|
|
56086
56180
|
if (fs33.existsSync(packageJsonPath)) {
|
|
56087
56181
|
signal.usefulSignals++;
|
|
56088
56182
|
addDomainScores(signal.domainScores, DOMAIN_CONFIG_HINTS["package.json"]);
|
|
@@ -56112,33 +56206,33 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
|
|
|
56112
56206
|
debugLog(`inferInitScaffoldFromRepo package.json parse failed: ${errorMessage(err)}`);
|
|
56113
56207
|
}
|
|
56114
56208
|
}
|
|
56115
|
-
const topLevelConfigs = Object.keys(DOMAIN_CONFIG_HINTS).filter((fileName) => fs33.existsSync(
|
|
56209
|
+
const topLevelConfigs = Object.keys(DOMAIN_CONFIG_HINTS).filter((fileName) => fs33.existsSync(path100.join(resolvedRoot, fileName)));
|
|
56116
56210
|
for (const configName of topLevelConfigs) {
|
|
56117
56211
|
signal.usefulSignals++;
|
|
56118
56212
|
const configScore = DOMAIN_CONFIG_HINTS[configName];
|
|
56119
56213
|
if (configScore) addDomainScores(signal.domainScores, configScore);
|
|
56120
56214
|
}
|
|
56121
56215
|
const readmeCandidates = [
|
|
56122
|
-
|
|
56123
|
-
|
|
56216
|
+
path100.join(resolvedRoot, "README.md"),
|
|
56217
|
+
path100.join(resolvedRoot, "readme.md")
|
|
56124
56218
|
];
|
|
56125
56219
|
for (const readmePath of readmeCandidates) {
|
|
56126
56220
|
if (!fs33.existsSync(readmePath)) continue;
|
|
56127
56221
|
const content = maybeReadUtf8(readmePath);
|
|
56128
56222
|
if (!content) continue;
|
|
56129
56223
|
signal.usefulSignals++;
|
|
56130
|
-
signal.referenceHints.push(
|
|
56224
|
+
signal.referenceHints.push(path100.relative(resolvedRoot, readmePath));
|
|
56131
56225
|
addTermCount(signal.terms, content, 2);
|
|
56132
56226
|
signal.docsText += ` ${content.toLowerCase()}`;
|
|
56133
56227
|
break;
|
|
56134
56228
|
}
|
|
56135
|
-
const docsDir =
|
|
56229
|
+
const docsDir = path100.join(resolvedRoot, "docs");
|
|
56136
56230
|
if (fs33.existsSync(docsDir) && fs33.statSync(docsDir).isDirectory()) {
|
|
56137
56231
|
signal.referenceHints.push("docs/");
|
|
56138
56232
|
for (const entry2 of fs33.readdirSync(docsDir, { withFileTypes: true })) {
|
|
56139
56233
|
if (!entry2.isFile()) continue;
|
|
56140
56234
|
if (!/\.(md|txt|rst)$/i.test(entry2.name)) continue;
|
|
56141
|
-
const docsContent = maybeReadUtf8(
|
|
56235
|
+
const docsContent = maybeReadUtf8(path100.join(docsDir, entry2.name));
|
|
56142
56236
|
if (!docsContent) continue;
|
|
56143
56237
|
signal.usefulSignals++;
|
|
56144
56238
|
addTermCount(signal.terms, docsContent, 1);
|
|
@@ -56146,7 +56240,7 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
|
|
|
56146
56240
|
}
|
|
56147
56241
|
}
|
|
56148
56242
|
for (const folderName of ["reference", "specs", "design", "architecture", "src", "packages", "apps"]) {
|
|
56149
|
-
const fullPath =
|
|
56243
|
+
const fullPath = path100.join(resolvedRoot, folderName);
|
|
56150
56244
|
if (fs33.existsSync(fullPath)) {
|
|
56151
56245
|
signal.referenceHints.push(`${folderName}/`);
|
|
56152
56246
|
}
|
|
@@ -56157,14 +56251,14 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
|
|
|
56157
56251
|
if (scannedFiles >= maxFiles) return;
|
|
56158
56252
|
for (const entry2 of fs33.readdirSync(dir, { withFileTypes: true })) {
|
|
56159
56253
|
if (scannedFiles >= maxFiles) return;
|
|
56160
|
-
const fullPath =
|
|
56254
|
+
const fullPath = path100.join(dir, entry2.name);
|
|
56161
56255
|
if (entry2.isDirectory()) {
|
|
56162
56256
|
if (skipDirs.has(entry2.name)) continue;
|
|
56163
56257
|
walk(fullPath);
|
|
56164
56258
|
continue;
|
|
56165
56259
|
}
|
|
56166
56260
|
scannedFiles++;
|
|
56167
|
-
const ext =
|
|
56261
|
+
const ext = path100.extname(entry2.name).toLowerCase();
|
|
56168
56262
|
if (!ext) continue;
|
|
56169
56263
|
const extScore = EXTENSION_DOMAIN_HINTS[ext];
|
|
56170
56264
|
if (extScore) {
|
|
@@ -56338,7 +56432,7 @@ function findExistingProjectForSource(phrenPath, sourceRoot, derivedName) {
|
|
|
56338
56432
|
return null;
|
|
56339
56433
|
}
|
|
56340
56434
|
};
|
|
56341
|
-
const resolvedSource =
|
|
56435
|
+
const resolvedSource = path100.resolve(sourceRoot);
|
|
56342
56436
|
for (const project of candidates) {
|
|
56343
56437
|
if (sourceOf(project) === resolvedSource) return project;
|
|
56344
56438
|
}
|
|
@@ -56352,7 +56446,7 @@ function findExistingProjectForSource(phrenPath, sourceRoot, derivedName) {
|
|
|
56352
56446
|
function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
|
|
56353
56447
|
const profile = typeof opts === "string" ? opts : opts.profile;
|
|
56354
56448
|
const profilePhrenPath = typeof opts === "string" ? phrenPath : opts.profilePhrenPath ?? phrenPath;
|
|
56355
|
-
const resolvedPath =
|
|
56449
|
+
const resolvedPath = path100.resolve(projectPath);
|
|
56356
56450
|
if (!fs33.existsSync(resolvedPath)) {
|
|
56357
56451
|
throw new Error(`Path does not exist: ${resolvedPath}`);
|
|
56358
56452
|
}
|
|
@@ -56363,17 +56457,17 @@ function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
|
|
|
56363
56457
|
if (worktreeRepoRoot) {
|
|
56364
56458
|
debugLog(`bootstrapFromExisting: ${resolvedPath} is a ${worktree.reason}; attributing to ${worktreeRepoRoot}`);
|
|
56365
56459
|
}
|
|
56366
|
-
const sourceRoot = isProjectLocal ?
|
|
56460
|
+
const sourceRoot = isProjectLocal ? path100.resolve(manifest.workspaceRoot || resolvedPath) : worktreeRepoRoot ?? resolvedPath;
|
|
56367
56461
|
if (isProjectLocal) {
|
|
56368
|
-
const matchesWorkspace = resolvedPath === sourceRoot || resolvedPath.startsWith(sourceRoot +
|
|
56462
|
+
const matchesWorkspace = resolvedPath === sourceRoot || resolvedPath.startsWith(sourceRoot + path100.sep);
|
|
56369
56463
|
if (!matchesWorkspace) {
|
|
56370
56464
|
throw new Error(`Project-local phren can only enroll the owning workspace: ${sourceRoot}`);
|
|
56371
56465
|
}
|
|
56372
56466
|
}
|
|
56373
56467
|
let claudeMdPath = null;
|
|
56374
56468
|
const candidates = [
|
|
56375
|
-
|
|
56376
|
-
|
|
56469
|
+
path100.join(sourceRoot, "AGENTS.md"),
|
|
56470
|
+
path100.join(sourceRoot, ".claude", "CLAUDE.md")
|
|
56377
56471
|
];
|
|
56378
56472
|
for (const c of candidates) {
|
|
56379
56473
|
if (fs33.existsSync(c)) {
|
|
@@ -56393,12 +56487,12 @@ function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
|
|
|
56393
56487
|
`Project "${existingProject}" already exists with different casing. Refusing to bootstrap "${projectName2}" because it would split the same project on case-sensitive filesystems.`
|
|
56394
56488
|
);
|
|
56395
56489
|
}
|
|
56396
|
-
const projDir =
|
|
56490
|
+
const projDir = path100.join(phrenPath, projectName2);
|
|
56397
56491
|
fs33.mkdirSync(projDir, { recursive: true });
|
|
56398
56492
|
const inferredScaffold = inferInitScaffoldFromRepo(sourceRoot);
|
|
56399
56493
|
const existingConfig = readProjectConfig(phrenPath, projectName2);
|
|
56400
56494
|
const ownership = typeof opts === "string" ? parseProjectOwnershipMode(existingConfig.ownership) ?? getProjectOwnershipDefault(phrenPath) : opts.ownership ?? parseProjectOwnershipMode(existingConfig.ownership) ?? getProjectOwnershipDefault(phrenPath);
|
|
56401
|
-
const claudePath =
|
|
56495
|
+
const claudePath = path100.join(projDir, "AGENTS.md");
|
|
56402
56496
|
if (ownership !== "repo-managed") {
|
|
56403
56497
|
if (claudeContent) {
|
|
56404
56498
|
if (!fs33.existsSync(claudePath)) {
|
|
@@ -56433,7 +56527,7 @@ function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
|
|
|
56433
56527
|
}
|
|
56434
56528
|
}
|
|
56435
56529
|
const sourceInfo = claudeMdPath ? `**Source AGENTS.md:** ${claudeMdPath}` : `**Source:** ${sourceRoot}`;
|
|
56436
|
-
const summaryPath =
|
|
56530
|
+
const summaryPath = path100.join(projDir, "summary.md");
|
|
56437
56531
|
if (!fs33.existsSync(summaryPath)) {
|
|
56438
56532
|
atomicWriteText(
|
|
56439
56533
|
summaryPath,
|
|
@@ -56446,18 +56540,18 @@ ${summaryLines.length > 1 ? summaryLines.slice(1).join("\n") : ""}
|
|
|
56446
56540
|
`
|
|
56447
56541
|
);
|
|
56448
56542
|
}
|
|
56449
|
-
if (!fs33.existsSync(
|
|
56543
|
+
if (!fs33.existsSync(path100.join(projDir, FINDINGS_FILENAME))) {
|
|
56450
56544
|
atomicWriteText(
|
|
56451
|
-
|
|
56545
|
+
path100.join(projDir, FINDINGS_FILENAME),
|
|
56452
56546
|
`# ${projectName2} FINDINGS
|
|
56453
56547
|
|
|
56454
56548
|
<!-- Bootstrapped from ${sourceRoot} -->
|
|
56455
56549
|
`
|
|
56456
56550
|
);
|
|
56457
56551
|
}
|
|
56458
|
-
if (moduleEnabled(phrenPath, "tasks") && !fs33.existsSync(
|
|
56552
|
+
if (moduleEnabled(phrenPath, "tasks") && !fs33.existsSync(path100.join(projDir, TASKS_FILENAME))) {
|
|
56459
56553
|
atomicWriteText(
|
|
56460
|
-
|
|
56554
|
+
path100.join(projDir, TASKS_FILENAME),
|
|
56461
56555
|
`# ${projectName2} tasks
|
|
56462
56556
|
|
|
56463
56557
|
## Active
|
|
@@ -56468,11 +56562,11 @@ ${summaryLines.length > 1 ? summaryLines.slice(1).join("\n") : ""}
|
|
|
56468
56562
|
`
|
|
56469
56563
|
);
|
|
56470
56564
|
}
|
|
56471
|
-
if (!fs33.existsSync(
|
|
56565
|
+
if (!fs33.existsSync(path100.join(projDir, "topic-config.json"))) {
|
|
56472
56566
|
const inferredDomain = normalizeBuiltinTopicDomain(inferredScaffold?.domain ?? "software");
|
|
56473
56567
|
const inferredTopics = inferredScaffold?.topics?.length ? inferredScaffold.topics : getBuiltinTopicConfig(inferredDomain);
|
|
56474
56568
|
atomicWriteText(
|
|
56475
|
-
|
|
56569
|
+
path100.join(projDir, "topic-config.json"),
|
|
56476
56570
|
JSON.stringify({ version: 1, domain: inferredDomain, topics: inferredTopics }, null, 2) + "\n"
|
|
56477
56571
|
);
|
|
56478
56572
|
}
|
|
@@ -56504,10 +56598,10 @@ function addProjectFromPath(phrenPath, targetPath, requestedProfile, ownership,
|
|
|
56504
56598
|
if (!activeProfile.ok) return activeProfile;
|
|
56505
56599
|
const writePhrenPath = options.writeToPath ?? phrenPath;
|
|
56506
56600
|
const manifest = readRootManifest(phrenPath);
|
|
56507
|
-
const resolvedPath =
|
|
56601
|
+
const resolvedPath = path101.resolve(targetPath);
|
|
56508
56602
|
if (manifest?.installMode === "project-local") {
|
|
56509
|
-
const workspaceRoot =
|
|
56510
|
-
const matchesWorkspace = resolvedPath === workspaceRoot || resolvedPath.startsWith(workspaceRoot +
|
|
56603
|
+
const workspaceRoot = path101.resolve(manifest.workspaceRoot || "");
|
|
56604
|
+
const matchesWorkspace = resolvedPath === workspaceRoot || resolvedPath.startsWith(workspaceRoot + path101.sep);
|
|
56511
56605
|
if (!matchesWorkspace) {
|
|
56512
56606
|
return phrenErr(`Project-local phren can only add the owning workspace: ${workspaceRoot}`);
|
|
56513
56607
|
}
|
|
@@ -56525,9 +56619,9 @@ function addProjectFromPath(phrenPath, targetPath, requestedProfile, ownership,
|
|
|
56525
56619
|
ownership: added.ownership,
|
|
56526
56620
|
files: {
|
|
56527
56621
|
claude: added.claudePath,
|
|
56528
|
-
summary:
|
|
56529
|
-
findings:
|
|
56530
|
-
task:
|
|
56622
|
+
summary: path101.join(writePhrenPath, added.project, "summary.md"),
|
|
56623
|
+
findings: path101.join(writePhrenPath, added.project, FINDINGS_FILENAME),
|
|
56624
|
+
task: path101.join(writePhrenPath, added.project, TASKS_FILENAME)
|
|
56531
56625
|
}
|
|
56532
56626
|
});
|
|
56533
56627
|
}
|
|
@@ -56553,7 +56647,7 @@ import { execFileSync as execFileSync6, spawnSync as spawnSync2 } from "child_pr
|
|
|
56553
56647
|
import * as crypto10 from "crypto";
|
|
56554
56648
|
import * as fs34 from "fs";
|
|
56555
56649
|
import * as os3 from "os";
|
|
56556
|
-
import * as
|
|
56650
|
+
import * as path102 from "path";
|
|
56557
56651
|
|
|
56558
56652
|
// src/content/summarize.ts
|
|
56559
56653
|
init_phren_dotenv();
|
|
@@ -56714,7 +56808,7 @@ function mergeTasksByBid(base, ours, theirs) {
|
|
|
56714
56808
|
// src/sync/conflict-resolve.ts
|
|
56715
56809
|
function conflictStrategy(relFile) {
|
|
56716
56810
|
const file3 = relFile.replace(/\\/g, "/");
|
|
56717
|
-
const name =
|
|
56811
|
+
const name = path102.posix.basename(file3).toLowerCase();
|
|
56718
56812
|
if (isTaskFileName(name)) return "tasks";
|
|
56719
56813
|
if (name === "findings.md") return "findings";
|
|
56720
56814
|
if (/^\.config\/task-archive\/[^/]+\.md$/i.test(file3)) return "archive";
|
|
@@ -56749,9 +56843,9 @@ function splitBlock(content, start, end) {
|
|
|
56749
56843
|
function mergeText(base, ours, theirs) {
|
|
56750
56844
|
if (ours === theirs || ours === base) return theirs;
|
|
56751
56845
|
if (theirs === base) return ours;
|
|
56752
|
-
const dir = fs34.mkdtempSync(
|
|
56846
|
+
const dir = fs34.mkdtempSync(path102.join(os3.tmpdir(), "phren-merge-"));
|
|
56753
56847
|
try {
|
|
56754
|
-
const [o, b, t] = ["ours", "base", "theirs"].map((name) =>
|
|
56848
|
+
const [o, b, t] = ["ours", "base", "theirs"].map((name) => path102.join(dir, name));
|
|
56755
56849
|
fs34.writeFileSync(o, ours);
|
|
56756
56850
|
fs34.writeFileSync(b, base);
|
|
56757
56851
|
fs34.writeFileSync(t, theirs);
|
|
@@ -56764,9 +56858,9 @@ function mergeText(base, ours, theirs) {
|
|
|
56764
56858
|
function unionText(base, ours, theirs) {
|
|
56765
56859
|
const clean2 = mergeText(base, ours, theirs);
|
|
56766
56860
|
if (clean2 !== null) return clean2;
|
|
56767
|
-
const dir = fs34.mkdtempSync(
|
|
56861
|
+
const dir = fs34.mkdtempSync(path102.join(os3.tmpdir(), "phren-merge-"));
|
|
56768
56862
|
try {
|
|
56769
|
-
const [o, b, t] = ["ours", "base", "theirs"].map((name) =>
|
|
56863
|
+
const [o, b, t] = ["ours", "base", "theirs"].map((name) => path102.join(dir, name));
|
|
56770
56864
|
fs34.writeFileSync(o, ours);
|
|
56771
56865
|
fs34.writeFileSync(b, base);
|
|
56772
56866
|
fs34.writeFileSync(t, theirs);
|
|
@@ -56826,7 +56920,7 @@ function resolveStoreConflicts(cwd) {
|
|
|
56826
56920
|
const base = stage(cwd, 1, relFile) ?? "";
|
|
56827
56921
|
const ours = stage(cwd, 2, relFile);
|
|
56828
56922
|
const theirs = stage(cwd, 3, relFile);
|
|
56829
|
-
const fullPath =
|
|
56923
|
+
const fullPath = path102.join(cwd, relFile);
|
|
56830
56924
|
if (ours === null && theirs === null) {
|
|
56831
56925
|
unresolved.push(relFile);
|
|
56832
56926
|
continue;
|
|
@@ -56837,7 +56931,7 @@ function resolveStoreConflicts(cwd) {
|
|
|
56837
56931
|
continue;
|
|
56838
56932
|
}
|
|
56839
56933
|
const tmp = `${fullPath}.tmp-${crypto10.randomUUID()}`;
|
|
56840
|
-
fs34.mkdirSync(
|
|
56934
|
+
fs34.mkdirSync(path102.dirname(fullPath), { recursive: true });
|
|
56841
56935
|
fs34.writeFileSync(tmp, merged);
|
|
56842
56936
|
fs34.renameSync(tmp, fullPath);
|
|
56843
56937
|
git4(cwd, ["add", "--", relFile]);
|
|
@@ -57117,7 +57211,7 @@ function repoName(url2) {
|
|
|
57117
57211
|
}
|
|
57118
57212
|
async function isRepository(directory) {
|
|
57119
57213
|
try {
|
|
57120
|
-
await stat26(
|
|
57214
|
+
await stat26(path103.join(directory, ".git"));
|
|
57121
57215
|
return true;
|
|
57122
57216
|
} catch {
|
|
57123
57217
|
return false;
|
|
@@ -57137,7 +57231,7 @@ async function registeredSources(env) {
|
|
|
57137
57231
|
const source = readProjectConfig(store, project).sourcePath;
|
|
57138
57232
|
if (typeof source === "string" && source) {
|
|
57139
57233
|
try {
|
|
57140
|
-
paths.add(realpathSync5.native(
|
|
57234
|
+
paths.add(realpathSync5.native(path103.resolve(source)));
|
|
57141
57235
|
} catch {
|
|
57142
57236
|
}
|
|
57143
57237
|
}
|
|
@@ -57149,7 +57243,7 @@ async function candidateRepos(activity, env = process.env) {
|
|
|
57149
57243
|
const found = [];
|
|
57150
57244
|
const seen = /* @__PURE__ */ new Set();
|
|
57151
57245
|
const offer = async (directory, source, lastSeen) => {
|
|
57152
|
-
let dir =
|
|
57246
|
+
let dir = path103.resolve(directory);
|
|
57153
57247
|
try {
|
|
57154
57248
|
if (!(await stat26(dir)).isDirectory()) return;
|
|
57155
57249
|
dir = realpathSync5.native(dir);
|
|
@@ -57164,7 +57258,7 @@ async function candidateRepos(activity, env = process.env) {
|
|
|
57164
57258
|
const toplevel = async (directory) => {
|
|
57165
57259
|
let existing = directory;
|
|
57166
57260
|
while (!await stat26(existing).catch(() => void 0)) {
|
|
57167
|
-
const parent =
|
|
57261
|
+
const parent = path103.dirname(existing);
|
|
57168
57262
|
if (parent === existing) return void 0;
|
|
57169
57263
|
existing = parent;
|
|
57170
57264
|
}
|
|
@@ -57177,25 +57271,25 @@ async function candidateRepos(activity, env = process.env) {
|
|
|
57177
57271
|
};
|
|
57178
57272
|
for (const event of [...activity].reverse()) {
|
|
57179
57273
|
const directory = typeof event.directory === "string" ? event.directory : void 0;
|
|
57180
|
-
if (!directory || !
|
|
57274
|
+
if (!directory || !path103.isAbsolute(directory)) continue;
|
|
57181
57275
|
const root = await toplevel(directory);
|
|
57182
57276
|
if (root) await offer(root, "activity", typeof event.at === "string" ? event.at : void 0);
|
|
57183
57277
|
}
|
|
57184
57278
|
try {
|
|
57185
|
-
const session = JSON.parse(await
|
|
57279
|
+
const session = JSON.parse(await readFile47(path103.join(herdrRoot(), "session.json"), "utf8"));
|
|
57186
57280
|
for (const match of JSON.stringify(session).matchAll(/"cwd":\s*"((?:\\.|[^"\\])*)"/g)) {
|
|
57187
57281
|
const directory = JSON.parse(`"${match[1]}"`);
|
|
57188
|
-
if (!
|
|
57282
|
+
if (!path103.isAbsolute(directory)) continue;
|
|
57189
57283
|
const root = await toplevel(directory);
|
|
57190
57284
|
if (root) await offer(root, "herdr");
|
|
57191
57285
|
}
|
|
57192
57286
|
} catch {
|
|
57193
57287
|
}
|
|
57194
57288
|
const home = homedir19();
|
|
57195
|
-
for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.map((r) =>
|
|
57289
|
+
for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.map((r) => path103.join(home, r))]) {
|
|
57196
57290
|
let children = [];
|
|
57197
57291
|
try {
|
|
57198
|
-
children = (await readdir19(root, { withFileTypes: true })).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) =>
|
|
57292
|
+
children = (await readdir19(root, { withFileTypes: true })).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => path103.join(root, e.name));
|
|
57199
57293
|
} catch {
|
|
57200
57294
|
continue;
|
|
57201
57295
|
}
|
|
@@ -57205,13 +57299,13 @@ async function candidateRepos(activity, env = process.env) {
|
|
|
57205
57299
|
}
|
|
57206
57300
|
async function cloneRoot(env) {
|
|
57207
57301
|
const home = homedir19();
|
|
57208
|
-
for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.filter((r) => r !== "Sites").map((r) =>
|
|
57302
|
+
for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.filter((r) => r !== "Sites").map((r) => path103.join(home, r))]) {
|
|
57209
57303
|
try {
|
|
57210
57304
|
if ((await stat26(root)).isDirectory()) return root;
|
|
57211
57305
|
} catch {
|
|
57212
57306
|
}
|
|
57213
57307
|
}
|
|
57214
|
-
const fallback2 =
|
|
57308
|
+
const fallback2 = path103.join(home, "Projects");
|
|
57215
57309
|
await mkdir25(fallback2, { recursive: true });
|
|
57216
57310
|
return fallback2;
|
|
57217
57311
|
}
|
|
@@ -57233,7 +57327,7 @@ async function publishStore(store, project) {
|
|
|
57233
57327
|
async function enrollProject(input2, env = process.env) {
|
|
57234
57328
|
const store = phrenStoreRoot(env);
|
|
57235
57329
|
try {
|
|
57236
|
-
if (!(await stat26(
|
|
57330
|
+
if (!(await stat26(path103.join(store, ".config"))).isDirectory()) throw new Error();
|
|
57237
57331
|
} catch {
|
|
57238
57332
|
throw new BridgeError(409, "phren is not set up on this computer. Run phren init there.");
|
|
57239
57333
|
}
|
|
@@ -57244,7 +57338,7 @@ async function enrollProject(input2, env = process.env) {
|
|
|
57244
57338
|
if (url2.length > 512 || !CLONE_URL.test(url2)) throw new BridgeError(400, "Enter a GitHub repository URL (https://github.com/owner/repo).");
|
|
57245
57339
|
const name = repoName(url2);
|
|
57246
57340
|
if (!name || name === "." || name === "..") throw new BridgeError(400, "That URL has no repository name.");
|
|
57247
|
-
directory =
|
|
57341
|
+
directory = path103.join(await cloneRoot(env), name);
|
|
57248
57342
|
try {
|
|
57249
57343
|
await stat26(directory);
|
|
57250
57344
|
throw new BridgeError(409, `${directory} already exists on this computer. Add that folder instead.`);
|
|
@@ -57261,7 +57355,7 @@ async function enrollProject(input2, env = process.env) {
|
|
|
57261
57355
|
cloned = true;
|
|
57262
57356
|
} else if (typeof input2.directory === "string" && input2.directory) {
|
|
57263
57357
|
const raw = input2.directory;
|
|
57264
|
-
if (raw.length > 4096 || raw.includes("\0") || !
|
|
57358
|
+
if (raw.length > 4096 || raw.includes("\0") || !path103.isAbsolute(raw)) throw new BridgeError(400, "Enter the full folder path on this computer.");
|
|
57265
57359
|
try {
|
|
57266
57360
|
directory = realpathSync5.native(raw);
|
|
57267
57361
|
if (!(await stat26(directory)).isDirectory()) throw new Error();
|
|
@@ -57278,20 +57372,20 @@ async function enrollProject(input2, env = process.env) {
|
|
|
57278
57372
|
init_protocol();
|
|
57279
57373
|
import { constants as constants4 } from "node:fs";
|
|
57280
57374
|
import { lstat as lstat29, open as open21, readdir as readdir20, realpath as realpath16 } from "node:fs/promises";
|
|
57281
|
-
import
|
|
57375
|
+
import path104 from "node:path";
|
|
57282
57376
|
var MAX_BYTES = 2097152;
|
|
57283
57377
|
async function browseFiles(root, relative3) {
|
|
57284
|
-
if (relative3.length > 4096 || relative3.includes("\0") || relative3.includes("\\") ||
|
|
57378
|
+
if (relative3.length > 4096 || relative3.includes("\0") || relative3.includes("\\") || path104.isAbsolute(relative3) || relative3.split("/").some((part) => part === ".." || part === ".git")) {
|
|
57285
57379
|
throw new BridgeError(400, "Invalid repository path.");
|
|
57286
57380
|
}
|
|
57287
57381
|
const base = await realpath16(root);
|
|
57288
57382
|
let file3 = base;
|
|
57289
57383
|
for (const part of relative3.split("/").filter((part2) => part2 && part2 !== ".")) {
|
|
57290
|
-
file3 =
|
|
57384
|
+
file3 = path104.join(file3, part);
|
|
57291
57385
|
if ((await lstat29(file3)).isSymbolicLink()) throw new BridgeError(403, "Symbolic links cannot be browsed.");
|
|
57292
57386
|
}
|
|
57293
57387
|
const resolved = await realpath16(file3);
|
|
57294
|
-
if (resolved !== base && !resolved.startsWith(base +
|
|
57388
|
+
if (resolved !== base && !resolved.startsWith(base + path104.sep)) throw new BridgeError(403, "The path is outside this repository.");
|
|
57295
57389
|
const metadata = await lstat29(resolved);
|
|
57296
57390
|
if (metadata.isDirectory()) {
|
|
57297
57391
|
const entries2 = (await readdir20(resolved, { withFileTypes: true })).filter((entry2) => entry2.name !== ".git" && (entry2.isDirectory() || entry2.isFile())).sort((a, b) => Number(b.isDirectory()) - Number(a.isDirectory()) || a.name.localeCompare(b.name));
|
|
@@ -57299,7 +57393,7 @@ async function browseFiles(root, relative3) {
|
|
|
57299
57393
|
path: relative3,
|
|
57300
57394
|
kind: "directory",
|
|
57301
57395
|
truncated: entries2.length > 500,
|
|
57302
|
-
entries: entries2.slice(0, 500).map((entry2) => ({ name: entry2.name, path:
|
|
57396
|
+
entries: entries2.slice(0, 500).map((entry2) => ({ name: entry2.name, path: path104.posix.join(relative3, entry2.name), kind: entry2.isDirectory() ? "directory" : "file" }))
|
|
57303
57397
|
};
|
|
57304
57398
|
}
|
|
57305
57399
|
if (!metadata.isFile()) throw new BridgeError(400, "Only regular files can be viewed.");
|
|
@@ -57326,7 +57420,7 @@ async function browseFiles(root, relative3) {
|
|
|
57326
57420
|
init_protocol();
|
|
57327
57421
|
import { constants as constants5 } from "node:fs";
|
|
57328
57422
|
import { lstat as lstat30, open as open22, realpath as realpath17 } from "node:fs/promises";
|
|
57329
|
-
import
|
|
57423
|
+
import path105 from "node:path";
|
|
57330
57424
|
var MAX_FILE_RANGE = 4 * 1024 * 1024;
|
|
57331
57425
|
var types = {
|
|
57332
57426
|
mp4: "video/mp4",
|
|
@@ -57363,7 +57457,7 @@ var types = {
|
|
|
57363
57457
|
xml: "text/xml"
|
|
57364
57458
|
};
|
|
57365
57459
|
function fileContentType(file3) {
|
|
57366
|
-
const ext =
|
|
57460
|
+
const ext = path105.extname(file3).slice(1).toLowerCase();
|
|
57367
57461
|
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");
|
|
57368
57462
|
}
|
|
57369
57463
|
function version2(stat29) {
|
|
@@ -57381,15 +57475,15 @@ async function readFileRange(root, requested, offset, length, expectedVersion) {
|
|
|
57381
57475
|
}
|
|
57382
57476
|
try {
|
|
57383
57477
|
const base = await realpath17(root);
|
|
57384
|
-
const relative3 =
|
|
57385
|
-
if (relative3 === ".." || relative3.startsWith(`..${
|
|
57478
|
+
const relative3 = path105.isAbsolute(requested) ? path105.relative(base, requested) : requested;
|
|
57479
|
+
if (relative3 === ".." || relative3.startsWith(`..${path105.sep}`) || path105.isAbsolute(relative3)) throw new BridgeError(403, "This file is outside the allowed folder.");
|
|
57386
57480
|
let file3 = base;
|
|
57387
|
-
for (const part of relative3.split(
|
|
57388
|
-
file3 =
|
|
57481
|
+
for (const part of relative3.split(path105.sep).filter((part2) => part2 && part2 !== ".")) {
|
|
57482
|
+
file3 = path105.join(file3, part);
|
|
57389
57483
|
if ((await lstat30(file3)).isSymbolicLink()) throw new BridgeError(403, "Symbolic links cannot be opened.");
|
|
57390
57484
|
}
|
|
57391
57485
|
const resolved = await realpath17(file3);
|
|
57392
|
-
if (!resolved.startsWith(base +
|
|
57486
|
+
if (!resolved.startsWith(base + path105.sep)) throw new BridgeError(403, "This file is outside the allowed folder.");
|
|
57393
57487
|
const metadata = await lstat30(resolved);
|
|
57394
57488
|
if (!metadata.isFile()) throw new BridgeError(400, "Only regular files can be opened.");
|
|
57395
57489
|
const handle = await open22(resolved, constants5.O_RDONLY | constants5.O_NOFOLLOW | constants5.O_NONBLOCK);
|
|
@@ -57433,8 +57527,8 @@ init_zod();
|
|
|
57433
57527
|
init_protocol();
|
|
57434
57528
|
import { execFile as execFile20 } from "node:child_process";
|
|
57435
57529
|
import { createHash as createHash26 } from "node:crypto";
|
|
57436
|
-
import { lstat as lstat31, mkdir as mkdir26, readFile as
|
|
57437
|
-
import
|
|
57530
|
+
import { lstat as lstat31, mkdir as mkdir26, readFile as readFile48, realpath as realpath18, rename as rename9, rm as rm13, writeFile as writeFile10 } from "node:fs/promises";
|
|
57531
|
+
import path106 from "node:path";
|
|
57438
57532
|
import { promisify as promisify19 } from "node:util";
|
|
57439
57533
|
var exec19 = promisify19(execFile20);
|
|
57440
57534
|
var SHA = /^[0-9a-f]{40}$/;
|
|
@@ -57462,7 +57556,7 @@ function blobSha(content) {
|
|
|
57462
57556
|
return createHash26("sha1").update(`blob ${content.length}\0`).update(content).digest("hex");
|
|
57463
57557
|
}
|
|
57464
57558
|
async function isRepository2(store) {
|
|
57465
|
-
return await lstat31(
|
|
57559
|
+
return await lstat31(path106.join(store, ".git")).catch(() => void 0) !== void 0;
|
|
57466
57560
|
}
|
|
57467
57561
|
function githubStoreRepository(remote) {
|
|
57468
57562
|
let host, pathname;
|
|
@@ -57492,10 +57586,10 @@ async function storeRepositoryIdentity(store) {
|
|
|
57492
57586
|
const repository3 = githubStoreRepository(remote);
|
|
57493
57587
|
return repository3 && branch.trim() ? { repository: repository3, branch: branch.trim() } : void 0;
|
|
57494
57588
|
}
|
|
57495
|
-
function storeHead(store, indexFile =
|
|
57589
|
+
function storeHead(store, indexFile = path106.join(bridgeRoot(), "store-snapshot.index")) {
|
|
57496
57590
|
return serialized2(async () => {
|
|
57497
57591
|
if (!await isRepository2(store)) throw new BridgeError(409, "This computer's phren store is not a git repository. Run phren init.");
|
|
57498
|
-
await mkdir26(
|
|
57592
|
+
await mkdir26(path106.dirname(indexFile), { recursive: true, mode: 448 });
|
|
57499
57593
|
const env = { GIT_INDEX_FILE: indexFile };
|
|
57500
57594
|
if (!await lstat31(indexFile).catch(() => void 0)) {
|
|
57501
57595
|
const head = await git5(store, ["rev-parse", "--verify", "--quiet", "HEAD"]).catch(() => "");
|
|
@@ -57520,31 +57614,37 @@ async function storeTree(store, sha) {
|
|
|
57520
57614
|
async function storeBlob(store, sha) {
|
|
57521
57615
|
if (!SHA.test(sha)) throw new BridgeError(400, "Invalid blob sha.");
|
|
57522
57616
|
if ((await git5(store, ["cat-file", "-t", sha]).catch(() => "")).trim() !== "blob") throw new BridgeError(404, "Unknown blob.");
|
|
57523
|
-
const
|
|
57617
|
+
const size = Number((await git5(store, ["cat-file", "-s", sha])).trim());
|
|
57618
|
+
if (size > MAX_FILE) throw new BridgeError(
|
|
57619
|
+
413,
|
|
57620
|
+
"This store file exceeds the phone's 4 MiB limit. Archive or shorten it on the computer, then sync again.",
|
|
57621
|
+
{ code: "store-file-too-large", size, limit: MAX_FILE }
|
|
57622
|
+
);
|
|
57623
|
+
const { stdout } = await exec19("git", ["-C", store, "cat-file", "blob", sha], { encoding: "buffer", maxBuffer: MAX_FILE, timeout: 6e4 });
|
|
57524
57624
|
return { sha, encoding: "base64", content: stdout.toString("base64") };
|
|
57525
57625
|
}
|
|
57526
57626
|
async function storeFile(store, relative3) {
|
|
57527
|
-
const normalized =
|
|
57528
|
-
if (!relative3 || relative3 !== normalized || normalized.startsWith("../") || normalized === ".." ||
|
|
57627
|
+
const normalized = path106.posix.normalize(relative3);
|
|
57628
|
+
if (!relative3 || relative3 !== normalized || normalized.startsWith("../") || normalized === ".." || path106.posix.isAbsolute(normalized) || normalized.split("/").some((part) => part === ".git" || part === "" || part === ".") || /[\0\r\n]/.test(normalized)) {
|
|
57529
57629
|
throw new BridgeError(400, "Invalid store path.");
|
|
57530
57630
|
}
|
|
57531
57631
|
const root = await realpath18(store);
|
|
57532
|
-
let parent =
|
|
57632
|
+
let parent = path106.dirname(path106.join(root, normalized));
|
|
57533
57633
|
for (; ; ) {
|
|
57534
57634
|
const real2 = await realpath18(parent).catch(() => void 0);
|
|
57535
57635
|
if (real2) {
|
|
57536
|
-
if (real2 !== root && !real2.startsWith(root +
|
|
57636
|
+
if (real2 !== root && !real2.startsWith(root + path106.sep)) throw new BridgeError(400, "Invalid store path.");
|
|
57537
57637
|
break;
|
|
57538
57638
|
}
|
|
57539
|
-
parent =
|
|
57639
|
+
parent = path106.dirname(parent);
|
|
57540
57640
|
}
|
|
57541
|
-
const file3 =
|
|
57641
|
+
const file3 = path106.join(root, normalized);
|
|
57542
57642
|
const info = await lstat31(file3).catch(() => void 0);
|
|
57543
57643
|
if (info && !info.isFile()) throw new BridgeError(400, "Invalid store path.");
|
|
57544
57644
|
return file3;
|
|
57545
57645
|
}
|
|
57546
57646
|
async function currentSha(file3) {
|
|
57547
|
-
const content = await
|
|
57647
|
+
const content = await readFile48(file3).catch((error62) => {
|
|
57548
57648
|
if (error62.code === "ENOENT") return null;
|
|
57549
57649
|
throw error62;
|
|
57550
57650
|
});
|
|
@@ -57559,7 +57659,7 @@ function putStoreFile(store, data) {
|
|
|
57559
57659
|
return serialized2(async () => {
|
|
57560
57660
|
const file3 = await storeFile(store, input2.path);
|
|
57561
57661
|
if (await currentSha(file3) !== (input2.sha ?? null)) throw new BridgeError(409, `${input2.path} changed on this computer.`);
|
|
57562
|
-
await mkdir26(
|
|
57662
|
+
await mkdir26(path106.dirname(file3), { recursive: true });
|
|
57563
57663
|
const temporary = `${file3}.phren-${process.pid}-${Date.now()}`;
|
|
57564
57664
|
await writeFile10(temporary, content, { flag: "wx" });
|
|
57565
57665
|
await rename9(temporary, file3);
|
|
@@ -57593,9 +57693,9 @@ init_protocol();
|
|
|
57593
57693
|
// src/bridge/simulators.ts
|
|
57594
57694
|
init_protocol();
|
|
57595
57695
|
import { execFile as execFile21 } from "node:child_process";
|
|
57596
|
-
import { chmod as chmod5, mkdir as mkdir27, readFile as
|
|
57696
|
+
import { chmod as chmod5, mkdir as mkdir27, readFile as readFile49, rename as rename10, stat as stat27, unlink as unlink9, writeFile as writeFile11 } from "node:fs/promises";
|
|
57597
57697
|
import { tmpdir as tmpdir4 } from "node:os";
|
|
57598
|
-
import
|
|
57698
|
+
import path107 from "node:path";
|
|
57599
57699
|
import { createHash as createHash27, randomUUID as randomUUID25 } from "node:crypto";
|
|
57600
57700
|
import { promisify as promisify20 } from "node:util";
|
|
57601
57701
|
var exec20 = promisify20(execFile21);
|
|
@@ -57623,10 +57723,10 @@ async function bootedSimulators() {
|
|
|
57623
57723
|
async function simulatorScreenshot(udid) {
|
|
57624
57724
|
if (!UDID.test(udid)) throw new BridgeError(400, "Invalid simulator identifier.");
|
|
57625
57725
|
if (process.platform !== "darwin") throw new BridgeError(404, "Simulators run on macOS only.");
|
|
57626
|
-
const file3 =
|
|
57726
|
+
const file3 = path107.join(tmpdir4(), `phren-sim-${randomUUID25()}.png`);
|
|
57627
57727
|
try {
|
|
57628
57728
|
await exec20("/usr/bin/xcrun", ["simctl", "io", udid, "screenshot", "--type=png", file3], { timeout: 15e3 });
|
|
57629
|
-
return await
|
|
57729
|
+
return await readFile49(file3);
|
|
57630
57730
|
} catch (error62) {
|
|
57631
57731
|
if (error62 instanceof BridgeError) throw error62;
|
|
57632
57732
|
throw new BridgeError(409, "Couldn't capture that simulator. Is it still booted?");
|
|
@@ -57642,14 +57742,14 @@ function helper() {
|
|
|
57642
57742
|
return building;
|
|
57643
57743
|
}
|
|
57644
57744
|
async function buildHelper() {
|
|
57645
|
-
const dir =
|
|
57646
|
-
const binary =
|
|
57647
|
-
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
|
|
57745
|
+
const dir = path107.join(bridgeRoot(), "native");
|
|
57746
|
+
const binary = path107.join(dir, "simtap");
|
|
57747
|
+
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 readFile49(new URL("./native/simtap.swift", import.meta.url), "utf8");
|
|
57648
57748
|
const digest2 = createHash27("sha256").update(code).digest("hex");
|
|
57649
|
-
const saved = await
|
|
57749
|
+
const saved = await readFile49(binary + ".sha256", "utf8").then(JSON.parse).catch(() => void 0);
|
|
57650
57750
|
if (await stat27(binary).catch(() => void 0) && saved?.sourceSha === digest2) return binary;
|
|
57651
57751
|
await mkdir27(dir, { recursive: true, mode: 448 });
|
|
57652
|
-
const temporary =
|
|
57752
|
+
const temporary = path107.join(dir, `simtap.${randomUUID25()}`), source = temporary + ".swift";
|
|
57653
57753
|
const sidecar = temporary + ".sha256";
|
|
57654
57754
|
try {
|
|
57655
57755
|
await writeFile11(source, code, { mode: 384, flag: "wx" });
|
|
@@ -57657,7 +57757,7 @@ async function buildHelper() {
|
|
|
57657
57757
|
throw new BridgeError(409, "Couldn't build the simulator input helper (needs Xcode's swiftc).");
|
|
57658
57758
|
});
|
|
57659
57759
|
await chmod5(temporary, 448);
|
|
57660
|
-
const binarySha = createHash27("sha256").update(await
|
|
57760
|
+
const binarySha = createHash27("sha256").update(await readFile49(temporary)).digest("hex");
|
|
57661
57761
|
await writeFile11(sidecar, JSON.stringify({ sourceSha: digest2, binarySha }), { mode: 384, flag: "wx" });
|
|
57662
57762
|
await rename10(temporary, binary);
|
|
57663
57763
|
await rename10(sidecar, binary + ".sha256");
|
|
@@ -57675,8 +57775,8 @@ function simtap(name, ...args) {
|
|
|
57675
57775
|
}
|
|
57676
57776
|
async function executeSimtap(name, ...args) {
|
|
57677
57777
|
const binary = await helper();
|
|
57678
|
-
const saved = await
|
|
57679
|
-
const binarySha = createHash27("sha256").update(await
|
|
57778
|
+
const saved = await readFile49(binary + ".sha256", "utf8").then(JSON.parse).catch(() => void 0);
|
|
57779
|
+
const binarySha = createHash27("sha256").update(await readFile49(binary)).digest("hex");
|
|
57680
57780
|
if (!saved || saved.binarySha !== binarySha) throw new BridgeError(409, "Simulator input helper integrity check failed.");
|
|
57681
57781
|
try {
|
|
57682
57782
|
await exec20(binary, [name, ...args], { timeout: 6e4 });
|
|
@@ -57762,7 +57862,7 @@ init_transcripts();
|
|
|
57762
57862
|
init_transcript_index();
|
|
57763
57863
|
init_transcripts();
|
|
57764
57864
|
import { homedir as homedir20, tmpdir as tmpdir5 } from "node:os";
|
|
57765
|
-
import
|
|
57865
|
+
import path108 from "node:path";
|
|
57766
57866
|
init_protocol();
|
|
57767
57867
|
var cache = /* @__PURE__ */ new Map();
|
|
57768
57868
|
var modelCache = /* @__PURE__ */ new Map();
|
|
@@ -57900,7 +58000,7 @@ function describe3(tool, args) {
|
|
|
57900
58000
|
return "";
|
|
57901
58001
|
};
|
|
57902
58002
|
const firstLine = (v) => v.split(/\r?\n/).map((l) => l.trim()).find((l) => l) ?? "";
|
|
57903
|
-
const base = (v) =>
|
|
58003
|
+
const base = (v) => path108.basename(v.split(" \xB7 ")[0].trim()) || "file";
|
|
57904
58004
|
const name = tool.toLowerCase();
|
|
57905
58005
|
let value2;
|
|
57906
58006
|
if (["bash", "shell", "exec_command", "exec", "parallel", "tools", "write_stdin", "container.exec"].includes(name)) {
|
|
@@ -57940,7 +58040,7 @@ init_terminal_text();
|
|
|
57940
58040
|
init_codex_servers();
|
|
57941
58041
|
init_herdr();
|
|
57942
58042
|
import { open as open23 } from "node:fs/promises";
|
|
57943
|
-
import
|
|
58043
|
+
import path109 from "node:path";
|
|
57944
58044
|
init_protocol();
|
|
57945
58045
|
init_terminal();
|
|
57946
58046
|
init_terminal_choice();
|
|
@@ -58001,7 +58101,7 @@ var defaultRenameDeps = {
|
|
|
58001
58101
|
return text4 === void 0 ? void 0 : lastCustomTitle(text4);
|
|
58002
58102
|
},
|
|
58003
58103
|
async codexIndexTitle(thread) {
|
|
58004
|
-
const text4 = await tail(
|
|
58104
|
+
const text4 = await tail(path109.join(codexHome(), "session_index.jsonl"));
|
|
58005
58105
|
return text4 === void 0 ? void 0 : lastIndexedName(text4, thread);
|
|
58006
58106
|
},
|
|
58007
58107
|
sleep: (ms) => new Promise((resolve11) => setTimeout(resolve11, ms)),
|
|
@@ -58088,14 +58188,14 @@ async function renameSession(server, data, deps2 = defaultRenameDeps) {
|
|
|
58088
58188
|
|
|
58089
58189
|
// src/bridge/server-launch.ts
|
|
58090
58190
|
init_transcripts();
|
|
58091
|
-
import { mkdir as mkdir29, readFile as readFile49 } from "node:fs/promises";
|
|
58092
|
-
import path110 from "node:path";
|
|
58093
58191
|
init_zod();
|
|
58094
58192
|
init_home_paths();
|
|
58095
58193
|
init_herdr();
|
|
58096
58194
|
init_terminal();
|
|
58097
58195
|
init_terminal_tmux();
|
|
58098
58196
|
init_limits();
|
|
58197
|
+
import { mkdir as mkdir29, readFile as readFile50 } from "node:fs/promises";
|
|
58198
|
+
import path111 from "node:path";
|
|
58099
58199
|
|
|
58100
58200
|
// src/bridge/launch-worktree.ts
|
|
58101
58201
|
init_zod();
|
|
@@ -58103,7 +58203,7 @@ init_utils_helpers();
|
|
|
58103
58203
|
init_metrics();
|
|
58104
58204
|
import { execFile as execFile22 } from "node:child_process";
|
|
58105
58205
|
import { mkdir as mkdir28, realpath as realpath19, rm as rm14, stat as stat28 } from "node:fs/promises";
|
|
58106
|
-
import
|
|
58206
|
+
import path110 from "node:path";
|
|
58107
58207
|
import { promisify as promisify21 } from "node:util";
|
|
58108
58208
|
init_protocol();
|
|
58109
58209
|
var exec21 = promisify21(execFile22);
|
|
@@ -58132,11 +58232,11 @@ async function createLaunchWorktree(cwd, request9) {
|
|
|
58132
58232
|
if (await git6(root, "show-ref", "--verify", "--quiet", `refs/heads/${branch}`).then(() => true, () => false)) {
|
|
58133
58233
|
throw new BridgeError(409, `A branch named "${branch}" already exists in this repository. Choose another branch name.`);
|
|
58134
58234
|
}
|
|
58135
|
-
const worktree =
|
|
58235
|
+
const worktree = path110.join(root, ".claude", "worktrees", worktreeFolderName(branch));
|
|
58136
58236
|
if (await stat28(worktree).then(() => true, () => false)) {
|
|
58137
58237
|
throw new BridgeError(409, `The folder .claude/worktrees/${worktreeFolderName(branch)} already exists. Choose another branch name.`);
|
|
58138
58238
|
}
|
|
58139
|
-
await mkdir28(
|
|
58239
|
+
await mkdir28(path110.dirname(worktree), { recursive: true });
|
|
58140
58240
|
try {
|
|
58141
58241
|
await git6(root, "worktree", "add", "-b", branch, worktree, head);
|
|
58142
58242
|
} catch (error62) {
|
|
@@ -58144,8 +58244,8 @@ async function createLaunchWorktree(cwd, request9) {
|
|
|
58144
58244
|
throw new BridgeError(409, `Git could not create the worktree${detail ? `: ${detail.replace(/^fatal:\s*/, "")}` : "."}`);
|
|
58145
58245
|
}
|
|
58146
58246
|
const abs = await realpath19(worktree);
|
|
58147
|
-
const inside =
|
|
58148
|
-
const start = inside && !inside.startsWith("..") ?
|
|
58247
|
+
const inside = path110.relative(root, await realpath19(cwd));
|
|
58248
|
+
const start = inside && !inside.startsWith("..") ? path110.join(abs, inside) : abs;
|
|
58149
58249
|
const startDir = await stat28(start).then((value2) => value2.isDirectory(), () => false) ? start : abs;
|
|
58150
58250
|
return {
|
|
58151
58251
|
cwd: startDir,
|
|
@@ -58169,25 +58269,6 @@ init_logger();
|
|
|
58169
58269
|
init_protocol();
|
|
58170
58270
|
var launchKinds = ["codex", "claude", "copilot", "opencode", "phren"];
|
|
58171
58271
|
var plainText = (max) => external_exports.string().min(1).max(max).refine((t) => !/[\x00-\x1f\x7f]/.test(t));
|
|
58172
|
-
async function conductorBrief() {
|
|
58173
|
-
let source;
|
|
58174
|
-
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- `account_usage` (CLI `phren dispatch usage`): every computer\'s agent usage\n merged by account (each Claude login, Codex, OpenCode Go and the rest): percent\n left on each window, when it resets, whether the numbers are fresh, and the\n computers where it is signed in. In core use\n `phren_admin(action: "account_usage")`.\n- `hand_off`: send a prompt to one of those sessions. A busy session queues it\n durably in its Hook. Keep its `deliveryId`; `queued` means waiting, `delivered`\n means confirmed. Check with `hand_off(target|session, computer?, deliveryId,\n status:true)` and no text. Never resend with a new id because it is busy.\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, stalled with an unchanged screen and transcript, 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- `dispatch_report`: workers record `prs`, an array of `{url, repo, branch,\n tests, notes?}`, on their own Hook before ending the turn. The done return\n carries that evidence, and the Hook queues it to the configured integrator.\n In core use `phren_admin(action: "dispatch_report", prs)`.\n- `owner_inbox` (CLI `phren owner-inbox`): list what waits on the owner across\n linked computers, add a title with optional project, or resolve an id with\n optional resolution. In core use `phren_admin(action: "owner_inbox", ...)`.\n Use an item\'s `inboxComputer` as `computer` when resolving a remote item;\n omit it for `local`. Say which computers were unreachable.\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.\nA worker that needs root runs `sudo -A <command>`: its launch sets\n`SUDO_ASKPASS`, and the owner approves the exact command and types the\npassword on the phone. Plain `sudo` fails without a terminal.\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.\nTell every lead the same: a worker started any other way (its own `opencode\nrun` or `codex exec`, a launch script, nohup) has no manifest, so the phone and\nyou cannot see, resume or review it. Workers that exist only as processes do\nnot count as dispatched.\n\nCheck `account_usage` before you dispatch, once per batch. The one hard rule:\nnever dispatch to an account that is `exhausted` (a window at 100%, or\nrefusing requests), until its `availableIn` passes. Low quota is information,\nnot a reason to steer away: `nearLimit` (under 20% left) is still usable, and\nthe owner often wants quota used up before it resets, so an account with quota\nleft that resets soon is a good pick; use it before it resets. For Claude, pass\nthe `account` id the row\'s `computers` list gives for the computer you pick. A\n`stale` row\'s numbers may be out of date, and a window marked `reset` has\nrolled over with no new number yet: say so rather than quoting them. Name the\nchoice in the dispatch line, such as "Desk has the parser checks on Codex,\nusing its last 15% before the week resets tomorrow." When every account is\nexhausted, tell the owner before dispatching. The owner\'s explicit choice of\nharness or account always wins. Usage on `unreachable` and `notLinked`\ncomputers is unknown, not zero.\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?, effort?, permissionMode?, prompt, label)`\nin core. The CLI equivalent is `phren dispatch <computer|anywhere> <project>\n--harness <harness> --label <label> --prompt <brief> [--model <model>] [--effort <effort>]\n[--permission-mode supervised|auto-edits|auto|full-access]`. `permissionMode` sets how the\nworker starts (Claude, Codex and Copilot; not OpenCode). `harness` is codex,\nclaude, opencode or copilot.\nFor release work (merge, publish, deploy, app-store, github-admin), read the\nowner\'s release authority policy first with `authority` in full or\n`phren_admin(action: "authority", project)` in core (CLI: `phren authority show\n<project>`), quote its `line` in the brief, and list the actions in\n`releaseActions`. An ask-first action is refused until the owner confirms it:\nask them, and never confirm or change the policy yourself. The policy only\nrestricts; when a worker\'s own harness still refuses release work, only the\nowner\'s own harness settings can allow it.\n`anywhere` chooses the connected computer with the fewest working agents, and\nskips one whose account for that harness is exhausted. Place\nbriefs sequentially, respecting busy/rate-limit responses. Keep their dispatch\nIDs. Do not send local filesystem paths as remote project names.\n\nConfigure the integrator once with `phren conductor integrator --session <id>\n[--computer <name>]`; list with `phren conductor integrator`, clear with\n`--clear`. A dispatch can override it with `integrator: {computer?, target}`.\nThe integrator\'s full target is bound to that conversation. Workers report\nstructured PR evidence with `dispatch_report(prs)` in full or\n`phren_admin(action:"dispatch_report", prs)` in core before finishing; they do not\nneed direct messaging or a GitHub comment to reach it. Inspect `prs` and\n`integratorDelivery` in receipts and verify the evidence before integration.\n\nFinished worker panes close after their done return is read. Use\n`closeOnFinish:false` (`--keep-open` in the CLI) for a worker you will reuse.\nThe Hook rechecks its ended turn and skips a pane with new work, background\ntasks, queued messages or uncertain delivery. Intentional closes do not return\n`gone`. Reading returns can close panes, so record any follow-up first.\n\nKeep one owner inbox item for each decision or action that waits on the owner.\nNeeds-you returns and blocked prompts appear automatically, even if their\nreturns were read. Add other actions such as restarting the router with\n`owner_inbox(operation:"add", title, project?, id?)` in full or\n`phren_admin(action:"owner_inbox", operation:"add", title, project?, id?)` in\ncore; keep the id on retries.\nResolve an item only once the owner decided or completed the action. Resolution\ndoes not send an answer, approve a prompt, or mark a task complete. Send an\nowner\'s answer separately with queued `hand_off`. A source that stopped waiting\nis retained as `live:false` until resolved; a resolved source stays resolved.\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\nA return with an `approval` is a permission request a worker is waiting on.\nAnswer it with `dispatch_approve` when it is plainly what the brief asked for;\ndeny when unsure and ask the owner. Standing grants already answer `dispatch`\nand `hand_off` requests they cover.\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\nA `stalled` return or `live_sessions` row with `stalled:true` means both the\nscreen and transcript have stopped changing while working. Check it and report\nwhat is known; do not launch a duplicate or interrupt it just because of the flag.\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';
|
|
58175
|
-
else {
|
|
58176
|
-
const here = path110.dirname(fileURLToPath(import.meta.url));
|
|
58177
|
-
for (const candidate of [
|
|
58178
|
-
path110.join(here, "..", "starter", "global", "skills", "conductor", "SKILL.md"),
|
|
58179
|
-
path110.join(here, "..", "..", "starter", "global", "skills", "conductor", "SKILL.md")
|
|
58180
|
-
]) {
|
|
58181
|
-
source = await readFile49(candidate, "utf8").catch(() => void 0);
|
|
58182
|
-
if (source !== void 0) break;
|
|
58183
|
-
}
|
|
58184
|
-
}
|
|
58185
|
-
if (source === void 0) throw new BridgeError(503, "The shipped conductor brief is unavailable. Reinstall Phren Hook.");
|
|
58186
|
-
const match = /^---\r?\n[\s\S]*?\r?\n---\r?\n([\s\S]*)$/.exec(source);
|
|
58187
|
-
const brief = (match?.[1] ?? source).trim();
|
|
58188
|
-
if (!brief) throw new BridgeError(503, "The shipped conductor brief is empty. Reinstall Phren Hook.");
|
|
58189
|
-
return brief;
|
|
58190
|
-
}
|
|
58191
58272
|
function effortArgs(kind, effort) {
|
|
58192
58273
|
if (kind === "claude") return ["--effort", effort];
|
|
58193
58274
|
if (kind === "codex") return ["-c", `model_reasoning_effort=${effort}`];
|
|
@@ -58207,7 +58288,7 @@ async function phrenLaunchArgs(kind, data, store = phrenStoreRoot()) {
|
|
|
58207
58288
|
return [...mode === "chat" ? ["--mode", "chat"] : [], ...resume ? ["--session", resume] : []];
|
|
58208
58289
|
}
|
|
58209
58290
|
async function sessionUsedTools(session, store = phrenStoreRoot()) {
|
|
58210
|
-
const raw = await
|
|
58291
|
+
const raw = await readFile50(path111.join(store, ".sessions", `session-${session}.events.jsonl`), "utf8").catch(() => "");
|
|
58211
58292
|
const withTools = (message) => {
|
|
58212
58293
|
const content = message?.content;
|
|
58213
58294
|
return Array.isArray(content) && content.some((block) => ["tool_use", "tool_result"].includes(String(block?.type)));
|
|
@@ -58235,15 +58316,12 @@ function phrenModelArgs(model) {
|
|
|
58235
58316
|
}
|
|
58236
58317
|
async function prepareConductor(kind, effort, model) {
|
|
58237
58318
|
const brief = await conductorBrief();
|
|
58238
|
-
const
|
|
58239
|
-
await mkdir29(briefDirectory2, { recursive: true, mode: 448 });
|
|
58240
|
-
const briefFile = path110.join(briefDirectory2, "brief.md");
|
|
58241
|
-
if (await readFile49(briefFile, "utf8").catch(() => void 0) !== brief + "\n") await atomic(briefFile, brief + "\n");
|
|
58319
|
+
const briefFile = await ensureConductorBrief(brief);
|
|
58242
58320
|
if (kind === "claude") return [...model ? ["--model", model] : [], "--append-system-prompt-file", briefFile, "--effort", effort];
|
|
58243
58321
|
if (kind === "codex") return [...model ? ["--model", model] : [], "-c", `model_reasoning_effort=${effort}`, "-c", `developer_instructions=${JSON.stringify(brief)}`];
|
|
58244
58322
|
if (kind === "opencode") {
|
|
58245
|
-
const directory =
|
|
58246
|
-
const file3 =
|
|
58323
|
+
const directory = path111.join(process.env.XDG_CONFIG_HOME || path111.join(homeDir(), ".config"), "opencode", "agents");
|
|
58324
|
+
const file3 = path111.join(directory, "conductor.md");
|
|
58247
58325
|
const definition = `---
|
|
58248
58326
|
description: Coordinate the owner's work across agent sessions.
|
|
58249
58327
|
mode: primary
|
|
@@ -58252,7 +58330,7 @@ mode: primary
|
|
|
58252
58330
|
${brief}
|
|
58253
58331
|
`;
|
|
58254
58332
|
await mkdir29(directory, { recursive: true, mode: 448 });
|
|
58255
|
-
if (await
|
|
58333
|
+
if (await readFile50(file3, "utf8").catch(() => void 0) !== definition) await atomic(file3, definition, 420);
|
|
58256
58334
|
return [...model ? ["--model", model] : [], "--agent", "conductor", "--variant", effort];
|
|
58257
58335
|
}
|
|
58258
58336
|
throw new BridgeError(400, "The selected harness cannot run as a conductor.");
|
|
@@ -58379,7 +58457,7 @@ async function stillListed(server, result) {
|
|
|
58379
58457
|
}
|
|
58380
58458
|
async function startSession(server, data, options) {
|
|
58381
58459
|
const role = external_exports.enum(["agent", "conductor"]).default("agent").parse(data.role);
|
|
58382
|
-
const projectDirectory = external_exports.string().min(1).max(4096).refine((t) =>
|
|
58460
|
+
const projectDirectory = external_exports.string().min(1).max(4096).refine((t) => path111.isAbsolute(t) && !/[\x00-\x1f\x7f]/.test(t)).parse(data.cwd);
|
|
58383
58461
|
const worktreeRequest = data.worktree === void 0 || data.worktree === null ? void 0 : launchWorktreeSchema.parse(data.worktree);
|
|
58384
58462
|
if (worktreeRequest && role === "conductor") throw new BridgeError(400, "A conductor works across projects, so it cannot start in a worktree.");
|
|
58385
58463
|
const label2 = plainText(200).parse(data.label);
|
|
@@ -58565,7 +58643,7 @@ async function workspaceAction(server, operation, data) {
|
|
|
58565
58643
|
if (tab && !objects(s.tabs).some((t) => t.tab_id === tab && (!workspace || t.workspace_id === workspace))) throw new BridgeError(409, "The tab changed.");
|
|
58566
58644
|
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.");
|
|
58567
58645
|
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);
|
|
58568
|
-
const cwd = data.cwd === void 0 ? void 0 : external_exports.string().max(4096).refine((t) =>
|
|
58646
|
+
const cwd = data.cwd === void 0 ? void 0 : external_exports.string().max(4096).refine((t) => path111.isAbsolute(t) && !/[\x00-\x1f\x7f]/.test(t)).parse(data.cwd);
|
|
58569
58647
|
if (operation === "create") await terminalProvider().create(server, { workspace, label: label2, cwd });
|
|
58570
58648
|
else if (!workspace && !tab && !pane) throw new BridgeError(400, "Choose a Herdr destination.");
|
|
58571
58649
|
else if (pane && operation === "focus") await terminalProvider().focusPane(server, pane);
|
|
@@ -58686,12 +58764,17 @@ var OVERVIEW_ENRICH_BUDGET_MS = 5e3;
|
|
|
58686
58764
|
var childActivityCache = /* @__PURE__ */ new Map();
|
|
58687
58765
|
async function childActivity(source, session) {
|
|
58688
58766
|
const key3 = `${source}\0${session}`, now = Date.now(), cached3 = childActivityCache.get(key3);
|
|
58689
|
-
if (cached3 && now - cached3.at < CHILD_ACTIVITY_CACHE_MS) return cached3.result;
|
|
58767
|
+
if (cached3 && (cached3.pending || now - cached3.at < CHILD_ACTIVITY_CACHE_MS)) return cached3.result;
|
|
58690
58768
|
const result = childAgentTree(source, session).then((tree) => {
|
|
58691
58769
|
const running2 = runningChildAgents(tree);
|
|
58692
58770
|
return { runningChildren: running2.length, childProviders: [...new Set(running2.map((child) => child.provider))].sort() };
|
|
58693
58771
|
}).catch(() => ({ runningChildren: 0, childProviders: [] }));
|
|
58694
|
-
|
|
58772
|
+
const entry2 = { at: now, pending: true, result };
|
|
58773
|
+
void result.then(() => {
|
|
58774
|
+
entry2.at = Date.now();
|
|
58775
|
+
entry2.pending = false;
|
|
58776
|
+
});
|
|
58777
|
+
childActivityCache.set(key3, entry2);
|
|
58695
58778
|
while (childActivityCache.size > 128) childActivityCache.delete(childActivityCache.keys().next().value);
|
|
58696
58779
|
return result;
|
|
58697
58780
|
}
|
|
@@ -58826,43 +58909,53 @@ function workspacesReader(ctx) {
|
|
|
58826
58909
|
]);
|
|
58827
58910
|
if (expired) return;
|
|
58828
58911
|
if (background) awaited.set(tab, background);
|
|
58829
|
-
markBackground(tab, background);
|
|
58912
|
+
markBackground(tab, (background ?? 0) + (typeof tab.runningChildren === "number" ? tab.runningChildren : 0));
|
|
58830
58913
|
const target = targetSchema.safeParse(tab.target);
|
|
58831
|
-
|
|
58914
|
+
const stall = target.success && agents.length === 1 ? await sessionStalls.observe(target.data, { ...agents[0], agent_status: tab.agentStatus }, async () => background) : {};
|
|
58915
|
+
if (expired) return;
|
|
58916
|
+
Object.assign(tab, stall);
|
|
58832
58917
|
tab.title = title2;
|
|
58833
58918
|
}));
|
|
58834
|
-
|
|
58835
|
-
|
|
58836
|
-
|
|
58837
|
-
|
|
58838
|
-
|
|
58839
|
-
|
|
58840
|
-
|
|
58841
|
-
|
|
58842
|
-
|
|
58843
|
-
|
|
58844
|
-
|
|
58845
|
-
|
|
58846
|
-
|
|
58847
|
-
|
|
58848
|
-
|
|
58849
|
-
|
|
58850
|
-
|
|
58851
|
-
|
|
58852
|
-
|
|
58853
|
-
|
|
58854
|
-
|
|
58855
|
-
|
|
58856
|
-
|
|
58857
|
-
|
|
58858
|
-
|
|
58859
|
-
|
|
58860
|
-
|
|
58861
|
-
|
|
58862
|
-
|
|
58863
|
-
|
|
58864
|
-
|
|
58865
|
-
|
|
58919
|
+
const eachTab = (read) => {
|
|
58920
|
+
let next = 0;
|
|
58921
|
+
return Promise.all(Array.from({ length: Math.min(4, tabs.length) }, async () => {
|
|
58922
|
+
while (!expired && next < tabs.length) await read(tabs[next++]);
|
|
58923
|
+
}));
|
|
58924
|
+
};
|
|
58925
|
+
const identified = (group, tab) => {
|
|
58926
|
+
const agents = agentsByTab.get(JSON.stringify([group.id, tab.id])) ?? [];
|
|
58927
|
+
if (agents.length !== 1 || !provider.safeParse(agents[0].agent).success) return void 0;
|
|
58928
|
+
const session = chatStates.get(agents[0])?.sessionId;
|
|
58929
|
+
return typeof session === "string" ? { source: agents[0].agent, session, pane: agents[0] } : void 0;
|
|
58930
|
+
};
|
|
58931
|
+
const enrich = Promise.all([
|
|
58932
|
+
records,
|
|
58933
|
+
eachTab(async ({ tab }) => {
|
|
58934
|
+
if (!modules.has("git") || typeof tab.cwd !== "string" || !tab.agent) return;
|
|
58935
|
+
const branch = await repositoryBranch(tab.cwd);
|
|
58936
|
+
if (!expired && branch !== void 0) tab.branch = branch;
|
|
58937
|
+
}),
|
|
58938
|
+
eachTab(async ({ group, tab }) => {
|
|
58939
|
+
const identity = identified(group, tab);
|
|
58940
|
+
if (!identity) return;
|
|
58941
|
+
const children = await childActivity(identity.source, identity.session);
|
|
58942
|
+
if (expired) return;
|
|
58943
|
+
Object.assign(tab, children);
|
|
58944
|
+
markBackground(tab, (awaited.get(tab) ?? 0) + children.runningChildren);
|
|
58945
|
+
}),
|
|
58946
|
+
eachTab(async ({ group, tab }) => {
|
|
58947
|
+
const identity = identified(group, tab);
|
|
58948
|
+
if (!identity) return;
|
|
58949
|
+
const model = await currentModel(identity.source, identity.session).catch(() => void 0);
|
|
58950
|
+
if (!expired && model) tab.model = model;
|
|
58951
|
+
}),
|
|
58952
|
+
eachTab(async ({ group, tab }) => {
|
|
58953
|
+
const identity = identified(group, tab);
|
|
58954
|
+
if (!identity || identity.pane.agent_status !== "working") return;
|
|
58955
|
+
const step2 = await currentStep(identity.source, identity.session).catch(() => void 0);
|
|
58956
|
+
if (!expired && step2) tab.currentStep = step2;
|
|
58957
|
+
})
|
|
58958
|
+
]);
|
|
58866
58959
|
await Promise.race([enrich, budget]);
|
|
58867
58960
|
expired = true;
|
|
58868
58961
|
clearTimeout(timer);
|
|
@@ -59045,7 +59138,7 @@ function createRouteHandler(ctx) {
|
|
|
59045
59138
|
case "/v1/files/range": {
|
|
59046
59139
|
let root;
|
|
59047
59140
|
if (url2.searchParams.get("scope") === "uploads") {
|
|
59048
|
-
root =
|
|
59141
|
+
root = path112.join(bridgeRoot(), "uploads");
|
|
59049
59142
|
} else if (url2.searchParams.has("session")) {
|
|
59050
59143
|
const target = targetFromURL(url2), pane = await validateTarget(target);
|
|
59051
59144
|
const cwd = await gitRepository(pane, target, url2.searchParams.get("child") ?? void 0, url2.searchParams.get("worktree") ?? void 0);
|
|
@@ -60165,12 +60258,12 @@ init_codex_servers();
|
|
|
60165
60258
|
init_home_paths();
|
|
60166
60259
|
init_logger();
|
|
60167
60260
|
init_protocol();
|
|
60168
|
-
import { readFile as
|
|
60169
|
-
import
|
|
60261
|
+
import { readFile as readFile51 } from "node:fs/promises";
|
|
60262
|
+
import path113 from "node:path";
|
|
60170
60263
|
var REFRESH_AFTER_MS = 6 * 864e5;
|
|
60171
|
-
async function lastCodexRefresh(file3 =
|
|
60264
|
+
async function lastCodexRefresh(file3 = path113.join(codexHome(), "auth.json")) {
|
|
60172
60265
|
try {
|
|
60173
|
-
const auth = object2(JSON.parse(await
|
|
60266
|
+
const auth = object2(JSON.parse(await readFile51(file3, "utf8")));
|
|
60174
60267
|
if (!object2(auth.tokens).refresh_token) return void 0;
|
|
60175
60268
|
const at = Date.parse(String(auth.last_refresh ?? ""));
|
|
60176
60269
|
return Number.isFinite(at) ? at : 0;
|
|
@@ -60224,9 +60317,9 @@ async function serve(version3, options = {}) {
|
|
|
60224
60317
|
await mkdir30(root, { recursive: true, mode: 448 });
|
|
60225
60318
|
await chmod6(root, 448);
|
|
60226
60319
|
let computerID2;
|
|
60227
|
-
const identityFile =
|
|
60320
|
+
const identityFile = path114.join(root, "computer-id");
|
|
60228
60321
|
try {
|
|
60229
|
-
computerID2 = (await
|
|
60322
|
+
computerID2 = (await readFile52(identityFile, "utf8")).trim();
|
|
60230
60323
|
} catch {
|
|
60231
60324
|
computerID2 = randomUUID26();
|
|
60232
60325
|
await writeFile12(identityFile, computerID2, { flag: "wx", mode: 384 });
|
|
@@ -60344,7 +60437,7 @@ async function serve(version3, options = {}) {
|
|
|
60344
60437
|
if (codeReindexer) agentHooks.changes.onRecord = (files) => codeReindexer.record(files);
|
|
60345
60438
|
function gatewayTiming() {
|
|
60346
60439
|
try {
|
|
60347
|
-
const parsed = JSON.parse(readFileSync37(
|
|
60440
|
+
const parsed = JSON.parse(readFileSync37(path114.join(root, "gateway.json"), "utf8"));
|
|
60348
60441
|
if (typeof parsed.ms === "number" && Number.isFinite(parsed.ms) && parsed.ms >= 0) return Math.round(parsed.ms);
|
|
60349
60442
|
} catch {
|
|
60350
60443
|
}
|
|
@@ -60390,7 +60483,7 @@ async function serve(version3, options = {}) {
|
|
|
60390
60483
|
}
|
|
60391
60484
|
const stopRetention = modules.has("git") ? await startChangeRetention() : () => {
|
|
60392
60485
|
};
|
|
60393
|
-
if (modules.has("git")) await rm15(
|
|
60486
|
+
if (modules.has("git")) await rm15(path114.join(root, "changes-scratch"), { recursive: true, force: true });
|
|
60394
60487
|
const streams = transcriptStreams({ modules, agentHooks, codexQuestions, sideQuestions, settingsSwitcher, info, activeCapabilities });
|
|
60395
60488
|
const { stream } = streams;
|
|
60396
60489
|
const overview = overviewStream({
|
|
@@ -60576,9 +60669,9 @@ init_protocol();
|
|
|
60576
60669
|
init_profile_store();
|
|
60577
60670
|
init_phren_paths();
|
|
60578
60671
|
import { execFile as execFile23 } from "node:child_process";
|
|
60579
|
-
import { readFile as
|
|
60672
|
+
import { readFile as readFile53 } from "node:fs/promises";
|
|
60580
60673
|
import { homedir as homedir21, hostname as hostname13, userInfo as userInfo5 } from "node:os";
|
|
60581
|
-
import
|
|
60674
|
+
import path115 from "node:path";
|
|
60582
60675
|
import { promisify as promisify22 } from "node:util";
|
|
60583
60676
|
init_protocol();
|
|
60584
60677
|
var exec22 = promisify22(execFile23);
|
|
@@ -60625,11 +60718,11 @@ async function probe2(host) {
|
|
|
60625
60718
|
return computerId ? { host, computerId, user: field("user") ?? "", client: field("client") } : void 0;
|
|
60626
60719
|
}
|
|
60627
60720
|
async function discoverComputers(options = {}) {
|
|
60628
|
-
const config3 = options.sshConfig ?? await
|
|
60721
|
+
const config3 = options.sshConfig ?? await readFile53(path115.join(homedir21(), ".ssh", "config"), "utf8").catch(() => "");
|
|
60629
60722
|
const store = options.store !== void 0 ? options.store : findPhrenPath();
|
|
60630
60723
|
const machines = store ? listMachines(store) : void 0;
|
|
60631
60724
|
const { peers } = await optionalHookPeers();
|
|
60632
|
-
const own2 = (await
|
|
60725
|
+
const own2 = (await readFile53(path115.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
|
|
60633
60726
|
const known2 = new Set([...localNames(), ...peers.flatMap((peer) => [peer.name, peer.address])].map(computerLabel));
|
|
60634
60727
|
const candidates = [.../* @__PURE__ */ new Set([...sshConfigHosts(config3), ...machines?.ok ? Object.keys(machines.data) : []])].filter((host) => !known2.has(computerLabel(host))).slice(0, 32);
|
|
60635
60728
|
const [found, peerIds] = await Promise.all([
|
|
@@ -60651,7 +60744,7 @@ function slugName(value2) {
|
|
|
60651
60744
|
async function linkComputer(host, options = {}) {
|
|
60652
60745
|
const remote = await probe2(host);
|
|
60653
60746
|
if (!remote) throw new BridgeError(409, `${host} answers over ssh but Phren Hook is not installed there. Run phren bridge install on it first.`);
|
|
60654
|
-
const own2 = (await
|
|
60747
|
+
const own2 = (await readFile53(path115.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
|
|
60655
60748
|
if (remote.computerId === own2) throw new BridgeError(409, `${host} is this computer.`);
|
|
60656
60749
|
const name = computerName.parse(options.name ?? slugName(host));
|
|
60657
60750
|
const as = computerName.parse(options.as ?? slugName(hostname13()));
|
|
@@ -60659,7 +60752,7 @@ async function linkComputer(host, options = {}) {
|
|
|
60659
60752
|
if (!backAddress) throw new BridgeError(409, `${host} did not report this computer's address; pass --back-address.`);
|
|
60660
60753
|
const resolved = Object.fromEntries((await exec22("ssh", ["-G", "--", host], { timeout: 5e3 })).stdout.split("\n").map((line) => line.split(" ")).filter((parts) => parts.length >= 2).map(([key3, ...rest]) => [key3, rest.join(" ")]));
|
|
60661
60754
|
const remoteHostKey = publicComputerKey((await ssh(host, "cat /etc/ssh/ssh_host_ed25519_key.pub")).trim().split(/\s+/).slice(0, 2).join(" "));
|
|
60662
|
-
const localHostKey = publicComputerKey((await
|
|
60755
|
+
const localHostKey = publicComputerKey((await readFile53("/etc/ssh/ssh_host_ed25519_key.pub", "utf8")).trim().split(/\s+/).slice(0, 2).join(" "));
|
|
60663
60756
|
const remoteLine = (await ssh(host, `${REMOTE_PATH} phren bridge enroll-computer ${name}`)).trim();
|
|
60664
60757
|
await ssh(host, `f=$(mktemp) && cat > "$f" && ${REMOTE_PATH} phren bridge enroll-computer ${as} --accept "$f"; s=$?; rm -f "$f"; exit $s`, await enrollComputer(as));
|
|
60665
60758
|
await acceptComputer(name, remoteLine);
|
|
@@ -60695,7 +60788,7 @@ async function runBridge(args, version3) {
|
|
|
60695
60788
|
case "enroll-computer": {
|
|
60696
60789
|
if (args.length === 2) console.log(await enrollComputer(args[1]));
|
|
60697
60790
|
else if (args.length === 4 && args[2] === "--accept") {
|
|
60698
|
-
await acceptComputer(args[1], await
|
|
60791
|
+
await acceptComputer(args[1], await readFile54(args[3], "utf8"));
|
|
60699
60792
|
console.log(`Enrolled ${args[1]} for Phren Hook.`);
|
|
60700
60793
|
} else throw new Error("Usage: phren bridge enroll-computer <name> [--accept <public-key-file>]");
|
|
60701
60794
|
break;
|
|
@@ -60834,7 +60927,7 @@ async function runBridge(args, version3) {
|
|
|
60834
60927
|
break;
|
|
60835
60928
|
}
|
|
60836
60929
|
const readModels = async (source) => {
|
|
60837
|
-
const rows = JSON.parse(await
|
|
60930
|
+
const rows = JSON.parse(await readFile54(fixture, "utf8"));
|
|
60838
60931
|
return Array.isArray(rows[source]) ? rows[source] : [];
|
|
60839
60932
|
};
|
|
60840
60933
|
const emptyUsage = (source) => ({ source, windows: [] });
|
|
@@ -60944,7 +61037,7 @@ async function readSecret(prompt) {
|
|
|
60944
61037
|
// src/bridge/hook-main.ts
|
|
60945
61038
|
init_utils_helpers();
|
|
60946
61039
|
Object.assign(process.env, nonInteractiveGitEnv());
|
|
60947
|
-
runBridge(process.argv.slice(2), "0.3.
|
|
61040
|
+
runBridge(process.argv.slice(2), "0.3.23").then((code) => {
|
|
60948
61041
|
process.exitCode = code;
|
|
60949
61042
|
}).catch((error62) => {
|
|
60950
61043
|
console.error(error62 instanceof Error ? error62.message : "Phren Hook failed.");
|