@phren/cli 0.3.78 → 0.3.79
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/files.d.ts +1 -1
- package/dist/bridge/owner-proof.d.ts +41 -0
- package/dist/bridge/owner-proof.js +118 -0
- package/dist/bridge/server-routes.d.ts +1 -0
- package/dist/bridge/server-routes.js +10 -2
- package/dist/bridge-hook.mjs +373 -253
- package/dist/modules/registry.js +1 -1
- package/package.json +1 -1
package/dist/bridge-hook.mjs
CHANGED
|
@@ -387,10 +387,10 @@ function mergeDefs(...defs) {
|
|
|
387
387
|
function cloneDef(schema) {
|
|
388
388
|
return mergeDefs(schema._zod.def);
|
|
389
389
|
}
|
|
390
|
-
function getElementAtPath(obj3,
|
|
391
|
-
if (!
|
|
390
|
+
function getElementAtPath(obj3, path180) {
|
|
391
|
+
if (!path180)
|
|
392
392
|
return obj3;
|
|
393
|
-
return
|
|
393
|
+
return path180.reduce((acc, key4) => acc?.[key4], obj3);
|
|
394
394
|
}
|
|
395
395
|
function promiseAllObject(promisesObj) {
|
|
396
396
|
const keys2 = Object.keys(promisesObj);
|
|
@@ -649,11 +649,11 @@ function explicitlyAborted(x, startIndex = 0) {
|
|
|
649
649
|
}
|
|
650
650
|
return false;
|
|
651
651
|
}
|
|
652
|
-
function prefixIssues(
|
|
652
|
+
function prefixIssues(path180, issues) {
|
|
653
653
|
return issues.map((iss) => {
|
|
654
654
|
var _a3;
|
|
655
655
|
(_a3 = iss).path ?? (_a3.path = []);
|
|
656
|
-
iss.path.unshift(
|
|
656
|
+
iss.path.unshift(path180);
|
|
657
657
|
return iss;
|
|
658
658
|
});
|
|
659
659
|
}
|
|
@@ -1186,16 +1186,16 @@ function flattenError(error62, mapper = (issue2) => issue2.message) {
|
|
|
1186
1186
|
}
|
|
1187
1187
|
function formatError(error62, mapper = (issue2) => issue2.message) {
|
|
1188
1188
|
const fieldErrors = { _errors: [] };
|
|
1189
|
-
const processError = (error63,
|
|
1189
|
+
const processError = (error63, path180 = []) => {
|
|
1190
1190
|
for (const issue2 of error63.issues) {
|
|
1191
1191
|
if (issue2.code === "invalid_union" && issue2.errors.length) {
|
|
1192
|
-
issue2.errors.map((issues) => processError({ issues }, [...
|
|
1192
|
+
issue2.errors.map((issues) => processError({ issues }, [...path180, ...issue2.path]));
|
|
1193
1193
|
} else if (issue2.code === "invalid_key") {
|
|
1194
|
-
processError({ issues: issue2.issues }, [...
|
|
1194
|
+
processError({ issues: issue2.issues }, [...path180, ...issue2.path]);
|
|
1195
1195
|
} else if (issue2.code === "invalid_element") {
|
|
1196
|
-
processError({ issues: issue2.issues }, [...
|
|
1196
|
+
processError({ issues: issue2.issues }, [...path180, ...issue2.path]);
|
|
1197
1197
|
} else {
|
|
1198
|
-
const fullpath = [...
|
|
1198
|
+
const fullpath = [...path180, ...issue2.path];
|
|
1199
1199
|
if (fullpath.length === 0) {
|
|
1200
1200
|
fieldErrors._errors.push(mapper(issue2));
|
|
1201
1201
|
} else {
|
|
@@ -1234,17 +1234,17 @@ function formatError(error62, mapper = (issue2) => issue2.message) {
|
|
|
1234
1234
|
}
|
|
1235
1235
|
function treeifyError(error62, mapper = (issue2) => issue2.message) {
|
|
1236
1236
|
const result = { errors: [] };
|
|
1237
|
-
const processError = (error63,
|
|
1237
|
+
const processError = (error63, path180 = []) => {
|
|
1238
1238
|
var _a3;
|
|
1239
1239
|
for (const issue2 of error63.issues) {
|
|
1240
1240
|
if (issue2.code === "invalid_union" && issue2.errors.length) {
|
|
1241
|
-
issue2.errors.map((issues) => processError({ issues }, [...
|
|
1241
|
+
issue2.errors.map((issues) => processError({ issues }, [...path180, ...issue2.path]));
|
|
1242
1242
|
} else if (issue2.code === "invalid_key") {
|
|
1243
|
-
processError({ issues: issue2.issues }, [...
|
|
1243
|
+
processError({ issues: issue2.issues }, [...path180, ...issue2.path]);
|
|
1244
1244
|
} else if (issue2.code === "invalid_element") {
|
|
1245
|
-
processError({ issues: issue2.issues }, [...
|
|
1245
|
+
processError({ issues: issue2.issues }, [...path180, ...issue2.path]);
|
|
1246
1246
|
} else {
|
|
1247
|
-
const fullpath = [...
|
|
1247
|
+
const fullpath = [...path180, ...issue2.path];
|
|
1248
1248
|
if (fullpath.length === 0) {
|
|
1249
1249
|
result.errors.push(mapper(issue2));
|
|
1250
1250
|
continue;
|
|
@@ -1283,8 +1283,8 @@ function treeifyError(error62, mapper = (issue2) => issue2.message) {
|
|
|
1283
1283
|
}
|
|
1284
1284
|
function toDotPath(_path) {
|
|
1285
1285
|
const segs = [];
|
|
1286
|
-
const
|
|
1287
|
-
for (const seg of
|
|
1286
|
+
const path180 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
|
|
1287
|
+
for (const seg of path180) {
|
|
1288
1288
|
if (typeof seg === "number")
|
|
1289
1289
|
segs.push(`[${seg}]`);
|
|
1290
1290
|
else if (typeof seg === "symbol")
|
|
@@ -19316,13 +19316,13 @@ function resolveRef(ref, ctx) {
|
|
|
19316
19316
|
if (!ref.startsWith("#")) {
|
|
19317
19317
|
throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
|
|
19318
19318
|
}
|
|
19319
|
-
const
|
|
19320
|
-
if (
|
|
19319
|
+
const path180 = ref.slice(1).split("/").filter(Boolean);
|
|
19320
|
+
if (path180.length === 0) {
|
|
19321
19321
|
return ctx.rootSchema;
|
|
19322
19322
|
}
|
|
19323
19323
|
const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
|
|
19324
|
-
if (
|
|
19325
|
-
const key4 =
|
|
19324
|
+
if (path180[0] === defsKey) {
|
|
19325
|
+
const key4 = path180[1] === void 0 ? void 0 : decodeJSONPointerSegment(path180[1]);
|
|
19326
19326
|
if (!key4 || !ctx.defs[key4]) {
|
|
19327
19327
|
throw new Error(`Reference not found: ${ref}`);
|
|
19328
19328
|
}
|
|
@@ -35035,7 +35035,7 @@ var require_websocket = __commonJS({
|
|
|
35035
35035
|
var http = __require("http");
|
|
35036
35036
|
var net2 = __require("net");
|
|
35037
35037
|
var tls = __require("tls");
|
|
35038
|
-
var { randomBytes: randomBytes14, createHash:
|
|
35038
|
+
var { randomBytes: randomBytes14, createHash: createHash45 } = __require("crypto");
|
|
35039
35039
|
var { Duplex: Duplex2, Readable: Readable2 } = __require("stream");
|
|
35040
35040
|
var { URL: URL2 } = __require("url");
|
|
35041
35041
|
var PerMessageDeflate2 = require_permessage_deflate();
|
|
@@ -35716,7 +35716,7 @@ var require_websocket = __commonJS({
|
|
|
35716
35716
|
abortHandshake(websocket, socket, "Invalid Upgrade header");
|
|
35717
35717
|
return;
|
|
35718
35718
|
}
|
|
35719
|
-
const digest2 =
|
|
35719
|
+
const digest2 = createHash45("sha1").update(key4 + GUID).digest("base64");
|
|
35720
35720
|
if (res.headers["sec-websocket-accept"] !== digest2) {
|
|
35721
35721
|
abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
|
|
35722
35722
|
return;
|
|
@@ -36085,7 +36085,7 @@ var require_websocket_server = __commonJS({
|
|
|
36085
36085
|
var EventEmitter4 = __require("events");
|
|
36086
36086
|
var http = __require("http");
|
|
36087
36087
|
var { Duplex: Duplex2 } = __require("stream");
|
|
36088
|
-
var { createHash:
|
|
36088
|
+
var { createHash: createHash45 } = __require("crypto");
|
|
36089
36089
|
var extension2 = require_extension();
|
|
36090
36090
|
var PerMessageDeflate2 = require_permessage_deflate();
|
|
36091
36091
|
var subprotocol2 = require_subprotocol();
|
|
@@ -36392,7 +36392,7 @@ var require_websocket_server = __commonJS({
|
|
|
36392
36392
|
);
|
|
36393
36393
|
}
|
|
36394
36394
|
if (this._state > RUNNING) return abortHandshake(socket, 503);
|
|
36395
|
-
const digest2 =
|
|
36395
|
+
const digest2 = createHash45("sha1").update(key4 + GUID).digest("base64");
|
|
36396
36396
|
const headers = [
|
|
36397
36397
|
"HTTP/1.1 101 Switching Protocols",
|
|
36398
36398
|
"Upgrade: websocket",
|
|
@@ -39589,7 +39589,7 @@ var init_package_metadata = __esm({
|
|
|
39589
39589
|
__dirname = path41.dirname(fileURLToPath3(import.meta.url));
|
|
39590
39590
|
ROOT = path41.join(__dirname, "..");
|
|
39591
39591
|
PACKAGE_JSON_PATH = path41.join(ROOT, "package.json");
|
|
39592
|
-
BUNDLED_VERSION = true ? "0.3.
|
|
39592
|
+
BUNDLED_VERSION = true ? "0.3.79" : "0.0.0";
|
|
39593
39593
|
PACKAGE_JSON = readPackageJson();
|
|
39594
39594
|
PACKAGE_NAME = PACKAGE_JSON.name || "phren";
|
|
39595
39595
|
VERSION = PACKAGE_JSON.version || BUNDLED_VERSION;
|
|
@@ -41987,7 +41987,7 @@ var init_registry = __esm({
|
|
|
41987
41987
|
init_package_metadata();
|
|
41988
41988
|
core = (names) => names.map((name2) => ({ name: name2, profiles: ["core", "full"] }));
|
|
41989
41989
|
full = (names) => names.map((name2) => ({ name: name2, profiles: ["full"] }));
|
|
41990
|
-
routes = (method, paths) => paths.map((
|
|
41990
|
+
routes = (method, paths) => paths.map((path180) => ({ method, path: path180 }));
|
|
41991
41991
|
BUILTIN_MODULES = [
|
|
41992
41992
|
{
|
|
41993
41993
|
schemaVersion: 1,
|
|
@@ -42360,6 +42360,7 @@ var init_registry = __esm({
|
|
|
42360
42360
|
"sudo",
|
|
42361
42361
|
"sudoOutcome",
|
|
42362
42362
|
"secretExec",
|
|
42363
|
+
"ownerProof",
|
|
42363
42364
|
"previewDeltas",
|
|
42364
42365
|
"quickChat",
|
|
42365
42366
|
"agentFolder",
|
|
@@ -48470,10 +48471,10 @@ function parseScheduleEvent(body2) {
|
|
|
48470
48471
|
throw new BridgeError(400, "Invalid schedule event: expected { event, deliveryId, payload }.");
|
|
48471
48472
|
}
|
|
48472
48473
|
}
|
|
48473
|
-
function field(payload,
|
|
48474
|
-
if (!payloadPathSchema.safeParse(
|
|
48474
|
+
function field(payload, path180) {
|
|
48475
|
+
if (!payloadPathSchema.safeParse(path180).success) return void 0;
|
|
48475
48476
|
let current2 = payload;
|
|
48476
|
-
for (const part of
|
|
48477
|
+
for (const part of path180.split(".")) {
|
|
48477
48478
|
if (!current2 || typeof current2 !== "object" || !Object.hasOwn(current2, part)) return void 0;
|
|
48478
48479
|
current2 = current2[part];
|
|
48479
48480
|
}
|
|
@@ -48481,19 +48482,19 @@ function field(payload, path179) {
|
|
|
48481
48482
|
}
|
|
48482
48483
|
function scheduleEventPrompt(schedule2, event) {
|
|
48483
48484
|
const fields2 = /* @__PURE__ */ Object.create(null);
|
|
48484
|
-
const text7 = (
|
|
48485
|
-
if (!payloadPathSchema.safeParse(
|
|
48486
|
-
const value2 = field(event.payload,
|
|
48485
|
+
const text7 = (path180) => {
|
|
48486
|
+
if (!payloadPathSchema.safeParse(path180).success) return "";
|
|
48487
|
+
const value2 = field(event.payload, path180);
|
|
48487
48488
|
const scalar = typeof value2 === "string" || typeof value2 === "number" || typeof value2 === "boolean";
|
|
48488
48489
|
const safe3 = scalar ? redactSecretsForLog(String(value2)).slice(0, 1024).replace(/[\x00-\x08\x0b-\x1f\x7f]/g, "") : "";
|
|
48489
|
-
if (Object.keys(fields2).length < 64 || Object.hasOwn(fields2,
|
|
48490
|
+
if (Object.keys(fields2).length < 64 || Object.hasOwn(fields2, path180)) fields2[path180] = safe3;
|
|
48490
48491
|
return safe3;
|
|
48491
48492
|
};
|
|
48492
48493
|
const matches = (schedule2.filters ?? []).map((filter) => {
|
|
48493
48494
|
text7(filter.path);
|
|
48494
48495
|
return field(event.payload, filter.path) === filter.equals;
|
|
48495
48496
|
}).every(Boolean);
|
|
48496
|
-
const prompt = schedule2.prompt.replace(/\{\{payload\.([^{}]+)\}\}/g, (_match,
|
|
48497
|
+
const prompt = schedule2.prompt.replace(/\{\{payload\.([^{}]+)\}\}/g, (_match, path180) => text7(path180)).slice(0, 8e3);
|
|
48497
48498
|
return { prompt, fields: fields2, matches };
|
|
48498
48499
|
}
|
|
48499
48500
|
var SCHEDULE_EVENT_BODY_CAP, eventSchema;
|
|
@@ -50226,19 +50227,19 @@ function obj(value2) {
|
|
|
50226
50227
|
}
|
|
50227
50228
|
function projectPath(host) {
|
|
50228
50229
|
if (!host.webUrl || !host.domain) return null;
|
|
50229
|
-
const
|
|
50230
|
-
return
|
|
50230
|
+
const path180 = host.webUrl.replace(/^https?:\/\/[^/]+\//, "");
|
|
50231
|
+
return path180 || null;
|
|
50231
50232
|
}
|
|
50232
50233
|
async function context(root, host) {
|
|
50233
|
-
const
|
|
50234
|
-
if (!host.domain || !
|
|
50234
|
+
const path180 = projectPath(host);
|
|
50235
|
+
if (!host.domain || !path180) return { available: false, reason: "unknown-host", message: "This repository has no GitLab remote.", pulls: [], current: null };
|
|
50235
50236
|
const token2 = await resolveHostToken("gitlab", host.domain);
|
|
50236
50237
|
if (!token2) return { available: false, reason: "auth", message: SIGN_IN(host.domain), pulls: [], current: null };
|
|
50237
50238
|
const base2 = await apiRoot(root, host.domain, `https://${host.domain}/api/v4`);
|
|
50238
|
-
return { base: base2, token: token2.token, project: encodeURIComponent(
|
|
50239
|
+
return { base: base2, token: token2.token, project: encodeURIComponent(path180), domain: host.domain, account: { source: token2.source, ...token2.user ? { user: token2.user } : {} } };
|
|
50239
50240
|
}
|
|
50240
|
-
function call(ctx,
|
|
50241
|
-
return hostJson(`${ctx.base}/projects/${ctx.project}${
|
|
50241
|
+
function call(ctx, path180, init = {}) {
|
|
50242
|
+
return hostJson(`${ctx.base}/projects/${ctx.project}${path180}`, { token: ctx.token, scheme: "private-token", ...init });
|
|
50242
50243
|
}
|
|
50243
50244
|
function listed(mr) {
|
|
50244
50245
|
const author = obj(mr.author);
|
|
@@ -50441,8 +50442,8 @@ async function context2(root, host) {
|
|
|
50441
50442
|
const api = await apiRoot(root, host.domain, `https://${host.domain}/api/v1`);
|
|
50442
50443
|
return { api, web: api.replace(/\/api\/v1$/, ""), repo: repo2, token: token2.token, domain: host.domain, account: { source: token2.source, ...token2.user ? { user: token2.user } : {} } };
|
|
50443
50444
|
}
|
|
50444
|
-
function call2(ctx,
|
|
50445
|
-
return hostJson(`${ctx.api}/repos/${ctx.repo}${
|
|
50445
|
+
function call2(ctx, path180, init = {}) {
|
|
50446
|
+
return hostJson(`${ctx.api}/repos/${ctx.repo}${path180}`, { token: ctx.token, scheme: "bearer", ...init });
|
|
50446
50447
|
}
|
|
50447
50448
|
function sameRepository(ctx, pull) {
|
|
50448
50449
|
const head = obj2(pull.head_repository);
|
|
@@ -50685,8 +50686,8 @@ function parseRemoteUrl(url2) {
|
|
|
50685
50686
|
return null;
|
|
50686
50687
|
}
|
|
50687
50688
|
}
|
|
50688
|
-
function clean3(
|
|
50689
|
-
return
|
|
50689
|
+
function clean3(path180) {
|
|
50690
|
+
return path180.replace(/^\/+/, "").replace(/\/+$/, "").replace(/\.git$/i, "");
|
|
50690
50691
|
}
|
|
50691
50692
|
function kindFromDomain(domain2) {
|
|
50692
50693
|
if (domain2 === "github.com" || domain2.endsWith(".github.com") || domain2.endsWith(".ghe.com")) return "github";
|
|
@@ -51572,10 +51573,10 @@ function projectAgents(values, parent, receipt, fallbackComputer, fallbackTarget
|
|
|
51572
51573
|
for (const value2 of values.slice(0, 128)) {
|
|
51573
51574
|
if (state.count >= 128) break;
|
|
51574
51575
|
const raw = object2(value2), id3 = childID.safeParse(raw.id), source = provider.safeParse(raw.provider);
|
|
51575
|
-
const
|
|
51576
|
+
const path180 = publicLabel(raw.path);
|
|
51576
51577
|
const callId = typeof raw.callId === "string" && raw.callId.length > 0 && raw.callId.length <= 200 ? raw.callId : void 0;
|
|
51577
51578
|
const routed = destination(raw, fallbackComputer, fallbackTarget);
|
|
51578
|
-
if (!id3.success || !source.success || !
|
|
51579
|
+
if (!id3.success || !source.success || !path180 || !callId || !routed) continue;
|
|
51579
51580
|
const descendant = lineage ? `${lineage}/${id3.data}` : id3.data;
|
|
51580
51581
|
const nestedSession = sessionId.safeParse(raw.session);
|
|
51581
51582
|
const cycleIdentity = nestedSession.success ? nestedSession.data : routed.remote.child ?? routed.remote.target.session;
|
|
@@ -51588,7 +51589,7 @@ function projectAgents(values, parent, receipt, fallbackComputer, fallbackTarget
|
|
|
51588
51589
|
projected.push({
|
|
51589
51590
|
id: publicID(parent, routed.computer.id, receipt.id, descendant),
|
|
51590
51591
|
provider: source.data,
|
|
51591
|
-
path:
|
|
51592
|
+
path: path180,
|
|
51592
51593
|
callId,
|
|
51593
51594
|
state: raw.failed === true ? "failed" : childState,
|
|
51594
51595
|
...typeof raw.finishedAt === "string" && Number.isFinite(Date.parse(raw.finishedAt)) ? { finishedAt: raw.finishedAt } : {},
|
|
@@ -64903,13 +64904,13 @@ async function moveComputers(project, self, local, currentAccount, conductor = f
|
|
|
64903
64904
|
async function localPoolRefusal(cwd, account2) {
|
|
64904
64905
|
const { getProjectDirs: getProjectDirs2 } = await Promise.resolve().then(() => (init_phren_paths(), phren_paths_exports));
|
|
64905
64906
|
const { realpath: realpath29 } = await import("node:fs/promises");
|
|
64906
|
-
const
|
|
64907
|
+
const path180 = await import("node:path");
|
|
64907
64908
|
const source = await realpath29(cwd).catch(() => cwd);
|
|
64908
64909
|
let project, longest = 0;
|
|
64909
64910
|
for (const directoryName of getProjectDirs2(phrenStoreRoot())) {
|
|
64910
|
-
const name2 =
|
|
64911
|
+
const name2 = path180.basename(directoryName);
|
|
64911
64912
|
const directory = await dispatchProjectDirectory(name2).catch(() => void 0);
|
|
64912
|
-
if (directory && directory.length > longest && (source === directory || source.startsWith(directory +
|
|
64913
|
+
if (directory && directory.length > longest && (source === directory || source.startsWith(directory + path180.sep))) {
|
|
64913
64914
|
project = name2;
|
|
64914
64915
|
longest = directory.length;
|
|
64915
64916
|
}
|
|
@@ -80268,8 +80269,8 @@ function relayLiveSpeech(client, query, options = {}) {
|
|
|
80268
80269
|
params.set("auto_mode", "true");
|
|
80269
80270
|
params.set("inactivity_timeout", "180");
|
|
80270
80271
|
}
|
|
80271
|
-
const
|
|
80272
|
-
const socket = connect6(`${origin}${
|
|
80272
|
+
const path180 = endpoint === "dialogue" ? "/v1/text-to-dialogue/stream-input" : `/v1/text-to-speech/${encodeURIComponent(voice)}/stream-input`;
|
|
80273
|
+
const socket = connect6(`${origin}${path180}?${params}`, key4);
|
|
80273
80274
|
upstream = socket;
|
|
80274
80275
|
const current2 = () => upstream === socket && !closed;
|
|
80275
80276
|
let voiced = false, firstAudio;
|
|
@@ -81138,7 +81139,7 @@ var init_code_routes = __esm({
|
|
|
81138
81139
|
const project = projectSchema.parse(projectValue ?? "");
|
|
81139
81140
|
const { codeDatabasePath } = await requireCodePackage(this.store);
|
|
81140
81141
|
const file5 = codeDatabasePath(this.store, project);
|
|
81141
|
-
await Promise.all([file5, `${file5}-journal`, `${file5}-wal`, `${file5}-shm`].map((
|
|
81142
|
+
await Promise.all([file5, `${file5}-journal`, `${file5}-wal`, `${file5}-shm`].map((path180) => rm19(path180, { force: true })));
|
|
81142
81143
|
return { project, disabled: true };
|
|
81143
81144
|
}
|
|
81144
81145
|
async reindex(projectValue) {
|
|
@@ -84048,10 +84049,121 @@ var init_account_add = __esm({
|
|
|
84048
84049
|
}
|
|
84049
84050
|
});
|
|
84050
84051
|
|
|
84052
|
+
// src/bridge/owner-proof.ts
|
|
84053
|
+
import { createHash as createHash42, createPublicKey as createPublicKey2, verify as verify2 } from "node:crypto";
|
|
84054
|
+
import { lstat as lstat40, readFile as readFile58 } from "node:fs/promises";
|
|
84055
|
+
import path155 from "node:path";
|
|
84056
|
+
function deviceKeys(authorizedKeys) {
|
|
84057
|
+
const result = /* @__PURE__ */ new Set();
|
|
84058
|
+
for (const line of authorizedKeys.split("\n")) {
|
|
84059
|
+
const match = /^restrict,pty,command="sh ~\/\.local\/share\/phren\/bridge\/dispatch" ssh-ed25519 ([A-Za-z0-9+/]+={0,2}) phren-(?:iphone|android)\s*$/.exec(line);
|
|
84060
|
+
if (!match) continue;
|
|
84061
|
+
const wire = Buffer.from(match[1], "base64");
|
|
84062
|
+
if (wire.length === 51 && wire.readUInt32BE(0) === 11 && wire.subarray(4, 15).toString() === "ssh-ed25519" && wire.readUInt32BE(15) === 32) result.add(wire.subarray(19).toString("base64"));
|
|
84063
|
+
}
|
|
84064
|
+
return result;
|
|
84065
|
+
}
|
|
84066
|
+
var OWNER_PROOF_HEADER, DOMAIN, WINDOW_MS, ROUTES, payloadSchema, envelopeSchema2, ownerProofRoute, bodyDigest, OwnerProof;
|
|
84067
|
+
var init_owner_proof = __esm({
|
|
84068
|
+
"src/bridge/owner-proof.ts"() {
|
|
84069
|
+
"use strict";
|
|
84070
|
+
init_zod();
|
|
84071
|
+
init_home_paths();
|
|
84072
|
+
init_protocol();
|
|
84073
|
+
init_request_origin();
|
|
84074
|
+
OWNER_PROOF_HEADER = "x-phren-owner-proof";
|
|
84075
|
+
DOMAIN = "phren-owner-request-v1";
|
|
84076
|
+
WINDOW_MS = 3e5;
|
|
84077
|
+
ROUTES = /* @__PURE__ */ new Set([
|
|
84078
|
+
"POST /v1/authority",
|
|
84079
|
+
"POST /v1/authority/confirm",
|
|
84080
|
+
"DELETE /v1/authority",
|
|
84081
|
+
"POST /v1/agents/permission-mode",
|
|
84082
|
+
"POST /v1/conductor/make",
|
|
84083
|
+
"POST /v1/conductor/stop",
|
|
84084
|
+
"POST /v1/push/register",
|
|
84085
|
+
"POST /v1/sets/link"
|
|
84086
|
+
]);
|
|
84087
|
+
payloadSchema = external_exports.object({
|
|
84088
|
+
domain: external_exports.literal(DOMAIN),
|
|
84089
|
+
nonce: external_exports.string().uuid(),
|
|
84090
|
+
at: external_exports.string().datetime({ offset: true }),
|
|
84091
|
+
method: external_exports.enum(["POST", "DELETE"]),
|
|
84092
|
+
path: external_exports.string().min(1).max(4096),
|
|
84093
|
+
body: external_exports.string().regex(/^[a-f0-9]{64}$/)
|
|
84094
|
+
}).strict();
|
|
84095
|
+
envelopeSchema2 = external_exports.object({ payload: external_exports.string().min(1).max(8192), signature: external_exports.string().min(1).max(128), publicKey: external_exports.string().min(1).max(64) }).strict();
|
|
84096
|
+
ownerProofRoute = (method, pathname) => ROUTES.has(`${method} ${pathname}`);
|
|
84097
|
+
bodyDigest = (raw) => createHash42("sha256").update(raw).digest("hex");
|
|
84098
|
+
OwnerProof = class {
|
|
84099
|
+
constructor(options = {}) {
|
|
84100
|
+
this.options = options;
|
|
84101
|
+
}
|
|
84102
|
+
options;
|
|
84103
|
+
seen = /* @__PURE__ */ new Map();
|
|
84104
|
+
required;
|
|
84105
|
+
get root() {
|
|
84106
|
+
return this.options.root ?? bridgeRoot();
|
|
84107
|
+
}
|
|
84108
|
+
get file() {
|
|
84109
|
+
return path155.join(this.root, "owner-proof.json");
|
|
84110
|
+
}
|
|
84111
|
+
now() {
|
|
84112
|
+
return (this.options.now ?? Date.now)();
|
|
84113
|
+
}
|
|
84114
|
+
async keys() {
|
|
84115
|
+
if (this.options.keys) return this.options.keys();
|
|
84116
|
+
return deviceKeys(await readFile58(path155.join(homeDir(), ".ssh", "authorized_keys"), "utf8").catch(() => ""));
|
|
84117
|
+
}
|
|
84118
|
+
/** Whether a phone has signed before, so unsigned owner actions are refused. */
|
|
84119
|
+
async isRequired() {
|
|
84120
|
+
if (this.required) return true;
|
|
84121
|
+
const info = await lstat40(this.file).catch(() => void 0);
|
|
84122
|
+
this.required = !!info?.isFile();
|
|
84123
|
+
return this.required;
|
|
84124
|
+
}
|
|
84125
|
+
/**
|
|
84126
|
+
* Throws 403 unless an owner-only request may go ahead. Requests that carry
|
|
84127
|
+
* an agent or peer origin are left to the route, which refuses them anyway.
|
|
84128
|
+
*/
|
|
84129
|
+
async check(request11, pathname, data, digest2) {
|
|
84130
|
+
if (!ownerProofRoute(request11.method, pathname) || !ownerRequest(request11, data)) return;
|
|
84131
|
+
const header2 = request11.headers?.[OWNER_PROOF_HEADER];
|
|
84132
|
+
if (typeof header2 !== "string") {
|
|
84133
|
+
if (await this.isRequired()) throw new BridgeError(403, "Confirm this on your paired phone: this action needs its signature.", { code: "owner-proof-required" });
|
|
84134
|
+
return;
|
|
84135
|
+
}
|
|
84136
|
+
const refused2 = () => new BridgeError(403, "The phone's signature for this action did not verify.", { code: "owner-proof-invalid" });
|
|
84137
|
+
let envelope, payload;
|
|
84138
|
+
try {
|
|
84139
|
+
envelope = envelopeSchema2.parse(JSON.parse(Buffer.from(header2, "base64url").toString("utf8")));
|
|
84140
|
+
payload = payloadSchema.parse(JSON.parse(Buffer.from(envelope.payload, "base64").toString("utf8")));
|
|
84141
|
+
} catch {
|
|
84142
|
+
throw refused2();
|
|
84143
|
+
}
|
|
84144
|
+
const raw = Buffer.from(envelope.publicKey, "base64"), signature = Buffer.from(envelope.signature, "base64");
|
|
84145
|
+
if (raw.length !== 32 || signature.length !== 64 || !(await this.keys()).has(raw.toString("base64"))) throw refused2();
|
|
84146
|
+
const key4 = createPublicKey2({ key: Buffer.concat([Buffer.from("302a300506032b6570032100", "hex"), raw]), format: "der", type: "spki" });
|
|
84147
|
+
if (!verify2(null, Buffer.from(envelope.payload, "base64"), key4, signature)) throw refused2();
|
|
84148
|
+
const at2 = Date.parse(payload.at), now = this.now();
|
|
84149
|
+
if (payload.method !== request11.method || payload.path !== pathname || payload.body !== digest2 || !(Math.abs(now - at2) <= WINDOW_MS)) throw refused2();
|
|
84150
|
+
for (const [nonce, until2] of this.seen) if (until2 < now) this.seen.delete(nonce);
|
|
84151
|
+
if (this.seen.has(payload.nonce)) throw refused2();
|
|
84152
|
+
if (this.seen.size >= 4096) throw new BridgeError(429, "Too many signed owner actions. Try again in a few minutes.");
|
|
84153
|
+
this.seen.set(payload.nonce, now + 2 * WINDOW_MS);
|
|
84154
|
+
if (!await this.isRequired()) {
|
|
84155
|
+
await atomic(this.file, JSON.stringify({ since: new Date(now).toISOString(), key: createHash42("sha256").update(raw).digest("hex") }));
|
|
84156
|
+
this.required = true;
|
|
84157
|
+
}
|
|
84158
|
+
}
|
|
84159
|
+
};
|
|
84160
|
+
}
|
|
84161
|
+
});
|
|
84162
|
+
|
|
84051
84163
|
// src/bridge/server-launch.ts
|
|
84052
84164
|
import { randomUUID as randomUUID35 } from "node:crypto";
|
|
84053
|
-
import { mkdir as mkdir37, mkdtemp as mkdtemp7, readFile as
|
|
84054
|
-
import
|
|
84165
|
+
import { mkdir as mkdir37, mkdtemp as mkdtemp7, readFile as readFile59, realpath as realpath25, rmdir as rmdir2 } from "node:fs/promises";
|
|
84166
|
+
import path156 from "node:path";
|
|
84055
84167
|
function effortArgs(kind, effort) {
|
|
84056
84168
|
if (kind === "claude") return ["--effort", effort];
|
|
84057
84169
|
if (kind === "codex") return ["-c", `model_reasoning_effort=${effort}`];
|
|
@@ -84075,7 +84187,7 @@ async function phrenLaunchArgs(kind, data, store = phrenStoreRoot()) {
|
|
|
84075
84187
|
return [...mode === "chat" ? ["--mode", "chat"] : [], ...resume ? ["--session", resume] : []];
|
|
84076
84188
|
}
|
|
84077
84189
|
async function sessionUsedTools(session, store = phrenStoreRoot()) {
|
|
84078
|
-
const raw = await
|
|
84190
|
+
const raw = await readFile59(path156.join(store, ".sessions", `session-${session}.events.jsonl`), "utf8").catch(() => "");
|
|
84079
84191
|
const withTools = (message) => {
|
|
84080
84192
|
const content = message?.content;
|
|
84081
84193
|
return Array.isArray(content) && content.some((block) => ["tool_use", "tool_result"].includes(String(block?.type)));
|
|
@@ -84107,8 +84219,8 @@ async function prepareConductor(kind, effort, model) {
|
|
|
84107
84219
|
if (kind === "claude") return [...model ? ["--model", model] : [], "--append-system-prompt-file", briefFile, "--effort", effort];
|
|
84108
84220
|
if (kind === "codex") return [...model ? ["--model", model] : [], "-c", `model_reasoning_effort=${effort}`, "-c", `developer_instructions=${JSON.stringify(brief)}`];
|
|
84109
84221
|
if (kind === "opencode") {
|
|
84110
|
-
const directory =
|
|
84111
|
-
const file5 =
|
|
84222
|
+
const directory = path156.join(process.env.XDG_CONFIG_HOME || path156.join(homeDir(), ".config"), "opencode", "agents");
|
|
84223
|
+
const file5 = path156.join(directory, "conductor.md");
|
|
84112
84224
|
const definition = `---
|
|
84113
84225
|
description: Coordinate the owner's work across agent sessions.
|
|
84114
84226
|
mode: primary
|
|
@@ -84117,7 +84229,7 @@ mode: primary
|
|
|
84117
84229
|
${brief}
|
|
84118
84230
|
`;
|
|
84119
84231
|
await mkdir37(directory, { recursive: true, mode: 448 });
|
|
84120
|
-
if (await
|
|
84232
|
+
if (await readFile59(file5, "utf8").catch(() => void 0) !== definition) await atomic(file5, definition, 420);
|
|
84121
84233
|
return [...model ? ["--model", model] : [], "--agent", "conductor", "--variant", effort];
|
|
84122
84234
|
}
|
|
84123
84235
|
if (kind === "phren") return [...PHREN_AGENT_ARGS, ...model ? phrenModelArgs(model) : [], "--append-system-prompt-file", briefFile, ...effortArgs(kind, effort)];
|
|
@@ -84308,7 +84420,7 @@ async function startSession(server, data, options) {
|
|
|
84308
84420
|
throw new BridgeError(400, "An agent folder is for a projectless agent without cwd or worktree.");
|
|
84309
84421
|
}
|
|
84310
84422
|
if (options.into && (role !== "agent" || agentFolder || data.worktree != null)) throw new BridgeError(400, "Only a worker starts in an existing pane, in that pane's folder.");
|
|
84311
|
-
const projectDirectory = agentFolder ? void 0 : external_exports.string().min(1).max(4096).refine((t) =>
|
|
84423
|
+
const projectDirectory = agentFolder ? void 0 : external_exports.string().min(1).max(4096).refine((t) => path156.isAbsolute(t) && !/[\x00-\x1f\x7f]/.test(t)).parse(data.cwd);
|
|
84312
84424
|
const worktreeRequest = data.worktree === void 0 || data.worktree === null ? void 0 : launchWorktreeSchema.parse(data.worktree);
|
|
84313
84425
|
if (worktreeRequest && role === "conductor") throw new BridgeError(400, "A conductor works across projects, so it cannot start in a worktree.");
|
|
84314
84426
|
const label2 = plainText(200).parse(data.label);
|
|
@@ -84394,14 +84506,14 @@ async function startSession(server, data, options) {
|
|
|
84394
84506
|
}
|
|
84395
84507
|
let scratch;
|
|
84396
84508
|
if (agentFolder) {
|
|
84397
|
-
await mkdir37(
|
|
84509
|
+
await mkdir37(path156.join(defaultPhrenPath(), ".runtime"), { recursive: true, mode: 448 });
|
|
84398
84510
|
const store = await realpath25(defaultPhrenPath());
|
|
84399
|
-
const runtime =
|
|
84511
|
+
const runtime = path156.join(store, ".runtime");
|
|
84400
84512
|
if (await realpath25(runtime) !== runtime) throw new BridgeError(403, "The runtime folder must be inside the Phren directory.");
|
|
84401
|
-
const agents =
|
|
84513
|
+
const agents = path156.join(runtime, "agents");
|
|
84402
84514
|
await mkdir37(agents, { recursive: true, mode: 448 });
|
|
84403
84515
|
if (await realpath25(agents) !== agents) throw new BridgeError(403, "The agents folder must be inside the Phren directory.");
|
|
84404
|
-
scratch = await mkdtemp7(
|
|
84516
|
+
scratch = await mkdtemp7(path156.join(agents, `${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}-${herdrAgentName(label2)}-`));
|
|
84405
84517
|
}
|
|
84406
84518
|
const cwd = scratch ?? worktree?.cwd ?? projectDirectory;
|
|
84407
84519
|
let keyedGitboy;
|
|
@@ -84591,7 +84703,7 @@ async function workspaceAction(server, operation, data) {
|
|
|
84591
84703
|
if (tab && !objects(s.tabs).some((t) => t.tab_id === tab && (!workspace || t.workspace_id === workspace))) throw new BridgeError(409, "The tab changed.");
|
|
84592
84704
|
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.");
|
|
84593
84705
|
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);
|
|
84594
|
-
const cwd = data.cwd === void 0 ? void 0 : external_exports.string().max(4096).refine((t) =>
|
|
84706
|
+
const cwd = data.cwd === void 0 ? void 0 : external_exports.string().max(4096).refine((t) => path156.isAbsolute(t) && !/[\x00-\x1f\x7f]/.test(t)).parse(data.cwd);
|
|
84595
84707
|
if (operation === "create") await terminalProvider().create(server, { workspace, label: label2, cwd });
|
|
84596
84708
|
else if (!workspace && !tab && !pane) throw new BridgeError(400, "Choose a Herdr destination.");
|
|
84597
84709
|
else if (pane && operation === "focus") await terminalProvider().focusPane(server, pane);
|
|
@@ -84657,7 +84769,7 @@ var init_server_launch = __esm({
|
|
|
84657
84769
|
});
|
|
84658
84770
|
|
|
84659
84771
|
// src/bridge/task-routes.ts
|
|
84660
|
-
import * as
|
|
84772
|
+
import * as path157 from "node:path";
|
|
84661
84773
|
import { realpath as realpath26, stat as stat37 } from "node:fs/promises";
|
|
84662
84774
|
function owner(base2, id3, write) {
|
|
84663
84775
|
const matches = taskStores(base2).filter((s) => s.taskStoreId === id3 && s.available !== false);
|
|
@@ -84693,7 +84805,7 @@ function getTaskRoute(base2, url2) {
|
|
|
84693
84805
|
if (!taskStoreHasProject(store, project)) throw new BridgeError(404, "Project is not in that task store.");
|
|
84694
84806
|
const result = readTasks(store.path, project);
|
|
84695
84807
|
if (!result.ok) throw new BridgeError(400, result.error);
|
|
84696
|
-
if (
|
|
84808
|
+
if (path157.resolve(result.data.path) !== path157.join(path157.resolve(store.path), project, "tasks.md")) throw new BridgeError(404, "Project is not in that task store.");
|
|
84697
84809
|
const filter = external_exports.object({ responsibility: external_exports.enum(["human", "agent"]).optional(), readiness: external_exports.enum(["ready", "waiting-on-human", "waiting-on-task"]).optional() }).parse(Object.fromEntries(url2.searchParams));
|
|
84698
84810
|
const filtered = filterTaskDoc(base2, result.data, filter);
|
|
84699
84811
|
const writerSafety = taskWriterSafety(store.path);
|
|
@@ -84706,7 +84818,7 @@ function updateTaskRoute(base2, input2) {
|
|
|
84706
84818
|
const denied = permissionDeniedError(store.path, "update_task", data.project);
|
|
84707
84819
|
if (denied) throw new BridgeError(403, denied);
|
|
84708
84820
|
const current2 = readTasks(store.path, data.project);
|
|
84709
|
-
if (!current2.ok ||
|
|
84821
|
+
if (!current2.ok || path157.resolve(current2.data.path) !== path157.join(path157.resolve(store.path), data.project, "tasks.md")) throw new BridgeError(404, "Project is not in that task store.");
|
|
84710
84822
|
const result = updateTask(store.path, data.project, `bid:${data.stableId}`, data.updates, base2);
|
|
84711
84823
|
if (!result.ok) throw new BridgeError(400, result.error);
|
|
84712
84824
|
return getTaskRoute(base2, new URL(`http://phren.local/v1/tasks?storeId=${data.storeId}&project=${data.project}`));
|
|
@@ -84723,7 +84835,7 @@ function createTaskRoute(base2, input2) {
|
|
|
84723
84835
|
if (denied) throw new BridgeError(403, denied);
|
|
84724
84836
|
}
|
|
84725
84837
|
const current2 = readTasks(store.path, data.project);
|
|
84726
|
-
if (!current2.ok ||
|
|
84838
|
+
if (!current2.ok || path157.resolve(current2.data.path) !== path157.join(path157.resolve(store.path), data.project, "tasks.md")) throw new BridgeError(404, "Project is not in that task store.");
|
|
84727
84839
|
const result = addTask(store.path, data.project, data.text, { stableId: data.stableId, responsibility: data.responsibility, graphRoot: base2 });
|
|
84728
84840
|
if (!result.ok) throw new BridgeError(409, result.error);
|
|
84729
84841
|
return getTaskRoute(base2, new URL(`http://phren.local/v1/tasks?storeId=${data.storeId}&project=${data.project}`));
|
|
@@ -84744,7 +84856,7 @@ function writableTaskProject(base2, storeId, project) {
|
|
|
84744
84856
|
const denied = permissionDeniedError(store.path, "update_task", project);
|
|
84745
84857
|
if (denied) throw new BridgeError(403, denied);
|
|
84746
84858
|
const current2 = readTasks(store.path, project);
|
|
84747
|
-
if (!current2.ok ||
|
|
84859
|
+
if (!current2.ok || path157.resolve(current2.data.path) !== path157.join(path157.resolve(store.path), project, "tasks.md")) throw new BridgeError(404, "Project is not in that task store.");
|
|
84748
84860
|
if (taskWriterSafety(store.path).activation !== "owner-acknowledged") throw new BridgeError(409, "Task metadata is not enabled.");
|
|
84749
84861
|
return store;
|
|
84750
84862
|
}
|
|
@@ -84763,7 +84875,7 @@ async function launchTaskRoute(base2, server, input2) {
|
|
|
84763
84875
|
const cwd = configured ? await realpath26(configured).catch(() => void 0) : void 0;
|
|
84764
84876
|
if (!cwd || !(await stat37(cwd)).isDirectory()) throw new BridgeError(409, "This task project has no configured checkout on this computer.");
|
|
84765
84877
|
const currentStore = writableTaskProject(base2, data.storeId, data.project);
|
|
84766
|
-
if (
|
|
84878
|
+
if (path157.resolve(currentStore.path) !== path157.resolve(store.path)) throw new BridgeError(409, "Task store changed; refresh before starting.");
|
|
84767
84879
|
const reserved = reserveTaskLaunch(store.path, data.project, data.stableId, data.expectedRevision, getMachineName(), base2);
|
|
84768
84880
|
if (!reserved.ok) throw new BridgeError(409, reserved.error, { code: "task-launch-conflict" });
|
|
84769
84881
|
const task2 = reserved.data;
|
|
@@ -84881,7 +84993,7 @@ var init_owner_inbox_view = __esm({
|
|
|
84881
84993
|
});
|
|
84882
84994
|
|
|
84883
84995
|
// src/bridge/code-note.ts
|
|
84884
|
-
import * as
|
|
84996
|
+
import * as path158 from "node:path";
|
|
84885
84997
|
async function saveCodeNote(store, input2, deliver) {
|
|
84886
84998
|
const note = codeNoteSchema.parse(input2);
|
|
84887
84999
|
if (note.target && !deliver) throw new BridgeError(409, "Enable conductor to send code notes to an agent.");
|
|
@@ -84929,7 +85041,7 @@ var init_code_note = __esm({
|
|
|
84929
85041
|
// phone's spelling, accepted until 0.3.1.
|
|
84930
85042
|
name: external_exports.string().min(1).max(4600).optional(),
|
|
84931
85043
|
symbol: external_exports.string().min(1).max(4600).optional(),
|
|
84932
|
-
file: external_exports.string().min(1).max(4096).refine((file5) => !
|
|
85044
|
+
file: external_exports.string().min(1).max(4096).refine((file5) => !path158.isAbsolute(file5) && !file5.includes("\0") && !file5.split(/[\\/]/).includes("..")),
|
|
84933
85045
|
line: external_exports.number().int().positive(),
|
|
84934
85046
|
text: external_exports.string().trim().min(1).max(4500).refine((text7) => !/[\x00-\x08\x0b-\x1f\x7f]/.test(text7)),
|
|
84935
85047
|
target: external_exports.union([external_exports.object({ session: sessionId }).strict(), external_exports.object({ harness: external_exports.enum(DISPATCH_HARNESSES) }).strict()]).optional()
|
|
@@ -84944,7 +85056,7 @@ var init_code_note = __esm({
|
|
|
84944
85056
|
|
|
84945
85057
|
// src/core/project-registry.ts
|
|
84946
85058
|
import * as fs56 from "fs";
|
|
84947
|
-
import * as
|
|
85059
|
+
import * as path159 from "path";
|
|
84948
85060
|
function titleCase(text7) {
|
|
84949
85061
|
return text7.split(/[\s_-]+/).filter(Boolean).map((token2) => token2.slice(0, 1).toUpperCase() + token2.slice(1)).join(" ");
|
|
84950
85062
|
}
|
|
@@ -85016,7 +85128,7 @@ function scoreTopicsFromTerms(domain2, terms, docsText) {
|
|
|
85016
85128
|
return topics;
|
|
85017
85129
|
}
|
|
85018
85130
|
function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
|
|
85019
|
-
const resolvedRoot =
|
|
85131
|
+
const resolvedRoot = path159.resolve(repoRoot);
|
|
85020
85132
|
if (!fs56.existsSync(resolvedRoot)) return null;
|
|
85021
85133
|
const signal = {
|
|
85022
85134
|
domainScores: { software: 0, music: 0, game: 0, research: 0, writing: 0, creative: 0, other: 0 },
|
|
@@ -85027,7 +85139,7 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
|
|
|
85027
85139
|
usefulSignals: 0
|
|
85028
85140
|
};
|
|
85029
85141
|
const skipDirs = /* @__PURE__ */ new Set([".git", ".phren", "node_modules", "dist", "build", "coverage", ".next", ".turbo", "target"]);
|
|
85030
|
-
const packageJsonPath =
|
|
85142
|
+
const packageJsonPath = path159.join(resolvedRoot, "package.json");
|
|
85031
85143
|
if (fs56.existsSync(packageJsonPath)) {
|
|
85032
85144
|
signal.usefulSignals++;
|
|
85033
85145
|
addDomainScores(signal.domainScores, DOMAIN_CONFIG_HINTS["package.json"]);
|
|
@@ -85057,33 +85169,33 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
|
|
|
85057
85169
|
debugLog(`inferInitScaffoldFromRepo package.json parse failed: ${errorMessage(err)}`);
|
|
85058
85170
|
}
|
|
85059
85171
|
}
|
|
85060
|
-
const topLevelConfigs = Object.keys(DOMAIN_CONFIG_HINTS).filter((fileName) => fs56.existsSync(
|
|
85172
|
+
const topLevelConfigs = Object.keys(DOMAIN_CONFIG_HINTS).filter((fileName) => fs56.existsSync(path159.join(resolvedRoot, fileName)));
|
|
85061
85173
|
for (const configName of topLevelConfigs) {
|
|
85062
85174
|
signal.usefulSignals++;
|
|
85063
85175
|
const configScore = DOMAIN_CONFIG_HINTS[configName];
|
|
85064
85176
|
if (configScore) addDomainScores(signal.domainScores, configScore);
|
|
85065
85177
|
}
|
|
85066
85178
|
const readmeCandidates = [
|
|
85067
|
-
|
|
85068
|
-
|
|
85179
|
+
path159.join(resolvedRoot, "README.md"),
|
|
85180
|
+
path159.join(resolvedRoot, "readme.md")
|
|
85069
85181
|
];
|
|
85070
85182
|
for (const readmePath of readmeCandidates) {
|
|
85071
85183
|
if (!fs56.existsSync(readmePath)) continue;
|
|
85072
85184
|
const content = maybeReadUtf8(readmePath);
|
|
85073
85185
|
if (!content) continue;
|
|
85074
85186
|
signal.usefulSignals++;
|
|
85075
|
-
signal.referenceHints.push(
|
|
85187
|
+
signal.referenceHints.push(path159.relative(resolvedRoot, readmePath));
|
|
85076
85188
|
addTermCount(signal.terms, content, 2);
|
|
85077
85189
|
signal.docsText += ` ${content.toLowerCase()}`;
|
|
85078
85190
|
break;
|
|
85079
85191
|
}
|
|
85080
|
-
const docsDir =
|
|
85192
|
+
const docsDir = path159.join(resolvedRoot, "docs");
|
|
85081
85193
|
if (fs56.existsSync(docsDir) && fs56.statSync(docsDir).isDirectory()) {
|
|
85082
85194
|
signal.referenceHints.push("docs/");
|
|
85083
85195
|
for (const entry2 of fs56.readdirSync(docsDir, { withFileTypes: true })) {
|
|
85084
85196
|
if (!entry2.isFile()) continue;
|
|
85085
85197
|
if (!/\.(md|txt|rst)$/i.test(entry2.name)) continue;
|
|
85086
|
-
const docsContent = maybeReadUtf8(
|
|
85198
|
+
const docsContent = maybeReadUtf8(path159.join(docsDir, entry2.name));
|
|
85087
85199
|
if (!docsContent) continue;
|
|
85088
85200
|
signal.usefulSignals++;
|
|
85089
85201
|
addTermCount(signal.terms, docsContent, 1);
|
|
@@ -85091,7 +85203,7 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
|
|
|
85091
85203
|
}
|
|
85092
85204
|
}
|
|
85093
85205
|
for (const folderName of ["reference", "specs", "design", "architecture", "src", "packages", "apps"]) {
|
|
85094
|
-
const fullPath =
|
|
85206
|
+
const fullPath = path159.join(resolvedRoot, folderName);
|
|
85095
85207
|
if (fs56.existsSync(fullPath)) {
|
|
85096
85208
|
signal.referenceHints.push(`${folderName}/`);
|
|
85097
85209
|
}
|
|
@@ -85102,14 +85214,14 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
|
|
|
85102
85214
|
if (scannedFiles >= maxFiles) return;
|
|
85103
85215
|
for (const entry2 of fs56.readdirSync(dir, { withFileTypes: true })) {
|
|
85104
85216
|
if (scannedFiles >= maxFiles) return;
|
|
85105
|
-
const fullPath =
|
|
85217
|
+
const fullPath = path159.join(dir, entry2.name);
|
|
85106
85218
|
if (entry2.isDirectory()) {
|
|
85107
85219
|
if (skipDirs.has(entry2.name)) continue;
|
|
85108
85220
|
walk(fullPath);
|
|
85109
85221
|
continue;
|
|
85110
85222
|
}
|
|
85111
85223
|
scannedFiles++;
|
|
85112
|
-
const ext =
|
|
85224
|
+
const ext = path159.extname(entry2.name).toLowerCase();
|
|
85113
85225
|
if (!ext) continue;
|
|
85114
85226
|
const extScore = EXTENSION_DOMAIN_HINTS[ext];
|
|
85115
85227
|
if (extScore) {
|
|
@@ -85283,7 +85395,7 @@ function findExistingProjectForSource(phrenPath, sourceRoot, derivedName) {
|
|
|
85283
85395
|
return null;
|
|
85284
85396
|
}
|
|
85285
85397
|
};
|
|
85286
|
-
const resolvedSource =
|
|
85398
|
+
const resolvedSource = path159.resolve(sourceRoot);
|
|
85287
85399
|
for (const project of candidates) {
|
|
85288
85400
|
if (sourceOf(project) === resolvedSource) return project;
|
|
85289
85401
|
}
|
|
@@ -85297,7 +85409,7 @@ function findExistingProjectForSource(phrenPath, sourceRoot, derivedName) {
|
|
|
85297
85409
|
function bootstrapFromExisting(phrenPath, projectPath2, opts = {}) {
|
|
85298
85410
|
const profile = typeof opts === "string" ? opts : opts.profile;
|
|
85299
85411
|
const profilePhrenPath = typeof opts === "string" ? phrenPath : opts.profilePhrenPath ?? phrenPath;
|
|
85300
|
-
const resolvedPath =
|
|
85412
|
+
const resolvedPath = path159.resolve(projectPath2);
|
|
85301
85413
|
if (!fs56.existsSync(resolvedPath)) {
|
|
85302
85414
|
throw new Error(`Path does not exist: ${resolvedPath}`);
|
|
85303
85415
|
}
|
|
@@ -85308,17 +85420,17 @@ function bootstrapFromExisting(phrenPath, projectPath2, opts = {}) {
|
|
|
85308
85420
|
if (worktreeRepoRoot) {
|
|
85309
85421
|
debugLog(`bootstrapFromExisting: ${resolvedPath} is a ${worktree.reason}; attributing to ${worktreeRepoRoot}`);
|
|
85310
85422
|
}
|
|
85311
|
-
const sourceRoot = isProjectLocal ?
|
|
85423
|
+
const sourceRoot = isProjectLocal ? path159.resolve(manifest.workspaceRoot || resolvedPath) : worktreeRepoRoot ?? resolvedPath;
|
|
85312
85424
|
if (isProjectLocal) {
|
|
85313
|
-
const matchesWorkspace = resolvedPath === sourceRoot || resolvedPath.startsWith(sourceRoot +
|
|
85425
|
+
const matchesWorkspace = resolvedPath === sourceRoot || resolvedPath.startsWith(sourceRoot + path159.sep);
|
|
85314
85426
|
if (!matchesWorkspace) {
|
|
85315
85427
|
throw new Error(`Project-local phren can only enroll the owning workspace: ${sourceRoot}`);
|
|
85316
85428
|
}
|
|
85317
85429
|
}
|
|
85318
85430
|
let claudeMdPath = null;
|
|
85319
85431
|
const candidates = [
|
|
85320
|
-
|
|
85321
|
-
|
|
85432
|
+
path159.join(sourceRoot, "AGENTS.md"),
|
|
85433
|
+
path159.join(sourceRoot, ".claude", "CLAUDE.md")
|
|
85322
85434
|
];
|
|
85323
85435
|
for (const c of candidates) {
|
|
85324
85436
|
if (fs56.existsSync(c)) {
|
|
@@ -85342,12 +85454,12 @@ function bootstrapFromExisting(phrenPath, projectPath2, opts = {}) {
|
|
|
85342
85454
|
`Project "${existingProject}" already exists with different casing. Refusing to bootstrap "${projectName2}" because it would split the same project on case-sensitive filesystems.`
|
|
85343
85455
|
);
|
|
85344
85456
|
}
|
|
85345
|
-
const projDir =
|
|
85457
|
+
const projDir = path159.join(phrenPath, projectName2);
|
|
85346
85458
|
fs56.mkdirSync(projDir, { recursive: true });
|
|
85347
85459
|
const inferredScaffold = inferInitScaffoldFromRepo(sourceRoot);
|
|
85348
85460
|
const existingConfig = readProjectConfig(phrenPath, projectName2);
|
|
85349
85461
|
const ownership = typeof opts === "string" ? parseProjectOwnershipMode(existingConfig.ownership) ?? getProjectOwnershipDefault(phrenPath) : opts.ownership ?? parseProjectOwnershipMode(existingConfig.ownership) ?? getProjectOwnershipDefault(phrenPath);
|
|
85350
|
-
const claudePath =
|
|
85462
|
+
const claudePath = path159.join(projDir, "AGENTS.md");
|
|
85351
85463
|
if (ownership !== "repo-managed") {
|
|
85352
85464
|
if (claudeContent) {
|
|
85353
85465
|
if (!fs56.existsSync(claudePath)) {
|
|
@@ -85382,7 +85494,7 @@ function bootstrapFromExisting(phrenPath, projectPath2, opts = {}) {
|
|
|
85382
85494
|
}
|
|
85383
85495
|
}
|
|
85384
85496
|
const sourceInfo = claudeMdPath ? `**Source AGENTS.md:** ${claudeMdPath}` : `**Source:** ${sourceRoot}`;
|
|
85385
|
-
const summaryPath =
|
|
85497
|
+
const summaryPath = path159.join(projDir, "summary.md");
|
|
85386
85498
|
if (!fs56.existsSync(summaryPath)) {
|
|
85387
85499
|
atomicWriteText(
|
|
85388
85500
|
summaryPath,
|
|
@@ -85395,18 +85507,18 @@ ${summaryLines.length > 1 ? summaryLines.slice(1).join("\n") : ""}
|
|
|
85395
85507
|
`
|
|
85396
85508
|
);
|
|
85397
85509
|
}
|
|
85398
|
-
if (!fs56.existsSync(
|
|
85510
|
+
if (!fs56.existsSync(path159.join(projDir, FINDINGS_FILENAME))) {
|
|
85399
85511
|
atomicWriteText(
|
|
85400
|
-
|
|
85512
|
+
path159.join(projDir, FINDINGS_FILENAME),
|
|
85401
85513
|
`# ${projectName2} FINDINGS
|
|
85402
85514
|
|
|
85403
85515
|
<!-- Bootstrapped from ${sourceRoot} -->
|
|
85404
85516
|
`
|
|
85405
85517
|
);
|
|
85406
85518
|
}
|
|
85407
|
-
if (moduleEnabled(phrenPath, "tasks") && !fs56.existsSync(
|
|
85519
|
+
if (moduleEnabled(phrenPath, "tasks") && !fs56.existsSync(path159.join(projDir, TASKS_FILENAME))) {
|
|
85408
85520
|
atomicWriteText(
|
|
85409
|
-
|
|
85521
|
+
path159.join(projDir, TASKS_FILENAME),
|
|
85410
85522
|
`# ${projectName2} tasks
|
|
85411
85523
|
|
|
85412
85524
|
## Active
|
|
@@ -85417,11 +85529,11 @@ ${summaryLines.length > 1 ? summaryLines.slice(1).join("\n") : ""}
|
|
|
85417
85529
|
`
|
|
85418
85530
|
);
|
|
85419
85531
|
}
|
|
85420
|
-
if (!fs56.existsSync(
|
|
85532
|
+
if (!fs56.existsSync(path159.join(projDir, "topic-config.json"))) {
|
|
85421
85533
|
const inferredDomain = normalizeBuiltinTopicDomain(inferredScaffold?.domain ?? "software");
|
|
85422
85534
|
const inferredTopics = inferredScaffold?.topics?.length ? inferredScaffold.topics : getBuiltinTopicConfig(inferredDomain);
|
|
85423
85535
|
atomicWriteText(
|
|
85424
|
-
|
|
85536
|
+
path159.join(projDir, "topic-config.json"),
|
|
85425
85537
|
JSON.stringify({ version: 1, domain: inferredDomain, topics: inferredTopics }, null, 2) + "\n"
|
|
85426
85538
|
);
|
|
85427
85539
|
}
|
|
@@ -85588,7 +85700,7 @@ var init_project_registry = __esm({
|
|
|
85588
85700
|
});
|
|
85589
85701
|
|
|
85590
85702
|
// src/core/project.ts
|
|
85591
|
-
import * as
|
|
85703
|
+
import * as path160 from "path";
|
|
85592
85704
|
function addProjectFromPath(phrenPath, targetPath, requestedProfile, ownership, options = {}) {
|
|
85593
85705
|
if (!targetPath) {
|
|
85594
85706
|
return phrenErr("Path is required. Pass the current project directory explicitly to avoid adding the wrong working directory.");
|
|
@@ -85600,10 +85712,10 @@ function addProjectFromPath(phrenPath, targetPath, requestedProfile, ownership,
|
|
|
85600
85712
|
if (!activeProfile.ok) return activeProfile;
|
|
85601
85713
|
const writePhrenPath = options.writeToPath ?? phrenPath;
|
|
85602
85714
|
const manifest = readRootManifest(phrenPath);
|
|
85603
|
-
const resolvedPath =
|
|
85715
|
+
const resolvedPath = path160.resolve(targetPath);
|
|
85604
85716
|
if (manifest?.installMode === "project-local") {
|
|
85605
|
-
const workspaceRoot =
|
|
85606
|
-
const matchesWorkspace = resolvedPath === workspaceRoot || resolvedPath.startsWith(workspaceRoot +
|
|
85717
|
+
const workspaceRoot = path160.resolve(manifest.workspaceRoot || "");
|
|
85718
|
+
const matchesWorkspace = resolvedPath === workspaceRoot || resolvedPath.startsWith(workspaceRoot + path160.sep);
|
|
85607
85719
|
if (!matchesWorkspace) {
|
|
85608
85720
|
return phrenErr(`Project-local phren can only add the owning workspace: ${workspaceRoot}`);
|
|
85609
85721
|
}
|
|
@@ -85622,9 +85734,9 @@ function addProjectFromPath(phrenPath, targetPath, requestedProfile, ownership,
|
|
|
85622
85734
|
ownership: added.ownership,
|
|
85623
85735
|
files: {
|
|
85624
85736
|
claude: added.claudePath,
|
|
85625
|
-
summary:
|
|
85626
|
-
findings:
|
|
85627
|
-
task:
|
|
85737
|
+
summary: path160.join(writePhrenPath, added.project, "summary.md"),
|
|
85738
|
+
findings: path160.join(writePhrenPath, added.project, FINDINGS_FILENAME),
|
|
85739
|
+
task: path160.join(writePhrenPath, added.project, TASKS_FILENAME)
|
|
85628
85740
|
}
|
|
85629
85741
|
});
|
|
85630
85742
|
}
|
|
@@ -85712,16 +85824,16 @@ var init_session_git = __esm({
|
|
|
85712
85824
|
import { execFile as execFile36 } from "node:child_process";
|
|
85713
85825
|
import { promisify as promisify33 } from "node:util";
|
|
85714
85826
|
import { realpathSync as realpathSync8 } from "node:fs";
|
|
85715
|
-
import { readdir as readdir26, readFile as
|
|
85827
|
+
import { readdir as readdir26, readFile as readFile60, stat as stat38, mkdir as mkdir38 } from "node:fs/promises";
|
|
85716
85828
|
import { homedir as homedir20 } from "node:os";
|
|
85717
|
-
import
|
|
85829
|
+
import path161 from "node:path";
|
|
85718
85830
|
function repoName(url2) {
|
|
85719
85831
|
const last = url2.replace(/\/+$/, "").split(/[/:]/).pop() ?? "";
|
|
85720
85832
|
return last.replace(/\.git$/i, "");
|
|
85721
85833
|
}
|
|
85722
85834
|
async function isRepository2(directory) {
|
|
85723
85835
|
try {
|
|
85724
|
-
await stat38(
|
|
85836
|
+
await stat38(path161.join(directory, ".git"));
|
|
85725
85837
|
return true;
|
|
85726
85838
|
} catch {
|
|
85727
85839
|
return false;
|
|
@@ -85741,7 +85853,7 @@ async function registeredSources(env) {
|
|
|
85741
85853
|
const source = readProjectConfig(store, project).sourcePath;
|
|
85742
85854
|
if (typeof source === "string" && source) {
|
|
85743
85855
|
try {
|
|
85744
|
-
paths.add(realpathSync8.native(
|
|
85856
|
+
paths.add(realpathSync8.native(path161.resolve(source)));
|
|
85745
85857
|
} catch {
|
|
85746
85858
|
}
|
|
85747
85859
|
}
|
|
@@ -85753,7 +85865,7 @@ async function candidateRepos(activity, env = process.env) {
|
|
|
85753
85865
|
const found = [];
|
|
85754
85866
|
const seen = /* @__PURE__ */ new Set();
|
|
85755
85867
|
const offer = async (directory, source, lastSeen) => {
|
|
85756
|
-
let dir =
|
|
85868
|
+
let dir = path161.resolve(directory);
|
|
85757
85869
|
try {
|
|
85758
85870
|
if (!(await stat38(dir)).isDirectory()) return;
|
|
85759
85871
|
dir = realpathSync8.native(dir);
|
|
@@ -85768,7 +85880,7 @@ async function candidateRepos(activity, env = process.env) {
|
|
|
85768
85880
|
const toplevel = async (directory) => {
|
|
85769
85881
|
let existing = directory;
|
|
85770
85882
|
while (!await stat38(existing).catch(() => void 0)) {
|
|
85771
|
-
const parent =
|
|
85883
|
+
const parent = path161.dirname(existing);
|
|
85772
85884
|
if (parent === existing) return void 0;
|
|
85773
85885
|
existing = parent;
|
|
85774
85886
|
}
|
|
@@ -85788,7 +85900,7 @@ async function candidateRepos(activity, env = process.env) {
|
|
|
85788
85900
|
}
|
|
85789
85901
|
return root;
|
|
85790
85902
|
};
|
|
85791
|
-
const activityDirectory = (event) => typeof event.directory === "string" &&
|
|
85903
|
+
const activityDirectory = (event) => typeof event.directory === "string" && path161.isAbsolute(event.directory) ? event.directory : void 0;
|
|
85792
85904
|
const pending4 = [...new Set(activity.map(activityDirectory).filter((d) => !!d))];
|
|
85793
85905
|
await Promise.all(Array.from({ length: Math.min(8, pending4.length) }, async () => {
|
|
85794
85906
|
for (let directory = pending4.shift(); directory !== void 0; directory = pending4.shift()) await rootOf(directory);
|
|
@@ -85800,20 +85912,20 @@ async function candidateRepos(activity, env = process.env) {
|
|
|
85800
85912
|
if (root) await offer(root, "activity", typeof event.at === "string" ? event.at : void 0);
|
|
85801
85913
|
}
|
|
85802
85914
|
try {
|
|
85803
|
-
const session = JSON.parse(await
|
|
85915
|
+
const session = JSON.parse(await readFile60(path161.join(herdrRoot(), "session.json"), "utf8"));
|
|
85804
85916
|
for (const match of JSON.stringify(session).matchAll(/"cwd":\s*"((?:\\.|[^"\\])*)"/g)) {
|
|
85805
85917
|
const directory = JSON.parse(`"${match[1]}"`);
|
|
85806
|
-
if (!
|
|
85918
|
+
if (!path161.isAbsolute(directory)) continue;
|
|
85807
85919
|
const root = await rootOf(directory);
|
|
85808
85920
|
if (root) await offer(root, "herdr");
|
|
85809
85921
|
}
|
|
85810
85922
|
} catch {
|
|
85811
85923
|
}
|
|
85812
85924
|
const home = homedir20();
|
|
85813
|
-
for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.map((r7) =>
|
|
85925
|
+
for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.map((r7) => path161.join(home, r7))]) {
|
|
85814
85926
|
let children = [];
|
|
85815
85927
|
try {
|
|
85816
|
-
children = (await readdir26(root, { withFileTypes: true })).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) =>
|
|
85928
|
+
children = (await readdir26(root, { withFileTypes: true })).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => path161.join(root, e.name));
|
|
85817
85929
|
} catch {
|
|
85818
85930
|
continue;
|
|
85819
85931
|
}
|
|
@@ -85823,13 +85935,13 @@ async function candidateRepos(activity, env = process.env) {
|
|
|
85823
85935
|
}
|
|
85824
85936
|
async function cloneRoot(env) {
|
|
85825
85937
|
const home = homedir20();
|
|
85826
|
-
for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.filter((r7) => r7 !== "Sites").map((r7) =>
|
|
85938
|
+
for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.filter((r7) => r7 !== "Sites").map((r7) => path161.join(home, r7))]) {
|
|
85827
85939
|
try {
|
|
85828
85940
|
if ((await stat38(root)).isDirectory()) return root;
|
|
85829
85941
|
} catch {
|
|
85830
85942
|
}
|
|
85831
85943
|
}
|
|
85832
|
-
const fallback2 =
|
|
85944
|
+
const fallback2 = path161.join(home, "Projects");
|
|
85833
85945
|
await mkdir38(fallback2, { recursive: true });
|
|
85834
85946
|
return fallback2;
|
|
85835
85947
|
}
|
|
@@ -85855,7 +85967,7 @@ async function enrollProject(input2, env = process.env) {
|
|
|
85855
85967
|
const baseStore = phrenStoreRoot(env);
|
|
85856
85968
|
const store = await resolveCodeStore(baseStore, input2.store, true);
|
|
85857
85969
|
try {
|
|
85858
|
-
if (!(await stat38(
|
|
85970
|
+
if (!(await stat38(path161.join(baseStore, ".config"))).isDirectory()) throw new Error();
|
|
85859
85971
|
} catch {
|
|
85860
85972
|
throw new BridgeError(409, "phren is not set up on this computer. Run phren init there.");
|
|
85861
85973
|
}
|
|
@@ -85866,7 +85978,7 @@ async function enrollProject(input2, env = process.env) {
|
|
|
85866
85978
|
if (url2.length > 512 || !CLONE_URL.test(url2)) throw new BridgeError(400, "Enter a GitHub repository URL (https://github.com/owner/repo).");
|
|
85867
85979
|
const name2 = repoName(url2);
|
|
85868
85980
|
if (!name2 || name2 === "." || name2 === "..") throw new BridgeError(400, "That URL has no repository name.");
|
|
85869
|
-
directory =
|
|
85981
|
+
directory = path161.join(await cloneRoot(env), name2);
|
|
85870
85982
|
try {
|
|
85871
85983
|
await stat38(directory);
|
|
85872
85984
|
throw new BridgeError(409, `${directory} already exists on this computer. Add that folder instead.`);
|
|
@@ -85883,7 +85995,7 @@ async function enrollProject(input2, env = process.env) {
|
|
|
85883
85995
|
cloned = true;
|
|
85884
85996
|
} else if (typeof input2.directory === "string" && input2.directory) {
|
|
85885
85997
|
const raw = input2.directory;
|
|
85886
|
-
if (raw.length > 4096 || raw.includes("\0") || !
|
|
85998
|
+
if (raw.length > 4096 || raw.includes("\0") || !path161.isAbsolute(raw)) throw new BridgeError(400, "Enter the full folder path on this computer.");
|
|
85887
85999
|
try {
|
|
85888
86000
|
directory = realpathSync8.native(raw);
|
|
85889
86001
|
if (!(await stat38(directory)).isDirectory()) throw new Error();
|
|
@@ -85924,28 +86036,28 @@ var init_enroll = __esm({
|
|
|
85924
86036
|
|
|
85925
86037
|
// src/bridge/files.ts
|
|
85926
86038
|
import { constants as constants7 } from "node:fs";
|
|
85927
|
-
import { lstat as
|
|
85928
|
-
import
|
|
86039
|
+
import { lstat as lstat41, open as open30, readdir as readdir27, realpath as realpath27 } from "node:fs/promises";
|
|
86040
|
+
import path162 from "node:path";
|
|
85929
86041
|
async function browseFiles(root, relative6) {
|
|
85930
|
-
if (relative6.length > 4096 || relative6.includes("\0") || relative6.includes("\\") ||
|
|
86042
|
+
if (relative6.length > 4096 || relative6.includes("\0") || relative6.includes("\\") || path162.isAbsolute(relative6) || relative6.split("/").some((part) => part === ".." || isGitDirName(part))) {
|
|
85931
86043
|
throw new BridgeError(400, "Invalid repository path.");
|
|
85932
86044
|
}
|
|
85933
86045
|
const base2 = await realpath27(root);
|
|
85934
86046
|
let file5 = base2;
|
|
85935
86047
|
for (const part of relative6.split("/").filter((part2) => part2 && part2 !== ".")) {
|
|
85936
|
-
file5 =
|
|
85937
|
-
if ((await
|
|
86048
|
+
file5 = path162.join(file5, part);
|
|
86049
|
+
if ((await lstat41(file5)).isSymbolicLink()) throw new BridgeError(403, "Symbolic links cannot be browsed.");
|
|
85938
86050
|
}
|
|
85939
86051
|
const resolved = await realpath27(file5);
|
|
85940
|
-
if (resolved !== base2 && !resolved.startsWith(base2 +
|
|
85941
|
-
const metadata = await
|
|
86052
|
+
if (resolved !== base2 && !resolved.startsWith(base2 + path162.sep)) throw new BridgeError(403, "The path is outside this repository.");
|
|
86053
|
+
const metadata = await lstat41(resolved);
|
|
85942
86054
|
if (metadata.isDirectory()) {
|
|
85943
86055
|
const entries2 = (await readdir27(resolved, { withFileTypes: true })).filter((entry2) => !isGitDirName(entry2.name) && (entry2.isDirectory() || entry2.isFile())).sort((a, b) => Number(b.isDirectory()) - Number(a.isDirectory()) || a.name.localeCompare(b.name));
|
|
85944
86056
|
return {
|
|
85945
86057
|
path: relative6,
|
|
85946
86058
|
kind: "directory",
|
|
85947
86059
|
truncated: entries2.length > 500,
|
|
85948
|
-
entries: entries2.slice(0, 500).map((entry2) => ({ name: entry2.name, path:
|
|
86060
|
+
entries: entries2.slice(0, 500).map((entry2) => ({ name: entry2.name, path: path162.posix.join(relative6, entry2.name), kind: entry2.isDirectory() ? "directory" : "file" }))
|
|
85949
86061
|
};
|
|
85950
86062
|
}
|
|
85951
86063
|
if (!metadata.isFile()) throw new BridgeError(400, "Only regular files can be viewed.");
|
|
@@ -85978,21 +86090,21 @@ var init_files = __esm({
|
|
|
85978
86090
|
});
|
|
85979
86091
|
|
|
85980
86092
|
// src/bridge/file-resolve.ts
|
|
85981
|
-
import { lstat as
|
|
85982
|
-
import
|
|
86093
|
+
import { lstat as lstat42, realpath as realpath28 } from "node:fs/promises";
|
|
86094
|
+
import path163 from "node:path";
|
|
85983
86095
|
function beneath(root, file5) {
|
|
85984
|
-
const relative6 =
|
|
85985
|
-
return relative6 !== ".." && !relative6.startsWith(`..${
|
|
86096
|
+
const relative6 = path163.relative(root, file5);
|
|
86097
|
+
return relative6 !== ".." && !relative6.startsWith(`..${path163.sep}`) && !path163.isAbsolute(relative6);
|
|
85986
86098
|
}
|
|
85987
86099
|
async function resolveFilePath(root, cwd, requested) {
|
|
85988
86100
|
if (process.platform === "win32") requested = requested.replaceAll("\\", "/");
|
|
85989
|
-
if (!requested || requested.length > 4096 || /[\x00-\x1f\x7f\\]/.test(requested) || /^[A-Za-z]:[^/]/.test(requested) || requested.split("/").some(isGitDirName) ||
|
|
86101
|
+
if (!requested || requested.length > 4096 || /[\x00-\x1f\x7f\\]/.test(requested) || /^[A-Za-z]:[^/]/.test(requested) || requested.split("/").some(isGitDirName) || path163.win32.isAbsolute(requested) && !path163.isAbsolute(requested)) {
|
|
85990
86102
|
throw new BridgeError(400, "Invalid file path.");
|
|
85991
86103
|
}
|
|
85992
86104
|
const base2 = await realpath28(root), folder = await realpath28(cwd);
|
|
85993
86105
|
if (!beneath(base2, folder)) throw new BridgeError(403, "This folder is outside the repository.");
|
|
85994
|
-
const roots = [base2,
|
|
85995
|
-
const absolute =
|
|
86106
|
+
const roots = [base2, path163.resolve(root), path163.resolve(cwd, path163.relative(folder, base2))].map((value2) => value2.split(path163.sep).join("/"));
|
|
86107
|
+
const absolute = path163.isAbsolute(requested);
|
|
85996
86108
|
const alias = roots.find((candidate) => requested === candidate || requested.startsWith(candidate + "/"));
|
|
85997
86109
|
if (absolute && !alias) throw new BridgeError(403, "This file is outside the repository.");
|
|
85998
86110
|
const candidates = absolute ? [{ start: base2, name: requested.slice(alias.length) }] : [.../* @__PURE__ */ new Set([folder, base2])].map((start) => ({ start, name: requested }));
|
|
@@ -86000,11 +86112,11 @@ async function resolveFilePath(root, cwd, requested) {
|
|
|
86000
86112
|
try {
|
|
86001
86113
|
let file5 = candidate.start;
|
|
86002
86114
|
for (const part of candidate.name.split("/").filter((part2) => part2 && part2 !== ".")) {
|
|
86003
|
-
file5 =
|
|
86115
|
+
file5 = path163.resolve(file5, part);
|
|
86004
86116
|
if (!beneath(base2, file5)) throw new BridgeError(403, "This file is outside the repository.");
|
|
86005
|
-
if ((await
|
|
86117
|
+
if ((await lstat42(file5)).isSymbolicLink()) throw new BridgeError(403, "Symbolic links cannot be opened.");
|
|
86006
86118
|
}
|
|
86007
|
-
const relative6 =
|
|
86119
|
+
const relative6 = path163.relative(base2, file5).split(path163.sep).join("/");
|
|
86008
86120
|
const metadata = await readFileRange(base2, relative6, 0, 0);
|
|
86009
86121
|
return { path: relative6, size: metadata.total, contentType: metadata.contentType, version: metadata.version };
|
|
86010
86122
|
} catch (error62) {
|
|
@@ -86027,7 +86139,7 @@ var init_file_resolve = __esm({
|
|
|
86027
86139
|
// src/content/citation-freshness.ts
|
|
86028
86140
|
import { execFileSync as execFileSync9 } from "node:child_process";
|
|
86029
86141
|
import { readFileSync as readFileSync63, realpathSync as realpathSync9, renameSync as renameSync15, statSync as statSync31, unlinkSync as unlinkSync10, writeFileSync as writeFileSync30 } from "node:fs";
|
|
86030
|
-
import
|
|
86142
|
+
import path164 from "node:path";
|
|
86031
86143
|
import { randomUUID as randomUUID36 } from "node:crypto";
|
|
86032
86144
|
function git9(root, timeoutMs, ...args) {
|
|
86033
86145
|
if (timeoutMs <= 0) return "";
|
|
@@ -86042,13 +86154,13 @@ function git9(root, timeoutMs, ...args) {
|
|
|
86042
86154
|
}
|
|
86043
86155
|
}
|
|
86044
86156
|
function checkoutRoot2(repo2, deadline) {
|
|
86045
|
-
if (!repo2 || !
|
|
86157
|
+
if (!repo2 || !path164.isAbsolute(repo2)) return;
|
|
86046
86158
|
try {
|
|
86047
86159
|
const root = realpathSync9(repo2);
|
|
86048
86160
|
const toplevel = git9(root, Math.min(GIT_TIMEOUT_MS, deadline - Date.now()), "rev-parse", "--show-toplevel");
|
|
86049
|
-
if (!toplevel || !
|
|
86161
|
+
if (!toplevel || !path164.isAbsolute(toplevel)) return;
|
|
86050
86162
|
const canonical3 = (value2) => {
|
|
86051
|
-
const resolved =
|
|
86163
|
+
const resolved = path164.resolve((realpathSync9.native ?? realpathSync9)(value2));
|
|
86052
86164
|
return process.platform === "win32" ? resolved.toLowerCase() : resolved;
|
|
86053
86165
|
};
|
|
86054
86166
|
return canonical3(toplevel) === canonical3(root) ? root : void 0;
|
|
@@ -86085,16 +86197,16 @@ function repository5(citation, opts, entries2, deadline) {
|
|
|
86085
86197
|
}
|
|
86086
86198
|
function target(citation, repo2) {
|
|
86087
86199
|
if (!citation.file || !citation.commit || !/^[a-f0-9]{7,64}$/i.test(citation.commit)) return;
|
|
86088
|
-
let file5 = citation.file.split(
|
|
86200
|
+
let file5 = citation.file.split(path164.sep).join("/");
|
|
86089
86201
|
if (file5.includes("\\") || file5.includes("\0") || file5.split("/").includes("..")) return;
|
|
86090
86202
|
if (!repo2 || !validDomain(repo2.domain) || !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repo2.path) || repo2.path.split("/").some((part) => part === "." || part === "..")) return;
|
|
86091
|
-
if (
|
|
86092
|
-
if (!repo2.root || !
|
|
86093
|
-
const absolute = citation.repo &&
|
|
86094
|
-
file5 =
|
|
86095
|
-
if (file5 === ".." || file5.startsWith("../") ||
|
|
86203
|
+
if (path164.isAbsolute(file5)) {
|
|
86204
|
+
if (!repo2.root || !path164.isAbsolute(repo2.root)) return;
|
|
86205
|
+
const absolute = citation.repo && path164.isAbsolute(citation.repo) ? path164.resolve(repo2.root, path164.relative(citation.repo, file5)) : file5;
|
|
86206
|
+
file5 = path164.relative(repo2.root, absolute).split(path164.sep).join("/");
|
|
86207
|
+
if (file5 === ".." || file5.startsWith("../") || path164.isAbsolute(file5)) return;
|
|
86096
86208
|
}
|
|
86097
|
-
file5 =
|
|
86209
|
+
file5 = path164.posix.normalize(file5);
|
|
86098
86210
|
if (!file5 || file5 === "." || file5.startsWith("../")) return;
|
|
86099
86211
|
const result = { domain: repo2.domain, repo: repo2.path, commit: citation.commit, file: file5 };
|
|
86100
86212
|
return { ...result, key: JSON.stringify([result.domain, result.repo, result.commit, file5]) };
|
|
@@ -86449,10 +86561,10 @@ var init_types2 = __esm({
|
|
|
86449
86561
|
|
|
86450
86562
|
// src/tools/extract-facts.ts
|
|
86451
86563
|
import * as fs57 from "fs";
|
|
86452
|
-
import * as
|
|
86564
|
+
import * as path165 from "path";
|
|
86453
86565
|
function preferencesPath(phrenPath, project) {
|
|
86454
86566
|
const dir = storeAwareProjectPath(phrenPath, project);
|
|
86455
|
-
return dir ?
|
|
86567
|
+
return dir ? path165.join(dir, "preferences.json") : null;
|
|
86456
86568
|
}
|
|
86457
86569
|
function readExtractedFacts(phrenPath, project) {
|
|
86458
86570
|
const p = preferencesPath(phrenPath, project);
|
|
@@ -86700,10 +86812,10 @@ __export(journal_exports, {
|
|
|
86700
86812
|
readTeamJournalEntries: () => readTeamJournalEntries
|
|
86701
86813
|
});
|
|
86702
86814
|
import * as fs59 from "fs";
|
|
86703
|
-
import * as
|
|
86815
|
+
import * as path166 from "path";
|
|
86704
86816
|
import * as crypto14 from "crypto";
|
|
86705
86817
|
function journalRoot(phrenPath) {
|
|
86706
|
-
const dir =
|
|
86818
|
+
const dir = path166.join(runtimeDir(phrenPath), "finding-journal");
|
|
86707
86819
|
fs59.mkdirSync(dir, { recursive: true });
|
|
86708
86820
|
return dir;
|
|
86709
86821
|
}
|
|
@@ -86713,20 +86825,20 @@ function sanitizeSessionId(sessionId2) {
|
|
|
86713
86825
|
return safe3 || "session";
|
|
86714
86826
|
}
|
|
86715
86827
|
function journalFileFor(phrenPath, project, sessionId2) {
|
|
86716
|
-
const projectDir =
|
|
86828
|
+
const projectDir = path166.join(journalRoot(phrenPath), project);
|
|
86717
86829
|
fs59.mkdirSync(projectDir, { recursive: true });
|
|
86718
|
-
return
|
|
86830
|
+
return path166.join(projectDir, `${sanitizeSessionId(sessionId2)}.jsonl`);
|
|
86719
86831
|
}
|
|
86720
86832
|
function listJournalFiles(phrenPath, project) {
|
|
86721
86833
|
const root = journalRoot(phrenPath);
|
|
86722
|
-
const projects = project ? [project] : fs59.readdirSync(root).filter((entry2) => fs59.statSync(
|
|
86834
|
+
const projects = project ? [project] : fs59.readdirSync(root).filter((entry2) => fs59.statSync(path166.join(root, entry2)).isDirectory());
|
|
86723
86835
|
const files = [];
|
|
86724
86836
|
for (const projectName2 of projects) {
|
|
86725
|
-
const projectDir =
|
|
86837
|
+
const projectDir = path166.join(root, projectName2);
|
|
86726
86838
|
if (!fs59.existsSync(projectDir)) continue;
|
|
86727
86839
|
for (const entry2 of fs59.readdirSync(projectDir)) {
|
|
86728
86840
|
if (!entry2.endsWith(".jsonl")) continue;
|
|
86729
|
-
files.push(
|
|
86841
|
+
files.push(path166.join(projectDir, entry2));
|
|
86730
86842
|
}
|
|
86731
86843
|
}
|
|
86732
86844
|
return files.sort();
|
|
@@ -86746,7 +86858,7 @@ function appendFindingJournal(phrenPath, project, text7, opts = {}) {
|
|
|
86746
86858
|
};
|
|
86747
86859
|
try {
|
|
86748
86860
|
withFileLock(filePath, () => {
|
|
86749
|
-
fs59.mkdirSync(
|
|
86861
|
+
fs59.mkdirSync(path166.dirname(filePath), { recursive: true });
|
|
86750
86862
|
fs59.appendFileSync(filePath, JSON.stringify(entry2) + "\n");
|
|
86751
86863
|
});
|
|
86752
86864
|
return phrenOk(filePath);
|
|
@@ -86806,9 +86918,9 @@ function compactFindingJournals(phrenPath, project) {
|
|
|
86806
86918
|
function appendTeamJournal(storePath, project, finding3, actor, machine) {
|
|
86807
86919
|
const resolvedActor = actor || getCurrentActor();
|
|
86808
86920
|
const date5 = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
|
|
86809
|
-
const journalDir =
|
|
86921
|
+
const journalDir = path166.join(storePath, project, TEAM_JOURNAL_DIR);
|
|
86810
86922
|
const journalFile2 = `${date5}-${resolvedActor}.md`;
|
|
86811
|
-
const journalPath =
|
|
86923
|
+
const journalPath = path166.join(journalDir, journalFile2);
|
|
86812
86924
|
try {
|
|
86813
86925
|
fs59.mkdirSync(journalDir, { recursive: true });
|
|
86814
86926
|
const sourceComment = buildSourceComment({ source: "human", machine, actor: resolvedActor });
|
|
@@ -86827,13 +86939,13 @@ ${entry2}`);
|
|
|
86827
86939
|
}
|
|
86828
86940
|
}
|
|
86829
86941
|
function readTeamJournalEntries(storePath, project) {
|
|
86830
|
-
const journalDir =
|
|
86942
|
+
const journalDir = path166.join(storePath, project, TEAM_JOURNAL_DIR);
|
|
86831
86943
|
if (!fs59.existsSync(journalDir)) return [];
|
|
86832
86944
|
return fs59.readdirSync(journalDir).filter((f) => f.endsWith(".md")).sort().reverse().map((file5) => {
|
|
86833
86945
|
const match = file5.match(/^(\d{4}-\d{2}-\d{2})-(.+)\.md$/);
|
|
86834
86946
|
const date5 = match?.[1] ?? "unknown";
|
|
86835
86947
|
const actor = match?.[2] ?? "unknown";
|
|
86836
|
-
const content = fs59.readFileSync(
|
|
86948
|
+
const content = fs59.readFileSync(path166.join(journalDir, file5), "utf8");
|
|
86837
86949
|
const entries2 = content.split("\n").filter((line) => line.startsWith("- ")).map((line) => line.slice(2).trim());
|
|
86838
86950
|
return { file: file5, date: date5, actor, entries: entries2 };
|
|
86839
86951
|
});
|
|
@@ -86863,7 +86975,7 @@ function materializeTeamFindings(storePath, project) {
|
|
|
86863
86975
|
}
|
|
86864
86976
|
lines.push("");
|
|
86865
86977
|
}
|
|
86866
|
-
const findingsPath =
|
|
86978
|
+
const findingsPath = path166.join(storePath, project, FINDINGS_FILENAME);
|
|
86867
86979
|
try {
|
|
86868
86980
|
atomicWriteText(findingsPath, lines.join("\n"));
|
|
86869
86981
|
return phrenOk({ entryCount: count2 });
|
|
@@ -86895,10 +87007,10 @@ __export(finding_exports, {
|
|
|
86895
87007
|
syncTeamStores: () => syncTeamStores
|
|
86896
87008
|
});
|
|
86897
87009
|
import * as fs60 from "fs";
|
|
86898
|
-
import * as
|
|
87010
|
+
import * as path167 from "path";
|
|
86899
87011
|
function findJaccardCandidates(phrenPath, project, finding3) {
|
|
86900
87012
|
try {
|
|
86901
|
-
const findingsPath =
|
|
87013
|
+
const findingsPath = path167.join(phrenPath, project, FINDINGS_FILENAME);
|
|
86902
87014
|
if (!fs60.existsSync(findingsPath)) return [];
|
|
86903
87015
|
const content = fs60.readFileSync(findingsPath, "utf8");
|
|
86904
87016
|
const newClean = stripMetadata(finding3).trim();
|
|
@@ -86922,7 +87034,7 @@ function findJaccardCandidates(phrenPath, project, finding3) {
|
|
|
86922
87034
|
}
|
|
86923
87035
|
function findConflictCandidates(phrenPath, project, finding3) {
|
|
86924
87036
|
try {
|
|
86925
|
-
const findingsPath =
|
|
87037
|
+
const findingsPath = path167.join(phrenPath, project, FINDINGS_FILENAME);
|
|
86926
87038
|
if (!fs60.existsSync(findingsPath)) return [];
|
|
86927
87039
|
const content = fs60.readFileSync(findingsPath, "utf8");
|
|
86928
87040
|
const activeBullets = content.split("\n").filter((l) => l.startsWith("- ") && !isInactiveFindingLine(l));
|
|
@@ -86956,7 +87068,7 @@ function withLifecycleMutation(phrenPath, project, writeQueue, updateIndex, hand
|
|
|
86956
87068
|
const result = handler();
|
|
86957
87069
|
if (!result.ok) return mcpResponse({ ok: false, error: result.error });
|
|
86958
87070
|
const resolvedFindingsDir = storeAwareProjectPath(phrenPath, project);
|
|
86959
|
-
if (resolvedFindingsDir) updateIndex(
|
|
87071
|
+
if (resolvedFindingsDir) updateIndex(path167.join(resolvedFindingsDir, FINDINGS_FILENAME));
|
|
86960
87072
|
const mapped = mapResponse(result.data);
|
|
86961
87073
|
return mcpResponse({ ok: true, message: mapped.message, data: mapped.data });
|
|
86962
87074
|
});
|
|
@@ -87013,7 +87125,7 @@ async function handleAddFinding(ctx, params) {
|
|
|
87013
87125
|
const result = appendTeamJournal2(phrenPath, project, taggedFinding, provenance.actor, provenance.machine);
|
|
87014
87126
|
if (result.ok) {
|
|
87015
87127
|
added.push(taggedFinding);
|
|
87016
|
-
journals.add(
|
|
87128
|
+
journals.add(path167.join(phrenPath, project, "journal", result.data));
|
|
87017
87129
|
} else {
|
|
87018
87130
|
rejected.push({ finding: taggedFinding.slice(0, 60), reason: result.error });
|
|
87019
87131
|
}
|
|
@@ -87065,7 +87177,7 @@ async function handleAddFinding(ctx, params) {
|
|
|
87065
87177
|
if (added.length > 0) {
|
|
87066
87178
|
runCustomHooks(phrenPath, "post-finding", { PHREN_PROJECT: project });
|
|
87067
87179
|
incrementSessionFindings(phrenPath, added.length, sessionId2, project);
|
|
87068
|
-
updateFileInIndex(
|
|
87180
|
+
updateFileInIndex(path167.join(phrenPath, project, FINDINGS_FILENAME));
|
|
87069
87181
|
}
|
|
87070
87182
|
const rejectedMsg = rejected.length > 0 ? `, ${rejected.length} rejected` : "";
|
|
87071
87183
|
return mcpResponse({
|
|
@@ -87104,7 +87216,7 @@ async function handleAddFinding(ctx, params) {
|
|
|
87104
87216
|
if (result.data.status === "skipped") {
|
|
87105
87217
|
return mcpResponse({ ok: true, message: result.data.message, data: { project, finding: taggedFinding, status: "skipped" } });
|
|
87106
87218
|
}
|
|
87107
|
-
updateFileInIndex(
|
|
87219
|
+
updateFileInIndex(path167.join(phrenPath, project, FINDINGS_FILENAME));
|
|
87108
87220
|
if (result.data.status === "added" || result.data.status === "created") {
|
|
87109
87221
|
runCustomHooks(phrenPath, "post-finding", { PHREN_PROJECT: project });
|
|
87110
87222
|
incrementSessionFindings(phrenPath, 1, sessionId2, project);
|
|
@@ -87114,7 +87226,7 @@ async function handleAddFinding(ctx, params) {
|
|
|
87114
87226
|
if (activeTask) {
|
|
87115
87227
|
const taskMatch = activeTask.stableId ? `bid:${activeTask.stableId}` : activeTask.line;
|
|
87116
87228
|
try {
|
|
87117
|
-
const findingsPath =
|
|
87229
|
+
const findingsPath = path167.join(phrenPath, project, FINDINGS_FILENAME);
|
|
87118
87230
|
const findingsContent = fs60.readFileSync(findingsPath, "utf8");
|
|
87119
87231
|
const lines = findingsContent.split("\n");
|
|
87120
87232
|
const taggedText = taggedFinding.replace(/^-\s+/, "").trim().slice(0, 60).toLowerCase();
|
|
@@ -87303,7 +87415,7 @@ async function handleEditFinding(ctx, { project: projectInput, old_text, new_tex
|
|
|
87303
87415
|
const result = editFinding(phrenPath, project, old_text, new_text);
|
|
87304
87416
|
if (!result.ok) return mcpResponse({ ok: false, error: result.error });
|
|
87305
87417
|
const resolvedFindingsDir = storeAwareProjectPath(phrenPath, project);
|
|
87306
|
-
if (resolvedFindingsDir) updateFileInIndex(
|
|
87418
|
+
if (resolvedFindingsDir) updateFileInIndex(path167.join(resolvedFindingsDir, FINDINGS_FILENAME));
|
|
87307
87419
|
return mcpResponse({
|
|
87308
87420
|
ok: true,
|
|
87309
87421
|
message: result.data,
|
|
@@ -87330,7 +87442,7 @@ async function handleRemoveFinding(ctx, { project: projectInput, finding: findin
|
|
|
87330
87442
|
const result = removeFindings(phrenPath, project, finding3);
|
|
87331
87443
|
if (!result.ok) return mcpResponse({ ok: false, error: result.message });
|
|
87332
87444
|
const resolvedFindingsDir = storeAwareProjectPath(phrenPath, project);
|
|
87333
|
-
if (resolvedFindingsDir) updateFileInIndex(
|
|
87445
|
+
if (resolvedFindingsDir) updateFileInIndex(path167.join(resolvedFindingsDir, FINDINGS_FILENAME));
|
|
87334
87446
|
return mcpResponse({ ok: true, message: result.message, data: result.data });
|
|
87335
87447
|
});
|
|
87336
87448
|
}
|
|
@@ -87338,7 +87450,7 @@ async function handleRemoveFinding(ctx, { project: projectInput, finding: findin
|
|
|
87338
87450
|
const result = removeFinding2(phrenPath, project, finding3);
|
|
87339
87451
|
if (!result.ok) return mcpResponse({ ok: false, error: result.message });
|
|
87340
87452
|
const resolvedFindingsDir = storeAwareProjectPath(phrenPath, project);
|
|
87341
|
-
if (resolvedFindingsDir) updateFileInIndex(
|
|
87453
|
+
if (resolvedFindingsDir) updateFileInIndex(path167.join(resolvedFindingsDir, FINDINGS_FILENAME));
|
|
87342
87454
|
return mcpResponse({ ok: true, message: result.message, data: result.data });
|
|
87343
87455
|
});
|
|
87344
87456
|
}
|
|
@@ -87349,7 +87461,7 @@ async function syncTeamStores(phrenPath) {
|
|
|
87349
87461
|
const { getNonPrimaryStores: getNonPrimaryStores2 } = await Promise.resolve().then(() => (init_store_registry(), store_registry_exports));
|
|
87350
87462
|
const teamStores = getNonPrimaryStores2(phrenPath).filter((s) => s.role === "team");
|
|
87351
87463
|
for (const store of teamStores) {
|
|
87352
|
-
if (!fs60.existsSync(store.path) || !fs60.existsSync(
|
|
87464
|
+
if (!fs60.existsSync(store.path) || !fs60.existsSync(path167.join(store.path, ".git"))) continue;
|
|
87353
87465
|
const runStoreGit = (args, opts = {}) => execFileSync10("git", args, {
|
|
87354
87466
|
cwd: store.path,
|
|
87355
87467
|
encoding: "utf8",
|
|
@@ -87682,7 +87794,7 @@ var init_finding2 = __esm({
|
|
|
87682
87794
|
|
|
87683
87795
|
// src/bridge/project-memory.ts
|
|
87684
87796
|
import * as fs61 from "node:fs";
|
|
87685
|
-
import * as
|
|
87797
|
+
import * as path168 from "node:path";
|
|
87686
87798
|
function freshnessOptions(root, project) {
|
|
87687
87799
|
return { phrenPath: root, projectRemote: getProjectRemote(root, project, readProjectConfig(root, project)) };
|
|
87688
87800
|
}
|
|
@@ -87724,7 +87836,7 @@ function locate(base2, rawProject) {
|
|
|
87724
87836
|
} catch {
|
|
87725
87837
|
throw new BridgeError(404, "Project not found.");
|
|
87726
87838
|
}
|
|
87727
|
-
const storeId = taskStores(base2).find((entry2) =>
|
|
87839
|
+
const storeId = taskStores(base2).find((entry2) => path168.resolve(entry2.path) === path168.resolve(root))?.taskStoreId ?? null;
|
|
87728
87840
|
return { project, root, storeId };
|
|
87729
87841
|
}
|
|
87730
87842
|
function sortedFindings(root, project, opts) {
|
|
@@ -87737,7 +87849,7 @@ function sortedFindings(root, project, opts) {
|
|
|
87737
87849
|
return result.data.map((item, index2) => ({ item, index: index2, date: DATE.test(item.date) ? item.date : "" })).sort((a, b) => b.date.localeCompare(a.date) || a.index - b.index).map((entry2) => entry2.item);
|
|
87738
87850
|
}
|
|
87739
87851
|
function readTruths(root, project) {
|
|
87740
|
-
const file5 =
|
|
87852
|
+
const file5 = path168.join(root, project, "truths.md");
|
|
87741
87853
|
return fs61.existsSync(file5) ? fs61.readFileSync(file5, "utf8").split("\n").filter((line) => line.startsWith("- ")).map((line) => line.slice(2).trim()) : [];
|
|
87742
87854
|
}
|
|
87743
87855
|
function projectMemory(base2, rawProject) {
|
|
@@ -87982,17 +88094,17 @@ var init_project_git = __esm({
|
|
|
87982
88094
|
});
|
|
87983
88095
|
|
|
87984
88096
|
// src/bridge/session-seen.ts
|
|
87985
|
-
import { lstat as
|
|
87986
|
-
import
|
|
88097
|
+
import { lstat as lstat43, readFile as readFile61, unlink as unlink15 } from "node:fs/promises";
|
|
88098
|
+
import path169 from "node:path";
|
|
87987
88099
|
function seenPath(server, pane) {
|
|
87988
|
-
return
|
|
88100
|
+
return path169.join(bridgeRoot(), "turns", encodeURIComponent(serverName.parse(server)), encodeURIComponent(pane) + ".seen.json");
|
|
87989
88101
|
}
|
|
87990
88102
|
async function readSessionSeen(server, pane) {
|
|
87991
88103
|
try {
|
|
87992
88104
|
const file5 = seenPath(server, pane);
|
|
87993
|
-
const info = await
|
|
88105
|
+
const info = await lstat43(file5);
|
|
87994
88106
|
if (!info.isFile() || info.size > MAX_SEEN_BYTES) return void 0;
|
|
87995
|
-
const parsed = seenSchema.safeParse(JSON.parse(await
|
|
88107
|
+
const parsed = seenSchema.safeParse(JSON.parse(await readFile61(file5, "utf8")));
|
|
87996
88108
|
return parsed.success ? parsed.data.completion : void 0;
|
|
87997
88109
|
} catch {
|
|
87998
88110
|
return void 0;
|
|
@@ -88038,11 +88150,11 @@ var init_session_seen = __esm({
|
|
|
88038
88150
|
});
|
|
88039
88151
|
|
|
88040
88152
|
// src/bridge/conversation-search.ts
|
|
88041
|
-
import { createHash as
|
|
88042
|
-
import { appendFile as appendFile4, mkdir as mkdir39, open as open31, opendir as opendir2, readFile as
|
|
88043
|
-
import
|
|
88153
|
+
import { createHash as createHash43 } from "node:crypto";
|
|
88154
|
+
import { appendFile as appendFile4, mkdir as mkdir39, open as open31, opendir as opendir2, readFile as readFile62, rm as rm21, stat as stat39, writeFile as writeFile15 } from "node:fs/promises";
|
|
88155
|
+
import path170 from "node:path";
|
|
88044
88156
|
function absolutePath(value2) {
|
|
88045
|
-
return typeof value2 === "string" && value2.length > 0 && value2.length <= 4096 &&
|
|
88157
|
+
return typeof value2 === "string" && value2.length > 0 && value2.length <= 4096 && path170.isAbsolute(value2) ? value2 : void 0;
|
|
88046
88158
|
}
|
|
88047
88159
|
function textBlock(block) {
|
|
88048
88160
|
if (!["text", "input_text", "output_text"].includes(String(block.type))) return void 0;
|
|
@@ -88106,7 +88218,7 @@ function queuedMessage(projected, source, raw) {
|
|
|
88106
88218
|
return source === "copilot" && object2(raw.data).delivery === "queued";
|
|
88107
88219
|
}
|
|
88108
88220
|
function materializedFile(file5) {
|
|
88109
|
-
return file5.startsWith(materializedRoot() +
|
|
88221
|
+
return file5.startsWith(materializedRoot() + path170.sep);
|
|
88110
88222
|
}
|
|
88111
88223
|
async function openIndex() {
|
|
88112
88224
|
await mkdir39(bridgeRoot(), { recursive: true, mode: 448 });
|
|
@@ -88265,22 +88377,22 @@ async function pruneIndex(db, deadline) {
|
|
|
88265
88377
|
}
|
|
88266
88378
|
function transcriptRoots() {
|
|
88267
88379
|
const roots = [];
|
|
88268
|
-
for (const home of claudeHomes()) roots.push({ key: `claude:${home.id}`, root:
|
|
88269
|
-
roots.push({ key: "codex", root:
|
|
88270
|
-
roots.push({ key: "copilot", root:
|
|
88271
|
-
roots.push({ key: "opencode", root:
|
|
88380
|
+
for (const home of claudeHomes()) roots.push({ key: `claude:${home.id}`, root: path170.join(home.dir, "projects"), source: "claude", maxDepth: 1 });
|
|
88381
|
+
roots.push({ key: "codex", root: path170.join(codexHome(), "sessions"), source: "codex", maxDepth: 3 });
|
|
88382
|
+
roots.push({ key: "copilot", root: path170.join(copilotHome(), "session-state"), source: "copilot", maxDepth: 1 });
|
|
88383
|
+
roots.push({ key: "opencode", root: path170.join(phrenStoreRoot(), ".runtime", "sessions"), source: "opencode", maxDepth: 0 });
|
|
88272
88384
|
roots.push({ key: "codex-materialized", root: materializedRoot(), source: "codex", maxDepth: 0 });
|
|
88273
88385
|
return roots;
|
|
88274
88386
|
}
|
|
88275
88387
|
function fileIdentity2(source, file5) {
|
|
88276
|
-
const name2 =
|
|
88388
|
+
const name2 = path170.basename(file5);
|
|
88277
88389
|
if (source === "claude") {
|
|
88278
88390
|
const session = name2.endsWith(".jsonl") ? name2.slice(0, -".jsonl".length) : "";
|
|
88279
88391
|
return sessionId.safeParse(session).success ? { session } : void 0;
|
|
88280
88392
|
}
|
|
88281
88393
|
if (source === "copilot") {
|
|
88282
88394
|
if (name2 !== "events.jsonl") return void 0;
|
|
88283
|
-
const session =
|
|
88395
|
+
const session = path170.basename(path170.dirname(file5));
|
|
88284
88396
|
return sessionId.safeParse(session).success ? { session } : void 0;
|
|
88285
88397
|
}
|
|
88286
88398
|
if (source === "opencode") {
|
|
@@ -88289,7 +88401,7 @@ function fileIdentity2(source, file5) {
|
|
|
88289
88401
|
}
|
|
88290
88402
|
const materialized = /^([0-9a-f-]{36}|ses_[0-9A-Za-z]{1,64})\.jsonl$/i.exec(name2);
|
|
88291
88403
|
if (materialized && materializedFile(file5) && sessionId.safeParse(materialized[1]).success) return { session: materialized[1] };
|
|
88292
|
-
if (
|
|
88404
|
+
if (path170.relative(path170.join(codexHome(), "sessions"), file5).split(path170.sep).length !== 4) return void 0;
|
|
88293
88405
|
const rollout = /^rollout-.*-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/i.exec(name2);
|
|
88294
88406
|
return rollout && sessionId.safeParse(rollout[1]).success ? { session: rollout[1] } : void 0;
|
|
88295
88407
|
}
|
|
@@ -88331,7 +88443,7 @@ async function discoverDirectories(db, deadline) {
|
|
|
88331
88443
|
}
|
|
88332
88444
|
entries2++;
|
|
88333
88445
|
if (entry2.isSymbolicLink()) continue;
|
|
88334
|
-
const spec = specs.get(row.root), child =
|
|
88446
|
+
const spec = specs.get(row.root), child = path170.join(row.path, entry2.name);
|
|
88335
88447
|
if (entry2.isDirectory() && Number(row.depth) < (spec?.maxDepth ?? 0)) {
|
|
88336
88448
|
db.prepare("INSERT OR IGNORE INTO dirs(root, path, source, depth) VALUES(?, ?, ?, ?)").run(row.root, child, row.source, Number(row.depth) + 1);
|
|
88337
88449
|
} else if (entry2.isFile()) insertFile(db, row.path, row.source, child);
|
|
@@ -88442,7 +88554,7 @@ async function scanFile(db, row, info, budget, deadline, codex2) {
|
|
|
88442
88554
|
const rowBytes = chunk.subarray(0, newline2);
|
|
88443
88555
|
if (sidecarBytes + rowBytes.length <= MAX_ROW_BYTES2) {
|
|
88444
88556
|
if (rowBytes.length) await appendFile4(sidecar, rowBytes, { mode: 384 });
|
|
88445
|
-
const line = await
|
|
88557
|
+
const line = await readFile62(sidecar, "utf8").catch(() => "");
|
|
88446
88558
|
if (Date.now() >= deadline) {
|
|
88447
88559
|
position += newline2;
|
|
88448
88560
|
break;
|
|
@@ -88564,7 +88676,7 @@ async function refreshFiles(db, deadline, codex2) {
|
|
|
88564
88676
|
budget.partial = true;
|
|
88565
88677
|
continue;
|
|
88566
88678
|
}
|
|
88567
|
-
const state = await
|
|
88679
|
+
const state = await readFile62(file5 + ".state.json", "utf8").then((value2) => object2(JSON.parse(value2))).catch(() => ({}));
|
|
88568
88680
|
if (state.forwardDone !== true || state.updateTarget !== void 0 || state.upgrading === true) budget.partial = true;
|
|
88569
88681
|
await refreshFile(db, rowFor(db, row.path) ?? row, budget, deadline, codex2);
|
|
88570
88682
|
}
|
|
@@ -88625,7 +88737,7 @@ async function resolvePanes(keys2, deadline) {
|
|
|
88625
88737
|
const key4 = `${source}\0${identity}`;
|
|
88626
88738
|
if (!identity || !keys2.has(key4)) continue;
|
|
88627
88739
|
const name2 = String(pane.pane_id), terminal2 = String(pane.terminal_id);
|
|
88628
|
-
const record4 = await
|
|
88740
|
+
const record4 = await readFile62(path170.join(bridgeRoot(), "turns", encodeURIComponent(server), encodeURIComponent(name2) + ".json"), "utf8").then((value2) => object2(JSON.parse(value2))).catch(() => void 0);
|
|
88629
88741
|
if (record4 && record4.session === identity && record4.terminal !== terminal2) continue;
|
|
88630
88742
|
const at2 = record4?.session === identity && typeof record4.at === "string" ? record4.at : "";
|
|
88631
88743
|
const previous = candidates.get(key4);
|
|
@@ -88773,8 +88885,8 @@ var init_conversation_search = __esm({
|
|
|
88773
88885
|
init_herdr();
|
|
88774
88886
|
init_protocol();
|
|
88775
88887
|
init_transcripts();
|
|
88776
|
-
INDEX_FILE = () =>
|
|
88777
|
-
SIDECAR_DIR = () =>
|
|
88888
|
+
INDEX_FILE = () => path170.join(bridgeRoot(), "conversation-search.sqlite");
|
|
88889
|
+
SIDECAR_DIR = () => path170.join(bridgeRoot(), "conversation-search-rows");
|
|
88778
88890
|
DEFAULT_LIMIT = 20;
|
|
88779
88891
|
MAX_LIMIT = 50;
|
|
88780
88892
|
QUERY_MIN = 2;
|
|
@@ -88836,7 +88948,7 @@ CREATE TABLE IF NOT EXISTS dirs (
|
|
|
88836
88948
|
CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
|
88837
88949
|
`;
|
|
88838
88950
|
safe2 = (text7) => redactSecretsForLog(text7);
|
|
88839
|
-
sidecarPath = (file5) =>
|
|
88951
|
+
sidecarPath = (file5) => path170.join(SIDECAR_DIR(), createHash43("sha256").update(file5).digest("hex") + ".part");
|
|
88840
88952
|
textTokens = (text7) => [...new Set((text7.match(/[\p{L}\p{N}_]+/gu) ?? []).map((token2) => token2.toLowerCase()))];
|
|
88841
88953
|
directoryScans = /* @__PURE__ */ new Map();
|
|
88842
88954
|
encodeCursor = (cursor) => Buffer.from(JSON.stringify(cursor)).toString("base64url");
|
|
@@ -88846,7 +88958,7 @@ CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
|
|
88846
88958
|
|
|
88847
88959
|
// src/bridge/steps.ts
|
|
88848
88960
|
import { homedir as homedir21, tmpdir as tmpdir8 } from "node:os";
|
|
88849
|
-
import
|
|
88961
|
+
import path171 from "node:path";
|
|
88850
88962
|
async function currentStep(source, session) {
|
|
88851
88963
|
let file5;
|
|
88852
88964
|
try {
|
|
@@ -88974,7 +89086,7 @@ function describe4(tool, args) {
|
|
|
88974
89086
|
return "";
|
|
88975
89087
|
};
|
|
88976
89088
|
const firstLine2 = (v2) => v2.split(/\r?\n/).map((l) => l.trim()).find((l) => l) ?? "";
|
|
88977
|
-
const base2 = (v2) =>
|
|
89089
|
+
const base2 = (v2) => path171.basename(v2.split(" \xB7 ")[0].trim()) || "file";
|
|
88978
89090
|
const name2 = tool.toLowerCase();
|
|
88979
89091
|
let value2;
|
|
88980
89092
|
if (["bash", "shell", "exec_command", "exec", "parallel", "tools", "write_stdin", "container.exec"].includes(name2)) {
|
|
@@ -89024,7 +89136,7 @@ var init_steps = __esm({
|
|
|
89024
89136
|
});
|
|
89025
89137
|
|
|
89026
89138
|
// src/bridge/schedule-update.ts
|
|
89027
|
-
import
|
|
89139
|
+
import path172 from "node:path";
|
|
89028
89140
|
async function updateScheduleRoute(store, body2) {
|
|
89029
89141
|
let input2;
|
|
89030
89142
|
try {
|
|
@@ -89032,7 +89144,7 @@ async function updateScheduleRoute(store, body2) {
|
|
|
89032
89144
|
} catch (error62) {
|
|
89033
89145
|
throw new BridgeError(400, error62 instanceof Error ? error62.message : "Invalid schedule update.");
|
|
89034
89146
|
}
|
|
89035
|
-
const directory = getProjectDirs(store).find((dir) =>
|
|
89147
|
+
const directory = getProjectDirs(store).find((dir) => path172.basename(dir).toLowerCase() === input2.project.toLowerCase());
|
|
89036
89148
|
if (!directory) throw new BridgeError(404, `Unknown project "${input2.project}".`);
|
|
89037
89149
|
return withScheduleLock(directory, () => {
|
|
89038
89150
|
const file5 = readScheduleDocumentSync(directory);
|
|
@@ -89099,7 +89211,7 @@ var init_schedule_update = __esm({
|
|
|
89099
89211
|
|
|
89100
89212
|
// src/bridge/session-rename.ts
|
|
89101
89213
|
import { open as open32 } from "node:fs/promises";
|
|
89102
|
-
import
|
|
89214
|
+
import path173 from "node:path";
|
|
89103
89215
|
function lastCustomTitle(text7) {
|
|
89104
89216
|
for (const line of text7.split("\n").reverse()) {
|
|
89105
89217
|
if (!line.includes('"custom-title"')) continue;
|
|
@@ -89249,7 +89361,7 @@ var init_session_rename = __esm({
|
|
|
89249
89361
|
return text7 === void 0 ? void 0 : lastCustomTitle(text7);
|
|
89250
89362
|
},
|
|
89251
89363
|
async codexIndexTitle(thread) {
|
|
89252
|
-
const text7 = await tail2(
|
|
89364
|
+
const text7 = await tail2(path173.join(codexHome(), "session_index.jsonl"));
|
|
89253
89365
|
return text7 === void 0 ? void 0 : lastIndexedName(text7, thread);
|
|
89254
89366
|
},
|
|
89255
89367
|
sleep: (ms2) => new Promise((resolve20) => setTimeout(resolve20, ms2)),
|
|
@@ -89260,9 +89372,9 @@ var init_session_rename = __esm({
|
|
|
89260
89372
|
|
|
89261
89373
|
// src/bridge/link.ts
|
|
89262
89374
|
import { execFile as execFile37 } from "node:child_process";
|
|
89263
|
-
import { readFile as
|
|
89375
|
+
import { readFile as readFile63 } from "node:fs/promises";
|
|
89264
89376
|
import { homedir as homedir22, hostname as hostname12, userInfo as userInfo6 } from "node:os";
|
|
89265
|
-
import
|
|
89377
|
+
import path174 from "node:path";
|
|
89266
89378
|
import { promisify as promisify34 } from "node:util";
|
|
89267
89379
|
function sshConfigHosts(text7) {
|
|
89268
89380
|
const hosts = [];
|
|
@@ -89305,11 +89417,11 @@ async function probe2(host) {
|
|
|
89305
89417
|
return computerId ? { host, computerId, user: field2("user") ?? "", client: field2("client") } : void 0;
|
|
89306
89418
|
}
|
|
89307
89419
|
async function discoverComputers(options = {}) {
|
|
89308
|
-
const config4 = options.sshConfig ?? await
|
|
89420
|
+
const config4 = options.sshConfig ?? await readFile63(path174.join(homedir22(), ".ssh", "config"), "utf8").catch(() => "");
|
|
89309
89421
|
const store = options.store !== void 0 ? options.store : findPhrenPath();
|
|
89310
89422
|
const machines = store ? listMachines(store) : void 0;
|
|
89311
89423
|
const { peers } = await optionalHookPeers();
|
|
89312
|
-
const own2 = (await
|
|
89424
|
+
const own2 = (await readFile63(path174.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
|
|
89313
89425
|
const known2 = new Set([...localNames(), ...peers.flatMap((peer) => [peer.name, peer.address])].map(computerLabel));
|
|
89314
89426
|
const candidates = [.../* @__PURE__ */ new Set([...sshConfigHosts(config4), ...machines?.ok ? Object.keys(machines.data) : []])].filter((host) => !known2.has(computerLabel(host))).slice(0, 32);
|
|
89315
89427
|
const [found, peerIds] = await Promise.all([
|
|
@@ -89331,7 +89443,7 @@ function slugName(value2) {
|
|
|
89331
89443
|
async function linkComputer(host, options = {}) {
|
|
89332
89444
|
const remote = await probe2(host);
|
|
89333
89445
|
if (!remote) throw new BridgeError(409, `${host} answers over ssh but Phren Hook is not installed there. Run phren bridge install on it first.`);
|
|
89334
|
-
const own2 = (await
|
|
89446
|
+
const own2 = (await readFile63(path174.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
|
|
89335
89447
|
if (remote.computerId === own2) throw new BridgeError(409, `${host} is this computer.`);
|
|
89336
89448
|
const name2 = computerName.parse(options.name ?? slugName(host));
|
|
89337
89449
|
const as2 = computerName.parse(options.as ?? slugName(hostname12()));
|
|
@@ -89645,7 +89757,7 @@ var init_mux_wire = __esm({
|
|
|
89645
89757
|
});
|
|
89646
89758
|
|
|
89647
89759
|
// src/bridge/server-routes.ts
|
|
89648
|
-
import
|
|
89760
|
+
import path175 from "node:path";
|
|
89649
89761
|
import { stat as stat40 } from "node:fs/promises";
|
|
89650
89762
|
async function effectiveStatus(server, tabPanes, row, hooks) {
|
|
89651
89763
|
const panes3 = tabPanes.filter((p) => p.agent);
|
|
@@ -89713,7 +89825,9 @@ async function body(request11, cap = 115e5) {
|
|
|
89713
89825
|
if (size2 > cap) throw new BridgeError(413, "Request is too large.");
|
|
89714
89826
|
chunks.push(chunk);
|
|
89715
89827
|
}
|
|
89716
|
-
|
|
89828
|
+
const raw = Buffer.concat(chunks);
|
|
89829
|
+
bodyDigests.set(request11, bodyDigest(raw));
|
|
89830
|
+
return object2(JSON.parse(raw.toString() || "{}"));
|
|
89717
89831
|
}
|
|
89718
89832
|
function selectedServer(url2) {
|
|
89719
89833
|
const mux = url2.searchParams.get("mux");
|
|
@@ -90243,7 +90357,7 @@ function createRouteHandler(ctx) {
|
|
|
90243
90357
|
case "/v1/files/range": {
|
|
90244
90358
|
let root;
|
|
90245
90359
|
if (url2.searchParams.get("scope") === "uploads") {
|
|
90246
|
-
root =
|
|
90360
|
+
root = path175.join(bridgeRoot(), "uploads");
|
|
90247
90361
|
} else if (url2.searchParams.has("session")) {
|
|
90248
90362
|
const target2 = targetFromURL(url2), pane = await validateTarget(target2);
|
|
90249
90363
|
const cwd = await gitRepository(pane, target2, url2.searchParams.get("child") ?? void 0, url2.searchParams.get("worktree") ?? void 0);
|
|
@@ -90475,6 +90589,7 @@ function createRouteHandler(ctx) {
|
|
|
90475
90589
|
}
|
|
90476
90590
|
} else if (request11.method === "POST") {
|
|
90477
90591
|
const data = await body(request11, url2.pathname === "/v1/schedules/events" ? SCHEDULE_EVENT_BODY_CAP : void 0);
|
|
90592
|
+
await ownerProof.check(request11, url2.pathname, data, bodyDigests.get(request11));
|
|
90478
90593
|
if (url2.pathname.startsWith("/v1/conductor/move/")) await ctx.succession.authorize(external_exports.string().uuid().parse(data.id), requestPeer(request11), url2.pathname.endsWith("/prepare") ? external_exports.string().uuid().parse(data.originId) : void 0);
|
|
90479
90594
|
const executeConductor = async (action, payload2, origin, remote = false) => {
|
|
90480
90595
|
if (action === "dispatch") return dispatches.dispatch(payload2, { server: origin.server, workspace: origin.workspace, tab: origin.tab, pane: origin.pane });
|
|
@@ -90584,10 +90699,10 @@ function createRouteHandler(ctx) {
|
|
|
90584
90699
|
const cwd = prepared ? defaultPhrenPath() : await dispatchProjectDirectory(input2.project);
|
|
90585
90700
|
const wantsCopy = !!caller && input2.brief.text.includes(CONVERSATION_MARKER) && launchesWithBrief(input2.to.harness);
|
|
90586
90701
|
const conversation = wantsCopy ? await fetchContinuationConversation((offset) => peerContinuationIntent(caller, input2.brief.id, offset), redactPeerHandoff) : void 0;
|
|
90587
|
-
const copied = conversation ?
|
|
90702
|
+
const copied = conversation ? path175.join(briefRoot(), input2.brief.id, CONVERSATION_FILE) : void 0;
|
|
90588
90703
|
const brief = copied ? { ...input2.brief, text: withConversationPointer(input2.brief.text, copied) } : input2.brief;
|
|
90589
90704
|
return launchSession(selectedServer(url2), { cwd, kind: input2.to.harness, account: input2.to.account, model: input2.to.model, effort: input2.to.effort, label: `move-${input2.brief.id}`, brief }, { trustFolder: true, onPlaced: async (target2) => {
|
|
90590
|
-
if (copied && conversation && await stat40(
|
|
90705
|
+
if (copied && conversation && await stat40(path175.dirname(copied)).catch(() => void 0)) await atomicInPrivateDir(copied, conversation).catch(() => void 0);
|
|
90591
90706
|
await onPlaced(target2);
|
|
90592
90707
|
await terminalProvider().renamePane(selectedServer(url2), external_exports.string().parse(target2.pane), input2.label).catch(() => void 0);
|
|
90593
90708
|
} });
|
|
@@ -90790,6 +90905,7 @@ function createRouteHandler(ctx) {
|
|
|
90790
90905
|
} else if (request11.method === "DELETE") {
|
|
90791
90906
|
if (url2.pathname !== "/v1/conductor/grants" && url2.pathname !== "/v1/authority" && url2.pathname !== "/v1/approval-rules") throw new BridgeError(404, "Unknown Phren Hook route.");
|
|
90792
90907
|
const data = await body(request11);
|
|
90908
|
+
await ownerProof.check(request11, url2.pathname, data, bodyDigests.get(request11));
|
|
90793
90909
|
if (url2.pathname === "/v1/conductor/grants" && request11.headers?.["x-phren-origin"] === "peer") throw new BridgeError(403, "Peer conductor operations require the authenticated generation-scoped routes.");
|
|
90794
90910
|
if (url2.pathname === "/v1/approval-rules") {
|
|
90795
90911
|
result = await changeApprovalRule(data, "DELETE");
|
|
@@ -90813,7 +90929,7 @@ function createRouteHandler(ctx) {
|
|
|
90813
90929
|
}
|
|
90814
90930
|
};
|
|
90815
90931
|
}
|
|
90816
|
-
var OVERVIEW_ENRICH_BUDGET_MS, STATUS_ENRICH_BUDGET_MS, capabilities, verifiedPages;
|
|
90932
|
+
var OVERVIEW_ENRICH_BUDGET_MS, STATUS_ENRICH_BUDGET_MS, capabilities, ownerProof, bodyDigests, verifiedPages;
|
|
90817
90933
|
var init_server_routes = __esm({
|
|
90818
90934
|
"src/bridge/server-routes.ts"() {
|
|
90819
90935
|
"use strict";
|
|
@@ -90828,6 +90944,7 @@ var init_server_routes = __esm({
|
|
|
90828
90944
|
init_claude_accounts();
|
|
90829
90945
|
init_move_computers();
|
|
90830
90946
|
init_request_origin();
|
|
90947
|
+
init_owner_proof();
|
|
90831
90948
|
init_session_move();
|
|
90832
90949
|
init_task_routes();
|
|
90833
90950
|
init_owner_inbox_view();
|
|
@@ -90956,6 +91073,7 @@ var init_server_routes = __esm({
|
|
|
90956
91073
|
sudo: true,
|
|
90957
91074
|
sudoOutcome: true,
|
|
90958
91075
|
secretExec: true,
|
|
91076
|
+
ownerProof: 1,
|
|
90959
91077
|
previewDeltas: true,
|
|
90960
91078
|
quickChat: true,
|
|
90961
91079
|
agentFolder: true,
|
|
@@ -90984,6 +91102,8 @@ var init_server_routes = __esm({
|
|
|
90984
91102
|
terminalResolve: true,
|
|
90985
91103
|
conversationSearch: true
|
|
90986
91104
|
};
|
|
91105
|
+
ownerProof = new OwnerProof();
|
|
91106
|
+
bodyDigests = /* @__PURE__ */ new WeakMap();
|
|
90987
91107
|
verifiedPages = /* @__PURE__ */ new Map();
|
|
90988
91108
|
}
|
|
90989
91109
|
});
|
|
@@ -92043,14 +92163,14 @@ var init_server_overview = __esm({
|
|
|
92043
92163
|
});
|
|
92044
92164
|
|
|
92045
92165
|
// src/bridge/git-watch.ts
|
|
92046
|
-
import { createHash as
|
|
92166
|
+
import { createHash as createHash44 } from "node:crypto";
|
|
92047
92167
|
import { readFileSync as readFileSync69, watch as watchFs } from "node:fs";
|
|
92048
|
-
import
|
|
92168
|
+
import path176 from "node:path";
|
|
92049
92169
|
function gitDirectory2(root) {
|
|
92050
|
-
const dotGit =
|
|
92170
|
+
const dotGit = path176.join(root, ".git");
|
|
92051
92171
|
try {
|
|
92052
92172
|
const link2 = /^gitdir:\s*(.+)$/m.exec(readFileSync69(dotGit, "utf8"));
|
|
92053
|
-
if (link2) return
|
|
92173
|
+
if (link2) return path176.resolve(root, link2[1].trim());
|
|
92054
92174
|
} catch {
|
|
92055
92175
|
return dotGit;
|
|
92056
92176
|
}
|
|
@@ -92069,7 +92189,7 @@ function startNative(root, onChange, onError) {
|
|
|
92069
92189
|
rootWatch.on("error", onError);
|
|
92070
92190
|
handles.push(rootWatch);
|
|
92071
92191
|
const gitDir2 = gitDirectory2(root);
|
|
92072
|
-
const externalGitDir = gitDir2 !==
|
|
92192
|
+
const externalGitDir = gitDir2 !== path176.join(root, ".git");
|
|
92073
92193
|
try {
|
|
92074
92194
|
const indexWatch = watchFs(gitDir2, (_event, filename) => {
|
|
92075
92195
|
const name2 = filename;
|
|
@@ -92089,7 +92209,7 @@ function startNative(root, onChange, onError) {
|
|
|
92089
92209
|
}
|
|
92090
92210
|
function startPolling(root, onChange, onError, pollMs) {
|
|
92091
92211
|
let stopped = false, timer, current2;
|
|
92092
|
-
const read = async () =>
|
|
92212
|
+
const read = async () => createHash44("sha256").update(await git(root, "--no-optional-locks", "status", "--porcelain=v2", "-z")).digest("hex");
|
|
92093
92213
|
const tick = async () => {
|
|
92094
92214
|
if (stopped) return;
|
|
92095
92215
|
try {
|
|
@@ -92357,11 +92477,11 @@ var init_git_watch = __esm({
|
|
|
92357
92477
|
});
|
|
92358
92478
|
|
|
92359
92479
|
// src/bridge/codex-auth-refresh.ts
|
|
92360
|
-
import { readFile as
|
|
92361
|
-
import
|
|
92362
|
-
async function lastCodexRefresh(file5 =
|
|
92480
|
+
import { readFile as readFile64 } from "node:fs/promises";
|
|
92481
|
+
import path177 from "node:path";
|
|
92482
|
+
async function lastCodexRefresh(file5 = path177.join(codexHome(), "auth.json")) {
|
|
92363
92483
|
try {
|
|
92364
|
-
const auth = object2(JSON.parse(await
|
|
92484
|
+
const auth = object2(JSON.parse(await readFile64(file5, "utf8")));
|
|
92365
92485
|
if (!object2(auth.tokens).refresh_token) return void 0;
|
|
92366
92486
|
const at2 = Date.parse(String(auth.last_refresh ?? ""));
|
|
92367
92487
|
return Number.isFinite(at2) ? at2 : 0;
|
|
@@ -92477,11 +92597,11 @@ var init_socket_budget = __esm({
|
|
|
92477
92597
|
|
|
92478
92598
|
// src/bridge/server.ts
|
|
92479
92599
|
import { randomUUID as randomUUID38 } from "node:crypto";
|
|
92480
|
-
import { chmod as chmod8, lstat as
|
|
92600
|
+
import { chmod as chmod8, lstat as lstat44, mkdir as mkdir40, readFile as readFile65, rm as rm22, unlink as unlink16, writeFile as writeFile16 } from "node:fs/promises";
|
|
92481
92601
|
import { readFileSync as readFileSync70 } from "node:fs";
|
|
92482
92602
|
import { createServer as createServer6 } from "node:http";
|
|
92483
92603
|
import { cpus as cpus2, hostname as hostname13, loadavg as loadavg2 } from "node:os";
|
|
92484
|
-
import
|
|
92604
|
+
import path178 from "node:path";
|
|
92485
92605
|
async function serve(version2, options = {}) {
|
|
92486
92606
|
process.umask(63);
|
|
92487
92607
|
markHookServerProcess();
|
|
@@ -92493,9 +92613,9 @@ async function serve(version2, options = {}) {
|
|
|
92493
92613
|
await mkdir40(root, { recursive: true, mode: 448 });
|
|
92494
92614
|
await chmod8(root, 448);
|
|
92495
92615
|
let computerID2;
|
|
92496
|
-
const identityFile =
|
|
92616
|
+
const identityFile = path178.join(root, "computer-id");
|
|
92497
92617
|
try {
|
|
92498
|
-
computerID2 = (await
|
|
92618
|
+
computerID2 = (await readFile65(identityFile, "utf8")).trim();
|
|
92499
92619
|
} catch {
|
|
92500
92620
|
computerID2 = randomUUID38();
|
|
92501
92621
|
await writeFile16(identityFile, computerID2, { flag: "wx", mode: 384 });
|
|
@@ -92514,7 +92634,7 @@ async function serve(version2, options = {}) {
|
|
|
92514
92634
|
}) : void 0;
|
|
92515
92635
|
const locatedDirectories = /* @__PURE__ */ new Set();
|
|
92516
92636
|
const journal = new ActivityJournal();
|
|
92517
|
-
const agentHooks = new AgentHooks(void 0, modules,
|
|
92637
|
+
const agentHooks = new AgentHooks(void 0, modules, path178.join(bridgeRoot(), "deliveries.json"));
|
|
92518
92638
|
let succession;
|
|
92519
92639
|
const returns = dispatches ? new DispatchReturns({
|
|
92520
92640
|
takesPrompt: (target2, pane) => takesPrompt(target2.server, pane, target2.session, promptGuards(agentHooks, target2)),
|
|
@@ -92565,7 +92685,7 @@ async function serve(version2, options = {}) {
|
|
|
92565
92685
|
{},
|
|
92566
92686
|
typing
|
|
92567
92687
|
);
|
|
92568
|
-
const turnQueue = new TurnQueue(
|
|
92688
|
+
const turnQueue = new TurnQueue(path178.join(root, "turn-queue.json"), {
|
|
92569
92689
|
current: turnQueuePaneReader(agentHooks),
|
|
92570
92690
|
holding: (target2, exceptId) => agentHooks.deliveries.holding(target2, exceptId),
|
|
92571
92691
|
send: sendPrompt,
|
|
@@ -92665,7 +92785,7 @@ async function serve(version2, options = {}) {
|
|
|
92665
92785
|
if (codeReindexer) agentHooks.changes.onRecord = (files) => codeReindexer.record(files);
|
|
92666
92786
|
function gatewayTiming() {
|
|
92667
92787
|
try {
|
|
92668
|
-
const parsed = JSON.parse(readFileSync70(
|
|
92788
|
+
const parsed = JSON.parse(readFileSync70(path178.join(root, "gateway.json"), "utf8"));
|
|
92669
92789
|
if (typeof parsed.ms === "number" && Number.isFinite(parsed.ms) && parsed.ms >= 0) return Math.round(parsed.ms);
|
|
92670
92790
|
} catch {
|
|
92671
92791
|
}
|
|
@@ -92694,7 +92814,7 @@ async function serve(version2, options = {}) {
|
|
|
92694
92814
|
launch: (server, data) => launches.run(() => launchSession(server, data, { canary: true })),
|
|
92695
92815
|
scheduler
|
|
92696
92816
|
});
|
|
92697
|
-
const old = await
|
|
92817
|
+
const old = await lstat44(socketPath()).catch(() => null);
|
|
92698
92818
|
if (old) {
|
|
92699
92819
|
if (!old.isSocket() || process.getuid && old.uid !== process.getuid()) throw new Error("Refusing to replace an unexpected hook socket.");
|
|
92700
92820
|
const { connect: connect6 } = await import("node:net");
|
|
@@ -92721,7 +92841,7 @@ async function serve(version2, options = {}) {
|
|
|
92721
92841
|
await browsers.start();
|
|
92722
92842
|
const stopRetention = modules.has("git") ? await startChangeRetention() : () => {
|
|
92723
92843
|
};
|
|
92724
|
-
if (modules.has("git")) await rm22(
|
|
92844
|
+
if (modules.has("git")) await rm22(path178.join(root, "changes-scratch"), { recursive: true, force: true });
|
|
92725
92845
|
const streams = transcriptStreams({ modules, agentHooks, codexQuestions, sideQuestions, settingsSwitcher, info, activeCapabilities });
|
|
92726
92846
|
const { stream } = streams;
|
|
92727
92847
|
const overview = overviewStream({
|
|
@@ -93052,24 +93172,24 @@ __export(device_enroll_exports, {
|
|
|
93052
93172
|
enrollDevice: () => enrollDevice,
|
|
93053
93173
|
runEnrollDevice: () => runEnrollDevice
|
|
93054
93174
|
});
|
|
93055
|
-
import { readFile as
|
|
93175
|
+
import { readFile as readFile66 } from "node:fs/promises";
|
|
93056
93176
|
import { homedir as homedir23, userInfo as userInfo7 } from "node:os";
|
|
93057
|
-
import
|
|
93177
|
+
import path179 from "node:path";
|
|
93058
93178
|
async function enrollDevice(input2, options) {
|
|
93059
93179
|
try {
|
|
93060
93180
|
const publicKey = publicComputerKey(input2);
|
|
93061
93181
|
const comment = options.device === "android" ? "phren-android" : "phren-iphone";
|
|
93062
93182
|
const line = `restrict,pty,${forcedCommand} ${publicKey} ${comment}`;
|
|
93063
93183
|
const encoded = publicKey.split(" ")[1];
|
|
93064
|
-
const file5 =
|
|
93065
|
-
const before = await
|
|
93184
|
+
const file5 = path179.join(options.sshDirectory ?? path179.join(homedir23(), ".ssh"), "authorized_keys");
|
|
93185
|
+
const before = await readFile66(file5, "utf8").catch(() => "");
|
|
93066
93186
|
await appendAuthorizedKey(
|
|
93067
93187
|
line,
|
|
93068
93188
|
(existing) => existing.split(/\s+/).includes(encoded),
|
|
93069
93189
|
"This phone key is already authorized with different options.",
|
|
93070
93190
|
options.sshDirectory
|
|
93071
93191
|
);
|
|
93072
|
-
const id3 = await
|
|
93192
|
+
const id3 = await readFile66(path179.join(options.root ?? bridgeRoot(), "computer-id"), "utf8").then((value2) => value2.trim() || null).catch(() => null);
|
|
93073
93193
|
return {
|
|
93074
93194
|
v: 1,
|
|
93075
93195
|
ok: true,
|
|
@@ -93120,13 +93240,13 @@ __export(command_exports, {
|
|
|
93120
93240
|
approvalPushCheck: () => approvalPushCheck,
|
|
93121
93241
|
runBridge: () => runBridge
|
|
93122
93242
|
});
|
|
93123
|
-
import { readFile as
|
|
93243
|
+
import { readFile as readFile67 } from "node:fs/promises";
|
|
93124
93244
|
async function runBridge(args, version2) {
|
|
93125
93245
|
switch (args[0]) {
|
|
93126
93246
|
case "enroll-computer": {
|
|
93127
93247
|
if (args.length === 2) console.log(await enrollComputer(args[1]));
|
|
93128
93248
|
else if (args.length === 4 && args[2] === "--accept") {
|
|
93129
|
-
await acceptComputer(args[1], await
|
|
93249
|
+
await acceptComputer(args[1], await readFile67(args[3], "utf8"));
|
|
93130
93250
|
console.log(`Enrolled ${args[1]} for Phren Hook.`);
|
|
93131
93251
|
} else throw new Error("Usage: phren bridge enroll-computer <name> [--accept <public-key-file>]");
|
|
93132
93252
|
break;
|
|
@@ -93319,7 +93439,7 @@ async function runBridge(args, version2) {
|
|
|
93319
93439
|
break;
|
|
93320
93440
|
}
|
|
93321
93441
|
const readModels = async (source) => {
|
|
93322
|
-
const rows3 = JSON.parse(await
|
|
93442
|
+
const rows3 = JSON.parse(await readFile67(fixture, "utf8"));
|
|
93323
93443
|
return Array.isArray(rows3[source]) ? rows3[source] : [];
|
|
93324
93444
|
};
|
|
93325
93445
|
const emptyUsage = (source) => ({ source, windows: [] });
|
|
@@ -93482,7 +93602,7 @@ async function main() {
|
|
|
93482
93602
|
return askpass2(args[1]);
|
|
93483
93603
|
}
|
|
93484
93604
|
const { runBridge: runBridge2 } = await Promise.resolve().then(() => (init_command(), command_exports));
|
|
93485
|
-
return runBridge2(args, "0.3.
|
|
93605
|
+
return runBridge2(args, "0.3.79");
|
|
93486
93606
|
}
|
|
93487
93607
|
main().then((code) => {
|
|
93488
93608
|
process.exitCode = code;
|