@phren/cli 0.3.10 → 0.3.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bridge/fanout-messages.js +2 -2
- package/dist/bridge/fanouts.js +1 -1
- package/dist/bridge/resources.d.ts +119 -0
- package/dist/bridge/resources.js +298 -0
- package/dist/bridge/server-overview.d.ts +8 -2
- package/dist/bridge/server-overview.js +16 -3
- package/dist/bridge/server-routes.d.ts +4 -1
- package/dist/bridge/server-routes.js +34 -3
- package/dist/bridge/server.js +5 -2
- package/dist/bridge/transcript-claude.js +5 -0
- package/dist/bridge/usage.d.ts +36 -20
- package/dist/bridge/usage.js +163 -301
- package/dist/bridge-hook.mjs +974 -793
- package/dist/cli-registry.d.ts +2 -0
- package/dist/cli-registry.js +13 -0
- package/dist/computers/command.d.ts +6 -0
- package/dist/computers/command.js +152 -0
- package/dist/computers/mcp.d.ts +1 -0
- package/dist/computers/mcp.js +97 -0
- package/dist/computers/read.d.ts +85 -0
- package/dist/computers/read.js +177 -0
- package/dist/entrypoint.js +10 -0
- package/dist/fanout/adapters/claude.js +15 -2
- package/dist/fanout/adapters/types.d.ts +6 -0
- package/dist/fanout/launcher.d.ts +5 -1
- package/dist/fanout/launcher.js +34 -3
- package/dist/fanout/picker.js +3 -2
- package/dist/fanout/usage.js +1 -1
- package/dist/modules/registry.js +3 -3
- package/package.json +1 -1
- package/starter/global/skills/fanout/SKILL.md +3 -0
package/dist/bridge-hook.mjs
CHANGED
|
@@ -268,10 +268,10 @@ function mergeDefs(...defs) {
|
|
|
268
268
|
function cloneDef(schema) {
|
|
269
269
|
return mergeDefs(schema._zod.def);
|
|
270
270
|
}
|
|
271
|
-
function getElementAtPath(obj,
|
|
272
|
-
if (!
|
|
271
|
+
function getElementAtPath(obj, path87) {
|
|
272
|
+
if (!path87)
|
|
273
273
|
return obj;
|
|
274
|
-
return
|
|
274
|
+
return path87.reduce((acc, key2) => acc?.[key2], obj);
|
|
275
275
|
}
|
|
276
276
|
function promiseAllObject(promisesObj) {
|
|
277
277
|
const keys = Object.keys(promisesObj);
|
|
@@ -530,11 +530,11 @@ function explicitlyAborted(x, startIndex = 0) {
|
|
|
530
530
|
}
|
|
531
531
|
return false;
|
|
532
532
|
}
|
|
533
|
-
function prefixIssues(
|
|
533
|
+
function prefixIssues(path87, issues) {
|
|
534
534
|
return issues.map((iss) => {
|
|
535
535
|
var _a3;
|
|
536
536
|
(_a3 = iss).path ?? (_a3.path = []);
|
|
537
|
-
iss.path.unshift(
|
|
537
|
+
iss.path.unshift(path87);
|
|
538
538
|
return iss;
|
|
539
539
|
});
|
|
540
540
|
}
|
|
@@ -1055,16 +1055,16 @@ function flattenError(error62, mapper = (issue2) => issue2.message) {
|
|
|
1055
1055
|
}
|
|
1056
1056
|
function formatError(error62, mapper = (issue2) => issue2.message) {
|
|
1057
1057
|
const fieldErrors = { _errors: [] };
|
|
1058
|
-
const processError = (error63,
|
|
1058
|
+
const processError = (error63, path87 = []) => {
|
|
1059
1059
|
for (const issue2 of error63.issues) {
|
|
1060
1060
|
if (issue2.code === "invalid_union" && issue2.errors.length) {
|
|
1061
|
-
issue2.errors.map((issues) => processError({ issues }, [...
|
|
1061
|
+
issue2.errors.map((issues) => processError({ issues }, [...path87, ...issue2.path]));
|
|
1062
1062
|
} else if (issue2.code === "invalid_key") {
|
|
1063
|
-
processError({ issues: issue2.issues }, [...
|
|
1063
|
+
processError({ issues: issue2.issues }, [...path87, ...issue2.path]);
|
|
1064
1064
|
} else if (issue2.code === "invalid_element") {
|
|
1065
|
-
processError({ issues: issue2.issues }, [...
|
|
1065
|
+
processError({ issues: issue2.issues }, [...path87, ...issue2.path]);
|
|
1066
1066
|
} else {
|
|
1067
|
-
const fullpath = [...
|
|
1067
|
+
const fullpath = [...path87, ...issue2.path];
|
|
1068
1068
|
if (fullpath.length === 0) {
|
|
1069
1069
|
fieldErrors._errors.push(mapper(issue2));
|
|
1070
1070
|
} else {
|
|
@@ -1103,17 +1103,17 @@ function formatError(error62, mapper = (issue2) => issue2.message) {
|
|
|
1103
1103
|
}
|
|
1104
1104
|
function treeifyError(error62, mapper = (issue2) => issue2.message) {
|
|
1105
1105
|
const result = { errors: [] };
|
|
1106
|
-
const processError = (error63,
|
|
1106
|
+
const processError = (error63, path87 = []) => {
|
|
1107
1107
|
var _a3;
|
|
1108
1108
|
for (const issue2 of error63.issues) {
|
|
1109
1109
|
if (issue2.code === "invalid_union" && issue2.errors.length) {
|
|
1110
|
-
issue2.errors.map((issues) => processError({ issues }, [...
|
|
1110
|
+
issue2.errors.map((issues) => processError({ issues }, [...path87, ...issue2.path]));
|
|
1111
1111
|
} else if (issue2.code === "invalid_key") {
|
|
1112
|
-
processError({ issues: issue2.issues }, [...
|
|
1112
|
+
processError({ issues: issue2.issues }, [...path87, ...issue2.path]);
|
|
1113
1113
|
} else if (issue2.code === "invalid_element") {
|
|
1114
|
-
processError({ issues: issue2.issues }, [...
|
|
1114
|
+
processError({ issues: issue2.issues }, [...path87, ...issue2.path]);
|
|
1115
1115
|
} else {
|
|
1116
|
-
const fullpath = [...
|
|
1116
|
+
const fullpath = [...path87, ...issue2.path];
|
|
1117
1117
|
if (fullpath.length === 0) {
|
|
1118
1118
|
result.errors.push(mapper(issue2));
|
|
1119
1119
|
continue;
|
|
@@ -1152,8 +1152,8 @@ function treeifyError(error62, mapper = (issue2) => issue2.message) {
|
|
|
1152
1152
|
}
|
|
1153
1153
|
function toDotPath(_path) {
|
|
1154
1154
|
const segs = [];
|
|
1155
|
-
const
|
|
1156
|
-
for (const seg of
|
|
1155
|
+
const path87 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
|
|
1156
|
+
for (const seg of path87) {
|
|
1157
1157
|
if (typeof seg === "number")
|
|
1158
1158
|
segs.push(`[${seg}]`);
|
|
1159
1159
|
else if (typeof seg === "symbol")
|
|
@@ -2251,10 +2251,10 @@ function isValidJWT(token, algorithm = null) {
|
|
|
2251
2251
|
const tokensParts = token.split(".");
|
|
2252
2252
|
if (tokensParts.length !== 3)
|
|
2253
2253
|
return false;
|
|
2254
|
-
const [
|
|
2255
|
-
if (!
|
|
2254
|
+
const [header] = tokensParts;
|
|
2255
|
+
if (!header)
|
|
2256
2256
|
return false;
|
|
2257
|
-
const parsedHeader = JSON.parse(atob(
|
|
2257
|
+
const parsedHeader = JSON.parse(atob(header));
|
|
2258
2258
|
if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT")
|
|
2259
2259
|
return false;
|
|
2260
2260
|
if (!parsedHeader.alg)
|
|
@@ -19149,13 +19149,13 @@ function resolveRef(ref, ctx) {
|
|
|
19149
19149
|
if (!ref.startsWith("#")) {
|
|
19150
19150
|
throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
|
|
19151
19151
|
}
|
|
19152
|
-
const
|
|
19153
|
-
if (
|
|
19152
|
+
const path87 = ref.slice(1).split("/").filter(Boolean);
|
|
19153
|
+
if (path87.length === 0) {
|
|
19154
19154
|
return ctx.rootSchema;
|
|
19155
19155
|
}
|
|
19156
19156
|
const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
|
|
19157
|
-
if (
|
|
19158
|
-
const key2 =
|
|
19157
|
+
if (path87[0] === defsKey) {
|
|
19158
|
+
const key2 = path87[1] === void 0 ? void 0 : decodeJSONPointerSegment(path87[1]);
|
|
19159
19159
|
if (!key2 || !ctx.defs[key2]) {
|
|
19160
19160
|
throw new Error(`Reference not found: ${ref}`);
|
|
19161
19161
|
}
|
|
@@ -19875,7 +19875,7 @@ function visit(schema, fnOrHandlers) {
|
|
|
19875
19875
|
return h ? h(node2, rewritten) : node2;
|
|
19876
19876
|
};
|
|
19877
19877
|
const cache2 = /* @__PURE__ */ new Map();
|
|
19878
|
-
function
|
|
19878
|
+
function run2(s) {
|
|
19879
19879
|
const cached2 = cache2.get(s);
|
|
19880
19880
|
if (cached2 === RESOLVING) {
|
|
19881
19881
|
return new $ZodLazy({
|
|
@@ -19901,21 +19901,21 @@ function visit(schema, fnOrHandlers) {
|
|
|
19901
19901
|
let changed2 = false;
|
|
19902
19902
|
const newShape = {};
|
|
19903
19903
|
for (const k of keys) {
|
|
19904
|
-
const mapped =
|
|
19904
|
+
const mapped = run2(oldShape[k]);
|
|
19905
19905
|
if (mapped !== oldShape[k])
|
|
19906
19906
|
changed2 = true;
|
|
19907
19907
|
newShape[k] = mapped;
|
|
19908
19908
|
}
|
|
19909
19909
|
let newCatchall = def.catchall;
|
|
19910
19910
|
if (def.catchall) {
|
|
19911
|
-
newCatchall =
|
|
19911
|
+
newCatchall = run2(def.catchall);
|
|
19912
19912
|
if (newCatchall !== def.catchall)
|
|
19913
19913
|
changed2 = true;
|
|
19914
19914
|
}
|
|
19915
19915
|
return changed2 ? clone(s, { ...def, shape: newShape, catchall: newCatchall }) : s;
|
|
19916
19916
|
}
|
|
19917
19917
|
case "array": {
|
|
19918
|
-
const mapped =
|
|
19918
|
+
const mapped = run2(def.element);
|
|
19919
19919
|
return mapped === def.element ? s : clone(s, { ...def, element: mapped });
|
|
19920
19920
|
}
|
|
19921
19921
|
case "tuple": {
|
|
@@ -19923,14 +19923,14 @@ function visit(schema, fnOrHandlers) {
|
|
|
19923
19923
|
let changed2 = false;
|
|
19924
19924
|
const newItems = [];
|
|
19925
19925
|
for (const item of oldItems) {
|
|
19926
|
-
const mapped =
|
|
19926
|
+
const mapped = run2(item);
|
|
19927
19927
|
if (mapped !== item)
|
|
19928
19928
|
changed2 = true;
|
|
19929
19929
|
newItems.push(mapped);
|
|
19930
19930
|
}
|
|
19931
19931
|
let newRest = def.rest;
|
|
19932
19932
|
if (def.rest) {
|
|
19933
|
-
newRest =
|
|
19933
|
+
newRest = run2(def.rest);
|
|
19934
19934
|
if (newRest !== def.rest)
|
|
19935
19935
|
changed2 = true;
|
|
19936
19936
|
}
|
|
@@ -19938,12 +19938,12 @@ function visit(schema, fnOrHandlers) {
|
|
|
19938
19938
|
}
|
|
19939
19939
|
case "record":
|
|
19940
19940
|
case "map": {
|
|
19941
|
-
const newKey =
|
|
19942
|
-
const newVal =
|
|
19941
|
+
const newKey = run2(def.keyType);
|
|
19942
|
+
const newVal = run2(def.valueType);
|
|
19943
19943
|
return newKey === def.keyType && newVal === def.valueType ? s : clone(s, { ...def, keyType: newKey, valueType: newVal });
|
|
19944
19944
|
}
|
|
19945
19945
|
case "set": {
|
|
19946
|
-
const newVal =
|
|
19946
|
+
const newVal = run2(def.valueType);
|
|
19947
19947
|
return newVal === def.valueType ? s : clone(s, { ...def, valueType: newVal });
|
|
19948
19948
|
}
|
|
19949
19949
|
case "union": {
|
|
@@ -19951,7 +19951,7 @@ function visit(schema, fnOrHandlers) {
|
|
|
19951
19951
|
let changed2 = false;
|
|
19952
19952
|
const newOptions = [];
|
|
19953
19953
|
for (const opt of oldOptions) {
|
|
19954
|
-
const mapped =
|
|
19954
|
+
const mapped = run2(opt);
|
|
19955
19955
|
if (mapped !== opt)
|
|
19956
19956
|
changed2 = true;
|
|
19957
19957
|
newOptions.push(mapped);
|
|
@@ -19959,8 +19959,8 @@ function visit(schema, fnOrHandlers) {
|
|
|
19959
19959
|
return changed2 ? clone(s, { ...def, options: newOptions }) : s;
|
|
19960
19960
|
}
|
|
19961
19961
|
case "intersection": {
|
|
19962
|
-
const newLeft =
|
|
19963
|
-
const newRight =
|
|
19962
|
+
const newLeft = run2(def.left);
|
|
19963
|
+
const newRight = run2(def.right);
|
|
19964
19964
|
return newLeft === def.left && newRight === def.right ? s : clone(s, { ...def, left: newLeft, right: newRight });
|
|
19965
19965
|
}
|
|
19966
19966
|
case "optional":
|
|
@@ -19972,23 +19972,23 @@ function visit(schema, fnOrHandlers) {
|
|
|
19972
19972
|
case "nonoptional":
|
|
19973
19973
|
case "promise":
|
|
19974
19974
|
case "success": {
|
|
19975
|
-
const newInner =
|
|
19975
|
+
const newInner = run2(def.innerType);
|
|
19976
19976
|
return newInner === def.innerType ? s : clone(s, { ...def, innerType: newInner });
|
|
19977
19977
|
}
|
|
19978
19978
|
case "pipe": {
|
|
19979
|
-
const newIn =
|
|
19980
|
-
const newOut =
|
|
19979
|
+
const newIn = run2(def.in);
|
|
19980
|
+
const newOut = run2(def.out);
|
|
19981
19981
|
return newIn === def.in && newOut === def.out ? s : clone(s, { ...def, in: newIn, out: newOut });
|
|
19982
19982
|
}
|
|
19983
19983
|
case "function": {
|
|
19984
|
-
const newInput =
|
|
19985
|
-
const newOutput =
|
|
19984
|
+
const newInput = run2(def.input);
|
|
19985
|
+
const newOutput = run2(def.output);
|
|
19986
19986
|
return newInput === def.input && newOutput === def.output ? s : clone(s, { ...def, input: newInput, output: newOutput });
|
|
19987
19987
|
}
|
|
19988
19988
|
case "lazy": {
|
|
19989
19989
|
const original = def.getter;
|
|
19990
19990
|
const { _cachedInner, ...rest } = def;
|
|
19991
|
-
return clone(s, { ...rest, getter: () =>
|
|
19991
|
+
return clone(s, { ...rest, getter: () => run2(original()) });
|
|
19992
19992
|
}
|
|
19993
19993
|
// A leaf by choice: `parts` are regex fragments, not data positions.
|
|
19994
19994
|
case "template_literal":
|
|
@@ -20019,7 +20019,7 @@ function visit(schema, fnOrHandlers) {
|
|
|
20019
20019
|
}
|
|
20020
20020
|
}
|
|
20021
20021
|
}
|
|
20022
|
-
return
|
|
20022
|
+
return run2(schema);
|
|
20023
20023
|
}
|
|
20024
20024
|
var RESOLVING;
|
|
20025
20025
|
var init_visit = __esm({
|
|
@@ -21950,6 +21950,9 @@ function phrenHookContext(raw, includeSidechain = false) {
|
|
|
21950
21950
|
};
|
|
21951
21951
|
}
|
|
21952
21952
|
function visibleClaudeEvent(raw, includeSidechain = false) {
|
|
21953
|
+
if (raw.type === "phren/fanout-message" && typeof raw.text === "string") {
|
|
21954
|
+
return { type: "user", timestamp: raw.timestamp, message: { role: "user", content: raw.text.slice(0, 65536) } };
|
|
21955
|
+
}
|
|
21953
21956
|
if (raw.type === "queue-operation" && typeof raw.content === "string") raw = { ...raw, content: unwrapPastedContent(raw.content) };
|
|
21954
21957
|
if (raw.type === "queue-operation" && raw.operation === "remove" && typeof raw.content === "string") {
|
|
21955
21958
|
return { type: "phren_queue_consumed", key: createHash2("sha256").update(raw.content).digest("hex"), timestamp: raw.timestamp };
|
|
@@ -22978,7 +22981,7 @@ async function fanoutChildren(parentProvider, parentSession, env = process.env,
|
|
|
22978
22981
|
...blocked ? { reason: blockedReason(blocked) } : asking ? { reason: `needs-you: ${String(asking.message ?? asking.type)}`.slice(0, 500) } : {},
|
|
22979
22982
|
...finishedAt ? { finishedAt } : {},
|
|
22980
22983
|
transcript,
|
|
22981
|
-
fanout: { resumable:
|
|
22984
|
+
fanout: { resumable: manifest.session !== void 0 },
|
|
22982
22985
|
children: []
|
|
22983
22986
|
});
|
|
22984
22987
|
} catch {
|
|
@@ -23230,12 +23233,12 @@ function visibleCodexExecEvent(raw) {
|
|
|
23230
23233
|
} };
|
|
23231
23234
|
}
|
|
23232
23235
|
if (raw.type === "item.completed" && item.type === "file_change") {
|
|
23233
|
-
const files = codexFiles(item),
|
|
23236
|
+
const files = codexFiles(item), header = `${files.length} file(s) changed`;
|
|
23234
23237
|
return { type: "response_item", payload: {
|
|
23235
23238
|
type: "function_call_output",
|
|
23236
23239
|
call_id: callId(),
|
|
23237
|
-
output: files.length ? `${
|
|
23238
|
-
${files.map((file2) => file2.path).join("\n")}` :
|
|
23240
|
+
output: files.length ? `${header}
|
|
23241
|
+
${files.map((file2) => file2.path).join("\n")}` : header
|
|
23239
23242
|
} };
|
|
23240
23243
|
}
|
|
23241
23244
|
if (raw.type === "turn.completed") return { type: "event_msg", payload: { type: "task_complete" } };
|
|
@@ -26629,8 +26632,8 @@ function appendAuditLog(phrenPath, event, details) {
|
|
|
26629
26632
|
fs3.mkdirSync(path11.dirname(logPath), { recursive: true });
|
|
26630
26633
|
withFileLock(logPath, () => {
|
|
26631
26634
|
fs3.appendFileSync(logPath, line);
|
|
26632
|
-
const
|
|
26633
|
-
if (
|
|
26635
|
+
const stat26 = fs3.statSync(logPath);
|
|
26636
|
+
if (stat26.size > 1e6) {
|
|
26634
26637
|
const content = fs3.readFileSync(logPath, "utf8");
|
|
26635
26638
|
const lines = content.split("\n");
|
|
26636
26639
|
fs3.writeFileSync(logPath, lines.slice(-MAX_LOG_LINES).join("\n") + "\n");
|
|
@@ -26719,8 +26722,8 @@ ${Date.now()}`, { flag: "wx" });
|
|
|
26719
26722
|
} catch (err) {
|
|
26720
26723
|
logger.debug("acquireFileLock", `lockWrite: ${errorMessage(err)}`);
|
|
26721
26724
|
try {
|
|
26722
|
-
const
|
|
26723
|
-
if (Date.now() -
|
|
26725
|
+
const stat26 = fs5.statSync(lockPath);
|
|
26726
|
+
if (Date.now() - stat26.mtimeMs > staleThreshold) {
|
|
26724
26727
|
let ownerAlive = false;
|
|
26725
26728
|
try {
|
|
26726
26729
|
const content = fs5.readFileSync(lockPath, "utf-8");
|
|
@@ -27925,13 +27928,22 @@ var init_claude = __esm({
|
|
|
27925
27928
|
"--output-format",
|
|
27926
27929
|
"stream-json",
|
|
27927
27930
|
"--verbose",
|
|
27928
|
-
"--model",
|
|
27929
|
-
|
|
27930
|
-
|
|
27931
|
+
...o.model && o.model !== "default" ? ["--model", o.model] : [],
|
|
27932
|
+
"--permission-mode",
|
|
27933
|
+
o.review ? "plan" : "acceptEdits",
|
|
27931
27934
|
...o.resume ? ["--resume", o.resume] : [],
|
|
27932
27935
|
...o.extra ?? []
|
|
27933
27936
|
],
|
|
27934
|
-
session: (event) => uuid3(event.session_id)
|
|
27937
|
+
session: (event) => uuid3(event.session_id),
|
|
27938
|
+
// It exits 0 after refusing a tool; the result row lists what it refused.
|
|
27939
|
+
refusal: (event) => {
|
|
27940
|
+
const denials = event.type === "result" && Array.isArray(event.permission_denials) ? event.permission_denials : [];
|
|
27941
|
+
const first = denials[0] && typeof denials[0] === "object" ? denials[0] : void 0;
|
|
27942
|
+
if (!first) return void 0;
|
|
27943
|
+
const tool = String(first.tool_name ?? "tool").slice(0, 200), input2 = first.tool_input && typeof first.tool_input === "object" ? first.tool_input : {};
|
|
27944
|
+
const target = String(input2.command ?? input2.file_path ?? input2.path ?? "").slice(0, 500);
|
|
27945
|
+
return { type: "permission", pattern: `${tool} ${target}`.trim(), message: `${denials.length} tool call(s) refused; first: ${tool}` };
|
|
27946
|
+
}
|
|
27935
27947
|
};
|
|
27936
27948
|
}
|
|
27937
27949
|
});
|
|
@@ -27975,6 +27987,7 @@ __export(launcher_exports, {
|
|
|
27975
27987
|
jobsRoot: () => jobsRoot,
|
|
27976
27988
|
launch: () => launch,
|
|
27977
27989
|
listJobs: () => listJobs,
|
|
27990
|
+
nearestAgent: () => nearestAgent,
|
|
27978
27991
|
readJob: () => readJob,
|
|
27979
27992
|
swiftBuildCount: () => swiftBuildCount,
|
|
27980
27993
|
writeManifest: () => writeManifest
|
|
@@ -28010,11 +28023,29 @@ function swiftBuildCount() {
|
|
|
28010
28023
|
const output2 = execFileSync2("ps", ["-axo", "comm="], { encoding: "utf8", timeout: 5e3 });
|
|
28011
28024
|
return output2.split("\n").filter((line) => path19.basename(line.trim()) === "xcodebuild").length;
|
|
28012
28025
|
}
|
|
28026
|
+
function nearestAgent(pid = process.ppid) {
|
|
28027
|
+
if (process.platform === "win32") return void 0;
|
|
28028
|
+
for (let depth = 0; depth < 16 && pid > 1; depth++) {
|
|
28029
|
+
let row;
|
|
28030
|
+
try {
|
|
28031
|
+
row = execFileSync2("ps", ["-o", "ppid=,comm=", "-p", String(pid)], { encoding: "utf8", timeout: 2e3 }).trim();
|
|
28032
|
+
} catch {
|
|
28033
|
+
return void 0;
|
|
28034
|
+
}
|
|
28035
|
+
const match = /^(\d+)\s+(.+)$/.exec(row);
|
|
28036
|
+
if (!match) return void 0;
|
|
28037
|
+
const name = path19.basename(match[2].trim());
|
|
28038
|
+
if (name === "claude") return "claude";
|
|
28039
|
+
if (name === "codex" || name.startsWith("codex-")) return "codex";
|
|
28040
|
+
pid = Number(match[1]);
|
|
28041
|
+
}
|
|
28042
|
+
return void 0;
|
|
28043
|
+
}
|
|
28013
28044
|
function writeManifest(job, manifest) {
|
|
28014
28045
|
atomicWriteText(path19.join(job, "manifest.json"), JSON.stringify(manifestSchema.parse(manifest)) + "\n");
|
|
28015
28046
|
fs11.chmodSync(path19.join(job, "manifest.json"), 384);
|
|
28016
28047
|
}
|
|
28017
|
-
function createJob(options, env = process.env) {
|
|
28048
|
+
function createJob(options, env = process.env, nearest = nearestAgent) {
|
|
28018
28049
|
if (!options.label.trim() || options.label.length > 200) throw new Error("Choose a label of 1 to 200 characters.");
|
|
28019
28050
|
const worktree = fs11.realpathSync(options.worktree);
|
|
28020
28051
|
if (!fs11.statSync(worktree).isDirectory()) throw new Error("Choose a worktree directory.");
|
|
@@ -28022,7 +28053,9 @@ function createJob(options, env = process.env) {
|
|
|
28022
28053
|
const root = jobsRoot(options.store), job = path19.join(root, id2);
|
|
28023
28054
|
fs11.mkdirSync(job, { recursive: true, mode: 448 });
|
|
28024
28055
|
fs11.chmodSync(root, 448);
|
|
28025
|
-
const
|
|
28056
|
+
const claudeParent = uuid3(env.CLAUDE_CODE_SESSION_ID);
|
|
28057
|
+
let codexParent = uuid3(env.CODEX_THREAD_ID || env.CODEX_SESSION_ID);
|
|
28058
|
+
if (codexParent && claudeParent && nearest() === "claude") codexParent = void 0;
|
|
28026
28059
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
28027
28060
|
const manifest = {
|
|
28028
28061
|
schemaVersion: 1,
|
|
@@ -28062,6 +28095,7 @@ async function launch(options, reservation = createJob(options)) {
|
|
|
28062
28095
|
detached: process.platform !== "win32"
|
|
28063
28096
|
});
|
|
28064
28097
|
let pending = "", stderr = "", cancelled = false;
|
|
28098
|
+
let refused;
|
|
28065
28099
|
const watchdog = new LoopWatchdog();
|
|
28066
28100
|
const kill = () => {
|
|
28067
28101
|
try {
|
|
@@ -28092,6 +28126,7 @@ async function launch(options, reservation = createJob(options)) {
|
|
|
28092
28126
|
const event = JSON.parse(line);
|
|
28093
28127
|
watchdog.observe(event);
|
|
28094
28128
|
record2(adapter.session(event));
|
|
28129
|
+
refused ??= adapter.refusal?.(event);
|
|
28095
28130
|
} catch {
|
|
28096
28131
|
}
|
|
28097
28132
|
}
|
|
@@ -28138,7 +28173,7 @@ async function launch(options, reservation = createJob(options)) {
|
|
|
28138
28173
|
for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) process.off(signal, cancel);
|
|
28139
28174
|
fs11.closeSync(out);
|
|
28140
28175
|
fs11.closeSync(err);
|
|
28141
|
-
const blockedFile = path19.join(job, "blocked.json"), refusal = stderrRefusal(stderr);
|
|
28176
|
+
const blockedFile = path19.join(job, "blocked.json"), refusal = refused ?? stderrRefusal(stderr);
|
|
28142
28177
|
if (refusal && !fs11.existsSync(blockedFile)) atomicWriteText(blockedFile, JSON.stringify({ ...refusal, at: (/* @__PURE__ */ new Date()).toISOString() }));
|
|
28143
28178
|
const blocked = fs11.existsSync(blockedFile);
|
|
28144
28179
|
if (blocked) console.error(`blocked: ${fs11.readFileSync(blockedFile, "utf8").slice(0, 4e3)}`);
|
|
@@ -28410,12 +28445,12 @@ function writeProfile(file2, name, projects, description) {
|
|
|
28410
28445
|
if (!line.startsWith("#") && line.trim() !== "") break;
|
|
28411
28446
|
headerLines.push(line);
|
|
28412
28447
|
}
|
|
28413
|
-
const
|
|
28448
|
+
const header = headerLines.length ? `${headerLines.join("\n").replace(/\n+$/, "")}
|
|
28414
28449
|
` : "";
|
|
28415
28450
|
const normalized = [...new Set(projects)].sort();
|
|
28416
28451
|
const out = dump({ name, ...description ? { description } : {}, projects: normalized, ...rest }, { lineWidth: 1e3 });
|
|
28417
28452
|
const tmpPath = `${file2}.tmp-${crypto3.randomUUID()}`;
|
|
28418
|
-
fs14.writeFileSync(tmpPath,
|
|
28453
|
+
fs14.writeFileSync(tmpPath, header + out);
|
|
28419
28454
|
fs14.renameSync(tmpPath, file2);
|
|
28420
28455
|
}
|
|
28421
28456
|
function addProjectToProfile(phrenPath, profile, project) {
|
|
@@ -28468,7 +28503,7 @@ var init_package_metadata = __esm({
|
|
|
28468
28503
|
__dirname = path24.dirname(fileURLToPath2(import.meta.url));
|
|
28469
28504
|
ROOT = path24.join(__dirname, "..");
|
|
28470
28505
|
PACKAGE_JSON_PATH = path24.join(ROOT, "package.json");
|
|
28471
|
-
BUNDLED_VERSION = true ? "0.3.
|
|
28506
|
+
BUNDLED_VERSION = true ? "0.3.11" : "0.0.0";
|
|
28472
28507
|
PACKAGE_JSON = readPackageJson();
|
|
28473
28508
|
PACKAGE_NAME = PACKAGE_JSON.name || "phren";
|
|
28474
28509
|
VERSION = PACKAGE_JSON.version || BUNDLED_VERSION;
|
|
@@ -30562,7 +30597,7 @@ var require_extension = __commonJS({
|
|
|
30562
30597
|
if (dest[name] === void 0) dest[name] = [elem];
|
|
30563
30598
|
else dest[name].push(elem);
|
|
30564
30599
|
}
|
|
30565
|
-
function parse4(
|
|
30600
|
+
function parse4(header) {
|
|
30566
30601
|
const offers = /* @__PURE__ */ Object.create(null);
|
|
30567
30602
|
let params = /* @__PURE__ */ Object.create(null);
|
|
30568
30603
|
let mustUnescape = false;
|
|
@@ -30574,8 +30609,8 @@ var require_extension = __commonJS({
|
|
|
30574
30609
|
let code = -1;
|
|
30575
30610
|
let end = -1;
|
|
30576
30611
|
let i = 0;
|
|
30577
|
-
for (; i <
|
|
30578
|
-
code =
|
|
30612
|
+
for (; i < header.length; i++) {
|
|
30613
|
+
code = header.charCodeAt(i);
|
|
30579
30614
|
if (extensionName === void 0) {
|
|
30580
30615
|
if (end === -1 && tokenChars[code] === 1) {
|
|
30581
30616
|
if (start === -1) start = i;
|
|
@@ -30586,7 +30621,7 @@ var require_extension = __commonJS({
|
|
|
30586
30621
|
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
30587
30622
|
}
|
|
30588
30623
|
if (end === -1) end = i;
|
|
30589
|
-
const name =
|
|
30624
|
+
const name = header.slice(start, end);
|
|
30590
30625
|
if (code === 44) {
|
|
30591
30626
|
push(offers, name, params);
|
|
30592
30627
|
params = /* @__PURE__ */ Object.create(null);
|
|
@@ -30607,7 +30642,7 @@ var require_extension = __commonJS({
|
|
|
30607
30642
|
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
30608
30643
|
}
|
|
30609
30644
|
if (end === -1) end = i;
|
|
30610
|
-
push(params,
|
|
30645
|
+
push(params, header.slice(start, end), true);
|
|
30611
30646
|
if (code === 44) {
|
|
30612
30647
|
push(offers, extensionName, params);
|
|
30613
30648
|
params = /* @__PURE__ */ Object.create(null);
|
|
@@ -30615,7 +30650,7 @@ var require_extension = __commonJS({
|
|
|
30615
30650
|
}
|
|
30616
30651
|
start = end = -1;
|
|
30617
30652
|
} else if (code === 61 && start !== -1 && end === -1) {
|
|
30618
|
-
paramName =
|
|
30653
|
+
paramName = header.slice(start, i);
|
|
30619
30654
|
start = end = -1;
|
|
30620
30655
|
} else {
|
|
30621
30656
|
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
@@ -30639,7 +30674,7 @@ var require_extension = __commonJS({
|
|
|
30639
30674
|
} else {
|
|
30640
30675
|
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
30641
30676
|
}
|
|
30642
|
-
} else if (code === 34 &&
|
|
30677
|
+
} else if (code === 34 && header.charCodeAt(i - 1) === 61) {
|
|
30643
30678
|
inQuotes = true;
|
|
30644
30679
|
} else if (end === -1 && tokenChars[code] === 1) {
|
|
30645
30680
|
if (start === -1) start = i;
|
|
@@ -30650,7 +30685,7 @@ var require_extension = __commonJS({
|
|
|
30650
30685
|
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
30651
30686
|
}
|
|
30652
30687
|
if (end === -1) end = i;
|
|
30653
|
-
let value2 =
|
|
30688
|
+
let value2 = header.slice(start, end);
|
|
30654
30689
|
if (mustUnescape) {
|
|
30655
30690
|
value2 = value2.replace(/\\/g, "");
|
|
30656
30691
|
mustUnescape = false;
|
|
@@ -30672,7 +30707,7 @@ var require_extension = __commonJS({
|
|
|
30672
30707
|
throw new SyntaxError("Unexpected end of input");
|
|
30673
30708
|
}
|
|
30674
30709
|
if (end === -1) end = i;
|
|
30675
|
-
const token =
|
|
30710
|
+
const token = header.slice(start, end);
|
|
30676
30711
|
if (extensionName === void 0) {
|
|
30677
30712
|
push(offers, token, params);
|
|
30678
30713
|
} else {
|
|
@@ -31705,13 +31740,13 @@ var require_subprotocol = __commonJS({
|
|
|
31705
31740
|
"../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/subprotocol.js"(exports, module) {
|
|
31706
31741
|
"use strict";
|
|
31707
31742
|
var { tokenChars } = require_validation();
|
|
31708
|
-
function parse4(
|
|
31743
|
+
function parse4(header) {
|
|
31709
31744
|
const protocols = /* @__PURE__ */ new Set();
|
|
31710
31745
|
let start = -1;
|
|
31711
31746
|
let end = -1;
|
|
31712
31747
|
let i = 0;
|
|
31713
|
-
for (i; i <
|
|
31714
|
-
const code =
|
|
31748
|
+
for (i; i < header.length; i++) {
|
|
31749
|
+
const code = header.charCodeAt(i);
|
|
31715
31750
|
if (end === -1 && tokenChars[code] === 1) {
|
|
31716
31751
|
if (start === -1) start = i;
|
|
31717
31752
|
} else if (i !== 0 && (code === 32 || code === 9)) {
|
|
@@ -31721,7 +31756,7 @@ var require_subprotocol = __commonJS({
|
|
|
31721
31756
|
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
31722
31757
|
}
|
|
31723
31758
|
if (end === -1) end = i;
|
|
31724
|
-
const protocol2 =
|
|
31759
|
+
const protocol2 = header.slice(start, end);
|
|
31725
31760
|
if (protocols.has(protocol2)) {
|
|
31726
31761
|
throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
|
|
31727
31762
|
}
|
|
@@ -31734,7 +31769,7 @@ var require_subprotocol = __commonJS({
|
|
|
31734
31769
|
if (start === -1 || end !== -1) {
|
|
31735
31770
|
throw new SyntaxError("Unexpected end of input");
|
|
31736
31771
|
}
|
|
31737
|
-
const protocol =
|
|
31772
|
+
const protocol = header.slice(start, i);
|
|
31738
31773
|
if (protocols.has(protocol)) {
|
|
31739
31774
|
throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
|
|
31740
31775
|
}
|
|
@@ -32951,14 +32986,14 @@ function opencodePermissionDialog(ansi) {
|
|
|
32951
32986
|
const raw = ansi.split(/\r?\n/);
|
|
32952
32987
|
const plain2 = raw.map((line) => stripTerminal(line).replace(/\r/g, ""));
|
|
32953
32988
|
const content = (line) => line.replace(/^\s*[┃│]?/, "");
|
|
32954
|
-
let
|
|
32989
|
+
let header = -1;
|
|
32955
32990
|
plain2.forEach((line, index2) => {
|
|
32956
|
-
if (/^\s*△\s*Permission required\s*$/.test(content(line)))
|
|
32991
|
+
if (/^\s*△\s*Permission required\s*$/.test(content(line))) header = index2;
|
|
32957
32992
|
});
|
|
32958
|
-
if (
|
|
32959
|
-
const row = plain2.findIndex((line, index2) => index2 >
|
|
32960
|
-
if (row < 0 || row -
|
|
32961
|
-
const body2 = plain2.slice(
|
|
32993
|
+
if (header < 0) return void 0;
|
|
32994
|
+
const row = plain2.findIndex((line, index2) => index2 > header && OPENCODE_OPTIONS.every((label2) => line.includes(label2)));
|
|
32995
|
+
if (row < 0 || row - header > 24) return void 0;
|
|
32996
|
+
const body2 = plain2.slice(header + 1, row).map(content).filter((line) => line.trim() && !/^\s{24,}/.test(line)).map((line) => line.trim());
|
|
32962
32997
|
const [asks, ...rest] = body2;
|
|
32963
32998
|
const title = (asks?.replace(/^[←→]\s*/, "") || "Permission required").slice(0, 4e3);
|
|
32964
32999
|
const patterns = rest.indexOf("Patterns");
|
|
@@ -34598,7 +34633,7 @@ var init_audit = __esm({
|
|
|
34598
34633
|
|
|
34599
34634
|
// src/governance/activity.ts
|
|
34600
34635
|
import * as fs25 from "fs";
|
|
34601
|
-
import * as
|
|
34636
|
+
import * as path58 from "path";
|
|
34602
34637
|
function clampSnippet(snippet) {
|
|
34603
34638
|
if (!snippet) return void 0;
|
|
34604
34639
|
const flat = snippet.replace(/\s+/g, " ").trim();
|
|
@@ -34609,7 +34644,7 @@ function recordLookupEvents(phrenPath, events) {
|
|
|
34609
34644
|
if (!events.length) return;
|
|
34610
34645
|
const logPath = lookupEventsLogFile(phrenPath);
|
|
34611
34646
|
try {
|
|
34612
|
-
fs25.mkdirSync(
|
|
34647
|
+
fs25.mkdirSync(path58.dirname(logPath), { recursive: true });
|
|
34613
34648
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
34614
34649
|
const lines = events.map(
|
|
34615
34650
|
(e) => JSON.stringify({
|
|
@@ -34631,8 +34666,8 @@ function recordLookupEvents(phrenPath, events) {
|
|
|
34631
34666
|
return;
|
|
34632
34667
|
}
|
|
34633
34668
|
try {
|
|
34634
|
-
const
|
|
34635
|
-
if (
|
|
34669
|
+
const stat26 = fs25.statSync(logPath);
|
|
34670
|
+
if (stat26.size > ROTATE_BYTES) {
|
|
34636
34671
|
const content = fs25.readFileSync(logPath, "utf8");
|
|
34637
34672
|
const kept = content.split("\n").filter(Boolean).slice(-MAX_LOG_LINES2);
|
|
34638
34673
|
fs25.writeFileSync(logPath, kept.join("\n") + "\n");
|
|
@@ -34894,7 +34929,7 @@ var init_metadata = __esm({
|
|
|
34894
34929
|
|
|
34895
34930
|
// src/governance/policy.ts
|
|
34896
34931
|
import * as fs26 from "fs";
|
|
34897
|
-
import * as
|
|
34932
|
+
import * as path59 from "path";
|
|
34898
34933
|
function assessSyncOutage(sync, nowMs = Date.now()) {
|
|
34899
34934
|
const consecutiveFailures = sync?.consecutiveFailures ?? 0;
|
|
34900
34935
|
const failingNow = sync?.lastPushStatus !== void 0 && FAILED_PUSH_STATUSES.has(sync.lastPushStatus);
|
|
@@ -35031,7 +35066,7 @@ function normalizeIndexPolicy(data) {
|
|
|
35031
35066
|
function readJsonFile(filePath, fallback) {
|
|
35032
35067
|
try {
|
|
35033
35068
|
if (!fs26.existsSync(filePath)) return fallback;
|
|
35034
|
-
const basename12 =
|
|
35069
|
+
const basename12 = path59.basename(filePath);
|
|
35035
35070
|
const schema = GOVERNANCE_FILE_SCHEMAS[basename12];
|
|
35036
35071
|
if (schema && !validateGovernanceJson(filePath, schema)) {
|
|
35037
35072
|
debugLog(`readJsonFile: ${filePath} failed validation, using defaults`);
|
|
@@ -35164,7 +35199,7 @@ var init_policy = __esm({
|
|
|
35164
35199
|
});
|
|
35165
35200
|
|
|
35166
35201
|
// src/bridge/command.ts
|
|
35167
|
-
import { readFile as
|
|
35202
|
+
import { readFile as readFile36 } from "node:fs/promises";
|
|
35168
35203
|
|
|
35169
35204
|
// src/bridge/fanout-messages.ts
|
|
35170
35205
|
init_zod();
|
|
@@ -35231,7 +35266,7 @@ var FanoutMessages = class {
|
|
|
35231
35266
|
if (!relation?.fanout?.resumable) throw new BridgeError(404, "That resumable worker is not part of this conversation.");
|
|
35232
35267
|
const root = await containedFanoutRoot(this.env);
|
|
35233
35268
|
const job = (await this.jobs()).find((job2) => root && fanoutChildID(root, job2.manifest) === child);
|
|
35234
|
-
if (!job || !job.manifest.session || !["codex", "opencode"].includes(job.manifest.provider)) {
|
|
35269
|
+
if (!job || !job.manifest.session || !["codex", "opencode", "claude"].includes(job.manifest.provider)) {
|
|
35235
35270
|
throw new BridgeError(404, "That worker does not belong to this store.");
|
|
35236
35271
|
}
|
|
35237
35272
|
return job;
|
|
@@ -35314,7 +35349,7 @@ var FanoutMessages = class {
|
|
|
35314
35349
|
try {
|
|
35315
35350
|
const fresh = (await this.jobs()).find((candidate) => candidate.directory === job.directory);
|
|
35316
35351
|
if (!fresh || ["queued", "running"].includes(fresh.manifest.status)) return;
|
|
35317
|
-
if (!fresh.manifest.session || !["codex", "opencode"].includes(fresh.manifest.provider)) return;
|
|
35352
|
+
if (!fresh.manifest.session || !["codex", "opencode", "claude"].includes(fresh.manifest.provider)) return;
|
|
35318
35353
|
const next = (await this.records(fresh)).find((row) => row.message.status === "queued");
|
|
35319
35354
|
if (!next) return;
|
|
35320
35355
|
pending = next;
|
|
@@ -35358,7 +35393,7 @@ var FanoutMessages = class {
|
|
|
35358
35393
|
id: message.id,
|
|
35359
35394
|
text: message.text
|
|
35360
35395
|
}) + "\n", { mode: 384 });
|
|
35361
|
-
const
|
|
35396
|
+
const run2 = this.deps.run ?? (async (job2, text4) => {
|
|
35362
35397
|
const { launch: launch2 } = await Promise.resolve().then(() => (init_launcher(), launcher_exports));
|
|
35363
35398
|
return launch2({
|
|
35364
35399
|
store: storeRoot(this.env),
|
|
@@ -35372,7 +35407,7 @@ var FanoutMessages = class {
|
|
|
35372
35407
|
}, { job: job2.directory, manifest: job2.manifest });
|
|
35373
35408
|
});
|
|
35374
35409
|
launched = true;
|
|
35375
|
-
void
|
|
35410
|
+
void run2({ ...fresh, manifest }, message.text).then(async (code) => {
|
|
35376
35411
|
await atomic(sentFile, JSON.stringify({ ...message, status: code === 0 ? "completed" : "failed" }));
|
|
35377
35412
|
}).catch(async () => {
|
|
35378
35413
|
await atomic(sentFile, JSON.stringify({ ...message, status: "failed" }));
|
|
@@ -35431,9 +35466,9 @@ import * as path23 from "node:path";
|
|
|
35431
35466
|
function gitDirectory(store) {
|
|
35432
35467
|
const dotGit = path23.join(store, ".git");
|
|
35433
35468
|
try {
|
|
35434
|
-
const
|
|
35435
|
-
if (
|
|
35436
|
-
if (!
|
|
35469
|
+
const stat26 = fs15.statSync(dotGit);
|
|
35470
|
+
if (stat26.isDirectory()) return dotGit;
|
|
35471
|
+
if (!stat26.isFile()) return void 0;
|
|
35437
35472
|
const match = /^gitdir:\s*(.+)\s*$/i.exec(fs15.readFileSync(dotGit, "utf8"));
|
|
35438
35473
|
if (!match) return void 0;
|
|
35439
35474
|
return path23.resolve(store, match[1]);
|
|
@@ -35468,7 +35503,7 @@ import * as fs17 from "node:fs";
|
|
|
35468
35503
|
import * as path25 from "node:path";
|
|
35469
35504
|
var core = (names) => names.map((name) => ({ name, profiles: ["core", "full"] }));
|
|
35470
35505
|
var full = (names) => names.map((name) => ({ name, profiles: ["full"] }));
|
|
35471
|
-
var routes = (method, paths) => paths.map((
|
|
35506
|
+
var routes = (method, paths) => paths.map((path87) => ({ method, path: path87 }));
|
|
35472
35507
|
var BUILTIN_MODULES = [
|
|
35473
35508
|
{
|
|
35474
35509
|
schemaVersion: 1,
|
|
@@ -35665,7 +35700,10 @@ var BUILTIN_MODULES = [
|
|
|
35665
35700
|
"bridge ssh",
|
|
35666
35701
|
"pair",
|
|
35667
35702
|
"bridge fanouts archive",
|
|
35668
|
-
"canary"
|
|
35703
|
+
"canary",
|
|
35704
|
+
"computers",
|
|
35705
|
+
"computers mcp",
|
|
35706
|
+
"usage"
|
|
35669
35707
|
],
|
|
35670
35708
|
agentHooks: [
|
|
35671
35709
|
{ agents: ["codex", "claude"], events: ["SessionStart", "UserPromptSubmit", "Stop", "PermissionRequest"], handler: "bridge-hook.mjs hook <agent>" },
|
|
@@ -35690,6 +35728,7 @@ var BUILTIN_MODULES = [
|
|
|
35690
35728
|
"/v1/uploads/image",
|
|
35691
35729
|
"/v1/files/range",
|
|
35692
35730
|
"/v1/usage",
|
|
35731
|
+
"/v1/resources",
|
|
35693
35732
|
"/v1/push/status",
|
|
35694
35733
|
"/v1/projects/locate",
|
|
35695
35734
|
"/v1/projects/repos",
|
|
@@ -35755,7 +35794,8 @@ var BUILTIN_MODULES = [
|
|
|
35755
35794
|
"speech",
|
|
35756
35795
|
"speechTimestamps",
|
|
35757
35796
|
"transcribe",
|
|
35758
|
-
"promptOnce"
|
|
35797
|
+
"promptOnce",
|
|
35798
|
+
"resources"
|
|
35759
35799
|
],
|
|
35760
35800
|
storeFiles: [".runtime/sessions/opencode-*.events.jsonl", ".runtime/approvals/opencode-*.json"],
|
|
35761
35801
|
localFiles: ["<bridge>/installed.json", "<bridge>/versions/**", "<bridge>/current", "<bridge>/dispatch", "<bridge>/computer-id", "<bridge>/canary.json", "<bridge>/canary-daily"],
|
|
@@ -35987,11 +36027,11 @@ function activateModules(store, profile = snapshotProfile(store), legacyHook = f
|
|
|
35987
36027
|
|
|
35988
36028
|
// src/bridge/server.ts
|
|
35989
36029
|
import { randomUUID as randomUUID19 } from "node:crypto";
|
|
35990
|
-
import { chmod as chmod5, lstat as lstat20, mkdir as mkdir21, readFile as
|
|
36030
|
+
import { chmod as chmod5, lstat as lstat20, mkdir as mkdir21, readFile as readFile34, rm as rm10, unlink as unlink7, writeFile as writeFile11 } from "node:fs/promises";
|
|
35991
36031
|
import { readFileSync as readFileSync32 } from "node:fs";
|
|
35992
36032
|
import { createServer as createServer2 } from "node:http";
|
|
35993
|
-
import { cpus, hostname as hostname9, loadavg } from "node:os";
|
|
35994
|
-
import
|
|
36033
|
+
import { cpus as cpus2, hostname as hostname9, loadavg as loadavg2 } from "node:os";
|
|
36034
|
+
import path85 from "node:path";
|
|
35995
36035
|
|
|
35996
36036
|
// ../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/wrapper.mjs
|
|
35997
36037
|
var import_stream = __toESM(require_stream(), 1);
|
|
@@ -36610,9 +36650,9 @@ var APNsSender = class {
|
|
|
36610
36650
|
token() {
|
|
36611
36651
|
const created = Math.floor(this.now() / 1e3);
|
|
36612
36652
|
if (this.jwt && created - this.jwt.created < 50 * 60) return this.jwt.value;
|
|
36613
|
-
const
|
|
36653
|
+
const header = base64url3(JSON.stringify({ alg: "ES256", kid: this.config.keyId }));
|
|
36614
36654
|
const claims = base64url3(JSON.stringify({ iss: this.config.teamId, iat: created }));
|
|
36615
|
-
const input2 = `${
|
|
36655
|
+
const input2 = `${header}.${claims}`;
|
|
36616
36656
|
const signature = sign("sha256", Buffer.from(input2), { key: createPrivateKey(this.key), dsaEncoding: "ieee-p1363" });
|
|
36617
36657
|
const value2 = `${input2}.${base64url3(signature)}`;
|
|
36618
36658
|
this.jwt = { value: value2, created };
|
|
@@ -38556,7 +38596,7 @@ var CodeRoutes = class {
|
|
|
38556
38596
|
const project = projectSchema.parse(projectValue ?? "");
|
|
38557
38597
|
const { codeDatabasePath } = await requireCodePackage(this.store);
|
|
38558
38598
|
const file2 = codeDatabasePath(this.store, project);
|
|
38559
|
-
await Promise.all([file2, `${file2}-journal`, `${file2}-wal`, `${file2}-shm`].map((
|
|
38599
|
+
await Promise.all([file2, `${file2}-journal`, `${file2}-wal`, `${file2}-shm`].map((path87) => rm4(path87, { force: true })));
|
|
38560
38600
|
return { project, disabled: true };
|
|
38561
38601
|
}
|
|
38562
38602
|
async reindex(projectValue) {
|
|
@@ -38761,10 +38801,10 @@ var ContextUsageReader = class {
|
|
|
38761
38801
|
const metadata = await handle.stat();
|
|
38762
38802
|
if (!metadata.isFile()) return void 0;
|
|
38763
38803
|
const key2 = `codex:${session}:${file2}`;
|
|
38764
|
-
const
|
|
38804
|
+
const stat26 = `${metadata.dev}:${metadata.ino}:${metadata.size}:${metadata.mtimeMs}:${metadata.ctimeMs}`;
|
|
38765
38805
|
const cached2 = this.cache.get(key2);
|
|
38766
38806
|
this.cache.delete(key2);
|
|
38767
|
-
if (cached2?.stat ===
|
|
38807
|
+
if (cached2?.stat === stat26) {
|
|
38768
38808
|
this.cache.set(key2, cached2);
|
|
38769
38809
|
return cached2.percent;
|
|
38770
38810
|
}
|
|
@@ -38775,7 +38815,7 @@ var ContextUsageReader = class {
|
|
|
38775
38815
|
const after = await handle.stat();
|
|
38776
38816
|
if (after.size !== metadata.size || after.mtimeMs !== metadata.mtimeMs || after.ctimeMs !== metadata.ctimeMs) return void 0;
|
|
38777
38817
|
const percent = codexContext(tail, start === 0);
|
|
38778
|
-
this.cache.set(key2, { stat:
|
|
38818
|
+
this.cache.set(key2, { stat: stat26, percent });
|
|
38779
38819
|
while (this.cache.size > MAX_SESSIONS) this.cache.delete(this.cache.keys().next().value);
|
|
38780
38820
|
return percent;
|
|
38781
38821
|
} finally {
|
|
@@ -38852,7 +38892,7 @@ init_zod();
|
|
|
38852
38892
|
init_logger();
|
|
38853
38893
|
init_project_config();
|
|
38854
38894
|
import { randomUUID as randomUUID9 } from "node:crypto";
|
|
38855
|
-
import { lstat as lstat12, mkdir as mkdir12, readFile as readFile21, readdir as readdir10, realpath as
|
|
38895
|
+
import { lstat as lstat12, mkdir as mkdir12, readFile as readFile21, readdir as readdir10, realpath as realpath9, stat as stat14 } from "node:fs/promises";
|
|
38856
38896
|
import path51 from "node:path";
|
|
38857
38897
|
|
|
38858
38898
|
// src/bridge/computers.ts
|
|
@@ -38868,12 +38908,12 @@ import { execFile as execFile8 } from "node:child_process";
|
|
|
38868
38908
|
|
|
38869
38909
|
// src/bridge/usage.ts
|
|
38870
38910
|
init_home_paths();
|
|
38871
|
-
init_fanouts();
|
|
38872
38911
|
init_protocol();
|
|
38873
38912
|
init_terminal_text();
|
|
38874
38913
|
import { execFile as execFile7, spawn as spawn2 } from "node:child_process";
|
|
38875
38914
|
import { createHash as createHash9 } from "node:crypto";
|
|
38876
|
-
import {
|
|
38915
|
+
import { statSync as statSync13 } from "node:fs";
|
|
38916
|
+
import { lstat as lstat8, open as open9, readFile as readFile17, readdir as readdir9 } from "node:fs/promises";
|
|
38877
38917
|
import { homedir as homedir11 } from "node:os";
|
|
38878
38918
|
import path45 from "node:path";
|
|
38879
38919
|
import { promisify as promisify6 } from "node:util";
|
|
@@ -38988,8 +39028,8 @@ async function readOpenRouterKey() {
|
|
|
38988
39028
|
try {
|
|
38989
39029
|
const handle = await open9(openCodeAuthFile(), "r");
|
|
38990
39030
|
try {
|
|
38991
|
-
const
|
|
38992
|
-
if (!
|
|
39031
|
+
const stat26 = await handle.stat();
|
|
39032
|
+
if (!stat26.isFile() || stat26.size > 65536) return void 0;
|
|
38993
39033
|
const key2 = object2(object2(JSON.parse(await handle.readFile("utf8"))).openrouter).key;
|
|
38994
39034
|
return typeof key2 === "string" && key2.length >= 16 && key2.length <= 4096 && !/[\x00-\x1f\x7f]/.test(key2) ? key2 : void 0;
|
|
38995
39035
|
} finally {
|
|
@@ -39014,309 +39054,114 @@ async function readOpenCodeGoKey() {
|
|
|
39014
39054
|
return void 0;
|
|
39015
39055
|
}
|
|
39016
39056
|
}
|
|
39017
|
-
var goPeriods = [
|
|
39018
|
-
{ id: "5h", label: "5h", milliseconds: 5 * 60 * 60 * 1e3 },
|
|
39019
|
-
{ id: "7d", label: "7d", milliseconds: 7 * 24 * 60 * 60 * 1e3 },
|
|
39020
|
-
{ id: "30d", label: "30d", milliseconds: 30 * 24 * 60 * 60 * 1e3 }
|
|
39021
|
-
];
|
|
39022
39057
|
var GO_GATEWAY = "https://opencode.ai/zen/go/v1";
|
|
39023
|
-
var MAX_GO_JOBS = 128;
|
|
39024
|
-
var MAX_GO_MANIFEST_BYTES = 64 * 1024;
|
|
39025
|
-
var MAX_GO_EVENTS_BYTES = 64 * 1024 * 1024;
|
|
39026
39058
|
var GO_KEY_MESSAGE = "Connect OpenCode Go on this computer to see its usage.";
|
|
39027
|
-
|
|
39028
|
-
|
|
39029
|
-
|
|
39030
|
-
|
|
39031
|
-
|
|
39032
|
-
|
|
39033
|
-
|
|
39034
|
-
|
|
39035
|
-
|
|
39036
|
-
|
|
39037
|
-
|
|
39038
|
-
|
|
39039
|
-
"
|
|
39040
|
-
|
|
39041
|
-
|
|
39042
|
-
|
|
39043
|
-
|
|
39044
|
-
"window",
|
|
39045
|
-
"period",
|
|
39046
|
-
"monthly",
|
|
39047
|
-
"weekly",
|
|
39048
|
-
"5h",
|
|
39049
|
-
"7d",
|
|
39050
|
-
"30d",
|
|
39051
|
-
"fivehour",
|
|
39052
|
-
"seven_day",
|
|
39053
|
-
"month",
|
|
39054
|
-
"limit",
|
|
39055
|
-
"quota",
|
|
39056
|
-
"max",
|
|
39057
|
-
"plan",
|
|
39058
|
-
"account",
|
|
39059
|
-
"rate",
|
|
39060
|
-
"ratelimit",
|
|
39061
|
-
"ratelimits",
|
|
39062
|
-
"remaining",
|
|
39063
|
-
"reset"
|
|
39064
|
-
]);
|
|
39065
|
-
return allowBare && /^[A-Za-z0-9][A-Za-z0-9._/-]{0,190}$/.test(model) && !reserved.has(model.toLowerCase()) ? `opencode-go/${model}` : void 0;
|
|
39066
|
-
}
|
|
39067
|
-
function amount(value2) {
|
|
39068
|
-
return typeof value2 === "number" && Number.isFinite(value2) && value2 >= 0 && value2 <= 1e9 ? value2 : void 0;
|
|
39069
|
-
}
|
|
39070
|
-
function resetAt(value2) {
|
|
39071
|
-
if (typeof value2 === "string" && Number.isFinite(Date.parse(value2))) return new Date(value2).toISOString();
|
|
39072
|
-
if (typeof value2 === "string" && /^\d+(?:\.\d+)?$/.test(value2)) return resetAt(Number(value2));
|
|
39073
|
-
if (typeof value2 === "number" && Number.isFinite(value2) && value2 > 0 && value2 < 3250368e4) {
|
|
39074
|
-
return new Date(value2 * 1e3).toISOString();
|
|
39075
|
-
}
|
|
39076
|
-
return void 0;
|
|
39077
|
-
}
|
|
39078
|
-
function recordGoLimit(limits, model, period, limitUSD, resetsAt) {
|
|
39079
|
-
if (limitUSD === void 0 || limitUSD <= 0) return;
|
|
39080
|
-
const current2 = limits.get(model) ?? {};
|
|
39081
|
-
const existing = current2[period];
|
|
39082
|
-
current2[period] = existing ? { ...existing, ...existing.resetsAt ? {} : { resetsAt } } : { limitUSD, resetsAt };
|
|
39083
|
-
limits.set(model, current2);
|
|
39084
|
-
}
|
|
39085
|
-
function numberFrom(value2, names) {
|
|
39086
|
-
for (const name of names) {
|
|
39087
|
-
const found = amount(value2[name]);
|
|
39088
|
-
if (found !== void 0) return found;
|
|
39089
|
-
}
|
|
39090
|
-
return void 0;
|
|
39091
|
-
}
|
|
39092
|
-
function parseGoLimits(value2, limits, model, period, depth = 0) {
|
|
39093
|
-
if (depth > 8) return;
|
|
39094
|
-
if (typeof value2 === "number") {
|
|
39095
|
-
if (period) recordGoLimit(limits, model ?? "*", period, amount(value2));
|
|
39096
|
-
return;
|
|
39097
|
-
}
|
|
39098
|
-
if (Array.isArray(value2)) {
|
|
39099
|
-
for (const item2 of value2.slice(0, 64)) parseGoLimits(item2, limits, model, period, depth + 1);
|
|
39100
|
-
return;
|
|
39101
|
-
}
|
|
39102
|
-
const item = object2(value2);
|
|
39103
|
-
if (!Object.keys(item).length) return;
|
|
39104
|
-
const nestedModel = goModel(item.model, true) ?? goModel(item.modelId, true) ?? goModel(item.model_id, true) ?? model;
|
|
39105
|
-
const nestedPeriod = goPeriod(item.window) ?? goPeriod(item.period) ?? goPeriod(item.interval) ?? goPeriod(item.windowName) ?? period;
|
|
39106
|
-
const limitUSD = numberFrom(item, ["limitUSD", "limit_usd", "dollarLimit", "dollar_limit", "creditLimit", "credit_limit", "limit", "quota", "max"]);
|
|
39107
|
-
const reset = resetAt(item.resetsAt) ?? resetAt(item.resets_at) ?? resetAt(item.resetAt) ?? resetAt(item.reset_at);
|
|
39108
|
-
if (nestedPeriod) recordGoLimit(limits, nestedModel ?? "*", nestedPeriod, limitUSD, reset);
|
|
39109
|
-
for (const [key2, nested] of Object.entries(item).slice(0, 64)) {
|
|
39110
|
-
const keyPeriod = goPeriod(key2) ?? nestedPeriod;
|
|
39111
|
-
const keyModel = goModel(key2) ?? nestedModel ?? (typeof nested === "object" && !keyPeriod ? goModel(key2, true) : void 0);
|
|
39112
|
-
if (typeof nested !== "object" && typeof nested !== "number") continue;
|
|
39113
|
-
parseGoLimits(nested, limits, keyModel, keyPeriod, depth + 1);
|
|
39114
|
-
}
|
|
39115
|
-
}
|
|
39116
|
-
function completeGoLimits(limits) {
|
|
39117
|
-
for (const [model, windows] of limits) {
|
|
39118
|
-
const monthly = windows["30d"]?.limitUSD ?? (windows["7d"] ? windows["7d"].limitUSD * 2 : windows["5h"] ? windows["5h"].limitUSD * 5 : void 0);
|
|
39119
|
-
if (!monthly || !Number.isFinite(monthly) || monthly <= 0) continue;
|
|
39120
|
-
recordGoLimit(limits, model, "5h", monthly * 0.2);
|
|
39121
|
-
recordGoLimit(limits, model, "7d", monthly * 0.5);
|
|
39122
|
-
recordGoLimit(limits, model, "30d", monthly);
|
|
39123
|
-
}
|
|
39124
|
-
}
|
|
39125
|
-
function header(response, name) {
|
|
39126
|
-
try {
|
|
39127
|
-
return response.headers.get(name) ?? void 0;
|
|
39128
|
-
} catch {
|
|
39129
|
-
return void 0;
|
|
39130
|
-
}
|
|
39131
|
-
}
|
|
39132
|
-
function parseGoHeaders(response, limits) {
|
|
39133
|
-
const limit = amount(Number(header(response, "x-ratelimit-limit")));
|
|
39134
|
-
const remaining = amount(Number(header(response, "x-ratelimit-remaining")));
|
|
39135
|
-
if (limit === void 0 || remaining === void 0 || remaining > limit) return;
|
|
39136
|
-
const period = goPeriod(header(response, "x-ratelimit-window"));
|
|
39137
|
-
const reset = resetAt(header(response, "x-ratelimit-reset"));
|
|
39138
|
-
recordGoLimit(limits, "*", period ?? "30d", limit, reset);
|
|
39139
|
-
}
|
|
39140
|
-
async function fetchOpenCodeGoLimits(key2, fetchImpl = fetch) {
|
|
39059
|
+
var GO_WINDOWS = [
|
|
39060
|
+
{ key: "rolling", id: "opencode-go:plan:5h", name: "5-hour limit" },
|
|
39061
|
+
{ key: "weekly", id: "opencode-go:plan:7d", name: "Weekly limit" },
|
|
39062
|
+
{ key: "monthly", id: "opencode-go:plan:30d", name: "Monthly limit" }
|
|
39063
|
+
];
|
|
39064
|
+
function openCodeGoPlan(value2) {
|
|
39065
|
+
const usage = object2(object2(value2).usage);
|
|
39066
|
+
return GO_WINDOWS.flatMap(({ key: key2, id: id2, name }) => {
|
|
39067
|
+
const item = object2(usage[key2]);
|
|
39068
|
+
const percent = item.percent;
|
|
39069
|
+
if (typeof percent !== "number" || !Number.isFinite(percent) || percent < 0 || percent > 100) return [];
|
|
39070
|
+
const resetsAt = typeof item.resetsAt === "string" && Number.isFinite(Date.parse(item.resetsAt)) ? new Date(item.resetsAt).toISOString() : void 0;
|
|
39071
|
+
const limited = typeof item.status === "string" && item.status !== "ok";
|
|
39072
|
+
return [{ id: id2, name, usedPercent: Math.round(percent * 10) / 10, ...resetsAt ? { resetsAt } : {}, ...limited ? { limited: true } : {} }];
|
|
39073
|
+
});
|
|
39074
|
+
}
|
|
39075
|
+
async function fetchOpenCodeGoPlan(key2, fetchImpl = fetch) {
|
|
39141
39076
|
const controller = new AbortController();
|
|
39142
39077
|
const timer = setTimeout(() => controller.abort(), 8e3);
|
|
39143
|
-
const limits = /* @__PURE__ */ new Map();
|
|
39144
39078
|
try {
|
|
39145
|
-
const
|
|
39146
|
-
|
|
39147
|
-
|
|
39148
|
-
|
|
39149
|
-
|
|
39150
|
-
|
|
39151
|
-
|
|
39152
|
-
method,
|
|
39153
|
-
headers: { authorization: `Bearer ${key2}`, accept: "application/json" },
|
|
39154
|
-
redirect: "error",
|
|
39155
|
-
signal: controller.signal
|
|
39156
|
-
});
|
|
39157
|
-
if (!response.ok) return;
|
|
39158
|
-
parseGoHeaders(response, limits);
|
|
39159
|
-
if (method === "GET") {
|
|
39160
|
-
try {
|
|
39161
|
-
parseGoLimits(await response.json(), limits);
|
|
39162
|
-
} catch {
|
|
39163
|
-
}
|
|
39164
|
-
}
|
|
39165
|
-
}));
|
|
39166
|
-
void responses;
|
|
39079
|
+
const response = await fetchImpl(`${GO_GATEWAY}/usage`, {
|
|
39080
|
+
headers: { authorization: `Bearer ${key2}`, accept: "application/json" },
|
|
39081
|
+
redirect: "error",
|
|
39082
|
+
signal: controller.signal
|
|
39083
|
+
});
|
|
39084
|
+
if (!response.ok) throw new Error(`OpenCode Go usage returned ${response.status}.`);
|
|
39085
|
+
return openCodeGoPlan(await response.json());
|
|
39167
39086
|
} finally {
|
|
39168
39087
|
clearTimeout(timer);
|
|
39169
39088
|
}
|
|
39170
|
-
completeGoLimits(limits);
|
|
39171
|
-
return limits;
|
|
39172
|
-
}
|
|
39173
|
-
async function containedRegularFile(root, candidate, maximum) {
|
|
39174
|
-
try {
|
|
39175
|
-
const link = await lstat8(candidate);
|
|
39176
|
-
if (!link.isFile() || link.isSymbolicLink() || link.size > maximum) return void 0;
|
|
39177
|
-
const resolved = await realpath9(candidate);
|
|
39178
|
-
if (!resolved.startsWith(root + path45.sep)) return void 0;
|
|
39179
|
-
const metadata = await stat14(resolved);
|
|
39180
|
-
return metadata.isFile() && metadata.size <= maximum ? resolved : void 0;
|
|
39181
|
-
} catch {
|
|
39182
|
-
return void 0;
|
|
39183
|
-
}
|
|
39184
|
-
}
|
|
39185
|
-
function goEventTime(value2) {
|
|
39186
|
-
const raw = value2.timestamp ?? value2.time ?? value2.createdAt ?? value2.created_at;
|
|
39187
|
-
if (typeof raw === "string" && Number.isFinite(Date.parse(raw))) return Date.parse(raw);
|
|
39188
|
-
if (typeof raw !== "number" || !Number.isFinite(raw) || raw <= 0) return void 0;
|
|
39189
|
-
return raw < 3250368e4 ? raw * 1e3 : raw;
|
|
39190
|
-
}
|
|
39191
|
-
function goTokenCount(value2, depth = 0) {
|
|
39192
|
-
if (depth > 5) return 0;
|
|
39193
|
-
if (typeof value2 === "number") return Number.isFinite(value2) && value2 >= 0 && value2 <= 1e10 ? value2 : 0;
|
|
39194
|
-
const item = object2(value2);
|
|
39195
|
-
const total = amount(item.total) ?? amount(item.totalTokens) ?? amount(item.total_tokens);
|
|
39196
|
-
if (total !== void 0) return total;
|
|
39197
|
-
return Object.values(item).reduce((sum, part) => sum + goTokenCount(part, depth + 1), 0);
|
|
39198
|
-
}
|
|
39199
|
-
function goStepCost(event, part) {
|
|
39200
|
-
const raw = part.cost ?? event.cost;
|
|
39201
|
-
if (typeof raw === "number") return amount(raw);
|
|
39202
|
-
const cost = object2(raw);
|
|
39203
|
-
return numberFrom(cost, ["total", "amount", "usd", "cost"]);
|
|
39204
39089
|
}
|
|
39205
|
-
|
|
39206
|
-
|
|
39207
|
-
|
|
39208
|
-
|
|
39209
|
-
|
|
39210
|
-
|
|
39211
|
-
|
|
39212
|
-
|
|
39213
|
-
|
|
39214
|
-
|
|
39215
|
-
|
|
39216
|
-
|
|
39217
|
-
if (
|
|
39218
|
-
|
|
39219
|
-
try {
|
|
39220
|
-
manifest = object2(JSON.parse(await readFile17(manifestFile, "utf8")));
|
|
39221
|
-
} catch {
|
|
39222
|
-
continue;
|
|
39223
|
-
}
|
|
39224
|
-
const model = goModel(manifest.model);
|
|
39225
|
-
const eventLog = typeof manifest.eventLog === "string" && /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}\.jsonl$/.test(manifest.eventLog) ? manifest.eventLog : void 0;
|
|
39226
|
-
if (manifest.provider !== "opencode" || !model || !eventLog) continue;
|
|
39227
|
-
const jobRoot = await realpath9(path45.join(directory, name)).catch(() => void 0);
|
|
39228
|
-
if (!jobRoot || !jobRoot.startsWith(directory + path45.sep)) continue;
|
|
39229
|
-
const eventsFile = await containedRegularFile(jobRoot, path45.join(jobRoot, eventLog), MAX_GO_EVENTS_BYTES);
|
|
39230
|
-
if (!eventsFile) continue;
|
|
39231
|
-
let events;
|
|
39232
|
-
try {
|
|
39233
|
-
events = await readFile17(eventsFile, "utf8");
|
|
39234
|
-
} catch {
|
|
39235
|
-
continue;
|
|
39236
|
-
}
|
|
39237
|
-
for (const line of events.split("\n")) {
|
|
39238
|
-
if (!line || Buffer.byteLength(line) > 1048576) continue;
|
|
39239
|
-
let event;
|
|
39090
|
+
var openCodeLogDir = () => path45.join(process.env.OPENCODE_DATA_DIR || path45.join(process.env.XDG_DATA_HOME || path45.join(homedir11(), ".local/share"), "opencode"), "log");
|
|
39091
|
+
var refusalScans = /* @__PURE__ */ new Map();
|
|
39092
|
+
var FIRST_SCAN_BYTES = 64 * 1048576;
|
|
39093
|
+
async function readGoRefusals(now = /* @__PURE__ */ new Date(), withinMs = 24 * 36e5, root = openCodeLogDir()) {
|
|
39094
|
+
const since = now.getTime() - withinMs;
|
|
39095
|
+
const events = [];
|
|
39096
|
+
for (const name of (await readdir9(root).catch(() => [])).filter((name2) => name2.endsWith(".log")).slice(0, 32)) {
|
|
39097
|
+
const file2 = path45.join(root, name);
|
|
39098
|
+
const info = await lstat8(file2).catch(() => void 0);
|
|
39099
|
+
if (!info?.isFile() || info.isSymbolicLink() || info.mtimeMs < since) continue;
|
|
39100
|
+
let scan = refusalScans.get(file2);
|
|
39101
|
+
if (!scan || scan.ino !== info.ino || scan.offset > info.size) scan = { ino: info.ino, offset: Math.max(0, info.size - FIRST_SCAN_BYTES), events: [] };
|
|
39102
|
+
if (info.size > scan.offset) {
|
|
39103
|
+
const handle = await open9(file2, "r");
|
|
39240
39104
|
try {
|
|
39241
|
-
|
|
39242
|
-
|
|
39243
|
-
|
|
39244
|
-
|
|
39245
|
-
|
|
39246
|
-
|
|
39247
|
-
|
|
39248
|
-
|
|
39249
|
-
|
|
39250
|
-
|
|
39251
|
-
|
|
39252
|
-
|
|
39253
|
-
|
|
39254
|
-
"30d": { usedUSD: 0, usedTokens: 0 }
|
|
39255
|
-
};
|
|
39256
|
-
const usedUSD = modelTotals[period.id].usedUSD + (cost ?? 0);
|
|
39257
|
-
if (usedUSD > 1e9) continue;
|
|
39258
|
-
modelTotals[period.id].usedUSD = usedUSD;
|
|
39259
|
-
modelTotals[period.id].usedTokens += tokens;
|
|
39260
|
-
totals.set(model, modelTotals);
|
|
39105
|
+
const length = Math.min(info.size - scan.offset, FIRST_SCAN_BYTES), bytes = Buffer.alloc(length);
|
|
39106
|
+
await handle.read(bytes, 0, length, info.size - length);
|
|
39107
|
+
const text4 = bytes.toString("utf8");
|
|
39108
|
+
const complete = text4.lastIndexOf("\n") + 1;
|
|
39109
|
+
for (const line of text4.slice(0, complete).split("\n")) {
|
|
39110
|
+
if (!line.includes("Go usage limit exceeded")) continue;
|
|
39111
|
+
const stamp = /timestamp=(\S+)/.exec(line)?.[1] ?? /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z/.exec(line)?.[0];
|
|
39112
|
+
const at = stamp ? Date.parse(stamp) : NaN;
|
|
39113
|
+
if (Number.isFinite(at)) scan.events.push({ at, model: /modelID=([A-Za-z0-9._\/-]{1,120})/.exec(line)?.[1] });
|
|
39114
|
+
}
|
|
39115
|
+
scan.offset = info.size - length + complete;
|
|
39116
|
+
} finally {
|
|
39117
|
+
await handle.close();
|
|
39261
39118
|
}
|
|
39262
39119
|
}
|
|
39263
|
-
|
|
39264
|
-
|
|
39265
|
-
|
|
39266
|
-
|
|
39267
|
-
|
|
39268
|
-
|
|
39269
|
-
|
|
39270
|
-
return
|
|
39271
|
-
}
|
|
39272
|
-
|
|
39273
|
-
|
|
39274
|
-
|
|
39275
|
-
|
|
39276
|
-
|
|
39277
|
-
|
|
39278
|
-
|
|
39279
|
-
|
|
39280
|
-
|
|
39281
|
-
|
|
39282
|
-
|
|
39283
|
-
|
|
39284
|
-
|
|
39285
|
-
|
|
39286
|
-
|
|
39287
|
-
|
|
39288
|
-
|
|
39289
|
-
|
|
39290
|
-
|
|
39291
|
-
|
|
39292
|
-
|
|
39293
|
-
updatedAt: now.toISOString(),
|
|
39294
|
-
...windows.length ? { spend: { amountUSD: total30Days, period: "rolling_30_days" } } : {},
|
|
39295
|
-
...!hasKey ? { message: GO_KEY_MESSAGE } : {}
|
|
39296
|
-
};
|
|
39297
|
-
}
|
|
39298
|
-
var goDiscoveryCached;
|
|
39299
|
-
var goDiscoveryPending;
|
|
39300
|
-
async function cachedOpenCodeGoLimits(key2, now) {
|
|
39301
|
-
if (!goDiscoveryCached || now.getTime() - goDiscoveryCached.at >= 10 * 6e4) {
|
|
39302
|
-
goDiscoveryPending ??= fetchOpenCodeGoLimits(key2).catch(() => /* @__PURE__ */ new Map()).then((limits) => {
|
|
39303
|
-
goDiscoveryCached = { at: now.getTime(), limits };
|
|
39304
|
-
return limits;
|
|
39120
|
+
scan.events = scan.events.filter((event) => event.at >= now.getTime() - 7 * 24 * 36e5).slice(-1e4);
|
|
39121
|
+
refusalScans.set(file2, scan);
|
|
39122
|
+
events.push(...scan.events.filter((event) => event.at >= since && event.at <= now.getTime() + 6e4));
|
|
39123
|
+
}
|
|
39124
|
+
if (!events.length) return void 0;
|
|
39125
|
+
events.sort((a, b) => a.at - b.at);
|
|
39126
|
+
const models = [...new Set(events.flatMap((event) => event.model ? [`opencode-go/${event.model}`] : []))].sort().slice(0, 8);
|
|
39127
|
+
return { count: events.length, first: new Date(events[0].at).toISOString(), last: new Date(events.at(-1).at).toISOString(), models };
|
|
39128
|
+
}
|
|
39129
|
+
var clock = (iso) => `${iso.slice(11, 16)} UTC`;
|
|
39130
|
+
function openCodeGoUsage(windows, refusals, now, hasKey, planError) {
|
|
39131
|
+
const refused = refusals ? `OpenCode refused ${refusals.count} Go request${refusals.count === 1 ? "" : "s"} with "usage limit exceeded" in the last day (${refusals.first.slice(0, 10) === refusals.last.slice(0, 10) ? `${clock(refusals.first)} to ${clock(refusals.last)}` : `${refusals.first.slice(0, 16).replace("T", " ")} to ${refusals.last.slice(0, 16).replace("T", " ")} UTC`}).` : void 0;
|
|
39132
|
+
const reached = windows.filter((window2) => window2.limited).map((window2) => window2.name.replace(" limit", "").toLowerCase());
|
|
39133
|
+
const message = [
|
|
39134
|
+
!hasKey ? GO_KEY_MESSAGE : planError ? "Could not read Go's usage report; showing what OpenCode's log says." : void 0,
|
|
39135
|
+
reached.length ? `Go is refusing requests: the ${reached.join(" and ")} limit is reached.` : void 0,
|
|
39136
|
+
refused
|
|
39137
|
+
].filter(Boolean).join(" ");
|
|
39138
|
+
return { source: "opencode-go", windows, updatedAt: now.toISOString(), ...message ? { message } : {} };
|
|
39139
|
+
}
|
|
39140
|
+
function usageForCaller(accounts, sources, goPlan) {
|
|
39141
|
+
return accounts.filter((account) => sources.has(account.source)).map((account) => goPlan || account.source !== "opencode-go" ? account : { ...account, windows: account.windows.filter((window2) => !window2.id.startsWith("opencode-go:plan:")) });
|
|
39142
|
+
}
|
|
39143
|
+
var goPlanCached;
|
|
39144
|
+
var goPlanPending;
|
|
39145
|
+
async function cachedOpenCodeGoPlan(key2, now) {
|
|
39146
|
+
if (!goPlanCached || now.getTime() - goPlanCached.at >= 6e4) {
|
|
39147
|
+
goPlanPending ??= fetchOpenCodeGoPlan(key2).then((windows) => {
|
|
39148
|
+
goPlanCached = { at: now.getTime(), windows };
|
|
39149
|
+
return windows;
|
|
39305
39150
|
}).finally(() => {
|
|
39306
|
-
|
|
39151
|
+
goPlanPending = void 0;
|
|
39307
39152
|
});
|
|
39308
39153
|
}
|
|
39309
|
-
return
|
|
39154
|
+
return goPlanPending ? await goPlanPending : goPlanCached.windows;
|
|
39310
39155
|
}
|
|
39311
39156
|
async function readOpenCodeGoUsage(now = /* @__PURE__ */ new Date(), options = {}) {
|
|
39312
|
-
const [
|
|
39313
|
-
if (!key2) return openCodeGoUsage(
|
|
39314
|
-
let limits = /* @__PURE__ */ new Map();
|
|
39157
|
+
const [key2, refusals] = await Promise.all([(options.readKey ?? readOpenCodeGoKey)(), (options.readRefusals ?? readGoRefusals)(now).catch(() => void 0)]);
|
|
39158
|
+
if (!key2) return openCodeGoUsage([], refusals, now, false);
|
|
39315
39159
|
try {
|
|
39316
|
-
|
|
39160
|
+
const windows = options.fetchImpl ? await fetchOpenCodeGoPlan(key2, options.fetchImpl) : await cachedOpenCodeGoPlan(key2, now);
|
|
39161
|
+
return openCodeGoUsage(windows, refusals, now, true);
|
|
39317
39162
|
} catch {
|
|
39163
|
+
return openCodeGoUsage([], refusals, now, true, true);
|
|
39318
39164
|
}
|
|
39319
|
-
return openCodeGoUsage(totals, limits, now, true);
|
|
39320
39165
|
}
|
|
39321
39166
|
async function fetchOpenRouterUsage(key2, fetchImpl = fetch, now = /* @__PURE__ */ new Date()) {
|
|
39322
39167
|
const controller = new AbortController();
|
|
@@ -39543,14 +39388,55 @@ function readCodexLimits(executable2 = codexExecutable()) {
|
|
|
39543
39388
|
send2({ id: 0, method: "initialize", params: { clientInfo: { name: "phren_usage", title: "Phren Usage", version: "1" } } });
|
|
39544
39389
|
});
|
|
39545
39390
|
}
|
|
39391
|
+
function copilotUsage(value2, now = /* @__PURE__ */ new Date()) {
|
|
39392
|
+
const result = object2(value2), snapshots = object2(result.quota_snapshots);
|
|
39393
|
+
const reset = typeof result.quota_reset_date_utc === "string" && Number.isFinite(Date.parse(result.quota_reset_date_utc)) ? new Date(Date.parse(result.quota_reset_date_utc)).toISOString() : void 0;
|
|
39394
|
+
const names = { premium_interactions: "Premium requests \xB7 monthly", chat: "Chat \xB7 monthly", completions: "Completions \xB7 monthly" };
|
|
39395
|
+
const windows = [], unlimited = [];
|
|
39396
|
+
for (const [id2, raw] of Object.entries(snapshots).slice(0, 8)) {
|
|
39397
|
+
const quota = object2(raw), key2 = safeText(id2) ?? "quota";
|
|
39398
|
+
if (quota.unlimited === true) {
|
|
39399
|
+
unlimited.push((names[key2] ?? key2).replace(" \xB7 monthly", "").toLowerCase());
|
|
39400
|
+
continue;
|
|
39401
|
+
}
|
|
39402
|
+
const remaining = quota.percent_remaining;
|
|
39403
|
+
if (typeof remaining !== "number" || !Number.isFinite(remaining) || remaining < 0 || remaining > 100) continue;
|
|
39404
|
+
windows.push({ id: key2, name: names[key2] ?? key2, usedPercent: Math.round((100 - remaining) * 10) / 10, ...reset ? { resetsAt: reset } : {} });
|
|
39405
|
+
}
|
|
39406
|
+
const plan = safeText(result.copilot_plan);
|
|
39407
|
+
const notes = [plan ? `Plan: ${plan}.` : "", unlimited.length ? `Unlimited: ${unlimited.join(", ")}.` : ""].filter(Boolean).join(" ");
|
|
39408
|
+
return {
|
|
39409
|
+
source: "copilot",
|
|
39410
|
+
windows,
|
|
39411
|
+
updatedAt: now.toISOString(),
|
|
39412
|
+
...notes || !windows.length ? { message: notes || "GitHub reported no Copilot quotas for this account." } : {}
|
|
39413
|
+
};
|
|
39414
|
+
}
|
|
39415
|
+
function ghExecutable() {
|
|
39416
|
+
for (const candidate of ["/opt/homebrew/bin/gh", "/usr/local/bin/gh", "/usr/bin/gh"]) {
|
|
39417
|
+
try {
|
|
39418
|
+
if (statSync13(candidate).isFile()) return candidate;
|
|
39419
|
+
} catch {
|
|
39420
|
+
}
|
|
39421
|
+
}
|
|
39422
|
+
return "gh";
|
|
39423
|
+
}
|
|
39424
|
+
async function readCopilotUsage(now = /* @__PURE__ */ new Date(), run2 = async (file2, args) => (await exec6(file2, args, { timeout: 1e4, maxBuffer: 1048576, cwd: homedir11() })).stdout) {
|
|
39425
|
+
try {
|
|
39426
|
+
return copilotUsage(JSON.parse(await run2(ghExecutable(), ["api", "/copilot_internal/user"])), now);
|
|
39427
|
+
} catch {
|
|
39428
|
+
return { source: "copilot", windows: [], message: "Could not read Copilot usage. Sign in with gh auth login on this computer (Copilot reports its quotas through GitHub)." };
|
|
39429
|
+
}
|
|
39430
|
+
}
|
|
39546
39431
|
var AccountUsageReader = class {
|
|
39547
|
-
constructor(readCodex = readCodexLimits, now = Date.now, readClaudeLive = liveClaudeUsage, readOpenCode = (now2) => readOpenCodeUsage("opencode", now2), readOpenRouter = liveOpenRouterUsage, readOpenCodeGo = readOpenCodeGoUsage) {
|
|
39432
|
+
constructor(readCodex = readCodexLimits, now = Date.now, readClaudeLive = liveClaudeUsage, readOpenCode = (now2) => readOpenCodeUsage("opencode", now2), readOpenRouter = liveOpenRouterUsage, readOpenCodeGo = readOpenCodeGoUsage, readCopilot = readCopilotUsage) {
|
|
39548
39433
|
this.readCodex = readCodex;
|
|
39549
39434
|
this.now = now;
|
|
39550
39435
|
this.readClaudeLive = readClaudeLive;
|
|
39551
39436
|
this.readOpenCode = readOpenCode;
|
|
39552
39437
|
this.readOpenRouter = readOpenRouter;
|
|
39553
39438
|
this.readOpenCodeGo = readOpenCodeGo;
|
|
39439
|
+
this.readCopilot = readCopilot;
|
|
39554
39440
|
}
|
|
39555
39441
|
readCodex;
|
|
39556
39442
|
now;
|
|
@@ -39558,6 +39444,7 @@ var AccountUsageReader = class {
|
|
|
39558
39444
|
readOpenCode;
|
|
39559
39445
|
readOpenRouter;
|
|
39560
39446
|
readOpenCodeGo;
|
|
39447
|
+
readCopilot;
|
|
39561
39448
|
cached;
|
|
39562
39449
|
pending;
|
|
39563
39450
|
claudeCached;
|
|
@@ -39580,7 +39467,7 @@ var AccountUsageReader = class {
|
|
|
39580
39467
|
async spending() {
|
|
39581
39468
|
if (!this.spendingCached || this.now() - this.spendingCached.at >= 6e4) {
|
|
39582
39469
|
const at = this.now();
|
|
39583
|
-
this.spendingPending ??= Promise.all([this.readOpenCode(new Date(at)), this.readOpenCodeGo(new Date(at)), this.readOpenRouter(new Date(at))]).then(([openCode, openCodeGo, openRouter]) => [openCode, openCodeGo, ...openRouter ? [openRouter] : []]).then((value2) => {
|
|
39470
|
+
this.spendingPending ??= Promise.all([this.readOpenCode(new Date(at)), this.readOpenCodeGo(new Date(at)), this.readOpenRouter(new Date(at)), this.readCopilot(new Date(at))]).then(([openCode, openCodeGo, openRouter, copilot]) => [openCode, openCodeGo, ...openRouter ? [openRouter] : [], copilot]).then((value2) => {
|
|
39584
39471
|
this.spendingCached = { at, value: value2 };
|
|
39585
39472
|
return value2;
|
|
39586
39473
|
}).finally(() => {
|
|
@@ -39613,8 +39500,8 @@ var AccountUsageReader = class {
|
|
|
39613
39500
|
try {
|
|
39614
39501
|
const handle = await open9(claudeFile(), "r");
|
|
39615
39502
|
try {
|
|
39616
|
-
const
|
|
39617
|
-
if (!
|
|
39503
|
+
const stat26 = await handle.stat();
|
|
39504
|
+
if (!stat26.isFile() || stat26.size > 16384) throw new Error("Invalid usage snapshot");
|
|
39618
39505
|
const saved = object2(JSON.parse(await handle.readFile("utf8")));
|
|
39619
39506
|
const date5 = new Date(String(saved.updatedAt));
|
|
39620
39507
|
if (!Number.isFinite(date5.getTime()) || date5.getTime() > this.now() + 6e4) throw new Error("Invalid usage timestamp");
|
|
@@ -39627,8 +39514,8 @@ var AccountUsageReader = class {
|
|
|
39627
39514
|
try {
|
|
39628
39515
|
const handle = await open9(claudeConfigFile(), "r");
|
|
39629
39516
|
try {
|
|
39630
|
-
const
|
|
39631
|
-
if (!
|
|
39517
|
+
const stat26 = await handle.stat();
|
|
39518
|
+
if (!stat26.isFile() || stat26.size > 16777216) throw new Error("Invalid Claude config");
|
|
39632
39519
|
const scoped = claudeScopedWindows(JSON.parse(await handle.readFile("utf8")), new Date(this.now())).filter((entry) => !claude2.windows.some((existing) => existing.id === entry.id));
|
|
39633
39520
|
if (scoped.length) claude2 = { ...claude2, windows: [...claude2.windows, ...scoped], message: void 0 };
|
|
39634
39521
|
} finally {
|
|
@@ -40393,10 +40280,10 @@ function projectAgents(values, parent, receipt, fallbackComputer, fallbackTarget
|
|
|
40393
40280
|
for (const value2 of values.slice(0, 128)) {
|
|
40394
40281
|
if (state.count >= 128) break;
|
|
40395
40282
|
const raw = object2(value2), id2 = childID.safeParse(raw.id), source = provider.safeParse(raw.provider);
|
|
40396
|
-
const
|
|
40283
|
+
const path87 = publicLabel(raw.path);
|
|
40397
40284
|
const callId = typeof raw.callId === "string" && raw.callId.length > 0 && raw.callId.length <= 200 ? raw.callId : void 0;
|
|
40398
40285
|
const routed = destination(raw, fallbackComputer, fallbackTarget);
|
|
40399
|
-
if (!id2.success || !source.success || !
|
|
40286
|
+
if (!id2.success || !source.success || !path87 || !callId || !routed) continue;
|
|
40400
40287
|
const descendant = lineage ? `${lineage}/${id2.data}` : id2.data;
|
|
40401
40288
|
const nestedSession = sessionId.safeParse(raw.session);
|
|
40402
40289
|
const cycleIdentity = nestedSession.success ? nestedSession.data : routed.remote.child ?? routed.remote.target.session;
|
|
@@ -40409,7 +40296,7 @@ function projectAgents(values, parent, receipt, fallbackComputer, fallbackTarget
|
|
|
40409
40296
|
projected.push({
|
|
40410
40297
|
id: publicID(parent, routed.computer.id, receipt.id, descendant),
|
|
40411
40298
|
provider: source.data,
|
|
40412
|
-
path:
|
|
40299
|
+
path: path87,
|
|
40413
40300
|
callId,
|
|
40414
40301
|
state: raw.failed === true ? "failed" : childState,
|
|
40415
40302
|
...typeof raw.finishedAt === "string" && Number.isFinite(Date.parse(raw.finishedAt)) ? { finishedAt: raw.finishedAt } : {},
|
|
@@ -40727,8 +40614,8 @@ async function dispatchProjectDirectory(project) {
|
|
|
40727
40614
|
const name = projectName.parse(project);
|
|
40728
40615
|
const source = readProjectConfig(phrenStoreRoot(), name).sourcePath;
|
|
40729
40616
|
if (typeof source !== "string" || !path51.isAbsolute(source) || /[\x00-\x1f\x7f]/.test(source)) throw new BridgeError(404, "Project has no absolute sourcePath on this computer.");
|
|
40730
|
-
const directory = await
|
|
40731
|
-
if (!directory || !(await
|
|
40617
|
+
const directory = await realpath9(source).catch(() => void 0);
|
|
40618
|
+
if (!directory || !(await stat14(directory)).isDirectory()) throw new BridgeError(404, "Project is not on this computer.");
|
|
40732
40619
|
return directory;
|
|
40733
40620
|
}
|
|
40734
40621
|
async function save(receipt) {
|
|
@@ -40739,7 +40626,7 @@ async function save(receipt) {
|
|
|
40739
40626
|
var MAX_RECEIPT_BYTES = 65536;
|
|
40740
40627
|
var receiptUpdates = Promise.resolve();
|
|
40741
40628
|
function updateReceipt(receiptID, change) {
|
|
40742
|
-
const
|
|
40629
|
+
const run2 = receiptUpdates.then(async () => {
|
|
40743
40630
|
const file2 = path51.join(bridgeRoot(), "dispatches", `${external_exports.string().uuid().parse(receiptID)}.json`);
|
|
40744
40631
|
const info = await lstat12(file2).catch(() => void 0);
|
|
40745
40632
|
if (!info?.isFile() || info.isSymbolicLink() || info.size > MAX_RECEIPT_BYTES) return void 0;
|
|
@@ -40750,8 +40637,8 @@ function updateReceipt(receiptID, change) {
|
|
|
40750
40637
|
await atomic(file2, receiptSchema2.parse(receipt));
|
|
40751
40638
|
return receipt;
|
|
40752
40639
|
});
|
|
40753
|
-
receiptUpdates =
|
|
40754
|
-
return
|
|
40640
|
+
receiptUpdates = run2.catch(() => void 0);
|
|
40641
|
+
return run2;
|
|
40755
40642
|
}
|
|
40756
40643
|
async function receiptNames(root) {
|
|
40757
40644
|
try {
|
|
@@ -41060,7 +40947,7 @@ init_protocol();
|
|
|
41060
40947
|
|
|
41061
40948
|
// src/bridge/schedule-watch.ts
|
|
41062
40949
|
init_herdr();
|
|
41063
|
-
import { open as open11, stat as
|
|
40950
|
+
import { open as open11, stat as stat15 } from "node:fs/promises";
|
|
41064
40951
|
init_protocol();
|
|
41065
40952
|
init_transcripts();
|
|
41066
40953
|
init_terminal_text();
|
|
@@ -41195,7 +41082,7 @@ function ownerQuestion(text4) {
|
|
|
41195
41082
|
async function realTranscriptStamp(source, sessionId2) {
|
|
41196
41083
|
if (!sessionId2) return void 0;
|
|
41197
41084
|
const file2 = await transcriptPath(source, sessionId2).catch(() => void 0);
|
|
41198
|
-
const metadata = file2 ? await
|
|
41085
|
+
const metadata = file2 ? await stat15(file2).catch(() => void 0) : void 0;
|
|
41199
41086
|
return metadata ? { size: metadata.size, mtimeMs: metadata.mtimeMs } : void 0;
|
|
41200
41087
|
}
|
|
41201
41088
|
async function watchHerdrRun(server, target, signal, startup, env = {}) {
|
|
@@ -41525,7 +41412,7 @@ init_herdr();
|
|
|
41525
41412
|
init_transcripts();
|
|
41526
41413
|
import { execFile as execFile10 } from "node:child_process";
|
|
41527
41414
|
import { createHash as createHash12 } from "node:crypto";
|
|
41528
|
-
import { mkdir as mkdir13, open as open12, stat as
|
|
41415
|
+
import { mkdir as mkdir13, open as open12, stat as stat16, readFile as readFile22, writeFile as writeFile7 } from "node:fs/promises";
|
|
41529
41416
|
import path52 from "node:path";
|
|
41530
41417
|
import { promisify as promisify9 } from "node:util";
|
|
41531
41418
|
init_transcript_index();
|
|
@@ -41646,7 +41533,7 @@ var CodexQuestions = class {
|
|
|
41646
41533
|
const cached2 = this.snapshots.get(target.session);
|
|
41647
41534
|
let pending = cached2?.pending;
|
|
41648
41535
|
if (!cached2 || Date.now() - cached2.at > 1e3) {
|
|
41649
|
-
const metadata = await
|
|
41536
|
+
const metadata = await stat16(file2), stamp = `${metadata.ino}:${metadata.size}:${metadata.mtimeMs}`;
|
|
41650
41537
|
pending = cached2?.stamp === stamp ? cached2.pending : await pendingAsyncQuestions(file2).catch((error62) => {
|
|
41651
41538
|
if (this.failedSnapshots.size >= 64) this.failedSnapshots.delete(this.failedSnapshots.keys().next().value);
|
|
41652
41539
|
this.failedSnapshots.set(target.session, Date.now());
|
|
@@ -41700,7 +41587,7 @@ init_transcripts();
|
|
|
41700
41587
|
init_home_paths();
|
|
41701
41588
|
init_protocol();
|
|
41702
41589
|
import { spawn as spawn6 } from "node:child_process";
|
|
41703
|
-
import { readdir as readdir11, readFile as readFile23, stat as
|
|
41590
|
+
import { readdir as readdir11, readFile as readFile23, stat as stat17 } from "node:fs/promises";
|
|
41704
41591
|
import { homedir as homedir15 } from "node:os";
|
|
41705
41592
|
import path53 from "node:path";
|
|
41706
41593
|
function readCodexModels(executable2 = codexExecutable()) {
|
|
@@ -41786,7 +41673,7 @@ async function readClaudeCatalog(configDir = claudeConfigDir(), installed) {
|
|
|
41786
41673
|
try {
|
|
41787
41674
|
for (const name of await readdir11(directory)) {
|
|
41788
41675
|
if (!name.endsWith("-cc.json")) continue;
|
|
41789
|
-
const file2 = path53.join(directory, name), at = (await
|
|
41676
|
+
const file2 = path53.join(directory, name), at = (await stat17(file2)).mtimeMs;
|
|
41790
41677
|
if (!newest || at > newest.at) newest = { file: file2, at };
|
|
41791
41678
|
}
|
|
41792
41679
|
} catch {
|
|
@@ -42358,20 +42245,277 @@ var ModelSwitcher = class {
|
|
|
42358
42245
|
}
|
|
42359
42246
|
};
|
|
42360
42247
|
|
|
42248
|
+
// src/bridge/resources.ts
|
|
42249
|
+
init_home_paths();
|
|
42250
|
+
init_herdr();
|
|
42251
|
+
init_limits();
|
|
42252
|
+
init_protocol();
|
|
42253
|
+
import { execFile as execFile11 } from "node:child_process";
|
|
42254
|
+
import { readdir as readdir12, readFile as readFile24, statfs } from "node:fs/promises";
|
|
42255
|
+
import { cpus, loadavg, totalmem, uptime } from "node:os";
|
|
42256
|
+
import path54 from "node:path";
|
|
42257
|
+
import { promisify as promisify10 } from "node:util";
|
|
42258
|
+
var exec10 = promisify10(execFile11);
|
|
42259
|
+
var RESOURCES_MAX_AGE_MS = intervalFromEnv("PHREN_RESOURCES_MAX_AGE_MS", 1e4, 1e3, 6e4);
|
|
42260
|
+
var LOW_DISK_BYTES = 10 * 1024 ** 3;
|
|
42261
|
+
var GB = 1024 ** 3;
|
|
42262
|
+
function parsePs(stats, args) {
|
|
42263
|
+
const argv = /* @__PURE__ */ new Map();
|
|
42264
|
+
for (const line of args.split("\n")) {
|
|
42265
|
+
const match = /^\s*(\d+)\s+(.*)$/.exec(line);
|
|
42266
|
+
if (match) argv.set(Number(match[1]), match[2]);
|
|
42267
|
+
}
|
|
42268
|
+
const rows = [];
|
|
42269
|
+
for (const line of stats.split("\n")) {
|
|
42270
|
+
const match = /^\s*(\d+)\s+(\d+)\s+([\d.]+)\s+(\d+)\s+(.*)$/.exec(line);
|
|
42271
|
+
if (!match) continue;
|
|
42272
|
+
const pid = Number(match[1]);
|
|
42273
|
+
rows.push({ pid, ppid: Number(match[2]), cpu: Number(match[3]), rssKB: Number(match[4]), command: match[5].trim(), args: argv.get(pid) ?? match[5].trim() });
|
|
42274
|
+
}
|
|
42275
|
+
return rows;
|
|
42276
|
+
}
|
|
42277
|
+
function heavyKind(row) {
|
|
42278
|
+
const base = path54.basename(row.command);
|
|
42279
|
+
const args = row.args;
|
|
42280
|
+
if (base === "launchd_sim") {
|
|
42281
|
+
return { kind: "simulator", name: /XCTestDevices|Clone \d+ of /.test(args) ? "Simulator test clone" : "Simulator" };
|
|
42282
|
+
}
|
|
42283
|
+
if (/^qemu-system/.test(base) || base === "emulator" || /^emulator\d*-/.test(base) || /(?:^|\/)emulator\/qemu\//.test(args)) return { kind: "emulator", name: "Android emulator" };
|
|
42284
|
+
if (base === "xcodebuild") return { kind: "xcodebuild", name: "xcodebuild" };
|
|
42285
|
+
if (base === "java") {
|
|
42286
|
+
if (/Gradle(?:Daemon|Worker|Main)|gradle-launcher|org\.gradle\./.test(args)) return { kind: "gradle", name: /Kotlin/.test(args) ? "Kotlin daemon" : "Gradle" };
|
|
42287
|
+
if (/KotlinCompileDaemon/.test(args)) return { kind: "gradle", name: "Kotlin daemon" };
|
|
42288
|
+
return { kind: "java", name: "Java" };
|
|
42289
|
+
}
|
|
42290
|
+
if (base === "codex" || base === "node" && /^\S*node\s+\S*\/codex(?:\.js)?(?:\s|$)/.test(args)) return { kind: "codex", name: "Codex" };
|
|
42291
|
+
if (base === "opencode" || base === ".opencode") return { kind: "opencode", name: "OpenCode" };
|
|
42292
|
+
if (base === "claude" || /^\d+\.\d+\.\d+$/.test(base) && /(?:^|\/)claude(?:\s|$)/.test(args)) return { kind: "claude", name: "Claude Code" };
|
|
42293
|
+
return void 0;
|
|
42294
|
+
}
|
|
42295
|
+
function heavyProcesses(rows, owners = /* @__PURE__ */ new Map(), limit = 12) {
|
|
42296
|
+
const byPid = new Map(rows.map((row) => [row.pid, row]));
|
|
42297
|
+
const kinds = /* @__PURE__ */ new Map();
|
|
42298
|
+
for (const row of rows) {
|
|
42299
|
+
const kind = heavyKind(row);
|
|
42300
|
+
if (kind) kinds.set(row.pid, kind);
|
|
42301
|
+
}
|
|
42302
|
+
const totals = /* @__PURE__ */ new Map();
|
|
42303
|
+
const busy = /* @__PURE__ */ new Map();
|
|
42304
|
+
const claim2 = (row) => {
|
|
42305
|
+
for (let at = row, hops = 0; at && hops < 64; at = byPid.get(at.ppid), hops++) {
|
|
42306
|
+
if (kinds.has(at.pid)) return at.pid;
|
|
42307
|
+
if (at.ppid === at.pid || at.ppid <= 1) break;
|
|
42308
|
+
}
|
|
42309
|
+
return void 0;
|
|
42310
|
+
};
|
|
42311
|
+
const owner = (row) => {
|
|
42312
|
+
for (let at = row, hops = 0; at && hops < 64; at = byPid.get(at.ppid), hops++) {
|
|
42313
|
+
const pane = owners.get(at.pid);
|
|
42314
|
+
if (pane) return pane;
|
|
42315
|
+
if (at.ppid === at.pid || at.ppid <= 1) break;
|
|
42316
|
+
}
|
|
42317
|
+
return void 0;
|
|
42318
|
+
};
|
|
42319
|
+
for (const row of rows) {
|
|
42320
|
+
const root = claim2(row);
|
|
42321
|
+
if (root === void 0) {
|
|
42322
|
+
const name = path54.basename(row.command).slice(0, 60);
|
|
42323
|
+
const group = busy.get(name);
|
|
42324
|
+
if (!group) busy.set(name, { kind: "busy", name, pid: row.pid, processes: 1, cpuPercent: row.cpu, memoryBytes: row.rssKB * 1024, top: row.cpu, row });
|
|
42325
|
+
else {
|
|
42326
|
+
group.processes++;
|
|
42327
|
+
group.cpuPercent += row.cpu;
|
|
42328
|
+
group.memoryBytes += row.rssKB * 1024;
|
|
42329
|
+
if (row.cpu > group.top) {
|
|
42330
|
+
group.top = row.cpu;
|
|
42331
|
+
group.pid = row.pid;
|
|
42332
|
+
group.row = row;
|
|
42333
|
+
}
|
|
42334
|
+
}
|
|
42335
|
+
continue;
|
|
42336
|
+
}
|
|
42337
|
+
let total = totals.get(root);
|
|
42338
|
+
if (!total) {
|
|
42339
|
+
const { kind, name } = kinds.get(root);
|
|
42340
|
+
const pane = owner(byPid.get(root));
|
|
42341
|
+
total = { kind, name, pid: root, processes: 0, cpuPercent: 0, memoryBytes: 0, ...pane ? { pane } : {} };
|
|
42342
|
+
totals.set(root, total);
|
|
42343
|
+
}
|
|
42344
|
+
total.processes++;
|
|
42345
|
+
total.cpuPercent += row.cpu;
|
|
42346
|
+
total.memoryBytes += row.rssKB * 1024;
|
|
42347
|
+
}
|
|
42348
|
+
for (const { top: _top, row, ...group } of busy.values()) {
|
|
42349
|
+
if (group.cpuPercent < 50) continue;
|
|
42350
|
+
const pane = owner(row);
|
|
42351
|
+
totals.set(group.pid, { ...group, ...pane ? { pane } : {} });
|
|
42352
|
+
}
|
|
42353
|
+
return [...totals.values()].filter((item) => item.kind === "simulator" || item.kind === "emulator" || item.kind === "busy" || item.cpuPercent >= 10 || item.memoryBytes >= 200 * 1024 ** 2).map((item) => ({ ...item, cpuPercent: Math.round(item.cpuPercent * 10) / 10 })).sort((a, b) => b.cpuPercent - a.cpuPercent || b.memoryBytes - a.memoryBytes).slice(0, limit);
|
|
42354
|
+
}
|
|
42355
|
+
function parsePmset(output2) {
|
|
42356
|
+
const match = /(\d{1,3})%;\s*([^;]+);/.exec(output2);
|
|
42357
|
+
if (!match) return void 0;
|
|
42358
|
+
const state = match[2].trim().toLowerCase();
|
|
42359
|
+
return {
|
|
42360
|
+
percent: Math.min(100, Number(match[1])),
|
|
42361
|
+
charging: state === "charging" || state === "charged" || state === "finishing charge",
|
|
42362
|
+
onAC: /'AC Power'/.test(output2)
|
|
42363
|
+
};
|
|
42364
|
+
}
|
|
42365
|
+
function parseSwap(output2) {
|
|
42366
|
+
const match = /used\s*=\s*([\d.]+)([KMG])/.exec(output2);
|
|
42367
|
+
if (!match) return void 0;
|
|
42368
|
+
return Math.round(Number(match[1]) * { K: 1024, M: 1024 ** 2, G: GB }[match[2]]);
|
|
42369
|
+
}
|
|
42370
|
+
function parseMeminfo(text4) {
|
|
42371
|
+
const field = (name) => {
|
|
42372
|
+
const match = new RegExp(`^${name}:\\s+(\\d+)`, "m").exec(text4);
|
|
42373
|
+
return match ? Number(match[1]) * 1024 : void 0;
|
|
42374
|
+
};
|
|
42375
|
+
const total = field("MemTotal") ?? totalmem(), available = field("MemAvailable");
|
|
42376
|
+
const swapTotal = field("SwapTotal"), swapFree = field("SwapFree");
|
|
42377
|
+
const availablePercent = available !== void 0 && total ? Math.round(available / total * 100) : void 0;
|
|
42378
|
+
return {
|
|
42379
|
+
totalBytes: total,
|
|
42380
|
+
...availablePercent !== void 0 ? { availablePercent, pressure: availablePercent < 5 ? "critical" : availablePercent < 15 ? "warn" : "normal" } : {},
|
|
42381
|
+
...swapTotal !== void 0 && swapFree !== void 0 ? { swapUsedBytes: swapTotal - swapFree } : {}
|
|
42382
|
+
};
|
|
42383
|
+
}
|
|
42384
|
+
function assess(value2) {
|
|
42385
|
+
const cpu = Math.min(1, value2.cpu.loadPerCore / 2);
|
|
42386
|
+
const memory = value2.memory.pressure === "critical" ? 1 : Math.max(value2.memory.pressure === "warn" ? 0.75 : 0, value2.memory.availablePercent === void 0 ? 0 : 1 - value2.memory.availablePercent / 100);
|
|
42387
|
+
const free = value2.disk?.freeBytes, total = value2.disk?.totalBytes;
|
|
42388
|
+
const disk = free === void 0 || !total ? 0 : free >= 50 * GB ? 0.5 * (1 - free / total) : Math.min(1, 0.5 + (50 * GB - free) / (80 * GB));
|
|
42389
|
+
const round = (n) => Math.round(Math.max(0, n) * 100) / 100;
|
|
42390
|
+
const warnings = [];
|
|
42391
|
+
if (value2.cpu.loadPerCore > 2) warnings.push("load-high");
|
|
42392
|
+
if (value2.memory.pressure === "critical" || (value2.memory.availablePercent ?? 100) < 5) warnings.push("memory-low");
|
|
42393
|
+
if (free !== void 0 && free < LOW_DISK_BYTES) warnings.push("disk-low");
|
|
42394
|
+
if (value2.battery && !value2.battery.onAC && value2.battery.percent < 15) warnings.push("battery-low");
|
|
42395
|
+
const overall = Math.max(cpu, memory, disk);
|
|
42396
|
+
return {
|
|
42397
|
+
pressure: { cpu: round(cpu), memory: round(memory), disk: round(disk), overall: round(overall) },
|
|
42398
|
+
level: warnings.some((w) => w !== "battery-low") || overall >= 0.9 ? "stressed" : overall >= 0.6 ? "busy" : "ok",
|
|
42399
|
+
warnings
|
|
42400
|
+
};
|
|
42401
|
+
}
|
|
42402
|
+
async function run(file2, args) {
|
|
42403
|
+
return (await exec10(file2, args, { timeout: 4e3, maxBuffer: 8 * 1024 * 1024, env: { ...process.env, LC_ALL: "C" } })).stdout;
|
|
42404
|
+
}
|
|
42405
|
+
async function darwinMemory() {
|
|
42406
|
+
const [level, pressure, swap] = await Promise.all([
|
|
42407
|
+
run("/usr/sbin/sysctl", ["-n", "kern.memorystatus_level"]).catch(() => ""),
|
|
42408
|
+
run("/usr/sbin/sysctl", ["-n", "kern.memorystatus_vm_pressure_level"]).catch(() => ""),
|
|
42409
|
+
run("/usr/sbin/sysctl", ["-n", "vm.swapusage"]).catch(() => "")
|
|
42410
|
+
]);
|
|
42411
|
+
const available = Number(level.trim()), code = Number(pressure.trim()), swapUsedBytes = parseSwap(swap);
|
|
42412
|
+
return {
|
|
42413
|
+
totalBytes: totalmem(),
|
|
42414
|
+
...level.trim() && Number.isFinite(available) ? { availablePercent: available } : {},
|
|
42415
|
+
...pressure.trim() && Number.isFinite(code) ? { pressure: code >= 4 ? "critical" : code >= 2 ? "warn" : "normal" } : {},
|
|
42416
|
+
...swapUsedBytes !== void 0 ? { swapUsedBytes } : {}
|
|
42417
|
+
};
|
|
42418
|
+
}
|
|
42419
|
+
async function linuxBattery() {
|
|
42420
|
+
const root = "/sys/class/power_supply";
|
|
42421
|
+
const names = await readdir12(root).catch(() => []);
|
|
42422
|
+
const battery = names.find((name) => /^BAT/.test(name));
|
|
42423
|
+
if (!battery) return void 0;
|
|
42424
|
+
const read = (name, field) => readFile24(path54.join(root, name, field), "utf8").then((text4) => text4.trim()).catch(() => "");
|
|
42425
|
+
const [capacity2, status] = await Promise.all([read(battery, "capacity"), read(battery, "status")]);
|
|
42426
|
+
const online = await Promise.all(names.filter((name) => !/^BAT/.test(name)).map((name) => read(name, "online")));
|
|
42427
|
+
const percent = Number(capacity2);
|
|
42428
|
+
if (!capacity2 || !Number.isFinite(percent)) return void 0;
|
|
42429
|
+
return { percent, charging: status === "Charging" || status === "Full", onAC: online.includes("1") };
|
|
42430
|
+
}
|
|
42431
|
+
async function processTable2() {
|
|
42432
|
+
const [stats, args] = await Promise.all([run("/bin/ps", ["-axo", "pid=,ppid=,pcpu=,rss=,comm="]), run("/bin/ps", ["-axo", "pid=,args="])]);
|
|
42433
|
+
return parsePs(stats, args);
|
|
42434
|
+
}
|
|
42435
|
+
async function paneOwners() {
|
|
42436
|
+
const owners = /* @__PURE__ */ new Map();
|
|
42437
|
+
const { terminalProvider: terminalProvider2 } = await Promise.resolve().then(() => (init_terminal(), terminal_exports));
|
|
42438
|
+
const provider2 = terminalProvider2();
|
|
42439
|
+
for (const server of (await recentServers()).slice(0, 8)) {
|
|
42440
|
+
const name = String(server.session);
|
|
42441
|
+
const s = await sharedSnapshot(name, RESOURCES_MAX_AGE_MS).catch(() => void 0);
|
|
42442
|
+
if (!s) continue;
|
|
42443
|
+
const workspaces = new Map(objects(s.workspaces).map((w) => [String(w.workspace_id), typeof w.label === "string" ? w.label : void 0]));
|
|
42444
|
+
await Promise.all(objects(s.panes).slice(0, 64).map(async (pane) => {
|
|
42445
|
+
const processes = await provider2.processes(name, String(pane.pane_id)).catch(() => void 0);
|
|
42446
|
+
if (!processes) return;
|
|
42447
|
+
const ref = {
|
|
42448
|
+
server: name,
|
|
42449
|
+
pane: String(pane.pane_id),
|
|
42450
|
+
...workspaces.get(String(pane.workspace_id)) ? { workspace: workspaces.get(String(pane.workspace_id)) } : {},
|
|
42451
|
+
...typeof pane.agent === "string" ? { agent: pane.agent } : {},
|
|
42452
|
+
...typeof pane.label === "string" && pane.label ? { label: pane.label } : {}
|
|
42453
|
+
};
|
|
42454
|
+
for (const pid of [processes.shellPid, ...processes.foregroundPids]) if (typeof pid === "number" && pid > 0) owners.set(pid, ref);
|
|
42455
|
+
}));
|
|
42456
|
+
}
|
|
42457
|
+
return owners;
|
|
42458
|
+
}
|
|
42459
|
+
async function collectResources(deps2) {
|
|
42460
|
+
const [one, five, fifteen] = loadavg();
|
|
42461
|
+
const cores = cpus().length || 1;
|
|
42462
|
+
const platform = deps2.platform;
|
|
42463
|
+
const [memory, disk, battery, rows] = await Promise.all([
|
|
42464
|
+
platform === "darwin" ? darwinMemory() : platform === "linux" ? readFile24("/proc/meminfo", "utf8").then(parseMeminfo).catch(() => ({ totalBytes: totalmem() })) : Promise.resolve({ totalBytes: totalmem() }),
|
|
42465
|
+
statfs(deps2.home()).then((info) => ({ path: "~", totalBytes: info.blocks * info.bsize, freeBytes: info.bavail * info.bsize })).catch(() => void 0),
|
|
42466
|
+
platform === "darwin" ? run("/usr/bin/pmset", ["-g", "batt"]).then(parsePmset).catch(() => void 0) : platform === "linux" ? linuxBattery() : Promise.resolve(void 0),
|
|
42467
|
+
deps2.processes().catch(() => [])
|
|
42468
|
+
]);
|
|
42469
|
+
const preliminary = heavyProcesses(rows);
|
|
42470
|
+
const owners = preliminary.length ? await deps2.owners().catch(() => /* @__PURE__ */ new Map()) : /* @__PURE__ */ new Map();
|
|
42471
|
+
const round = (n) => Math.round(n * 100) / 100;
|
|
42472
|
+
const value2 = {
|
|
42473
|
+
collectedAt: new Date(deps2.now()).toISOString(),
|
|
42474
|
+
platform,
|
|
42475
|
+
uptimeSeconds: Math.round(uptime()),
|
|
42476
|
+
cpu: { cores, load1: round(one), load5: round(five), load15: round(fifteen), loadPerCore: round(one / cores) },
|
|
42477
|
+
memory,
|
|
42478
|
+
...disk ? { disk } : {},
|
|
42479
|
+
...battery ? { battery } : {},
|
|
42480
|
+
heavy: owners.size ? heavyProcesses(rows, owners) : preliminary
|
|
42481
|
+
};
|
|
42482
|
+
return { ...value2, ...assess(value2) };
|
|
42483
|
+
}
|
|
42484
|
+
var ResourceMonitor = class {
|
|
42485
|
+
constructor(deps2 = {}, maxAgeMs = RESOURCES_MAX_AGE_MS) {
|
|
42486
|
+
this.maxAgeMs = maxAgeMs;
|
|
42487
|
+
this.deps = { platform: process.platform, now: Date.now, home: homeDir, processes: processTable2, owners: paneOwners, ...deps2 };
|
|
42488
|
+
}
|
|
42489
|
+
maxAgeMs;
|
|
42490
|
+
cached;
|
|
42491
|
+
pending;
|
|
42492
|
+
deps;
|
|
42493
|
+
async read() {
|
|
42494
|
+
if (this.cached && this.deps.now() - this.cached.at < this.maxAgeMs) return this.cached.value;
|
|
42495
|
+
this.pending ??= collectResources(this.deps).then((value2) => {
|
|
42496
|
+
this.cached = { at: this.deps.now(), value: value2 };
|
|
42497
|
+
return value2;
|
|
42498
|
+
}).finally(() => {
|
|
42499
|
+
this.pending = void 0;
|
|
42500
|
+
});
|
|
42501
|
+
return this.pending;
|
|
42502
|
+
}
|
|
42503
|
+
};
|
|
42504
|
+
|
|
42361
42505
|
// src/bridge/schedules.ts
|
|
42362
42506
|
init_protocol();
|
|
42363
42507
|
init_project_config();
|
|
42364
42508
|
init_shared();
|
|
42365
42509
|
import { randomUUID as randomUUID11 } from "node:crypto";
|
|
42366
42510
|
import { hostname as hostname6 } from "node:os";
|
|
42367
|
-
import
|
|
42511
|
+
import path57 from "node:path";
|
|
42368
42512
|
|
|
42369
42513
|
// src/bridge/schedule-format.ts
|
|
42370
42514
|
init_js_yaml();
|
|
42371
42515
|
init_zod();
|
|
42372
42516
|
init_protocol();
|
|
42373
|
-
import { readFile as
|
|
42374
|
-
import
|
|
42517
|
+
import { readFile as readFile25 } from "node:fs/promises";
|
|
42518
|
+
import path55 from "node:path";
|
|
42375
42519
|
var SCHEDULE_EVERY = ["interval", "daily", "weekly", "once", "cron"];
|
|
42376
42520
|
var SCHEDULE_HARNESSES = ["claude", "codex", "opencode"];
|
|
42377
42521
|
var SCHEDULE_NOTIFY = ["start", "finish", "failure"];
|
|
@@ -42384,7 +42528,7 @@ var scheduleName = singleLine(80);
|
|
|
42384
42528
|
var timestamp3 = external_exports.string().datetime({ offset: true });
|
|
42385
42529
|
var localTimestamp = external_exports.string().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/);
|
|
42386
42530
|
var clockTime = external_exports.string().regex(/^(?:[01]\d|2[0-3]):[0-5]\d$/);
|
|
42387
|
-
var schedulePath = (projectDir) =>
|
|
42531
|
+
var schedulePath = (projectDir) => path55.join(projectDir, "schedules.yaml");
|
|
42388
42532
|
var runningStatuses = /* @__PURE__ */ new Set(["launched", "running", "blocked"]);
|
|
42389
42533
|
var MAX_SCHEDULES = 64;
|
|
42390
42534
|
var MAX_RUNS = 2e3;
|
|
@@ -42440,7 +42584,7 @@ function parseSchedule(value2) {
|
|
|
42440
42584
|
async function readScheduleDocument(projectDir) {
|
|
42441
42585
|
let text4;
|
|
42442
42586
|
try {
|
|
42443
|
-
text4 = await
|
|
42587
|
+
text4 = await readFile25(schedulePath(projectDir), "utf8");
|
|
42444
42588
|
} catch (error62) {
|
|
42445
42589
|
if (error62.code === "ENOENT") return { document: { version: 1 }, schedules: [] };
|
|
42446
42590
|
throw error62;
|
|
@@ -42561,7 +42705,7 @@ function nextRun(schedule, lastRun) {
|
|
|
42561
42705
|
async function readScheduleRuns(file2) {
|
|
42562
42706
|
let text4;
|
|
42563
42707
|
try {
|
|
42564
|
-
text4 = await
|
|
42708
|
+
text4 = await readFile25(file2, "utf8");
|
|
42565
42709
|
} catch (error62) {
|
|
42566
42710
|
if (error62.code === "ENOENT") return [];
|
|
42567
42711
|
throw error62;
|
|
@@ -42581,10 +42725,10 @@ async function readScheduleRuns(file2) {
|
|
|
42581
42725
|
}
|
|
42582
42726
|
async function writeScheduleRuns(file2, runs) {
|
|
42583
42727
|
const kept = runs.slice(-MAX_RUNS);
|
|
42584
|
-
await atomicInPrivateDir(file2, kept.map((
|
|
42728
|
+
await atomicInPrivateDir(file2, kept.map((run2) => JSON.stringify(run2)).join("\n") + (kept.length ? "\n" : ""));
|
|
42585
42729
|
}
|
|
42586
42730
|
function scheduleRunsFile() {
|
|
42587
|
-
return
|
|
42731
|
+
return path55.join(bridgeRoot(), "schedule-runs.jsonl");
|
|
42588
42732
|
}
|
|
42589
42733
|
|
|
42590
42734
|
// src/bridge/schedule-launch.ts
|
|
@@ -42597,8 +42741,8 @@ init_logger();
|
|
|
42597
42741
|
init_shared();
|
|
42598
42742
|
import { spawn as spawn7 } from "node:child_process";
|
|
42599
42743
|
import { createWriteStream } from "node:fs";
|
|
42600
|
-
import { mkdir as mkdir14, readFile as
|
|
42601
|
-
import
|
|
42744
|
+
import { mkdir as mkdir14, readFile as readFile26, stat as stat18 } from "node:fs/promises";
|
|
42745
|
+
import path56 from "node:path";
|
|
42602
42746
|
import { finished as streamFinished } from "node:stream/promises";
|
|
42603
42747
|
var CLAUDE_SCHEDULE_SETTINGS = JSON.stringify({ enableAllProjectMcpServers: true });
|
|
42604
42748
|
function createScheduleLauncher(launchHerdr, store = defaultPhrenPath()) {
|
|
@@ -42616,22 +42760,22 @@ function createScheduleLauncher(launchHerdr, store = defaultPhrenPath()) {
|
|
|
42616
42760
|
for (const child of children) child.kill("SIGTERM");
|
|
42617
42761
|
children.clear();
|
|
42618
42762
|
};
|
|
42619
|
-
launcher.resume = (
|
|
42763
|
+
launcher.resume = (run2, schedule) => resumeScheduleRun(run2, schedule, abort.signal);
|
|
42620
42764
|
return launcher;
|
|
42621
42765
|
}
|
|
42622
|
-
async function resumeScheduleRun(
|
|
42623
|
-
const launch2 =
|
|
42624
|
-
if (
|
|
42766
|
+
async function resumeScheduleRun(run2, schedule, signal, watch2 = watchHerdrRun) {
|
|
42767
|
+
const launch2 = run2.launch;
|
|
42768
|
+
if (run2.status === "launched") return { status: "failed", reason: "Phren Hook restarted before this run finished launching." };
|
|
42625
42769
|
if (launch2.mode === "herdr" && launch2.server && launch2.workspaceId && launch2.tabId && launch2.paneId) {
|
|
42626
42770
|
return watch2(
|
|
42627
42771
|
launch2.server,
|
|
42628
42772
|
{ workspaceId: launch2.workspaceId, tabId: launch2.tabId, paneId: launch2.paneId },
|
|
42629
42773
|
signal,
|
|
42630
|
-
{ source: schedule.harness, startedAt: Date.parse(
|
|
42774
|
+
{ source: schedule.harness, startedAt: Date.parse(run2.startedAt), sessionId: launch2.sessionId }
|
|
42631
42775
|
);
|
|
42632
42776
|
}
|
|
42633
42777
|
if (launch2.mode === "headless" && launch2.jobDir) {
|
|
42634
|
-
const manifest = await
|
|
42778
|
+
const manifest = await readFile26(path56.join(launch2.jobDir, "manifest.json"), "utf8").then((text4) => JSON.parse(text4)).catch(() => void 0);
|
|
42635
42779
|
if (manifest?.status === "completed") return { status: "finished" };
|
|
42636
42780
|
if (manifest?.status === "failed") {
|
|
42637
42781
|
return { status: "failed", reason: typeof manifest.exitCode === "number" ? `The scheduled agent exited with code ${manifest.exitCode}.` : "The scheduled agent failed." };
|
|
@@ -42679,7 +42823,7 @@ async function promptWhenReady(server, paneId, text4, signal, waitMs = 6e4) {
|
|
|
42679
42823
|
}
|
|
42680
42824
|
}
|
|
42681
42825
|
async function launchHeadless(context, store, started) {
|
|
42682
|
-
const root = fanoutRoot({ ...process.env, PHREN_PATH: store }), jobDir =
|
|
42826
|
+
const root = fanoutRoot({ ...process.env, PHREN_PATH: store }), jobDir = path56.join(root, context.runId);
|
|
42683
42827
|
await mkdir14(jobDir, { recursive: true, mode: 448 });
|
|
42684
42828
|
const eventLog = "events.jsonl", now = (/* @__PURE__ */ new Date()).toISOString();
|
|
42685
42829
|
const manifest = {
|
|
@@ -42699,7 +42843,7 @@ async function launchHeadless(context, store, started) {
|
|
|
42699
42843
|
};
|
|
42700
42844
|
await writeManifest2(jobDir, manifest);
|
|
42701
42845
|
const command = headlessCommand(context.schedule, context.cwd);
|
|
42702
|
-
if (context.schedule.harness === "codex") await ensureCodexDirTrusted(context.cwd).catch((error62) => logger.warn("schedule", `Could not mark ${
|
|
42846
|
+
if (context.schedule.harness === "codex") await ensureCodexDirTrusted(context.cwd).catch((error62) => logger.warn("schedule", `Could not mark ${path56.basename(context.cwd)} trusted for Codex (run ${context.runId}): ${error62 instanceof Error ? error62.message.split("\n")[0] : String(error62)}`));
|
|
42703
42847
|
let child;
|
|
42704
42848
|
try {
|
|
42705
42849
|
child = spawn7(command.file, command.args, { cwd: command.cwd, env: process.env, stdio: ["pipe", "pipe", "pipe"] });
|
|
@@ -42711,8 +42855,8 @@ async function launchHeadless(context, store, started) {
|
|
|
42711
42855
|
const closed = new Promise((resolve11) => {
|
|
42712
42856
|
child.once("close", (code, signal) => resolve11({ code, signal }));
|
|
42713
42857
|
});
|
|
42714
|
-
const output2 = createWriteStream(
|
|
42715
|
-
const errors = createWriteStream(
|
|
42858
|
+
const output2 = createWriteStream(path56.join(jobDir, eventLog), { flags: "a", mode: 384 });
|
|
42859
|
+
const errors = createWriteStream(path56.join(jobDir, "stderr.log"), { flags: "a", mode: 384 });
|
|
42716
42860
|
const streamsFinished = Promise.all([streamFinished(output2), streamFinished(errors)]).then(() => void 0).catch(() => void 0);
|
|
42717
42861
|
child.stdin?.on("error", () => {
|
|
42718
42862
|
});
|
|
@@ -42765,19 +42909,19 @@ function tomlQuote(value2) {
|
|
|
42765
42909
|
}
|
|
42766
42910
|
async function ensureCodexDirTrusted(cwd) {
|
|
42767
42911
|
const directory = codexHome();
|
|
42768
|
-
const file2 =
|
|
42912
|
+
const file2 = path56.join(directory, "config.toml");
|
|
42769
42913
|
let text4 = "";
|
|
42770
42914
|
try {
|
|
42771
|
-
text4 = await
|
|
42915
|
+
text4 = await readFile26(file2, "utf8");
|
|
42772
42916
|
} catch (error62) {
|
|
42773
42917
|
if (error62.code !== "ENOENT") throw error62;
|
|
42774
42918
|
}
|
|
42775
|
-
const
|
|
42919
|
+
const header = `[projects.${tomlQuote(cwd)}]`;
|
|
42776
42920
|
const trustLine = 'trust_level = "trusted"';
|
|
42777
42921
|
let next;
|
|
42778
|
-
const at = text4.indexOf(
|
|
42922
|
+
const at = text4.indexOf(header);
|
|
42779
42923
|
if (at >= 0) {
|
|
42780
|
-
const bodyStart = at +
|
|
42924
|
+
const bodyStart = at + header.length;
|
|
42781
42925
|
const rest = text4.slice(bodyStart);
|
|
42782
42926
|
const nextTable = rest.search(/^\s*\[/m);
|
|
42783
42927
|
const section = nextTable >= 0 ? rest.slice(0, nextTable) : rest;
|
|
@@ -42792,17 +42936,17 @@ async function ensureCodexDirTrusted(cwd) {
|
|
|
42792
42936
|
}
|
|
42793
42937
|
} else {
|
|
42794
42938
|
const separator = text4 && !text4.endsWith("\n") ? "\n\n" : text4 ? "\n" : "";
|
|
42795
|
-
next = text4 + `${separator}${
|
|
42939
|
+
next = text4 + `${separator}${header}
|
|
42796
42940
|
${trustLine}
|
|
42797
42941
|
`;
|
|
42798
42942
|
}
|
|
42799
42943
|
await mkdir14(directory, { recursive: true, mode: 448 });
|
|
42800
|
-
const metadata = await
|
|
42944
|
+
const metadata = await stat18(file2).catch(() => void 0);
|
|
42801
42945
|
const mode = metadata ? metadata.mode & 511 : 384;
|
|
42802
42946
|
await atomic(file2, next, mode);
|
|
42803
42947
|
}
|
|
42804
42948
|
async function writeManifest2(jobDir, manifest) {
|
|
42805
|
-
await atomicInPrivateDir(
|
|
42949
|
+
await atomicInPrivateDir(path56.join(jobDir, "manifest.json"), JSON.stringify(manifest, null, 2) + "\n");
|
|
42806
42950
|
}
|
|
42807
42951
|
|
|
42808
42952
|
// src/bridge/schedules.ts
|
|
@@ -42840,7 +42984,7 @@ var Scheduler = class {
|
|
|
42840
42984
|
return getProjectDirs(this.store);
|
|
42841
42985
|
}
|
|
42842
42986
|
projectDirectory(project) {
|
|
42843
|
-
const found = this.projectDirectories().find((directory) =>
|
|
42987
|
+
const found = this.projectDirectories().find((directory) => path57.basename(directory).toLowerCase() === project.toLowerCase());
|
|
42844
42988
|
if (!found) throw new BridgeError(404, `Unknown project "${project}".`);
|
|
42845
42989
|
return found;
|
|
42846
42990
|
}
|
|
@@ -42866,10 +43010,10 @@ var Scheduler = class {
|
|
|
42866
43010
|
} catch {
|
|
42867
43011
|
continue;
|
|
42868
43012
|
}
|
|
42869
|
-
const project =
|
|
43013
|
+
const project = path57.basename(directory);
|
|
42870
43014
|
for (const schedule of schedules) {
|
|
42871
|
-
const matching = runs.filter((
|
|
42872
|
-
const last = matching.at(-1), running2 = matching.some((
|
|
43015
|
+
const matching = runs.filter((run2) => run2.project === project && run2.scheduleId === schedule.id);
|
|
43016
|
+
const last = matching.at(-1), running2 = matching.some((run2) => runningStatuses.has(run2.status));
|
|
42873
43017
|
const due = computerMatches(schedule.computer, computer) ? nextRun(schedule, last) : null;
|
|
42874
43018
|
result.push({
|
|
42875
43019
|
...schedule,
|
|
@@ -42892,28 +43036,28 @@ var Scheduler = class {
|
|
|
42892
43036
|
}
|
|
42893
43037
|
async history(filters = {}) {
|
|
42894
43038
|
const limit = Math.min(500, Math.max(1, filters.limit ?? 50));
|
|
42895
|
-
return (await readScheduleRuns(this.runsFile)).filter((
|
|
43039
|
+
return (await readScheduleRuns(this.runsFile)).filter((run2) => (!filters.project || run2.project.toLowerCase() === filters.project.toLowerCase()) && (!filters.id || run2.scheduleId === filters.id)).slice(-limit).reverse();
|
|
42896
43040
|
}
|
|
42897
43041
|
async launchNow(projectName2, id2) {
|
|
42898
43042
|
const prepared = await this.exclusive(async () => {
|
|
42899
|
-
const projectDir = this.projectDirectory(projectName2), project =
|
|
43043
|
+
const projectDir = this.projectDirectory(projectName2), project = path57.basename(projectDir);
|
|
42900
43044
|
const file2 = await readScheduleDocument(projectDir), schedule = file2.schedules.find((item) => item.id === id2);
|
|
42901
43045
|
if (!schedule) throw new BridgeError(404, `Schedule "${id2}" was not found in ${project}.`);
|
|
42902
43046
|
if (!computerMatches(schedule.computer, this.computer())) throw new BridgeError(409, `${schedule.computer} owns this schedule; run it from that computer.`);
|
|
42903
43047
|
const runs = await readScheduleRuns(this.runsFile);
|
|
42904
|
-
if (runs.some((
|
|
43048
|
+
if (runs.some((run3) => run3.project === project && run3.scheduleId === id2 && runningStatuses.has(run3.status))) {
|
|
42905
43049
|
throw new BridgeError(409, `Schedule "${schedule.name}" is already running.`);
|
|
42906
43050
|
}
|
|
42907
|
-
const
|
|
42908
|
-
this.own.add(
|
|
42909
|
-
await writeScheduleRuns(this.runsFile, [...runs,
|
|
43051
|
+
const run2 = { id: randomUUID11(), scheduleId: id2, project, startedAt: this.now().toISOString(), status: "launched", launch: { mode: "headless" } };
|
|
43052
|
+
this.own.add(run2.id);
|
|
43053
|
+
await writeScheduleRuns(this.runsFile, [...runs, run2]);
|
|
42910
43054
|
if (schedule.every === "once" && schedule.enabled) {
|
|
42911
43055
|
const updatedAt = this.now().toISOString();
|
|
42912
43056
|
const schedules = file2.schedules.map((item) => item.id === id2 ? { ...item, enabled: false, updatedAt } : item);
|
|
42913
43057
|
await writeScheduleDocument(projectDir, schedules, file2.document);
|
|
42914
43058
|
}
|
|
42915
43059
|
const source = getProjectSourcePath(this.store, project);
|
|
42916
|
-
return { projectDir, project, schedule, run, cwd: source ?? await this.locateProject(project) ?? projectDir };
|
|
43060
|
+
return { projectDir, project, schedule, run: run2, cwd: source ?? await this.locateProject(project) ?? projectDir };
|
|
42917
43061
|
});
|
|
42918
43062
|
try {
|
|
42919
43063
|
const launched = await this.launch({
|
|
@@ -42947,7 +43091,7 @@ var Scheduler = class {
|
|
|
42947
43091
|
}
|
|
42948
43092
|
async updateRun(id2, patch) {
|
|
42949
43093
|
return this.exclusive(async () => {
|
|
42950
|
-
const runs = await readScheduleRuns(this.runsFile), index2 = runs.findIndex((
|
|
43094
|
+
const runs = await readScheduleRuns(this.runsFile), index2 = runs.findIndex((run2) => run2.id === id2);
|
|
42951
43095
|
if (index2 < 0) throw new Error("The schedule run record disappeared.");
|
|
42952
43096
|
runs[index2] = { ...runs[index2], ...patch };
|
|
42953
43097
|
await writeScheduleRuns(this.runsFile, runs);
|
|
@@ -42955,34 +43099,34 @@ var Scheduler = class {
|
|
|
42955
43099
|
});
|
|
42956
43100
|
}
|
|
42957
43101
|
async finishRun(id2, schedule, status, reason2, previousNotification) {
|
|
42958
|
-
const
|
|
43102
|
+
const run2 = await this.updateRun(id2, { status, finishedAt: this.now().toISOString(), ...reason2 ? { reason: reason2 } : {} });
|
|
42959
43103
|
await previousNotification;
|
|
42960
|
-
if (
|
|
42961
|
-
await this.notifyRun(
|
|
43104
|
+
if (run2.blockedStartupPrompt && run2.blockNotified) return;
|
|
43105
|
+
await this.notifyRun(run2, schedule, status === "failed" ? "scheduleFailed" : "scheduleFinished");
|
|
42962
43106
|
}
|
|
42963
43107
|
async recordBlockedStartup(id2, schedule, promptText2) {
|
|
42964
43108
|
try {
|
|
42965
43109
|
const prompt = promptText2.slice(0, 4e3);
|
|
42966
|
-
const
|
|
42967
|
-
const delivered = await this.notifyRun(
|
|
43110
|
+
const run2 = await this.updateRun(id2, { status: "blocked", blockedStartupPrompt: prompt });
|
|
43111
|
+
const delivered = await this.notifyRun(run2, schedule, "scheduleBlocked", `Blocked at startup: ${prompt}`);
|
|
42968
43112
|
if (delivered) await this.updateRun(id2, { blockNotified: true });
|
|
42969
43113
|
} catch (error62) {
|
|
42970
43114
|
this.log(`[schedule] blocked-at-startup record for run ${id2} failed: ${error62 instanceof Error ? error62.message : "unknown error"}`);
|
|
42971
43115
|
}
|
|
42972
43116
|
}
|
|
42973
|
-
async notifyRun(
|
|
43117
|
+
async notifyRun(run2, schedule, kind, reason2) {
|
|
42974
43118
|
const preference = kind === "scheduleStarted" ? "start" : kind === "scheduleFinished" ? "finish" : "failure";
|
|
42975
43119
|
if (!scheduleNotifications(schedule).has(preference)) return false;
|
|
42976
|
-
const route2 = scheduleSessionRoute(schedule,
|
|
42977
|
-
const text4 = reason2 ??
|
|
43120
|
+
const route2 = scheduleSessionRoute(schedule, run2.launch);
|
|
43121
|
+
const text4 = reason2 ?? run2.reason;
|
|
42978
43122
|
const value2 = {
|
|
42979
43123
|
kind,
|
|
42980
43124
|
scheduleId: schedule.id,
|
|
42981
|
-
project:
|
|
43125
|
+
project: run2.project,
|
|
42982
43126
|
name: schedule.name,
|
|
42983
43127
|
computer: schedule.computer,
|
|
42984
|
-
runId:
|
|
42985
|
-
status: kind === "scheduleStarted" ? "running" : kind === "scheduleFinished" ?
|
|
43128
|
+
runId: run2.id,
|
|
43129
|
+
status: kind === "scheduleStarted" ? "running" : kind === "scheduleFinished" ? run2.status === "needs-you" ? "needs-you" : "finished" : kind === "scheduleBlocked" ? "blocked" : "failed",
|
|
42986
43130
|
...text4 ? { reason: text4 } : {},
|
|
42987
43131
|
...route2 ? { route: route2 } : {}
|
|
42988
43132
|
};
|
|
@@ -42993,11 +43137,11 @@ var Scheduler = class {
|
|
|
42993
43137
|
result = { notified: false, reason: "push delivery failed" };
|
|
42994
43138
|
}
|
|
42995
43139
|
try {
|
|
42996
|
-
await this.updateRun(
|
|
43140
|
+
await this.updateRun(run2.id, { notified: result.notified, ...result.reason ? { notifyReason: result.reason } : { notifyReason: void 0 } });
|
|
42997
43141
|
} catch (error62) {
|
|
42998
|
-
this.log(`[schedule] ${kind} notification result for run ${
|
|
43142
|
+
this.log(`[schedule] ${kind} notification result for run ${run2.id} could not be recorded: ${error62 instanceof Error ? error62.message : "unknown error"}`);
|
|
42999
43143
|
}
|
|
43000
|
-
if (!result.notified) this.log(`[schedule] ${kind} notification for run ${
|
|
43144
|
+
if (!result.notified) this.log(`[schedule] ${kind} notification for run ${run2.id}: ${result.reason ?? "not delivered"}`);
|
|
43001
43145
|
return result.notified;
|
|
43002
43146
|
}
|
|
43003
43147
|
/**
|
|
@@ -43010,26 +43154,26 @@ var Scheduler = class {
|
|
|
43010
43154
|
const resume = this.launch.resume;
|
|
43011
43155
|
if (this.recovered || !resume) return;
|
|
43012
43156
|
this.recovered = true;
|
|
43013
|
-
const open17 = (await readScheduleRuns(this.runsFile)).filter((
|
|
43014
|
-
for (const
|
|
43015
|
-
this.own.add(
|
|
43157
|
+
const open17 = (await readScheduleRuns(this.runsFile)).filter((run2) => runningStatuses.has(run2.status) && !this.own.has(run2.id));
|
|
43158
|
+
for (const run2 of open17) {
|
|
43159
|
+
this.own.add(run2.id);
|
|
43016
43160
|
let schedule;
|
|
43017
43161
|
try {
|
|
43018
|
-
schedule = (await readScheduleDocument(this.projectDirectory(
|
|
43162
|
+
schedule = (await readScheduleDocument(this.projectDirectory(run2.project))).schedules.find((item) => item.id === run2.scheduleId);
|
|
43019
43163
|
} catch {
|
|
43020
43164
|
schedule = void 0;
|
|
43021
43165
|
}
|
|
43022
43166
|
if (!schedule) {
|
|
43023
|
-
await this.updateRun(
|
|
43167
|
+
await this.updateRun(run2.id, {
|
|
43024
43168
|
status: "failed",
|
|
43025
43169
|
finishedAt: this.now().toISOString(),
|
|
43026
43170
|
reason: "Phren Hook restarted during this run, and its schedule no longer exists."
|
|
43027
|
-
}).catch((error62) => this.log(`[schedule] Could not close run ${
|
|
43171
|
+
}).catch((error62) => this.log(`[schedule] Could not close run ${run2.id}: ${String(error62)}`));
|
|
43028
43172
|
continue;
|
|
43029
43173
|
}
|
|
43030
43174
|
const known = schedule;
|
|
43031
|
-
this.log(`[schedule] Following run ${
|
|
43032
|
-
void resume(
|
|
43175
|
+
this.log(`[schedule] Following run ${run2.id} of "${known.name}", left ${run2.status} by an earlier Hook process.`);
|
|
43176
|
+
void resume(run2, known).catch((error62) => ({ status: "failed", reason: error62 instanceof Error ? error62.message : "The scheduled agent failed." })).then((result) => this.finishRun(run2.id, known, result.status, result.reason)).catch((error62) => this.log(`[schedule] Could not finish run ${run2.id}: ${String(error62)}`));
|
|
43033
43177
|
}
|
|
43034
43178
|
}
|
|
43035
43179
|
async tick() {
|
|
@@ -43055,23 +43199,23 @@ var Scheduler = class {
|
|
|
43055
43199
|
|
|
43056
43200
|
// src/bridge/canary.ts
|
|
43057
43201
|
init_phren_paths();
|
|
43058
|
-
import { lstat as lstat14, mkdtemp as mkdtemp4, realpath as
|
|
43202
|
+
import { lstat as lstat14, mkdtemp as mkdtemp4, realpath as realpath10, rm as rm7 } from "node:fs/promises";
|
|
43059
43203
|
import { hostname as hostname8, tmpdir } from "node:os";
|
|
43060
|
-
import
|
|
43204
|
+
import path61 from "node:path";
|
|
43061
43205
|
|
|
43062
43206
|
// src/bridge/health.ts
|
|
43063
43207
|
init_policy();
|
|
43064
43208
|
init_phren_paths();
|
|
43065
43209
|
init_store_registry();
|
|
43066
|
-
import { execFile as
|
|
43067
|
-
import { lstat as lstat13, readFile as
|
|
43210
|
+
import { execFile as execFile12, spawn as spawn8 } from "node:child_process";
|
|
43211
|
+
import { lstat as lstat13, readFile as readFile27 } from "node:fs/promises";
|
|
43068
43212
|
import { homedir as homedir16, hostname as hostname7 } from "node:os";
|
|
43069
|
-
import
|
|
43070
|
-
import { promisify as
|
|
43213
|
+
import path60 from "node:path";
|
|
43214
|
+
import { promisify as promisify11 } from "node:util";
|
|
43071
43215
|
init_protocol();
|
|
43072
43216
|
init_metrics();
|
|
43073
43217
|
init_terminal_tmux();
|
|
43074
|
-
var
|
|
43218
|
+
var exec11 = promisify11(execFile12);
|
|
43075
43219
|
async function terminalHealth() {
|
|
43076
43220
|
const [{ servers: servers2 }, tmux2] = await Promise.all([Promise.resolve().then(() => (init_herdr(), herdr_exports)), tmuxHealth()]);
|
|
43077
43221
|
const running2 = (await servers2().catch(() => [])).map((server) => ({
|
|
@@ -43132,7 +43276,7 @@ function plainError(value2) {
|
|
|
43132
43276
|
async function git3(cwd, args) {
|
|
43133
43277
|
try {
|
|
43134
43278
|
countGit("health");
|
|
43135
|
-
const { stdout } = await
|
|
43279
|
+
const { stdout } = await exec11("git", args, { cwd, timeout: 5e3, maxBuffer: 65536, env: { ...process.env, GIT_TERMINAL_PROMPT: "0" } });
|
|
43136
43280
|
return stdout.trim();
|
|
43137
43281
|
} catch {
|
|
43138
43282
|
return void 0;
|
|
@@ -43177,10 +43321,10 @@ async function storeSync(store) {
|
|
|
43177
43321
|
}
|
|
43178
43322
|
async function lastScheduledRun(store, runsFile = scheduleRunsFile()) {
|
|
43179
43323
|
const runs = await readScheduleRuns(runsFile).catch(() => []);
|
|
43180
|
-
const last = runs.reduce((newest,
|
|
43324
|
+
const last = runs.reduce((newest, run2) => !newest || run2.startedAt >= newest.startedAt ? run2 : newest, void 0);
|
|
43181
43325
|
if (!last) return null;
|
|
43182
43326
|
let name;
|
|
43183
|
-
const directory = getProjectDirs(store).find((dir) =>
|
|
43327
|
+
const directory = getProjectDirs(store).find((dir) => path60.basename(dir).toLowerCase() === last.project.toLowerCase());
|
|
43184
43328
|
if (directory) name = (await readScheduleDocument(directory).catch(() => void 0))?.schedules.find((item) => item.id === last.scheduleId)?.name;
|
|
43185
43329
|
return {
|
|
43186
43330
|
...name ? { name } : {},
|
|
@@ -43193,7 +43337,7 @@ async function lastScheduledRun(store, runsFile = scheduleRunsFile()) {
|
|
|
43193
43337
|
}
|
|
43194
43338
|
async function ownHostKey() {
|
|
43195
43339
|
try {
|
|
43196
|
-
return publicComputerKey(await
|
|
43340
|
+
return publicComputerKey(await readFile27("/etc/ssh/ssh_host_ed25519_key.pub", "utf8"));
|
|
43197
43341
|
} catch {
|
|
43198
43342
|
return void 0;
|
|
43199
43343
|
}
|
|
@@ -43234,20 +43378,20 @@ async function probePeer(peer, caller) {
|
|
|
43234
43378
|
}
|
|
43235
43379
|
}
|
|
43236
43380
|
function canaryFile(root = bridgeRoot()) {
|
|
43237
|
-
return
|
|
43381
|
+
return path60.join(root, "canary.json");
|
|
43238
43382
|
}
|
|
43239
43383
|
async function readCanary(root = bridgeRoot()) {
|
|
43240
43384
|
try {
|
|
43241
43385
|
const info = await lstat13(canaryFile(root));
|
|
43242
43386
|
if (!info.isFile() || info.size > 65536) return null;
|
|
43243
|
-
const value2 = JSON.parse(await
|
|
43387
|
+
const value2 = JSON.parse(await readFile27(canaryFile(root), "utf8"));
|
|
43244
43388
|
return value2 && value2.version === 1 && Array.isArray(value2.steps) ? value2 : null;
|
|
43245
43389
|
} catch {
|
|
43246
43390
|
return null;
|
|
43247
43391
|
}
|
|
43248
43392
|
}
|
|
43249
43393
|
async function pushConfigured() {
|
|
43250
|
-
const file2 = process.env.PHREN_APNS_CONFIG ||
|
|
43394
|
+
const file2 = process.env.PHREN_APNS_CONFIG || path60.join(bridgeRoot(), "apns.json");
|
|
43251
43395
|
const info = await lstat13(file2).catch(() => void 0);
|
|
43252
43396
|
return { configured: !!info?.isFile() };
|
|
43253
43397
|
}
|
|
@@ -43306,10 +43450,10 @@ function reason(error62) {
|
|
|
43306
43450
|
const text4 = error62 instanceof Error ? error62.message : "Unknown failure.";
|
|
43307
43451
|
return text4.replace(/[\x00-\x1f\x7f]+/g, " ").trim().slice(0, 300) || "Unknown failure.";
|
|
43308
43452
|
}
|
|
43309
|
-
async function step(steps, name,
|
|
43453
|
+
async function step(steps, name, run2) {
|
|
43310
43454
|
const started = Date.now();
|
|
43311
43455
|
try {
|
|
43312
|
-
steps.push({ name, durationMs: 0, ...await
|
|
43456
|
+
steps.push({ name, durationMs: 0, ...await run2() });
|
|
43313
43457
|
} catch (error62) {
|
|
43314
43458
|
steps.push({ name, durationMs: 0, status: "failed", reason: reason(error62) });
|
|
43315
43459
|
}
|
|
@@ -43336,7 +43480,7 @@ async function closeCanaryWorkspaces(server, before, created) {
|
|
|
43336
43480
|
}
|
|
43337
43481
|
async function conductorStep(options, server) {
|
|
43338
43482
|
const before = new Set(objects((await snapshot(server)).workspaces).map((workspace) => String(workspace.workspace_id)));
|
|
43339
|
-
const folder = await
|
|
43483
|
+
const folder = await realpath10(await mkdtemp4(path61.join(tmpdir(), "phren-canary-")));
|
|
43340
43484
|
let created, failure2, detail;
|
|
43341
43485
|
try {
|
|
43342
43486
|
const launched = await options.launch(server, { role: "conductor", kind: "claude", label: CANARY_LABEL, cwd: folder, timeoutMs: 45e3 });
|
|
@@ -43357,12 +43501,12 @@ async function scheduleStep(options) {
|
|
|
43357
43501
|
let count2 = 0;
|
|
43358
43502
|
const broken = [];
|
|
43359
43503
|
for (const directory of getProjectDirs(options.store)) {
|
|
43360
|
-
const present2 = await lstat14(
|
|
43504
|
+
const present2 = await lstat14(path61.join(directory, "schedules.yaml")).catch(() => void 0);
|
|
43361
43505
|
if (!present2) continue;
|
|
43362
43506
|
try {
|
|
43363
43507
|
count2 += (await readScheduleDocument(directory)).schedules.length;
|
|
43364
43508
|
} catch (error62) {
|
|
43365
|
-
broken.push(`${
|
|
43509
|
+
broken.push(`${path61.basename(directory)}: ${reason(error62)}`);
|
|
43366
43510
|
}
|
|
43367
43511
|
}
|
|
43368
43512
|
const tick = options.scheduler.lastTickAt;
|
|
@@ -43432,7 +43576,7 @@ function runCanary(options) {
|
|
|
43432
43576
|
}
|
|
43433
43577
|
async function dailyCanaryEnabled(root = bridgeRoot()) {
|
|
43434
43578
|
if (process.env.PHREN_CANARY_DAILY === "1") return true;
|
|
43435
|
-
return !!(await lstat14(
|
|
43579
|
+
return !!(await lstat14(path61.join(root, "canary-daily")).catch(() => void 0))?.isFile();
|
|
43436
43580
|
}
|
|
43437
43581
|
async function dailyCanaryDue(root = bridgeRoot(), now = Date.now()) {
|
|
43438
43582
|
if (running || !await dailyCanaryEnabled(root)) return false;
|
|
@@ -43445,11 +43589,11 @@ init_shared();
|
|
|
43445
43589
|
|
|
43446
43590
|
// src/bridge/server-routes.ts
|
|
43447
43591
|
init_zod();
|
|
43448
|
-
import
|
|
43592
|
+
import path84 from "node:path";
|
|
43449
43593
|
|
|
43450
43594
|
// src/bridge/code-note.ts
|
|
43451
43595
|
init_zod();
|
|
43452
|
-
import * as
|
|
43596
|
+
import * as path67 from "node:path";
|
|
43453
43597
|
|
|
43454
43598
|
// src/content/validate.ts
|
|
43455
43599
|
init_utils_helpers();
|
|
@@ -43463,7 +43607,7 @@ init_store_routing();
|
|
|
43463
43607
|
init_locks();
|
|
43464
43608
|
init_data_utils();
|
|
43465
43609
|
import * as fs28 from "fs";
|
|
43466
|
-
import * as
|
|
43610
|
+
import * as path63 from "path";
|
|
43467
43611
|
import * as crypto7 from "crypto";
|
|
43468
43612
|
|
|
43469
43613
|
// src/project-topics.ts
|
|
@@ -43475,7 +43619,7 @@ init_data_utils();
|
|
|
43475
43619
|
init_filenames();
|
|
43476
43620
|
import * as crypto6 from "crypto";
|
|
43477
43621
|
import * as fs27 from "fs";
|
|
43478
|
-
import * as
|
|
43622
|
+
import * as path62 from "path";
|
|
43479
43623
|
var TOPIC_CONFIG_FILENAME = "topic-config.json";
|
|
43480
43624
|
var SOFTWARE_TOPICS = [
|
|
43481
43625
|
{
|
|
@@ -44013,7 +44157,7 @@ function topicDocHeader(project, topic) {
|
|
|
44013
44157
|
}
|
|
44014
44158
|
function appendArchivedEntriesToTopicDoc(filePath, project, topic, entries2) {
|
|
44015
44159
|
if (entries2.length === 0) return;
|
|
44016
|
-
fs27.mkdirSync(
|
|
44160
|
+
fs27.mkdirSync(path62.dirname(filePath), { recursive: true });
|
|
44017
44161
|
withFileLock(filePath, () => {
|
|
44018
44162
|
let existing = "";
|
|
44019
44163
|
if (fs27.existsSync(filePath)) existing = fs27.readFileSync(filePath, "utf8");
|
|
@@ -44132,7 +44276,7 @@ function autoArchiveToReference(phrenPath, project, keepCount) {
|
|
|
44132
44276
|
if (!isValidProjectName(project)) return phrenErr(`Invalid project name: "${project}".`, PhrenError.INVALID_PROJECT_NAME);
|
|
44133
44277
|
const resolvedDir = storeAwareProjectPath(phrenPath, project);
|
|
44134
44278
|
if (!resolvedDir || !fs28.existsSync(resolvedDir)) return phrenErr(`Project "${project}" not found in phren.`, PhrenError.PROJECT_NOT_FOUND);
|
|
44135
|
-
const learningsPath =
|
|
44279
|
+
const learningsPath = path63.join(resolvedDir, FINDINGS_FILENAME);
|
|
44136
44280
|
if (!fs28.existsSync(learningsPath)) return phrenOk(0);
|
|
44137
44281
|
const STALE_LOCK_MS = 6e5;
|
|
44138
44282
|
const lockFile = runtimeFile(phrenPath, `consolidation-${project}.lock`);
|
|
@@ -44141,8 +44285,8 @@ function autoArchiveToReference(phrenPath, project, keepCount) {
|
|
|
44141
44285
|
} catch (e) {
|
|
44142
44286
|
if (e.code === "EEXIST") {
|
|
44143
44287
|
try {
|
|
44144
|
-
const
|
|
44145
|
-
if (Date.now() -
|
|
44288
|
+
const stat26 = fs28.statSync(lockFile);
|
|
44289
|
+
if (Date.now() - stat26.mtimeMs < STALE_LOCK_MS) {
|
|
44146
44290
|
return phrenErr("Consolidation already running", PhrenError.LOCK_TIMEOUT);
|
|
44147
44291
|
}
|
|
44148
44292
|
tryUnlink(lockFile);
|
|
@@ -44168,7 +44312,7 @@ function autoArchiveToReference(phrenPath, project, keepCount) {
|
|
|
44168
44312
|
const entries2 = parseActiveEntries(content);
|
|
44169
44313
|
if (entries2.length <= keepCount) return phrenOk(0);
|
|
44170
44314
|
const toArchive = entries2.slice(0, entries2.length - keepCount);
|
|
44171
|
-
const referenceDir =
|
|
44315
|
+
const referenceDir = path63.join(resolvedDir, "reference");
|
|
44172
44316
|
const { topics } = readProjectTopics(phrenPath, project);
|
|
44173
44317
|
const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
|
|
44174
44318
|
const archivedSet = buildArchivedBulletSet(referenceDir);
|
|
@@ -44732,7 +44876,7 @@ var DEFAULT_DECAY = {
|
|
|
44732
44876
|
var DEFAULT_UNDATED_CONFIDENCE = DEFAULT_DECAY.d120;
|
|
44733
44877
|
|
|
44734
44878
|
// src/content/dedup.ts
|
|
44735
|
-
import * as
|
|
44879
|
+
import * as path64 from "path";
|
|
44736
44880
|
init_shared();
|
|
44737
44881
|
init_utils();
|
|
44738
44882
|
init_store_routing();
|
|
@@ -44856,7 +45000,7 @@ function resolveCoref(text4, context) {
|
|
|
44856
45000
|
result = result.replace(/\bthe project\b/gi, context.project);
|
|
44857
45001
|
}
|
|
44858
45002
|
if (context.file) {
|
|
44859
|
-
const basename12 =
|
|
45003
|
+
const basename12 = path64.basename(context.file);
|
|
44860
45004
|
result = result.replace(/\b(this file|the file)\b/gi, basename12);
|
|
44861
45005
|
}
|
|
44862
45006
|
if (context.project && /\b(it|this|that|they|them)\b/i.test(result)) {
|
|
@@ -44873,7 +45017,7 @@ init_shared();
|
|
|
44873
45017
|
init_shared();
|
|
44874
45018
|
init_governance();
|
|
44875
45019
|
import * as fs30 from "fs";
|
|
44876
|
-
import * as
|
|
45020
|
+
import * as path66 from "path";
|
|
44877
45021
|
import * as crypto8 from "crypto";
|
|
44878
45022
|
|
|
44879
45023
|
// src/finding-graph-id.ts
|
|
@@ -44908,7 +45052,7 @@ init_store_routing();
|
|
|
44908
45052
|
// src/finding/context.ts
|
|
44909
45053
|
init_utils();
|
|
44910
45054
|
import * as fs29 from "fs";
|
|
44911
|
-
import * as
|
|
45055
|
+
import * as path65 from "path";
|
|
44912
45056
|
|
|
44913
45057
|
// src/session/utils.ts
|
|
44914
45058
|
init_utils();
|
|
@@ -44990,14 +45134,14 @@ function resolveFindingTaskReference(phrenPath, project, match) {
|
|
|
44990
45134
|
const projectDir = safeProjectPath(phrenPath, project);
|
|
44991
45135
|
if (!projectDir) return { error: `Invalid project name: "${project}".` };
|
|
44992
45136
|
const taskPath = resolveTaskFilePath(phrenPath, project);
|
|
44993
|
-
const items = parseTaskItems(taskPath ??
|
|
45137
|
+
const items = parseTaskItems(taskPath ?? path65.join(projectDir, "tasks.md"));
|
|
44994
45138
|
return resolveTaskItemMatch(items, match);
|
|
44995
45139
|
}
|
|
44996
45140
|
function resolveAutoFindingTaskItem(phrenPath, project) {
|
|
44997
45141
|
const projectDir = safeProjectPath(phrenPath, project);
|
|
44998
45142
|
if (!projectDir) return void 0;
|
|
44999
45143
|
const taskPath = resolveTaskFilePath(phrenPath, project);
|
|
45000
|
-
const active = parseTaskItems(taskPath ??
|
|
45144
|
+
const active = parseTaskItems(taskPath ?? path65.join(projectDir, "tasks.md")).filter(
|
|
45001
45145
|
(item) => item.section === "Active" && item.stableId
|
|
45002
45146
|
);
|
|
45003
45147
|
if (active.length === 1) return active[0].stableId;
|
|
@@ -45037,7 +45181,7 @@ function buildFindingCitation(citationInput, nowIso, inferredRepo, headCommit) {
|
|
|
45037
45181
|
function resolveInferredCitationRepo(citationInput) {
|
|
45038
45182
|
if (citationInput?.repo) return citationInput.repo;
|
|
45039
45183
|
if (citationInput?.file) {
|
|
45040
|
-
const fileDir =
|
|
45184
|
+
const fileDir = path66.dirname(citationInput.file);
|
|
45041
45185
|
return getRepoRoot(fileDir);
|
|
45042
45186
|
}
|
|
45043
45187
|
return void 0;
|
|
@@ -45172,7 +45316,7 @@ function addFindingToFile(phrenPath, project, learning, citationInput, opts) {
|
|
|
45172
45316
|
if (!isValidProjectName(project)) return phrenErr(`Invalid project name: "${project}".`, PhrenError.INVALID_PROJECT_NAME);
|
|
45173
45317
|
const resolvedDir = storeAwareProjectPath(phrenPath, project);
|
|
45174
45318
|
if (!resolvedDir) return phrenErr(`Invalid project name: "${project}".`, PhrenError.INVALID_PROJECT_NAME);
|
|
45175
|
-
const learningsPath =
|
|
45319
|
+
const learningsPath = path66.join(resolvedDir, FINDINGS_FILENAME);
|
|
45176
45320
|
const nowIso = (opts?.now ?? /* @__PURE__ */ new Date()).toISOString();
|
|
45177
45321
|
const today = nowIso.slice(0, 10);
|
|
45178
45322
|
const resolvedCitationInputResult = resolveFindingCitationInput(phrenPath, project, citationInput);
|
|
@@ -45354,7 +45498,7 @@ var codeNoteSchema = external_exports.object({
|
|
|
45354
45498
|
// phone's spelling, accepted until 0.3.1.
|
|
45355
45499
|
name: external_exports.string().min(1).max(4600).optional(),
|
|
45356
45500
|
symbol: external_exports.string().min(1).max(4600).optional(),
|
|
45357
|
-
file: external_exports.string().min(1).max(4096).refine((file2) => !
|
|
45501
|
+
file: external_exports.string().min(1).max(4096).refine((file2) => !path67.isAbsolute(file2) && !file2.includes("\0") && !file2.split(/[\\/]/).includes("..")),
|
|
45358
45502
|
line: external_exports.number().int().positive(),
|
|
45359
45503
|
text: external_exports.string().trim().min(1).max(4500).refine((text4) => !/[\x00-\x08\x0b-\x1f\x7f]/.test(text4)),
|
|
45360
45504
|
target: external_exports.union([external_exports.object({ session: sessionId }).strict(), external_exports.object({ harness: external_exports.enum(["codex", "claude", "opencode"]) }).strict()]).optional()
|
|
@@ -45404,29 +45548,29 @@ init_utils_helpers();
|
|
|
45404
45548
|
init_protocol();
|
|
45405
45549
|
init_herdr();
|
|
45406
45550
|
init_transcripts();
|
|
45407
|
-
import { execFile as
|
|
45408
|
-
import { promisify as
|
|
45551
|
+
import { execFile as execFile13 } from "node:child_process";
|
|
45552
|
+
import { promisify as promisify12 } from "node:util";
|
|
45409
45553
|
import { realpathSync as realpathSync5 } from "node:fs";
|
|
45410
|
-
import { readdir as
|
|
45554
|
+
import { readdir as readdir13, readFile as readFile28, stat as stat19, mkdir as mkdir15 } from "node:fs/promises";
|
|
45411
45555
|
import { homedir as homedir17 } from "node:os";
|
|
45412
|
-
import
|
|
45556
|
+
import path72 from "node:path";
|
|
45413
45557
|
|
|
45414
45558
|
// src/core/project.ts
|
|
45415
45559
|
init_shared();
|
|
45416
|
-
import * as
|
|
45560
|
+
import * as path70 from "path";
|
|
45417
45561
|
|
|
45418
45562
|
// src/core/project-registry.ts
|
|
45419
45563
|
init_phren_paths();
|
|
45420
45564
|
import * as fs32 from "fs";
|
|
45421
|
-
import * as
|
|
45565
|
+
import * as path69 from "path";
|
|
45422
45566
|
|
|
45423
45567
|
// src/git-worktree.ts
|
|
45424
45568
|
import * as fs31 from "fs";
|
|
45425
|
-
import * as
|
|
45569
|
+
import * as path68 from "path";
|
|
45426
45570
|
var WORKTREE_CONTAINER_NAMES = /* @__PURE__ */ new Set(["worktrees", ".worktrees"]);
|
|
45427
|
-
var LINKED_WORKTREE_SEGMENT = `${
|
|
45571
|
+
var LINKED_WORKTREE_SEGMENT = `${path68.sep}.git${path68.sep}worktrees${path68.sep}`;
|
|
45428
45572
|
function resolveWorktreeParent(dir) {
|
|
45429
|
-
const resolved =
|
|
45573
|
+
const resolved = path68.resolve(dir);
|
|
45430
45574
|
const agentParent = parentFromAgentWorktreePath(resolved);
|
|
45431
45575
|
if (agentParent) return { repoRoot: agentParent, reason: "agent-worktree-dir" };
|
|
45432
45576
|
const linkedParent = parentFromLinkedWorktree(resolved);
|
|
@@ -45434,23 +45578,23 @@ function resolveWorktreeParent(dir) {
|
|
|
45434
45578
|
return null;
|
|
45435
45579
|
}
|
|
45436
45580
|
function parentFromAgentWorktreePath(resolved) {
|
|
45437
|
-
const segments = resolved.split(
|
|
45581
|
+
const segments = resolved.split(path68.sep);
|
|
45438
45582
|
for (let i = 1; i < segments.length; i++) {
|
|
45439
45583
|
if (!WORKTREE_CONTAINER_NAMES.has(segments[i])) continue;
|
|
45440
45584
|
let j = i - 1;
|
|
45441
45585
|
if (!segments[j]?.startsWith(".")) continue;
|
|
45442
45586
|
while (j >= 1 && segments[j].startsWith(".")) j--;
|
|
45443
45587
|
if (j < 1) continue;
|
|
45444
|
-
return segments.slice(0, j + 1).join(
|
|
45588
|
+
return segments.slice(0, j + 1).join(path68.sep) || path68.sep;
|
|
45445
45589
|
}
|
|
45446
45590
|
return null;
|
|
45447
45591
|
}
|
|
45448
45592
|
function parentFromLinkedWorktree(resolved) {
|
|
45449
45593
|
let current2 = resolved;
|
|
45450
45594
|
while (true) {
|
|
45451
|
-
const parent = repoRootFromGitFile(
|
|
45595
|
+
const parent = repoRootFromGitFile(path68.join(current2, ".git"));
|
|
45452
45596
|
if (parent) return parent;
|
|
45453
|
-
const next =
|
|
45597
|
+
const next = path68.dirname(current2);
|
|
45454
45598
|
if (next === current2) return null;
|
|
45455
45599
|
current2 = next;
|
|
45456
45600
|
}
|
|
@@ -45465,7 +45609,7 @@ function repoRootFromGitFile(gitPath) {
|
|
|
45465
45609
|
}
|
|
45466
45610
|
const match = raw.match(/^\s*gitdir:\s*(.+?)\s*$/m);
|
|
45467
45611
|
if (!match) return null;
|
|
45468
|
-
const gitDir =
|
|
45612
|
+
const gitDir = path68.resolve(path68.dirname(gitPath), match[1].replace(/[/\\]/g, path68.sep));
|
|
45469
45613
|
const idx = gitDir.indexOf(LINKED_WORKTREE_SEGMENT);
|
|
45470
45614
|
if (idx === -1) return null;
|
|
45471
45615
|
return gitDir.slice(0, idx);
|
|
@@ -45618,8 +45762,8 @@ function addTermCount(terms, rawText, weight = 1) {
|
|
|
45618
45762
|
}
|
|
45619
45763
|
function maybeReadUtf8(filePath, maxBytes = 256e3) {
|
|
45620
45764
|
try {
|
|
45621
|
-
const
|
|
45622
|
-
if (!
|
|
45765
|
+
const stat26 = fs32.statSync(filePath);
|
|
45766
|
+
if (!stat26.isFile() || stat26.size > maxBytes) return "";
|
|
45623
45767
|
return fs32.readFileSync(filePath, "utf8");
|
|
45624
45768
|
} catch {
|
|
45625
45769
|
return "";
|
|
@@ -45678,7 +45822,7 @@ function scoreTopicsFromTerms(domain2, terms, docsText) {
|
|
|
45678
45822
|
return topics;
|
|
45679
45823
|
}
|
|
45680
45824
|
function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
|
|
45681
|
-
const resolvedRoot =
|
|
45825
|
+
const resolvedRoot = path69.resolve(repoRoot);
|
|
45682
45826
|
if (!fs32.existsSync(resolvedRoot)) return null;
|
|
45683
45827
|
const signal = {
|
|
45684
45828
|
domainScores: { software: 0, music: 0, game: 0, research: 0, writing: 0, creative: 0, other: 0 },
|
|
@@ -45689,7 +45833,7 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
|
|
|
45689
45833
|
usefulSignals: 0
|
|
45690
45834
|
};
|
|
45691
45835
|
const skipDirs = /* @__PURE__ */ new Set([".git", ".phren", "node_modules", "dist", "build", "coverage", ".next", ".turbo", "target"]);
|
|
45692
|
-
const packageJsonPath =
|
|
45836
|
+
const packageJsonPath = path69.join(resolvedRoot, "package.json");
|
|
45693
45837
|
if (fs32.existsSync(packageJsonPath)) {
|
|
45694
45838
|
signal.usefulSignals++;
|
|
45695
45839
|
addDomainScores(signal.domainScores, DOMAIN_CONFIG_HINTS["package.json"]);
|
|
@@ -45719,33 +45863,33 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
|
|
|
45719
45863
|
debugLog(`inferInitScaffoldFromRepo package.json parse failed: ${errorMessage(err)}`);
|
|
45720
45864
|
}
|
|
45721
45865
|
}
|
|
45722
|
-
const topLevelConfigs = Object.keys(DOMAIN_CONFIG_HINTS).filter((fileName) => fs32.existsSync(
|
|
45866
|
+
const topLevelConfigs = Object.keys(DOMAIN_CONFIG_HINTS).filter((fileName) => fs32.existsSync(path69.join(resolvedRoot, fileName)));
|
|
45723
45867
|
for (const configName of topLevelConfigs) {
|
|
45724
45868
|
signal.usefulSignals++;
|
|
45725
45869
|
const configScore = DOMAIN_CONFIG_HINTS[configName];
|
|
45726
45870
|
if (configScore) addDomainScores(signal.domainScores, configScore);
|
|
45727
45871
|
}
|
|
45728
45872
|
const readmeCandidates = [
|
|
45729
|
-
|
|
45730
|
-
|
|
45873
|
+
path69.join(resolvedRoot, "README.md"),
|
|
45874
|
+
path69.join(resolvedRoot, "readme.md")
|
|
45731
45875
|
];
|
|
45732
45876
|
for (const readmePath of readmeCandidates) {
|
|
45733
45877
|
if (!fs32.existsSync(readmePath)) continue;
|
|
45734
45878
|
const content = maybeReadUtf8(readmePath);
|
|
45735
45879
|
if (!content) continue;
|
|
45736
45880
|
signal.usefulSignals++;
|
|
45737
|
-
signal.referenceHints.push(
|
|
45881
|
+
signal.referenceHints.push(path69.relative(resolvedRoot, readmePath));
|
|
45738
45882
|
addTermCount(signal.terms, content, 2);
|
|
45739
45883
|
signal.docsText += ` ${content.toLowerCase()}`;
|
|
45740
45884
|
break;
|
|
45741
45885
|
}
|
|
45742
|
-
const docsDir =
|
|
45886
|
+
const docsDir = path69.join(resolvedRoot, "docs");
|
|
45743
45887
|
if (fs32.existsSync(docsDir) && fs32.statSync(docsDir).isDirectory()) {
|
|
45744
45888
|
signal.referenceHints.push("docs/");
|
|
45745
45889
|
for (const entry of fs32.readdirSync(docsDir, { withFileTypes: true })) {
|
|
45746
45890
|
if (!entry.isFile()) continue;
|
|
45747
45891
|
if (!/\.(md|txt|rst)$/i.test(entry.name)) continue;
|
|
45748
|
-
const docsContent = maybeReadUtf8(
|
|
45892
|
+
const docsContent = maybeReadUtf8(path69.join(docsDir, entry.name));
|
|
45749
45893
|
if (!docsContent) continue;
|
|
45750
45894
|
signal.usefulSignals++;
|
|
45751
45895
|
addTermCount(signal.terms, docsContent, 1);
|
|
@@ -45753,7 +45897,7 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
|
|
|
45753
45897
|
}
|
|
45754
45898
|
}
|
|
45755
45899
|
for (const folderName of ["reference", "specs", "design", "architecture", "src", "packages", "apps"]) {
|
|
45756
|
-
const fullPath =
|
|
45900
|
+
const fullPath = path69.join(resolvedRoot, folderName);
|
|
45757
45901
|
if (fs32.existsSync(fullPath)) {
|
|
45758
45902
|
signal.referenceHints.push(`${folderName}/`);
|
|
45759
45903
|
}
|
|
@@ -45764,14 +45908,14 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
|
|
|
45764
45908
|
if (scannedFiles >= maxFiles) return;
|
|
45765
45909
|
for (const entry of fs32.readdirSync(dir, { withFileTypes: true })) {
|
|
45766
45910
|
if (scannedFiles >= maxFiles) return;
|
|
45767
|
-
const fullPath =
|
|
45911
|
+
const fullPath = path69.join(dir, entry.name);
|
|
45768
45912
|
if (entry.isDirectory()) {
|
|
45769
45913
|
if (skipDirs.has(entry.name)) continue;
|
|
45770
45914
|
walk(fullPath);
|
|
45771
45915
|
continue;
|
|
45772
45916
|
}
|
|
45773
45917
|
scannedFiles++;
|
|
45774
|
-
const ext =
|
|
45918
|
+
const ext = path69.extname(entry.name).toLowerCase();
|
|
45775
45919
|
if (!ext) continue;
|
|
45776
45920
|
const extScore = EXTENSION_DOMAIN_HINTS[ext];
|
|
45777
45921
|
if (extScore) {
|
|
@@ -45945,7 +46089,7 @@ function findExistingProjectForSource(phrenPath, sourceRoot, derivedName) {
|
|
|
45945
46089
|
return null;
|
|
45946
46090
|
}
|
|
45947
46091
|
};
|
|
45948
|
-
const resolvedSource =
|
|
46092
|
+
const resolvedSource = path69.resolve(sourceRoot);
|
|
45949
46093
|
for (const project of candidates) {
|
|
45950
46094
|
if (sourceOf(project) === resolvedSource) return project;
|
|
45951
46095
|
}
|
|
@@ -45959,7 +46103,7 @@ function findExistingProjectForSource(phrenPath, sourceRoot, derivedName) {
|
|
|
45959
46103
|
function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
|
|
45960
46104
|
const profile = typeof opts === "string" ? opts : opts.profile;
|
|
45961
46105
|
const profilePhrenPath = typeof opts === "string" ? phrenPath : opts.profilePhrenPath ?? phrenPath;
|
|
45962
|
-
const resolvedPath =
|
|
46106
|
+
const resolvedPath = path69.resolve(projectPath);
|
|
45963
46107
|
if (!fs32.existsSync(resolvedPath)) {
|
|
45964
46108
|
throw new Error(`Path does not exist: ${resolvedPath}`);
|
|
45965
46109
|
}
|
|
@@ -45970,17 +46114,17 @@ function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
|
|
|
45970
46114
|
if (worktreeRepoRoot) {
|
|
45971
46115
|
debugLog(`bootstrapFromExisting: ${resolvedPath} is a ${worktree.reason}; attributing to ${worktreeRepoRoot}`);
|
|
45972
46116
|
}
|
|
45973
|
-
const sourceRoot = isProjectLocal ?
|
|
46117
|
+
const sourceRoot = isProjectLocal ? path69.resolve(manifest.workspaceRoot || resolvedPath) : worktreeRepoRoot ?? resolvedPath;
|
|
45974
46118
|
if (isProjectLocal) {
|
|
45975
|
-
const matchesWorkspace = resolvedPath === sourceRoot || resolvedPath.startsWith(sourceRoot +
|
|
46119
|
+
const matchesWorkspace = resolvedPath === sourceRoot || resolvedPath.startsWith(sourceRoot + path69.sep);
|
|
45976
46120
|
if (!matchesWorkspace) {
|
|
45977
46121
|
throw new Error(`Project-local phren can only enroll the owning workspace: ${sourceRoot}`);
|
|
45978
46122
|
}
|
|
45979
46123
|
}
|
|
45980
46124
|
let claudeMdPath = null;
|
|
45981
46125
|
const candidates = [
|
|
45982
|
-
|
|
45983
|
-
|
|
46126
|
+
path69.join(sourceRoot, "AGENTS.md"),
|
|
46127
|
+
path69.join(sourceRoot, ".claude", "CLAUDE.md")
|
|
45984
46128
|
];
|
|
45985
46129
|
for (const c of candidates) {
|
|
45986
46130
|
if (fs32.existsSync(c)) {
|
|
@@ -46000,12 +46144,12 @@ function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
|
|
|
46000
46144
|
`Project "${existingProject}" already exists with different casing. Refusing to bootstrap "${projectName2}" because it would split the same project on case-sensitive filesystems.`
|
|
46001
46145
|
);
|
|
46002
46146
|
}
|
|
46003
|
-
const projDir =
|
|
46147
|
+
const projDir = path69.join(phrenPath, projectName2);
|
|
46004
46148
|
fs32.mkdirSync(projDir, { recursive: true });
|
|
46005
46149
|
const inferredScaffold = inferInitScaffoldFromRepo(sourceRoot);
|
|
46006
46150
|
const existingConfig = readProjectConfig(phrenPath, projectName2);
|
|
46007
46151
|
const ownership = typeof opts === "string" ? parseProjectOwnershipMode(existingConfig.ownership) ?? getProjectOwnershipDefault(phrenPath) : opts.ownership ?? parseProjectOwnershipMode(existingConfig.ownership) ?? getProjectOwnershipDefault(phrenPath);
|
|
46008
|
-
const claudePath =
|
|
46152
|
+
const claudePath = path69.join(projDir, "AGENTS.md");
|
|
46009
46153
|
if (ownership !== "repo-managed") {
|
|
46010
46154
|
if (claudeContent) {
|
|
46011
46155
|
if (!fs32.existsSync(claudePath)) {
|
|
@@ -46040,7 +46184,7 @@ function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
|
|
|
46040
46184
|
}
|
|
46041
46185
|
}
|
|
46042
46186
|
const sourceInfo = claudeMdPath ? `**Source AGENTS.md:** ${claudeMdPath}` : `**Source:** ${sourceRoot}`;
|
|
46043
|
-
const summaryPath =
|
|
46187
|
+
const summaryPath = path69.join(projDir, "summary.md");
|
|
46044
46188
|
if (!fs32.existsSync(summaryPath)) {
|
|
46045
46189
|
atomicWriteText(
|
|
46046
46190
|
summaryPath,
|
|
@@ -46053,18 +46197,18 @@ ${summaryLines.length > 1 ? summaryLines.slice(1).join("\n") : ""}
|
|
|
46053
46197
|
`
|
|
46054
46198
|
);
|
|
46055
46199
|
}
|
|
46056
|
-
if (!fs32.existsSync(
|
|
46200
|
+
if (!fs32.existsSync(path69.join(projDir, FINDINGS_FILENAME))) {
|
|
46057
46201
|
atomicWriteText(
|
|
46058
|
-
|
|
46202
|
+
path69.join(projDir, FINDINGS_FILENAME),
|
|
46059
46203
|
`# ${projectName2} FINDINGS
|
|
46060
46204
|
|
|
46061
46205
|
<!-- Bootstrapped from ${sourceRoot} -->
|
|
46062
46206
|
`
|
|
46063
46207
|
);
|
|
46064
46208
|
}
|
|
46065
|
-
if (moduleEnabled(phrenPath, "tasks") && !fs32.existsSync(
|
|
46209
|
+
if (moduleEnabled(phrenPath, "tasks") && !fs32.existsSync(path69.join(projDir, TASKS_FILENAME))) {
|
|
46066
46210
|
atomicWriteText(
|
|
46067
|
-
|
|
46211
|
+
path69.join(projDir, TASKS_FILENAME),
|
|
46068
46212
|
`# ${projectName2} tasks
|
|
46069
46213
|
|
|
46070
46214
|
## Active
|
|
@@ -46075,11 +46219,11 @@ ${summaryLines.length > 1 ? summaryLines.slice(1).join("\n") : ""}
|
|
|
46075
46219
|
`
|
|
46076
46220
|
);
|
|
46077
46221
|
}
|
|
46078
|
-
if (!fs32.existsSync(
|
|
46222
|
+
if (!fs32.existsSync(path69.join(projDir, "topic-config.json"))) {
|
|
46079
46223
|
const inferredDomain = normalizeBuiltinTopicDomain(inferredScaffold?.domain ?? "software");
|
|
46080
46224
|
const inferredTopics = inferredScaffold?.topics?.length ? inferredScaffold.topics : getBuiltinTopicConfig(inferredDomain);
|
|
46081
46225
|
atomicWriteText(
|
|
46082
|
-
|
|
46226
|
+
path69.join(projDir, "topic-config.json"),
|
|
46083
46227
|
JSON.stringify({ version: 1, domain: inferredDomain, topics: inferredTopics }, null, 2) + "\n"
|
|
46084
46228
|
);
|
|
46085
46229
|
}
|
|
@@ -46111,10 +46255,10 @@ function addProjectFromPath(phrenPath, targetPath, requestedProfile, ownership,
|
|
|
46111
46255
|
if (!activeProfile.ok) return activeProfile;
|
|
46112
46256
|
const writePhrenPath = options.writeToPath ?? phrenPath;
|
|
46113
46257
|
const manifest = readRootManifest(phrenPath);
|
|
46114
|
-
const resolvedPath =
|
|
46258
|
+
const resolvedPath = path70.resolve(targetPath);
|
|
46115
46259
|
if (manifest?.installMode === "project-local") {
|
|
46116
|
-
const workspaceRoot =
|
|
46117
|
-
const matchesWorkspace = resolvedPath === workspaceRoot || resolvedPath.startsWith(workspaceRoot +
|
|
46260
|
+
const workspaceRoot = path70.resolve(manifest.workspaceRoot || "");
|
|
46261
|
+
const matchesWorkspace = resolvedPath === workspaceRoot || resolvedPath.startsWith(workspaceRoot + path70.sep);
|
|
46118
46262
|
if (!matchesWorkspace) {
|
|
46119
46263
|
return phrenErr(`Project-local phren can only add the owning workspace: ${workspaceRoot}`);
|
|
46120
46264
|
}
|
|
@@ -46132,9 +46276,9 @@ function addProjectFromPath(phrenPath, targetPath, requestedProfile, ownership,
|
|
|
46132
46276
|
ownership: added.ownership,
|
|
46133
46277
|
files: {
|
|
46134
46278
|
claude: added.claudePath,
|
|
46135
|
-
summary:
|
|
46136
|
-
findings:
|
|
46137
|
-
task:
|
|
46279
|
+
summary: path70.join(writePhrenPath, added.project, "summary.md"),
|
|
46280
|
+
findings: path70.join(writePhrenPath, added.project, FINDINGS_FILENAME),
|
|
46281
|
+
task: path70.join(writePhrenPath, added.project, TASKS_FILENAME)
|
|
46138
46282
|
}
|
|
46139
46283
|
});
|
|
46140
46284
|
}
|
|
@@ -46160,7 +46304,7 @@ import { execFileSync as execFileSync6, spawnSync as spawnSync2 } from "child_pr
|
|
|
46160
46304
|
import * as crypto9 from "crypto";
|
|
46161
46305
|
import * as fs33 from "fs";
|
|
46162
46306
|
import * as os3 from "os";
|
|
46163
|
-
import * as
|
|
46307
|
+
import * as path71 from "path";
|
|
46164
46308
|
|
|
46165
46309
|
// src/content/summarize.ts
|
|
46166
46310
|
init_phren_dotenv();
|
|
@@ -46321,7 +46465,7 @@ function mergeTasksByBid(base, ours, theirs) {
|
|
|
46321
46465
|
// src/sync/conflict-resolve.ts
|
|
46322
46466
|
function conflictStrategy(relFile) {
|
|
46323
46467
|
const file2 = relFile.replace(/\\/g, "/");
|
|
46324
|
-
const name =
|
|
46468
|
+
const name = path71.posix.basename(file2).toLowerCase();
|
|
46325
46469
|
if (isTaskFileName(name)) return "tasks";
|
|
46326
46470
|
if (name === "findings.md") return "findings";
|
|
46327
46471
|
if (/^\.config\/task-archive\/[^/]+\.md$/i.test(file2)) return "archive";
|
|
@@ -46356,9 +46500,9 @@ function splitBlock(content, start, end) {
|
|
|
46356
46500
|
function mergeText(base, ours, theirs) {
|
|
46357
46501
|
if (ours === theirs || ours === base) return theirs;
|
|
46358
46502
|
if (theirs === base) return ours;
|
|
46359
|
-
const dir = fs33.mkdtempSync(
|
|
46503
|
+
const dir = fs33.mkdtempSync(path71.join(os3.tmpdir(), "phren-merge-"));
|
|
46360
46504
|
try {
|
|
46361
|
-
const [o, b, t] = ["ours", "base", "theirs"].map((name) =>
|
|
46505
|
+
const [o, b, t] = ["ours", "base", "theirs"].map((name) => path71.join(dir, name));
|
|
46362
46506
|
fs33.writeFileSync(o, ours);
|
|
46363
46507
|
fs33.writeFileSync(b, base);
|
|
46364
46508
|
fs33.writeFileSync(t, theirs);
|
|
@@ -46371,9 +46515,9 @@ function mergeText(base, ours, theirs) {
|
|
|
46371
46515
|
function unionText(base, ours, theirs) {
|
|
46372
46516
|
const clean2 = mergeText(base, ours, theirs);
|
|
46373
46517
|
if (clean2 !== null) return clean2;
|
|
46374
|
-
const dir = fs33.mkdtempSync(
|
|
46518
|
+
const dir = fs33.mkdtempSync(path71.join(os3.tmpdir(), "phren-merge-"));
|
|
46375
46519
|
try {
|
|
46376
|
-
const [o, b, t] = ["ours", "base", "theirs"].map((name) =>
|
|
46520
|
+
const [o, b, t] = ["ours", "base", "theirs"].map((name) => path71.join(dir, name));
|
|
46377
46521
|
fs33.writeFileSync(o, ours);
|
|
46378
46522
|
fs33.writeFileSync(b, base);
|
|
46379
46523
|
fs33.writeFileSync(t, theirs);
|
|
@@ -46433,7 +46577,7 @@ function resolveStoreConflicts(cwd) {
|
|
|
46433
46577
|
const base = stage(cwd, 1, relFile) ?? "";
|
|
46434
46578
|
const ours = stage(cwd, 2, relFile);
|
|
46435
46579
|
const theirs = stage(cwd, 3, relFile);
|
|
46436
|
-
const fullPath =
|
|
46580
|
+
const fullPath = path71.join(cwd, relFile);
|
|
46437
46581
|
if (ours === null && theirs === null) {
|
|
46438
46582
|
unresolved.push(relFile);
|
|
46439
46583
|
continue;
|
|
@@ -46444,7 +46588,7 @@ function resolveStoreConflicts(cwd) {
|
|
|
46444
46588
|
continue;
|
|
46445
46589
|
}
|
|
46446
46590
|
const tmp = `${fullPath}.tmp-${crypto9.randomUUID()}`;
|
|
46447
|
-
fs33.mkdirSync(
|
|
46591
|
+
fs33.mkdirSync(path71.dirname(fullPath), { recursive: true });
|
|
46448
46592
|
fs33.writeFileSync(tmp, merged);
|
|
46449
46593
|
fs33.renameSync(tmp, fullPath);
|
|
46450
46594
|
git4(cwd, ["add", "--", relFile]);
|
|
@@ -46711,7 +46855,7 @@ async function runBestEffortGit(args, cwd) {
|
|
|
46711
46855
|
// src/bridge/enroll.ts
|
|
46712
46856
|
init_metrics();
|
|
46713
46857
|
init_machine_identity();
|
|
46714
|
-
var
|
|
46858
|
+
var exec12 = promisify12(execFile13);
|
|
46715
46859
|
var runEnrollStoreGit = async (cwd, args) => {
|
|
46716
46860
|
const result = await runBestEffortGit(args, cwd);
|
|
46717
46861
|
return { ok: result.ok, output: result.output ?? "", error: result.error };
|
|
@@ -46724,7 +46868,7 @@ function repoName(url2) {
|
|
|
46724
46868
|
}
|
|
46725
46869
|
async function isRepository(directory) {
|
|
46726
46870
|
try {
|
|
46727
|
-
await
|
|
46871
|
+
await stat19(path72.join(directory, ".git"));
|
|
46728
46872
|
return true;
|
|
46729
46873
|
} catch {
|
|
46730
46874
|
return false;
|
|
@@ -46735,7 +46879,7 @@ async function registeredSources(env) {
|
|
|
46735
46879
|
const paths = /* @__PURE__ */ new Set(), names = /* @__PURE__ */ new Set();
|
|
46736
46880
|
let entries2 = [];
|
|
46737
46881
|
try {
|
|
46738
|
-
entries2 = (await
|
|
46882
|
+
entries2 = (await readdir13(store, { withFileTypes: true })).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => e.name);
|
|
46739
46883
|
} catch {
|
|
46740
46884
|
return { paths, names };
|
|
46741
46885
|
}
|
|
@@ -46744,7 +46888,7 @@ async function registeredSources(env) {
|
|
|
46744
46888
|
const source = readProjectConfig(store, project).sourcePath;
|
|
46745
46889
|
if (typeof source === "string" && source) {
|
|
46746
46890
|
try {
|
|
46747
|
-
paths.add(realpathSync5.native(
|
|
46891
|
+
paths.add(realpathSync5.native(path72.resolve(source)));
|
|
46748
46892
|
} catch {
|
|
46749
46893
|
}
|
|
46750
46894
|
}
|
|
@@ -46756,9 +46900,9 @@ async function candidateRepos(activity, env = process.env) {
|
|
|
46756
46900
|
const found = [];
|
|
46757
46901
|
const seen = /* @__PURE__ */ new Set();
|
|
46758
46902
|
const offer = async (directory, source, lastSeen) => {
|
|
46759
|
-
let dir =
|
|
46903
|
+
let dir = path72.resolve(directory);
|
|
46760
46904
|
try {
|
|
46761
|
-
if (!(await
|
|
46905
|
+
if (!(await stat19(dir)).isDirectory()) return;
|
|
46762
46906
|
dir = realpathSync5.native(dir);
|
|
46763
46907
|
} catch {
|
|
46764
46908
|
return;
|
|
@@ -46770,39 +46914,39 @@ async function candidateRepos(activity, env = process.env) {
|
|
|
46770
46914
|
};
|
|
46771
46915
|
const toplevel = async (directory) => {
|
|
46772
46916
|
let existing = directory;
|
|
46773
|
-
while (!await
|
|
46774
|
-
const parent =
|
|
46917
|
+
while (!await stat19(existing).catch(() => void 0)) {
|
|
46918
|
+
const parent = path72.dirname(existing);
|
|
46775
46919
|
if (parent === existing) return void 0;
|
|
46776
46920
|
existing = parent;
|
|
46777
46921
|
}
|
|
46778
46922
|
try {
|
|
46779
46923
|
countGit("enroll");
|
|
46780
|
-
return (await
|
|
46924
|
+
return (await exec12("git", ["-C", existing, "rev-parse", "--show-toplevel"], { env: nonInteractiveGitEnv(), timeout: 5e3 })).stdout.trim() || void 0;
|
|
46781
46925
|
} catch {
|
|
46782
46926
|
return void 0;
|
|
46783
46927
|
}
|
|
46784
46928
|
};
|
|
46785
46929
|
for (const event of [...activity].reverse()) {
|
|
46786
46930
|
const directory = typeof event.directory === "string" ? event.directory : void 0;
|
|
46787
|
-
if (!directory || !
|
|
46931
|
+
if (!directory || !path72.isAbsolute(directory)) continue;
|
|
46788
46932
|
const root = await toplevel(directory);
|
|
46789
46933
|
if (root) await offer(root, "activity", typeof event.at === "string" ? event.at : void 0);
|
|
46790
46934
|
}
|
|
46791
46935
|
try {
|
|
46792
|
-
const session = JSON.parse(await
|
|
46936
|
+
const session = JSON.parse(await readFile28(path72.join(herdrRoot(), "session.json"), "utf8"));
|
|
46793
46937
|
for (const match of JSON.stringify(session).matchAll(/"cwd":\s*"((?:\\.|[^"\\])*)"/g)) {
|
|
46794
46938
|
const directory = JSON.parse(`"${match[1]}"`);
|
|
46795
|
-
if (!
|
|
46939
|
+
if (!path72.isAbsolute(directory)) continue;
|
|
46796
46940
|
const root = await toplevel(directory);
|
|
46797
46941
|
if (root) await offer(root, "herdr");
|
|
46798
46942
|
}
|
|
46799
46943
|
} catch {
|
|
46800
46944
|
}
|
|
46801
46945
|
const home = homedir17();
|
|
46802
|
-
for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.map((r) =>
|
|
46946
|
+
for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.map((r) => path72.join(home, r))]) {
|
|
46803
46947
|
let children = [];
|
|
46804
46948
|
try {
|
|
46805
|
-
children = (await
|
|
46949
|
+
children = (await readdir13(root, { withFileTypes: true })).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => path72.join(root, e.name));
|
|
46806
46950
|
} catch {
|
|
46807
46951
|
continue;
|
|
46808
46952
|
}
|
|
@@ -46812,13 +46956,13 @@ async function candidateRepos(activity, env = process.env) {
|
|
|
46812
46956
|
}
|
|
46813
46957
|
async function cloneRoot(env) {
|
|
46814
46958
|
const home = homedir17();
|
|
46815
|
-
for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.filter((r) => r !== "Sites").map((r) =>
|
|
46959
|
+
for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.filter((r) => r !== "Sites").map((r) => path72.join(home, r))]) {
|
|
46816
46960
|
try {
|
|
46817
|
-
if ((await
|
|
46961
|
+
if ((await stat19(root)).isDirectory()) return root;
|
|
46818
46962
|
} catch {
|
|
46819
46963
|
}
|
|
46820
46964
|
}
|
|
46821
|
-
const fallback =
|
|
46965
|
+
const fallback = path72.join(home, "Projects");
|
|
46822
46966
|
await mkdir15(fallback, { recursive: true });
|
|
46823
46967
|
return fallback;
|
|
46824
46968
|
}
|
|
@@ -46840,7 +46984,7 @@ async function publishStore(store, project) {
|
|
|
46840
46984
|
async function enrollProject(input2, env = process.env) {
|
|
46841
46985
|
const store = phrenStoreRoot(env);
|
|
46842
46986
|
try {
|
|
46843
|
-
if (!(await
|
|
46987
|
+
if (!(await stat19(path72.join(store, ".config"))).isDirectory()) throw new Error();
|
|
46844
46988
|
} catch {
|
|
46845
46989
|
throw new BridgeError(409, "phren is not set up on this computer. Run phren init there.");
|
|
46846
46990
|
}
|
|
@@ -46851,16 +46995,16 @@ async function enrollProject(input2, env = process.env) {
|
|
|
46851
46995
|
if (url2.length > 512 || !CLONE_URL.test(url2)) throw new BridgeError(400, "Enter a GitHub repository URL (https://github.com/owner/repo).");
|
|
46852
46996
|
const name = repoName(url2);
|
|
46853
46997
|
if (!name || name === "." || name === "..") throw new BridgeError(400, "That URL has no repository name.");
|
|
46854
|
-
directory =
|
|
46998
|
+
directory = path72.join(await cloneRoot(env), name);
|
|
46855
46999
|
try {
|
|
46856
|
-
await
|
|
47000
|
+
await stat19(directory);
|
|
46857
47001
|
throw new BridgeError(409, `${directory} already exists on this computer. Add that folder instead.`);
|
|
46858
47002
|
} catch (error62) {
|
|
46859
47003
|
if (error62 instanceof BridgeError) throw error62;
|
|
46860
47004
|
}
|
|
46861
47005
|
try {
|
|
46862
47006
|
countGit("enroll");
|
|
46863
|
-
await
|
|
47007
|
+
await exec12("git", ["clone", "--", url2, directory], { timeout: 18e4, maxBuffer: 4194304, env: nonInteractiveGitEnv(env) });
|
|
46864
47008
|
} catch (error62) {
|
|
46865
47009
|
const detail = error62 instanceof Error && "stderr" in error62 ? String(error62.stderr ?? "").trim().split("\n").pop() : void 0;
|
|
46866
47010
|
throw new BridgeError(502, `git clone failed${detail ? `: ${detail}` : ""}.`);
|
|
@@ -46868,10 +47012,10 @@ async function enrollProject(input2, env = process.env) {
|
|
|
46868
47012
|
cloned = true;
|
|
46869
47013
|
} else if (typeof input2.directory === "string" && input2.directory) {
|
|
46870
47014
|
const raw = input2.directory;
|
|
46871
|
-
if (raw.length > 4096 || raw.includes("\0") || !
|
|
47015
|
+
if (raw.length > 4096 || raw.includes("\0") || !path72.isAbsolute(raw)) throw new BridgeError(400, "Enter the full folder path on this computer.");
|
|
46872
47016
|
try {
|
|
46873
47017
|
directory = realpathSync5.native(raw);
|
|
46874
|
-
if (!(await
|
|
47018
|
+
if (!(await stat19(directory)).isDirectory()) throw new Error();
|
|
46875
47019
|
} catch {
|
|
46876
47020
|
throw new BridgeError(404, "That folder is not on this computer.");
|
|
46877
47021
|
}
|
|
@@ -46884,29 +47028,29 @@ async function enrollProject(input2, env = process.env) {
|
|
|
46884
47028
|
// src/bridge/files.ts
|
|
46885
47029
|
init_protocol();
|
|
46886
47030
|
import { constants as constants4 } from "node:fs";
|
|
46887
|
-
import { lstat as lstat15, open as open13, readdir as
|
|
46888
|
-
import
|
|
47031
|
+
import { lstat as lstat15, open as open13, readdir as readdir14, realpath as realpath11 } from "node:fs/promises";
|
|
47032
|
+
import path73 from "node:path";
|
|
46889
47033
|
var MAX_BYTES = 2097152;
|
|
46890
47034
|
async function browseFiles(root, relative3) {
|
|
46891
|
-
if (relative3.length > 4096 || relative3.includes("\0") || relative3.includes("\\") ||
|
|
47035
|
+
if (relative3.length > 4096 || relative3.includes("\0") || relative3.includes("\\") || path73.isAbsolute(relative3) || relative3.split("/").some((part) => part === ".." || part === ".git")) {
|
|
46892
47036
|
throw new BridgeError(400, "Invalid repository path.");
|
|
46893
47037
|
}
|
|
46894
|
-
const base = await
|
|
47038
|
+
const base = await realpath11(root);
|
|
46895
47039
|
let file2 = base;
|
|
46896
47040
|
for (const part of relative3.split("/").filter((part2) => part2 && part2 !== ".")) {
|
|
46897
|
-
file2 =
|
|
47041
|
+
file2 = path73.join(file2, part);
|
|
46898
47042
|
if ((await lstat15(file2)).isSymbolicLink()) throw new BridgeError(403, "Symbolic links cannot be browsed.");
|
|
46899
47043
|
}
|
|
46900
|
-
const resolved = await
|
|
46901
|
-
if (resolved !== base && !resolved.startsWith(base +
|
|
47044
|
+
const resolved = await realpath11(file2);
|
|
47045
|
+
if (resolved !== base && !resolved.startsWith(base + path73.sep)) throw new BridgeError(403, "The path is outside this repository.");
|
|
46902
47046
|
const metadata = await lstat15(resolved);
|
|
46903
47047
|
if (metadata.isDirectory()) {
|
|
46904
|
-
const entries2 = (await
|
|
47048
|
+
const entries2 = (await readdir14(resolved, { withFileTypes: true })).filter((entry) => entry.name !== ".git" && (entry.isDirectory() || entry.isFile())).sort((a, b) => Number(b.isDirectory()) - Number(a.isDirectory()) || a.name.localeCompare(b.name));
|
|
46905
47049
|
return {
|
|
46906
47050
|
path: relative3,
|
|
46907
47051
|
kind: "directory",
|
|
46908
47052
|
truncated: entries2.length > 500,
|
|
46909
|
-
entries: entries2.slice(0, 500).map((entry) => ({ name: entry.name, path:
|
|
47053
|
+
entries: entries2.slice(0, 500).map((entry) => ({ name: entry.name, path: path73.posix.join(relative3, entry.name), kind: entry.isDirectory() ? "directory" : "file" }))
|
|
46910
47054
|
};
|
|
46911
47055
|
}
|
|
46912
47056
|
if (!metadata.isFile()) throw new BridgeError(400, "Only regular files can be viewed.");
|
|
@@ -46932,8 +47076,8 @@ async function browseFiles(root, relative3) {
|
|
|
46932
47076
|
// src/bridge/file-range.ts
|
|
46933
47077
|
init_protocol();
|
|
46934
47078
|
import { constants as constants5 } from "node:fs";
|
|
46935
|
-
import { lstat as lstat16, open as open14, realpath as
|
|
46936
|
-
import
|
|
47079
|
+
import { lstat as lstat16, open as open14, realpath as realpath12 } from "node:fs/promises";
|
|
47080
|
+
import path74 from "node:path";
|
|
46937
47081
|
var MAX_FILE_RANGE = 4 * 1024 * 1024;
|
|
46938
47082
|
var types = {
|
|
46939
47083
|
mp4: "video/mp4",
|
|
@@ -46970,11 +47114,11 @@ var types = {
|
|
|
46970
47114
|
xml: "text/xml"
|
|
46971
47115
|
};
|
|
46972
47116
|
function fileContentType(file2) {
|
|
46973
|
-
const ext =
|
|
47117
|
+
const ext = path74.extname(file2).slice(1).toLowerCase();
|
|
46974
47118
|
return types[ext] ?? (/^(ts|tsx|js|jsx|swift|py|rs|go|rb|sh|bash|zsh|c|h|cpp|hpp|cs|java|kt|html|css|scss|sql|toml|ini)$/.test(ext) ? "text/plain" : "application/octet-stream");
|
|
46975
47119
|
}
|
|
46976
|
-
function version2(
|
|
46977
|
-
return `${
|
|
47120
|
+
function version2(stat26) {
|
|
47121
|
+
return `${stat26.dev}:${stat26.ino}:${stat26.size}:${stat26.mtimeMs}:${stat26.ctimeMs}`;
|
|
46978
47122
|
}
|
|
46979
47123
|
function rangeInteger(value2, fallback) {
|
|
46980
47124
|
if (value2 === null) return fallback;
|
|
@@ -46987,22 +47131,22 @@ async function readFileRange(root, requested, offset, length, expectedVersion) {
|
|
|
46987
47131
|
throw new BridgeError(400, "File ranges must be between 0 and 4 MiB.");
|
|
46988
47132
|
}
|
|
46989
47133
|
try {
|
|
46990
|
-
const base = await
|
|
46991
|
-
const relative3 =
|
|
46992
|
-
if (relative3 === ".." || relative3.startsWith(`..${
|
|
47134
|
+
const base = await realpath12(root);
|
|
47135
|
+
const relative3 = path74.isAbsolute(requested) ? path74.relative(base, requested) : requested;
|
|
47136
|
+
if (relative3 === ".." || relative3.startsWith(`..${path74.sep}`) || path74.isAbsolute(relative3)) throw new BridgeError(403, "This file is outside the allowed folder.");
|
|
46993
47137
|
let file2 = base;
|
|
46994
|
-
for (const part of relative3.split(
|
|
46995
|
-
file2 =
|
|
47138
|
+
for (const part of relative3.split(path74.sep).filter((part2) => part2 && part2 !== ".")) {
|
|
47139
|
+
file2 = path74.join(file2, part);
|
|
46996
47140
|
if ((await lstat16(file2)).isSymbolicLink()) throw new BridgeError(403, "Symbolic links cannot be opened.");
|
|
46997
47141
|
}
|
|
46998
|
-
const resolved = await
|
|
46999
|
-
if (!resolved.startsWith(base +
|
|
47142
|
+
const resolved = await realpath12(file2);
|
|
47143
|
+
if (!resolved.startsWith(base + path74.sep)) throw new BridgeError(403, "This file is outside the allowed folder.");
|
|
47000
47144
|
const metadata = await lstat16(resolved);
|
|
47001
47145
|
if (!metadata.isFile()) throw new BridgeError(400, "Only regular files can be opened.");
|
|
47002
47146
|
const handle = await open14(resolved, constants5.O_RDONLY | constants5.O_NOFOLLOW | constants5.O_NONBLOCK);
|
|
47003
47147
|
try {
|
|
47004
47148
|
const current2 = await handle.stat();
|
|
47005
|
-
if (!current2.isFile() || version2(current2) !== version2(metadata) || await
|
|
47149
|
+
if (!current2.isFile() || version2(current2) !== version2(metadata) || await realpath12(file2) !== resolved) {
|
|
47006
47150
|
throw new BridgeError(409, "The file changed. Open it again.");
|
|
47007
47151
|
}
|
|
47008
47152
|
const revision = version2(current2);
|
|
@@ -47038,12 +47182,12 @@ async function readFileRange(root, requested, offset, length, expectedVersion) {
|
|
|
47038
47182
|
// src/bridge/memory-store.ts
|
|
47039
47183
|
init_zod();
|
|
47040
47184
|
init_protocol();
|
|
47041
|
-
import { execFile as
|
|
47185
|
+
import { execFile as execFile14 } from "node:child_process";
|
|
47042
47186
|
import { createHash as createHash15 } from "node:crypto";
|
|
47043
|
-
import { lstat as lstat17, mkdir as mkdir16, readFile as
|
|
47044
|
-
import
|
|
47045
|
-
import { promisify as
|
|
47046
|
-
var
|
|
47187
|
+
import { lstat as lstat17, mkdir as mkdir16, readFile as readFile29, realpath as realpath13, rename as rename7, rm as rm8, writeFile as writeFile8 } from "node:fs/promises";
|
|
47188
|
+
import path75 from "node:path";
|
|
47189
|
+
import { promisify as promisify13 } from "node:util";
|
|
47190
|
+
var exec13 = promisify13(execFile14);
|
|
47047
47191
|
var SHA = /^[0-9a-f]{40}$/;
|
|
47048
47192
|
var MAX_FILE = 4 * 1024 * 1024;
|
|
47049
47193
|
var queue = Promise.resolve();
|
|
@@ -47054,7 +47198,7 @@ function serialized(work) {
|
|
|
47054
47198
|
}
|
|
47055
47199
|
async function git5(store, args, env = {}) {
|
|
47056
47200
|
try {
|
|
47057
|
-
const { stdout } = await
|
|
47201
|
+
const { stdout } = await exec13("git", ["-C", store, ...args], {
|
|
47058
47202
|
env: { ...process.env, ...env, GIT_TERMINAL_PROMPT: "0" },
|
|
47059
47203
|
maxBuffer: 64 * 1024 * 1024,
|
|
47060
47204
|
timeout: 6e4
|
|
@@ -47069,12 +47213,12 @@ function blobSha(content) {
|
|
|
47069
47213
|
return createHash15("sha1").update(`blob ${content.length}\0`).update(content).digest("hex");
|
|
47070
47214
|
}
|
|
47071
47215
|
async function isRepository2(store) {
|
|
47072
|
-
return await lstat17(
|
|
47216
|
+
return await lstat17(path75.join(store, ".git")).catch(() => void 0) !== void 0;
|
|
47073
47217
|
}
|
|
47074
|
-
function storeHead(store, indexFile =
|
|
47218
|
+
function storeHead(store, indexFile = path75.join(bridgeRoot(), "store-snapshot.index")) {
|
|
47075
47219
|
return serialized(async () => {
|
|
47076
47220
|
if (!await isRepository2(store)) throw new BridgeError(409, "This computer's phren store is not a git repository. Run phren init.");
|
|
47077
|
-
await mkdir16(
|
|
47221
|
+
await mkdir16(path75.dirname(indexFile), { recursive: true, mode: 448 });
|
|
47078
47222
|
const env = { GIT_INDEX_FILE: indexFile };
|
|
47079
47223
|
if (!await lstat17(indexFile).catch(() => void 0)) {
|
|
47080
47224
|
const head = await git5(store, ["rev-parse", "--verify", "--quiet", "HEAD"]).catch(() => "");
|
|
@@ -47097,31 +47241,31 @@ async function storeTree(store, sha) {
|
|
|
47097
47241
|
async function storeBlob(store, sha) {
|
|
47098
47242
|
if (!SHA.test(sha)) throw new BridgeError(400, "Invalid blob sha.");
|
|
47099
47243
|
if ((await git5(store, ["cat-file", "-t", sha]).catch(() => "")).trim() !== "blob") throw new BridgeError(404, "Unknown blob.");
|
|
47100
|
-
const { stdout } = await
|
|
47244
|
+
const { stdout } = await exec13("git", ["-C", store, "cat-file", "blob", sha], { encoding: "buffer", maxBuffer: MAX_FILE * 4 });
|
|
47101
47245
|
return { sha, encoding: "base64", content: stdout.toString("base64") };
|
|
47102
47246
|
}
|
|
47103
47247
|
async function storeFile(store, relative3) {
|
|
47104
|
-
const normalized =
|
|
47105
|
-
if (!relative3 || relative3 !== normalized || normalized.startsWith("../") || normalized === ".." ||
|
|
47248
|
+
const normalized = path75.posix.normalize(relative3);
|
|
47249
|
+
if (!relative3 || relative3 !== normalized || normalized.startsWith("../") || normalized === ".." || path75.posix.isAbsolute(normalized) || normalized.split("/").some((part) => part === ".git" || part === "" || part === ".") || /[\0\r\n]/.test(normalized)) {
|
|
47106
47250
|
throw new BridgeError(400, "Invalid store path.");
|
|
47107
47251
|
}
|
|
47108
|
-
const root = await
|
|
47109
|
-
let parent =
|
|
47252
|
+
const root = await realpath13(store);
|
|
47253
|
+
let parent = path75.dirname(path75.join(root, normalized));
|
|
47110
47254
|
for (; ; ) {
|
|
47111
|
-
const real2 = await
|
|
47255
|
+
const real2 = await realpath13(parent).catch(() => void 0);
|
|
47112
47256
|
if (real2) {
|
|
47113
|
-
if (real2 !== root && !real2.startsWith(root +
|
|
47257
|
+
if (real2 !== root && !real2.startsWith(root + path75.sep)) throw new BridgeError(400, "Invalid store path.");
|
|
47114
47258
|
break;
|
|
47115
47259
|
}
|
|
47116
|
-
parent =
|
|
47260
|
+
parent = path75.dirname(parent);
|
|
47117
47261
|
}
|
|
47118
|
-
const file2 =
|
|
47262
|
+
const file2 = path75.join(root, normalized);
|
|
47119
47263
|
const info = await lstat17(file2).catch(() => void 0);
|
|
47120
47264
|
if (info && !info.isFile()) throw new BridgeError(400, "Invalid store path.");
|
|
47121
47265
|
return file2;
|
|
47122
47266
|
}
|
|
47123
47267
|
async function currentSha(file2) {
|
|
47124
|
-
const content = await
|
|
47268
|
+
const content = await readFile29(file2).catch((error62) => {
|
|
47125
47269
|
if (error62.code === "ENOENT") return null;
|
|
47126
47270
|
throw error62;
|
|
47127
47271
|
});
|
|
@@ -47136,7 +47280,7 @@ function putStoreFile(store, data) {
|
|
|
47136
47280
|
return serialized(async () => {
|
|
47137
47281
|
const file2 = await storeFile(store, input2.path);
|
|
47138
47282
|
if (await currentSha(file2) !== (input2.sha ?? null)) throw new BridgeError(409, `${input2.path} changed on this computer.`);
|
|
47139
|
-
await mkdir16(
|
|
47283
|
+
await mkdir16(path75.dirname(file2), { recursive: true });
|
|
47140
47284
|
const temporary = `${file2}.phren-${process.pid}-${Date.now()}`;
|
|
47141
47285
|
await writeFile8(temporary, content, { flag: "wx" });
|
|
47142
47286
|
await rename7(temporary, file2);
|
|
@@ -47168,17 +47312,17 @@ init_protocol();
|
|
|
47168
47312
|
|
|
47169
47313
|
// src/bridge/simulators.ts
|
|
47170
47314
|
init_protocol();
|
|
47171
|
-
import { execFile as
|
|
47172
|
-
import { chmod as chmod4, mkdir as mkdir17, readFile as
|
|
47315
|
+
import { execFile as execFile15 } from "node:child_process";
|
|
47316
|
+
import { chmod as chmod4, mkdir as mkdir17, readFile as readFile30, rename as rename8, stat as stat20, unlink as unlink5, writeFile as writeFile9 } from "node:fs/promises";
|
|
47173
47317
|
import { tmpdir as tmpdir3 } from "node:os";
|
|
47174
|
-
import
|
|
47318
|
+
import path76 from "node:path";
|
|
47175
47319
|
import { createHash as createHash16, randomUUID as randomUUID17 } from "node:crypto";
|
|
47176
|
-
import { promisify as
|
|
47177
|
-
var
|
|
47320
|
+
import { promisify as promisify14 } from "node:util";
|
|
47321
|
+
var exec14 = promisify14(execFile15);
|
|
47178
47322
|
var UDID = /^[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}$/i;
|
|
47179
47323
|
async function bootedSimulators() {
|
|
47180
47324
|
if (process.platform !== "darwin") return [];
|
|
47181
|
-
const { stdout } = await
|
|
47325
|
+
const { stdout } = await exec14("/usr/bin/xcrun", ["simctl", "list", "devices", "booted", "-j"], { timeout: 8e3, maxBuffer: 4194304 }).catch(() => ({ stdout: "{}" }));
|
|
47182
47326
|
let parsed = {};
|
|
47183
47327
|
try {
|
|
47184
47328
|
parsed = JSON.parse(stdout);
|
|
@@ -47199,10 +47343,10 @@ async function bootedSimulators() {
|
|
|
47199
47343
|
async function simulatorScreenshot(udid) {
|
|
47200
47344
|
if (!UDID.test(udid)) throw new BridgeError(400, "Invalid simulator identifier.");
|
|
47201
47345
|
if (process.platform !== "darwin") throw new BridgeError(404, "Simulators run on macOS only.");
|
|
47202
|
-
const file2 =
|
|
47346
|
+
const file2 = path76.join(tmpdir3(), `phren-sim-${randomUUID17()}.png`);
|
|
47203
47347
|
try {
|
|
47204
|
-
await
|
|
47205
|
-
return await
|
|
47348
|
+
await exec14("/usr/bin/xcrun", ["simctl", "io", udid, "screenshot", "--type=png", file2], { timeout: 15e3 });
|
|
47349
|
+
return await readFile30(file2);
|
|
47206
47350
|
} catch (error62) {
|
|
47207
47351
|
if (error62 instanceof BridgeError) throw error62;
|
|
47208
47352
|
throw new BridgeError(409, "Couldn't capture that simulator. Is it still booted?");
|
|
@@ -47218,22 +47362,22 @@ function helper() {
|
|
|
47218
47362
|
return building;
|
|
47219
47363
|
}
|
|
47220
47364
|
async function buildHelper() {
|
|
47221
|
-
const dir =
|
|
47222
|
-
const binary =
|
|
47223
|
-
const code = true ? '// Touches and keys for the iOS Simulator, without AppleScript: the window\n// is found through the Accessibility API and events are posted with CGEvent,\n// so one Accessibility grant for this helper is all macOS asks for.\n// Built on demand by Phren Hook with swiftc; see simulators.ts.\nimport ApplicationServices\nimport Cocoa\n\nfunc fail(_ code: Int32, _ message: String) -> Never { FileHandle.standardError.write((message + "\\n").data(using: .utf8)!); exit(code) }\n\nlet args = CommandLine.arguments\nguard args.count >= 3 else { fail(2, "usage: simtap <window-title-prefix> tap <fx> <fy> | key <keycode> [cmd] [shift] | type <text> | raise") }\nlet prefix = args[1], command = args[2]\n\nguard AXIsProcessTrusted() else { fail(3, "accessibility") }\nguard let app = NSRunningApplication.runningApplications(withBundleIdentifier: "com.apple.iphonesimulator").first else { fail(4, "Simulator is not running") }\nlet element = AXUIElementCreateApplication(app.processIdentifier)\nvar windowsRef: CFTypeRef?\nAXUIElementCopyAttributeValue(element, kAXWindowsAttribute as CFString, &windowsRef)\nlet windows = (windowsRef as? [AXUIElement]) ?? []\nvar target: AXUIElement?\nfor window in windows {\n var titleRef: CFTypeRef?\n AXUIElementCopyAttributeValue(window, kAXTitleAttribute as CFString, &titleRef)\n if let title = titleRef as? String, title.hasPrefix(prefix + " ") || title == prefix { target = window; break }\n}\nguard let window = target else { fail(5, "no window for \\(prefix)") }\n\nfunc frame(_ window: AXUIElement) -> CGRect {\n var posRef: CFTypeRef?, sizeRef: CFTypeRef?\n AXUIElementCopyAttributeValue(window, kAXPositionAttribute as CFString, &posRef)\n AXUIElementCopyAttributeValue(window, kAXSizeAttribute as CFString, &sizeRef)\n var pos = CGPoint.zero, size = CGSize.zero\n if let p = posRef { AXValueGetValue(p as! AXValue, .cgPoint, &pos) }\n if let s = sizeRef { AXValueGetValue(s as! AXValue, .cgSize, &size) }\n return CGRect(origin: pos, size: size)\n}\nfunc raise() {\n app.activate(options: [])\n AXUIElementPerformAction(window, kAXRaiseAction as CFString)\n usleep(120_000)\n}\nfunc post(_ event: CGEvent?) {\n guard NSWorkspace.shared.frontmostApplication?.processIdentifier == app.processIdentifier else { fail(6, "focus lost") }\n event?.postToPid(app.processIdentifier)\n usleep(40_000)\n}\n\nswitch command {\ncase "raise": raise()\ncase "tap":\n guard args.count >= 5, let fx = Double(args[3]), let fy = Double(args[4]) else { fail(2, "tap needs fx fy") }\n raise()\n let f = frame(window)\n // The device screen fills the window below its title bar.\n let titleBar: CGFloat = 28\n let point = CGPoint(x: f.origin.x + CGFloat(fx) * f.width, y: f.origin.y + titleBar + CGFloat(fy) * (f.height - titleBar))\n post(CGEvent(mouseEventSource: nil, mouseType: .mouseMoved, mouseCursorPosition: point, mouseButton: .left))\n post(CGEvent(mouseEventSource: nil, mouseType: .leftMouseDown, mouseCursorPosition: point, mouseButton: .left))\n post(CGEvent(mouseEventSource: nil, mouseType: .leftMouseUp, mouseCursorPosition: point, mouseButton: .left))\ncase "key":\n guard args.count >= 4, let code = UInt16(args[3]) else { fail(2, "key needs a keycode") }\n raise()\n var flags: CGEventFlags = []\n if args.contains("cmd") { flags.insert(.maskCommand) }\n if args.contains("shift") { flags.insert(.maskShift) }\n let down = CGEvent(keyboardEventSource: nil, virtualKey: code, keyDown: true), up = CGEvent(keyboardEventSource: nil, virtualKey: code, keyDown: false)\n down?.flags = flags; up?.flags = flags\n post(down); post(up)\ncase "type":\n guard args.count >= 4, !args[3].isEmpty, args[3].utf16.count <= 500 else { fail(2, "type needs at most 500 characters") }\n let submit = args.count == 5 && args[4] == "submit"\n guard args[3].unicodeScalars.allSatisfy({ scalar in\n (scalar.value >= 32 && scalar.value != 127) || (scalar.value == 10 && submit)\n }) else { fail(2, "invalid type controls; newline needs submit") }\n raise()\n for scalar in args[3].unicodeScalars {\n var chars = Array(String(scalar).utf16)\n let down = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: true), up = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: false)\n down?.keyboardSetUnicodeString(stringLength: chars.count, unicodeString: &chars)\n up?.keyboardSetUnicodeString(stringLength: chars.count, unicodeString: &chars)\n post(down); post(up)\n }\ndefault: fail(2, "unknown command \\(command)")\n}\n' : await
|
|
47365
|
+
const dir = path76.join(bridgeRoot(), "native");
|
|
47366
|
+
const binary = path76.join(dir, "simtap");
|
|
47367
|
+
const code = true ? '// Touches and keys for the iOS Simulator, without AppleScript: the window\n// is found through the Accessibility API and events are posted with CGEvent,\n// so one Accessibility grant for this helper is all macOS asks for.\n// Built on demand by Phren Hook with swiftc; see simulators.ts.\nimport ApplicationServices\nimport Cocoa\n\nfunc fail(_ code: Int32, _ message: String) -> Never { FileHandle.standardError.write((message + "\\n").data(using: .utf8)!); exit(code) }\n\nlet args = CommandLine.arguments\nguard args.count >= 3 else { fail(2, "usage: simtap <window-title-prefix> tap <fx> <fy> | key <keycode> [cmd] [shift] | type <text> | raise") }\nlet prefix = args[1], command = args[2]\n\nguard AXIsProcessTrusted() else { fail(3, "accessibility") }\nguard let app = NSRunningApplication.runningApplications(withBundleIdentifier: "com.apple.iphonesimulator").first else { fail(4, "Simulator is not running") }\nlet element = AXUIElementCreateApplication(app.processIdentifier)\nvar windowsRef: CFTypeRef?\nAXUIElementCopyAttributeValue(element, kAXWindowsAttribute as CFString, &windowsRef)\nlet windows = (windowsRef as? [AXUIElement]) ?? []\nvar target: AXUIElement?\nfor window in windows {\n var titleRef: CFTypeRef?\n AXUIElementCopyAttributeValue(window, kAXTitleAttribute as CFString, &titleRef)\n if let title = titleRef as? String, title.hasPrefix(prefix + " ") || title == prefix { target = window; break }\n}\nguard let window = target else { fail(5, "no window for \\(prefix)") }\n\nfunc frame(_ window: AXUIElement) -> CGRect {\n var posRef: CFTypeRef?, sizeRef: CFTypeRef?\n AXUIElementCopyAttributeValue(window, kAXPositionAttribute as CFString, &posRef)\n AXUIElementCopyAttributeValue(window, kAXSizeAttribute as CFString, &sizeRef)\n var pos = CGPoint.zero, size = CGSize.zero\n if let p = posRef { AXValueGetValue(p as! AXValue, .cgPoint, &pos) }\n if let s = sizeRef { AXValueGetValue(s as! AXValue, .cgSize, &size) }\n return CGRect(origin: pos, size: size)\n}\nfunc raise() {\n app.activate(options: [])\n AXUIElementPerformAction(window, kAXRaiseAction as CFString)\n usleep(120_000)\n}\nfunc post(_ event: CGEvent?) {\n guard NSWorkspace.shared.frontmostApplication?.processIdentifier == app.processIdentifier else { fail(6, "focus lost") }\n event?.postToPid(app.processIdentifier)\n usleep(40_000)\n}\n\nswitch command {\ncase "raise": raise()\ncase "tap":\n guard args.count >= 5, let fx = Double(args[3]), let fy = Double(args[4]) else { fail(2, "tap needs fx fy") }\n raise()\n let f = frame(window)\n // The device screen fills the window below its title bar.\n let titleBar: CGFloat = 28\n let point = CGPoint(x: f.origin.x + CGFloat(fx) * f.width, y: f.origin.y + titleBar + CGFloat(fy) * (f.height - titleBar))\n post(CGEvent(mouseEventSource: nil, mouseType: .mouseMoved, mouseCursorPosition: point, mouseButton: .left))\n post(CGEvent(mouseEventSource: nil, mouseType: .leftMouseDown, mouseCursorPosition: point, mouseButton: .left))\n post(CGEvent(mouseEventSource: nil, mouseType: .leftMouseUp, mouseCursorPosition: point, mouseButton: .left))\ncase "key":\n guard args.count >= 4, let code = UInt16(args[3]) else { fail(2, "key needs a keycode") }\n raise()\n var flags: CGEventFlags = []\n if args.contains("cmd") { flags.insert(.maskCommand) }\n if args.contains("shift") { flags.insert(.maskShift) }\n let down = CGEvent(keyboardEventSource: nil, virtualKey: code, keyDown: true), up = CGEvent(keyboardEventSource: nil, virtualKey: code, keyDown: false)\n down?.flags = flags; up?.flags = flags\n post(down); post(up)\ncase "type":\n guard args.count >= 4, !args[3].isEmpty, args[3].utf16.count <= 500 else { fail(2, "type needs at most 500 characters") }\n let submit = args.count == 5 && args[4] == "submit"\n guard args[3].unicodeScalars.allSatisfy({ scalar in\n (scalar.value >= 32 && scalar.value != 127) || (scalar.value == 10 && submit)\n }) else { fail(2, "invalid type controls; newline needs submit") }\n raise()\n for scalar in args[3].unicodeScalars {\n var chars = Array(String(scalar).utf16)\n let down = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: true), up = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: false)\n down?.keyboardSetUnicodeString(stringLength: chars.count, unicodeString: &chars)\n up?.keyboardSetUnicodeString(stringLength: chars.count, unicodeString: &chars)\n post(down); post(up)\n }\ndefault: fail(2, "unknown command \\(command)")\n}\n' : await readFile30(new URL("./native/simtap.swift", import.meta.url), "utf8");
|
|
47224
47368
|
const digest2 = createHash16("sha256").update(code).digest("hex");
|
|
47225
|
-
const saved = await
|
|
47226
|
-
if (await
|
|
47369
|
+
const saved = await readFile30(binary + ".sha256", "utf8").then(JSON.parse).catch(() => void 0);
|
|
47370
|
+
if (await stat20(binary).catch(() => void 0) && saved?.sourceSha === digest2) return binary;
|
|
47227
47371
|
await mkdir17(dir, { recursive: true, mode: 448 });
|
|
47228
|
-
const temporary =
|
|
47372
|
+
const temporary = path76.join(dir, `simtap.${randomUUID17()}`), source = temporary + ".swift";
|
|
47229
47373
|
const sidecar = temporary + ".sha256";
|
|
47230
47374
|
try {
|
|
47231
47375
|
await writeFile9(source, code, { mode: 384, flag: "wx" });
|
|
47232
|
-
await
|
|
47376
|
+
await exec14("/usr/bin/swiftc", ["-O", "-o", temporary, source], { timeout: 18e4 }).catch(() => {
|
|
47233
47377
|
throw new BridgeError(409, "Couldn't build the simulator input helper (needs Xcode's swiftc).");
|
|
47234
47378
|
});
|
|
47235
47379
|
await chmod4(temporary, 448);
|
|
47236
|
-
const binarySha = createHash16("sha256").update(await
|
|
47380
|
+
const binarySha = createHash16("sha256").update(await readFile30(temporary)).digest("hex");
|
|
47237
47381
|
await writeFile9(sidecar, JSON.stringify({ sourceSha: digest2, binarySha }), { mode: 384, flag: "wx" });
|
|
47238
47382
|
await rename8(temporary, binary);
|
|
47239
47383
|
await rename8(sidecar, binary + ".sha256");
|
|
@@ -47251,11 +47395,11 @@ function simtap(name, ...args) {
|
|
|
47251
47395
|
}
|
|
47252
47396
|
async function executeSimtap(name, ...args) {
|
|
47253
47397
|
const binary = await helper();
|
|
47254
|
-
const saved = await
|
|
47255
|
-
const binarySha = createHash16("sha256").update(await
|
|
47398
|
+
const saved = await readFile30(binary + ".sha256", "utf8").then(JSON.parse).catch(() => void 0);
|
|
47399
|
+
const binarySha = createHash16("sha256").update(await readFile30(binary)).digest("hex");
|
|
47256
47400
|
if (!saved || saved.binarySha !== binarySha) throw new BridgeError(409, "Simulator input helper integrity check failed.");
|
|
47257
47401
|
try {
|
|
47258
|
-
await
|
|
47402
|
+
await exec14(binary, [name, ...args], { timeout: 6e4 });
|
|
47259
47403
|
} catch (error62) {
|
|
47260
47404
|
const failure2 = error62;
|
|
47261
47405
|
const message = String(failure2?.stderr ?? failure2?.message ?? "");
|
|
@@ -47271,7 +47415,7 @@ async function simulatorAct(udid, request6) {
|
|
|
47271
47415
|
if (!UDID.test(udid)) throw new BridgeError(400, "Invalid simulator identifier.");
|
|
47272
47416
|
if (!["boot", "shutdown", "launch", "openurl", "home", "lock", "type", "tap", "screenshot-ready"].includes(request6.action)) throw new BridgeError(400, "Unknown simulator action.");
|
|
47273
47417
|
if (process.platform !== "darwin") throw new BridgeError(404, "Simulators run on macOS only.");
|
|
47274
|
-
const simctl = (...args) =>
|
|
47418
|
+
const simctl = (...args) => exec14("/usr/bin/xcrun", ["simctl", ...args], { timeout: 3e4 }).catch(() => {
|
|
47275
47419
|
throw new BridgeError(409, `simctl ${args[0]} failed for that simulator.`);
|
|
47276
47420
|
});
|
|
47277
47421
|
switch (request6.action) {
|
|
@@ -47320,7 +47464,7 @@ async function deviceName(udid) {
|
|
|
47320
47464
|
async function simulatorApps(udid) {
|
|
47321
47465
|
if (!UDID.test(udid)) throw new BridgeError(400, "Invalid simulator identifier.");
|
|
47322
47466
|
if (process.platform !== "darwin") return [];
|
|
47323
|
-
const { stdout } = await
|
|
47467
|
+
const { stdout } = await exec14("/usr/bin/xcrun", ["simctl", "listapps", udid], { timeout: 15e3, maxBuffer: 4194304 }).catch(() => ({ stdout: "" }));
|
|
47324
47468
|
const apps = [];
|
|
47325
47469
|
const blocks = stdout.split(/\n(?=\s{4}"[^"]+" =\s+\{)/);
|
|
47326
47470
|
for (const block of blocks) {
|
|
@@ -47336,8 +47480,8 @@ init_transcripts();
|
|
|
47336
47480
|
|
|
47337
47481
|
// src/bridge/uploads.ts
|
|
47338
47482
|
init_protocol();
|
|
47339
|
-
import { mkdir as mkdir18, readdir as
|
|
47340
|
-
import
|
|
47483
|
+
import { mkdir as mkdir18, readdir as readdir15, lstat as lstat18, realpath as realpath14, readFile as readFile31, stat as stat21, unlink as unlink6, writeFile as writeFile10 } from "node:fs/promises";
|
|
47484
|
+
import path77 from "node:path";
|
|
47341
47485
|
import { randomUUID as randomUUID18 } from "node:crypto";
|
|
47342
47486
|
function imageBytes(bytes) {
|
|
47343
47487
|
return bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])) || bytes.subarray(0, 3).equals(Buffer.from([255, 216, 255])) || /^GIF8[79]a/.test(bytes.subarray(0, 6).toString()) || bytes.subarray(0, 4).toString() === "RIFF" && bytes.subarray(8, 12).toString() === "WEBP";
|
|
@@ -47350,24 +47494,24 @@ async function saveUpload(session, name, bytes) {
|
|
|
47350
47494
|
let saved = "";
|
|
47351
47495
|
const task = uploadQueue.catch(() => {
|
|
47352
47496
|
}).then(async () => {
|
|
47353
|
-
const root =
|
|
47497
|
+
const root = path77.join(bridgeRoot(), "uploads");
|
|
47354
47498
|
await mkdir18(root, { recursive: true, mode: 448 });
|
|
47355
47499
|
let used = 0;
|
|
47356
|
-
const directories = await
|
|
47500
|
+
const directories = await readdir15(root, { withFileTypes: true });
|
|
47357
47501
|
for (const dir of directories) {
|
|
47358
47502
|
if (!dir.isDirectory()) continue;
|
|
47359
|
-
const folder2 =
|
|
47360
|
-
for (const entry of await
|
|
47503
|
+
const folder2 = path77.join(root, dir.name);
|
|
47504
|
+
for (const entry of await readdir15(folder2, { withFileTypes: true })) {
|
|
47361
47505
|
if (!entry.isFile()) continue;
|
|
47362
|
-
const file2 =
|
|
47506
|
+
const file2 = path77.join(folder2, entry.name), metadata = await lstat18(file2);
|
|
47363
47507
|
if (Date.now() - metadata.mtimeMs > 14 * 864e5) await unlink6(file2);
|
|
47364
47508
|
else used += metadata.size;
|
|
47365
47509
|
}
|
|
47366
47510
|
}
|
|
47367
47511
|
if (used + bytes.length > 268435456) throw new BridgeError(413, "Phren's image storage is full. Remove older uploads on the computer.");
|
|
47368
|
-
const folder =
|
|
47512
|
+
const folder = path77.join(root, session);
|
|
47369
47513
|
await mkdir18(folder, { recursive: true, mode: 448 });
|
|
47370
|
-
saved =
|
|
47514
|
+
saved = path77.join(folder, `${randomUUID18()}-${name}`);
|
|
47371
47515
|
await writeFile10(saved, bytes, { flag: "wx", mode: 384 });
|
|
47372
47516
|
});
|
|
47373
47517
|
uploadQueue = task;
|
|
@@ -47375,26 +47519,26 @@ async function saveUpload(session, name, bytes) {
|
|
|
47375
47519
|
return saved;
|
|
47376
47520
|
}
|
|
47377
47521
|
async function listUploads(session) {
|
|
47378
|
-
const folder =
|
|
47379
|
-
const entries2 = await
|
|
47522
|
+
const folder = path77.join(bridgeRoot(), "uploads", session);
|
|
47523
|
+
const entries2 = await readdir15(folder, { withFileTypes: true }).catch(() => []);
|
|
47380
47524
|
const files = [];
|
|
47381
47525
|
for (const entry of entries2) {
|
|
47382
47526
|
if (!entry.isFile()) continue;
|
|
47383
|
-
const file2 =
|
|
47527
|
+
const file2 = path77.join(folder, entry.name), metadata = await stat21(file2);
|
|
47384
47528
|
files.push({ name: entry.name.replace(/^[0-9a-f-]{36}-/, ""), path: file2, size: metadata.size, modified: metadata.mtime.toISOString() });
|
|
47385
47529
|
}
|
|
47386
47530
|
return files.sort((a, b) => b.modified.localeCompare(a.modified)).slice(0, 200);
|
|
47387
47531
|
}
|
|
47388
47532
|
async function uploadImage(requested) {
|
|
47389
47533
|
const missing = new BridgeError(404, "This image is not one of the phone's uploads.");
|
|
47390
|
-
if (!requested || requested.length > 4096 || !
|
|
47391
|
-
const root = await
|
|
47392
|
-
const file2 = await
|
|
47393
|
-
if (!root || !file2 || !file2.startsWith(root +
|
|
47394
|
-
const metadata = await
|
|
47534
|
+
if (!requested || requested.length > 4096 || !path77.isAbsolute(requested)) throw missing;
|
|
47535
|
+
const root = await realpath14(path77.join(bridgeRoot(), "uploads")).catch(() => void 0);
|
|
47536
|
+
const file2 = await realpath14(requested).catch(() => void 0);
|
|
47537
|
+
if (!root || !file2 || !file2.startsWith(root + path77.sep)) throw missing;
|
|
47538
|
+
const metadata = await stat21(file2);
|
|
47395
47539
|
if (!metadata.isFile()) throw missing;
|
|
47396
47540
|
if (metadata.size > 8388608) throw new BridgeError(413, "This image is too large.");
|
|
47397
|
-
const bytes = await
|
|
47541
|
+
const bytes = await readFile31(file2);
|
|
47398
47542
|
if (bytes.length > 8388608) throw new BridgeError(413, "This image is too large.");
|
|
47399
47543
|
if (!imageBytes(bytes)) throw missing;
|
|
47400
47544
|
return bytes;
|
|
@@ -47404,7 +47548,7 @@ async function uploadImage(requested) {
|
|
|
47404
47548
|
init_transcript_index();
|
|
47405
47549
|
init_transcripts();
|
|
47406
47550
|
import { homedir as homedir18, tmpdir as tmpdir4 } from "node:os";
|
|
47407
|
-
import
|
|
47551
|
+
import path78 from "node:path";
|
|
47408
47552
|
init_protocol();
|
|
47409
47553
|
var cache = /* @__PURE__ */ new Map();
|
|
47410
47554
|
var modelCache = /* @__PURE__ */ new Map();
|
|
@@ -47542,7 +47686,7 @@ function describe3(tool, args) {
|
|
|
47542
47686
|
return "";
|
|
47543
47687
|
};
|
|
47544
47688
|
const firstLine = (v) => v.split(/\r?\n/).map((l) => l.trim()).find((l) => l) ?? "";
|
|
47545
|
-
const base = (v) =>
|
|
47689
|
+
const base = (v) => path78.basename(v.split(" \xB7 ")[0].trim()) || "file";
|
|
47546
47690
|
const name = tool.toLowerCase();
|
|
47547
47691
|
let value2;
|
|
47548
47692
|
if (["bash", "shell", "exec_command", "exec", "parallel", "tools", "write_stdin", "container.exec"].includes(name)) {
|
|
@@ -47577,17 +47721,17 @@ init_shared();
|
|
|
47577
47721
|
|
|
47578
47722
|
// src/bridge/server-pane-routes.ts
|
|
47579
47723
|
init_zod();
|
|
47580
|
-
import
|
|
47724
|
+
import path81 from "node:path";
|
|
47581
47725
|
import { setTimeout as sleep2 } from "node:timers/promises";
|
|
47582
47726
|
|
|
47583
47727
|
// src/bridge/git.ts
|
|
47584
47728
|
init_protocol();
|
|
47585
47729
|
import { createHash as createHash17 } from "node:crypto";
|
|
47586
|
-
import { execFile as
|
|
47587
|
-
import { lstat as lstat19, readdir as
|
|
47588
|
-
import
|
|
47589
|
-
import { promisify as
|
|
47590
|
-
var
|
|
47730
|
+
import { execFile as execFile16 } from "node:child_process";
|
|
47731
|
+
import { lstat as lstat19, readdir as readdir16, readFile as readFile32, realpath as realpath15, stat as stat22 } from "node:fs/promises";
|
|
47732
|
+
import path79 from "node:path";
|
|
47733
|
+
import { promisify as promisify15 } from "node:util";
|
|
47734
|
+
var exec15 = promisify15(execFile16);
|
|
47591
47735
|
function statusLetter(code) {
|
|
47592
47736
|
const letter = code[0];
|
|
47593
47737
|
return ["M", "A", "D", "R", "C", "U"].includes(letter) ? letter : "M";
|
|
@@ -47631,9 +47775,9 @@ function parseNumstat(out) {
|
|
|
47631
47775
|
}
|
|
47632
47776
|
async function countLines(root, rel) {
|
|
47633
47777
|
try {
|
|
47634
|
-
const abs =
|
|
47635
|
-
if ((await
|
|
47636
|
-
const bytes = await
|
|
47778
|
+
const abs = path79.join(root, await repositoryPath(root, rel));
|
|
47779
|
+
if ((await stat22(abs)).size > 5e6) return 0;
|
|
47780
|
+
const bytes = await readFile32(abs);
|
|
47637
47781
|
if (!bytes.length || bytes.includes(0)) return 0;
|
|
47638
47782
|
let lines = 0;
|
|
47639
47783
|
for (const byte of bytes) if (byte === 10) lines++;
|
|
@@ -47799,7 +47943,7 @@ function checkRollup(items) {
|
|
|
47799
47943
|
}
|
|
47800
47944
|
async function currentPull(root, branch) {
|
|
47801
47945
|
try {
|
|
47802
|
-
const { stdout } = await
|
|
47946
|
+
const { stdout } = await exec15("gh", ["pr", "view", "--json", "number,title,url,state,isDraft,headRefName,baseRefName,statusCheckRollup"], {
|
|
47803
47947
|
cwd: root,
|
|
47804
47948
|
timeout: 15e3,
|
|
47805
47949
|
maxBuffer: 4194304,
|
|
@@ -47826,7 +47970,7 @@ async function gitPulls(cwd) {
|
|
|
47826
47970
|
const branch = (await git2(root, "branch", "--show-current").catch(() => "")).trim();
|
|
47827
47971
|
try {
|
|
47828
47972
|
const [{ stdout }, current2] = await Promise.all([
|
|
47829
|
-
|
|
47973
|
+
exec15("gh", ["pr", "list", "--json", "number,title,headRefName,baseRefName,author,url,isDraft,state,updatedAt", "--limit", "50"], {
|
|
47830
47974
|
cwd: root,
|
|
47831
47975
|
timeout: 15e3,
|
|
47832
47976
|
maxBuffer: 4194304,
|
|
@@ -47855,13 +47999,13 @@ async function gitPulls(cwd) {
|
|
|
47855
47999
|
}
|
|
47856
48000
|
}
|
|
47857
48001
|
async function repositoryPath(root, raw, allowRoot = false) {
|
|
47858
|
-
if (typeof raw !== "string" || raw.length > 4096 || raw.includes("\0") ||
|
|
48002
|
+
if (typeof raw !== "string" || raw.length > 4096 || raw.includes("\0") || path79.isAbsolute(raw) || path79.win32.isAbsolute(raw) || raw.startsWith("\\")) throw new BridgeError(400, "Invalid path.");
|
|
47859
48003
|
const segments = raw.split(/[\\/]/);
|
|
47860
48004
|
if (segments.includes("..")) throw new BridgeError(400, "Invalid path.");
|
|
47861
48005
|
const clean2 = segments.filter((part) => part && part !== ".").join("/");
|
|
47862
48006
|
if (!clean2 && !allowRoot || clean2.startsWith("-")) throw new BridgeError(400, "Invalid path.");
|
|
47863
|
-
const abs =
|
|
47864
|
-
if (abs !== root && !abs.startsWith(root +
|
|
48007
|
+
const abs = path79.resolve(root, clean2);
|
|
48008
|
+
if (abs !== root && !abs.startsWith(root + path79.sep)) throw new BridgeError(403, "This path is outside the repository.");
|
|
47865
48009
|
let existing = abs;
|
|
47866
48010
|
while (true) {
|
|
47867
48011
|
try {
|
|
@@ -47869,16 +48013,16 @@ async function repositoryPath(root, raw, allowRoot = false) {
|
|
|
47869
48013
|
break;
|
|
47870
48014
|
} catch (error62) {
|
|
47871
48015
|
if (error62.code !== "ENOENT" || existing === root) throw new BridgeError(400, "Invalid path.");
|
|
47872
|
-
existing =
|
|
48016
|
+
existing = path79.dirname(existing);
|
|
47873
48017
|
}
|
|
47874
48018
|
}
|
|
47875
48019
|
let resolved;
|
|
47876
48020
|
try {
|
|
47877
|
-
resolved = await
|
|
48021
|
+
resolved = await realpath15(existing);
|
|
47878
48022
|
} catch {
|
|
47879
48023
|
throw new BridgeError(403, "This path cannot be resolved inside the repository.");
|
|
47880
48024
|
}
|
|
47881
|
-
if (resolved !== root && !resolved.startsWith(root +
|
|
48025
|
+
if (resolved !== root && !resolved.startsWith(root + path79.sep)) throw new BridgeError(403, "This path is outside the repository.");
|
|
47882
48026
|
return clean2;
|
|
47883
48027
|
}
|
|
47884
48028
|
var treeCache = /* @__PURE__ */ new Map();
|
|
@@ -47960,7 +48104,7 @@ async function ignoredEntries(root, prefix, shown) {
|
|
|
47960
48104
|
const entries2 = /* @__PURE__ */ new Map();
|
|
47961
48105
|
const inside = prefix && listing.some((item) => item.endsWith("/") && (prefix + "/").startsWith(item));
|
|
47962
48106
|
if (inside) {
|
|
47963
|
-
const dirents = await
|
|
48107
|
+
const dirents = await readdir16(path79.join(root, prefix), { withFileTypes: true }).catch(() => []);
|
|
47964
48108
|
for (const dirent of dirents) {
|
|
47965
48109
|
if (dirent.name === ".git" || taken.has(dirent.name) || entries2.size >= MAX_IGNORED_ENTRIES) continue;
|
|
47966
48110
|
entries2.set(dirent.name, { name: dirent.name, path: `${prefix}/${dirent.name}`, kind: dirent.isDirectory() ? "dir" : "file", ignored: true });
|
|
@@ -48057,9 +48201,9 @@ init_fanouts();
|
|
|
48057
48201
|
// src/bridge/git-worktrees.ts
|
|
48058
48202
|
init_protocol();
|
|
48059
48203
|
import { createHash as createHash18 } from "node:crypto";
|
|
48060
|
-
import { realpath as
|
|
48204
|
+
import { realpath as realpath16, stat as stat23 } from "node:fs/promises";
|
|
48061
48205
|
import { homedir as homedir19 } from "node:os";
|
|
48062
|
-
import
|
|
48206
|
+
import path80 from "node:path";
|
|
48063
48207
|
var MAX_WORKTREES = 64;
|
|
48064
48208
|
var worktreeIdPattern = /^[a-f0-9]{32}$/;
|
|
48065
48209
|
function worktreeId(abs) {
|
|
@@ -48087,8 +48231,8 @@ async function listed(root) {
|
|
|
48087
48231
|
let main;
|
|
48088
48232
|
for (const [index2, block] of blocks.entries()) {
|
|
48089
48233
|
if (block.bare !== void 0 || block.prunable !== void 0) continue;
|
|
48090
|
-
const abs = await
|
|
48091
|
-
if (!abs || !(await
|
|
48234
|
+
const abs = await realpath16(block.worktree).catch(() => void 0);
|
|
48235
|
+
if (!abs || !(await stat23(abs).catch(() => void 0))?.isDirectory()) continue;
|
|
48092
48236
|
if (index2 === 0) main = abs;
|
|
48093
48237
|
const branch = block.branch?.startsWith("refs/heads/") ? block.branch.slice("refs/heads/".length) : null;
|
|
48094
48238
|
worktrees.push({ abs, head: block.HEAD ?? "", branch, locked: block.locked !== void 0 });
|
|
@@ -48098,11 +48242,11 @@ async function listed(root) {
|
|
|
48098
48242
|
}
|
|
48099
48243
|
function displayPath(abs, roots) {
|
|
48100
48244
|
for (const root of roots) {
|
|
48101
|
-
const rel =
|
|
48102
|
-
if (rel && !rel.startsWith("..") && !
|
|
48245
|
+
const rel = path80.relative(root, abs);
|
|
48246
|
+
if (rel && !rel.startsWith("..") && !path80.isAbsolute(rel)) return rel.split(path80.sep).join("/");
|
|
48103
48247
|
}
|
|
48104
48248
|
const home = homedir19();
|
|
48105
|
-
return abs === home ? "~" : abs.startsWith(home +
|
|
48249
|
+
return abs === home ? "~" : abs.startsWith(home + path80.sep) ? "~/" + path80.relative(home, abs).split(path80.sep).join("/") : abs;
|
|
48106
48250
|
}
|
|
48107
48251
|
function uncommitted(status) {
|
|
48108
48252
|
const tokens = status.split("\0");
|
|
@@ -48116,12 +48260,12 @@ function uncommitted(status) {
|
|
|
48116
48260
|
return count2;
|
|
48117
48261
|
}
|
|
48118
48262
|
async function workerFor(abs, workers, all = []) {
|
|
48119
|
-
const nested = all.filter((other) => other.startsWith(abs +
|
|
48263
|
+
const nested = all.filter((other) => other.startsWith(abs + path80.sep));
|
|
48120
48264
|
let best;
|
|
48121
48265
|
for (const worker of workers) {
|
|
48122
|
-
const cwd = await
|
|
48123
|
-
if (cwd !== abs && !cwd.startsWith(abs +
|
|
48124
|
-
if (nested.some((inner) => cwd === inner || cwd.startsWith(inner +
|
|
48266
|
+
const cwd = await realpath16(worker.cwd).catch(() => path80.resolve(worker.cwd));
|
|
48267
|
+
if (cwd !== abs && !cwd.startsWith(abs + path80.sep)) continue;
|
|
48268
|
+
if (nested.some((inner) => cwd === inner || cwd.startsWith(inner + path80.sep))) continue;
|
|
48125
48269
|
const score = (cwd === abs ? 2 : 0) + (worker.child ? 1 : 0);
|
|
48126
48270
|
if (!best || score > best.score) best = { worker, score };
|
|
48127
48271
|
}
|
|
@@ -48192,10 +48336,10 @@ var MAX_MESSAGE = 2e4;
|
|
|
48192
48336
|
function runCombined(command, args, cwd, timeout) {
|
|
48193
48337
|
return new Promise((resolve11) => {
|
|
48194
48338
|
let output2 = "", truncated = false, timedOut = false, settled = false;
|
|
48195
|
-
const finish = (
|
|
48339
|
+
const finish = (run2) => {
|
|
48196
48340
|
if (!settled) {
|
|
48197
48341
|
settled = true;
|
|
48198
|
-
resolve11(
|
|
48342
|
+
resolve11(run2);
|
|
48199
48343
|
}
|
|
48200
48344
|
};
|
|
48201
48345
|
const child = spawn9(command, args, {
|
|
@@ -48249,13 +48393,13 @@ async function gitCommit(cwd, message) {
|
|
|
48249
48393
|
invalidateTree(root);
|
|
48250
48394
|
try {
|
|
48251
48395
|
countGit("projects");
|
|
48252
|
-
const
|
|
48253
|
-
if (
|
|
48254
|
-
return { ok: false, output:
|
|
48255
|
-
[git commit did not finish within ${COMMIT_TIMEOUT_MS / 1e3} seconds]`.trim() :
|
|
48396
|
+
const run2 = await runCombined("git", ["-C", root, "--no-pager", "commit", "--quiet", "--cleanup=strip", "-m", message], root, COMMIT_TIMEOUT_MS);
|
|
48397
|
+
if (run2.code !== 0) {
|
|
48398
|
+
return { ok: false, output: run2.timedOut ? `${run2.output}
|
|
48399
|
+
[git commit did not finish within ${COMMIT_TIMEOUT_MS / 1e3} seconds]`.trim() : run2.output || "git commit failed." };
|
|
48256
48400
|
}
|
|
48257
48401
|
const [sha, short, subject] = (await git2(root, "log", "-1", "--format=%H%x00%h%x00%s")).trim().split("\0");
|
|
48258
|
-
return { ok: true, sha, short, subject, branch: (await git2(root, "branch", "--show-current")).trim(), ...
|
|
48402
|
+
return { ok: true, sha, short, subject, branch: (await git2(root, "branch", "--show-current")).trim(), ...run2.output ? { output: run2.output } : {} };
|
|
48259
48403
|
} finally {
|
|
48260
48404
|
invalidateTree(root);
|
|
48261
48405
|
}
|
|
@@ -48278,13 +48422,13 @@ async function gitPush(cwd, confirmDefault) {
|
|
|
48278
48422
|
}
|
|
48279
48423
|
const args = ["-C", root, "--no-pager", "push", "--porcelain", ...tracked ? [] : ["--set-upstream"], remote, `refs/heads/${branch}:refs/heads/${destination2}`];
|
|
48280
48424
|
countGit("projects");
|
|
48281
|
-
const
|
|
48425
|
+
const run2 = await runCombined("git", args, root, PUSH_TIMEOUT_MS);
|
|
48282
48426
|
invalidateTree(root);
|
|
48283
|
-
if (
|
|
48284
|
-
return { ok: false, output:
|
|
48285
|
-
[git push did not finish within ${PUSH_TIMEOUT_MS / 1e3} seconds]`.trim() :
|
|
48427
|
+
if (run2.code !== 0) {
|
|
48428
|
+
return { ok: false, output: run2.timedOut ? `${run2.output}
|
|
48429
|
+
[git push did not finish within ${PUSH_TIMEOUT_MS / 1e3} seconds]`.trim() : run2.output || "git push failed." };
|
|
48286
48430
|
}
|
|
48287
|
-
return { ok: true, branch, remote, upstream: `${remote}/${destination2}`, setUpstream: !tracked, output:
|
|
48431
|
+
return { ok: true, branch, remote, upstream: `${remote}/${destination2}`, setUpstream: !tracked, output: run2.output };
|
|
48288
48432
|
}
|
|
48289
48433
|
var PULL_URL = /https:\/\/[^\s"'<>]+\/pull\/\d+/;
|
|
48290
48434
|
async function gitPullRequest(cwd, draft) {
|
|
@@ -48298,12 +48442,12 @@ async function gitPullRequest(cwd, draft) {
|
|
|
48298
48442
|
if (auth.code !== 0) {
|
|
48299
48443
|
return { ok: false, reason: "auth", message: "The GitHub CLI is not signed in on this computer. Run gh auth login there.", output: auth.output };
|
|
48300
48444
|
}
|
|
48301
|
-
const
|
|
48302
|
-
const url2 = PULL_URL.exec(
|
|
48303
|
-
if (
|
|
48304
|
-
if (url2 && /already exists/i.test(
|
|
48305
|
-
return { ok: false, reason: "failed", output:
|
|
48306
|
-
[gh did not finish within ${PR_TIMEOUT_MS / 1e3} seconds]`.trim() :
|
|
48445
|
+
const run2 = await runCombined("gh", ["pr", "create", "--fill", "--head", branch, ...draft === true ? ["--draft"] : []], root, PR_TIMEOUT_MS);
|
|
48446
|
+
const url2 = PULL_URL.exec(run2.output)?.[0];
|
|
48447
|
+
if (run2.code === 0 && url2) return { ok: true, url: url2, branch, draft: draft === true };
|
|
48448
|
+
if (url2 && /already exists/i.test(run2.output)) return { ok: true, url: url2, branch, existing: true };
|
|
48449
|
+
return { ok: false, reason: "failed", output: run2.timedOut ? `${run2.output}
|
|
48450
|
+
[gh did not finish within ${PR_TIMEOUT_MS / 1e3} seconds]`.trim() : run2.output || "gh pr create failed." };
|
|
48307
48451
|
}
|
|
48308
48452
|
|
|
48309
48453
|
// src/bridge/server-pane-routes.ts
|
|
@@ -48314,11 +48458,11 @@ init_terminal();
|
|
|
48314
48458
|
init_protocol();
|
|
48315
48459
|
init_herdr();
|
|
48316
48460
|
init_terminal();
|
|
48317
|
-
import { execFile as
|
|
48318
|
-
import { open as open15, stat as
|
|
48319
|
-
import { promisify as
|
|
48461
|
+
import { execFile as execFile17 } from "node:child_process";
|
|
48462
|
+
import { open as open15, stat as stat24 } from "node:fs/promises";
|
|
48463
|
+
import { promisify as promisify16 } from "node:util";
|
|
48320
48464
|
init_transcripts();
|
|
48321
|
-
var
|
|
48465
|
+
var exec16 = promisify16(execFile17);
|
|
48322
48466
|
var MAX_DEPTH = 64;
|
|
48323
48467
|
var TRANSCRIPT_TAIL_BYTES = 1048576;
|
|
48324
48468
|
var MAX_OTHER_PANES = 48;
|
|
@@ -48349,8 +48493,8 @@ function attributeServers(input2) {
|
|
|
48349
48493
|
}
|
|
48350
48494
|
return result.sort((a, b) => Number(a.source === "mentioned") - Number(b.source === "mentioned") || a.port - b.port);
|
|
48351
48495
|
}
|
|
48352
|
-
async function
|
|
48353
|
-
const { stdout } = await
|
|
48496
|
+
async function processTable3(session) {
|
|
48497
|
+
const { stdout } = await exec16("ps", ["-axo", "pid=,ppid=,args="], { timeout: 4e3, maxBuffer: 16777216 });
|
|
48354
48498
|
const parents = /* @__PURE__ */ new Map();
|
|
48355
48499
|
const runners = [];
|
|
48356
48500
|
const flag = `--session-id ${session}`;
|
|
@@ -48371,11 +48515,11 @@ async function paneRoots(server, paneId) {
|
|
|
48371
48515
|
}
|
|
48372
48516
|
async function transcriptHolders(file2) {
|
|
48373
48517
|
const lsof = process.platform === "darwin" ? "/usr/sbin/lsof" : "lsof";
|
|
48374
|
-
const { stdout } = await
|
|
48518
|
+
const { stdout } = await exec16(lsof, ["-t", "--", file2], { timeout: 3e3 }).catch(() => ({ stdout: "" }));
|
|
48375
48519
|
return stdout.split("\n").map(Number).filter((pid) => Number.isSafeInteger(pid) && pid > 1 && pid !== process.pid);
|
|
48376
48520
|
}
|
|
48377
48521
|
async function transcriptTail(file2) {
|
|
48378
|
-
const size = (await
|
|
48522
|
+
const size = (await stat24(file2)).size;
|
|
48379
48523
|
const handle = await open15(file2, "r");
|
|
48380
48524
|
try {
|
|
48381
48525
|
const length = Math.min(size, TRANSCRIPT_TAIL_BYTES);
|
|
@@ -48389,7 +48533,7 @@ async function transcriptTail(file2) {
|
|
|
48389
48533
|
async function sessionWebServers(target, pane) {
|
|
48390
48534
|
const [servers2, table2, own2, file2] = await Promise.all([
|
|
48391
48535
|
webServers(),
|
|
48392
|
-
|
|
48536
|
+
processTable3(target.session),
|
|
48393
48537
|
paneRoots(target.server, pane.pane_id),
|
|
48394
48538
|
transcriptPath(target.source, target.session).catch(() => void 0)
|
|
48395
48539
|
]);
|
|
@@ -48505,7 +48649,7 @@ function herdrWorktreeWorkers(s) {
|
|
|
48505
48649
|
const workers = [];
|
|
48506
48650
|
for (const pane of objects(s.panes)) {
|
|
48507
48651
|
const cwd = pane.foreground_cwd || pane.cwd;
|
|
48508
|
-
if (typeof pane.agent !== "string" || typeof cwd !== "string" || !
|
|
48652
|
+
if (typeof pane.agent !== "string" || typeof cwd !== "string" || !path81.isAbsolute(cwd)) continue;
|
|
48509
48653
|
const name = paneAgentName(s, pane);
|
|
48510
48654
|
workers.push({
|
|
48511
48655
|
cwd,
|
|
@@ -48823,8 +48967,8 @@ async function paneRouteOnce(ctx, url2, data, response, typing) {
|
|
|
48823
48967
|
}
|
|
48824
48968
|
|
|
48825
48969
|
// src/bridge/server-launch.ts
|
|
48826
|
-
import { mkdir as mkdir20, readFile as
|
|
48827
|
-
import
|
|
48970
|
+
import { mkdir as mkdir20, readFile as readFile33 } from "node:fs/promises";
|
|
48971
|
+
import path83 from "node:path";
|
|
48828
48972
|
init_zod();
|
|
48829
48973
|
init_home_paths();
|
|
48830
48974
|
init_herdr();
|
|
@@ -48834,15 +48978,15 @@ init_terminal();
|
|
|
48834
48978
|
init_zod();
|
|
48835
48979
|
init_utils_helpers();
|
|
48836
48980
|
init_metrics();
|
|
48837
|
-
import { execFile as
|
|
48838
|
-
import { mkdir as mkdir19, realpath as
|
|
48839
|
-
import
|
|
48840
|
-
import { promisify as
|
|
48981
|
+
import { execFile as execFile18 } from "node:child_process";
|
|
48982
|
+
import { mkdir as mkdir19, realpath as realpath17, rm as rm9, stat as stat25 } from "node:fs/promises";
|
|
48983
|
+
import path82 from "node:path";
|
|
48984
|
+
import { promisify as promisify17 } from "node:util";
|
|
48841
48985
|
init_protocol();
|
|
48842
|
-
var
|
|
48986
|
+
var exec17 = promisify17(execFile18);
|
|
48843
48987
|
async function git6(cwd, ...args) {
|
|
48844
48988
|
countGit("launch-worktree");
|
|
48845
|
-
return (await
|
|
48989
|
+
return (await exec17("git", ["-C", cwd, "--no-pager", ...args], {
|
|
48846
48990
|
timeout: 12e4,
|
|
48847
48991
|
maxBuffer: 1048576,
|
|
48848
48992
|
env: nonInteractiveGitEnv({ ...process.env, GIT_CONFIG_NOSYSTEM: "1" })
|
|
@@ -48865,21 +49009,21 @@ async function createLaunchWorktree(cwd, request6) {
|
|
|
48865
49009
|
if (await git6(root, "show-ref", "--verify", "--quiet", `refs/heads/${branch}`).then(() => true, () => false)) {
|
|
48866
49010
|
throw new BridgeError(409, `A branch named "${branch}" already exists in this repository. Choose another branch name.`);
|
|
48867
49011
|
}
|
|
48868
|
-
const worktree =
|
|
48869
|
-
if (await
|
|
49012
|
+
const worktree = path82.join(root, ".claude", "worktrees", worktreeFolderName(branch));
|
|
49013
|
+
if (await stat25(worktree).then(() => true, () => false)) {
|
|
48870
49014
|
throw new BridgeError(409, `The folder .claude/worktrees/${worktreeFolderName(branch)} already exists. Choose another branch name.`);
|
|
48871
49015
|
}
|
|
48872
|
-
await mkdir19(
|
|
49016
|
+
await mkdir19(path82.dirname(worktree), { recursive: true });
|
|
48873
49017
|
try {
|
|
48874
49018
|
await git6(root, "worktree", "add", "-b", branch, worktree, head);
|
|
48875
49019
|
} catch (error62) {
|
|
48876
49020
|
const detail = error62 instanceof Error && "stderr" in error62 ? String(error62.stderr ?? "").trim().split("\n").at(-1) : "";
|
|
48877
49021
|
throw new BridgeError(409, `Git could not create the worktree${detail ? `: ${detail.replace(/^fatal:\s*/, "")}` : "."}`);
|
|
48878
49022
|
}
|
|
48879
|
-
const abs = await
|
|
48880
|
-
const inside =
|
|
48881
|
-
const start = inside && !inside.startsWith("..") ?
|
|
48882
|
-
const startDir = await
|
|
49023
|
+
const abs = await realpath17(worktree);
|
|
49024
|
+
const inside = path82.relative(root, await realpath17(cwd));
|
|
49025
|
+
const start = inside && !inside.startsWith("..") ? path82.join(abs, inside) : abs;
|
|
49026
|
+
const startDir = await stat25(start).then((value2) => value2.isDirectory(), () => false) ? start : abs;
|
|
48883
49027
|
return {
|
|
48884
49028
|
cwd: startDir,
|
|
48885
49029
|
path: abs,
|
|
@@ -48921,12 +49065,12 @@ async function conductorBrief() {
|
|
|
48921
49065
|
let source;
|
|
48922
49066
|
if (true) source = "---\nname: conductor\ndescription: Coordinate independent Phren tasks across every project in the store and every enrolled computer, supervise their local agent fanout, and integrate verified returns in a concise dispatcher voice.\n---\n\n# Conductor\n\nYou are the owner's dispatcher for the whole store, not one project. You start\nin the phren store itself; that folder is not a project and not your work.\n\nFirst, before trusting your tools, check which phren you are running:\n`phren --version` and `command -v phren`. If the version is older than the one\nthe store or the owner expects, or the path is not the install you expect (a\nstale global package, an old checkout), tell the owner in one line and say\nwhich tools may be missing or behave differently.\n\nThen read the relevant projects' summaries and Phren tasks\n(`get_project_summary`, `get_tasks`) before selecting work.\n\nYour tools, use these instead of exploring the CLI or the Hook's files:\n\n- `live_sessions` (CLI `phren dispatch sessions`): every live agent on this\n computer and each enrolled one, with project, harness, status, `idleFor`\n (seconds since it last changed) and the target `hand_off` takes. Start here\n when asked what is running. Computers it could not reach are listed; say so\n rather than guessing. Computers in `notLinked` are registered in the store\n but have no Hook link here: say they were not checked, never that nothing is\n running there.\n- `hand_off`: send a prompt to one of those sessions.\n- `dispatch`: start a new worker on a computer (or `anywhere`).\n- `dispatch_returns` (CLI `phren dispatch returns`): what your workers sent\n back since you last asked: done with the final reply, needs-you with the\n question, failed with the error (a usage limit), blocked, or gone. Reading them marks them read. In core use\n `phren_admin(action: \"dispatch_returns\")`.\n- `phren dispatch status`: receipts of what you dispatched.\n- `get_tasks`, `get_project_summary`, `search_knowledge`: the store's memory.\n\nKeep engineering detail in worker briefs, Phren tasks and findings, and review\nartifacts, not in the owner's chat.\n\n## Voice and pace\n\nThe owner talks to you from the phone, often in talk mode, where your replies\nare read aloud in their voice. Sound like a good dispatcher: short, quick and\nconversational.\n\n- Lead with the outcome in one sentence. Keep the whole reply to one to four\n short sentences unless the owner asks for detail.\n- No tables, file paths, SHAs, PR numbers or run IDs in a reply unless the\n owner asks for them. Record them in Phren tasks and findings instead.\n- One short line per dispatch or return: who, what, result. A routine watcher\n or monitor event where nothing changed gets silence or a single line.\n- When the owner gives you a task, dispatch an engineer for it right away and\n say so in one line. That is the owner's standing rule; do not ask first.\n- Ask at most one question at a time, and name the options.\n- Delegate reading and analysis to workers instead of running long\n investigations yourself, so your own turns stay fast.\n- A message that begins with `[voice]` was spoken in talk mode, and your reply\n will be read aloud. Answer in one or two spoken sentences with no markdown,\n lists, symbols or code, written to sound natural read aloud: \"back in about\n twenty minutes\", not \"ETA ~20m\".\n\n```text\nLinuxbox has the parser checks on Codex, back around two twenty.\nDesk finished the navigation checks: tests passed, not merged yet.\n```\n\nIf a result or return time is unknown, say so. Surface a worker's question in\nthe same short voice, with the worker's own choices.\n\n## Dispatching\n\nPick five to ten independent tasks when that many are available and capacity\npermits. Do not manufacture tasks to fill the batch. Separate dependencies and\nfile ownership; give each remote lead a base revision, acceptance checks, local\nfanout limit, report time and integration instructions. Every brief repeats the\nowner's repository constraints, including any prohibition on commits, pushes,\nbranches or particular tests. Dispatch never expands the owner's authorization.\n\nYou are the one conductor for this computer and every computer linked with\nit; a second conductor in the group is refused at launch. Conductors on\ncomputers that are not linked share only the store, so claim a task before you\ndispatch it: `claim_task` (in core, `manage_task` with `action: \"claim\"`).\nSkip tasks marked `[claimed: <computer>]` by another computer. A claim that\ncomes back not claimed, with `heldBy`, means another conductor got there first:\nmove on. Completing a task clears its claim; release one you will not do. Start\nworkers with `dispatch` or `hand_off`, never as tabs in your own Herdr\nworkspace. When a computer shows up in `notLinked`, tell the owner that\n`phren bridge link <host>` can link it; never link a computer yourself.\n\nPrefer Codex. Use OpenCode Go when its account and harness are connected. Use\nOpenRouter only when the owner explicitly requests it; an unavailable account\ndoes not authorize another paid provider. Name an explicit model when instructed,\notherwise use and report the remote configured default. Each remote lead owns\nits local checkouts, fanout and provider rate limits. Where installed, local\nworkers use the fanout wrapper's `scripts/run.sh --provider codex|opencode\n--label --worktree [--model] [--mode]` contract and parent-bound manifests.\nTell every lead the same: a worker started any other way (its own `opencode\nrun` or `codex exec`, a launch script, nohup) has no manifest, so the phone and\nyou cannot see, resume or review it. Workers that exist only as processes do\nnot count as dispatched.\n\nPrefer handing work to a session that already owns the project and is idle or\ndoing related work; call `hand_off` in full or `phren_admin(action: \"hand_off\",\ncomputer?, target|session, text)` in core. Otherwise dispatch a new worker.\nWrite one short line either way. Call `dispatch` in full or\n`phren_admin(action: \"dispatch\", computer, project, harness, model?, prompt, label)`\nin core. The CLI equivalent is `phren dispatch <computer|anywhere> <project>\n--harness <harness> --label <label> --prompt <brief> [--model <model>]`.\n`anywhere` chooses the connected computer with the fewest working agents. Place\nbriefs sequentially, respecting busy/rate-limit responses. Keep their dispatch\nIDs. Do not send local filesystem paths as remote project names.\n\n`accepted` on a receipt is prompt acceptance, not worker completion. Returns\narrive on their own: the Hook follows every worker you dispatch, and when you\nare idle it types one line into this session, such as `Return: Linuxbox parser\nchecks done, tests passed (dispatch <id>). Call dispatch_returns.` When you see\none, call `dispatch_returns` and report each return in one short line. You may\nalso call it whenever you want the current state; do not poll it in a loop, and\ndo not read remote transcripts by hand to learn whether a worker finished. Tell\nthe owner a return time as an expectation, not a promise.\n\nFor a `needs-you` return, surface the worker's question in the owner's chat\nwith its choices as the worker wrote them; do not rewrite or answer it for the\nowner unless the owner already decided. Send the answer back with `hand_off`\nto the row's `target`. A `blocked` worker waits on terminal input, such as a\npermission prompt: say so and point the owner to the phone or the terminal. A\n`gone` worker's pane closed or was taken over: say so, and decide with the\nowner before giving its work to another agent. A `done` reply is the worker's\nown account; check its evidence before saying tests passed or work merged.\n\nAn uncertain delivery is never retried automatically. Inspect its known target\nor status before deciding with the owner whether a replacement is needed. Keep\nunavailable workers visible instead of giving their work to another agent\nwhile the original may still be running.\n\nIntegrate returned changes in dependency order within the owner's allowed\nworkflow. Run a cleanup pass across the combined result and the affected checks.\nRequire evidence before saying tests passed or merged. Ship only within existing\nauthorization; if publication is not authorized, return the reviewable result.\nUpdate Phren tasks when verified complete and save durable decisions. A worker's\nfinished turn alone does not complete the owner's task.\n";
|
|
48923
49067
|
else {
|
|
48924
|
-
const here =
|
|
49068
|
+
const here = path83.dirname(fileURLToPath(import.meta.url));
|
|
48925
49069
|
for (const candidate of [
|
|
48926
|
-
|
|
48927
|
-
|
|
49070
|
+
path83.join(here, "..", "starter", "global", "skills", "conductor", "SKILL.md"),
|
|
49071
|
+
path83.join(here, "..", "..", "starter", "global", "skills", "conductor", "SKILL.md")
|
|
48928
49072
|
]) {
|
|
48929
|
-
source = await
|
|
49073
|
+
source = await readFile33(candidate, "utf8").catch(() => void 0);
|
|
48930
49074
|
if (source !== void 0) break;
|
|
48931
49075
|
}
|
|
48932
49076
|
}
|
|
@@ -48945,15 +49089,15 @@ function effortArgs(kind, effort) {
|
|
|
48945
49089
|
}
|
|
48946
49090
|
async function prepareConductor(kind, effort, model) {
|
|
48947
49091
|
const brief = await conductorBrief();
|
|
48948
|
-
const briefDirectory =
|
|
49092
|
+
const briefDirectory = path83.join(bridgeRoot(), "conductor");
|
|
48949
49093
|
await mkdir20(briefDirectory, { recursive: true, mode: 448 });
|
|
48950
|
-
const briefFile =
|
|
48951
|
-
if (await
|
|
49094
|
+
const briefFile = path83.join(briefDirectory, "brief.md");
|
|
49095
|
+
if (await readFile33(briefFile, "utf8").catch(() => void 0) !== brief + "\n") await atomic(briefFile, brief + "\n");
|
|
48952
49096
|
if (kind === "claude") return [...model ? ["--model", model] : [], "--append-system-prompt-file", briefFile, "--effort", effort];
|
|
48953
49097
|
if (kind === "codex") return [...model ? ["--model", model] : [], "-c", `model_reasoning_effort=${effort}`, "-c", `developer_instructions=${JSON.stringify(brief)}`];
|
|
48954
49098
|
if (kind === "opencode") {
|
|
48955
|
-
const directory =
|
|
48956
|
-
const file2 =
|
|
49099
|
+
const directory = path83.join(process.env.XDG_CONFIG_HOME || path83.join(homeDir(), ".config"), "opencode", "agents");
|
|
49100
|
+
const file2 = path83.join(directory, "conductor.md");
|
|
48957
49101
|
const definition = `---
|
|
48958
49102
|
description: Coordinate the owner's work across agent sessions.
|
|
48959
49103
|
mode: primary
|
|
@@ -48962,7 +49106,7 @@ mode: primary
|
|
|
48962
49106
|
${brief}
|
|
48963
49107
|
`;
|
|
48964
49108
|
await mkdir20(directory, { recursive: true, mode: 448 });
|
|
48965
|
-
if (await
|
|
49109
|
+
if (await readFile33(file2, "utf8").catch(() => void 0) !== definition) await atomic(file2, definition, 420);
|
|
48966
49110
|
return [...model ? ["--model", model] : [], "--agent", "conductor", "--variant", effort];
|
|
48967
49111
|
}
|
|
48968
49112
|
throw new BridgeError(400, "The selected harness cannot run as a conductor.");
|
|
@@ -48990,7 +49134,7 @@ function herdrAgentName(label2) {
|
|
|
48990
49134
|
}
|
|
48991
49135
|
async function launchSession(server, data, options = {}) {
|
|
48992
49136
|
const role = external_exports.enum(["agent", "conductor"]).default("agent").parse(data.role);
|
|
48993
|
-
const projectDirectory = external_exports.string().min(1).max(4096).refine((t) =>
|
|
49137
|
+
const projectDirectory = external_exports.string().min(1).max(4096).refine((t) => path83.isAbsolute(t) && !/[\x00-\x1f\x7f]/.test(t)).parse(data.cwd);
|
|
48994
49138
|
const worktreeRequest = data.worktree === void 0 || data.worktree === null ? void 0 : launchWorktreeSchema.parse(data.worktree);
|
|
48995
49139
|
if (worktreeRequest && role === "conductor") throw new BridgeError(400, "A conductor works across projects, so it cannot start in a worktree.");
|
|
48996
49140
|
const label2 = plainText(200).parse(data.label);
|
|
@@ -49082,7 +49226,7 @@ async function workspaceAction(server, operation, data) {
|
|
|
49082
49226
|
if (tab && !objects(s.tabs).some((t) => t.tab_id === tab && (!workspace || t.workspace_id === workspace))) throw new BridgeError(409, "The tab changed.");
|
|
49083
49227
|
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.");
|
|
49084
49228
|
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);
|
|
49085
|
-
const cwd = data.cwd === void 0 ? void 0 : external_exports.string().max(4096).refine((t) =>
|
|
49229
|
+
const cwd = data.cwd === void 0 ? void 0 : external_exports.string().max(4096).refine((t) => path83.isAbsolute(t) && !/[\x00-\x1f\x7f]/.test(t)).parse(data.cwd);
|
|
49086
49230
|
if (operation === "create") await terminalProvider().create(server, { workspace, label: label2, cwd });
|
|
49087
49231
|
else if (!workspace && !tab && !pane) throw new BridgeError(400, "Choose a Herdr destination.");
|
|
49088
49232
|
else if (pane && operation === "focus") await terminalProvider().focusPane(server, pane);
|
|
@@ -49257,7 +49401,8 @@ var capabilities = {
|
|
|
49257
49401
|
speechTimestamps: true,
|
|
49258
49402
|
transcribe: true,
|
|
49259
49403
|
memoryStore: true,
|
|
49260
|
-
promptOnce: true
|
|
49404
|
+
promptOnce: true,
|
|
49405
|
+
resources: true
|
|
49261
49406
|
};
|
|
49262
49407
|
function capabilitiesForModules(snapshot2) {
|
|
49263
49408
|
const allowed = new Set(snapshot2.modules.flatMap((module) => module.capabilities));
|
|
@@ -49356,6 +49501,19 @@ function workspacesReader(ctx) {
|
|
|
49356
49501
|
return { ...workspaces, phren: info };
|
|
49357
49502
|
};
|
|
49358
49503
|
}
|
|
49504
|
+
async function fromPeers(route2) {
|
|
49505
|
+
const { peers, peerError } = await optionalHookPeers();
|
|
49506
|
+
const answers = await Promise.all(peers.map(async (peer) => {
|
|
49507
|
+
try {
|
|
49508
|
+
return { name: peer.name, ...await peerRequest(peer, route2, void 0, 15e3) };
|
|
49509
|
+
} catch (error62) {
|
|
49510
|
+
const code = error62 instanceof BridgeError && typeof error62.details?.code === "string" ? error62.details.code : void 0;
|
|
49511
|
+
const older = error62 instanceof BridgeError && error62.status === 404;
|
|
49512
|
+
return { name: peer.name, error: older ? "This computer's Hook predates this report; update it with phren bridge update." : error62 instanceof Error ? error62.message.slice(0, 300) : "Unavailable", ...code ? { code } : {} };
|
|
49513
|
+
}
|
|
49514
|
+
}));
|
|
49515
|
+
return { peers: answers, ...peerError ? { peerError } : {} };
|
|
49516
|
+
}
|
|
49359
49517
|
function createRouteHandler(ctx) {
|
|
49360
49518
|
const {
|
|
49361
49519
|
version: version3,
|
|
@@ -49369,6 +49527,7 @@ function createRouteHandler(ctx) {
|
|
|
49369
49527
|
journal,
|
|
49370
49528
|
modelCatalog,
|
|
49371
49529
|
accountUsage,
|
|
49530
|
+
resources,
|
|
49372
49531
|
launches,
|
|
49373
49532
|
locatedDirectories,
|
|
49374
49533
|
fanoutMessages,
|
|
@@ -49454,7 +49613,7 @@ function createRouteHandler(ctx) {
|
|
|
49454
49613
|
case "/v1/files/range": {
|
|
49455
49614
|
let root;
|
|
49456
49615
|
if (url2.searchParams.get("scope") === "uploads") {
|
|
49457
|
-
root =
|
|
49616
|
+
root = path84.join(bridgeRoot(), "uploads");
|
|
49458
49617
|
} else if (url2.searchParams.has("session")) {
|
|
49459
49618
|
const target = targetFromURL(url2), pane = await validateTarget(target);
|
|
49460
49619
|
const cwd = await gitRepository(pane, target, url2.searchParams.get("child") ?? void 0, url2.searchParams.get("worktree") ?? void 0);
|
|
@@ -49499,8 +49658,19 @@ function createRouteHandler(ctx) {
|
|
|
49499
49658
|
break;
|
|
49500
49659
|
case "/v1/usage": {
|
|
49501
49660
|
const known = new Set((url2.searchParams.get("sources") ?? "codex,claude,opencode,openrouter").split(",").map((s) => s.trim()).filter(Boolean));
|
|
49661
|
+
const goPlan = url2.searchParams.get("goPlan") === "1";
|
|
49502
49662
|
const usage = await accountUsage.read();
|
|
49503
|
-
result = { ...usage, accounts: usage.accounts
|
|
49663
|
+
result = { ...usage, accounts: usageForCaller(usage.accounts, known, goPlan) };
|
|
49664
|
+
if (url2.searchParams.get("peers") === "1") result = {
|
|
49665
|
+
...result,
|
|
49666
|
+
computer: info.computer,
|
|
49667
|
+
...await fromPeers(`/v1/usage?${new URLSearchParams({ sources: [...known].join(","), ...goPlan ? { goPlan: "1" } : {} })}`)
|
|
49668
|
+
};
|
|
49669
|
+
break;
|
|
49670
|
+
}
|
|
49671
|
+
case "/v1/resources": {
|
|
49672
|
+
result = { computer: info.computer, resources: await resources.read() };
|
|
49673
|
+
if (url2.searchParams.get("peers") === "1") result = { ...result, ...await fromPeers("/v1/resources") };
|
|
49504
49674
|
break;
|
|
49505
49675
|
}
|
|
49506
49676
|
case "/v1/push/status":
|
|
@@ -49898,10 +50068,10 @@ function copilotThinking(rendered) {
|
|
|
49898
50068
|
if (/^\s*❯\s+(?!\d+[.)]\s)\S/.test(line)) from = index2 + 1;
|
|
49899
50069
|
});
|
|
49900
50070
|
for (let i = lines.length - 1; i >= from; i--) {
|
|
49901
|
-
const
|
|
49902
|
-
if (!
|
|
49903
|
-
if (
|
|
49904
|
-
const seconds = spinnerSeconds(
|
|
50071
|
+
const header = /^\s*[⌄⌃▾▸›>]?\s*(?:(Thinking)\b.*|Thought for (\S+))\s*$/.exec(lines[i]);
|
|
50072
|
+
if (!header) continue;
|
|
50073
|
+
if (header[1]) return { verb: "Working", thinking: true };
|
|
50074
|
+
const seconds = spinnerSeconds(header[2]);
|
|
49905
50075
|
if (seconds !== void 0) return { verb: "Working", thinking: false, thoughtFor: seconds };
|
|
49906
50076
|
}
|
|
49907
50077
|
return void 0;
|
|
@@ -49994,8 +50164,8 @@ async function readDeltaPreview(target, file2, rollout) {
|
|
|
49994
50164
|
const handle = await open16(file2 + ".preview.json", constants6.O_RDONLY | constants6.O_NOFOLLOW | constants6.O_NONBLOCK);
|
|
49995
50165
|
let bytes;
|
|
49996
50166
|
try {
|
|
49997
|
-
const
|
|
49998
|
-
if (!
|
|
50167
|
+
const stat26 = await handle.stat();
|
|
50168
|
+
if (!stat26.isFile() || stat26.size > MAX_PREVIEW_BYTES) return null;
|
|
49999
50169
|
const buffer = Buffer.alloc(MAX_PREVIEW_BYTES + 1);
|
|
50000
50170
|
const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
|
|
50001
50171
|
if (bytesRead > MAX_PREVIEW_BYTES) return null;
|
|
@@ -50345,12 +50515,14 @@ function transcriptStreams(ctx) {
|
|
|
50345
50515
|
var OVERVIEW_TICK_MS = intervalFromEnv("PHREN_OVERVIEW_TICK_MS", 5e3, 250, 6e4);
|
|
50346
50516
|
var OVERVIEW_REFRESH_MS = intervalFromEnv("PHREN_OVERVIEW_REFRESH_MS", 1e4, 1e3, 12e4);
|
|
50347
50517
|
var OVERVIEW_HEARTBEAT_MS = intervalFromEnv("PHREN_OVERVIEW_HEARTBEAT_MS", 2e4, 1e3, 6e4);
|
|
50518
|
+
var OVERVIEW_RESOURCES_MS = intervalFromEnv("PHREN_OVERVIEW_RESOURCES_MS", 12e3, 1e3, 12e4);
|
|
50348
50519
|
function overviewStream(options) {
|
|
50349
50520
|
const snapshot2 = options.snapshot ?? sharedSnapshot;
|
|
50350
50521
|
const now = options.now ?? Date.now;
|
|
50351
50522
|
const tickMs = options.tickMs ?? OVERVIEW_TICK_MS;
|
|
50352
50523
|
const refreshMs = options.refreshMs ?? OVERVIEW_REFRESH_MS;
|
|
50353
50524
|
const heartbeatMs = options.heartbeatMs ?? OVERVIEW_HEARTBEAT_MS;
|
|
50525
|
+
const resourcesMs = options.resourcesMs ?? OVERVIEW_RESOURCES_MS;
|
|
50354
50526
|
function send2(client, frame) {
|
|
50355
50527
|
if (client.readyState !== import_websocket.default.OPEN) return false;
|
|
50356
50528
|
const data = JSON.stringify(frame);
|
|
@@ -50361,15 +50533,21 @@ function overviewStream(options) {
|
|
|
50361
50533
|
client.send(data);
|
|
50362
50534
|
return true;
|
|
50363
50535
|
}
|
|
50364
|
-
return function stream(client, server, watchApprovals) {
|
|
50536
|
+
return function stream(client, server, watchApprovals, withResources = false) {
|
|
50365
50537
|
let closed = false, busy = false, first = true;
|
|
50366
|
-
let snapshotKey = "", builtAt = 0, sentKey = "", sentAt = 0;
|
|
50538
|
+
let snapshotKey = "", builtAt = 0, sentKey = "", sentAt = 0, resourcesAt = -Infinity;
|
|
50367
50539
|
const tick = async () => {
|
|
50368
50540
|
if (busy || closed) return;
|
|
50369
50541
|
busy = true;
|
|
50370
50542
|
try {
|
|
50371
50543
|
countTick("overview-stream");
|
|
50372
50544
|
const at = now();
|
|
50545
|
+
if (withResources && options.resources && at - resourcesAt >= resourcesMs) {
|
|
50546
|
+
resourcesAt = at;
|
|
50547
|
+
const resources = await options.resources().catch(() => void 0);
|
|
50548
|
+
if (closed) return;
|
|
50549
|
+
if (resources) send2(client, { type: "resources", resources });
|
|
50550
|
+
}
|
|
50373
50551
|
const held = await snapshot2(server, first ? 0 : tickMs);
|
|
50374
50552
|
if (closed) return;
|
|
50375
50553
|
const key2 = JSON.stringify(held);
|
|
@@ -50426,9 +50604,9 @@ async function serve(version3) {
|
|
|
50426
50604
|
await mkdir21(root, { recursive: true, mode: 448 });
|
|
50427
50605
|
await chmod5(root, 448);
|
|
50428
50606
|
let computerID2;
|
|
50429
|
-
const identityFile =
|
|
50607
|
+
const identityFile = path85.join(root, "computer-id");
|
|
50430
50608
|
try {
|
|
50431
|
-
computerID2 = (await
|
|
50609
|
+
computerID2 = (await readFile34(identityFile, "utf8")).trim();
|
|
50432
50610
|
} catch {
|
|
50433
50611
|
computerID2 = randomUUID19();
|
|
50434
50612
|
await writeFile11(identityFile, computerID2, { flag: "wx", mode: 384 });
|
|
@@ -50455,6 +50633,7 @@ async function serve(version3) {
|
|
|
50455
50633
|
const sideQuestions = new SideQuestions();
|
|
50456
50634
|
const contextUsage = new WorkspaceContextUsage();
|
|
50457
50635
|
const accountUsage = new AccountUsageReader();
|
|
50636
|
+
const resources = new ResourceMonitor();
|
|
50458
50637
|
const tabActivity = new TabActivityStore();
|
|
50459
50638
|
const codexQuestions = new CodexQuestions();
|
|
50460
50639
|
const scheduleStore = defaultPhrenPath();
|
|
@@ -50476,7 +50655,7 @@ async function serve(version3) {
|
|
|
50476
50655
|
if (codeReindexer) agentHooks.changes.onRecord = (files) => codeReindexer.record(files);
|
|
50477
50656
|
function gatewayTiming() {
|
|
50478
50657
|
try {
|
|
50479
|
-
const parsed = JSON.parse(readFileSync32(
|
|
50658
|
+
const parsed = JSON.parse(readFileSync32(path85.join(root, "gateway.json"), "utf8"));
|
|
50480
50659
|
if (typeof parsed.ms === "number" && Number.isFinite(parsed.ms) && parsed.ms >= 0) return Math.round(parsed.ms);
|
|
50481
50660
|
} catch {
|
|
50482
50661
|
}
|
|
@@ -50493,7 +50672,7 @@ async function serve(version3) {
|
|
|
50493
50672
|
profile: modules.profile,
|
|
50494
50673
|
generation: modules.generation,
|
|
50495
50674
|
get load() {
|
|
50496
|
-
return { average: Number(
|
|
50675
|
+
return { average: Number(loadavg2()[0].toFixed(2)), cpus: cpus2().length };
|
|
50497
50676
|
},
|
|
50498
50677
|
get gatewayMs() {
|
|
50499
50678
|
return gatewayTiming();
|
|
@@ -50522,13 +50701,14 @@ async function serve(version3) {
|
|
|
50522
50701
|
}
|
|
50523
50702
|
const stopRetention = modules.has("git") ? await startChangeRetention() : () => {
|
|
50524
50703
|
};
|
|
50525
|
-
if (modules.has("git")) await rm10(
|
|
50704
|
+
if (modules.has("git")) await rm10(path85.join(root, "changes-scratch"), { recursive: true, force: true });
|
|
50526
50705
|
const streams = transcriptStreams({ modules, agentHooks, codexQuestions, sideQuestions, info, activeCapabilities });
|
|
50527
50706
|
const { stream } = streams;
|
|
50528
50707
|
const overview = overviewStream({
|
|
50529
50708
|
read: workspacesReader({ modules, info, agentHooks, journal, tabActivity, contextUsage }),
|
|
50530
50709
|
info: () => ({ ...info, capabilities: info.capabilities }),
|
|
50531
|
-
renew: (server) => agentHooks.overview.renew(server)
|
|
50710
|
+
renew: (server) => agentHooks.overview.renew(server),
|
|
50711
|
+
resources: () => resources.read()
|
|
50532
50712
|
});
|
|
50533
50713
|
const http = createServer2(createRouteHandler({
|
|
50534
50714
|
version: version3,
|
|
@@ -50546,6 +50726,7 @@ async function serve(version3) {
|
|
|
50546
50726
|
modelSwitcher,
|
|
50547
50727
|
sideQuestions,
|
|
50548
50728
|
accountUsage,
|
|
50729
|
+
resources,
|
|
50549
50730
|
codexQuestions,
|
|
50550
50731
|
launches,
|
|
50551
50732
|
locatedDirectories,
|
|
@@ -50575,7 +50756,7 @@ async function serve(version3) {
|
|
|
50575
50756
|
ws.clients.delete(oldest);
|
|
50576
50757
|
}
|
|
50577
50758
|
if (overviewServer !== void 0) {
|
|
50578
|
-
overview(client, overviewServer, url2.searchParams.get("watchApprovals") === "1");
|
|
50759
|
+
overview(client, overviewServer, url2.searchParams.get("watchApprovals") === "1", url2.searchParams.get("resources") === "1");
|
|
50579
50760
|
return;
|
|
50580
50761
|
}
|
|
50581
50762
|
if (url2.pathname === "/v1/speech/transcribe") {
|
|
@@ -50669,13 +50850,13 @@ init_protocol();
|
|
|
50669
50850
|
// src/bridge/link.ts
|
|
50670
50851
|
init_profile_store();
|
|
50671
50852
|
init_phren_paths();
|
|
50672
|
-
import { execFile as
|
|
50673
|
-
import { readFile as
|
|
50853
|
+
import { execFile as execFile19 } from "node:child_process";
|
|
50854
|
+
import { readFile as readFile35 } from "node:fs/promises";
|
|
50674
50855
|
import { homedir as homedir20, hostname as hostname10, userInfo as userInfo3 } from "node:os";
|
|
50675
|
-
import
|
|
50676
|
-
import { promisify as
|
|
50856
|
+
import path86 from "node:path";
|
|
50857
|
+
import { promisify as promisify18 } from "node:util";
|
|
50677
50858
|
init_protocol();
|
|
50678
|
-
var
|
|
50859
|
+
var exec18 = promisify18(execFile19);
|
|
50679
50860
|
var REMOTE_PATH = 'PATH="$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin:$PATH"';
|
|
50680
50861
|
var GIT_HOSTS = /(^|\.)(github\.com|gitlab\.com|bitbucket\.org)$/i;
|
|
50681
50862
|
function sshConfigHosts(text4) {
|
|
@@ -50700,7 +50881,7 @@ function sshConfigHosts(text4) {
|
|
|
50700
50881
|
}
|
|
50701
50882
|
async function ssh(host, command, input2, timeout = 2e4) {
|
|
50702
50883
|
return new Promise((resolve11, reject) => {
|
|
50703
|
-
const child =
|
|
50884
|
+
const child = execFile19(
|
|
50704
50885
|
"ssh",
|
|
50705
50886
|
["-o", "BatchMode=yes", "-o", "ConnectTimeout=5", "--", host, command],
|
|
50706
50887
|
{ timeout, maxBuffer: 1048576 },
|
|
@@ -50719,11 +50900,11 @@ async function probe2(host) {
|
|
|
50719
50900
|
return computerId ? { host, computerId, user: field("user") ?? "", client: field("client") } : void 0;
|
|
50720
50901
|
}
|
|
50721
50902
|
async function discoverComputers(options = {}) {
|
|
50722
|
-
const config3 = options.sshConfig ?? await
|
|
50903
|
+
const config3 = options.sshConfig ?? await readFile35(path86.join(homedir20(), ".ssh", "config"), "utf8").catch(() => "");
|
|
50723
50904
|
const store = options.store !== void 0 ? options.store : findPhrenPath();
|
|
50724
50905
|
const machines = store ? listMachines(store) : void 0;
|
|
50725
50906
|
const { peers } = await optionalHookPeers();
|
|
50726
|
-
const own2 = (await
|
|
50907
|
+
const own2 = (await readFile35(path86.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
|
|
50727
50908
|
const known = new Set([...localNames(), ...peers.flatMap((peer) => [peer.name, peer.address])].map(computerLabel));
|
|
50728
50909
|
const candidates = [.../* @__PURE__ */ new Set([...sshConfigHosts(config3), ...machines?.ok ? Object.keys(machines.data) : []])].filter((host) => !known.has(computerLabel(host))).slice(0, 32);
|
|
50729
50910
|
const [found, peerIds] = await Promise.all([
|
|
@@ -50745,15 +50926,15 @@ function slugName(value2) {
|
|
|
50745
50926
|
async function linkComputer(host, options = {}) {
|
|
50746
50927
|
const remote = await probe2(host);
|
|
50747
50928
|
if (!remote) throw new BridgeError(409, `${host} answers over ssh but Phren Hook is not installed there. Run phren bridge install on it first.`);
|
|
50748
|
-
const own2 = (await
|
|
50929
|
+
const own2 = (await readFile35(path86.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
|
|
50749
50930
|
if (remote.computerId === own2) throw new BridgeError(409, `${host} is this computer.`);
|
|
50750
50931
|
const name = computerName.parse(options.name ?? slugName(host));
|
|
50751
50932
|
const as = computerName.parse(options.as ?? slugName(hostname10()));
|
|
50752
50933
|
const backAddress = options.backAddress ?? remote.client;
|
|
50753
50934
|
if (!backAddress) throw new BridgeError(409, `${host} did not report this computer's address; pass --back-address.`);
|
|
50754
|
-
const resolved = Object.fromEntries((await
|
|
50935
|
+
const resolved = Object.fromEntries((await exec18("ssh", ["-G", "--", host], { timeout: 5e3 })).stdout.split("\n").map((line) => line.split(" ")).filter((parts) => parts.length >= 2).map(([key2, ...rest]) => [key2, rest.join(" ")]));
|
|
50755
50936
|
const remoteHostKey = publicComputerKey((await ssh(host, "cat /etc/ssh/ssh_host_ed25519_key.pub")).trim().split(/\s+/).slice(0, 2).join(" "));
|
|
50756
|
-
const localHostKey = publicComputerKey((await
|
|
50937
|
+
const localHostKey = publicComputerKey((await readFile35("/etc/ssh/ssh_host_ed25519_key.pub", "utf8")).trim().split(/\s+/).slice(0, 2).join(" "));
|
|
50757
50938
|
const remoteLine = (await ssh(host, `${REMOTE_PATH} phren bridge enroll-computer ${name}`)).trim();
|
|
50758
50939
|
await ssh(host, `f=$(mktemp) && cat > "$f" && ${REMOTE_PATH} phren bridge enroll-computer ${as} --accept "$f"; s=$?; rm -f "$f"; exit $s`, await enrollComputer(as));
|
|
50759
50940
|
await acceptComputer(name, remoteLine);
|
|
@@ -50788,7 +50969,7 @@ async function runBridge(args, version3) {
|
|
|
50788
50969
|
case "enroll-computer": {
|
|
50789
50970
|
if (args.length === 2) console.log(await enrollComputer(args[1]));
|
|
50790
50971
|
else if (args.length === 4 && args[2] === "--accept") {
|
|
50791
|
-
await acceptComputer(args[1], await
|
|
50972
|
+
await acceptComputer(args[1], await readFile36(args[3], "utf8"));
|
|
50792
50973
|
console.log(`Enrolled ${args[1]} for Phren Hook.`);
|
|
50793
50974
|
} else throw new Error("Usage: phren bridge enroll-computer <name> [--accept <public-key-file>]");
|
|
50794
50975
|
break;
|
|
@@ -50946,7 +51127,7 @@ async function readSecret(prompt) {
|
|
|
50946
51127
|
// src/bridge/hook-main.ts
|
|
50947
51128
|
init_utils_helpers();
|
|
50948
51129
|
Object.assign(process.env, nonInteractiveGitEnv());
|
|
50949
|
-
runBridge(process.argv.slice(2), "0.3.
|
|
51130
|
+
runBridge(process.argv.slice(2), "0.3.11").then((code) => {
|
|
50950
51131
|
process.exitCode = code;
|
|
50951
51132
|
}).catch((error62) => {
|
|
50952
51133
|
console.error(error62 instanceof Error ? error62.message : "Phren Hook failed.");
|