@phren/cli 0.3.8 → 0.3.9
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/claude-question-dialog.js +8 -4
- package/dist/bridge/codex-binary.d.ts +11 -0
- package/dist/bridge/codex-binary.js +58 -0
- package/dist/bridge/models.js +2 -1
- package/dist/bridge/questions.d.ts +4 -2
- package/dist/bridge/questions.js +12 -5
- package/dist/bridge/usage.js +2 -1
- package/dist/bridge-hook.mjs +391 -342
- package/package.json +1 -1
package/dist/bridge-hook.mjs
CHANGED
|
@@ -268,10 +268,10 @@ function mergeDefs(...defs) {
|
|
|
268
268
|
function cloneDef(schema) {
|
|
269
269
|
return mergeDefs(schema._zod.def);
|
|
270
270
|
}
|
|
271
|
-
function getElementAtPath(obj,
|
|
272
|
-
if (!
|
|
271
|
+
function getElementAtPath(obj, path86) {
|
|
272
|
+
if (!path86)
|
|
273
273
|
return obj;
|
|
274
|
-
return
|
|
274
|
+
return path86.reduce((acc, key2) => acc?.[key2], obj);
|
|
275
275
|
}
|
|
276
276
|
function promiseAllObject(promisesObj) {
|
|
277
277
|
const keys = Object.keys(promisesObj);
|
|
@@ -530,11 +530,11 @@ function explicitlyAborted(x, startIndex = 0) {
|
|
|
530
530
|
}
|
|
531
531
|
return false;
|
|
532
532
|
}
|
|
533
|
-
function prefixIssues(
|
|
533
|
+
function prefixIssues(path86, 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(path86);
|
|
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, path86 = []) => {
|
|
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 }, [...path86, ...issue2.path]));
|
|
1062
1062
|
} else if (issue2.code === "invalid_key") {
|
|
1063
|
-
processError({ issues: issue2.issues }, [...
|
|
1063
|
+
processError({ issues: issue2.issues }, [...path86, ...issue2.path]);
|
|
1064
1064
|
} else if (issue2.code === "invalid_element") {
|
|
1065
|
-
processError({ issues: issue2.issues }, [...
|
|
1065
|
+
processError({ issues: issue2.issues }, [...path86, ...issue2.path]);
|
|
1066
1066
|
} else {
|
|
1067
|
-
const fullpath = [...
|
|
1067
|
+
const fullpath = [...path86, ...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, path86 = []) => {
|
|
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 }, [...path86, ...issue2.path]));
|
|
1111
1111
|
} else if (issue2.code === "invalid_key") {
|
|
1112
|
-
processError({ issues: issue2.issues }, [...
|
|
1112
|
+
processError({ issues: issue2.issues }, [...path86, ...issue2.path]);
|
|
1113
1113
|
} else if (issue2.code === "invalid_element") {
|
|
1114
|
-
processError({ issues: issue2.issues }, [...
|
|
1114
|
+
processError({ issues: issue2.issues }, [...path86, ...issue2.path]);
|
|
1115
1115
|
} else {
|
|
1116
|
-
const fullpath = [...
|
|
1116
|
+
const fullpath = [...path86, ...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 path86 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
|
|
1156
|
+
for (const seg of path86) {
|
|
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 path86 = ref.slice(1).split("/").filter(Boolean);
|
|
19153
|
+
if (path86.length === 0) {
|
|
19154
19154
|
return ctx.rootSchema;
|
|
19155
19155
|
}
|
|
19156
19156
|
const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
|
|
19157
|
-
if (
|
|
19158
|
-
const key2 =
|
|
19157
|
+
if (path86[0] === defsKey) {
|
|
19158
|
+
const key2 = path86[1] === void 0 ? void 0 : decodeJSONPointerSegment(path86[1]);
|
|
19159
19159
|
if (!key2 || !ctx.defs[key2]) {
|
|
19160
19160
|
throw new Error(`Reference not found: ${ref}`);
|
|
19161
19161
|
}
|
|
@@ -28317,7 +28317,7 @@ var init_package_metadata = __esm({
|
|
|
28317
28317
|
__dirname = path24.dirname(fileURLToPath2(import.meta.url));
|
|
28318
28318
|
ROOT = path24.join(__dirname, "..");
|
|
28319
28319
|
PACKAGE_JSON_PATH = path24.join(ROOT, "package.json");
|
|
28320
|
-
BUNDLED_VERSION = true ? "0.3.
|
|
28320
|
+
BUNDLED_VERSION = true ? "0.3.9" : "0.0.0";
|
|
28321
28321
|
PACKAGE_JSON = readPackageJson();
|
|
28322
28322
|
PACKAGE_NAME = PACKAGE_JSON.name || "phren";
|
|
28323
28323
|
VERSION = PACKAGE_JSON.version || BUNDLED_VERSION;
|
|
@@ -32603,6 +32603,7 @@ async function answerClaudeQuestionDialog(io, questions, answers, options = {})
|
|
|
32603
32603
|
await sleep3(120);
|
|
32604
32604
|
}
|
|
32605
32605
|
};
|
|
32606
|
+
const ANSWERED_MS = 8e3;
|
|
32606
32607
|
const initial = await settle2((screen) => screen);
|
|
32607
32608
|
if (!initial) throw changed("The terminal is not showing Claude's question.");
|
|
32608
32609
|
if (initial.tabs.length !== questions.length) throw changed("The terminal is asking a different set of questions.");
|
|
@@ -32639,7 +32640,7 @@ async function answerClaudeQuestionDialog(io, questions, answers, options = {})
|
|
|
32639
32640
|
} else {
|
|
32640
32641
|
await io.keys([String(screen.options[answer.options[0]].number)]);
|
|
32641
32642
|
}
|
|
32642
|
-
if (!await settle2(leaves(index2))) throw changed("The terminal did not take the answer.");
|
|
32643
|
+
if (!await settle2(leaves(index2), ANSWERED_MS)) throw changed("The terminal did not take the answer.");
|
|
32643
32644
|
continue;
|
|
32644
32645
|
}
|
|
32645
32646
|
const rows = [...screen.options, ...screen.other ? [screen.other] : []];
|
|
@@ -32666,10 +32667,10 @@ async function answerClaudeQuestionDialog(io, questions, answers, options = {})
|
|
|
32666
32667
|
} else {
|
|
32667
32668
|
await io.keys(screen.other && screen.cursor === screen.other.number ? ["up", "tab"] : ["tab"]);
|
|
32668
32669
|
}
|
|
32669
|
-
if (!await settle2(leaves(index2))) throw changed("The terminal did not move past the question.");
|
|
32670
|
+
if (!await settle2(leaves(index2), ANSWERED_MS)) throw changed("The terminal did not move past the question.");
|
|
32670
32671
|
}
|
|
32671
32672
|
if (!submit) return;
|
|
32672
|
-
const review = await settle2((value2) => value2?.kind === "review" ? value2 : value2 === void 0 ? "gone" : void 0);
|
|
32673
|
+
const review = await settle2((value2) => value2?.kind === "review" ? value2 : value2 === void 0 ? "gone" : void 0, ANSWERED_MS);
|
|
32673
32674
|
if (review === "gone") return;
|
|
32674
32675
|
if (!review) throw changed("The terminal did not reach the review of the answers.");
|
|
32675
32676
|
const expected = questions.map((question2) => normalize(question2.question));
|
|
@@ -32677,7 +32678,7 @@ async function answerClaudeQuestionDialog(io, questions, answers, options = {})
|
|
|
32677
32678
|
throw changed("Not every question has an answer in the terminal.");
|
|
32678
32679
|
}
|
|
32679
32680
|
await io.keys(["1"]);
|
|
32680
|
-
if (await settle2((value2) => value2 === void 0 ? "gone" : void 0) !== "gone") throw changed("The terminal did not submit the answers.");
|
|
32681
|
+
if (await settle2((value2) => value2 === void 0 ? "gone" : void 0, ANSWERED_MS) !== "gone") throw changed("The terminal did not submit the answers.");
|
|
32681
32682
|
}
|
|
32682
32683
|
var TAB_BAR, ROW, NEXT, normalize, changed, typedKeys;
|
|
32683
32684
|
var init_claude_question_dialog = __esm({
|
|
@@ -34268,11 +34269,11 @@ __export(agent_package_exports, {
|
|
|
34268
34269
|
import { execFileSync as execFileSync4, spawn as spawn4 } from "node:child_process";
|
|
34269
34270
|
import * as fs24 from "node:fs";
|
|
34270
34271
|
import { createRequire } from "node:module";
|
|
34271
|
-
import * as
|
|
34272
|
+
import * as path47 from "node:path";
|
|
34272
34273
|
import { fileURLToPath as fileURLToPath4 } from "node:url";
|
|
34273
34274
|
function readManifest(directory) {
|
|
34274
34275
|
try {
|
|
34275
|
-
return JSON.parse(fs24.readFileSync(
|
|
34276
|
+
return JSON.parse(fs24.readFileSync(path47.join(directory, "package.json"), "utf8"));
|
|
34276
34277
|
} catch {
|
|
34277
34278
|
return void 0;
|
|
34278
34279
|
}
|
|
@@ -34282,15 +34283,15 @@ function agentPackageAt(directory, source) {
|
|
|
34282
34283
|
if (manifest?.name !== "@phren/agent") return void 0;
|
|
34283
34284
|
const relative3 = typeof manifest.bin === "string" ? manifest.bin : manifest.bin?.["phren-agent"];
|
|
34284
34285
|
if (!relative3) return void 0;
|
|
34285
|
-
const bin =
|
|
34286
|
+
const bin = path47.join(directory, relative3);
|
|
34286
34287
|
return fs24.existsSync(bin) ? { directory, bin, version: manifest.version, source } : void 0;
|
|
34287
34288
|
}
|
|
34288
34289
|
function workspaceDirectory() {
|
|
34289
|
-
let directory =
|
|
34290
|
+
let directory = path47.dirname(fileURLToPath4(import.meta.url));
|
|
34290
34291
|
for (let depth = 0; depth < 8; depth++) {
|
|
34291
|
-
const candidate =
|
|
34292
|
-
if (fs24.existsSync(
|
|
34293
|
-
const parent =
|
|
34292
|
+
const candidate = path47.join(directory, "packages", "agent");
|
|
34293
|
+
if (fs24.existsSync(path47.join(candidate, "package.json"))) return candidate;
|
|
34294
|
+
const parent = path47.dirname(directory);
|
|
34294
34295
|
if (parent === directory) break;
|
|
34295
34296
|
directory = parent;
|
|
34296
34297
|
}
|
|
@@ -34298,7 +34299,7 @@ function workspaceDirectory() {
|
|
|
34298
34299
|
}
|
|
34299
34300
|
function resolvedDirectory() {
|
|
34300
34301
|
try {
|
|
34301
|
-
return
|
|
34302
|
+
return path47.dirname(createRequire(import.meta.url).resolve("@phren/agent/package.json"));
|
|
34302
34303
|
} catch {
|
|
34303
34304
|
return void 0;
|
|
34304
34305
|
}
|
|
@@ -34307,7 +34308,7 @@ function globalDirectory() {
|
|
|
34307
34308
|
try {
|
|
34308
34309
|
const options = { encoding: "utf8", timeout: 1e4, stdio: ["ignore", "pipe", "ignore"] };
|
|
34309
34310
|
const root = (process.platform === "win32" ? execFileSync4("npm.cmd", ["root", "-g"], { ...options, shell: true }) : execFileSync4("npm", ["root", "-g"], options)).trim();
|
|
34310
|
-
return root ?
|
|
34311
|
+
return root ? path47.join(root, "@phren", "agent") : void 0;
|
|
34311
34312
|
} catch {
|
|
34312
34313
|
return void 0;
|
|
34313
34314
|
}
|
|
@@ -34446,7 +34447,7 @@ var init_audit = __esm({
|
|
|
34446
34447
|
|
|
34447
34448
|
// src/governance/activity.ts
|
|
34448
34449
|
import * as fs25 from "fs";
|
|
34449
|
-
import * as
|
|
34450
|
+
import * as path57 from "path";
|
|
34450
34451
|
function clampSnippet(snippet) {
|
|
34451
34452
|
if (!snippet) return void 0;
|
|
34452
34453
|
const flat = snippet.replace(/\s+/g, " ").trim();
|
|
@@ -34457,7 +34458,7 @@ function recordLookupEvents(phrenPath, events) {
|
|
|
34457
34458
|
if (!events.length) return;
|
|
34458
34459
|
const logPath = lookupEventsLogFile(phrenPath);
|
|
34459
34460
|
try {
|
|
34460
|
-
fs25.mkdirSync(
|
|
34461
|
+
fs25.mkdirSync(path57.dirname(logPath), { recursive: true });
|
|
34461
34462
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
34462
34463
|
const lines = events.map(
|
|
34463
34464
|
(e) => JSON.stringify({
|
|
@@ -34742,7 +34743,7 @@ var init_metadata = __esm({
|
|
|
34742
34743
|
|
|
34743
34744
|
// src/governance/policy.ts
|
|
34744
34745
|
import * as fs26 from "fs";
|
|
34745
|
-
import * as
|
|
34746
|
+
import * as path58 from "path";
|
|
34746
34747
|
function assessSyncOutage(sync, nowMs = Date.now()) {
|
|
34747
34748
|
const consecutiveFailures = sync?.consecutiveFailures ?? 0;
|
|
34748
34749
|
const failingNow = sync?.lastPushStatus !== void 0 && FAILED_PUSH_STATUSES.has(sync.lastPushStatus);
|
|
@@ -34879,7 +34880,7 @@ function normalizeIndexPolicy(data) {
|
|
|
34879
34880
|
function readJsonFile(filePath, fallback) {
|
|
34880
34881
|
try {
|
|
34881
34882
|
if (!fs26.existsSync(filePath)) return fallback;
|
|
34882
|
-
const basename12 =
|
|
34883
|
+
const basename12 = path58.basename(filePath);
|
|
34883
34884
|
const schema = GOVERNANCE_FILE_SCHEMAS[basename12];
|
|
34884
34885
|
if (schema && !validateGovernanceJson(filePath, schema)) {
|
|
34885
34886
|
debugLog(`readJsonFile: ${filePath} failed validation, using defaults`);
|
|
@@ -35316,7 +35317,7 @@ import * as fs17 from "node:fs";
|
|
|
35316
35317
|
import * as path25 from "node:path";
|
|
35317
35318
|
var core = (names) => names.map((name) => ({ name, profiles: ["core", "full"] }));
|
|
35318
35319
|
var full = (names) => names.map((name) => ({ name, profiles: ["full"] }));
|
|
35319
|
-
var routes = (method, paths) => paths.map((
|
|
35320
|
+
var routes = (method, paths) => paths.map((path86) => ({ method, path: path86 }));
|
|
35320
35321
|
var BUILTIN_MODULES = [
|
|
35321
35322
|
{
|
|
35322
35323
|
schemaVersion: 1,
|
|
@@ -35839,7 +35840,7 @@ import { chmod as chmod5, lstat as lstat20, mkdir as mkdir21, readFile as readFi
|
|
|
35839
35840
|
import { readFileSync as readFileSync32 } from "node:fs";
|
|
35840
35841
|
import { createServer as createServer2 } from "node:http";
|
|
35841
35842
|
import { cpus, hostname as hostname9, loadavg } from "node:os";
|
|
35842
|
-
import
|
|
35843
|
+
import path84 from "node:path";
|
|
35843
35844
|
|
|
35844
35845
|
// ../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/wrapper.mjs
|
|
35845
35846
|
var import_stream = __toESM(require_stream(), 1);
|
|
@@ -38404,7 +38405,7 @@ var CodeRoutes = class {
|
|
|
38404
38405
|
const project = projectSchema.parse(projectValue ?? "");
|
|
38405
38406
|
const { codeDatabasePath } = await requireCodePackage(this.store);
|
|
38406
38407
|
const file2 = codeDatabasePath(this.store, project);
|
|
38407
|
-
await Promise.all([file2, `${file2}-journal`, `${file2}-wal`, `${file2}-shm`].map((
|
|
38408
|
+
await Promise.all([file2, `${file2}-journal`, `${file2}-wal`, `${file2}-shm`].map((path86) => rm4(path86, { force: true })));
|
|
38408
38409
|
return { project, disabled: true };
|
|
38409
38410
|
}
|
|
38410
38411
|
async reindex(projectValue) {
|
|
@@ -38701,13 +38702,13 @@ init_logger();
|
|
|
38701
38702
|
init_project_config();
|
|
38702
38703
|
import { randomUUID as randomUUID9 } from "node:crypto";
|
|
38703
38704
|
import { lstat as lstat12, mkdir as mkdir12, readFile as readFile21, readdir as readdir10, realpath as realpath10, stat as stat15 } from "node:fs/promises";
|
|
38704
|
-
import
|
|
38705
|
+
import path51 from "node:path";
|
|
38705
38706
|
|
|
38706
38707
|
// src/bridge/computers.ts
|
|
38707
38708
|
import { execFile as execFile9 } from "node:child_process";
|
|
38708
38709
|
import { chmod as chmod3, lstat as lstat10, mkdir as mkdir11, mkdtemp as mkdtemp2, readFile as readFile19, rename as rename6, rm as rm5, writeFile as writeFile5 } from "node:fs/promises";
|
|
38709
38710
|
import { homedir as homedir14 } from "node:os";
|
|
38710
|
-
import
|
|
38711
|
+
import path49 from "node:path";
|
|
38711
38712
|
import { promisify as promisify8 } from "node:util";
|
|
38712
38713
|
|
|
38713
38714
|
// src/bridge/install.ts
|
|
@@ -38723,10 +38724,53 @@ import { execFile as execFile7, spawn as spawn2 } from "node:child_process";
|
|
|
38723
38724
|
import { createHash as createHash9 } from "node:crypto";
|
|
38724
38725
|
import { lstat as lstat8, open as open9, readFile as readFile17, readdir as readdir9, realpath as realpath9, stat as stat14 } from "node:fs/promises";
|
|
38725
38726
|
import { homedir as homedir11 } from "node:os";
|
|
38726
|
-
import
|
|
38727
|
+
import path45 from "node:path";
|
|
38727
38728
|
import { promisify as promisify6 } from "node:util";
|
|
38729
|
+
|
|
38730
|
+
// src/bridge/codex-binary.ts
|
|
38731
|
+
import { accessSync as accessSync2, closeSync as closeSync2, constants as constants3, openSync as openSync2, readSync, statSync as statSync12 } from "node:fs";
|
|
38732
|
+
import path44 from "node:path";
|
|
38733
|
+
function codexExecutable(env = process.env) {
|
|
38734
|
+
if (process.platform === "win32") return "codex";
|
|
38735
|
+
for (const directory of (env.PATH ?? "").split(path44.delimiter)) {
|
|
38736
|
+
if (!path44.isAbsolute(directory)) continue;
|
|
38737
|
+
const candidate = path44.join(directory, "codex");
|
|
38738
|
+
if (!executable(candidate)) continue;
|
|
38739
|
+
const wrapped = phrenWrapperTarget(candidate);
|
|
38740
|
+
if (wrapped === void 0) return candidate;
|
|
38741
|
+
if (wrapped && executable(wrapped)) return wrapped;
|
|
38742
|
+
}
|
|
38743
|
+
return "codex";
|
|
38744
|
+
}
|
|
38745
|
+
function executable(file2) {
|
|
38746
|
+
try {
|
|
38747
|
+
return statSync12(file2).isFile() && (accessSync2(file2, constants3.X_OK), true);
|
|
38748
|
+
} catch {
|
|
38749
|
+
return false;
|
|
38750
|
+
}
|
|
38751
|
+
}
|
|
38752
|
+
function phrenWrapperTarget(file2) {
|
|
38753
|
+
let head = "";
|
|
38754
|
+
try {
|
|
38755
|
+
const fd = openSync2(file2, "r");
|
|
38756
|
+
try {
|
|
38757
|
+
const buffer = Buffer.alloc(4096);
|
|
38758
|
+
head = buffer.subarray(0, readSync(fd, buffer, 0, buffer.length, 0)).toString("utf8");
|
|
38759
|
+
} finally {
|
|
38760
|
+
closeSync2(fd);
|
|
38761
|
+
}
|
|
38762
|
+
} catch {
|
|
38763
|
+
return void 0;
|
|
38764
|
+
}
|
|
38765
|
+
if (!head.startsWith("#!/bin/sh") || !head.includes("phren wrapper error:")) return void 0;
|
|
38766
|
+
const match = /^REAL_BIN='((?:[^']|'\\'')*)'$/m.exec(head);
|
|
38767
|
+
const target = match?.[1].replace(/'\\''/g, "'");
|
|
38768
|
+
return target && path44.isAbsolute(target) ? target : "";
|
|
38769
|
+
}
|
|
38770
|
+
|
|
38771
|
+
// src/bridge/usage.ts
|
|
38728
38772
|
var exec6 = promisify6(execFile7);
|
|
38729
|
-
var claudeFile = () =>
|
|
38773
|
+
var claudeFile = () => path45.join(bridgeRoot(), "usage", "claude.json");
|
|
38730
38774
|
var safeText = (v) => typeof v === "string" ? v.replace(/[\x00-\x1f\x7f]/g, "").slice(0, 100) : void 0;
|
|
38731
38775
|
function window(id2, name, percent, reset) {
|
|
38732
38776
|
if (typeof percent !== "number" || !Number.isFinite(percent) || percent < 0 || percent > 100) return;
|
|
@@ -38767,9 +38811,9 @@ function openCodeUsage(output2, now = /* @__PURE__ */ new Date()) {
|
|
|
38767
38811
|
}
|
|
38768
38812
|
return { source: "opencode", windows: [], spend: { amountUSD, period: "rolling_7_days" }, updatedAt: now.toISOString() };
|
|
38769
38813
|
}
|
|
38770
|
-
async function readOpenCodeUsage(
|
|
38814
|
+
async function readOpenCodeUsage(executable2 = "opencode", now = /* @__PURE__ */ new Date()) {
|
|
38771
38815
|
try {
|
|
38772
|
-
const { stdout } = await exec6(
|
|
38816
|
+
const { stdout } = await exec6(executable2, ["stats", "--days", "7", "--pure"], { timeout: 12e3, maxBuffer: 1048576 });
|
|
38773
38817
|
return openCodeUsage(stdout, now);
|
|
38774
38818
|
} catch (error62) {
|
|
38775
38819
|
return { source: "opencode", windows: [], message: openCodeFailure(error62) };
|
|
@@ -38785,8 +38829,8 @@ function openCodeFailure(error62) {
|
|
|
38785
38829
|
const exit = typeof failure2?.code === "number" ? ` (exit ${failure2.code})` : "";
|
|
38786
38830
|
return `opencode stats --days 7 failed${exit}${said ? `: ${said}` : ""}. Run it on this computer to see why.`;
|
|
38787
38831
|
}
|
|
38788
|
-
var openCodeAuthFile = () =>
|
|
38789
|
-
process.env.OPENCODE_DATA_DIR ||
|
|
38832
|
+
var openCodeAuthFile = () => path45.join(
|
|
38833
|
+
process.env.OPENCODE_DATA_DIR || path45.join(process.env.XDG_DATA_HOME || path45.join(homedir11(), ".local", "share"), "opencode"),
|
|
38790
38834
|
"auth.json"
|
|
38791
38835
|
);
|
|
38792
38836
|
async function readOpenRouterKey() {
|
|
@@ -38980,7 +39024,7 @@ async function containedRegularFile(root, candidate, maximum) {
|
|
|
38980
39024
|
const link = await lstat8(candidate);
|
|
38981
39025
|
if (!link.isFile() || link.isSymbolicLink() || link.size > maximum) return void 0;
|
|
38982
39026
|
const resolved = await realpath9(candidate);
|
|
38983
|
-
if (!resolved.startsWith(root +
|
|
39027
|
+
if (!resolved.startsWith(root + path45.sep)) return void 0;
|
|
38984
39028
|
const metadata = await stat14(resolved);
|
|
38985
39029
|
return metadata.isFile() && metadata.size <= maximum ? resolved : void 0;
|
|
38986
39030
|
} catch {
|
|
@@ -39018,7 +39062,7 @@ async function readOpenCodeGoLedger(root = fanoutRoot(), now = /* @__PURE__ */ n
|
|
|
39018
39062
|
const names = (await readdir9(directory).catch(() => [])).slice(0, MAX_GO_JOBS);
|
|
39019
39063
|
for (const name of names) {
|
|
39020
39064
|
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(name)) continue;
|
|
39021
|
-
const manifestFile = await containedRegularFile(directory,
|
|
39065
|
+
const manifestFile = await containedRegularFile(directory, path45.join(directory, name, "manifest.json"), MAX_GO_MANIFEST_BYTES);
|
|
39022
39066
|
if (!manifestFile) continue;
|
|
39023
39067
|
let manifest;
|
|
39024
39068
|
try {
|
|
@@ -39029,9 +39073,9 @@ async function readOpenCodeGoLedger(root = fanoutRoot(), now = /* @__PURE__ */ n
|
|
|
39029
39073
|
const model = goModel(manifest.model);
|
|
39030
39074
|
const eventLog = typeof manifest.eventLog === "string" && /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}\.jsonl$/.test(manifest.eventLog) ? manifest.eventLog : void 0;
|
|
39031
39075
|
if (manifest.provider !== "opencode" || !model || !eventLog) continue;
|
|
39032
|
-
const jobRoot = await realpath9(
|
|
39033
|
-
if (!jobRoot || !jobRoot.startsWith(directory +
|
|
39034
|
-
const eventsFile = await containedRegularFile(jobRoot,
|
|
39076
|
+
const jobRoot = await realpath9(path45.join(directory, name)).catch(() => void 0);
|
|
39077
|
+
if (!jobRoot || !jobRoot.startsWith(directory + path45.sep)) continue;
|
|
39078
|
+
const eventsFile = await containedRegularFile(jobRoot, path45.join(jobRoot, eventLog), MAX_GO_EVENTS_BYTES);
|
|
39035
39079
|
if (!eventsFile) continue;
|
|
39036
39080
|
let events;
|
|
39037
39081
|
try {
|
|
@@ -39208,8 +39252,8 @@ function claudeScopedWindows(config3, now = /* @__PURE__ */ new Date()) {
|
|
|
39208
39252
|
}
|
|
39209
39253
|
return windows;
|
|
39210
39254
|
}
|
|
39211
|
-
var claudeConfigFile = () =>
|
|
39212
|
-
var claudeCredentialsFile = () =>
|
|
39255
|
+
var claudeConfigFile = () => path45.join(process.env.CLAUDE_CONFIG_DIR?.trim() ? claudeConfigDir() : homeDir(), ".claude.json");
|
|
39256
|
+
var claudeCredentialsFile = () => path45.join(claudeConfigDir(), ".credentials.json");
|
|
39213
39257
|
function claudeOAuthUsage(value2, now = /* @__PURE__ */ new Date()) {
|
|
39214
39258
|
const limits = object2(value2).limits;
|
|
39215
39259
|
const windows = [];
|
|
@@ -39288,9 +39332,9 @@ async function liveClaudeUsage(now) {
|
|
|
39288
39332
|
return void 0;
|
|
39289
39333
|
}
|
|
39290
39334
|
}
|
|
39291
|
-
function readCodexLimits(
|
|
39335
|
+
function readCodexLimits(executable2 = codexExecutable()) {
|
|
39292
39336
|
return new Promise((resolve11) => {
|
|
39293
|
-
const child = spawn2(
|
|
39337
|
+
const child = spawn2(executable2, ["app-server"], { cwd: homedir11(), stdio: ["pipe", "pipe", "ignore"] });
|
|
39294
39338
|
let pending = "", bytes = 0, initialized = false, done = false;
|
|
39295
39339
|
const finish = (result) => {
|
|
39296
39340
|
if (done) return;
|
|
@@ -39495,7 +39539,7 @@ init_protocol();
|
|
|
39495
39539
|
init_herdr();
|
|
39496
39540
|
import { chmod as chmod2, copyFile as copyFile2, mkdir as mkdir10, open as open10, readFile as readFile18, rename as rename5, symlink, unlink as unlink4, lstat as lstat9, writeFile as writeFile4 } from "node:fs/promises";
|
|
39497
39541
|
import { homedir as homedir13 } from "node:os";
|
|
39498
|
-
import
|
|
39542
|
+
import path48 from "node:path";
|
|
39499
39543
|
import { fileURLToPath as fileURLToPath5 } from "node:url";
|
|
39500
39544
|
import { promisify as promisify7 } from "node:util";
|
|
39501
39545
|
|
|
@@ -39508,17 +39552,17 @@ import { connect as connect3 } from "node:net";
|
|
|
39508
39552
|
import { request as request3 } from "node:http";
|
|
39509
39553
|
import { spawn as spawn3 } from "node:child_process";
|
|
39510
39554
|
import { homedir as homedir12 } from "node:os";
|
|
39511
|
-
import
|
|
39555
|
+
import path46 from "node:path";
|
|
39512
39556
|
function decodeShellDirectory(encoded) {
|
|
39513
39557
|
if (!/^[A-Za-z0-9_-]{1,8192}$/.test(encoded)) return void 0;
|
|
39514
39558
|
const decoded = Buffer.from(encoded, "base64url");
|
|
39515
39559
|
if (decoded.toString("base64url") !== encoded) return void 0;
|
|
39516
39560
|
const dir = decoded.toString("utf8");
|
|
39517
|
-
return
|
|
39561
|
+
return path46.isAbsolute(dir) && !/[\x00-\x1f\x7f]/.test(dir) && !dir.includes("\uFFFD") ? dir : void 0;
|
|
39518
39562
|
}
|
|
39519
39563
|
function shellEnvironment(base = process.env) {
|
|
39520
39564
|
const env = Object.fromEntries(Object.entries(base).filter(([key2]) => !key2.startsWith("HERDR_") && key2 !== "TMUX" && key2 !== "TMUX_PANE"));
|
|
39521
|
-
env.PATH = [
|
|
39565
|
+
env.PATH = [path46.join(homedir12(), ".local/bin"), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin"].join(":");
|
|
39522
39566
|
return env;
|
|
39523
39567
|
}
|
|
39524
39568
|
async function health() {
|
|
@@ -39579,7 +39623,7 @@ async function dispatch(command) {
|
|
|
39579
39623
|
};
|
|
39580
39624
|
if (command === "phren-hook v1 pipe") {
|
|
39581
39625
|
requireHook();
|
|
39582
|
-
await pipe2({ path: socketPath() },
|
|
39626
|
+
await pipe2({ path: socketPath() }, path46.join(bridgeRoot(), "gateway.json"), true);
|
|
39583
39627
|
return;
|
|
39584
39628
|
}
|
|
39585
39629
|
const preview = /^phren-hook v1 web (127\.0\.0\.1|::1) ([1-9][0-9]{0,4})$/.exec(command);
|
|
@@ -39595,7 +39639,7 @@ async function dispatch(command) {
|
|
|
39595
39639
|
if (!raw) throw new BridgeError(403, "The shell folder is not a valid absolute path.");
|
|
39596
39640
|
const cwd = await launchDirectory(raw);
|
|
39597
39641
|
if (!process.stdin.isTTY || !process.stdout.isTTY) throw new Error("Request an SSH terminal first.");
|
|
39598
|
-
const login = process.env.SHELL &&
|
|
39642
|
+
const login = process.env.SHELL && path46.isAbsolute(process.env.SHELL) ? process.env.SHELL : "/bin/sh";
|
|
39599
39643
|
const [file2, args] = shell[2] ? [shell[2], []] : [login, ["-l"]];
|
|
39600
39644
|
await attach(file2, args, { cwd, env: shellEnvironment() }, shell[2] ? `${shell[2]} exited.` : "The shell exited.");
|
|
39601
39645
|
return;
|
|
@@ -39707,9 +39751,9 @@ ${pipe3}exec ${quote2(node2)} ${quote2(bundle)} ssh
|
|
|
39707
39751
|
}
|
|
39708
39752
|
async function activate(version3) {
|
|
39709
39753
|
const root = bridgeRoot();
|
|
39710
|
-
const next =
|
|
39711
|
-
await symlink(
|
|
39712
|
-
await rename5(next,
|
|
39754
|
+
const next = path48.join(root, `current-${process.pid}`);
|
|
39755
|
+
await symlink(path48.join("versions", version3), next);
|
|
39756
|
+
await rename5(next, path48.join(root, "current"));
|
|
39713
39757
|
}
|
|
39714
39758
|
function launchDomain(uid, guiSession2) {
|
|
39715
39759
|
return guiSession2 ? `gui/${uid}` : `user/${uid}`;
|
|
@@ -39717,7 +39761,7 @@ function launchDomain(uid, guiSession2) {
|
|
|
39717
39761
|
function launchCommands(domain2, plist) {
|
|
39718
39762
|
return [`launchctl bootout ${domain2}/${label}`, `launchctl bootstrap ${domain2} ${quote2(plist)}`, `launchctl kickstart -k ${domain2}/${label}`];
|
|
39719
39763
|
}
|
|
39720
|
-
var launchAgentPlist = () =>
|
|
39764
|
+
var launchAgentPlist = () => path48.join(homedir13(), "Library/LaunchAgents", `${label}.plist`);
|
|
39721
39765
|
async function guiSession(uid) {
|
|
39722
39766
|
return exec7("launchctl", ["print", `gui/${uid}`]).then(() => true, () => false);
|
|
39723
39767
|
}
|
|
@@ -39759,52 +39803,52 @@ async function install(version3, noService = false) {
|
|
|
39759
39803
|
if (!/^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(version3)) throw new Error("Invalid helper version.");
|
|
39760
39804
|
const modules = activateModules(defaultPhrenPath(), void 0, true);
|
|
39761
39805
|
if (!modules.has("hook")) throw new Error(disabledHint("hook"));
|
|
39762
|
-
const root = bridgeRoot(), herdr = herdrRoot(), versions =
|
|
39806
|
+
const root = bridgeRoot(), herdr = herdrRoot(), versions = path48.join(root, "versions");
|
|
39763
39807
|
await mkdir10(versions, { recursive: true, mode: 448 });
|
|
39764
39808
|
await chmod2(root, 448);
|
|
39765
|
-
const serviceLog =
|
|
39809
|
+
const serviceLog = path48.join(root, "service.log");
|
|
39766
39810
|
const log2 = await open10(serviceLog, "a", 384);
|
|
39767
39811
|
try {
|
|
39768
39812
|
await log2.chmod(384);
|
|
39769
39813
|
} finally {
|
|
39770
39814
|
await log2.close();
|
|
39771
39815
|
}
|
|
39772
|
-
const hookEdits = await planAgentHooks(
|
|
39816
|
+
const hookEdits = await planAgentHooks(path48.join(root, "current/bridge-hook.mjs"), false, modules);
|
|
39773
39817
|
const own2 = fileURLToPath5(import.meta.url);
|
|
39774
|
-
const bundle = own2.endsWith("bridge-hook.mjs") ? own2 :
|
|
39775
|
-
const destination2 =
|
|
39818
|
+
const bundle = own2.endsWith("bridge-hook.mjs") ? own2 : path48.join(path48.dirname(own2), "..", "bridge-hook.mjs");
|
|
39819
|
+
const destination2 = path48.join(versions, version3);
|
|
39776
39820
|
await mkdir10(destination2, { recursive: true, mode: 448 });
|
|
39777
|
-
const installedBundle =
|
|
39821
|
+
const installedBundle = path48.join(destination2, "bridge-hook.mjs");
|
|
39778
39822
|
const previousBundle = await missingFile(readFile18(installedBundle));
|
|
39779
39823
|
const stagedBundle = installedBundle + `.phren-${process.pid}`;
|
|
39780
39824
|
await copyFile2(bundle, stagedBundle);
|
|
39781
39825
|
await rename5(stagedBundle, installedBundle);
|
|
39782
|
-
const previous = await readFile18(
|
|
39826
|
+
const previous = await readFile18(path48.join(root, "installed.json"), "utf8").then((v) => JSON.parse(v)).catch(() => null);
|
|
39783
39827
|
const gateway = await detectGateway();
|
|
39784
|
-
await atomic(
|
|
39828
|
+
await atomic(path48.join(root, "dispatch"), gatewayScript(gateway, {
|
|
39785
39829
|
root,
|
|
39786
39830
|
herdr,
|
|
39787
39831
|
store: modules.store,
|
|
39788
39832
|
profile: modules.profile,
|
|
39789
39833
|
node: process.execPath,
|
|
39790
|
-
bundle:
|
|
39834
|
+
bundle: path48.join(root, "current/bridge-hook.mjs"),
|
|
39791
39835
|
socket: socketPath(),
|
|
39792
|
-
timing:
|
|
39836
|
+
timing: path48.join(root, "gateway.json")
|
|
39793
39837
|
}), 448);
|
|
39794
|
-
const environmentPath = [
|
|
39795
|
-
const program =
|
|
39838
|
+
const environmentPath = [path48.dirname(process.execPath), path48.join(homedir13(), ".local/bin"), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin"].join(":");
|
|
39839
|
+
const program = path48.join(root, "current/bridge-hook.mjs");
|
|
39796
39840
|
if (!noService) {
|
|
39797
39841
|
if (process.platform === "darwin") {
|
|
39798
|
-
const folder =
|
|
39842
|
+
const folder = path48.join(homedir13(), "Library/LaunchAgents");
|
|
39799
39843
|
await mkdir10(folder, { recursive: true });
|
|
39800
|
-
await atomic(
|
|
39844
|
+
await atomic(path48.join(folder, `${label}.plist`), `<?xml version="1.0" encoding="UTF-8"?>
|
|
39801
39845
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
39802
|
-
<plist version="1.0"><dict><key>Label</key><string>${label}</string><key>ProgramArguments</key><array><string>${xml(process.execPath)}</string><string>${xml(program)}</string><string>serve</string></array><key>Umask</key><integer>63</integer><key>RunAtLoad</key><true/><key>KeepAlive</key><true/><key>ThrottleInterval</key><integer>5</integer><key>Nice</key><integer>-5</integer><key>EnvironmentVariables</key><dict><key>PATH</key><string>${xml(environmentPath)}</string><key>PHREN_BRIDGE_HOME</key><string>${xml(root)}</string><key>PHREN_HERDR_HOME</key><string>${xml(herdr)}</string><key>PHREN_PATH</key><string>${xml(modules.store)}</string><key>PHREN_PROFILE</key><string>${xml(modules.profile)}</string></dict><key>StandardErrorPath</key><string>${xml(
|
|
39846
|
+
<plist version="1.0"><dict><key>Label</key><string>${label}</string><key>ProgramArguments</key><array><string>${xml(process.execPath)}</string><string>${xml(program)}</string><string>serve</string></array><key>Umask</key><integer>63</integer><key>RunAtLoad</key><true/><key>KeepAlive</key><true/><key>ThrottleInterval</key><integer>5</integer><key>Nice</key><integer>-5</integer><key>EnvironmentVariables</key><dict><key>PATH</key><string>${xml(environmentPath)}</string><key>PHREN_BRIDGE_HOME</key><string>${xml(root)}</string><key>PHREN_HERDR_HOME</key><string>${xml(herdr)}</string><key>PHREN_PATH</key><string>${xml(modules.store)}</string><key>PHREN_PROFILE</key><string>${xml(modules.profile)}</string></dict><key>StandardErrorPath</key><string>${xml(path48.join(root, "service.log"))}</string></dict></plist>
|
|
39803
39847
|
`);
|
|
39804
39848
|
} else {
|
|
39805
|
-
const folder =
|
|
39849
|
+
const folder = path48.join(homedir13(), ".config/systemd/user");
|
|
39806
39850
|
await mkdir10(folder, { recursive: true });
|
|
39807
|
-
await atomic(
|
|
39851
|
+
await atomic(path48.join(folder, unit), `[Unit]
|
|
39808
39852
|
Description=Phren Hook
|
|
39809
39853
|
[Service]
|
|
39810
39854
|
ExecStart=${systemdQuote(process.execPath)} ${systemdQuote(program)} serve
|
|
@@ -39846,7 +39890,7 @@ WantedBy=default.target
|
|
|
39846
39890
|
if ((await Promise.resolve().then(() => (init_agent_package(), agent_package_exports))).agentInstalled()) {
|
|
39847
39891
|
console.log("phren-agent chat: found; it reports to this Hook itself, so restart any phren-agent session started before now.");
|
|
39848
39892
|
}
|
|
39849
|
-
const keys =
|
|
39893
|
+
const keys = path48.join(homedir13(), ".ssh/authorized_keys");
|
|
39850
39894
|
const keyStat = await lstat9(keys).catch(() => null);
|
|
39851
39895
|
if (keyStat && !keyStat.isSymbolicLink() && keyStat.isFile()) {
|
|
39852
39896
|
const before = await readFile18(keys, "utf8"), after = upgradeKeys(before);
|
|
@@ -39857,7 +39901,7 @@ WantedBy=default.target
|
|
|
39857
39901
|
}
|
|
39858
39902
|
console.log(`Updated ${after.changed} Phren iPhone key(s); other keys were preserved.`);
|
|
39859
39903
|
}
|
|
39860
|
-
await atomic(
|
|
39904
|
+
await atomic(path48.join(root, "installed.json"), JSON.stringify({ version: version3, previous: previous?.version === version3 ? previous.previous : previous?.version, node: process.execPath, gateway }, null, 2) + "\n");
|
|
39861
39905
|
console.log("Agent hooks installed. In Codex, review the new Phren entries in /hooks. Existing agents may need to resume before new hooks load.");
|
|
39862
39906
|
console.log(`SSH gateway: ${gateway}${gateway === "node" ? " (no socat or nc -U found)" : ""}.`);
|
|
39863
39907
|
console.log(`Phren Hook ${version3} installed${noService ? " (service not started)" : " and running"}. Run phren bridge doctor.`);
|
|
@@ -39882,12 +39926,12 @@ async function uninstall() {
|
|
|
39882
39926
|
else {
|
|
39883
39927
|
await exec7("systemctl", ["--user", "disable", unit]).catch(() => {
|
|
39884
39928
|
});
|
|
39885
|
-
await unlink4(
|
|
39929
|
+
await unlink4(path48.join(homedir13(), ".config/systemd/user", unit)).catch(() => {
|
|
39886
39930
|
});
|
|
39887
39931
|
await exec7("systemctl", ["--user", "daemon-reload"]).catch(() => {
|
|
39888
39932
|
});
|
|
39889
39933
|
}
|
|
39890
|
-
await applyAgentHooks(await planAgentHooks(
|
|
39934
|
+
await applyAgentHooks(await planAgentHooks(path48.join(bridgeRoot(), "current/bridge-hook.mjs"), true));
|
|
39891
39935
|
await applyOpencodePlugin(true);
|
|
39892
39936
|
console.log("Phren Hook stopped and its background service removed. Remove phren-iphone, phren-android and phren-computer keys from authorized_keys to revoke device access. Local data remains in " + bridgeRoot());
|
|
39893
39937
|
}
|
|
@@ -39902,9 +39946,9 @@ async function missingFile(operation) {
|
|
|
39902
39946
|
async function planAgentHooks(program, remove = false, modules) {
|
|
39903
39947
|
const edits = [];
|
|
39904
39948
|
for (const [source, file2] of [
|
|
39905
|
-
["codex",
|
|
39906
|
-
["claude",
|
|
39907
|
-
["copilot",
|
|
39949
|
+
["codex", path48.join(codexHome(), "hooks.json")],
|
|
39950
|
+
["claude", path48.join(claudeConfigDir(), "settings.json")],
|
|
39951
|
+
["copilot", path48.join(process.env.COPILOT_HOME || path48.join(homedir13(), ".copilot"), "hooks/phren.json")]
|
|
39908
39952
|
]) {
|
|
39909
39953
|
const metadata = await missingFile(lstat9(file2));
|
|
39910
39954
|
if (metadata && (!metadata.isFile() || metadata.isSymbolicLink() || metadata.size > 2097152)) {
|
|
@@ -39954,7 +39998,7 @@ async function planAgentHooks(program, remove = false, modules) {
|
|
|
39954
39998
|
}
|
|
39955
39999
|
return edits;
|
|
39956
40000
|
}
|
|
39957
|
-
var opencodePluginsDir = () =>
|
|
40001
|
+
var opencodePluginsDir = () => path48.join(process.env.XDG_CONFIG_HOME || path48.join(homedir13(), ".config"), "opencode", "plugins");
|
|
39958
40002
|
var OPENCODE_PLUGIN_MARKER = "// Installed by Phren Hook";
|
|
39959
40003
|
function opencodePluginNeedsWrite(existing, source) {
|
|
39960
40004
|
if (existing === void 0) return true;
|
|
@@ -39963,10 +40007,10 @@ function opencodePluginNeedsWrite(existing, source) {
|
|
|
39963
40007
|
}
|
|
39964
40008
|
async function opencodePluginSource() {
|
|
39965
40009
|
if (true) return '// Installed by Phren Hook and replaced on every update. Copy it under another name to customize.\nimport { lstatSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";\nimport { homedir } from "node:os";\nimport path from "node:path";\n\nconst PHREN_STORE = "__PHREN_STORE__";\nconst FLUSH_MS = 250;\nconst MAX_TOOL_OUTPUT = 200_000;\n// OpenCode\'s read tool returns a picture as an inline data URL on the tool\n// part (`state.attachments`). The Hook serves images up to 8 MiB; the session\n// budget bounds what every flush rewrites.\nconst MAX_IMAGE_DATA = 4_000_000;\nconst MAX_SESSION_IMAGE_DATA = 24_000_000;\nconst IMAGE_DATA_URL = /^data:(image\\/(?:png|jpeg|gif|webp));base64,([A-Za-z0-9+/=]+)$/;\nconst STOP_REASONS = { stop: "end_turn", "tool-calls": "tool_use", length: "max_tokens" };\nconst OPENCODE_SESSION = /^ses_[0-9A-Za-z]{1,64}$/;\nconst APPROVAL_POLL_MS = 200;\nconst APPROVAL_DEADLINE_MS = 50_000;\n\nfunction storeRoot() {\n if (PHREN_STORE && !PHREN_STORE.startsWith("__")) return PHREN_STORE;\n const configured = process.env.PHREN_PATH?.trim();\n if (!configured) return path.join(homedir(), ".phren");\n const expanded = configured === "~" ? homedir() : configured.startsWith("~/") ? path.join(homedir(), configured.slice(2)) : configured;\n return path.resolve(expanded);\n}\n\nfunction text(value) {\n return typeof value === "string" ? value : "";\n}\n\nfunction approvalDirectory() {\n return path.join(storeRoot(), ".runtime", "approvals");\n}\n\nfunction fanoutDirectory() {\n const configured = process.env.PHREN_FANOUT_DIR?.trim();\n if (configured) return path.resolve(configured);\n return path.join(storeRoot(), ".runtime", "agent-fanouts", text(process.env.PHREN_FANOUT_JOB));\n}\n\nfunction fanoutPatterns(input) {\n const value = input?.pattern;\n if (Array.isArray(value)) return value.filter(entry => typeof entry === "string" && entry);\n return typeof value === "string" && value ? [value] : [];\n}\n\n/** The worktree\'s grandparent is the scratch root the fan-out launcher owns:\n * external reads and writes are allowed only inside it. */\nfunction underScratchRoot(value) {\n const scratch = path.dirname(path.dirname(path.resolve(process.cwd())));\n if (scratch === path.parse(scratch).root) return false;\n const resolved = path.resolve(scratch, value);\n return resolved === scratch || resolved.startsWith(scratch + path.sep);\n}\n\nfunction under(parent, value) {\n if (!parent || parent === path.parse(parent).root) return false;\n const root = path.resolve(parent), resolved = path.resolve(root, value);\n return resolved === root || resolved.startsWith(root + path.sep);\n}\n\n/** Beyond the scratch root, a worker legitimately reads its own machine: the\n * node_modules its worktree links into the main checkout, the store it was\n * briefed from, the toolchains a build shells out to, and the temporary\n * directories those builds write. Everything outside this set is refused. */\nfunction fanoutReadable(value) {\n if (underScratchRoot(value)) return true;\n const home = process.env.HOME || "";\n const roots = [home, storeRoot(), "/tmp", "/private/tmp", "/var/folders", "/private/var/folders",\n "/Applications/Xcode.app", "/Library/Developer"];\n return roots.some(root => under(root, value));\n}\n\n/** A headless fan-out worker may edit, run commands and fetch, and continue\n * when OpenCode\'s own loop detector asks (the launcher\'s watchdog stops a real\n * loop and says why, which is a clearer failure than a refused permission).\n * Anything else is refused outright. */\nfunction fanoutAllowed(input) {\n const kind = text(input?.type);\n if (kind === "edit" || kind === "bash" || kind === "webfetch" || kind === "doom_loop") return true;\n if (kind !== "external_directory") return false;\n const patterns = fanoutPatterns(input);\n return patterns.length > 0 && patterns.every(fanoutReadable);\n}\n\nfunction writeBlocked(input) {\n try {\n const directory = fanoutDirectory();\n mkdirSync(directory, { recursive: true });\n writeJsonAtomic(path.join(directory, "blocked.json"), {\n type: text(input?.type) || "action",\n pattern: fanoutPatterns(input).join(", "),\n message: permissionMessage(input),\n at: new Date().toISOString(),\n });\n } catch {}\n}\n\nfunction approvalPaths(sessionID) {\n const base = path.join(approvalDirectory(), `opencode-${sessionID}`);\n return { request: `${base}.request.json`, answer: `${base}.answer.json` };\n}\n\nfunction writeJsonAtomic(file, value) {\n const staging = `${file}.${process.pid}.tmp`;\n writeFileSync(staging, JSON.stringify(value), { mode: 0o600 });\n renameSync(staging, file);\n}\n\nfunction removeFile(file) {\n try { unlinkSync(file); } catch {}\n}\n\nfunction sleep(ms) {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n\nfunction setStatus(output, status) {\n if (output && typeof output === "object") output.status = status;\n}\n\nfunction permissionMessage(input) {\n const type = text(input?.type) || "action";\n const pattern = Array.isArray(input?.pattern)\n ? input.pattern.filter(value => typeof value === "string").join(", ")\n : text(input?.pattern);\n const metadata = input?.metadata && typeof input.metadata === "object" ? input.metadata : {};\n const detail = [pattern, text(metadata.command), text(metadata.description), text(metadata.path), text(metadata.url)].find(value => value);\n return (detail ? `${type}: ${detail}` : `opencode asks to use ${type}.`).slice(0, 2000);\n}\n\nfunction toolOutput(state) {\n if (!state || typeof state !== "object") return "";\n const output = state.output ?? state.metadata?.output ?? state.result ?? "";\n const value = typeof output === "string" ? output : JSON.stringify(output ?? "");\n return value.length > MAX_TOOL_OUTPUT ? value.slice(0, MAX_TOOL_OUTPUT) : value;\n}\n\nfunction blocksFor(message) {\n const blocks = [];\n for (const id of message.partOrder) {\n const part = message.parts.get(id);\n if (!part || typeof part !== "object") continue;\n if (part.type === "text" && typeof part.text === "string" && part.text.length) {\n blocks.push({ type: "text", text: part.text });\n } else if (part.type === "tool" && typeof part.callID === "string") {\n blocks.push({ type: "tool_use", id: part.callID, name: text(part.tool) || "tool", input: part.state?.input ?? {} });\n }\n }\n return blocks;\n}\n\n/** A tool\'s picture attachments as Anthropic-shaped image blocks, the form the\n * Hook\'s image route and the phone already read from Claude Code. Only inline\n * data URLs are carried; an image over the caps becomes a text marker. */\nfunction toolImages(state, budget) {\n const blocks = [];\n for (const attachment of Array.isArray(state?.attachments) ? state.attachments : []) {\n if (attachment?.type !== "file" || typeof attachment.url !== "string") continue;\n const match = IMAGE_DATA_URL.exec(attachment.url);\n if (!match) continue;\n const data = match[2];\n if (data.length > MAX_IMAGE_DATA || data.length > budget.remaining) {\n blocks.push({ type: "text", text: "[Image not included: too large to show on the phone]" });\n continue;\n }\n budget.remaining -= data.length;\n blocks.push({ type: "image", source: { type: "base64", media_type: match[1], data } });\n }\n return blocks;\n}\n\nfunction toolResults(message, budget) {\n const results = [];\n for (const id of message.partOrder) {\n const part = message.parts.get(id);\n if (!part || part.type !== "tool" || typeof part.callID !== "string") continue;\n const status = part.state?.status;\n if (status !== "completed" && status !== "error") continue;\n const output = toolOutput(part.state), images = toolImages(part.state, budget);\n const content = images.length ? [{ type: "text", text: output }, ...images] : output;\n results.push({ type: "tool_result", tool_use_id: part.callID, content, is_error: status === "error" });\n }\n return results;\n}\n\nfunction linesFor(session) {\n const messages = session.order\n .map(id => session.messages.get(id))\n .filter(Boolean)\n .sort((a, b) => (a.info?.time?.created ?? 0) - (b.info?.time?.created ?? 0) || String(a.info?.id).localeCompare(String(b.info?.id)));\n const lines = [];\n const budget = { remaining: MAX_SESSION_IMAGE_DATA };\n let seq = 0;\n const emit = (type, data, created) => {\n lines.push(JSON.stringify({ seq: seq++, time: new Date(created || Date.now()).toISOString(), type, data }));\n };\n for (const message of messages) {\n const info = message.info ?? {};\n if (info.role === "user") {\n const blocks = blocksFor(message);\n if (blocks.length) emit("user/message", { source: "user", message: { role: "user", content: blocks } }, info.time?.created);\n } else if (info.role === "assistant") {\n const complete = Boolean(info.time?.completed || info.finish);\n const blocks = blocksFor(message).filter(block => complete || block.type !== "text");\n const data = { stop_reason: STOP_REASONS[info.finish] || info.finish || "end_turn", message: { role: "assistant", content: blocks } };\n if (info.tokens && (typeof info.tokens.input === "number" || typeof info.tokens.output === "number")) {\n data.usage = { input_tokens: info.tokens.input ?? 0, output_tokens: info.tokens.output ?? 0 };\n }\n if (blocks.length) emit("assistant/message", data, info.time?.created);\n const results = toolResults(message, budget);\n if (results.length) emit("tool/results", { message: { role: "user", content: results } }, info.time?.updated ?? info.time?.created);\n }\n }\n return lines;\n}\n\n/** Which conversation this OpenCode process is showing, by PID: the Hook\n * reads it to bind a pane when Herdr reports no session for it. */\nconst pidBindingFile = () => path.join(storeRoot(), ".runtime", "sessions", `opencode-pid-${process.pid}.json`);\nfunction writePidBinding(sessionID) {\n mkdirSync(path.dirname(pidBindingFile()), { recursive: true });\n writeJsonAtomic(pidBindingFile(), { session: sessionID, at: new Date().toISOString() });\n}\n\n/** What this OpenCode process is doing, by PID: "working", "idle" or\n * "blocked" (a permission waits for an answer). The Hook reads it for a pane\n * whose terminal does not watch its agents (tmux); Herdr has its own. */\nconst statusFile = () => path.join(storeRoot(), ".runtime", "sessions", `opencode-status-${process.pid}.json`);\n\nexport const PhrenTranscriptPlugin = async () => {\n const sessions = new Map();\n // Subagent sessions run inside the same process; the pane shows their parent.\n const children = new Set();\n let boundSession;\n // A reused PID must not inherit an old process\'s conversation or state.\n try { removeFile(pidBindingFile()); removeFile(statusFile()); } catch {}\n let recordedStatus;\n // Permission asks still open, by id: while any is, the process is blocked.\n const asking = new Set();\n const recordStatus = (status, sessionID) => {\n // A fan-out worker runs headless, in no pane.\n if (process.env.PHREN_FANOUT_JOB) return;\n const next = asking.size && status === "working" ? "blocked" : status;\n if (next === recordedStatus) return;\n try {\n mkdirSync(path.dirname(statusFile()), { recursive: true });\n writeJsonAtomic(statusFile(), { status: next, ...(sessionID ? { session: sessionID } : {}), at: new Date().toISOString() });\n recordedStatus = next;\n } catch {}\n };\n const permissionId = properties => text(properties?.permissionID) || text(properties?.requestID) || text(properties?.id);\n const timers = new Map();\n const written = new Map();\n const pendingApprovals = new Set();\n\n const sessionState = sessionID => {\n let state = sessions.get(sessionID);\n if (!state) { state = { messages: new Map(), order: [], idle: false }; sessions.set(sessionID, state); }\n return state;\n };\n\n const messageState = (sessionID, messageID) => {\n const state = sessionState(sessionID);\n let message = state.messages.get(messageID);\n if (!message) { message = { info: { id: messageID }, parts: new Map(), partOrder: [] }; state.messages.set(messageID, message); state.order.push(messageID); }\n return message;\n };\n\n const flush = sessionID => {\n const state = sessions.get(sessionID);\n if (!state) return;\n const body = linesFor(state);\n const content = body.length ? body.join("\\n") + "\\n" : "";\n const directory = path.join(storeRoot(), ".runtime", "sessions");\n mkdirSync(directory, { recursive: true });\n const file = path.join(directory, `opencode-${sessionID}.events.jsonl`);\n const messages = state.order.map(id => state.messages.get(id));\n const latest = messages.at(-1), info = latest?.info;\n const user = messages.findLast(message => message.info?.role === "user");\n const preview = !state.idle && info?.role === "assistant" && !info.time?.completed && !info.finish\n ? blocksFor(latest).filter(block => block.type === "text").map(block => block.text).join("\\n").slice(0, 32_768) : "";\n if (preview && user?.info.time?.created) writeJsonAtomic(file + ".preview.json", {\n turnStartedAt: new Date(user.info.time.created).toISOString(), text: preview,\n });\n else removeFile(file + ".preview.json");\n if (written.get(sessionID) === content) return;\n const staging = `${file}.${process.pid}.tmp`;\n writeFileSync(staging, content, { mode: 0o600 });\n renameSync(staging, file);\n written.set(sessionID, content);\n };\n\n const schedule = sessionID => {\n if (!sessionID || timers.has(sessionID)) return;\n timers.set(sessionID, setTimeout(() => {\n timers.delete(sessionID);\n try { flush(sessionID); } catch {}\n }, FLUSH_MS));\n };\n\n const rememberInfo = (sessionID, info) => {\n if (!info || typeof info.id !== "string") return;\n const message = messageState(sessionID, info.id);\n message.info = { ...message.info, ...info };\n if (info.role === "user") sessionState(sessionID).idle = false;\n schedule(sessionID);\n };\n\n const rememberPart = (sessionID, messageID, part) => {\n if (!part || typeof part.id !== "string" || typeof messageID !== "string") return;\n const message = messageState(sessionID, messageID);\n if (!message.parts.has(part.id)) message.partOrder.push(part.id);\n message.parts.set(part.id, part);\n schedule(sessionID);\n };\n\n return {\n "chat.message": async (input, output) => {\n if (!OPENCODE_SESSION.test(text(input?.sessionID)) || !output?.message) return;\n if (!process.env.PHREN_FANOUT_JOB && !children.has(input.sessionID) && boundSession !== input.sessionID) {\n try { writePidBinding(input.sessionID); boundSession = input.sessionID; } catch {}\n }\n rememberInfo(input.sessionID, output.message);\n for (const part of output.parts ?? []) rememberPart(input.sessionID, output.message.id, part);\n if (!children.has(input.sessionID)) recordStatus("working", input.sessionID);\n },\n "permission.ask": async (input, output) => {\n // A fan-out worker runs headless in its own worktree with nobody watching\n // the phone\'s approval queue, so edits, commands and fetches inside that\n // worktree are granted here and anything else is refused outright rather\n // than waiting 50 seconds for an answer that never comes.\n if (process.env.PHREN_FANOUT_JOB) {\n if (fanoutAllowed(input)) { setStatus(output, "allow"); return; }\n // A worker the launcher drives through `opencode serve` relays the\n // ask to the phone and resumes on the owner\'s answer.\n if (process.env.PHREN_FANOUT_APPROVALS === "1") { setStatus(output, "ask"); return; }\n setStatus(output, "deny");\n // A denied permission aborts the turn; record what was refused so the\n // Hook can report the worker as blocked rather than finished.\n writeBlocked(input);\n return;\n }\n let request, answer, pendingSession, decision;\n // The ask blocks the process until it is answered: here from the\n // phone, or in the terminal (permission.replied below).\n const askId = text(input?.id);\n if (askId) { asking.add(askId); recordStatus("blocked", text(input?.sessionID)); }\n try {\n const sessionID = text(input?.sessionID), id = text(input?.id);\n if (!OPENCODE_SESSION.test(sessionID) || !id) { setStatus(output, "ask"); return; }\n // A second request for this session belongs in the terminal until\n // the existing phone request has finished.\n if (pendingApprovals.has(sessionID)) { setStatus(output, "ask"); return; }\n pendingApprovals.add(sessionID);\n pendingSession = sessionID;\n const paths = approvalPaths(sessionID);\n request = paths.request; answer = paths.answer;\n mkdirSync(approvalDirectory(), { recursive: true });\n removeFile(answer);\n const created = Date.now();\n writeJsonAtomic(request, { id, sessionID, type: text(input.type) || "action",\n title: text(input.title) || `Allow ${text(input.type) || "action"}?`, message: permissionMessage(input),\n createdAt: new Date(created).toISOString(), expiresAt: new Date(created + APPROVAL_DEADLINE_MS).toISOString() });\n const deadline = created + APPROVAL_DEADLINE_MS;\n while (Date.now() < deadline) {\n await sleep(APPROVAL_POLL_MS);\n try {\n const info = lstatSync(answer);\n if (!info.isFile() || info.size > 65_536) continue;\n const value = JSON.parse(readFileSync(answer, "utf8"));\n if (value && value.id === id) { decision = value.decision; break; }\n } catch {}\n }\n setStatus(output, decision === "approve" ? "allow" : decision === "deny" ? "deny" : "ask");\n } catch {\n setStatus(output, "ask");\n } finally {\n if (answer) removeFile(answer);\n if (request) removeFile(request);\n if (pendingSession) pendingApprovals.delete(pendingSession);\n // Answered from the phone: back to work. Otherwise the terminal asks.\n if (askId && (decision === "approve" || decision === "deny")) { asking.delete(askId); recordStatus("working", pendingSession); }\n }\n },\n event: async ({ event }) => {\n const properties = event?.properties ?? {};\n if ((event?.type === "session.created" || event?.type === "session.updated") && properties.info?.parentID\n && OPENCODE_SESSION.test(text(properties.info.id))) children.add(properties.info.id);\n const sessionID = typeof properties.sessionID === "string" ? properties.sessionID : properties.info?.sessionID ?? properties.part?.sessionID;\n // Permission events name the ask (permission.updated / permission.asked)\n // and its answer, which may come from the terminal.\n if (event?.type === "permission.updated" || event?.type === "permission.asked") {\n const id = permissionId(properties);\n if (id) { asking.add(id); recordStatus("blocked", text(sessionID)); }\n } else if (event?.type === "permission.replied") {\n const id = permissionId(properties);\n if (id) asking.delete(id); else asking.clear();\n recordStatus("working", text(sessionID));\n }\n if (!OPENCODE_SESSION.test(text(sessionID))) return;\n if (event.type === "message.updated") rememberInfo(sessionID, properties.info);\n else if (event.type === "message.part.updated") rememberPart(sessionID, properties.part?.messageID, properties.part);\n else if (event.type === "message.part.delta" && properties.field === "text" && typeof properties.delta === "string") {\n const message = messageState(sessionID, properties.messageID);\n const part = message.parts.get(properties.partID);\n if (part?.type === "text") rememberPart(sessionID, properties.messageID, { ...part, text: text(part.text) + properties.delta });\n }\n else if (event.type === "message.removed") {\n const state = sessions.get(sessionID);\n if (state && typeof properties.messageID === "string") {\n state.messages.delete(properties.messageID);\n state.order = state.order.filter(id => id !== properties.messageID);\n schedule(sessionID);\n }\n } else if (event.type === "session.idle" || event.type === "session.error") {\n sessionState(sessionID).idle = true;\n flush(sessionID);\n if (!children.has(sessionID)) { asking.clear(); recordStatus("idle", sessionID); }\n } else if (event.type === "session.status") {\n if (properties.status?.type === "busy") sessionState(sessionID).idle = false;\n // A subagent\'s session runs inside its parent\'s turn.\n if (!children.has(sessionID) && ["busy", "retry", "idle"].includes(properties.status?.type)) {\n if (properties.status.type === "idle") asking.clear();\n recordStatus(properties.status.type === "idle" ? "idle" : "working", sessionID);\n }\n }\n },\n };\n};\n';
|
|
39966
|
-
const here =
|
|
40010
|
+
const here = path48.dirname(fileURLToPath5(import.meta.url));
|
|
39967
40011
|
for (const candidate of [
|
|
39968
|
-
|
|
39969
|
-
|
|
40012
|
+
path48.join(here, "..", "..", "plugins", "opencode", "phren-transcript.js"),
|
|
40013
|
+
path48.join(here, "..", "plugins", "opencode", "phren-transcript.js")
|
|
39970
40014
|
]) {
|
|
39971
40015
|
const source = await missingFile(readFile18(candidate, "utf8"));
|
|
39972
40016
|
if (source !== void 0) return source;
|
|
@@ -39974,7 +40018,7 @@ async function opencodePluginSource() {
|
|
|
39974
40018
|
return void 0;
|
|
39975
40019
|
}
|
|
39976
40020
|
async function applyOpencodePlugin(remove = false) {
|
|
39977
|
-
const dir = opencodePluginsDir(), file2 =
|
|
40021
|
+
const dir = opencodePluginsDir(), file2 = path48.join(dir, "phren-transcript.js");
|
|
39978
40022
|
const source = await opencodePluginSource();
|
|
39979
40023
|
const existing = await missingFile(readFile18(file2, "utf8"));
|
|
39980
40024
|
if (remove) {
|
|
@@ -39982,14 +40026,14 @@ async function applyOpencodePlugin(remove = false) {
|
|
|
39982
40026
|
return false;
|
|
39983
40027
|
}
|
|
39984
40028
|
if (source === void 0 || !opencodePluginNeedsWrite(existing, source)) return false;
|
|
39985
|
-
if (!(await lstat9(
|
|
40029
|
+
if (!(await lstat9(path48.dirname(dir)).catch(() => null))?.isDirectory()) return false;
|
|
39986
40030
|
await mkdir10(dir, { recursive: true });
|
|
39987
40031
|
await atomic(file2, source, 420);
|
|
39988
40032
|
return true;
|
|
39989
40033
|
}
|
|
39990
40034
|
async function applyAgentHooks(edits) {
|
|
39991
40035
|
for (const { file: file2, before, after } of edits) {
|
|
39992
|
-
await mkdir10(
|
|
40036
|
+
await mkdir10(path48.dirname(file2), { recursive: true, mode: 448 });
|
|
39993
40037
|
if (await missingFile(readFile18(file2, "utf8")) !== before) throw new Error("Agent settings changed during installation. Run install again.");
|
|
39994
40038
|
if (before !== void 0) await copyFile2(file2, file2 + `.phren-hook-${Date.now()}.bak`);
|
|
39995
40039
|
await atomic(file2, after);
|
|
@@ -40003,18 +40047,18 @@ async function restoreAgentHooks(edits) {
|
|
|
40003
40047
|
}
|
|
40004
40048
|
}
|
|
40005
40049
|
async function rollback() {
|
|
40006
|
-
const config3 = JSON.parse(await readFile18(
|
|
40050
|
+
const config3 = JSON.parse(await readFile18(path48.join(bridgeRoot(), "installed.json"), "utf8"));
|
|
40007
40051
|
if (!config3.previous || !/^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(config3.previous)) throw new Error("No previous helper version is available.");
|
|
40008
40052
|
await stopService();
|
|
40009
40053
|
await activate(config3.previous);
|
|
40010
40054
|
await startService();
|
|
40011
|
-
await atomic(
|
|
40055
|
+
await atomic(path48.join(bridgeRoot(), "installed.json"), JSON.stringify({ version: config3.previous, previous: config3.version }) + "\n");
|
|
40012
40056
|
}
|
|
40013
40057
|
|
|
40014
40058
|
// src/bridge/computers.ts
|
|
40015
40059
|
init_protocol();
|
|
40016
40060
|
var exec8 = promisify8(execFile9);
|
|
40017
|
-
var dispatchKeyPath = (root = bridgeRoot()) =>
|
|
40061
|
+
var dispatchKeyPath = (root = bridgeRoot()) => path49.join(root, "id_ed25519_dispatch");
|
|
40018
40062
|
function publicComputerKey(value2) {
|
|
40019
40063
|
const match = /^ssh-ed25519 ([A-Za-z0-9+/]+={0,2})(?: [^\r\n]*)?$/.exec(value2.trim());
|
|
40020
40064
|
if (!match) throw new BridgeError(400, "Supply one ed25519 public key.");
|
|
@@ -40040,7 +40084,7 @@ async function enrollComputer(name, root = bridgeRoot()) {
|
|
|
40040
40084
|
computerName.parse(name);
|
|
40041
40085
|
await mkdir11(root, { recursive: true, mode: 448 });
|
|
40042
40086
|
await chmod3(root, 448);
|
|
40043
|
-
const lock =
|
|
40087
|
+
const lock = path49.join(root, "enroll-computer.lock");
|
|
40044
40088
|
try {
|
|
40045
40089
|
await mkdir11(lock, { mode: 448 });
|
|
40046
40090
|
} catch {
|
|
@@ -40049,9 +40093,9 @@ async function enrollComputer(name, root = bridgeRoot()) {
|
|
|
40049
40093
|
try {
|
|
40050
40094
|
const key2 = dispatchKeyPath(root);
|
|
40051
40095
|
if (!await regularFile(key2)) {
|
|
40052
|
-
const temporary = await mkdtemp2(
|
|
40096
|
+
const temporary = await mkdtemp2(path49.join(root, "enroll-"));
|
|
40053
40097
|
try {
|
|
40054
|
-
const generated =
|
|
40098
|
+
const generated = path49.join(temporary, "key");
|
|
40055
40099
|
await exec8("ssh-keygen", ["-q", "-t", "ed25519", "-N", "", "-C", "phren-computer", "-f", generated], { timeout: 1e4 });
|
|
40056
40100
|
await rename6(generated, key2);
|
|
40057
40101
|
} finally {
|
|
@@ -40065,7 +40109,7 @@ async function enrollComputer(name, root = bridgeRoot()) {
|
|
|
40065
40109
|
await rm5(lock, { recursive: true, force: true });
|
|
40066
40110
|
}
|
|
40067
40111
|
}
|
|
40068
|
-
async function acceptComputer(name, input2, sshDirectory =
|
|
40112
|
+
async function acceptComputer(name, input2, sshDirectory = path49.join(homedir14(), ".ssh")) {
|
|
40069
40113
|
computerName.parse(name);
|
|
40070
40114
|
const prefix = `restrict,pty,${forcedCommand} `;
|
|
40071
40115
|
const raw = input2.trim();
|
|
@@ -40079,19 +40123,19 @@ async function acceptComputer(name, input2, sshDirectory = path48.join(homedir14
|
|
|
40079
40123
|
sshDirectory
|
|
40080
40124
|
);
|
|
40081
40125
|
}
|
|
40082
|
-
async function appendAuthorizedKey(line, conflicts, conflictMessage, sshDirectory =
|
|
40126
|
+
async function appendAuthorizedKey(line, conflicts, conflictMessage, sshDirectory = path49.join(homedir14(), ".ssh")) {
|
|
40083
40127
|
const directory = await lstat10(sshDirectory).catch(() => void 0);
|
|
40084
40128
|
if (directory && (!directory.isDirectory() || directory.isSymbolicLink())) throw new BridgeError(409, "Refusing an unexpected SSH directory.");
|
|
40085
40129
|
await mkdir11(sshDirectory, { recursive: true, mode: 448 });
|
|
40086
40130
|
await chmod3(sshDirectory, 448);
|
|
40087
|
-
const lock =
|
|
40131
|
+
const lock = path49.join(sshDirectory, ".phren-enroll.lock");
|
|
40088
40132
|
try {
|
|
40089
40133
|
await mkdir11(lock, { mode: 448 });
|
|
40090
40134
|
} catch {
|
|
40091
40135
|
throw new BridgeError(409, "SSH enrollment is already running; inspect .phren-enroll.lock if interrupted.");
|
|
40092
40136
|
}
|
|
40093
|
-
const file2 =
|
|
40094
|
-
const temporary =
|
|
40137
|
+
const file2 = path49.join(sshDirectory, "authorized_keys");
|
|
40138
|
+
const temporary = path49.join(lock, "authorized_keys");
|
|
40095
40139
|
try {
|
|
40096
40140
|
const before = await regularFile(file2) ? await readFile19(file2, "utf8") : "";
|
|
40097
40141
|
const lines = before.split("\n").filter(Boolean);
|
|
@@ -40198,10 +40242,10 @@ function projectAgents(values, parent, receipt, fallbackComputer, fallbackTarget
|
|
|
40198
40242
|
for (const value2 of values.slice(0, 128)) {
|
|
40199
40243
|
if (state.count >= 128) break;
|
|
40200
40244
|
const raw = object2(value2), id2 = childID.safeParse(raw.id), source = provider.safeParse(raw.provider);
|
|
40201
|
-
const
|
|
40245
|
+
const path86 = publicLabel(raw.path);
|
|
40202
40246
|
const callId = typeof raw.callId === "string" && raw.callId.length > 0 && raw.callId.length <= 200 ? raw.callId : void 0;
|
|
40203
40247
|
const routed = destination(raw, fallbackComputer, fallbackTarget);
|
|
40204
|
-
if (!id2.success || !source.success || !
|
|
40248
|
+
if (!id2.success || !source.success || !path86 || !callId || !routed) continue;
|
|
40205
40249
|
const descendant = lineage ? `${lineage}/${id2.data}` : id2.data;
|
|
40206
40250
|
const nestedSession = sessionId.safeParse(raw.session);
|
|
40207
40251
|
const cycleIdentity = nestedSession.success ? nestedSession.data : routed.remote.child ?? routed.remote.target.session;
|
|
@@ -40214,7 +40258,7 @@ function projectAgents(values, parent, receipt, fallbackComputer, fallbackTarget
|
|
|
40214
40258
|
projected.push({
|
|
40215
40259
|
id: publicID(parent, routed.computer.id, receipt.id, descendant),
|
|
40216
40260
|
provider: source.data,
|
|
40217
|
-
path:
|
|
40261
|
+
path: path86,
|
|
40218
40262
|
callId,
|
|
40219
40263
|
state: raw.failed === true ? "failed" : childState,
|
|
40220
40264
|
...typeof raw.finishedAt === "string" && Number.isFinite(Date.parse(raw.finishedAt)) ? { finishedAt: raw.finishedAt } : {},
|
|
@@ -40276,7 +40320,7 @@ init_logger();
|
|
|
40276
40320
|
init_client();
|
|
40277
40321
|
import { spawn as spawn5 } from "node:child_process";
|
|
40278
40322
|
import { lstat as lstat11, mkdtemp as mkdtemp3, readFile as readFile20, rm as rm6, writeFile as writeFile6 } from "node:fs/promises";
|
|
40279
|
-
import
|
|
40323
|
+
import path50 from "node:path";
|
|
40280
40324
|
import { Duplex } from "node:stream";
|
|
40281
40325
|
init_protocol();
|
|
40282
40326
|
var peerSchema = external_exports.object({
|
|
@@ -40288,7 +40332,7 @@ var peerSchema = external_exports.object({
|
|
|
40288
40332
|
server: serverName.default("default")
|
|
40289
40333
|
}).strict();
|
|
40290
40334
|
async function hookPeers(root = bridgeRoot()) {
|
|
40291
|
-
const file2 =
|
|
40335
|
+
const file2 = path50.join(root, "hooks.yaml");
|
|
40292
40336
|
const info = await lstat11(file2).catch((error62) => {
|
|
40293
40337
|
if (error62.code === "ENOENT") return void 0;
|
|
40294
40338
|
throw new BridgeError(409, `hooks.yaml could not be read (${error62.code ?? "unknown error"}).`);
|
|
@@ -40310,7 +40354,7 @@ async function addHookPeer(input2, root = bridgeRoot()) {
|
|
|
40310
40354
|
const clash = existing.find((other) => other.name === peer.name || other.address === peer.address && other.port === peer.port && other.server === peer.server);
|
|
40311
40355
|
if (clash) throw new BridgeError(409, `hooks.yaml already has ${clash.name} at ${clash.address}; remove that entry first to link it differently.`);
|
|
40312
40356
|
if (existing.length >= 32) throw new BridgeError(409, "hooks.yaml already has 32 computers.");
|
|
40313
|
-
await atomic(
|
|
40357
|
+
await atomic(path50.join(root, "hooks.yaml"), dump({ version: 1, computers: [...existing, peer] }, { lineWidth: -1 }));
|
|
40314
40358
|
return { added: true, peer };
|
|
40315
40359
|
}
|
|
40316
40360
|
async function optionalHookPeers(root = bridgeRoot()) {
|
|
@@ -40391,10 +40435,10 @@ async function peerRequest(peer, route2, data, timeout) {
|
|
|
40391
40435
|
const root = bridgeRoot(), key2 = dispatchKeyPath(root);
|
|
40392
40436
|
const info = await lstat11(key2).catch(() => void 0);
|
|
40393
40437
|
if (!info?.isFile() || info.isSymbolicLink() || info.mode & 63) throw new BridgeError(409, "Run phren bridge enroll-computer on this computer first (private key mode 0600).", { code: "dispatch-key-missing" });
|
|
40394
|
-
const temporary = await mkdtemp3(
|
|
40438
|
+
const temporary = await mkdtemp3(path50.join(root, "peer-"));
|
|
40395
40439
|
let child, stream;
|
|
40396
40440
|
try {
|
|
40397
|
-
const knownHosts =
|
|
40441
|
+
const knownHosts = path50.join(temporary, "known_hosts");
|
|
40398
40442
|
await writeFile6(knownHosts, `phren-peer ${peer.hostKey}
|
|
40399
40443
|
`, { mode: 384 });
|
|
40400
40444
|
const ssh2 = spawn5("ssh", peerSSHArgs(peer, knownHosts, key2), { stdio: ["pipe", "pipe", "pipe"] });
|
|
@@ -40531,21 +40575,21 @@ var receiptSchema2 = dispatchSchema.omit({ prompt: true }).extend({
|
|
|
40531
40575
|
async function dispatchProjectDirectory(project) {
|
|
40532
40576
|
const name = projectName.parse(project);
|
|
40533
40577
|
const source = readProjectConfig(phrenStoreRoot(), name).sourcePath;
|
|
40534
|
-
if (typeof source !== "string" || !
|
|
40578
|
+
if (typeof source !== "string" || !path51.isAbsolute(source) || /[\x00-\x1f\x7f]/.test(source)) throw new BridgeError(404, "Project has no absolute sourcePath on this computer.");
|
|
40535
40579
|
const directory = await realpath10(source).catch(() => void 0);
|
|
40536
40580
|
if (!directory || !(await stat15(directory)).isDirectory()) throw new BridgeError(404, "Project is not on this computer.");
|
|
40537
40581
|
return directory;
|
|
40538
40582
|
}
|
|
40539
40583
|
async function save(receipt) {
|
|
40540
|
-
const root =
|
|
40584
|
+
const root = path51.join(bridgeRoot(), "dispatches");
|
|
40541
40585
|
await mkdir12(root, { recursive: true, mode: 448 });
|
|
40542
|
-
await atomic(
|
|
40586
|
+
await atomic(path51.join(root, `${receipt.id}.json`), receipt);
|
|
40543
40587
|
}
|
|
40544
40588
|
var MAX_RECEIPT_BYTES = 65536;
|
|
40545
40589
|
var receiptUpdates = Promise.resolve();
|
|
40546
40590
|
function updateReceipt(receiptID, change) {
|
|
40547
40591
|
const run = receiptUpdates.then(async () => {
|
|
40548
|
-
const file2 =
|
|
40592
|
+
const file2 = path51.join(bridgeRoot(), "dispatches", `${external_exports.string().uuid().parse(receiptID)}.json`);
|
|
40549
40593
|
const info = await lstat12(file2).catch(() => void 0);
|
|
40550
40594
|
if (!info?.isFile() || info.isSymbolicLink() || info.size > MAX_RECEIPT_BYTES) return void 0;
|
|
40551
40595
|
const receipt = receiptSchema2.parse(JSON.parse(await readFile21(file2, "utf8")));
|
|
@@ -40573,12 +40617,12 @@ function failureReason(error62) {
|
|
|
40573
40617
|
return `${typeof code === "string" && !(error62 instanceof BridgeError) ? `${code}: ` : ""}${message}`.replace(/[\x00-\x1f\x7f]/g, " ").slice(0, 200);
|
|
40574
40618
|
}
|
|
40575
40619
|
async function dispatchStatus() {
|
|
40576
|
-
const root =
|
|
40620
|
+
const root = path51.join(bridgeRoot(), "dispatches");
|
|
40577
40621
|
const names = (await receiptNames(root)).filter((name) => /^[a-f0-9-]{36}\.json$/.test(name)).slice(0, 1024);
|
|
40578
40622
|
const receipts = [];
|
|
40579
40623
|
for (const name of names) {
|
|
40580
40624
|
try {
|
|
40581
|
-
const file2 =
|
|
40625
|
+
const file2 = path51.join(root, name);
|
|
40582
40626
|
const info = await lstat12(file2);
|
|
40583
40627
|
if (!info.isFile() || info.isSymbolicLink() || info.size > MAX_RECEIPT_BYTES) continue;
|
|
40584
40628
|
const receipt = receiptSchema2.parse(JSON.parse(await readFile21(file2, "utf8")));
|
|
@@ -40653,7 +40697,7 @@ var DispatchService = class {
|
|
|
40653
40697
|
if (!this.identity) throw new BridgeError(503, "This Hook cannot validate a dispatch parent.");
|
|
40654
40698
|
await validateDispatchParent(data, this.identity.computerID, this.identity.validateParentTarget);
|
|
40655
40699
|
}
|
|
40656
|
-
if ((await receiptNames(
|
|
40700
|
+
if ((await receiptNames(path51.join(bridgeRoot(), "dispatches"))).length >= 1024) throw new BridgeError(429, "Dispatch history is full. Archive old receipts before dispatching again.");
|
|
40657
40701
|
const here = this.local();
|
|
40658
40702
|
const toLocal = data.computer !== "anywhere" && isLocalComputer(data.computer, here.names);
|
|
40659
40703
|
const enrolled = await hookPeers().catch((error62) => {
|
|
@@ -41328,12 +41372,12 @@ init_zod();
|
|
|
41328
41372
|
init_protocol();
|
|
41329
41373
|
init_herdr();
|
|
41330
41374
|
init_transcripts();
|
|
41331
|
-
init_transcript_index();
|
|
41332
41375
|
import { execFile as execFile10 } from "node:child_process";
|
|
41333
41376
|
import { createHash as createHash12 } from "node:crypto";
|
|
41334
41377
|
import { mkdir as mkdir13, open as open12, stat as stat17, readFile as readFile22, writeFile as writeFile7 } from "node:fs/promises";
|
|
41335
|
-
import
|
|
41378
|
+
import path52 from "node:path";
|
|
41336
41379
|
import { promisify as promisify9 } from "node:util";
|
|
41380
|
+
init_transcript_index();
|
|
41337
41381
|
var exec9 = promisify9(execFile10);
|
|
41338
41382
|
var text3 = external_exports.string().trim().min(1).max(4e3).refine((t) => !/[\x00-\x08\x0b-\x1f\x7f]/.test(t));
|
|
41339
41383
|
var question = external_exports.object({ title: text3, options: external_exports.array(text3).max(12).nullable().optional() });
|
|
@@ -41377,7 +41421,7 @@ var answersQuestions = (reply, questions) => questions.every((q) => {
|
|
|
41377
41421
|
});
|
|
41378
41422
|
async function pendingAsyncQuestions(file2, targetID) {
|
|
41379
41423
|
return withTranscriptIndex(file2, async (handle, index2) => {
|
|
41380
|
-
const replies = [], acknowledged = /* @__PURE__ */ new Set(), resolved = /* @__PURE__ */ new Set(), pending = [];
|
|
41424
|
+
const replies = [], acknowledged = /* @__PURE__ */ new Set(), resolved = /* @__PURE__ */ new Set(), seen = /* @__PURE__ */ new Set(), pending = [];
|
|
41381
41425
|
let bytes = 0;
|
|
41382
41426
|
for await (const row of index2.rows(handle, index2.lines, Math.max(0, index2.lines - 1e4))) {
|
|
41383
41427
|
if (!row.bytes || (bytes += row.bytes.length) > 8388608) throw new BridgeError(413, "The pending question history is too large to verify.");
|
|
@@ -41403,10 +41447,11 @@ async function pendingAsyncQuestions(file2, targetID) {
|
|
|
41403
41447
|
if (targetID && resolved.has(targetID)) return [];
|
|
41404
41448
|
if (!id2 || !acknowledged.has(id2)) continue;
|
|
41405
41449
|
const questions = asyncQuestion(raw, id2);
|
|
41406
|
-
if (questions && !replies.some((reply) => answersQuestions(reply, questions))) {
|
|
41450
|
+
if (questions && !seen.has(id2) && !replies.some((reply) => answersQuestions(reply, questions))) {
|
|
41407
41451
|
pending.push({ id: id2, questions });
|
|
41408
41452
|
if (pending.length >= 64) throw new BridgeError(413, "Too many pending questions to verify.");
|
|
41409
41453
|
}
|
|
41454
|
+
if (questions) seen.add(id2);
|
|
41410
41455
|
if (targetID && questions && id2 === targetID) return pending.filter((p2) => p2.id === targetID);
|
|
41411
41456
|
}
|
|
41412
41457
|
if (index2.lines > 1e4) throw new BridgeError(413, "The pending question history is too large to verify.");
|
|
@@ -41419,10 +41464,11 @@ async function pendingAsyncQuestion(file2, id2) {
|
|
|
41419
41464
|
return pending.questions;
|
|
41420
41465
|
}
|
|
41421
41466
|
var CodexQuestions = class {
|
|
41422
|
-
|
|
41423
|
-
|
|
41467
|
+
/** No executable: the real `codex` on PATH, past phren's session wrapper. */
|
|
41468
|
+
constructor(configured) {
|
|
41469
|
+
this.configured = configured;
|
|
41424
41470
|
}
|
|
41425
|
-
|
|
41471
|
+
configured;
|
|
41426
41472
|
snapshots = /* @__PURE__ */ new Map();
|
|
41427
41473
|
failedSnapshots = /* @__PURE__ */ new Map();
|
|
41428
41474
|
inboxAvailable = false;
|
|
@@ -41432,6 +41478,9 @@ var CodexQuestions = class {
|
|
|
41432
41478
|
return this.inboxAvailable;
|
|
41433
41479
|
}
|
|
41434
41480
|
probe;
|
|
41481
|
+
get executable() {
|
|
41482
|
+
return this.configured ?? codexExecutable();
|
|
41483
|
+
}
|
|
41435
41484
|
supported() {
|
|
41436
41485
|
if (!this.probe || Date.now() - this.probe.at > 3e5) this.probe = { at: Date.now(), result: exec9(this.executable, ["queue", "--help"], { timeout: 5e3, maxBuffer: 65536 }).then(({ stdout }) => stdout.includes("--thread") && stdout.includes("--message")).catch(() => false).then((available) => {
|
|
41437
41486
|
this.inboxAvailable = available;
|
|
@@ -41458,7 +41507,7 @@ var CodexQuestions = class {
|
|
|
41458
41507
|
}
|
|
41459
41508
|
return Promise.all((pending ?? []).map(async (p) => {
|
|
41460
41509
|
const key2 = createHash12("sha256").update(JSON.stringify([target.source, target.session, p.id])).digest("hex");
|
|
41461
|
-
const submitted = await readFile22(
|
|
41510
|
+
const submitted = await readFile22(path52.join(bridgeRoot(), "question-replies", key2), "utf8").then((value2) => value2 === "submitted").catch(() => false);
|
|
41462
41511
|
return { toolUseId: p.id, isAsync: true, submitted, questions: p.questions.map((q) => ({
|
|
41463
41512
|
question: q.title,
|
|
41464
41513
|
options: (q.options ?? []).map((label2) => ({ label: label2 })),
|
|
@@ -41474,10 +41523,10 @@ var CodexQuestions = class {
|
|
|
41474
41523
|
const reply = questionReply(questions, data.answers);
|
|
41475
41524
|
const pane = await validateTarget(target);
|
|
41476
41525
|
if (await paneIdentity(target.server, pane, true) !== target.session) throw new BridgeError(409, "This pane's conversation changed. Reopen the chat.");
|
|
41477
|
-
const directory =
|
|
41526
|
+
const directory = path52.join(bridgeRoot(), "question-replies");
|
|
41478
41527
|
await mkdir13(directory, { recursive: true, mode: 448 });
|
|
41479
41528
|
const key2 = createHash12("sha256").update(JSON.stringify([target.source, target.session, id2])).digest("hex");
|
|
41480
|
-
const receiptPath =
|
|
41529
|
+
const receiptPath = path52.join(directory, key2);
|
|
41481
41530
|
const receipt = await open12(receiptPath, "wx", 384).catch((error62) => {
|
|
41482
41531
|
if (error62.code === "EEXIST") throw new BridgeError(409, "An answer was already submitted. Check the conversation before answering again.");
|
|
41483
41532
|
throw new BridgeError(503, "Phren could not record this answer. Nothing was sent.");
|
|
@@ -41502,10 +41551,10 @@ init_protocol();
|
|
|
41502
41551
|
import { spawn as spawn6 } from "node:child_process";
|
|
41503
41552
|
import { readdir as readdir11, readFile as readFile23, stat as stat18 } from "node:fs/promises";
|
|
41504
41553
|
import { homedir as homedir15 } from "node:os";
|
|
41505
|
-
import
|
|
41506
|
-
function readCodexModels(
|
|
41554
|
+
import path53 from "node:path";
|
|
41555
|
+
function readCodexModels(executable2 = codexExecutable()) {
|
|
41507
41556
|
return new Promise((resolve11) => {
|
|
41508
|
-
const child = spawn6(
|
|
41557
|
+
const child = spawn6(executable2, ["app-server"], { cwd: homedir15(), stdio: ["pipe", "pipe", "ignore"] });
|
|
41509
41558
|
let pending = "", bytes = 0, initialized = false, done = false;
|
|
41510
41559
|
const finish = (result = []) => {
|
|
41511
41560
|
if (done) return;
|
|
@@ -41581,12 +41630,12 @@ var CLAUDE_MENU = [
|
|
|
41581
41630
|
{ id: "claude-fable-5-1[1m]", name: "Fable 5.1 (1M context)", description: "Fable 5.1 with a 1M context window." }
|
|
41582
41631
|
];
|
|
41583
41632
|
async function readClaudeCatalog(configDir = claudeConfigDir(), installed) {
|
|
41584
|
-
const directory =
|
|
41633
|
+
const directory = path53.join(configDir, "cache", "model-catalog");
|
|
41585
41634
|
let newest;
|
|
41586
41635
|
try {
|
|
41587
41636
|
for (const name of await readdir11(directory)) {
|
|
41588
41637
|
if (!name.endsWith("-cc.json")) continue;
|
|
41589
|
-
const file2 =
|
|
41638
|
+
const file2 = path53.join(directory, name), at = (await stat18(file2)).mtimeMs;
|
|
41590
41639
|
if (!newest || at > newest.at) newest = { file: file2, at };
|
|
41591
41640
|
}
|
|
41592
41641
|
} catch {
|
|
@@ -41640,9 +41689,9 @@ function olderVersion(installed, required2) {
|
|
|
41640
41689
|
for (let index2 = 0; index2 < 3; index2++) if (have[index2] !== need[index2]) return have[index2] < need[index2];
|
|
41641
41690
|
return false;
|
|
41642
41691
|
}
|
|
41643
|
-
function claudeVersion(
|
|
41692
|
+
function claudeVersion(executable2 = "claude") {
|
|
41644
41693
|
return new Promise((resolve11) => {
|
|
41645
|
-
const child = spawn6(
|
|
41694
|
+
const child = spawn6(executable2, ["--version"], { cwd: homedir15(), stdio: ["ignore", "pipe", "ignore"] });
|
|
41646
41695
|
let out = "";
|
|
41647
41696
|
const timer = setTimeout(() => {
|
|
41648
41697
|
child.kill("SIGKILL");
|
|
@@ -41667,9 +41716,9 @@ async function readClaudeModels(configDir, installed) {
|
|
|
41667
41716
|
const live = await readClaudeCatalog(configDir, version3).catch(() => []);
|
|
41668
41717
|
return live.length ? live : CLAUDE_MENU.map((model) => ({ ...model }));
|
|
41669
41718
|
}
|
|
41670
|
-
async function readOpenCodeModels(
|
|
41719
|
+
async function readOpenCodeModels(executable2 = "opencode", configDir = path53.join(homedir15(), ".config/opencode")) {
|
|
41671
41720
|
const listed2 = await new Promise((resolve11) => {
|
|
41672
|
-
const child = spawn6(
|
|
41721
|
+
const child = spawn6(executable2, ["models"], { cwd: homedir15(), stdio: ["ignore", "pipe", "ignore"] });
|
|
41673
41722
|
let out = "", done = false;
|
|
41674
41723
|
const finish = () => {
|
|
41675
41724
|
if (!done) {
|
|
@@ -41694,7 +41743,7 @@ async function readOpenCodeModels(executable = "opencode", configDir = path52.jo
|
|
|
41694
41743
|
let configured;
|
|
41695
41744
|
for (const file2 of ["opencode.json", "opencode.jsonc"]) {
|
|
41696
41745
|
try {
|
|
41697
|
-
const text4 = await readFile23(
|
|
41746
|
+
const text4 = await readFile23(path53.join(configDir, file2), "utf8");
|
|
41698
41747
|
const model = /"model"\s*:\s*"([^"]+)"/.exec(text4)?.[1];
|
|
41699
41748
|
if (model) {
|
|
41700
41749
|
configured = model.slice(0, 200);
|
|
@@ -42164,14 +42213,14 @@ init_project_config();
|
|
|
42164
42213
|
init_shared();
|
|
42165
42214
|
import { randomUUID as randomUUID11 } from "node:crypto";
|
|
42166
42215
|
import { hostname as hostname6 } from "node:os";
|
|
42167
|
-
import
|
|
42216
|
+
import path56 from "node:path";
|
|
42168
42217
|
|
|
42169
42218
|
// src/bridge/schedule-format.ts
|
|
42170
42219
|
init_js_yaml();
|
|
42171
42220
|
init_zod();
|
|
42172
42221
|
init_protocol();
|
|
42173
42222
|
import { readFile as readFile24 } from "node:fs/promises";
|
|
42174
|
-
import
|
|
42223
|
+
import path54 from "node:path";
|
|
42175
42224
|
var SCHEDULE_EVERY = ["interval", "daily", "weekly", "once", "cron"];
|
|
42176
42225
|
var SCHEDULE_HARNESSES = ["claude", "codex", "opencode"];
|
|
42177
42226
|
var SCHEDULE_NOTIFY = ["start", "finish", "failure"];
|
|
@@ -42184,7 +42233,7 @@ var scheduleName = singleLine(80);
|
|
|
42184
42233
|
var timestamp3 = external_exports.string().datetime({ offset: true });
|
|
42185
42234
|
var localTimestamp = external_exports.string().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/);
|
|
42186
42235
|
var clockTime = external_exports.string().regex(/^(?:[01]\d|2[0-3]):[0-5]\d$/);
|
|
42187
|
-
var schedulePath = (projectDir) =>
|
|
42236
|
+
var schedulePath = (projectDir) => path54.join(projectDir, "schedules.yaml");
|
|
42188
42237
|
var runningStatuses = /* @__PURE__ */ new Set(["launched", "running", "blocked"]);
|
|
42189
42238
|
var MAX_SCHEDULES = 64;
|
|
42190
42239
|
var MAX_RUNS = 2e3;
|
|
@@ -42384,7 +42433,7 @@ async function writeScheduleRuns(file2, runs) {
|
|
|
42384
42433
|
await atomicInPrivateDir(file2, kept.map((run) => JSON.stringify(run)).join("\n") + (kept.length ? "\n" : ""));
|
|
42385
42434
|
}
|
|
42386
42435
|
function scheduleRunsFile() {
|
|
42387
|
-
return
|
|
42436
|
+
return path54.join(bridgeRoot(), "schedule-runs.jsonl");
|
|
42388
42437
|
}
|
|
42389
42438
|
|
|
42390
42439
|
// src/bridge/schedule-launch.ts
|
|
@@ -42398,7 +42447,7 @@ init_shared();
|
|
|
42398
42447
|
import { spawn as spawn7 } from "node:child_process";
|
|
42399
42448
|
import { createWriteStream } from "node:fs";
|
|
42400
42449
|
import { mkdir as mkdir14, readFile as readFile25, stat as stat19 } from "node:fs/promises";
|
|
42401
|
-
import
|
|
42450
|
+
import path55 from "node:path";
|
|
42402
42451
|
import { finished as streamFinished } from "node:stream/promises";
|
|
42403
42452
|
var CLAUDE_SCHEDULE_SETTINGS = JSON.stringify({ enableAllProjectMcpServers: true });
|
|
42404
42453
|
function createScheduleLauncher(launchHerdr, store = defaultPhrenPath()) {
|
|
@@ -42431,7 +42480,7 @@ async function resumeScheduleRun(run, schedule, signal, watch2 = watchHerdrRun)
|
|
|
42431
42480
|
);
|
|
42432
42481
|
}
|
|
42433
42482
|
if (launch2.mode === "headless" && launch2.jobDir) {
|
|
42434
|
-
const manifest = await readFile25(
|
|
42483
|
+
const manifest = await readFile25(path55.join(launch2.jobDir, "manifest.json"), "utf8").then((text4) => JSON.parse(text4)).catch(() => void 0);
|
|
42435
42484
|
if (manifest?.status === "completed") return { status: "finished" };
|
|
42436
42485
|
if (manifest?.status === "failed") {
|
|
42437
42486
|
return { status: "failed", reason: typeof manifest.exitCode === "number" ? `The scheduled agent exited with code ${manifest.exitCode}.` : "The scheduled agent failed." };
|
|
@@ -42479,7 +42528,7 @@ async function promptWhenReady(server, paneId, text4, signal, waitMs = 6e4) {
|
|
|
42479
42528
|
}
|
|
42480
42529
|
}
|
|
42481
42530
|
async function launchHeadless(context, store, started) {
|
|
42482
|
-
const root = fanoutRoot({ ...process.env, PHREN_PATH: store }), jobDir =
|
|
42531
|
+
const root = fanoutRoot({ ...process.env, PHREN_PATH: store }), jobDir = path55.join(root, context.runId);
|
|
42483
42532
|
await mkdir14(jobDir, { recursive: true, mode: 448 });
|
|
42484
42533
|
const eventLog = "events.jsonl", now = (/* @__PURE__ */ new Date()).toISOString();
|
|
42485
42534
|
const manifest = {
|
|
@@ -42499,7 +42548,7 @@ async function launchHeadless(context, store, started) {
|
|
|
42499
42548
|
};
|
|
42500
42549
|
await writeManifest2(jobDir, manifest);
|
|
42501
42550
|
const command = headlessCommand(context.schedule, context.cwd);
|
|
42502
|
-
if (context.schedule.harness === "codex") await ensureCodexDirTrusted(context.cwd).catch((error62) => logger.warn("schedule", `Could not mark ${
|
|
42551
|
+
if (context.schedule.harness === "codex") await ensureCodexDirTrusted(context.cwd).catch((error62) => logger.warn("schedule", `Could not mark ${path55.basename(context.cwd)} trusted for Codex (run ${context.runId}): ${error62 instanceof Error ? error62.message.split("\n")[0] : String(error62)}`));
|
|
42503
42552
|
let child;
|
|
42504
42553
|
try {
|
|
42505
42554
|
child = spawn7(command.file, command.args, { cwd: command.cwd, env: process.env, stdio: ["pipe", "pipe", "pipe"] });
|
|
@@ -42511,8 +42560,8 @@ async function launchHeadless(context, store, started) {
|
|
|
42511
42560
|
const closed = new Promise((resolve11) => {
|
|
42512
42561
|
child.once("close", (code, signal) => resolve11({ code, signal }));
|
|
42513
42562
|
});
|
|
42514
|
-
const output2 = createWriteStream(
|
|
42515
|
-
const errors = createWriteStream(
|
|
42563
|
+
const output2 = createWriteStream(path55.join(jobDir, eventLog), { flags: "a", mode: 384 });
|
|
42564
|
+
const errors = createWriteStream(path55.join(jobDir, "stderr.log"), { flags: "a", mode: 384 });
|
|
42516
42565
|
const streamsFinished = Promise.all([streamFinished(output2), streamFinished(errors)]).then(() => void 0).catch(() => void 0);
|
|
42517
42566
|
child.stdin?.on("error", () => {
|
|
42518
42567
|
});
|
|
@@ -42565,7 +42614,7 @@ function tomlQuote(value2) {
|
|
|
42565
42614
|
}
|
|
42566
42615
|
async function ensureCodexDirTrusted(cwd) {
|
|
42567
42616
|
const directory = codexHome();
|
|
42568
|
-
const file2 =
|
|
42617
|
+
const file2 = path55.join(directory, "config.toml");
|
|
42569
42618
|
let text4 = "";
|
|
42570
42619
|
try {
|
|
42571
42620
|
text4 = await readFile25(file2, "utf8");
|
|
@@ -42602,7 +42651,7 @@ ${trustLine}
|
|
|
42602
42651
|
await atomic(file2, next, mode);
|
|
42603
42652
|
}
|
|
42604
42653
|
async function writeManifest2(jobDir, manifest) {
|
|
42605
|
-
await atomicInPrivateDir(
|
|
42654
|
+
await atomicInPrivateDir(path55.join(jobDir, "manifest.json"), JSON.stringify(manifest, null, 2) + "\n");
|
|
42606
42655
|
}
|
|
42607
42656
|
|
|
42608
42657
|
// src/bridge/schedules.ts
|
|
@@ -42640,7 +42689,7 @@ var Scheduler = class {
|
|
|
42640
42689
|
return getProjectDirs(this.store);
|
|
42641
42690
|
}
|
|
42642
42691
|
projectDirectory(project) {
|
|
42643
|
-
const found = this.projectDirectories().find((directory) =>
|
|
42692
|
+
const found = this.projectDirectories().find((directory) => path56.basename(directory).toLowerCase() === project.toLowerCase());
|
|
42644
42693
|
if (!found) throw new BridgeError(404, `Unknown project "${project}".`);
|
|
42645
42694
|
return found;
|
|
42646
42695
|
}
|
|
@@ -42666,7 +42715,7 @@ var Scheduler = class {
|
|
|
42666
42715
|
} catch {
|
|
42667
42716
|
continue;
|
|
42668
42717
|
}
|
|
42669
|
-
const project =
|
|
42718
|
+
const project = path56.basename(directory);
|
|
42670
42719
|
for (const schedule of schedules) {
|
|
42671
42720
|
const matching = runs.filter((run) => run.project === project && run.scheduleId === schedule.id);
|
|
42672
42721
|
const last = matching.at(-1), running2 = matching.some((run) => runningStatuses.has(run.status));
|
|
@@ -42696,7 +42745,7 @@ var Scheduler = class {
|
|
|
42696
42745
|
}
|
|
42697
42746
|
async launchNow(projectName2, id2) {
|
|
42698
42747
|
const prepared = await this.exclusive(async () => {
|
|
42699
|
-
const projectDir = this.projectDirectory(projectName2), project =
|
|
42748
|
+
const projectDir = this.projectDirectory(projectName2), project = path56.basename(projectDir);
|
|
42700
42749
|
const file2 = await readScheduleDocument(projectDir), schedule = file2.schedules.find((item) => item.id === id2);
|
|
42701
42750
|
if (!schedule) throw new BridgeError(404, `Schedule "${id2}" was not found in ${project}.`);
|
|
42702
42751
|
if (!computerMatches(schedule.computer, this.computer())) throw new BridgeError(409, `${schedule.computer} owns this schedule; run it from that computer.`);
|
|
@@ -42857,7 +42906,7 @@ var Scheduler = class {
|
|
|
42857
42906
|
init_phren_paths();
|
|
42858
42907
|
import { lstat as lstat14, mkdtemp as mkdtemp4, realpath as realpath11, rm as rm7 } from "node:fs/promises";
|
|
42859
42908
|
import { hostname as hostname8, tmpdir } from "node:os";
|
|
42860
|
-
import
|
|
42909
|
+
import path60 from "node:path";
|
|
42861
42910
|
|
|
42862
42911
|
// src/bridge/health.ts
|
|
42863
42912
|
init_policy();
|
|
@@ -42866,7 +42915,7 @@ init_store_registry();
|
|
|
42866
42915
|
import { execFile as execFile11, spawn as spawn8 } from "node:child_process";
|
|
42867
42916
|
import { lstat as lstat13, readFile as readFile26 } from "node:fs/promises";
|
|
42868
42917
|
import { homedir as homedir16, hostname as hostname7 } from "node:os";
|
|
42869
|
-
import
|
|
42918
|
+
import path59 from "node:path";
|
|
42870
42919
|
import { promisify as promisify10 } from "node:util";
|
|
42871
42920
|
init_protocol();
|
|
42872
42921
|
init_metrics();
|
|
@@ -42894,12 +42943,12 @@ var VERSION_TIMEOUT_MS = 3e3;
|
|
|
42894
42943
|
var VERSION_CACHE_MS = 5 * 6e4;
|
|
42895
42944
|
var PEER_TIMEOUT_MS = 5e3;
|
|
42896
42945
|
var versionCache = /* @__PURE__ */ new Map();
|
|
42897
|
-
function toolVersion(tool,
|
|
42946
|
+
function toolVersion(tool, executable2 = tool) {
|
|
42898
42947
|
const cached2 = versionCache.get(tool);
|
|
42899
42948
|
if (cached2 && Date.now() - cached2.at < VERSION_CACHE_MS) return cached2.value;
|
|
42900
42949
|
const value2 = new Promise((resolve11) => {
|
|
42901
42950
|
let out = "", done = false;
|
|
42902
|
-
const child = spawn8(
|
|
42951
|
+
const child = spawn8(executable2, ["--version"], { cwd: homedir16(), stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, NO_COLOR: "1" } });
|
|
42903
42952
|
const finish = (result) => {
|
|
42904
42953
|
if (!done) {
|
|
42905
42954
|
done = true;
|
|
@@ -42980,7 +43029,7 @@ async function lastScheduledRun(store, runsFile = scheduleRunsFile()) {
|
|
|
42980
43029
|
const last = runs.reduce((newest, run) => !newest || run.startedAt >= newest.startedAt ? run : newest, void 0);
|
|
42981
43030
|
if (!last) return null;
|
|
42982
43031
|
let name;
|
|
42983
|
-
const directory = getProjectDirs(store).find((dir) =>
|
|
43032
|
+
const directory = getProjectDirs(store).find((dir) => path59.basename(dir).toLowerCase() === last.project.toLowerCase());
|
|
42984
43033
|
if (directory) name = (await readScheduleDocument(directory).catch(() => void 0))?.schedules.find((item) => item.id === last.scheduleId)?.name;
|
|
42985
43034
|
return {
|
|
42986
43035
|
...name ? { name } : {},
|
|
@@ -43034,7 +43083,7 @@ async function probePeer(peer, caller) {
|
|
|
43034
43083
|
}
|
|
43035
43084
|
}
|
|
43036
43085
|
function canaryFile(root = bridgeRoot()) {
|
|
43037
|
-
return
|
|
43086
|
+
return path59.join(root, "canary.json");
|
|
43038
43087
|
}
|
|
43039
43088
|
async function readCanary(root = bridgeRoot()) {
|
|
43040
43089
|
try {
|
|
@@ -43047,7 +43096,7 @@ async function readCanary(root = bridgeRoot()) {
|
|
|
43047
43096
|
}
|
|
43048
43097
|
}
|
|
43049
43098
|
async function pushConfigured() {
|
|
43050
|
-
const file2 = process.env.PHREN_APNS_CONFIG ||
|
|
43099
|
+
const file2 = process.env.PHREN_APNS_CONFIG || path59.join(bridgeRoot(), "apns.json");
|
|
43051
43100
|
const info = await lstat13(file2).catch(() => void 0);
|
|
43052
43101
|
return { configured: !!info?.isFile() };
|
|
43053
43102
|
}
|
|
@@ -43136,7 +43185,7 @@ async function closeCanaryWorkspaces(server, before, created) {
|
|
|
43136
43185
|
}
|
|
43137
43186
|
async function conductorStep(options, server) {
|
|
43138
43187
|
const before = new Set(objects((await snapshot(server)).workspaces).map((workspace) => String(workspace.workspace_id)));
|
|
43139
|
-
const folder = await realpath11(await mkdtemp4(
|
|
43188
|
+
const folder = await realpath11(await mkdtemp4(path60.join(tmpdir(), "phren-canary-")));
|
|
43140
43189
|
let created, failure2, detail;
|
|
43141
43190
|
try {
|
|
43142
43191
|
const launched = await options.launch(server, { role: "conductor", kind: "claude", label: CANARY_LABEL, cwd: folder, timeoutMs: 45e3 });
|
|
@@ -43157,12 +43206,12 @@ async function scheduleStep(options) {
|
|
|
43157
43206
|
let count2 = 0;
|
|
43158
43207
|
const broken = [];
|
|
43159
43208
|
for (const directory of getProjectDirs(options.store)) {
|
|
43160
|
-
const present2 = await lstat14(
|
|
43209
|
+
const present2 = await lstat14(path60.join(directory, "schedules.yaml")).catch(() => void 0);
|
|
43161
43210
|
if (!present2) continue;
|
|
43162
43211
|
try {
|
|
43163
43212
|
count2 += (await readScheduleDocument(directory)).schedules.length;
|
|
43164
43213
|
} catch (error62) {
|
|
43165
|
-
broken.push(`${
|
|
43214
|
+
broken.push(`${path60.basename(directory)}: ${reason(error62)}`);
|
|
43166
43215
|
}
|
|
43167
43216
|
}
|
|
43168
43217
|
const tick = options.scheduler.lastTickAt;
|
|
@@ -43232,7 +43281,7 @@ function runCanary(options) {
|
|
|
43232
43281
|
}
|
|
43233
43282
|
async function dailyCanaryEnabled(root = bridgeRoot()) {
|
|
43234
43283
|
if (process.env.PHREN_CANARY_DAILY === "1") return true;
|
|
43235
|
-
return !!(await lstat14(
|
|
43284
|
+
return !!(await lstat14(path60.join(root, "canary-daily")).catch(() => void 0))?.isFile();
|
|
43236
43285
|
}
|
|
43237
43286
|
async function dailyCanaryDue(root = bridgeRoot(), now = Date.now()) {
|
|
43238
43287
|
if (running || !await dailyCanaryEnabled(root)) return false;
|
|
@@ -43245,11 +43294,11 @@ init_shared();
|
|
|
43245
43294
|
|
|
43246
43295
|
// src/bridge/server-routes.ts
|
|
43247
43296
|
init_zod();
|
|
43248
|
-
import
|
|
43297
|
+
import path83 from "node:path";
|
|
43249
43298
|
|
|
43250
43299
|
// src/bridge/code-note.ts
|
|
43251
43300
|
init_zod();
|
|
43252
|
-
import * as
|
|
43301
|
+
import * as path66 from "node:path";
|
|
43253
43302
|
|
|
43254
43303
|
// src/content/validate.ts
|
|
43255
43304
|
init_utils_helpers();
|
|
@@ -43263,7 +43312,7 @@ init_store_routing();
|
|
|
43263
43312
|
init_locks();
|
|
43264
43313
|
init_data_utils();
|
|
43265
43314
|
import * as fs28 from "fs";
|
|
43266
|
-
import * as
|
|
43315
|
+
import * as path62 from "path";
|
|
43267
43316
|
import * as crypto7 from "crypto";
|
|
43268
43317
|
|
|
43269
43318
|
// src/project-topics.ts
|
|
@@ -43275,7 +43324,7 @@ init_data_utils();
|
|
|
43275
43324
|
init_filenames();
|
|
43276
43325
|
import * as crypto6 from "crypto";
|
|
43277
43326
|
import * as fs27 from "fs";
|
|
43278
|
-
import * as
|
|
43327
|
+
import * as path61 from "path";
|
|
43279
43328
|
var TOPIC_CONFIG_FILENAME = "topic-config.json";
|
|
43280
43329
|
var SOFTWARE_TOPICS = [
|
|
43281
43330
|
{
|
|
@@ -43813,7 +43862,7 @@ function topicDocHeader(project, topic) {
|
|
|
43813
43862
|
}
|
|
43814
43863
|
function appendArchivedEntriesToTopicDoc(filePath, project, topic, entries2) {
|
|
43815
43864
|
if (entries2.length === 0) return;
|
|
43816
|
-
fs27.mkdirSync(
|
|
43865
|
+
fs27.mkdirSync(path61.dirname(filePath), { recursive: true });
|
|
43817
43866
|
withFileLock(filePath, () => {
|
|
43818
43867
|
let existing = "";
|
|
43819
43868
|
if (fs27.existsSync(filePath)) existing = fs27.readFileSync(filePath, "utf8");
|
|
@@ -43932,7 +43981,7 @@ function autoArchiveToReference(phrenPath, project, keepCount) {
|
|
|
43932
43981
|
if (!isValidProjectName(project)) return phrenErr(`Invalid project name: "${project}".`, PhrenError.INVALID_PROJECT_NAME);
|
|
43933
43982
|
const resolvedDir = storeAwareProjectPath(phrenPath, project);
|
|
43934
43983
|
if (!resolvedDir || !fs28.existsSync(resolvedDir)) return phrenErr(`Project "${project}" not found in phren.`, PhrenError.PROJECT_NOT_FOUND);
|
|
43935
|
-
const learningsPath =
|
|
43984
|
+
const learningsPath = path62.join(resolvedDir, FINDINGS_FILENAME);
|
|
43936
43985
|
if (!fs28.existsSync(learningsPath)) return phrenOk(0);
|
|
43937
43986
|
const STALE_LOCK_MS = 6e5;
|
|
43938
43987
|
const lockFile = runtimeFile(phrenPath, `consolidation-${project}.lock`);
|
|
@@ -43968,7 +44017,7 @@ function autoArchiveToReference(phrenPath, project, keepCount) {
|
|
|
43968
44017
|
const entries2 = parseActiveEntries(content);
|
|
43969
44018
|
if (entries2.length <= keepCount) return phrenOk(0);
|
|
43970
44019
|
const toArchive = entries2.slice(0, entries2.length - keepCount);
|
|
43971
|
-
const referenceDir =
|
|
44020
|
+
const referenceDir = path62.join(resolvedDir, "reference");
|
|
43972
44021
|
const { topics } = readProjectTopics(phrenPath, project);
|
|
43973
44022
|
const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
|
|
43974
44023
|
const archivedSet = buildArchivedBulletSet(referenceDir);
|
|
@@ -44532,7 +44581,7 @@ var DEFAULT_DECAY = {
|
|
|
44532
44581
|
var DEFAULT_UNDATED_CONFIDENCE = DEFAULT_DECAY.d120;
|
|
44533
44582
|
|
|
44534
44583
|
// src/content/dedup.ts
|
|
44535
|
-
import * as
|
|
44584
|
+
import * as path63 from "path";
|
|
44536
44585
|
init_shared();
|
|
44537
44586
|
init_utils();
|
|
44538
44587
|
init_store_routing();
|
|
@@ -44656,7 +44705,7 @@ function resolveCoref(text4, context) {
|
|
|
44656
44705
|
result = result.replace(/\bthe project\b/gi, context.project);
|
|
44657
44706
|
}
|
|
44658
44707
|
if (context.file) {
|
|
44659
|
-
const basename12 =
|
|
44708
|
+
const basename12 = path63.basename(context.file);
|
|
44660
44709
|
result = result.replace(/\b(this file|the file)\b/gi, basename12);
|
|
44661
44710
|
}
|
|
44662
44711
|
if (context.project && /\b(it|this|that|they|them)\b/i.test(result)) {
|
|
@@ -44673,7 +44722,7 @@ init_shared();
|
|
|
44673
44722
|
init_shared();
|
|
44674
44723
|
init_governance();
|
|
44675
44724
|
import * as fs30 from "fs";
|
|
44676
|
-
import * as
|
|
44725
|
+
import * as path65 from "path";
|
|
44677
44726
|
import * as crypto8 from "crypto";
|
|
44678
44727
|
|
|
44679
44728
|
// src/finding-graph-id.ts
|
|
@@ -44708,7 +44757,7 @@ init_store_routing();
|
|
|
44708
44757
|
// src/finding/context.ts
|
|
44709
44758
|
init_utils();
|
|
44710
44759
|
import * as fs29 from "fs";
|
|
44711
|
-
import * as
|
|
44760
|
+
import * as path64 from "path";
|
|
44712
44761
|
|
|
44713
44762
|
// src/session/utils.ts
|
|
44714
44763
|
init_utils();
|
|
@@ -44790,14 +44839,14 @@ function resolveFindingTaskReference(phrenPath, project, match) {
|
|
|
44790
44839
|
const projectDir = safeProjectPath(phrenPath, project);
|
|
44791
44840
|
if (!projectDir) return { error: `Invalid project name: "${project}".` };
|
|
44792
44841
|
const taskPath = resolveTaskFilePath(phrenPath, project);
|
|
44793
|
-
const items = parseTaskItems(taskPath ??
|
|
44842
|
+
const items = parseTaskItems(taskPath ?? path64.join(projectDir, "tasks.md"));
|
|
44794
44843
|
return resolveTaskItemMatch(items, match);
|
|
44795
44844
|
}
|
|
44796
44845
|
function resolveAutoFindingTaskItem(phrenPath, project) {
|
|
44797
44846
|
const projectDir = safeProjectPath(phrenPath, project);
|
|
44798
44847
|
if (!projectDir) return void 0;
|
|
44799
44848
|
const taskPath = resolveTaskFilePath(phrenPath, project);
|
|
44800
|
-
const active = parseTaskItems(taskPath ??
|
|
44849
|
+
const active = parseTaskItems(taskPath ?? path64.join(projectDir, "tasks.md")).filter(
|
|
44801
44850
|
(item) => item.section === "Active" && item.stableId
|
|
44802
44851
|
);
|
|
44803
44852
|
if (active.length === 1) return active[0].stableId;
|
|
@@ -44837,7 +44886,7 @@ function buildFindingCitation(citationInput, nowIso, inferredRepo, headCommit) {
|
|
|
44837
44886
|
function resolveInferredCitationRepo(citationInput) {
|
|
44838
44887
|
if (citationInput?.repo) return citationInput.repo;
|
|
44839
44888
|
if (citationInput?.file) {
|
|
44840
|
-
const fileDir =
|
|
44889
|
+
const fileDir = path65.dirname(citationInput.file);
|
|
44841
44890
|
return getRepoRoot(fileDir);
|
|
44842
44891
|
}
|
|
44843
44892
|
return void 0;
|
|
@@ -44972,7 +45021,7 @@ function addFindingToFile(phrenPath, project, learning, citationInput, opts) {
|
|
|
44972
45021
|
if (!isValidProjectName(project)) return phrenErr(`Invalid project name: "${project}".`, PhrenError.INVALID_PROJECT_NAME);
|
|
44973
45022
|
const resolvedDir = storeAwareProjectPath(phrenPath, project);
|
|
44974
45023
|
if (!resolvedDir) return phrenErr(`Invalid project name: "${project}".`, PhrenError.INVALID_PROJECT_NAME);
|
|
44975
|
-
const learningsPath =
|
|
45024
|
+
const learningsPath = path65.join(resolvedDir, FINDINGS_FILENAME);
|
|
44976
45025
|
const nowIso = (opts?.now ?? /* @__PURE__ */ new Date()).toISOString();
|
|
44977
45026
|
const today = nowIso.slice(0, 10);
|
|
44978
45027
|
const resolvedCitationInputResult = resolveFindingCitationInput(phrenPath, project, citationInput);
|
|
@@ -45154,7 +45203,7 @@ var codeNoteSchema = external_exports.object({
|
|
|
45154
45203
|
// phone's spelling, accepted until 0.3.1.
|
|
45155
45204
|
name: external_exports.string().min(1).max(4600).optional(),
|
|
45156
45205
|
symbol: external_exports.string().min(1).max(4600).optional(),
|
|
45157
|
-
file: external_exports.string().min(1).max(4096).refine((file2) => !
|
|
45206
|
+
file: external_exports.string().min(1).max(4096).refine((file2) => !path66.isAbsolute(file2) && !file2.includes("\0") && !file2.split(/[\\/]/).includes("..")),
|
|
45158
45207
|
line: external_exports.number().int().positive(),
|
|
45159
45208
|
text: external_exports.string().trim().min(1).max(4500).refine((text4) => !/[\x00-\x08\x0b-\x1f\x7f]/.test(text4)),
|
|
45160
45209
|
target: external_exports.union([external_exports.object({ session: sessionId }).strict(), external_exports.object({ harness: external_exports.enum(["codex", "claude", "opencode"]) }).strict()]).optional()
|
|
@@ -45209,24 +45258,24 @@ import { promisify as promisify11 } from "node:util";
|
|
|
45209
45258
|
import { realpathSync as realpathSync5 } from "node:fs";
|
|
45210
45259
|
import { readdir as readdir12, readFile as readFile27, stat as stat20, mkdir as mkdir15 } from "node:fs/promises";
|
|
45211
45260
|
import { homedir as homedir17 } from "node:os";
|
|
45212
|
-
import
|
|
45261
|
+
import path71 from "node:path";
|
|
45213
45262
|
|
|
45214
45263
|
// src/core/project.ts
|
|
45215
45264
|
init_shared();
|
|
45216
|
-
import * as
|
|
45265
|
+
import * as path69 from "path";
|
|
45217
45266
|
|
|
45218
45267
|
// src/core/project-registry.ts
|
|
45219
45268
|
init_phren_paths();
|
|
45220
45269
|
import * as fs32 from "fs";
|
|
45221
|
-
import * as
|
|
45270
|
+
import * as path68 from "path";
|
|
45222
45271
|
|
|
45223
45272
|
// src/git-worktree.ts
|
|
45224
45273
|
import * as fs31 from "fs";
|
|
45225
|
-
import * as
|
|
45274
|
+
import * as path67 from "path";
|
|
45226
45275
|
var WORKTREE_CONTAINER_NAMES = /* @__PURE__ */ new Set(["worktrees", ".worktrees"]);
|
|
45227
|
-
var LINKED_WORKTREE_SEGMENT = `${
|
|
45276
|
+
var LINKED_WORKTREE_SEGMENT = `${path67.sep}.git${path67.sep}worktrees${path67.sep}`;
|
|
45228
45277
|
function resolveWorktreeParent(dir) {
|
|
45229
|
-
const resolved =
|
|
45278
|
+
const resolved = path67.resolve(dir);
|
|
45230
45279
|
const agentParent = parentFromAgentWorktreePath(resolved);
|
|
45231
45280
|
if (agentParent) return { repoRoot: agentParent, reason: "agent-worktree-dir" };
|
|
45232
45281
|
const linkedParent = parentFromLinkedWorktree(resolved);
|
|
@@ -45234,23 +45283,23 @@ function resolveWorktreeParent(dir) {
|
|
|
45234
45283
|
return null;
|
|
45235
45284
|
}
|
|
45236
45285
|
function parentFromAgentWorktreePath(resolved) {
|
|
45237
|
-
const segments = resolved.split(
|
|
45286
|
+
const segments = resolved.split(path67.sep);
|
|
45238
45287
|
for (let i = 1; i < segments.length; i++) {
|
|
45239
45288
|
if (!WORKTREE_CONTAINER_NAMES.has(segments[i])) continue;
|
|
45240
45289
|
let j = i - 1;
|
|
45241
45290
|
if (!segments[j]?.startsWith(".")) continue;
|
|
45242
45291
|
while (j >= 1 && segments[j].startsWith(".")) j--;
|
|
45243
45292
|
if (j < 1) continue;
|
|
45244
|
-
return segments.slice(0, j + 1).join(
|
|
45293
|
+
return segments.slice(0, j + 1).join(path67.sep) || path67.sep;
|
|
45245
45294
|
}
|
|
45246
45295
|
return null;
|
|
45247
45296
|
}
|
|
45248
45297
|
function parentFromLinkedWorktree(resolved) {
|
|
45249
45298
|
let current2 = resolved;
|
|
45250
45299
|
while (true) {
|
|
45251
|
-
const parent = repoRootFromGitFile(
|
|
45300
|
+
const parent = repoRootFromGitFile(path67.join(current2, ".git"));
|
|
45252
45301
|
if (parent) return parent;
|
|
45253
|
-
const next =
|
|
45302
|
+
const next = path67.dirname(current2);
|
|
45254
45303
|
if (next === current2) return null;
|
|
45255
45304
|
current2 = next;
|
|
45256
45305
|
}
|
|
@@ -45265,7 +45314,7 @@ function repoRootFromGitFile(gitPath) {
|
|
|
45265
45314
|
}
|
|
45266
45315
|
const match = raw.match(/^\s*gitdir:\s*(.+?)\s*$/m);
|
|
45267
45316
|
if (!match) return null;
|
|
45268
|
-
const gitDir =
|
|
45317
|
+
const gitDir = path67.resolve(path67.dirname(gitPath), match[1].replace(/[/\\]/g, path67.sep));
|
|
45269
45318
|
const idx = gitDir.indexOf(LINKED_WORKTREE_SEGMENT);
|
|
45270
45319
|
if (idx === -1) return null;
|
|
45271
45320
|
return gitDir.slice(0, idx);
|
|
@@ -45478,7 +45527,7 @@ function scoreTopicsFromTerms(domain2, terms, docsText) {
|
|
|
45478
45527
|
return topics;
|
|
45479
45528
|
}
|
|
45480
45529
|
function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
|
|
45481
|
-
const resolvedRoot =
|
|
45530
|
+
const resolvedRoot = path68.resolve(repoRoot);
|
|
45482
45531
|
if (!fs32.existsSync(resolvedRoot)) return null;
|
|
45483
45532
|
const signal = {
|
|
45484
45533
|
domainScores: { software: 0, music: 0, game: 0, research: 0, writing: 0, creative: 0, other: 0 },
|
|
@@ -45489,7 +45538,7 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
|
|
|
45489
45538
|
usefulSignals: 0
|
|
45490
45539
|
};
|
|
45491
45540
|
const skipDirs = /* @__PURE__ */ new Set([".git", ".phren", "node_modules", "dist", "build", "coverage", ".next", ".turbo", "target"]);
|
|
45492
|
-
const packageJsonPath =
|
|
45541
|
+
const packageJsonPath = path68.join(resolvedRoot, "package.json");
|
|
45493
45542
|
if (fs32.existsSync(packageJsonPath)) {
|
|
45494
45543
|
signal.usefulSignals++;
|
|
45495
45544
|
addDomainScores(signal.domainScores, DOMAIN_CONFIG_HINTS["package.json"]);
|
|
@@ -45519,33 +45568,33 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
|
|
|
45519
45568
|
debugLog(`inferInitScaffoldFromRepo package.json parse failed: ${errorMessage(err)}`);
|
|
45520
45569
|
}
|
|
45521
45570
|
}
|
|
45522
|
-
const topLevelConfigs = Object.keys(DOMAIN_CONFIG_HINTS).filter((fileName) => fs32.existsSync(
|
|
45571
|
+
const topLevelConfigs = Object.keys(DOMAIN_CONFIG_HINTS).filter((fileName) => fs32.existsSync(path68.join(resolvedRoot, fileName)));
|
|
45523
45572
|
for (const configName of topLevelConfigs) {
|
|
45524
45573
|
signal.usefulSignals++;
|
|
45525
45574
|
const configScore = DOMAIN_CONFIG_HINTS[configName];
|
|
45526
45575
|
if (configScore) addDomainScores(signal.domainScores, configScore);
|
|
45527
45576
|
}
|
|
45528
45577
|
const readmeCandidates = [
|
|
45529
|
-
|
|
45530
|
-
|
|
45578
|
+
path68.join(resolvedRoot, "README.md"),
|
|
45579
|
+
path68.join(resolvedRoot, "readme.md")
|
|
45531
45580
|
];
|
|
45532
45581
|
for (const readmePath of readmeCandidates) {
|
|
45533
45582
|
if (!fs32.existsSync(readmePath)) continue;
|
|
45534
45583
|
const content = maybeReadUtf8(readmePath);
|
|
45535
45584
|
if (!content) continue;
|
|
45536
45585
|
signal.usefulSignals++;
|
|
45537
|
-
signal.referenceHints.push(
|
|
45586
|
+
signal.referenceHints.push(path68.relative(resolvedRoot, readmePath));
|
|
45538
45587
|
addTermCount(signal.terms, content, 2);
|
|
45539
45588
|
signal.docsText += ` ${content.toLowerCase()}`;
|
|
45540
45589
|
break;
|
|
45541
45590
|
}
|
|
45542
|
-
const docsDir =
|
|
45591
|
+
const docsDir = path68.join(resolvedRoot, "docs");
|
|
45543
45592
|
if (fs32.existsSync(docsDir) && fs32.statSync(docsDir).isDirectory()) {
|
|
45544
45593
|
signal.referenceHints.push("docs/");
|
|
45545
45594
|
for (const entry of fs32.readdirSync(docsDir, { withFileTypes: true })) {
|
|
45546
45595
|
if (!entry.isFile()) continue;
|
|
45547
45596
|
if (!/\.(md|txt|rst)$/i.test(entry.name)) continue;
|
|
45548
|
-
const docsContent = maybeReadUtf8(
|
|
45597
|
+
const docsContent = maybeReadUtf8(path68.join(docsDir, entry.name));
|
|
45549
45598
|
if (!docsContent) continue;
|
|
45550
45599
|
signal.usefulSignals++;
|
|
45551
45600
|
addTermCount(signal.terms, docsContent, 1);
|
|
@@ -45553,7 +45602,7 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
|
|
|
45553
45602
|
}
|
|
45554
45603
|
}
|
|
45555
45604
|
for (const folderName of ["reference", "specs", "design", "architecture", "src", "packages", "apps"]) {
|
|
45556
|
-
const fullPath =
|
|
45605
|
+
const fullPath = path68.join(resolvedRoot, folderName);
|
|
45557
45606
|
if (fs32.existsSync(fullPath)) {
|
|
45558
45607
|
signal.referenceHints.push(`${folderName}/`);
|
|
45559
45608
|
}
|
|
@@ -45564,14 +45613,14 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
|
|
|
45564
45613
|
if (scannedFiles >= maxFiles) return;
|
|
45565
45614
|
for (const entry of fs32.readdirSync(dir, { withFileTypes: true })) {
|
|
45566
45615
|
if (scannedFiles >= maxFiles) return;
|
|
45567
|
-
const fullPath =
|
|
45616
|
+
const fullPath = path68.join(dir, entry.name);
|
|
45568
45617
|
if (entry.isDirectory()) {
|
|
45569
45618
|
if (skipDirs.has(entry.name)) continue;
|
|
45570
45619
|
walk(fullPath);
|
|
45571
45620
|
continue;
|
|
45572
45621
|
}
|
|
45573
45622
|
scannedFiles++;
|
|
45574
|
-
const ext =
|
|
45623
|
+
const ext = path68.extname(entry.name).toLowerCase();
|
|
45575
45624
|
if (!ext) continue;
|
|
45576
45625
|
const extScore = EXTENSION_DOMAIN_HINTS[ext];
|
|
45577
45626
|
if (extScore) {
|
|
@@ -45745,7 +45794,7 @@ function findExistingProjectForSource(phrenPath, sourceRoot, derivedName) {
|
|
|
45745
45794
|
return null;
|
|
45746
45795
|
}
|
|
45747
45796
|
};
|
|
45748
|
-
const resolvedSource =
|
|
45797
|
+
const resolvedSource = path68.resolve(sourceRoot);
|
|
45749
45798
|
for (const project of candidates) {
|
|
45750
45799
|
if (sourceOf(project) === resolvedSource) return project;
|
|
45751
45800
|
}
|
|
@@ -45759,7 +45808,7 @@ function findExistingProjectForSource(phrenPath, sourceRoot, derivedName) {
|
|
|
45759
45808
|
function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
|
|
45760
45809
|
const profile = typeof opts === "string" ? opts : opts.profile;
|
|
45761
45810
|
const profilePhrenPath = typeof opts === "string" ? phrenPath : opts.profilePhrenPath ?? phrenPath;
|
|
45762
|
-
const resolvedPath =
|
|
45811
|
+
const resolvedPath = path68.resolve(projectPath);
|
|
45763
45812
|
if (!fs32.existsSync(resolvedPath)) {
|
|
45764
45813
|
throw new Error(`Path does not exist: ${resolvedPath}`);
|
|
45765
45814
|
}
|
|
@@ -45770,17 +45819,17 @@ function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
|
|
|
45770
45819
|
if (worktreeRepoRoot) {
|
|
45771
45820
|
debugLog(`bootstrapFromExisting: ${resolvedPath} is a ${worktree.reason}; attributing to ${worktreeRepoRoot}`);
|
|
45772
45821
|
}
|
|
45773
|
-
const sourceRoot = isProjectLocal ?
|
|
45822
|
+
const sourceRoot = isProjectLocal ? path68.resolve(manifest.workspaceRoot || resolvedPath) : worktreeRepoRoot ?? resolvedPath;
|
|
45774
45823
|
if (isProjectLocal) {
|
|
45775
|
-
const matchesWorkspace = resolvedPath === sourceRoot || resolvedPath.startsWith(sourceRoot +
|
|
45824
|
+
const matchesWorkspace = resolvedPath === sourceRoot || resolvedPath.startsWith(sourceRoot + path68.sep);
|
|
45776
45825
|
if (!matchesWorkspace) {
|
|
45777
45826
|
throw new Error(`Project-local phren can only enroll the owning workspace: ${sourceRoot}`);
|
|
45778
45827
|
}
|
|
45779
45828
|
}
|
|
45780
45829
|
let claudeMdPath = null;
|
|
45781
45830
|
const candidates = [
|
|
45782
|
-
|
|
45783
|
-
|
|
45831
|
+
path68.join(sourceRoot, "AGENTS.md"),
|
|
45832
|
+
path68.join(sourceRoot, ".claude", "CLAUDE.md")
|
|
45784
45833
|
];
|
|
45785
45834
|
for (const c of candidates) {
|
|
45786
45835
|
if (fs32.existsSync(c)) {
|
|
@@ -45800,12 +45849,12 @@ function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
|
|
|
45800
45849
|
`Project "${existingProject}" already exists with different casing. Refusing to bootstrap "${projectName2}" because it would split the same project on case-sensitive filesystems.`
|
|
45801
45850
|
);
|
|
45802
45851
|
}
|
|
45803
|
-
const projDir =
|
|
45852
|
+
const projDir = path68.join(phrenPath, projectName2);
|
|
45804
45853
|
fs32.mkdirSync(projDir, { recursive: true });
|
|
45805
45854
|
const inferredScaffold = inferInitScaffoldFromRepo(sourceRoot);
|
|
45806
45855
|
const existingConfig = readProjectConfig(phrenPath, projectName2);
|
|
45807
45856
|
const ownership = typeof opts === "string" ? parseProjectOwnershipMode(existingConfig.ownership) ?? getProjectOwnershipDefault(phrenPath) : opts.ownership ?? parseProjectOwnershipMode(existingConfig.ownership) ?? getProjectOwnershipDefault(phrenPath);
|
|
45808
|
-
const claudePath =
|
|
45857
|
+
const claudePath = path68.join(projDir, "AGENTS.md");
|
|
45809
45858
|
if (ownership !== "repo-managed") {
|
|
45810
45859
|
if (claudeContent) {
|
|
45811
45860
|
if (!fs32.existsSync(claudePath)) {
|
|
@@ -45840,7 +45889,7 @@ function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
|
|
|
45840
45889
|
}
|
|
45841
45890
|
}
|
|
45842
45891
|
const sourceInfo = claudeMdPath ? `**Source AGENTS.md:** ${claudeMdPath}` : `**Source:** ${sourceRoot}`;
|
|
45843
|
-
const summaryPath =
|
|
45892
|
+
const summaryPath = path68.join(projDir, "summary.md");
|
|
45844
45893
|
if (!fs32.existsSync(summaryPath)) {
|
|
45845
45894
|
atomicWriteText(
|
|
45846
45895
|
summaryPath,
|
|
@@ -45853,18 +45902,18 @@ ${summaryLines.length > 1 ? summaryLines.slice(1).join("\n") : ""}
|
|
|
45853
45902
|
`
|
|
45854
45903
|
);
|
|
45855
45904
|
}
|
|
45856
|
-
if (!fs32.existsSync(
|
|
45905
|
+
if (!fs32.existsSync(path68.join(projDir, FINDINGS_FILENAME))) {
|
|
45857
45906
|
atomicWriteText(
|
|
45858
|
-
|
|
45907
|
+
path68.join(projDir, FINDINGS_FILENAME),
|
|
45859
45908
|
`# ${projectName2} FINDINGS
|
|
45860
45909
|
|
|
45861
45910
|
<!-- Bootstrapped from ${sourceRoot} -->
|
|
45862
45911
|
`
|
|
45863
45912
|
);
|
|
45864
45913
|
}
|
|
45865
|
-
if (moduleEnabled(phrenPath, "tasks") && !fs32.existsSync(
|
|
45914
|
+
if (moduleEnabled(phrenPath, "tasks") && !fs32.existsSync(path68.join(projDir, TASKS_FILENAME))) {
|
|
45866
45915
|
atomicWriteText(
|
|
45867
|
-
|
|
45916
|
+
path68.join(projDir, TASKS_FILENAME),
|
|
45868
45917
|
`# ${projectName2} tasks
|
|
45869
45918
|
|
|
45870
45919
|
## Active
|
|
@@ -45875,11 +45924,11 @@ ${summaryLines.length > 1 ? summaryLines.slice(1).join("\n") : ""}
|
|
|
45875
45924
|
`
|
|
45876
45925
|
);
|
|
45877
45926
|
}
|
|
45878
|
-
if (!fs32.existsSync(
|
|
45927
|
+
if (!fs32.existsSync(path68.join(projDir, "topic-config.json"))) {
|
|
45879
45928
|
const inferredDomain = normalizeBuiltinTopicDomain(inferredScaffold?.domain ?? "software");
|
|
45880
45929
|
const inferredTopics = inferredScaffold?.topics?.length ? inferredScaffold.topics : getBuiltinTopicConfig(inferredDomain);
|
|
45881
45930
|
atomicWriteText(
|
|
45882
|
-
|
|
45931
|
+
path68.join(projDir, "topic-config.json"),
|
|
45883
45932
|
JSON.stringify({ version: 1, domain: inferredDomain, topics: inferredTopics }, null, 2) + "\n"
|
|
45884
45933
|
);
|
|
45885
45934
|
}
|
|
@@ -45911,10 +45960,10 @@ function addProjectFromPath(phrenPath, targetPath, requestedProfile, ownership,
|
|
|
45911
45960
|
if (!activeProfile.ok) return activeProfile;
|
|
45912
45961
|
const writePhrenPath = options.writeToPath ?? phrenPath;
|
|
45913
45962
|
const manifest = readRootManifest(phrenPath);
|
|
45914
|
-
const resolvedPath =
|
|
45963
|
+
const resolvedPath = path69.resolve(targetPath);
|
|
45915
45964
|
if (manifest?.installMode === "project-local") {
|
|
45916
|
-
const workspaceRoot =
|
|
45917
|
-
const matchesWorkspace = resolvedPath === workspaceRoot || resolvedPath.startsWith(workspaceRoot +
|
|
45965
|
+
const workspaceRoot = path69.resolve(manifest.workspaceRoot || "");
|
|
45966
|
+
const matchesWorkspace = resolvedPath === workspaceRoot || resolvedPath.startsWith(workspaceRoot + path69.sep);
|
|
45918
45967
|
if (!matchesWorkspace) {
|
|
45919
45968
|
return phrenErr(`Project-local phren can only add the owning workspace: ${workspaceRoot}`);
|
|
45920
45969
|
}
|
|
@@ -45932,9 +45981,9 @@ function addProjectFromPath(phrenPath, targetPath, requestedProfile, ownership,
|
|
|
45932
45981
|
ownership: added.ownership,
|
|
45933
45982
|
files: {
|
|
45934
45983
|
claude: added.claudePath,
|
|
45935
|
-
summary:
|
|
45936
|
-
findings:
|
|
45937
|
-
task:
|
|
45984
|
+
summary: path69.join(writePhrenPath, added.project, "summary.md"),
|
|
45985
|
+
findings: path69.join(writePhrenPath, added.project, FINDINGS_FILENAME),
|
|
45986
|
+
task: path69.join(writePhrenPath, added.project, TASKS_FILENAME)
|
|
45938
45987
|
}
|
|
45939
45988
|
});
|
|
45940
45989
|
}
|
|
@@ -45960,7 +46009,7 @@ import { execFileSync as execFileSync6, spawnSync as spawnSync2 } from "child_pr
|
|
|
45960
46009
|
import * as crypto9 from "crypto";
|
|
45961
46010
|
import * as fs33 from "fs";
|
|
45962
46011
|
import * as os3 from "os";
|
|
45963
|
-
import * as
|
|
46012
|
+
import * as path70 from "path";
|
|
45964
46013
|
|
|
45965
46014
|
// src/content/summarize.ts
|
|
45966
46015
|
init_phren_dotenv();
|
|
@@ -46121,7 +46170,7 @@ function mergeTasksByBid(base, ours, theirs) {
|
|
|
46121
46170
|
// src/sync/conflict-resolve.ts
|
|
46122
46171
|
function conflictStrategy(relFile) {
|
|
46123
46172
|
const file2 = relFile.replace(/\\/g, "/");
|
|
46124
|
-
const name =
|
|
46173
|
+
const name = path70.posix.basename(file2).toLowerCase();
|
|
46125
46174
|
if (isTaskFileName(name)) return "tasks";
|
|
46126
46175
|
if (name === "findings.md") return "findings";
|
|
46127
46176
|
if (/^\.config\/task-archive\/[^/]+\.md$/i.test(file2)) return "archive";
|
|
@@ -46156,9 +46205,9 @@ function splitBlock(content, start, end) {
|
|
|
46156
46205
|
function mergeText(base, ours, theirs) {
|
|
46157
46206
|
if (ours === theirs || ours === base) return theirs;
|
|
46158
46207
|
if (theirs === base) return ours;
|
|
46159
|
-
const dir = fs33.mkdtempSync(
|
|
46208
|
+
const dir = fs33.mkdtempSync(path70.join(os3.tmpdir(), "phren-merge-"));
|
|
46160
46209
|
try {
|
|
46161
|
-
const [o, b, t] = ["ours", "base", "theirs"].map((name) =>
|
|
46210
|
+
const [o, b, t] = ["ours", "base", "theirs"].map((name) => path70.join(dir, name));
|
|
46162
46211
|
fs33.writeFileSync(o, ours);
|
|
46163
46212
|
fs33.writeFileSync(b, base);
|
|
46164
46213
|
fs33.writeFileSync(t, theirs);
|
|
@@ -46171,9 +46220,9 @@ function mergeText(base, ours, theirs) {
|
|
|
46171
46220
|
function unionText(base, ours, theirs) {
|
|
46172
46221
|
const clean2 = mergeText(base, ours, theirs);
|
|
46173
46222
|
if (clean2 !== null) return clean2;
|
|
46174
|
-
const dir = fs33.mkdtempSync(
|
|
46223
|
+
const dir = fs33.mkdtempSync(path70.join(os3.tmpdir(), "phren-merge-"));
|
|
46175
46224
|
try {
|
|
46176
|
-
const [o, b, t] = ["ours", "base", "theirs"].map((name) =>
|
|
46225
|
+
const [o, b, t] = ["ours", "base", "theirs"].map((name) => path70.join(dir, name));
|
|
46177
46226
|
fs33.writeFileSync(o, ours);
|
|
46178
46227
|
fs33.writeFileSync(b, base);
|
|
46179
46228
|
fs33.writeFileSync(t, theirs);
|
|
@@ -46233,7 +46282,7 @@ function resolveStoreConflicts(cwd) {
|
|
|
46233
46282
|
const base = stage(cwd, 1, relFile) ?? "";
|
|
46234
46283
|
const ours = stage(cwd, 2, relFile);
|
|
46235
46284
|
const theirs = stage(cwd, 3, relFile);
|
|
46236
|
-
const fullPath =
|
|
46285
|
+
const fullPath = path70.join(cwd, relFile);
|
|
46237
46286
|
if (ours === null && theirs === null) {
|
|
46238
46287
|
unresolved.push(relFile);
|
|
46239
46288
|
continue;
|
|
@@ -46244,7 +46293,7 @@ function resolveStoreConflicts(cwd) {
|
|
|
46244
46293
|
continue;
|
|
46245
46294
|
}
|
|
46246
46295
|
const tmp = `${fullPath}.tmp-${crypto9.randomUUID()}`;
|
|
46247
|
-
fs33.mkdirSync(
|
|
46296
|
+
fs33.mkdirSync(path70.dirname(fullPath), { recursive: true });
|
|
46248
46297
|
fs33.writeFileSync(tmp, merged);
|
|
46249
46298
|
fs33.renameSync(tmp, fullPath);
|
|
46250
46299
|
git4(cwd, ["add", "--", relFile]);
|
|
@@ -46524,7 +46573,7 @@ function repoName(url2) {
|
|
|
46524
46573
|
}
|
|
46525
46574
|
async function isRepository(directory) {
|
|
46526
46575
|
try {
|
|
46527
|
-
await stat20(
|
|
46576
|
+
await stat20(path71.join(directory, ".git"));
|
|
46528
46577
|
return true;
|
|
46529
46578
|
} catch {
|
|
46530
46579
|
return false;
|
|
@@ -46544,7 +46593,7 @@ async function registeredSources(env) {
|
|
|
46544
46593
|
const source = readProjectConfig(store, project).sourcePath;
|
|
46545
46594
|
if (typeof source === "string" && source) {
|
|
46546
46595
|
try {
|
|
46547
|
-
paths.add(realpathSync5.native(
|
|
46596
|
+
paths.add(realpathSync5.native(path71.resolve(source)));
|
|
46548
46597
|
} catch {
|
|
46549
46598
|
}
|
|
46550
46599
|
}
|
|
@@ -46556,7 +46605,7 @@ async function candidateRepos(activity, env = process.env) {
|
|
|
46556
46605
|
const found = [];
|
|
46557
46606
|
const seen = /* @__PURE__ */ new Set();
|
|
46558
46607
|
const offer = async (directory, source, lastSeen) => {
|
|
46559
|
-
let dir =
|
|
46608
|
+
let dir = path71.resolve(directory);
|
|
46560
46609
|
try {
|
|
46561
46610
|
if (!(await stat20(dir)).isDirectory()) return;
|
|
46562
46611
|
dir = realpathSync5.native(dir);
|
|
@@ -46571,7 +46620,7 @@ async function candidateRepos(activity, env = process.env) {
|
|
|
46571
46620
|
const toplevel = async (directory) => {
|
|
46572
46621
|
let existing = directory;
|
|
46573
46622
|
while (!await stat20(existing).catch(() => void 0)) {
|
|
46574
|
-
const parent =
|
|
46623
|
+
const parent = path71.dirname(existing);
|
|
46575
46624
|
if (parent === existing) return void 0;
|
|
46576
46625
|
existing = parent;
|
|
46577
46626
|
}
|
|
@@ -46584,25 +46633,25 @@ async function candidateRepos(activity, env = process.env) {
|
|
|
46584
46633
|
};
|
|
46585
46634
|
for (const event of [...activity].reverse()) {
|
|
46586
46635
|
const directory = typeof event.directory === "string" ? event.directory : void 0;
|
|
46587
|
-
if (!directory || !
|
|
46636
|
+
if (!directory || !path71.isAbsolute(directory)) continue;
|
|
46588
46637
|
const root = await toplevel(directory);
|
|
46589
46638
|
if (root) await offer(root, "activity", typeof event.at === "string" ? event.at : void 0);
|
|
46590
46639
|
}
|
|
46591
46640
|
try {
|
|
46592
|
-
const session = JSON.parse(await readFile27(
|
|
46641
|
+
const session = JSON.parse(await readFile27(path71.join(herdrRoot(), "session.json"), "utf8"));
|
|
46593
46642
|
for (const match of JSON.stringify(session).matchAll(/"cwd":\s*"((?:\\.|[^"\\])*)"/g)) {
|
|
46594
46643
|
const directory = JSON.parse(`"${match[1]}"`);
|
|
46595
|
-
if (!
|
|
46644
|
+
if (!path71.isAbsolute(directory)) continue;
|
|
46596
46645
|
const root = await toplevel(directory);
|
|
46597
46646
|
if (root) await offer(root, "herdr");
|
|
46598
46647
|
}
|
|
46599
46648
|
} catch {
|
|
46600
46649
|
}
|
|
46601
46650
|
const home = homedir17();
|
|
46602
|
-
for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.map((r) =>
|
|
46651
|
+
for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.map((r) => path71.join(home, r))]) {
|
|
46603
46652
|
let children = [];
|
|
46604
46653
|
try {
|
|
46605
|
-
children = (await readdir12(root, { withFileTypes: true })).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) =>
|
|
46654
|
+
children = (await readdir12(root, { withFileTypes: true })).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => path71.join(root, e.name));
|
|
46606
46655
|
} catch {
|
|
46607
46656
|
continue;
|
|
46608
46657
|
}
|
|
@@ -46612,13 +46661,13 @@ async function candidateRepos(activity, env = process.env) {
|
|
|
46612
46661
|
}
|
|
46613
46662
|
async function cloneRoot(env) {
|
|
46614
46663
|
const home = homedir17();
|
|
46615
|
-
for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.filter((r) => r !== "Sites").map((r) =>
|
|
46664
|
+
for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.filter((r) => r !== "Sites").map((r) => path71.join(home, r))]) {
|
|
46616
46665
|
try {
|
|
46617
46666
|
if ((await stat20(root)).isDirectory()) return root;
|
|
46618
46667
|
} catch {
|
|
46619
46668
|
}
|
|
46620
46669
|
}
|
|
46621
|
-
const fallback =
|
|
46670
|
+
const fallback = path71.join(home, "Projects");
|
|
46622
46671
|
await mkdir15(fallback, { recursive: true });
|
|
46623
46672
|
return fallback;
|
|
46624
46673
|
}
|
|
@@ -46640,7 +46689,7 @@ async function publishStore(store, project) {
|
|
|
46640
46689
|
async function enrollProject(input2, env = process.env) {
|
|
46641
46690
|
const store = phrenStoreRoot(env);
|
|
46642
46691
|
try {
|
|
46643
|
-
if (!(await stat20(
|
|
46692
|
+
if (!(await stat20(path71.join(store, ".config"))).isDirectory()) throw new Error();
|
|
46644
46693
|
} catch {
|
|
46645
46694
|
throw new BridgeError(409, "phren is not set up on this computer. Run phren init there.");
|
|
46646
46695
|
}
|
|
@@ -46651,7 +46700,7 @@ async function enrollProject(input2, env = process.env) {
|
|
|
46651
46700
|
if (url2.length > 512 || !CLONE_URL.test(url2)) throw new BridgeError(400, "Enter a GitHub repository URL (https://github.com/owner/repo).");
|
|
46652
46701
|
const name = repoName(url2);
|
|
46653
46702
|
if (!name || name === "." || name === "..") throw new BridgeError(400, "That URL has no repository name.");
|
|
46654
|
-
directory =
|
|
46703
|
+
directory = path71.join(await cloneRoot(env), name);
|
|
46655
46704
|
try {
|
|
46656
46705
|
await stat20(directory);
|
|
46657
46706
|
throw new BridgeError(409, `${directory} already exists on this computer. Add that folder instead.`);
|
|
@@ -46668,7 +46717,7 @@ async function enrollProject(input2, env = process.env) {
|
|
|
46668
46717
|
cloned = true;
|
|
46669
46718
|
} else if (typeof input2.directory === "string" && input2.directory) {
|
|
46670
46719
|
const raw = input2.directory;
|
|
46671
|
-
if (raw.length > 4096 || raw.includes("\0") || !
|
|
46720
|
+
if (raw.length > 4096 || raw.includes("\0") || !path71.isAbsolute(raw)) throw new BridgeError(400, "Enter the full folder path on this computer.");
|
|
46672
46721
|
try {
|
|
46673
46722
|
directory = realpathSync5.native(raw);
|
|
46674
46723
|
if (!(await stat20(directory)).isDirectory()) throw new Error();
|
|
@@ -46683,22 +46732,22 @@ async function enrollProject(input2, env = process.env) {
|
|
|
46683
46732
|
|
|
46684
46733
|
// src/bridge/files.ts
|
|
46685
46734
|
init_protocol();
|
|
46686
|
-
import { constants as
|
|
46735
|
+
import { constants as constants4 } from "node:fs";
|
|
46687
46736
|
import { lstat as lstat15, open as open13, readdir as readdir13, realpath as realpath12 } from "node:fs/promises";
|
|
46688
|
-
import
|
|
46737
|
+
import path72 from "node:path";
|
|
46689
46738
|
var MAX_BYTES = 2097152;
|
|
46690
46739
|
async function browseFiles(root, relative3) {
|
|
46691
|
-
if (relative3.length > 4096 || relative3.includes("\0") || relative3.includes("\\") ||
|
|
46740
|
+
if (relative3.length > 4096 || relative3.includes("\0") || relative3.includes("\\") || path72.isAbsolute(relative3) || relative3.split("/").some((part) => part === ".." || part === ".git")) {
|
|
46692
46741
|
throw new BridgeError(400, "Invalid repository path.");
|
|
46693
46742
|
}
|
|
46694
46743
|
const base = await realpath12(root);
|
|
46695
46744
|
let file2 = base;
|
|
46696
46745
|
for (const part of relative3.split("/").filter((part2) => part2 && part2 !== ".")) {
|
|
46697
|
-
file2 =
|
|
46746
|
+
file2 = path72.join(file2, part);
|
|
46698
46747
|
if ((await lstat15(file2)).isSymbolicLink()) throw new BridgeError(403, "Symbolic links cannot be browsed.");
|
|
46699
46748
|
}
|
|
46700
46749
|
const resolved = await realpath12(file2);
|
|
46701
|
-
if (resolved !== base && !resolved.startsWith(base +
|
|
46750
|
+
if (resolved !== base && !resolved.startsWith(base + path72.sep)) throw new BridgeError(403, "The path is outside this repository.");
|
|
46702
46751
|
const metadata = await lstat15(resolved);
|
|
46703
46752
|
if (metadata.isDirectory()) {
|
|
46704
46753
|
const entries2 = (await readdir13(resolved, { withFileTypes: true })).filter((entry) => entry.name !== ".git" && (entry.isDirectory() || entry.isFile())).sort((a, b) => Number(b.isDirectory()) - Number(a.isDirectory()) || a.name.localeCompare(b.name));
|
|
@@ -46706,11 +46755,11 @@ async function browseFiles(root, relative3) {
|
|
|
46706
46755
|
path: relative3,
|
|
46707
46756
|
kind: "directory",
|
|
46708
46757
|
truncated: entries2.length > 500,
|
|
46709
|
-
entries: entries2.slice(0, 500).map((entry) => ({ name: entry.name, path:
|
|
46758
|
+
entries: entries2.slice(0, 500).map((entry) => ({ name: entry.name, path: path72.posix.join(relative3, entry.name), kind: entry.isDirectory() ? "directory" : "file" }))
|
|
46710
46759
|
};
|
|
46711
46760
|
}
|
|
46712
46761
|
if (!metadata.isFile()) throw new BridgeError(400, "Only regular files can be viewed.");
|
|
46713
|
-
const handle = await open13(resolved,
|
|
46762
|
+
const handle = await open13(resolved, constants4.O_RDONLY | constants4.O_NOFOLLOW | constants4.O_NONBLOCK);
|
|
46714
46763
|
try {
|
|
46715
46764
|
const current2 = await handle.stat();
|
|
46716
46765
|
if (!current2.isFile() || current2.ino !== metadata.ino || current2.dev !== metadata.dev) throw new BridgeError(409, "The file changed. Refresh and try again.");
|
|
@@ -46731,9 +46780,9 @@ async function browseFiles(root, relative3) {
|
|
|
46731
46780
|
|
|
46732
46781
|
// src/bridge/file-range.ts
|
|
46733
46782
|
init_protocol();
|
|
46734
|
-
import { constants as
|
|
46783
|
+
import { constants as constants5 } from "node:fs";
|
|
46735
46784
|
import { lstat as lstat16, open as open14, realpath as realpath13 } from "node:fs/promises";
|
|
46736
|
-
import
|
|
46785
|
+
import path73 from "node:path";
|
|
46737
46786
|
var MAX_FILE_RANGE = 4 * 1024 * 1024;
|
|
46738
46787
|
var types = {
|
|
46739
46788
|
mp4: "video/mp4",
|
|
@@ -46770,7 +46819,7 @@ var types = {
|
|
|
46770
46819
|
xml: "text/xml"
|
|
46771
46820
|
};
|
|
46772
46821
|
function fileContentType(file2) {
|
|
46773
|
-
const ext =
|
|
46822
|
+
const ext = path73.extname(file2).slice(1).toLowerCase();
|
|
46774
46823
|
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");
|
|
46775
46824
|
}
|
|
46776
46825
|
function version2(stat27) {
|
|
@@ -46788,18 +46837,18 @@ async function readFileRange(root, requested, offset, length, expectedVersion) {
|
|
|
46788
46837
|
}
|
|
46789
46838
|
try {
|
|
46790
46839
|
const base = await realpath13(root);
|
|
46791
|
-
const relative3 =
|
|
46792
|
-
if (relative3 === ".." || relative3.startsWith(`..${
|
|
46840
|
+
const relative3 = path73.isAbsolute(requested) ? path73.relative(base, requested) : requested;
|
|
46841
|
+
if (relative3 === ".." || relative3.startsWith(`..${path73.sep}`) || path73.isAbsolute(relative3)) throw new BridgeError(403, "This file is outside the allowed folder.");
|
|
46793
46842
|
let file2 = base;
|
|
46794
|
-
for (const part of relative3.split(
|
|
46795
|
-
file2 =
|
|
46843
|
+
for (const part of relative3.split(path73.sep).filter((part2) => part2 && part2 !== ".")) {
|
|
46844
|
+
file2 = path73.join(file2, part);
|
|
46796
46845
|
if ((await lstat16(file2)).isSymbolicLink()) throw new BridgeError(403, "Symbolic links cannot be opened.");
|
|
46797
46846
|
}
|
|
46798
46847
|
const resolved = await realpath13(file2);
|
|
46799
|
-
if (!resolved.startsWith(base +
|
|
46848
|
+
if (!resolved.startsWith(base + path73.sep)) throw new BridgeError(403, "This file is outside the allowed folder.");
|
|
46800
46849
|
const metadata = await lstat16(resolved);
|
|
46801
46850
|
if (!metadata.isFile()) throw new BridgeError(400, "Only regular files can be opened.");
|
|
46802
|
-
const handle = await open14(resolved,
|
|
46851
|
+
const handle = await open14(resolved, constants5.O_RDONLY | constants5.O_NOFOLLOW | constants5.O_NONBLOCK);
|
|
46803
46852
|
try {
|
|
46804
46853
|
const current2 = await handle.stat();
|
|
46805
46854
|
if (!current2.isFile() || version2(current2) !== version2(metadata) || await realpath13(file2) !== resolved) {
|
|
@@ -46841,7 +46890,7 @@ init_protocol();
|
|
|
46841
46890
|
import { execFile as execFile13 } from "node:child_process";
|
|
46842
46891
|
import { createHash as createHash15 } from "node:crypto";
|
|
46843
46892
|
import { lstat as lstat17, mkdir as mkdir16, readFile as readFile28, realpath as realpath14, rename as rename7, rm as rm8, writeFile as writeFile8 } from "node:fs/promises";
|
|
46844
|
-
import
|
|
46893
|
+
import path74 from "node:path";
|
|
46845
46894
|
import { promisify as promisify12 } from "node:util";
|
|
46846
46895
|
var exec12 = promisify12(execFile13);
|
|
46847
46896
|
var SHA = /^[0-9a-f]{40}$/;
|
|
@@ -46869,12 +46918,12 @@ function blobSha(content) {
|
|
|
46869
46918
|
return createHash15("sha1").update(`blob ${content.length}\0`).update(content).digest("hex");
|
|
46870
46919
|
}
|
|
46871
46920
|
async function isRepository2(store) {
|
|
46872
|
-
return await lstat17(
|
|
46921
|
+
return await lstat17(path74.join(store, ".git")).catch(() => void 0) !== void 0;
|
|
46873
46922
|
}
|
|
46874
|
-
function storeHead(store, indexFile =
|
|
46923
|
+
function storeHead(store, indexFile = path74.join(bridgeRoot(), "store-snapshot.index")) {
|
|
46875
46924
|
return serialized(async () => {
|
|
46876
46925
|
if (!await isRepository2(store)) throw new BridgeError(409, "This computer's phren store is not a git repository. Run phren init.");
|
|
46877
|
-
await mkdir16(
|
|
46926
|
+
await mkdir16(path74.dirname(indexFile), { recursive: true, mode: 448 });
|
|
46878
46927
|
const env = { GIT_INDEX_FILE: indexFile };
|
|
46879
46928
|
if (!await lstat17(indexFile).catch(() => void 0)) {
|
|
46880
46929
|
const head = await git5(store, ["rev-parse", "--verify", "--quiet", "HEAD"]).catch(() => "");
|
|
@@ -46901,21 +46950,21 @@ async function storeBlob(store, sha) {
|
|
|
46901
46950
|
return { sha, encoding: "base64", content: stdout.toString("base64") };
|
|
46902
46951
|
}
|
|
46903
46952
|
async function storeFile(store, relative3) {
|
|
46904
|
-
const normalized =
|
|
46905
|
-
if (!relative3 || relative3 !== normalized || normalized.startsWith("../") || normalized === ".." ||
|
|
46953
|
+
const normalized = path74.posix.normalize(relative3);
|
|
46954
|
+
if (!relative3 || relative3 !== normalized || normalized.startsWith("../") || normalized === ".." || path74.posix.isAbsolute(normalized) || normalized.split("/").some((part) => part === ".git" || part === "" || part === ".") || /[\0\r\n]/.test(normalized)) {
|
|
46906
46955
|
throw new BridgeError(400, "Invalid store path.");
|
|
46907
46956
|
}
|
|
46908
46957
|
const root = await realpath14(store);
|
|
46909
|
-
let parent =
|
|
46958
|
+
let parent = path74.dirname(path74.join(root, normalized));
|
|
46910
46959
|
for (; ; ) {
|
|
46911
46960
|
const real2 = await realpath14(parent).catch(() => void 0);
|
|
46912
46961
|
if (real2) {
|
|
46913
|
-
if (real2 !== root && !real2.startsWith(root +
|
|
46962
|
+
if (real2 !== root && !real2.startsWith(root + path74.sep)) throw new BridgeError(400, "Invalid store path.");
|
|
46914
46963
|
break;
|
|
46915
46964
|
}
|
|
46916
|
-
parent =
|
|
46965
|
+
parent = path74.dirname(parent);
|
|
46917
46966
|
}
|
|
46918
|
-
const file2 =
|
|
46967
|
+
const file2 = path74.join(root, normalized);
|
|
46919
46968
|
const info = await lstat17(file2).catch(() => void 0);
|
|
46920
46969
|
if (info && !info.isFile()) throw new BridgeError(400, "Invalid store path.");
|
|
46921
46970
|
return file2;
|
|
@@ -46936,7 +46985,7 @@ function putStoreFile(store, data) {
|
|
|
46936
46985
|
return serialized(async () => {
|
|
46937
46986
|
const file2 = await storeFile(store, input2.path);
|
|
46938
46987
|
if (await currentSha(file2) !== (input2.sha ?? null)) throw new BridgeError(409, `${input2.path} changed on this computer.`);
|
|
46939
|
-
await mkdir16(
|
|
46988
|
+
await mkdir16(path74.dirname(file2), { recursive: true });
|
|
46940
46989
|
const temporary = `${file2}.phren-${process.pid}-${Date.now()}`;
|
|
46941
46990
|
await writeFile8(temporary, content, { flag: "wx" });
|
|
46942
46991
|
await rename7(temporary, file2);
|
|
@@ -46971,7 +47020,7 @@ init_protocol();
|
|
|
46971
47020
|
import { execFile as execFile14 } from "node:child_process";
|
|
46972
47021
|
import { chmod as chmod4, mkdir as mkdir17, readFile as readFile29, rename as rename8, stat as stat21, unlink as unlink5, writeFile as writeFile9 } from "node:fs/promises";
|
|
46973
47022
|
import { tmpdir as tmpdir3 } from "node:os";
|
|
46974
|
-
import
|
|
47023
|
+
import path75 from "node:path";
|
|
46975
47024
|
import { createHash as createHash16, randomUUID as randomUUID17 } from "node:crypto";
|
|
46976
47025
|
import { promisify as promisify13 } from "node:util";
|
|
46977
47026
|
var exec13 = promisify13(execFile14);
|
|
@@ -46999,7 +47048,7 @@ async function bootedSimulators() {
|
|
|
46999
47048
|
async function simulatorScreenshot(udid) {
|
|
47000
47049
|
if (!UDID.test(udid)) throw new BridgeError(400, "Invalid simulator identifier.");
|
|
47001
47050
|
if (process.platform !== "darwin") throw new BridgeError(404, "Simulators run on macOS only.");
|
|
47002
|
-
const file2 =
|
|
47051
|
+
const file2 = path75.join(tmpdir3(), `phren-sim-${randomUUID17()}.png`);
|
|
47003
47052
|
try {
|
|
47004
47053
|
await exec13("/usr/bin/xcrun", ["simctl", "io", udid, "screenshot", "--type=png", file2], { timeout: 15e3 });
|
|
47005
47054
|
return await readFile29(file2);
|
|
@@ -47018,14 +47067,14 @@ function helper() {
|
|
|
47018
47067
|
return building;
|
|
47019
47068
|
}
|
|
47020
47069
|
async function buildHelper() {
|
|
47021
|
-
const dir =
|
|
47022
|
-
const binary =
|
|
47070
|
+
const dir = path75.join(bridgeRoot(), "native");
|
|
47071
|
+
const binary = path75.join(dir, "simtap");
|
|
47023
47072
|
const code = true ? '// Touches and keys for the iOS Simulator, without AppleScript: the window\n// is found through the Accessibility API and events are posted with CGEvent,\n// so one Accessibility grant for this helper is all macOS asks for.\n// Built on demand by Phren Hook with swiftc; see simulators.ts.\nimport ApplicationServices\nimport Cocoa\n\nfunc fail(_ code: Int32, _ message: String) -> Never { FileHandle.standardError.write((message + "\\n").data(using: .utf8)!); exit(code) }\n\nlet args = CommandLine.arguments\nguard args.count >= 3 else { fail(2, "usage: simtap <window-title-prefix> tap <fx> <fy> | key <keycode> [cmd] [shift] | type <text> | raise") }\nlet prefix = args[1], command = args[2]\n\nguard AXIsProcessTrusted() else { fail(3, "accessibility") }\nguard let app = NSRunningApplication.runningApplications(withBundleIdentifier: "com.apple.iphonesimulator").first else { fail(4, "Simulator is not running") }\nlet element = AXUIElementCreateApplication(app.processIdentifier)\nvar windowsRef: CFTypeRef?\nAXUIElementCopyAttributeValue(element, kAXWindowsAttribute as CFString, &windowsRef)\nlet windows = (windowsRef as? [AXUIElement]) ?? []\nvar target: AXUIElement?\nfor window in windows {\n var titleRef: CFTypeRef?\n AXUIElementCopyAttributeValue(window, kAXTitleAttribute as CFString, &titleRef)\n if let title = titleRef as? String, title.hasPrefix(prefix + " ") || title == prefix { target = window; break }\n}\nguard let window = target else { fail(5, "no window for \\(prefix)") }\n\nfunc frame(_ window: AXUIElement) -> CGRect {\n var posRef: CFTypeRef?, sizeRef: CFTypeRef?\n AXUIElementCopyAttributeValue(window, kAXPositionAttribute as CFString, &posRef)\n AXUIElementCopyAttributeValue(window, kAXSizeAttribute as CFString, &sizeRef)\n var pos = CGPoint.zero, size = CGSize.zero\n if let p = posRef { AXValueGetValue(p as! AXValue, .cgPoint, &pos) }\n if let s = sizeRef { AXValueGetValue(s as! AXValue, .cgSize, &size) }\n return CGRect(origin: pos, size: size)\n}\nfunc raise() {\n app.activate(options: [])\n AXUIElementPerformAction(window, kAXRaiseAction as CFString)\n usleep(120_000)\n}\nfunc post(_ event: CGEvent?) {\n guard NSWorkspace.shared.frontmostApplication?.processIdentifier == app.processIdentifier else { fail(6, "focus lost") }\n event?.postToPid(app.processIdentifier)\n usleep(40_000)\n}\n\nswitch command {\ncase "raise": raise()\ncase "tap":\n guard args.count >= 5, let fx = Double(args[3]), let fy = Double(args[4]) else { fail(2, "tap needs fx fy") }\n raise()\n let f = frame(window)\n // The device screen fills the window below its title bar.\n let titleBar: CGFloat = 28\n let point = CGPoint(x: f.origin.x + CGFloat(fx) * f.width, y: f.origin.y + titleBar + CGFloat(fy) * (f.height - titleBar))\n post(CGEvent(mouseEventSource: nil, mouseType: .mouseMoved, mouseCursorPosition: point, mouseButton: .left))\n post(CGEvent(mouseEventSource: nil, mouseType: .leftMouseDown, mouseCursorPosition: point, mouseButton: .left))\n post(CGEvent(mouseEventSource: nil, mouseType: .leftMouseUp, mouseCursorPosition: point, mouseButton: .left))\ncase "key":\n guard args.count >= 4, let code = UInt16(args[3]) else { fail(2, "key needs a keycode") }\n raise()\n var flags: CGEventFlags = []\n if args.contains("cmd") { flags.insert(.maskCommand) }\n if args.contains("shift") { flags.insert(.maskShift) }\n let down = CGEvent(keyboardEventSource: nil, virtualKey: code, keyDown: true), up = CGEvent(keyboardEventSource: nil, virtualKey: code, keyDown: false)\n down?.flags = flags; up?.flags = flags\n post(down); post(up)\ncase "type":\n guard args.count >= 4, !args[3].isEmpty, args[3].utf16.count <= 500 else { fail(2, "type needs at most 500 characters") }\n let submit = args.count == 5 && args[4] == "submit"\n guard args[3].unicodeScalars.allSatisfy({ scalar in\n (scalar.value >= 32 && scalar.value != 127) || (scalar.value == 10 && submit)\n }) else { fail(2, "invalid type controls; newline needs submit") }\n raise()\n for scalar in args[3].unicodeScalars {\n var chars = Array(String(scalar).utf16)\n let down = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: true), up = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: false)\n down?.keyboardSetUnicodeString(stringLength: chars.count, unicodeString: &chars)\n up?.keyboardSetUnicodeString(stringLength: chars.count, unicodeString: &chars)\n post(down); post(up)\n }\ndefault: fail(2, "unknown command \\(command)")\n}\n' : await readFile29(new URL("./native/simtap.swift", import.meta.url), "utf8");
|
|
47024
47073
|
const digest2 = createHash16("sha256").update(code).digest("hex");
|
|
47025
47074
|
const saved = await readFile29(binary + ".sha256", "utf8").then(JSON.parse).catch(() => void 0);
|
|
47026
47075
|
if (await stat21(binary).catch(() => void 0) && saved?.sourceSha === digest2) return binary;
|
|
47027
47076
|
await mkdir17(dir, { recursive: true, mode: 448 });
|
|
47028
|
-
const temporary =
|
|
47077
|
+
const temporary = path75.join(dir, `simtap.${randomUUID17()}`), source = temporary + ".swift";
|
|
47029
47078
|
const sidecar = temporary + ".sha256";
|
|
47030
47079
|
try {
|
|
47031
47080
|
await writeFile9(source, code, { mode: 384, flag: "wx" });
|
|
@@ -47137,7 +47186,7 @@ init_transcripts();
|
|
|
47137
47186
|
// src/bridge/uploads.ts
|
|
47138
47187
|
init_protocol();
|
|
47139
47188
|
import { mkdir as mkdir18, readdir as readdir14, lstat as lstat18, realpath as realpath15, readFile as readFile30, stat as stat22, unlink as unlink6, writeFile as writeFile10 } from "node:fs/promises";
|
|
47140
|
-
import
|
|
47189
|
+
import path76 from "node:path";
|
|
47141
47190
|
import { randomUUID as randomUUID18 } from "node:crypto";
|
|
47142
47191
|
function imageBytes(bytes) {
|
|
47143
47192
|
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";
|
|
@@ -47150,24 +47199,24 @@ async function saveUpload(session, name, bytes) {
|
|
|
47150
47199
|
let saved = "";
|
|
47151
47200
|
const task = uploadQueue.catch(() => {
|
|
47152
47201
|
}).then(async () => {
|
|
47153
|
-
const root =
|
|
47202
|
+
const root = path76.join(bridgeRoot(), "uploads");
|
|
47154
47203
|
await mkdir18(root, { recursive: true, mode: 448 });
|
|
47155
47204
|
let used = 0;
|
|
47156
47205
|
const directories = await readdir14(root, { withFileTypes: true });
|
|
47157
47206
|
for (const dir of directories) {
|
|
47158
47207
|
if (!dir.isDirectory()) continue;
|
|
47159
|
-
const folder2 =
|
|
47208
|
+
const folder2 = path76.join(root, dir.name);
|
|
47160
47209
|
for (const entry of await readdir14(folder2, { withFileTypes: true })) {
|
|
47161
47210
|
if (!entry.isFile()) continue;
|
|
47162
|
-
const file2 =
|
|
47211
|
+
const file2 = path76.join(folder2, entry.name), metadata = await lstat18(file2);
|
|
47163
47212
|
if (Date.now() - metadata.mtimeMs > 14 * 864e5) await unlink6(file2);
|
|
47164
47213
|
else used += metadata.size;
|
|
47165
47214
|
}
|
|
47166
47215
|
}
|
|
47167
47216
|
if (used + bytes.length > 268435456) throw new BridgeError(413, "Phren's image storage is full. Remove older uploads on the computer.");
|
|
47168
|
-
const folder =
|
|
47217
|
+
const folder = path76.join(root, session);
|
|
47169
47218
|
await mkdir18(folder, { recursive: true, mode: 448 });
|
|
47170
|
-
saved =
|
|
47219
|
+
saved = path76.join(folder, `${randomUUID18()}-${name}`);
|
|
47171
47220
|
await writeFile10(saved, bytes, { flag: "wx", mode: 384 });
|
|
47172
47221
|
});
|
|
47173
47222
|
uploadQueue = task;
|
|
@@ -47175,22 +47224,22 @@ async function saveUpload(session, name, bytes) {
|
|
|
47175
47224
|
return saved;
|
|
47176
47225
|
}
|
|
47177
47226
|
async function listUploads(session) {
|
|
47178
|
-
const folder =
|
|
47227
|
+
const folder = path76.join(bridgeRoot(), "uploads", session);
|
|
47179
47228
|
const entries2 = await readdir14(folder, { withFileTypes: true }).catch(() => []);
|
|
47180
47229
|
const files = [];
|
|
47181
47230
|
for (const entry of entries2) {
|
|
47182
47231
|
if (!entry.isFile()) continue;
|
|
47183
|
-
const file2 =
|
|
47232
|
+
const file2 = path76.join(folder, entry.name), metadata = await stat22(file2);
|
|
47184
47233
|
files.push({ name: entry.name.replace(/^[0-9a-f-]{36}-/, ""), path: file2, size: metadata.size, modified: metadata.mtime.toISOString() });
|
|
47185
47234
|
}
|
|
47186
47235
|
return files.sort((a, b) => b.modified.localeCompare(a.modified)).slice(0, 200);
|
|
47187
47236
|
}
|
|
47188
47237
|
async function uploadImage(requested) {
|
|
47189
47238
|
const missing = new BridgeError(404, "This image is not one of the phone's uploads.");
|
|
47190
|
-
if (!requested || requested.length > 4096 || !
|
|
47191
|
-
const root = await realpath15(
|
|
47239
|
+
if (!requested || requested.length > 4096 || !path76.isAbsolute(requested)) throw missing;
|
|
47240
|
+
const root = await realpath15(path76.join(bridgeRoot(), "uploads")).catch(() => void 0);
|
|
47192
47241
|
const file2 = await realpath15(requested).catch(() => void 0);
|
|
47193
|
-
if (!root || !file2 || !file2.startsWith(root +
|
|
47242
|
+
if (!root || !file2 || !file2.startsWith(root + path76.sep)) throw missing;
|
|
47194
47243
|
const metadata = await stat22(file2);
|
|
47195
47244
|
if (!metadata.isFile()) throw missing;
|
|
47196
47245
|
if (metadata.size > 8388608) throw new BridgeError(413, "This image is too large.");
|
|
@@ -47204,7 +47253,7 @@ async function uploadImage(requested) {
|
|
|
47204
47253
|
init_transcript_index();
|
|
47205
47254
|
init_transcripts();
|
|
47206
47255
|
import { homedir as homedir18, tmpdir as tmpdir4 } from "node:os";
|
|
47207
|
-
import
|
|
47256
|
+
import path77 from "node:path";
|
|
47208
47257
|
init_protocol();
|
|
47209
47258
|
var cache = /* @__PURE__ */ new Map();
|
|
47210
47259
|
var modelCache = /* @__PURE__ */ new Map();
|
|
@@ -47342,7 +47391,7 @@ function describe3(tool, args) {
|
|
|
47342
47391
|
return "";
|
|
47343
47392
|
};
|
|
47344
47393
|
const firstLine = (v) => v.split(/\r?\n/).map((l) => l.trim()).find((l) => l) ?? "";
|
|
47345
|
-
const base = (v) =>
|
|
47394
|
+
const base = (v) => path77.basename(v.split(" \xB7 ")[0].trim()) || "file";
|
|
47346
47395
|
const name = tool.toLowerCase();
|
|
47347
47396
|
let value2;
|
|
47348
47397
|
if (["bash", "shell", "exec_command", "exec", "parallel", "tools", "write_stdin", "container.exec"].includes(name)) {
|
|
@@ -47377,7 +47426,7 @@ init_shared();
|
|
|
47377
47426
|
|
|
47378
47427
|
// src/bridge/server-pane-routes.ts
|
|
47379
47428
|
init_zod();
|
|
47380
|
-
import
|
|
47429
|
+
import path80 from "node:path";
|
|
47381
47430
|
import { setTimeout as sleep2 } from "node:timers/promises";
|
|
47382
47431
|
|
|
47383
47432
|
// src/bridge/git.ts
|
|
@@ -47385,7 +47434,7 @@ init_protocol();
|
|
|
47385
47434
|
import { createHash as createHash17 } from "node:crypto";
|
|
47386
47435
|
import { execFile as execFile15 } from "node:child_process";
|
|
47387
47436
|
import { lstat as lstat19, readdir as readdir15, readFile as readFile31, realpath as realpath16, stat as stat23 } from "node:fs/promises";
|
|
47388
|
-
import
|
|
47437
|
+
import path78 from "node:path";
|
|
47389
47438
|
import { promisify as promisify14 } from "node:util";
|
|
47390
47439
|
var exec14 = promisify14(execFile15);
|
|
47391
47440
|
function statusLetter(code) {
|
|
@@ -47431,7 +47480,7 @@ function parseNumstat(out) {
|
|
|
47431
47480
|
}
|
|
47432
47481
|
async function countLines(root, rel) {
|
|
47433
47482
|
try {
|
|
47434
|
-
const abs =
|
|
47483
|
+
const abs = path78.join(root, await repositoryPath(root, rel));
|
|
47435
47484
|
if ((await stat23(abs)).size > 5e6) return 0;
|
|
47436
47485
|
const bytes = await readFile31(abs);
|
|
47437
47486
|
if (!bytes.length || bytes.includes(0)) return 0;
|
|
@@ -47655,13 +47704,13 @@ async function gitPulls(cwd) {
|
|
|
47655
47704
|
}
|
|
47656
47705
|
}
|
|
47657
47706
|
async function repositoryPath(root, raw, allowRoot = false) {
|
|
47658
|
-
if (typeof raw !== "string" || raw.length > 4096 || raw.includes("\0") ||
|
|
47707
|
+
if (typeof raw !== "string" || raw.length > 4096 || raw.includes("\0") || path78.isAbsolute(raw) || path78.win32.isAbsolute(raw) || raw.startsWith("\\")) throw new BridgeError(400, "Invalid path.");
|
|
47659
47708
|
const segments = raw.split(/[\\/]/);
|
|
47660
47709
|
if (segments.includes("..")) throw new BridgeError(400, "Invalid path.");
|
|
47661
47710
|
const clean2 = segments.filter((part) => part && part !== ".").join("/");
|
|
47662
47711
|
if (!clean2 && !allowRoot || clean2.startsWith("-")) throw new BridgeError(400, "Invalid path.");
|
|
47663
|
-
const abs =
|
|
47664
|
-
if (abs !== root && !abs.startsWith(root +
|
|
47712
|
+
const abs = path78.resolve(root, clean2);
|
|
47713
|
+
if (abs !== root && !abs.startsWith(root + path78.sep)) throw new BridgeError(403, "This path is outside the repository.");
|
|
47665
47714
|
let existing = abs;
|
|
47666
47715
|
while (true) {
|
|
47667
47716
|
try {
|
|
@@ -47669,7 +47718,7 @@ async function repositoryPath(root, raw, allowRoot = false) {
|
|
|
47669
47718
|
break;
|
|
47670
47719
|
} catch (error62) {
|
|
47671
47720
|
if (error62.code !== "ENOENT" || existing === root) throw new BridgeError(400, "Invalid path.");
|
|
47672
|
-
existing =
|
|
47721
|
+
existing = path78.dirname(existing);
|
|
47673
47722
|
}
|
|
47674
47723
|
}
|
|
47675
47724
|
let resolved;
|
|
@@ -47678,7 +47727,7 @@ async function repositoryPath(root, raw, allowRoot = false) {
|
|
|
47678
47727
|
} catch {
|
|
47679
47728
|
throw new BridgeError(403, "This path cannot be resolved inside the repository.");
|
|
47680
47729
|
}
|
|
47681
|
-
if (resolved !== root && !resolved.startsWith(root +
|
|
47730
|
+
if (resolved !== root && !resolved.startsWith(root + path78.sep)) throw new BridgeError(403, "This path is outside the repository.");
|
|
47682
47731
|
return clean2;
|
|
47683
47732
|
}
|
|
47684
47733
|
var treeCache = /* @__PURE__ */ new Map();
|
|
@@ -47760,7 +47809,7 @@ async function ignoredEntries(root, prefix, shown) {
|
|
|
47760
47809
|
const entries2 = /* @__PURE__ */ new Map();
|
|
47761
47810
|
const inside = prefix && listing.some((item) => item.endsWith("/") && (prefix + "/").startsWith(item));
|
|
47762
47811
|
if (inside) {
|
|
47763
|
-
const dirents = await readdir15(
|
|
47812
|
+
const dirents = await readdir15(path78.join(root, prefix), { withFileTypes: true }).catch(() => []);
|
|
47764
47813
|
for (const dirent of dirents) {
|
|
47765
47814
|
if (dirent.name === ".git" || taken.has(dirent.name) || entries2.size >= MAX_IGNORED_ENTRIES) continue;
|
|
47766
47815
|
entries2.set(dirent.name, { name: dirent.name, path: `${prefix}/${dirent.name}`, kind: dirent.isDirectory() ? "dir" : "file", ignored: true });
|
|
@@ -47859,7 +47908,7 @@ init_protocol();
|
|
|
47859
47908
|
import { createHash as createHash18 } from "node:crypto";
|
|
47860
47909
|
import { realpath as realpath17, stat as stat24 } from "node:fs/promises";
|
|
47861
47910
|
import { homedir as homedir19 } from "node:os";
|
|
47862
|
-
import
|
|
47911
|
+
import path79 from "node:path";
|
|
47863
47912
|
var MAX_WORKTREES = 64;
|
|
47864
47913
|
var worktreeIdPattern = /^[a-f0-9]{32}$/;
|
|
47865
47914
|
function worktreeId(abs) {
|
|
@@ -47898,11 +47947,11 @@ async function listed(root) {
|
|
|
47898
47947
|
}
|
|
47899
47948
|
function displayPath(abs, roots) {
|
|
47900
47949
|
for (const root of roots) {
|
|
47901
|
-
const rel =
|
|
47902
|
-
if (rel && !rel.startsWith("..") && !
|
|
47950
|
+
const rel = path79.relative(root, abs);
|
|
47951
|
+
if (rel && !rel.startsWith("..") && !path79.isAbsolute(rel)) return rel.split(path79.sep).join("/");
|
|
47903
47952
|
}
|
|
47904
47953
|
const home = homedir19();
|
|
47905
|
-
return abs === home ? "~" : abs.startsWith(home +
|
|
47954
|
+
return abs === home ? "~" : abs.startsWith(home + path79.sep) ? "~/" + path79.relative(home, abs).split(path79.sep).join("/") : abs;
|
|
47906
47955
|
}
|
|
47907
47956
|
function uncommitted(status) {
|
|
47908
47957
|
const tokens = status.split("\0");
|
|
@@ -47916,12 +47965,12 @@ function uncommitted(status) {
|
|
|
47916
47965
|
return count2;
|
|
47917
47966
|
}
|
|
47918
47967
|
async function workerFor(abs, workers, all = []) {
|
|
47919
|
-
const nested = all.filter((other) => other.startsWith(abs +
|
|
47968
|
+
const nested = all.filter((other) => other.startsWith(abs + path79.sep));
|
|
47920
47969
|
let best;
|
|
47921
47970
|
for (const worker of workers) {
|
|
47922
|
-
const cwd = await realpath17(worker.cwd).catch(() =>
|
|
47923
|
-
if (cwd !== abs && !cwd.startsWith(abs +
|
|
47924
|
-
if (nested.some((inner) => cwd === inner || cwd.startsWith(inner +
|
|
47971
|
+
const cwd = await realpath17(worker.cwd).catch(() => path79.resolve(worker.cwd));
|
|
47972
|
+
if (cwd !== abs && !cwd.startsWith(abs + path79.sep)) continue;
|
|
47973
|
+
if (nested.some((inner) => cwd === inner || cwd.startsWith(inner + path79.sep))) continue;
|
|
47925
47974
|
const score = (cwd === abs ? 2 : 0) + (worker.child ? 1 : 0);
|
|
47926
47975
|
if (!best || score > best.score) best = { worker, score };
|
|
47927
47976
|
}
|
|
@@ -48305,7 +48354,7 @@ function herdrWorktreeWorkers(s) {
|
|
|
48305
48354
|
const workers = [];
|
|
48306
48355
|
for (const pane of objects(s.panes)) {
|
|
48307
48356
|
const cwd = pane.foreground_cwd || pane.cwd;
|
|
48308
|
-
if (typeof pane.agent !== "string" || typeof cwd !== "string" || !
|
|
48357
|
+
if (typeof pane.agent !== "string" || typeof cwd !== "string" || !path80.isAbsolute(cwd)) continue;
|
|
48309
48358
|
const name = paneAgentName(s, pane);
|
|
48310
48359
|
workers.push({
|
|
48311
48360
|
cwd,
|
|
@@ -48624,7 +48673,7 @@ async function paneRouteOnce(ctx, url2, data, response, typing) {
|
|
|
48624
48673
|
|
|
48625
48674
|
// src/bridge/server-launch.ts
|
|
48626
48675
|
import { mkdir as mkdir20, readFile as readFile32 } from "node:fs/promises";
|
|
48627
|
-
import
|
|
48676
|
+
import path82 from "node:path";
|
|
48628
48677
|
init_zod();
|
|
48629
48678
|
init_home_paths();
|
|
48630
48679
|
init_herdr();
|
|
@@ -48636,7 +48685,7 @@ init_utils_helpers();
|
|
|
48636
48685
|
init_metrics();
|
|
48637
48686
|
import { execFile as execFile17 } from "node:child_process";
|
|
48638
48687
|
import { mkdir as mkdir19, realpath as realpath18, rm as rm9, stat as stat26 } from "node:fs/promises";
|
|
48639
|
-
import
|
|
48688
|
+
import path81 from "node:path";
|
|
48640
48689
|
import { promisify as promisify16 } from "node:util";
|
|
48641
48690
|
init_protocol();
|
|
48642
48691
|
var exec16 = promisify16(execFile17);
|
|
@@ -48665,11 +48714,11 @@ async function createLaunchWorktree(cwd, request6) {
|
|
|
48665
48714
|
if (await git6(root, "show-ref", "--verify", "--quiet", `refs/heads/${branch}`).then(() => true, () => false)) {
|
|
48666
48715
|
throw new BridgeError(409, `A branch named "${branch}" already exists in this repository. Choose another branch name.`);
|
|
48667
48716
|
}
|
|
48668
|
-
const worktree =
|
|
48717
|
+
const worktree = path81.join(root, ".claude", "worktrees", worktreeFolderName(branch));
|
|
48669
48718
|
if (await stat26(worktree).then(() => true, () => false)) {
|
|
48670
48719
|
throw new BridgeError(409, `The folder .claude/worktrees/${worktreeFolderName(branch)} already exists. Choose another branch name.`);
|
|
48671
48720
|
}
|
|
48672
|
-
await mkdir19(
|
|
48721
|
+
await mkdir19(path81.dirname(worktree), { recursive: true });
|
|
48673
48722
|
try {
|
|
48674
48723
|
await git6(root, "worktree", "add", "-b", branch, worktree, head);
|
|
48675
48724
|
} catch (error62) {
|
|
@@ -48677,8 +48726,8 @@ async function createLaunchWorktree(cwd, request6) {
|
|
|
48677
48726
|
throw new BridgeError(409, `Git could not create the worktree${detail ? `: ${detail.replace(/^fatal:\s*/, "")}` : "."}`);
|
|
48678
48727
|
}
|
|
48679
48728
|
const abs = await realpath18(worktree);
|
|
48680
|
-
const inside =
|
|
48681
|
-
const start = inside && !inside.startsWith("..") ?
|
|
48729
|
+
const inside = path81.relative(root, await realpath18(cwd));
|
|
48730
|
+
const start = inside && !inside.startsWith("..") ? path81.join(abs, inside) : abs;
|
|
48682
48731
|
const startDir = await stat26(start).then((value2) => value2.isDirectory(), () => false) ? start : abs;
|
|
48683
48732
|
return {
|
|
48684
48733
|
cwd: startDir,
|
|
@@ -48721,10 +48770,10 @@ async function conductorBrief() {
|
|
|
48721
48770
|
let source;
|
|
48722
48771
|
if (true) source = "---\nname: conductor\ndescription: Coordinate independent Phren tasks across every project in the store and every enrolled computer, supervise their local agent fanout, and integrate verified returns in a concise dispatcher voice.\n---\n\n# Conductor\n\nYou are the owner's dispatcher for the whole store, not one project. You start\nin the phren store itself; that folder is not a project and not your work.\n\nFirst, before trusting your tools, check which phren you are running:\n`phren --version` and `command -v phren`. If the version is older than the one\nthe store or the owner expects, or the path is not the install you expect (a\nstale global package, an old checkout), tell the owner in one line and say\nwhich tools may be missing or behave differently.\n\nThen read the relevant projects' summaries and Phren tasks\n(`get_project_summary`, `get_tasks`) before selecting work.\n\nYour tools, use these instead of exploring the CLI or the Hook's files:\n\n- `live_sessions` (CLI `phren dispatch sessions`): every live agent on this\n computer and each enrolled one, with project, harness, status, `idleFor`\n (seconds since it last changed) and the target `hand_off` takes. Start here\n when asked what is running. Computers it could not reach are listed; say so\n rather than guessing. Computers in `notLinked` are registered in the store\n but have no Hook link here: say they were not checked, never that nothing is\n running there.\n- `hand_off`: send a prompt to one of those sessions.\n- `dispatch`: start a new worker on a computer (or `anywhere`).\n- `dispatch_returns` (CLI `phren dispatch returns`): what your workers sent\n back since you last asked: done with the final reply, needs-you with the\n question, failed with the error (a usage limit), blocked, or gone. Reading them marks them read. In core use\n `phren_admin(action: \"dispatch_returns\")`.\n- `phren dispatch status`: receipts of what you dispatched.\n- `get_tasks`, `get_project_summary`, `search_knowledge`: the store's memory.\n\nKeep engineering detail in worker briefs, Phren tasks and findings, and review\nartifacts, not in the owner's chat.\n\n## Voice and pace\n\nThe owner talks to you from the phone, often in talk mode, where your replies\nare read aloud in their voice. Sound like a good dispatcher: short, quick and\nconversational.\n\n- Lead with the outcome in one sentence. Keep the whole reply to one to four\n short sentences unless the owner asks for detail.\n- No tables, file paths, SHAs, PR numbers or run IDs in a reply unless the\n owner asks for them. Record them in Phren tasks and findings instead.\n- One short line per dispatch or return: who, what, result. A routine watcher\n or monitor event where nothing changed gets silence or a single line.\n- When the owner gives you a task, dispatch an engineer for it right away and\n say so in one line. That is the owner's standing rule; do not ask first.\n- Ask at most one question at a time, and name the options.\n- Delegate reading and analysis to workers instead of running long\n investigations yourself, so your own turns stay fast.\n- A message that begins with `[voice]` was spoken in talk mode, and your reply\n will be read aloud. Answer in one or two spoken sentences with no markdown,\n lists, symbols or code, written to sound natural read aloud: \"back in about\n twenty minutes\", not \"ETA ~20m\".\n\n```text\nLinuxbox has the parser checks on Codex, back around two twenty.\nDesk finished the navigation checks: tests passed, not merged yet.\n```\n\nIf a result or return time is unknown, say so. Surface a worker's question in\nthe same short voice, with the worker's own choices.\n\n## Dispatching\n\nPick five to ten independent tasks when that many are available and capacity\npermits. Do not manufacture tasks to fill the batch. Separate dependencies and\nfile ownership; give each remote lead a base revision, acceptance checks, local\nfanout limit, report time and integration instructions. Every brief repeats the\nowner's repository constraints, including any prohibition on commits, pushes,\nbranches or particular tests. Dispatch never expands the owner's authorization.\n\nYou are the one conductor for this computer and every computer linked with\nit; a second conductor in the group is refused at launch. Conductors on\ncomputers that are not linked share only the store, so claim a task before you\ndispatch it: `claim_task` (in core, `manage_task` with `action: \"claim\"`).\nSkip tasks marked `[claimed: <computer>]` by another computer. A claim that\ncomes back not claimed, with `heldBy`, means another conductor got there first:\nmove on. Completing a task clears its claim; release one you will not do. Start\nworkers with `dispatch` or `hand_off`, never as tabs in your own Herdr\nworkspace. When a computer shows up in `notLinked`, tell the owner that\n`phren bridge link <host>` can link it; never link a computer yourself.\n\nPrefer Codex. Use OpenCode Go when its account and harness are connected. Use\nOpenRouter only when the owner explicitly requests it; an unavailable account\ndoes not authorize another paid provider. Name an explicit model when instructed,\notherwise use and report the remote configured default. Each remote lead owns\nits local checkouts, fanout and provider rate limits. Where installed, local\nworkers use the fanout wrapper's `scripts/run.sh --provider codex|opencode\n--label --worktree [--model] [--mode]` contract and parent-bound manifests.\n\nPrefer handing work to a session that already owns the project and is idle or\ndoing related work; call `hand_off` in full or `phren_admin(action: \"hand_off\",\ncomputer?, target|session, text)` in core. Otherwise dispatch a new worker.\nWrite one short line either way. Call `dispatch` in full or\n`phren_admin(action: \"dispatch\", computer, project, harness, model?, prompt, label)`\nin core. The CLI equivalent is `phren dispatch <computer|anywhere> <project>\n--harness <harness> --label <label> --prompt <brief> [--model <model>]`.\n`anywhere` chooses the connected computer with the fewest working agents. Place\nbriefs sequentially, respecting busy/rate-limit responses. Keep their dispatch\nIDs. Do not send local filesystem paths as remote project names.\n\n`accepted` on a receipt is prompt acceptance, not worker completion. Returns\narrive on their own: the Hook follows every worker you dispatch, and when you\nare idle it types one line into this session, such as `Return: Linuxbox parser\nchecks done, tests passed (dispatch <id>). Call dispatch_returns.` When you see\none, call `dispatch_returns` and report each return in one short line. You may\nalso call it whenever you want the current state; do not poll it in a loop, and\ndo not read remote transcripts by hand to learn whether a worker finished. Tell\nthe owner a return time as an expectation, not a promise.\n\nFor a `needs-you` return, surface the worker's question in the owner's chat\nwith its choices as the worker wrote them; do not rewrite or answer it for the\nowner unless the owner already decided. Send the answer back with `hand_off`\nto the row's `target`. A `blocked` worker waits on terminal input, such as a\npermission prompt: say so and point the owner to the phone or the terminal. A\n`gone` worker's pane closed or was taken over: say so, and decide with the\nowner before giving its work to another agent. A `done` reply is the worker's\nown account; check its evidence before saying tests passed or work merged.\n\nAn uncertain delivery is never retried automatically. Inspect its known target\nor status before deciding with the owner whether a replacement is needed. Keep\nunavailable workers visible instead of giving their work to another agent\nwhile the original may still be running.\n\nIntegrate returned changes in dependency order within the owner's allowed\nworkflow. Run a cleanup pass across the combined result and the affected checks.\nRequire evidence before saying tests passed or merged. Ship only within existing\nauthorization; if publication is not authorized, return the reviewable result.\nUpdate Phren tasks when verified complete and save durable decisions. A worker's\nfinished turn alone does not complete the owner's task.\n";
|
|
48723
48772
|
else {
|
|
48724
|
-
const here =
|
|
48773
|
+
const here = path82.dirname(fileURLToPath(import.meta.url));
|
|
48725
48774
|
for (const candidate of [
|
|
48726
|
-
|
|
48727
|
-
|
|
48775
|
+
path82.join(here, "..", "starter", "global", "skills", "conductor", "SKILL.md"),
|
|
48776
|
+
path82.join(here, "..", "..", "starter", "global", "skills", "conductor", "SKILL.md")
|
|
48728
48777
|
]) {
|
|
48729
48778
|
source = await readFile32(candidate, "utf8").catch(() => void 0);
|
|
48730
48779
|
if (source !== void 0) break;
|
|
@@ -48745,15 +48794,15 @@ function effortArgs(kind, effort) {
|
|
|
48745
48794
|
}
|
|
48746
48795
|
async function prepareConductor(kind, effort, model) {
|
|
48747
48796
|
const brief = await conductorBrief();
|
|
48748
|
-
const briefDirectory =
|
|
48797
|
+
const briefDirectory = path82.join(bridgeRoot(), "conductor");
|
|
48749
48798
|
await mkdir20(briefDirectory, { recursive: true, mode: 448 });
|
|
48750
|
-
const briefFile =
|
|
48799
|
+
const briefFile = path82.join(briefDirectory, "brief.md");
|
|
48751
48800
|
if (await readFile32(briefFile, "utf8").catch(() => void 0) !== brief + "\n") await atomic(briefFile, brief + "\n");
|
|
48752
48801
|
if (kind === "claude") return [...model ? ["--model", model] : [], "--append-system-prompt-file", briefFile, "--effort", effort];
|
|
48753
48802
|
if (kind === "codex") return [...model ? ["--model", model] : [], "-c", `model_reasoning_effort=${effort}`, "-c", `developer_instructions=${JSON.stringify(brief)}`];
|
|
48754
48803
|
if (kind === "opencode") {
|
|
48755
|
-
const directory =
|
|
48756
|
-
const file2 =
|
|
48804
|
+
const directory = path82.join(process.env.XDG_CONFIG_HOME || path82.join(homeDir(), ".config"), "opencode", "agents");
|
|
48805
|
+
const file2 = path82.join(directory, "conductor.md");
|
|
48757
48806
|
const definition = `---
|
|
48758
48807
|
description: Coordinate the owner's work across agent sessions.
|
|
48759
48808
|
mode: primary
|
|
@@ -48790,7 +48839,7 @@ function herdrAgentName(label2) {
|
|
|
48790
48839
|
}
|
|
48791
48840
|
async function launchSession(server, data, options = {}) {
|
|
48792
48841
|
const role = external_exports.enum(["agent", "conductor"]).default("agent").parse(data.role);
|
|
48793
|
-
const projectDirectory = external_exports.string().min(1).max(4096).refine((t) =>
|
|
48842
|
+
const projectDirectory = external_exports.string().min(1).max(4096).refine((t) => path82.isAbsolute(t) && !/[\x00-\x1f\x7f]/.test(t)).parse(data.cwd);
|
|
48794
48843
|
const worktreeRequest = data.worktree === void 0 || data.worktree === null ? void 0 : launchWorktreeSchema.parse(data.worktree);
|
|
48795
48844
|
if (worktreeRequest && role === "conductor") throw new BridgeError(400, "A conductor works across projects, so it cannot start in a worktree.");
|
|
48796
48845
|
const label2 = plainText(200).parse(data.label);
|
|
@@ -48882,7 +48931,7 @@ async function workspaceAction(server, operation, data) {
|
|
|
48882
48931
|
if (tab && !objects(s.tabs).some((t) => t.tab_id === tab && (!workspace || t.workspace_id === workspace))) throw new BridgeError(409, "The tab changed.");
|
|
48883
48932
|
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.");
|
|
48884
48933
|
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);
|
|
48885
|
-
const cwd = data.cwd === void 0 ? void 0 : external_exports.string().max(4096).refine((t) =>
|
|
48934
|
+
const cwd = data.cwd === void 0 ? void 0 : external_exports.string().max(4096).refine((t) => path82.isAbsolute(t) && !/[\x00-\x1f\x7f]/.test(t)).parse(data.cwd);
|
|
48886
48935
|
if (operation === "create") await terminalProvider().create(server, { workspace, label: label2, cwd });
|
|
48887
48936
|
else if (!workspace && !tab && !pane) throw new BridgeError(400, "Choose a Herdr destination.");
|
|
48888
48937
|
else if (pane && operation === "focus") await terminalProvider().focusPane(server, pane);
|
|
@@ -49254,7 +49303,7 @@ function createRouteHandler(ctx) {
|
|
|
49254
49303
|
case "/v1/files/range": {
|
|
49255
49304
|
let root;
|
|
49256
49305
|
if (url2.searchParams.get("scope") === "uploads") {
|
|
49257
|
-
root =
|
|
49306
|
+
root = path83.join(bridgeRoot(), "uploads");
|
|
49258
49307
|
} else if (url2.searchParams.has("session")) {
|
|
49259
49308
|
const target = targetFromURL(url2), pane = await validateTarget(target);
|
|
49260
49309
|
const cwd = await gitRepository(pane, target, url2.searchParams.get("child") ?? void 0, url2.searchParams.get("worktree") ?? void 0);
|
|
@@ -49560,7 +49609,7 @@ init_protocol();
|
|
|
49560
49609
|
|
|
49561
49610
|
// src/bridge/transcript-preview.ts
|
|
49562
49611
|
init_codex_threads();
|
|
49563
|
-
import { constants as
|
|
49612
|
+
import { constants as constants6 } from "node:fs";
|
|
49564
49613
|
import { open as open16 } from "node:fs/promises";
|
|
49565
49614
|
init_protocol();
|
|
49566
49615
|
init_transcript_index();
|
|
@@ -49791,7 +49840,7 @@ async function readDeltaPreview(target, file2, rollout) {
|
|
|
49791
49840
|
if (target.source === "codex") return await codexThreadPreview(target.session) ?? (file2 && rollout ? await rollout.read(file2).catch(() => null) : null);
|
|
49792
49841
|
if (target.source !== "opencode" || !file2) return null;
|
|
49793
49842
|
try {
|
|
49794
|
-
const handle = await open16(file2 + ".preview.json",
|
|
49843
|
+
const handle = await open16(file2 + ".preview.json", constants6.O_RDONLY | constants6.O_NOFOLLOW | constants6.O_NONBLOCK);
|
|
49795
49844
|
let bytes;
|
|
49796
49845
|
try {
|
|
49797
49846
|
const stat27 = await handle.stat();
|
|
@@ -50226,7 +50275,7 @@ async function serve(version3) {
|
|
|
50226
50275
|
await mkdir21(root, { recursive: true, mode: 448 });
|
|
50227
50276
|
await chmod5(root, 448);
|
|
50228
50277
|
let computerID2;
|
|
50229
|
-
const identityFile =
|
|
50278
|
+
const identityFile = path84.join(root, "computer-id");
|
|
50230
50279
|
try {
|
|
50231
50280
|
computerID2 = (await readFile33(identityFile, "utf8")).trim();
|
|
50232
50281
|
} catch {
|
|
@@ -50276,7 +50325,7 @@ async function serve(version3) {
|
|
|
50276
50325
|
if (codeReindexer) agentHooks.changes.onRecord = (files) => codeReindexer.record(files);
|
|
50277
50326
|
function gatewayTiming() {
|
|
50278
50327
|
try {
|
|
50279
|
-
const parsed = JSON.parse(readFileSync32(
|
|
50328
|
+
const parsed = JSON.parse(readFileSync32(path84.join(root, "gateway.json"), "utf8"));
|
|
50280
50329
|
if (typeof parsed.ms === "number" && Number.isFinite(parsed.ms) && parsed.ms >= 0) return Math.round(parsed.ms);
|
|
50281
50330
|
} catch {
|
|
50282
50331
|
}
|
|
@@ -50322,7 +50371,7 @@ async function serve(version3) {
|
|
|
50322
50371
|
}
|
|
50323
50372
|
const stopRetention = modules.has("git") ? await startChangeRetention() : () => {
|
|
50324
50373
|
};
|
|
50325
|
-
if (modules.has("git")) await rm10(
|
|
50374
|
+
if (modules.has("git")) await rm10(path84.join(root, "changes-scratch"), { recursive: true, force: true });
|
|
50326
50375
|
const streams = transcriptStreams({ modules, agentHooks, codexQuestions, sideQuestions, info, activeCapabilities });
|
|
50327
50376
|
const { stream } = streams;
|
|
50328
50377
|
const overview = overviewStream({
|
|
@@ -50472,7 +50521,7 @@ init_phren_paths();
|
|
|
50472
50521
|
import { execFile as execFile18 } from "node:child_process";
|
|
50473
50522
|
import { readFile as readFile34 } from "node:fs/promises";
|
|
50474
50523
|
import { homedir as homedir20, hostname as hostname10, userInfo as userInfo3 } from "node:os";
|
|
50475
|
-
import
|
|
50524
|
+
import path85 from "node:path";
|
|
50476
50525
|
import { promisify as promisify17 } from "node:util";
|
|
50477
50526
|
init_protocol();
|
|
50478
50527
|
var exec17 = promisify17(execFile18);
|
|
@@ -50519,11 +50568,11 @@ async function probe2(host) {
|
|
|
50519
50568
|
return computerId ? { host, computerId, user: field("user") ?? "", client: field("client") } : void 0;
|
|
50520
50569
|
}
|
|
50521
50570
|
async function discoverComputers(options = {}) {
|
|
50522
|
-
const config3 = options.sshConfig ?? await readFile34(
|
|
50571
|
+
const config3 = options.sshConfig ?? await readFile34(path85.join(homedir20(), ".ssh", "config"), "utf8").catch(() => "");
|
|
50523
50572
|
const store = options.store !== void 0 ? options.store : findPhrenPath();
|
|
50524
50573
|
const machines = store ? listMachines(store) : void 0;
|
|
50525
50574
|
const { peers } = await optionalHookPeers();
|
|
50526
|
-
const own2 = (await readFile34(
|
|
50575
|
+
const own2 = (await readFile34(path85.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
|
|
50527
50576
|
const known = new Set([...localNames(), ...peers.flatMap((peer) => [peer.name, peer.address])].map(computerLabel));
|
|
50528
50577
|
const candidates = [.../* @__PURE__ */ new Set([...sshConfigHosts(config3), ...machines?.ok ? Object.keys(machines.data) : []])].filter((host) => !known.has(computerLabel(host))).slice(0, 32);
|
|
50529
50578
|
const [found, peerIds] = await Promise.all([
|
|
@@ -50545,7 +50594,7 @@ function slugName(value2) {
|
|
|
50545
50594
|
async function linkComputer(host, options = {}) {
|
|
50546
50595
|
const remote = await probe2(host);
|
|
50547
50596
|
if (!remote) throw new BridgeError(409, `${host} answers over ssh but Phren Hook is not installed there. Run phren bridge install on it first.`);
|
|
50548
|
-
const own2 = (await readFile34(
|
|
50597
|
+
const own2 = (await readFile34(path85.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
|
|
50549
50598
|
if (remote.computerId === own2) throw new BridgeError(409, `${host} is this computer.`);
|
|
50550
50599
|
const name = computerName.parse(options.name ?? slugName(host));
|
|
50551
50600
|
const as = computerName.parse(options.as ?? slugName(hostname10()));
|
|
@@ -50746,7 +50795,7 @@ async function readSecret(prompt) {
|
|
|
50746
50795
|
// src/bridge/hook-main.ts
|
|
50747
50796
|
init_utils_helpers();
|
|
50748
50797
|
Object.assign(process.env, nonInteractiveGitEnv());
|
|
50749
|
-
runBridge(process.argv.slice(2), "0.3.
|
|
50798
|
+
runBridge(process.argv.slice(2), "0.3.9").then((code) => {
|
|
50750
50799
|
process.exitCode = code;
|
|
50751
50800
|
}).catch((error62) => {
|
|
50752
50801
|
console.error(error62 instanceof Error ? error62.message : "Phren Hook failed.");
|