@phren/cli 0.3.9 → 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/transcript-codex.d.ts +20 -0
- package/dist/bridge/transcript-codex.js +177 -2
- package/dist/bridge/transcripts.js +6 -1
- package/dist/bridge/usage.d.ts +36 -20
- package/dist/bridge/usage.js +163 -301
- package/dist/bridge-hook.mjs +1132 -800
- 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/conductor/SKILL.md +4 -0
- package/starter/global/skills/fanout/SKILL.md +9 -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 };
|
|
@@ -22096,7 +22099,10 @@ function visibleCodexEvent(raw) {
|
|
|
22096
22099
|
payload: { type: "error", ...typeof p.message === "string" ? { message: p.message } : {} }
|
|
22097
22100
|
};
|
|
22098
22101
|
if (raw.type === "event_msg" && ["token_count", "task_started", "task_complete", "task_completed", "turn_aborted", "task_aborted", "error"].includes(String(p.type))) return raw;
|
|
22102
|
+
if (raw.type === "event_msg" && p.type === "item_completed") return itemCall(raw, object2(p.item));
|
|
22099
22103
|
if (raw.type !== "response_item") return void 0;
|
|
22104
|
+
const wrapper = codeModeWrapper(raw);
|
|
22105
|
+
if (wrapper) return wrapper.images.length ? imageCall(raw, wrapper) : void 0;
|
|
22100
22106
|
if (p.type === "message" && ["user", "assistant"].includes(String(p.role)) && p.channel !== "analysis") {
|
|
22101
22107
|
const text4 = typeof p.content === "string" ? p.content : objects(p.content).map((b) => typeof b.text === "string" ? b.text : "").join("\n");
|
|
22102
22108
|
return p.role === "user" && harnessPreamble(text4) ? void 0 : raw;
|
|
@@ -22104,6 +22110,136 @@ function visibleCodexEvent(raw) {
|
|
|
22104
22110
|
if (["function_call", "custom_tool_call", "function_call_output", "custom_tool_call_output"].includes(String(p.type))) return raw;
|
|
22105
22111
|
return void 0;
|
|
22106
22112
|
}
|
|
22113
|
+
function codeModeWrapper(raw) {
|
|
22114
|
+
const p = object2(raw.payload), source = p.input, callId = p.call_id;
|
|
22115
|
+
if (typeof raw.ordinal !== "number" || raw.type !== "response_item" || p.type !== "custom_tool_call" || p.name !== "exec") return void 0;
|
|
22116
|
+
if (typeof source !== "string" || typeof callId !== "string" || !callId || source.trimStart().startsWith("*** Begin Patch")) return void 0;
|
|
22117
|
+
const tools = [...source.matchAll(WRAPPED_TOOL)].map((match) => match[1]);
|
|
22118
|
+
if (!tools.length || !tools.every((tool) => ITEM_TOOLS.has(tool) || /^mcp__\w+$/.test(tool))) return void 0;
|
|
22119
|
+
const images = [...source.matchAll(VIEW_IMAGE)].map((match) => {
|
|
22120
|
+
const args = callArguments(source, (match.index ?? 0) + match[0].length - 1);
|
|
22121
|
+
return (args === void 0 ? void 0 : argumentString(args, source, ["path"])) ?? "";
|
|
22122
|
+
});
|
|
22123
|
+
return { callId, images };
|
|
22124
|
+
}
|
|
22125
|
+
function imageCall(raw, wrapper) {
|
|
22126
|
+
const file2 = wrapper.images.find(Boolean);
|
|
22127
|
+
return {
|
|
22128
|
+
type: "response_item",
|
|
22129
|
+
...raw.timestamp !== void 0 ? { timestamp: raw.timestamp } : {},
|
|
22130
|
+
payload: { type: "function_call", name: "view_image", call_id: wrapper.callId, arguments: JSON.stringify(file2 ? { path: file2.slice(0, 4096) } : {}) }
|
|
22131
|
+
};
|
|
22132
|
+
}
|
|
22133
|
+
function codeModeOutputCall(raw) {
|
|
22134
|
+
const p = object2(raw.payload);
|
|
22135
|
+
return typeof raw.ordinal === "number" && raw.type === "response_item" && p.type === "custom_tool_call_output" && typeof p.call_id === "string" && p.call_id ? p.call_id : void 0;
|
|
22136
|
+
}
|
|
22137
|
+
function projectCodeModeOutput(raw, call) {
|
|
22138
|
+
const wrapper = call && codeModeWrapper(call);
|
|
22139
|
+
if (!call || !wrapper) return raw;
|
|
22140
|
+
const p = object2(raw.payload), blocks = Array.isArray(p.output) ? objects(p.output) : [];
|
|
22141
|
+
const images = blocks.filter((block) => ["input_image", "image"].includes(String(block.type)));
|
|
22142
|
+
if (wrapper.images.length) return images.length ? { ...raw, payload: { ...p, output: images } } : raw;
|
|
22143
|
+
const text4 = typeof p.output === "string" ? p.output : blocks.map((block) => typeof block.text === "string" ? block.text : "").join("\n");
|
|
22144
|
+
if (/^Script (completed|running)\b/.test(text4)) return void 0;
|
|
22145
|
+
return {
|
|
22146
|
+
type: "response_item",
|
|
22147
|
+
...call.timestamp !== void 0 ? { timestamp: call.timestamp } : {},
|
|
22148
|
+
payload: { type: "custom_tool_call", name: "exec", call_id: wrapper.callId, input: object2(call.payload).input },
|
|
22149
|
+
phren_item_output: raw
|
|
22150
|
+
};
|
|
22151
|
+
}
|
|
22152
|
+
async function findCodeModeCall(rows, line, callId) {
|
|
22153
|
+
const needle = Buffer.from(JSON.stringify(callId));
|
|
22154
|
+
for await (const row of rows(line, Math.max(0, line - 256))) {
|
|
22155
|
+
if (!row.bytes?.includes(needle)) continue;
|
|
22156
|
+
try {
|
|
22157
|
+
const raw = object2(JSON.parse(row.bytes.toString())), p = object2(raw.payload);
|
|
22158
|
+
if (raw.type === "response_item" && p.type === "custom_tool_call" && p.call_id === callId) return raw;
|
|
22159
|
+
} catch {
|
|
22160
|
+
}
|
|
22161
|
+
}
|
|
22162
|
+
return void 0;
|
|
22163
|
+
}
|
|
22164
|
+
function commandText(value2) {
|
|
22165
|
+
if (typeof value2 === "string") return value2;
|
|
22166
|
+
const parts = Array.isArray(value2) ? value2.filter((part) => typeof part === "string") : [];
|
|
22167
|
+
if (parts.length === 3 && ["-lc", "-c"].includes(parts[1]) && /(^|\/)(ba|z|da|fi|k)?sh$/.test(parts[0])) return parts[2];
|
|
22168
|
+
return parts.join(" ");
|
|
22169
|
+
}
|
|
22170
|
+
function localPath(value2) {
|
|
22171
|
+
if (typeof value2 !== "string" || !value2) return void 0;
|
|
22172
|
+
if (value2.startsWith("file://")) {
|
|
22173
|
+
try {
|
|
22174
|
+
const url2 = new URL(value2);
|
|
22175
|
+
if (url2.host) return void 0;
|
|
22176
|
+
const pathname = decodeURIComponent(url2.pathname);
|
|
22177
|
+
return /^\/[A-Za-z]:\//.test(pathname) ? pathname.slice(1) : pathname;
|
|
22178
|
+
} catch {
|
|
22179
|
+
return void 0;
|
|
22180
|
+
}
|
|
22181
|
+
}
|
|
22182
|
+
return value2.startsWith("/") ? value2 : void 0;
|
|
22183
|
+
}
|
|
22184
|
+
function changePatch(changes) {
|
|
22185
|
+
const sections = Object.entries(object2(changes)).slice(0, 50).map(([file2, value2]) => {
|
|
22186
|
+
const change = object2(value2), kind = String(change.type ?? "update");
|
|
22187
|
+
if (kind === "add") {
|
|
22188
|
+
const content = typeof change.content === "string" ? change.content.slice(0, PATCH_FILE).replace(/\n$/, "") : "";
|
|
22189
|
+
return `*** Add File: ${file2}
|
|
22190
|
+
` + content.split("\n").map((line) => "+" + line).join("\n");
|
|
22191
|
+
}
|
|
22192
|
+
if (kind === "delete") return `*** Delete File: ${file2}`;
|
|
22193
|
+
const moved = typeof change.move_path === "string" && change.move_path ? `
|
|
22194
|
+
*** Move to: ${change.move_path}` : "";
|
|
22195
|
+
const diff = typeof change.unified_diff === "string" ? change.unified_diff.slice(0, PATCH_FILE).replace(/\n$/, "") : "";
|
|
22196
|
+
return `*** Update File: ${file2}${moved}${diff ? "\n" + diff : ""}`;
|
|
22197
|
+
});
|
|
22198
|
+
return ["*** Begin Patch", ...sections, "*** End Patch"].join("\n");
|
|
22199
|
+
}
|
|
22200
|
+
function itemCall(raw, item) {
|
|
22201
|
+
const id2 = typeof item.id === "string" && item.id ? item.id.slice(0, 200) : "";
|
|
22202
|
+
if (!id2) return void 0;
|
|
22203
|
+
const stamp = raw.timestamp !== void 0 ? { timestamp: raw.timestamp } : {};
|
|
22204
|
+
const row = (call, output2) => ({
|
|
22205
|
+
type: "response_item",
|
|
22206
|
+
...stamp,
|
|
22207
|
+
payload: { ...call, call_id: id2 },
|
|
22208
|
+
phren_item_output: { type: "response_item", ...stamp, payload: { ...output2, call_id: id2 } }
|
|
22209
|
+
});
|
|
22210
|
+
const status = typeof item.status === "string" ? item.status : "completed";
|
|
22211
|
+
switch (item.type) {
|
|
22212
|
+
case "CommandExecution": {
|
|
22213
|
+
const workdir = localPath(item.cwd);
|
|
22214
|
+
const text4 = [item.aggregated_output, item.formatted_output].find((v) => typeof v === "string") ?? [item.stdout, item.stderr].filter((v) => typeof v === "string").join("");
|
|
22215
|
+
const tail = text4.slice(-OUTPUT_TAIL2);
|
|
22216
|
+
const output2 = typeof item.exit_code === "number" ? JSON.stringify({ output: tail, exit_code: item.exit_code }) : `${tail}${tail && !tail.endsWith("\n") ? "\n" : ""}[${status}]`;
|
|
22217
|
+
return row(
|
|
22218
|
+
{ type: "function_call", name: "exec_command", arguments: JSON.stringify({ cmd: commandText(item.command).slice(0, COMMAND), ...workdir ? { workdir } : {} }) },
|
|
22219
|
+
{ type: "function_call_output", output: output2 }
|
|
22220
|
+
);
|
|
22221
|
+
}
|
|
22222
|
+
case "FileChange": {
|
|
22223
|
+
const said = [status === "completed" ? item.stdout : item.stderr, item.stdout, item.stderr].find((v) => typeof v === "string" && v.trim());
|
|
22224
|
+
return row(
|
|
22225
|
+
{ type: "custom_tool_call", name: "apply_patch", input: changePatch(item.changes) },
|
|
22226
|
+
{ type: "custom_tool_call_output", output: (said ?? status).slice(-OUTPUT_TAIL2) }
|
|
22227
|
+
);
|
|
22228
|
+
}
|
|
22229
|
+
case "McpToolCall": {
|
|
22230
|
+
const result = object2(item.result), ok = object2(result.Ok ?? result), error62 = result.Err ?? item.error;
|
|
22231
|
+
const text4 = objects(ok.content).filter((block) => block.type === "text" && typeof block.text === "string").map((block) => String(block.text)).join("\n");
|
|
22232
|
+
const output2 = text4 || (error62 !== void 0 && error62 !== null ? typeof error62 === "string" ? error62 : JSON.stringify(error62) : status);
|
|
22233
|
+
const args = typeof item.arguments === "string" ? item.arguments : JSON.stringify(item.arguments ?? {});
|
|
22234
|
+
return row(
|
|
22235
|
+
{ type: "function_call", name: `mcp__${String(item.server ?? "mcp")}__${String(item.tool ?? "tool")}`, arguments: args.slice(0, 262144) },
|
|
22236
|
+
{ type: "function_call_output", output: output2.slice(0, MCP_OUTPUT) }
|
|
22237
|
+
);
|
|
22238
|
+
}
|
|
22239
|
+
default:
|
|
22240
|
+
return void 0;
|
|
22241
|
+
}
|
|
22242
|
+
}
|
|
22107
22243
|
function unescapeJs(value2) {
|
|
22108
22244
|
return value2.replace(/\\(u\{[0-9a-fA-F]{1,6}\}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}|[\s\S])/g, (_match, escape) => {
|
|
22109
22245
|
if (escape[0] === "u") {
|
|
@@ -22157,16 +22293,19 @@ function callArguments(source, open17) {
|
|
|
22157
22293
|
}
|
|
22158
22294
|
return void 0;
|
|
22159
22295
|
}
|
|
22160
|
-
function
|
|
22296
|
+
function argumentString(expression, source, keys) {
|
|
22161
22297
|
const inline = resolveString(expression, source);
|
|
22162
22298
|
if (inline !== void 0) return inline;
|
|
22163
22299
|
const inner = /^\{([\s\S]*)\}$/.exec(expression.trim())?.[1];
|
|
22164
22300
|
if (inner === void 0) return void 0;
|
|
22165
22301
|
const body2 = inner.trim();
|
|
22166
22302
|
if (/^[A-Za-z_$][\w$]*$/.test(body2)) return resolveString(body2, source);
|
|
22167
|
-
const property =
|
|
22303
|
+
const property = new RegExp(`(?:^|[,{])\\s*(?:${keys.join("|")})\\s*:\\s*("(?:\\\\.|[^"\\\\])*"|'(?:\\\\.|[^'\\\\])*'|\`(?:\\\\.|[^\`\\\\])*\`|[A-Za-z_$][\\w$]*)`).exec(body2);
|
|
22168
22304
|
return property ? resolveString(property[1], source) : void 0;
|
|
22169
22305
|
}
|
|
22306
|
+
function shellCommand(expression, source) {
|
|
22307
|
+
return argumentString(expression, source, ["command", "cmd"]);
|
|
22308
|
+
}
|
|
22170
22309
|
function codeToolCalls(source) {
|
|
22171
22310
|
const calls = [], original = source.slice(0, 262144);
|
|
22172
22311
|
for (const match of source.matchAll(CODE_TOOL_CALL)) {
|
|
@@ -22216,6 +22355,12 @@ function renameProjectedChanges(raw, base) {
|
|
|
22216
22355
|
}
|
|
22217
22356
|
function projectCodexRow(raw) {
|
|
22218
22357
|
if (raw.type !== "response_item") return { rows: [raw] };
|
|
22358
|
+
if (raw.phren_item_output !== void 0) {
|
|
22359
|
+
const { phren_item_output: output2, ...call } = raw, result = object2(output2);
|
|
22360
|
+
const expanded = object2(call.payload).name === "exec" ? projectCodexRow(call) : { rows: [call] };
|
|
22361
|
+
if (!expanded.base) return { rows: [...expanded.rows, result] };
|
|
22362
|
+
return { rows: [...expanded.rows, { ...result, payload: { ...object2(result.payload), call_id: `${expanded.base}:1` } }] };
|
|
22363
|
+
}
|
|
22219
22364
|
const payload = object2(raw.payload), type = String(payload.type), callId = typeof payload.call_id === "string" ? payload.call_id : "";
|
|
22220
22365
|
if (type === "custom_tool_call" || type === "function_call") {
|
|
22221
22366
|
const source = codeToolSource(payload.input ?? payload.arguments);
|
|
@@ -22242,7 +22387,7 @@ function rewriteProjectedOutput(entries2, base) {
|
|
|
22242
22387
|
entry.raw = { ...renameProjectedChanges(entry.raw, base), payload: { ...payload, call_id: `${base}:1` } };
|
|
22243
22388
|
}
|
|
22244
22389
|
}
|
|
22245
|
-
var childRelationCache, CODE_TOOL_CALL, JS_ESCAPES, projectedCodeCalls;
|
|
22390
|
+
var childRelationCache, OUTPUT_TAIL2, MCP_OUTPUT, PATCH_FILE, COMMAND, WRAPPED_TOOL, VIEW_IMAGE, ITEM_TOOLS, CODE_TOOL_CALL, JS_ESCAPES, projectedCodeCalls;
|
|
22246
22391
|
var init_transcript_codex = __esm({
|
|
22247
22392
|
"src/bridge/transcript-codex.ts"() {
|
|
22248
22393
|
"use strict";
|
|
@@ -22250,6 +22395,13 @@ var init_transcript_codex = __esm({
|
|
|
22250
22395
|
init_fanouts();
|
|
22251
22396
|
init_transcript_claude();
|
|
22252
22397
|
childRelationCache = /* @__PURE__ */ new Map();
|
|
22398
|
+
OUTPUT_TAIL2 = 4e3;
|
|
22399
|
+
MCP_OUTPUT = 65536;
|
|
22400
|
+
PATCH_FILE = 2e5;
|
|
22401
|
+
COMMAND = 16384;
|
|
22402
|
+
WRAPPED_TOOL = /\btools\s*\.\s*([A-Za-z_$][\w$]*)\s*\(/g;
|
|
22403
|
+
VIEW_IMAGE = /\btools\s*\.\s*view_image\s*\(/g;
|
|
22404
|
+
ITEM_TOOLS = /* @__PURE__ */ new Set(["exec_command", "write_stdin", "apply_patch", "view_image"]);
|
|
22253
22405
|
CODE_TOOL_CALL = /\btools\s*\.\s*(apply_patch|shell|read)\s*\(/g;
|
|
22254
22406
|
JS_ESCAPES = { n: "\n", r: "\r", t: " ", b: "\b", f: "\f", v: "\v", "0": "\0", "'": "'", '"': '"', "\\": "\\", "/": "/" };
|
|
22255
22407
|
projectedCodeCalls = /* @__PURE__ */ new Set();
|
|
@@ -22585,6 +22737,8 @@ var init_transcripts = __esm({
|
|
|
22585
22737
|
const { isSidechain: _sidechain, ...own2 } = raw;
|
|
22586
22738
|
raw = own2;
|
|
22587
22739
|
}
|
|
22740
|
+
const codeModeCall = raw && this.source === "codex" ? codeModeOutputCall(raw) : void 0;
|
|
22741
|
+
if (raw && codeModeCall) raw = projectCodeModeOutput(raw, await findCodeModeCall((upper, lower2) => index2.rows(handle, upper, lower2, signal), row.line, codeModeCall));
|
|
22588
22742
|
if (raw) {
|
|
22589
22743
|
if (this.changes && this.imageLine === void 0) {
|
|
22590
22744
|
const ids = outputCallIds(raw, this.source);
|
|
@@ -22827,7 +22981,7 @@ async function fanoutChildren(parentProvider, parentSession, env = process.env,
|
|
|
22827
22981
|
...blocked ? { reason: blockedReason(blocked) } : asking ? { reason: `needs-you: ${String(asking.message ?? asking.type)}`.slice(0, 500) } : {},
|
|
22828
22982
|
...finishedAt ? { finishedAt } : {},
|
|
22829
22983
|
transcript,
|
|
22830
|
-
fanout: { resumable:
|
|
22984
|
+
fanout: { resumable: manifest.session !== void 0 },
|
|
22831
22985
|
children: []
|
|
22832
22986
|
});
|
|
22833
22987
|
} catch {
|
|
@@ -23079,12 +23233,12 @@ function visibleCodexExecEvent(raw) {
|
|
|
23079
23233
|
} };
|
|
23080
23234
|
}
|
|
23081
23235
|
if (raw.type === "item.completed" && item.type === "file_change") {
|
|
23082
|
-
const files = codexFiles(item),
|
|
23236
|
+
const files = codexFiles(item), header = `${files.length} file(s) changed`;
|
|
23083
23237
|
return { type: "response_item", payload: {
|
|
23084
23238
|
type: "function_call_output",
|
|
23085
23239
|
call_id: callId(),
|
|
23086
|
-
output: files.length ? `${
|
|
23087
|
-
${files.map((file2) => file2.path).join("\n")}` :
|
|
23240
|
+
output: files.length ? `${header}
|
|
23241
|
+
${files.map((file2) => file2.path).join("\n")}` : header
|
|
23088
23242
|
} };
|
|
23089
23243
|
}
|
|
23090
23244
|
if (raw.type === "turn.completed") return { type: "event_msg", payload: { type: "task_complete" } };
|
|
@@ -26478,8 +26632,8 @@ function appendAuditLog(phrenPath, event, details) {
|
|
|
26478
26632
|
fs3.mkdirSync(path11.dirname(logPath), { recursive: true });
|
|
26479
26633
|
withFileLock(logPath, () => {
|
|
26480
26634
|
fs3.appendFileSync(logPath, line);
|
|
26481
|
-
const
|
|
26482
|
-
if (
|
|
26635
|
+
const stat26 = fs3.statSync(logPath);
|
|
26636
|
+
if (stat26.size > 1e6) {
|
|
26483
26637
|
const content = fs3.readFileSync(logPath, "utf8");
|
|
26484
26638
|
const lines = content.split("\n");
|
|
26485
26639
|
fs3.writeFileSync(logPath, lines.slice(-MAX_LOG_LINES).join("\n") + "\n");
|
|
@@ -26568,8 +26722,8 @@ ${Date.now()}`, { flag: "wx" });
|
|
|
26568
26722
|
} catch (err) {
|
|
26569
26723
|
logger.debug("acquireFileLock", `lockWrite: ${errorMessage(err)}`);
|
|
26570
26724
|
try {
|
|
26571
|
-
const
|
|
26572
|
-
if (Date.now() -
|
|
26725
|
+
const stat26 = fs5.statSync(lockPath);
|
|
26726
|
+
if (Date.now() - stat26.mtimeMs > staleThreshold) {
|
|
26573
26727
|
let ownerAlive = false;
|
|
26574
26728
|
try {
|
|
26575
26729
|
const content = fs5.readFileSync(lockPath, "utf-8");
|
|
@@ -27774,13 +27928,22 @@ var init_claude = __esm({
|
|
|
27774
27928
|
"--output-format",
|
|
27775
27929
|
"stream-json",
|
|
27776
27930
|
"--verbose",
|
|
27777
|
-
"--model",
|
|
27778
|
-
|
|
27779
|
-
|
|
27931
|
+
...o.model && o.model !== "default" ? ["--model", o.model] : [],
|
|
27932
|
+
"--permission-mode",
|
|
27933
|
+
o.review ? "plan" : "acceptEdits",
|
|
27780
27934
|
...o.resume ? ["--resume", o.resume] : [],
|
|
27781
27935
|
...o.extra ?? []
|
|
27782
27936
|
],
|
|
27783
|
-
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
|
+
}
|
|
27784
27947
|
};
|
|
27785
27948
|
}
|
|
27786
27949
|
});
|
|
@@ -27824,6 +27987,7 @@ __export(launcher_exports, {
|
|
|
27824
27987
|
jobsRoot: () => jobsRoot,
|
|
27825
27988
|
launch: () => launch,
|
|
27826
27989
|
listJobs: () => listJobs,
|
|
27990
|
+
nearestAgent: () => nearestAgent,
|
|
27827
27991
|
readJob: () => readJob,
|
|
27828
27992
|
swiftBuildCount: () => swiftBuildCount,
|
|
27829
27993
|
writeManifest: () => writeManifest
|
|
@@ -27859,11 +28023,29 @@ function swiftBuildCount() {
|
|
|
27859
28023
|
const output2 = execFileSync2("ps", ["-axo", "comm="], { encoding: "utf8", timeout: 5e3 });
|
|
27860
28024
|
return output2.split("\n").filter((line) => path19.basename(line.trim()) === "xcodebuild").length;
|
|
27861
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
|
+
}
|
|
27862
28044
|
function writeManifest(job, manifest) {
|
|
27863
28045
|
atomicWriteText(path19.join(job, "manifest.json"), JSON.stringify(manifestSchema.parse(manifest)) + "\n");
|
|
27864
28046
|
fs11.chmodSync(path19.join(job, "manifest.json"), 384);
|
|
27865
28047
|
}
|
|
27866
|
-
function createJob(options, env = process.env) {
|
|
28048
|
+
function createJob(options, env = process.env, nearest = nearestAgent) {
|
|
27867
28049
|
if (!options.label.trim() || options.label.length > 200) throw new Error("Choose a label of 1 to 200 characters.");
|
|
27868
28050
|
const worktree = fs11.realpathSync(options.worktree);
|
|
27869
28051
|
if (!fs11.statSync(worktree).isDirectory()) throw new Error("Choose a worktree directory.");
|
|
@@ -27871,7 +28053,9 @@ function createJob(options, env = process.env) {
|
|
|
27871
28053
|
const root = jobsRoot(options.store), job = path19.join(root, id2);
|
|
27872
28054
|
fs11.mkdirSync(job, { recursive: true, mode: 448 });
|
|
27873
28055
|
fs11.chmodSync(root, 448);
|
|
27874
|
-
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;
|
|
27875
28059
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
27876
28060
|
const manifest = {
|
|
27877
28061
|
schemaVersion: 1,
|
|
@@ -27911,6 +28095,7 @@ async function launch(options, reservation = createJob(options)) {
|
|
|
27911
28095
|
detached: process.platform !== "win32"
|
|
27912
28096
|
});
|
|
27913
28097
|
let pending = "", stderr = "", cancelled = false;
|
|
28098
|
+
let refused;
|
|
27914
28099
|
const watchdog = new LoopWatchdog();
|
|
27915
28100
|
const kill = () => {
|
|
27916
28101
|
try {
|
|
@@ -27941,6 +28126,7 @@ async function launch(options, reservation = createJob(options)) {
|
|
|
27941
28126
|
const event = JSON.parse(line);
|
|
27942
28127
|
watchdog.observe(event);
|
|
27943
28128
|
record2(adapter.session(event));
|
|
28129
|
+
refused ??= adapter.refusal?.(event);
|
|
27944
28130
|
} catch {
|
|
27945
28131
|
}
|
|
27946
28132
|
}
|
|
@@ -27987,7 +28173,7 @@ async function launch(options, reservation = createJob(options)) {
|
|
|
27987
28173
|
for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) process.off(signal, cancel);
|
|
27988
28174
|
fs11.closeSync(out);
|
|
27989
28175
|
fs11.closeSync(err);
|
|
27990
|
-
const blockedFile = path19.join(job, "blocked.json"), refusal = stderrRefusal(stderr);
|
|
28176
|
+
const blockedFile = path19.join(job, "blocked.json"), refusal = refused ?? stderrRefusal(stderr);
|
|
27991
28177
|
if (refusal && !fs11.existsSync(blockedFile)) atomicWriteText(blockedFile, JSON.stringify({ ...refusal, at: (/* @__PURE__ */ new Date()).toISOString() }));
|
|
27992
28178
|
const blocked = fs11.existsSync(blockedFile);
|
|
27993
28179
|
if (blocked) console.error(`blocked: ${fs11.readFileSync(blockedFile, "utf8").slice(0, 4e3)}`);
|
|
@@ -28259,12 +28445,12 @@ function writeProfile(file2, name, projects, description) {
|
|
|
28259
28445
|
if (!line.startsWith("#") && line.trim() !== "") break;
|
|
28260
28446
|
headerLines.push(line);
|
|
28261
28447
|
}
|
|
28262
|
-
const
|
|
28448
|
+
const header = headerLines.length ? `${headerLines.join("\n").replace(/\n+$/, "")}
|
|
28263
28449
|
` : "";
|
|
28264
28450
|
const normalized = [...new Set(projects)].sort();
|
|
28265
28451
|
const out = dump({ name, ...description ? { description } : {}, projects: normalized, ...rest }, { lineWidth: 1e3 });
|
|
28266
28452
|
const tmpPath = `${file2}.tmp-${crypto3.randomUUID()}`;
|
|
28267
|
-
fs14.writeFileSync(tmpPath,
|
|
28453
|
+
fs14.writeFileSync(tmpPath, header + out);
|
|
28268
28454
|
fs14.renameSync(tmpPath, file2);
|
|
28269
28455
|
}
|
|
28270
28456
|
function addProjectToProfile(phrenPath, profile, project) {
|
|
@@ -28317,7 +28503,7 @@ var init_package_metadata = __esm({
|
|
|
28317
28503
|
__dirname = path24.dirname(fileURLToPath2(import.meta.url));
|
|
28318
28504
|
ROOT = path24.join(__dirname, "..");
|
|
28319
28505
|
PACKAGE_JSON_PATH = path24.join(ROOT, "package.json");
|
|
28320
|
-
BUNDLED_VERSION = true ? "0.3.
|
|
28506
|
+
BUNDLED_VERSION = true ? "0.3.11" : "0.0.0";
|
|
28321
28507
|
PACKAGE_JSON = readPackageJson();
|
|
28322
28508
|
PACKAGE_NAME = PACKAGE_JSON.name || "phren";
|
|
28323
28509
|
VERSION = PACKAGE_JSON.version || BUNDLED_VERSION;
|
|
@@ -30411,7 +30597,7 @@ var require_extension = __commonJS({
|
|
|
30411
30597
|
if (dest[name] === void 0) dest[name] = [elem];
|
|
30412
30598
|
else dest[name].push(elem);
|
|
30413
30599
|
}
|
|
30414
|
-
function parse4(
|
|
30600
|
+
function parse4(header) {
|
|
30415
30601
|
const offers = /* @__PURE__ */ Object.create(null);
|
|
30416
30602
|
let params = /* @__PURE__ */ Object.create(null);
|
|
30417
30603
|
let mustUnescape = false;
|
|
@@ -30423,8 +30609,8 @@ var require_extension = __commonJS({
|
|
|
30423
30609
|
let code = -1;
|
|
30424
30610
|
let end = -1;
|
|
30425
30611
|
let i = 0;
|
|
30426
|
-
for (; i <
|
|
30427
|
-
code =
|
|
30612
|
+
for (; i < header.length; i++) {
|
|
30613
|
+
code = header.charCodeAt(i);
|
|
30428
30614
|
if (extensionName === void 0) {
|
|
30429
30615
|
if (end === -1 && tokenChars[code] === 1) {
|
|
30430
30616
|
if (start === -1) start = i;
|
|
@@ -30435,7 +30621,7 @@ var require_extension = __commonJS({
|
|
|
30435
30621
|
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
30436
30622
|
}
|
|
30437
30623
|
if (end === -1) end = i;
|
|
30438
|
-
const name =
|
|
30624
|
+
const name = header.slice(start, end);
|
|
30439
30625
|
if (code === 44) {
|
|
30440
30626
|
push(offers, name, params);
|
|
30441
30627
|
params = /* @__PURE__ */ Object.create(null);
|
|
@@ -30456,7 +30642,7 @@ var require_extension = __commonJS({
|
|
|
30456
30642
|
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
30457
30643
|
}
|
|
30458
30644
|
if (end === -1) end = i;
|
|
30459
|
-
push(params,
|
|
30645
|
+
push(params, header.slice(start, end), true);
|
|
30460
30646
|
if (code === 44) {
|
|
30461
30647
|
push(offers, extensionName, params);
|
|
30462
30648
|
params = /* @__PURE__ */ Object.create(null);
|
|
@@ -30464,7 +30650,7 @@ var require_extension = __commonJS({
|
|
|
30464
30650
|
}
|
|
30465
30651
|
start = end = -1;
|
|
30466
30652
|
} else if (code === 61 && start !== -1 && end === -1) {
|
|
30467
|
-
paramName =
|
|
30653
|
+
paramName = header.slice(start, i);
|
|
30468
30654
|
start = end = -1;
|
|
30469
30655
|
} else {
|
|
30470
30656
|
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
@@ -30488,7 +30674,7 @@ var require_extension = __commonJS({
|
|
|
30488
30674
|
} else {
|
|
30489
30675
|
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
30490
30676
|
}
|
|
30491
|
-
} else if (code === 34 &&
|
|
30677
|
+
} else if (code === 34 && header.charCodeAt(i - 1) === 61) {
|
|
30492
30678
|
inQuotes = true;
|
|
30493
30679
|
} else if (end === -1 && tokenChars[code] === 1) {
|
|
30494
30680
|
if (start === -1) start = i;
|
|
@@ -30499,7 +30685,7 @@ var require_extension = __commonJS({
|
|
|
30499
30685
|
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
30500
30686
|
}
|
|
30501
30687
|
if (end === -1) end = i;
|
|
30502
|
-
let value2 =
|
|
30688
|
+
let value2 = header.slice(start, end);
|
|
30503
30689
|
if (mustUnescape) {
|
|
30504
30690
|
value2 = value2.replace(/\\/g, "");
|
|
30505
30691
|
mustUnescape = false;
|
|
@@ -30521,7 +30707,7 @@ var require_extension = __commonJS({
|
|
|
30521
30707
|
throw new SyntaxError("Unexpected end of input");
|
|
30522
30708
|
}
|
|
30523
30709
|
if (end === -1) end = i;
|
|
30524
|
-
const token =
|
|
30710
|
+
const token = header.slice(start, end);
|
|
30525
30711
|
if (extensionName === void 0) {
|
|
30526
30712
|
push(offers, token, params);
|
|
30527
30713
|
} else {
|
|
@@ -31554,13 +31740,13 @@ var require_subprotocol = __commonJS({
|
|
|
31554
31740
|
"../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/subprotocol.js"(exports, module) {
|
|
31555
31741
|
"use strict";
|
|
31556
31742
|
var { tokenChars } = require_validation();
|
|
31557
|
-
function parse4(
|
|
31743
|
+
function parse4(header) {
|
|
31558
31744
|
const protocols = /* @__PURE__ */ new Set();
|
|
31559
31745
|
let start = -1;
|
|
31560
31746
|
let end = -1;
|
|
31561
31747
|
let i = 0;
|
|
31562
|
-
for (i; i <
|
|
31563
|
-
const code =
|
|
31748
|
+
for (i; i < header.length; i++) {
|
|
31749
|
+
const code = header.charCodeAt(i);
|
|
31564
31750
|
if (end === -1 && tokenChars[code] === 1) {
|
|
31565
31751
|
if (start === -1) start = i;
|
|
31566
31752
|
} else if (i !== 0 && (code === 32 || code === 9)) {
|
|
@@ -31570,7 +31756,7 @@ var require_subprotocol = __commonJS({
|
|
|
31570
31756
|
throw new SyntaxError(`Unexpected character at index ${i}`);
|
|
31571
31757
|
}
|
|
31572
31758
|
if (end === -1) end = i;
|
|
31573
|
-
const protocol2 =
|
|
31759
|
+
const protocol2 = header.slice(start, end);
|
|
31574
31760
|
if (protocols.has(protocol2)) {
|
|
31575
31761
|
throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
|
|
31576
31762
|
}
|
|
@@ -31583,7 +31769,7 @@ var require_subprotocol = __commonJS({
|
|
|
31583
31769
|
if (start === -1 || end !== -1) {
|
|
31584
31770
|
throw new SyntaxError("Unexpected end of input");
|
|
31585
31771
|
}
|
|
31586
|
-
const protocol =
|
|
31772
|
+
const protocol = header.slice(start, i);
|
|
31587
31773
|
if (protocols.has(protocol)) {
|
|
31588
31774
|
throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
|
|
31589
31775
|
}
|
|
@@ -32704,7 +32890,7 @@ function choiceKey(value2) {
|
|
|
32704
32890
|
if (text4 === "up" || text4 === "down" || text4 === "tab") return text4[0].toUpperCase() + text4.slice(1);
|
|
32705
32891
|
return choiceKeys.has(text4) ? text4 : void 0;
|
|
32706
32892
|
}
|
|
32707
|
-
function
|
|
32893
|
+
function commandText2(value2) {
|
|
32708
32894
|
if (typeof value2 === "string" && value2.trim()) return value2.trim();
|
|
32709
32895
|
if (Array.isArray(value2)) {
|
|
32710
32896
|
const parts = value2.filter((part) => typeof part === "string" && !!part.trim());
|
|
@@ -32800,14 +32986,14 @@ function opencodePermissionDialog(ansi) {
|
|
|
32800
32986
|
const raw = ansi.split(/\r?\n/);
|
|
32801
32987
|
const plain2 = raw.map((line) => stripTerminal(line).replace(/\r/g, ""));
|
|
32802
32988
|
const content = (line) => line.replace(/^\s*[┃│]?/, "");
|
|
32803
|
-
let
|
|
32989
|
+
let header = -1;
|
|
32804
32990
|
plain2.forEach((line, index2) => {
|
|
32805
|
-
if (/^\s*△\s*Permission required\s*$/.test(content(line)))
|
|
32991
|
+
if (/^\s*△\s*Permission required\s*$/.test(content(line))) header = index2;
|
|
32806
32992
|
});
|
|
32807
|
-
if (
|
|
32808
|
-
const row = plain2.findIndex((line, index2) => index2 >
|
|
32809
|
-
if (row < 0 || row -
|
|
32810
|
-
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());
|
|
32811
32997
|
const [asks, ...rest] = body2;
|
|
32812
32998
|
const title = (asks?.replace(/^[←→]\s*/, "") || "Permission required").slice(0, 4e3);
|
|
32813
32999
|
const patterns = rest.indexOf("Patterns");
|
|
@@ -32853,7 +33039,7 @@ function numberedDialog(text4) {
|
|
|
32853
33039
|
return { title: title.slice(0, 4e3), options: options.slice(0, 12) };
|
|
32854
33040
|
}
|
|
32855
33041
|
function terminalChoice(input2) {
|
|
32856
|
-
const fields = object2(input2), command =
|
|
33042
|
+
const fields = object2(input2), command = commandText2(fields.command ?? fields.cmd);
|
|
32857
33043
|
let options = [fields.options, fields.choices, fields.actions, fields.answers].map(structuredOptions).find((list) => list.length >= 2) ?? [];
|
|
32858
33044
|
if (options.length < 2) {
|
|
32859
33045
|
const text4 = [fields.question, fields.description, fields.justification, fields.prompt, fields.message, fields.text, fields.content, fields.display].filter((value2) => typeof value2 === "string").join("\n");
|
|
@@ -32878,7 +33064,7 @@ function permissionTitle(tool, input2) {
|
|
|
32878
33064
|
function samePermission(choice, title, tool, input2) {
|
|
32879
33065
|
const text4 = choice.title?.toLowerCase() ?? "";
|
|
32880
33066
|
if (title && text4.includes(title.toLowerCase())) return true;
|
|
32881
|
-
const command =
|
|
33067
|
+
const command = commandText2(object2(input2).command ?? object2(input2).cmd);
|
|
32882
33068
|
if (command && text4.includes(command.toLowerCase())) return true;
|
|
32883
33069
|
const name = tool.split("__").pop();
|
|
32884
33070
|
return !!name && name !== "action" && text4.includes(name.toLowerCase());
|
|
@@ -34447,7 +34633,7 @@ var init_audit = __esm({
|
|
|
34447
34633
|
|
|
34448
34634
|
// src/governance/activity.ts
|
|
34449
34635
|
import * as fs25 from "fs";
|
|
34450
|
-
import * as
|
|
34636
|
+
import * as path58 from "path";
|
|
34451
34637
|
function clampSnippet(snippet) {
|
|
34452
34638
|
if (!snippet) return void 0;
|
|
34453
34639
|
const flat = snippet.replace(/\s+/g, " ").trim();
|
|
@@ -34458,7 +34644,7 @@ function recordLookupEvents(phrenPath, events) {
|
|
|
34458
34644
|
if (!events.length) return;
|
|
34459
34645
|
const logPath = lookupEventsLogFile(phrenPath);
|
|
34460
34646
|
try {
|
|
34461
|
-
fs25.mkdirSync(
|
|
34647
|
+
fs25.mkdirSync(path58.dirname(logPath), { recursive: true });
|
|
34462
34648
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
34463
34649
|
const lines = events.map(
|
|
34464
34650
|
(e) => JSON.stringify({
|
|
@@ -34480,8 +34666,8 @@ function recordLookupEvents(phrenPath, events) {
|
|
|
34480
34666
|
return;
|
|
34481
34667
|
}
|
|
34482
34668
|
try {
|
|
34483
|
-
const
|
|
34484
|
-
if (
|
|
34669
|
+
const stat26 = fs25.statSync(logPath);
|
|
34670
|
+
if (stat26.size > ROTATE_BYTES) {
|
|
34485
34671
|
const content = fs25.readFileSync(logPath, "utf8");
|
|
34486
34672
|
const kept = content.split("\n").filter(Boolean).slice(-MAX_LOG_LINES2);
|
|
34487
34673
|
fs25.writeFileSync(logPath, kept.join("\n") + "\n");
|
|
@@ -34743,7 +34929,7 @@ var init_metadata = __esm({
|
|
|
34743
34929
|
|
|
34744
34930
|
// src/governance/policy.ts
|
|
34745
34931
|
import * as fs26 from "fs";
|
|
34746
|
-
import * as
|
|
34932
|
+
import * as path59 from "path";
|
|
34747
34933
|
function assessSyncOutage(sync, nowMs = Date.now()) {
|
|
34748
34934
|
const consecutiveFailures = sync?.consecutiveFailures ?? 0;
|
|
34749
34935
|
const failingNow = sync?.lastPushStatus !== void 0 && FAILED_PUSH_STATUSES.has(sync.lastPushStatus);
|
|
@@ -34880,7 +35066,7 @@ function normalizeIndexPolicy(data) {
|
|
|
34880
35066
|
function readJsonFile(filePath, fallback) {
|
|
34881
35067
|
try {
|
|
34882
35068
|
if (!fs26.existsSync(filePath)) return fallback;
|
|
34883
|
-
const basename12 =
|
|
35069
|
+
const basename12 = path59.basename(filePath);
|
|
34884
35070
|
const schema = GOVERNANCE_FILE_SCHEMAS[basename12];
|
|
34885
35071
|
if (schema && !validateGovernanceJson(filePath, schema)) {
|
|
34886
35072
|
debugLog(`readJsonFile: ${filePath} failed validation, using defaults`);
|
|
@@ -35013,7 +35199,7 @@ var init_policy = __esm({
|
|
|
35013
35199
|
});
|
|
35014
35200
|
|
|
35015
35201
|
// src/bridge/command.ts
|
|
35016
|
-
import { readFile as
|
|
35202
|
+
import { readFile as readFile36 } from "node:fs/promises";
|
|
35017
35203
|
|
|
35018
35204
|
// src/bridge/fanout-messages.ts
|
|
35019
35205
|
init_zod();
|
|
@@ -35080,7 +35266,7 @@ var FanoutMessages = class {
|
|
|
35080
35266
|
if (!relation?.fanout?.resumable) throw new BridgeError(404, "That resumable worker is not part of this conversation.");
|
|
35081
35267
|
const root = await containedFanoutRoot(this.env);
|
|
35082
35268
|
const job = (await this.jobs()).find((job2) => root && fanoutChildID(root, job2.manifest) === child);
|
|
35083
|
-
if (!job || !job.manifest.session || !["codex", "opencode"].includes(job.manifest.provider)) {
|
|
35269
|
+
if (!job || !job.manifest.session || !["codex", "opencode", "claude"].includes(job.manifest.provider)) {
|
|
35084
35270
|
throw new BridgeError(404, "That worker does not belong to this store.");
|
|
35085
35271
|
}
|
|
35086
35272
|
return job;
|
|
@@ -35163,7 +35349,7 @@ var FanoutMessages = class {
|
|
|
35163
35349
|
try {
|
|
35164
35350
|
const fresh = (await this.jobs()).find((candidate) => candidate.directory === job.directory);
|
|
35165
35351
|
if (!fresh || ["queued", "running"].includes(fresh.manifest.status)) return;
|
|
35166
|
-
if (!fresh.manifest.session || !["codex", "opencode"].includes(fresh.manifest.provider)) return;
|
|
35352
|
+
if (!fresh.manifest.session || !["codex", "opencode", "claude"].includes(fresh.manifest.provider)) return;
|
|
35167
35353
|
const next = (await this.records(fresh)).find((row) => row.message.status === "queued");
|
|
35168
35354
|
if (!next) return;
|
|
35169
35355
|
pending = next;
|
|
@@ -35207,7 +35393,7 @@ var FanoutMessages = class {
|
|
|
35207
35393
|
id: message.id,
|
|
35208
35394
|
text: message.text
|
|
35209
35395
|
}) + "\n", { mode: 384 });
|
|
35210
|
-
const
|
|
35396
|
+
const run2 = this.deps.run ?? (async (job2, text4) => {
|
|
35211
35397
|
const { launch: launch2 } = await Promise.resolve().then(() => (init_launcher(), launcher_exports));
|
|
35212
35398
|
return launch2({
|
|
35213
35399
|
store: storeRoot(this.env),
|
|
@@ -35221,7 +35407,7 @@ var FanoutMessages = class {
|
|
|
35221
35407
|
}, { job: job2.directory, manifest: job2.manifest });
|
|
35222
35408
|
});
|
|
35223
35409
|
launched = true;
|
|
35224
|
-
void
|
|
35410
|
+
void run2({ ...fresh, manifest }, message.text).then(async (code) => {
|
|
35225
35411
|
await atomic(sentFile, JSON.stringify({ ...message, status: code === 0 ? "completed" : "failed" }));
|
|
35226
35412
|
}).catch(async () => {
|
|
35227
35413
|
await atomic(sentFile, JSON.stringify({ ...message, status: "failed" }));
|
|
@@ -35280,9 +35466,9 @@ import * as path23 from "node:path";
|
|
|
35280
35466
|
function gitDirectory(store) {
|
|
35281
35467
|
const dotGit = path23.join(store, ".git");
|
|
35282
35468
|
try {
|
|
35283
|
-
const
|
|
35284
|
-
if (
|
|
35285
|
-
if (!
|
|
35469
|
+
const stat26 = fs15.statSync(dotGit);
|
|
35470
|
+
if (stat26.isDirectory()) return dotGit;
|
|
35471
|
+
if (!stat26.isFile()) return void 0;
|
|
35286
35472
|
const match = /^gitdir:\s*(.+)\s*$/i.exec(fs15.readFileSync(dotGit, "utf8"));
|
|
35287
35473
|
if (!match) return void 0;
|
|
35288
35474
|
return path23.resolve(store, match[1]);
|
|
@@ -35317,7 +35503,7 @@ import * as fs17 from "node:fs";
|
|
|
35317
35503
|
import * as path25 from "node:path";
|
|
35318
35504
|
var core = (names) => names.map((name) => ({ name, profiles: ["core", "full"] }));
|
|
35319
35505
|
var full = (names) => names.map((name) => ({ name, profiles: ["full"] }));
|
|
35320
|
-
var routes = (method, paths) => paths.map((
|
|
35506
|
+
var routes = (method, paths) => paths.map((path87) => ({ method, path: path87 }));
|
|
35321
35507
|
var BUILTIN_MODULES = [
|
|
35322
35508
|
{
|
|
35323
35509
|
schemaVersion: 1,
|
|
@@ -35514,7 +35700,10 @@ var BUILTIN_MODULES = [
|
|
|
35514
35700
|
"bridge ssh",
|
|
35515
35701
|
"pair",
|
|
35516
35702
|
"bridge fanouts archive",
|
|
35517
|
-
"canary"
|
|
35703
|
+
"canary",
|
|
35704
|
+
"computers",
|
|
35705
|
+
"computers mcp",
|
|
35706
|
+
"usage"
|
|
35518
35707
|
],
|
|
35519
35708
|
agentHooks: [
|
|
35520
35709
|
{ agents: ["codex", "claude"], events: ["SessionStart", "UserPromptSubmit", "Stop", "PermissionRequest"], handler: "bridge-hook.mjs hook <agent>" },
|
|
@@ -35539,6 +35728,7 @@ var BUILTIN_MODULES = [
|
|
|
35539
35728
|
"/v1/uploads/image",
|
|
35540
35729
|
"/v1/files/range",
|
|
35541
35730
|
"/v1/usage",
|
|
35731
|
+
"/v1/resources",
|
|
35542
35732
|
"/v1/push/status",
|
|
35543
35733
|
"/v1/projects/locate",
|
|
35544
35734
|
"/v1/projects/repos",
|
|
@@ -35604,7 +35794,8 @@ var BUILTIN_MODULES = [
|
|
|
35604
35794
|
"speech",
|
|
35605
35795
|
"speechTimestamps",
|
|
35606
35796
|
"transcribe",
|
|
35607
|
-
"promptOnce"
|
|
35797
|
+
"promptOnce",
|
|
35798
|
+
"resources"
|
|
35608
35799
|
],
|
|
35609
35800
|
storeFiles: [".runtime/sessions/opencode-*.events.jsonl", ".runtime/approvals/opencode-*.json"],
|
|
35610
35801
|
localFiles: ["<bridge>/installed.json", "<bridge>/versions/**", "<bridge>/current", "<bridge>/dispatch", "<bridge>/computer-id", "<bridge>/canary.json", "<bridge>/canary-daily"],
|
|
@@ -35836,11 +36027,11 @@ function activateModules(store, profile = snapshotProfile(store), legacyHook = f
|
|
|
35836
36027
|
|
|
35837
36028
|
// src/bridge/server.ts
|
|
35838
36029
|
import { randomUUID as randomUUID19 } from "node:crypto";
|
|
35839
|
-
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";
|
|
35840
36031
|
import { readFileSync as readFileSync32 } from "node:fs";
|
|
35841
36032
|
import { createServer as createServer2 } from "node:http";
|
|
35842
|
-
import { cpus, hostname as hostname9, loadavg } from "node:os";
|
|
35843
|
-
import
|
|
36033
|
+
import { cpus as cpus2, hostname as hostname9, loadavg as loadavg2 } from "node:os";
|
|
36034
|
+
import path85 from "node:path";
|
|
35844
36035
|
|
|
35845
36036
|
// ../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/wrapper.mjs
|
|
35846
36037
|
var import_stream = __toESM(require_stream(), 1);
|
|
@@ -36459,9 +36650,9 @@ var APNsSender = class {
|
|
|
36459
36650
|
token() {
|
|
36460
36651
|
const created = Math.floor(this.now() / 1e3);
|
|
36461
36652
|
if (this.jwt && created - this.jwt.created < 50 * 60) return this.jwt.value;
|
|
36462
|
-
const
|
|
36653
|
+
const header = base64url3(JSON.stringify({ alg: "ES256", kid: this.config.keyId }));
|
|
36463
36654
|
const claims = base64url3(JSON.stringify({ iss: this.config.teamId, iat: created }));
|
|
36464
|
-
const input2 = `${
|
|
36655
|
+
const input2 = `${header}.${claims}`;
|
|
36465
36656
|
const signature = sign("sha256", Buffer.from(input2), { key: createPrivateKey(this.key), dsaEncoding: "ieee-p1363" });
|
|
36466
36657
|
const value2 = `${input2}.${base64url3(signature)}`;
|
|
36467
36658
|
this.jwt = { value: value2, created };
|
|
@@ -38405,7 +38596,7 @@ var CodeRoutes = class {
|
|
|
38405
38596
|
const project = projectSchema.parse(projectValue ?? "");
|
|
38406
38597
|
const { codeDatabasePath } = await requireCodePackage(this.store);
|
|
38407
38598
|
const file2 = codeDatabasePath(this.store, project);
|
|
38408
|
-
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 })));
|
|
38409
38600
|
return { project, disabled: true };
|
|
38410
38601
|
}
|
|
38411
38602
|
async reindex(projectValue) {
|
|
@@ -38610,10 +38801,10 @@ var ContextUsageReader = class {
|
|
|
38610
38801
|
const metadata = await handle.stat();
|
|
38611
38802
|
if (!metadata.isFile()) return void 0;
|
|
38612
38803
|
const key2 = `codex:${session}:${file2}`;
|
|
38613
|
-
const
|
|
38804
|
+
const stat26 = `${metadata.dev}:${metadata.ino}:${metadata.size}:${metadata.mtimeMs}:${metadata.ctimeMs}`;
|
|
38614
38805
|
const cached2 = this.cache.get(key2);
|
|
38615
38806
|
this.cache.delete(key2);
|
|
38616
|
-
if (cached2?.stat ===
|
|
38807
|
+
if (cached2?.stat === stat26) {
|
|
38617
38808
|
this.cache.set(key2, cached2);
|
|
38618
38809
|
return cached2.percent;
|
|
38619
38810
|
}
|
|
@@ -38624,7 +38815,7 @@ var ContextUsageReader = class {
|
|
|
38624
38815
|
const after = await handle.stat();
|
|
38625
38816
|
if (after.size !== metadata.size || after.mtimeMs !== metadata.mtimeMs || after.ctimeMs !== metadata.ctimeMs) return void 0;
|
|
38626
38817
|
const percent = codexContext(tail, start === 0);
|
|
38627
|
-
this.cache.set(key2, { stat:
|
|
38818
|
+
this.cache.set(key2, { stat: stat26, percent });
|
|
38628
38819
|
while (this.cache.size > MAX_SESSIONS) this.cache.delete(this.cache.keys().next().value);
|
|
38629
38820
|
return percent;
|
|
38630
38821
|
} finally {
|
|
@@ -38701,7 +38892,7 @@ init_zod();
|
|
|
38701
38892
|
init_logger();
|
|
38702
38893
|
init_project_config();
|
|
38703
38894
|
import { randomUUID as randomUUID9 } from "node:crypto";
|
|
38704
|
-
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";
|
|
38705
38896
|
import path51 from "node:path";
|
|
38706
38897
|
|
|
38707
38898
|
// src/bridge/computers.ts
|
|
@@ -38717,12 +38908,12 @@ import { execFile as execFile8 } from "node:child_process";
|
|
|
38717
38908
|
|
|
38718
38909
|
// src/bridge/usage.ts
|
|
38719
38910
|
init_home_paths();
|
|
38720
|
-
init_fanouts();
|
|
38721
38911
|
init_protocol();
|
|
38722
38912
|
init_terminal_text();
|
|
38723
38913
|
import { execFile as execFile7, spawn as spawn2 } from "node:child_process";
|
|
38724
38914
|
import { createHash as createHash9 } from "node:crypto";
|
|
38725
|
-
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";
|
|
38726
38917
|
import { homedir as homedir11 } from "node:os";
|
|
38727
38918
|
import path45 from "node:path";
|
|
38728
38919
|
import { promisify as promisify6 } from "node:util";
|
|
@@ -38837,8 +39028,8 @@ async function readOpenRouterKey() {
|
|
|
38837
39028
|
try {
|
|
38838
39029
|
const handle = await open9(openCodeAuthFile(), "r");
|
|
38839
39030
|
try {
|
|
38840
|
-
const
|
|
38841
|
-
if (!
|
|
39031
|
+
const stat26 = await handle.stat();
|
|
39032
|
+
if (!stat26.isFile() || stat26.size > 65536) return void 0;
|
|
38842
39033
|
const key2 = object2(object2(JSON.parse(await handle.readFile("utf8"))).openrouter).key;
|
|
38843
39034
|
return typeof key2 === "string" && key2.length >= 16 && key2.length <= 4096 && !/[\x00-\x1f\x7f]/.test(key2) ? key2 : void 0;
|
|
38844
39035
|
} finally {
|
|
@@ -38863,309 +39054,114 @@ async function readOpenCodeGoKey() {
|
|
|
38863
39054
|
return void 0;
|
|
38864
39055
|
}
|
|
38865
39056
|
}
|
|
38866
|
-
var goPeriods = [
|
|
38867
|
-
{ id: "5h", label: "5h", milliseconds: 5 * 60 * 60 * 1e3 },
|
|
38868
|
-
{ id: "7d", label: "7d", milliseconds: 7 * 24 * 60 * 60 * 1e3 },
|
|
38869
|
-
{ id: "30d", label: "30d", milliseconds: 30 * 24 * 60 * 60 * 1e3 }
|
|
38870
|
-
];
|
|
38871
39057
|
var GO_GATEWAY = "https://opencode.ai/zen/go/v1";
|
|
38872
|
-
var MAX_GO_JOBS = 128;
|
|
38873
|
-
var MAX_GO_MANIFEST_BYTES = 64 * 1024;
|
|
38874
|
-
var MAX_GO_EVENTS_BYTES = 64 * 1024 * 1024;
|
|
38875
39058
|
var GO_KEY_MESSAGE = "Connect OpenCode Go on this computer to see its usage.";
|
|
38876
|
-
|
|
38877
|
-
|
|
38878
|
-
|
|
38879
|
-
|
|
38880
|
-
|
|
38881
|
-
|
|
38882
|
-
|
|
38883
|
-
|
|
38884
|
-
|
|
38885
|
-
|
|
38886
|
-
|
|
38887
|
-
|
|
38888
|
-
"
|
|
38889
|
-
|
|
38890
|
-
|
|
38891
|
-
|
|
38892
|
-
|
|
38893
|
-
"window",
|
|
38894
|
-
"period",
|
|
38895
|
-
"monthly",
|
|
38896
|
-
"weekly",
|
|
38897
|
-
"5h",
|
|
38898
|
-
"7d",
|
|
38899
|
-
"30d",
|
|
38900
|
-
"fivehour",
|
|
38901
|
-
"seven_day",
|
|
38902
|
-
"month",
|
|
38903
|
-
"limit",
|
|
38904
|
-
"quota",
|
|
38905
|
-
"max",
|
|
38906
|
-
"plan",
|
|
38907
|
-
"account",
|
|
38908
|
-
"rate",
|
|
38909
|
-
"ratelimit",
|
|
38910
|
-
"ratelimits",
|
|
38911
|
-
"remaining",
|
|
38912
|
-
"reset"
|
|
38913
|
-
]);
|
|
38914
|
-
return allowBare && /^[A-Za-z0-9][A-Za-z0-9._/-]{0,190}$/.test(model) && !reserved.has(model.toLowerCase()) ? `opencode-go/${model}` : void 0;
|
|
38915
|
-
}
|
|
38916
|
-
function amount(value2) {
|
|
38917
|
-
return typeof value2 === "number" && Number.isFinite(value2) && value2 >= 0 && value2 <= 1e9 ? value2 : void 0;
|
|
38918
|
-
}
|
|
38919
|
-
function resetAt(value2) {
|
|
38920
|
-
if (typeof value2 === "string" && Number.isFinite(Date.parse(value2))) return new Date(value2).toISOString();
|
|
38921
|
-
if (typeof value2 === "string" && /^\d+(?:\.\d+)?$/.test(value2)) return resetAt(Number(value2));
|
|
38922
|
-
if (typeof value2 === "number" && Number.isFinite(value2) && value2 > 0 && value2 < 3250368e4) {
|
|
38923
|
-
return new Date(value2 * 1e3).toISOString();
|
|
38924
|
-
}
|
|
38925
|
-
return void 0;
|
|
38926
|
-
}
|
|
38927
|
-
function recordGoLimit(limits, model, period, limitUSD, resetsAt) {
|
|
38928
|
-
if (limitUSD === void 0 || limitUSD <= 0) return;
|
|
38929
|
-
const current2 = limits.get(model) ?? {};
|
|
38930
|
-
const existing = current2[period];
|
|
38931
|
-
current2[period] = existing ? { ...existing, ...existing.resetsAt ? {} : { resetsAt } } : { limitUSD, resetsAt };
|
|
38932
|
-
limits.set(model, current2);
|
|
38933
|
-
}
|
|
38934
|
-
function numberFrom(value2, names) {
|
|
38935
|
-
for (const name of names) {
|
|
38936
|
-
const found = amount(value2[name]);
|
|
38937
|
-
if (found !== void 0) return found;
|
|
38938
|
-
}
|
|
38939
|
-
return void 0;
|
|
38940
|
-
}
|
|
38941
|
-
function parseGoLimits(value2, limits, model, period, depth = 0) {
|
|
38942
|
-
if (depth > 8) return;
|
|
38943
|
-
if (typeof value2 === "number") {
|
|
38944
|
-
if (period) recordGoLimit(limits, model ?? "*", period, amount(value2));
|
|
38945
|
-
return;
|
|
38946
|
-
}
|
|
38947
|
-
if (Array.isArray(value2)) {
|
|
38948
|
-
for (const item2 of value2.slice(0, 64)) parseGoLimits(item2, limits, model, period, depth + 1);
|
|
38949
|
-
return;
|
|
38950
|
-
}
|
|
38951
|
-
const item = object2(value2);
|
|
38952
|
-
if (!Object.keys(item).length) return;
|
|
38953
|
-
const nestedModel = goModel(item.model, true) ?? goModel(item.modelId, true) ?? goModel(item.model_id, true) ?? model;
|
|
38954
|
-
const nestedPeriod = goPeriod(item.window) ?? goPeriod(item.period) ?? goPeriod(item.interval) ?? goPeriod(item.windowName) ?? period;
|
|
38955
|
-
const limitUSD = numberFrom(item, ["limitUSD", "limit_usd", "dollarLimit", "dollar_limit", "creditLimit", "credit_limit", "limit", "quota", "max"]);
|
|
38956
|
-
const reset = resetAt(item.resetsAt) ?? resetAt(item.resets_at) ?? resetAt(item.resetAt) ?? resetAt(item.reset_at);
|
|
38957
|
-
if (nestedPeriod) recordGoLimit(limits, nestedModel ?? "*", nestedPeriod, limitUSD, reset);
|
|
38958
|
-
for (const [key2, nested] of Object.entries(item).slice(0, 64)) {
|
|
38959
|
-
const keyPeriod = goPeriod(key2) ?? nestedPeriod;
|
|
38960
|
-
const keyModel = goModel(key2) ?? nestedModel ?? (typeof nested === "object" && !keyPeriod ? goModel(key2, true) : void 0);
|
|
38961
|
-
if (typeof nested !== "object" && typeof nested !== "number") continue;
|
|
38962
|
-
parseGoLimits(nested, limits, keyModel, keyPeriod, depth + 1);
|
|
38963
|
-
}
|
|
38964
|
-
}
|
|
38965
|
-
function completeGoLimits(limits) {
|
|
38966
|
-
for (const [model, windows] of limits) {
|
|
38967
|
-
const monthly = windows["30d"]?.limitUSD ?? (windows["7d"] ? windows["7d"].limitUSD * 2 : windows["5h"] ? windows["5h"].limitUSD * 5 : void 0);
|
|
38968
|
-
if (!monthly || !Number.isFinite(monthly) || monthly <= 0) continue;
|
|
38969
|
-
recordGoLimit(limits, model, "5h", monthly * 0.2);
|
|
38970
|
-
recordGoLimit(limits, model, "7d", monthly * 0.5);
|
|
38971
|
-
recordGoLimit(limits, model, "30d", monthly);
|
|
38972
|
-
}
|
|
38973
|
-
}
|
|
38974
|
-
function header(response, name) {
|
|
38975
|
-
try {
|
|
38976
|
-
return response.headers.get(name) ?? void 0;
|
|
38977
|
-
} catch {
|
|
38978
|
-
return void 0;
|
|
38979
|
-
}
|
|
38980
|
-
}
|
|
38981
|
-
function parseGoHeaders(response, limits) {
|
|
38982
|
-
const limit = amount(Number(header(response, "x-ratelimit-limit")));
|
|
38983
|
-
const remaining = amount(Number(header(response, "x-ratelimit-remaining")));
|
|
38984
|
-
if (limit === void 0 || remaining === void 0 || remaining > limit) return;
|
|
38985
|
-
const period = goPeriod(header(response, "x-ratelimit-window"));
|
|
38986
|
-
const reset = resetAt(header(response, "x-ratelimit-reset"));
|
|
38987
|
-
recordGoLimit(limits, "*", period ?? "30d", limit, reset);
|
|
38988
|
-
}
|
|
38989
|
-
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) {
|
|
38990
39076
|
const controller = new AbortController();
|
|
38991
39077
|
const timer = setTimeout(() => controller.abort(), 8e3);
|
|
38992
|
-
const limits = /* @__PURE__ */ new Map();
|
|
38993
39078
|
try {
|
|
38994
|
-
const
|
|
38995
|
-
|
|
38996
|
-
|
|
38997
|
-
|
|
38998
|
-
|
|
38999
|
-
|
|
39000
|
-
|
|
39001
|
-
method,
|
|
39002
|
-
headers: { authorization: `Bearer ${key2}`, accept: "application/json" },
|
|
39003
|
-
redirect: "error",
|
|
39004
|
-
signal: controller.signal
|
|
39005
|
-
});
|
|
39006
|
-
if (!response.ok) return;
|
|
39007
|
-
parseGoHeaders(response, limits);
|
|
39008
|
-
if (method === "GET") {
|
|
39009
|
-
try {
|
|
39010
|
-
parseGoLimits(await response.json(), limits);
|
|
39011
|
-
} catch {
|
|
39012
|
-
}
|
|
39013
|
-
}
|
|
39014
|
-
}));
|
|
39015
|
-
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());
|
|
39016
39086
|
} finally {
|
|
39017
39087
|
clearTimeout(timer);
|
|
39018
39088
|
}
|
|
39019
|
-
completeGoLimits(limits);
|
|
39020
|
-
return limits;
|
|
39021
|
-
}
|
|
39022
|
-
async function containedRegularFile(root, candidate, maximum) {
|
|
39023
|
-
try {
|
|
39024
|
-
const link = await lstat8(candidate);
|
|
39025
|
-
if (!link.isFile() || link.isSymbolicLink() || link.size > maximum) return void 0;
|
|
39026
|
-
const resolved = await realpath9(candidate);
|
|
39027
|
-
if (!resolved.startsWith(root + path45.sep)) return void 0;
|
|
39028
|
-
const metadata = await stat14(resolved);
|
|
39029
|
-
return metadata.isFile() && metadata.size <= maximum ? resolved : void 0;
|
|
39030
|
-
} catch {
|
|
39031
|
-
return void 0;
|
|
39032
|
-
}
|
|
39033
39089
|
}
|
|
39034
|
-
|
|
39035
|
-
|
|
39036
|
-
|
|
39037
|
-
|
|
39038
|
-
|
|
39039
|
-
|
|
39040
|
-
|
|
39041
|
-
|
|
39042
|
-
|
|
39043
|
-
|
|
39044
|
-
|
|
39045
|
-
|
|
39046
|
-
|
|
39047
|
-
|
|
39048
|
-
function goStepCost(event, part) {
|
|
39049
|
-
const raw = part.cost ?? event.cost;
|
|
39050
|
-
if (typeof raw === "number") return amount(raw);
|
|
39051
|
-
const cost = object2(raw);
|
|
39052
|
-
return numberFrom(cost, ["total", "amount", "usd", "cost"]);
|
|
39053
|
-
}
|
|
39054
|
-
async function readOpenCodeGoLedger(root = fanoutRoot(), now = /* @__PURE__ */ new Date()) {
|
|
39055
|
-
const totals = /* @__PURE__ */ new Map();
|
|
39056
|
-
let directory;
|
|
39057
|
-
try {
|
|
39058
|
-
directory = await realpath9(root);
|
|
39059
|
-
} catch {
|
|
39060
|
-
return totals;
|
|
39061
|
-
}
|
|
39062
|
-
const names = (await readdir9(directory).catch(() => [])).slice(0, MAX_GO_JOBS);
|
|
39063
|
-
for (const name of names) {
|
|
39064
|
-
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(name)) continue;
|
|
39065
|
-
const manifestFile = await containedRegularFile(directory, path45.join(directory, name, "manifest.json"), MAX_GO_MANIFEST_BYTES);
|
|
39066
|
-
if (!manifestFile) continue;
|
|
39067
|
-
let manifest;
|
|
39068
|
-
try {
|
|
39069
|
-
manifest = object2(JSON.parse(await readFile17(manifestFile, "utf8")));
|
|
39070
|
-
} catch {
|
|
39071
|
-
continue;
|
|
39072
|
-
}
|
|
39073
|
-
const model = goModel(manifest.model);
|
|
39074
|
-
const eventLog = typeof manifest.eventLog === "string" && /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}\.jsonl$/.test(manifest.eventLog) ? manifest.eventLog : void 0;
|
|
39075
|
-
if (manifest.provider !== "opencode" || !model || !eventLog) continue;
|
|
39076
|
-
const jobRoot = await realpath9(path45.join(directory, name)).catch(() => void 0);
|
|
39077
|
-
if (!jobRoot || !jobRoot.startsWith(directory + path45.sep)) continue;
|
|
39078
|
-
const eventsFile = await containedRegularFile(jobRoot, path45.join(jobRoot, eventLog), MAX_GO_EVENTS_BYTES);
|
|
39079
|
-
if (!eventsFile) continue;
|
|
39080
|
-
let events;
|
|
39081
|
-
try {
|
|
39082
|
-
events = await readFile17(eventsFile, "utf8");
|
|
39083
|
-
} catch {
|
|
39084
|
-
continue;
|
|
39085
|
-
}
|
|
39086
|
-
for (const line of events.split("\n")) {
|
|
39087
|
-
if (!line || Buffer.byteLength(line) > 1048576) continue;
|
|
39088
|
-
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");
|
|
39089
39104
|
try {
|
|
39090
|
-
|
|
39091
|
-
|
|
39092
|
-
|
|
39093
|
-
|
|
39094
|
-
|
|
39095
|
-
|
|
39096
|
-
|
|
39097
|
-
|
|
39098
|
-
|
|
39099
|
-
|
|
39100
|
-
|
|
39101
|
-
|
|
39102
|
-
|
|
39103
|
-
"30d": { usedUSD: 0, usedTokens: 0 }
|
|
39104
|
-
};
|
|
39105
|
-
const usedUSD = modelTotals[period.id].usedUSD + (cost ?? 0);
|
|
39106
|
-
if (usedUSD > 1e9) continue;
|
|
39107
|
-
modelTotals[period.id].usedUSD = usedUSD;
|
|
39108
|
-
modelTotals[period.id].usedTokens += tokens;
|
|
39109
|
-
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();
|
|
39110
39118
|
}
|
|
39111
39119
|
}
|
|
39112
|
-
|
|
39113
|
-
|
|
39114
|
-
|
|
39115
|
-
|
|
39116
|
-
|
|
39117
|
-
|
|
39118
|
-
|
|
39119
|
-
return
|
|
39120
|
-
}
|
|
39121
|
-
|
|
39122
|
-
|
|
39123
|
-
|
|
39124
|
-
|
|
39125
|
-
|
|
39126
|
-
|
|
39127
|
-
|
|
39128
|
-
|
|
39129
|
-
|
|
39130
|
-
|
|
39131
|
-
|
|
39132
|
-
|
|
39133
|
-
|
|
39134
|
-
|
|
39135
|
-
|
|
39136
|
-
|
|
39137
|
-
|
|
39138
|
-
|
|
39139
|
-
|
|
39140
|
-
|
|
39141
|
-
|
|
39142
|
-
updatedAt: now.toISOString(),
|
|
39143
|
-
...windows.length ? { spend: { amountUSD: total30Days, period: "rolling_30_days" } } : {},
|
|
39144
|
-
...!hasKey ? { message: GO_KEY_MESSAGE } : {}
|
|
39145
|
-
};
|
|
39146
|
-
}
|
|
39147
|
-
var goDiscoveryCached;
|
|
39148
|
-
var goDiscoveryPending;
|
|
39149
|
-
async function cachedOpenCodeGoLimits(key2, now) {
|
|
39150
|
-
if (!goDiscoveryCached || now.getTime() - goDiscoveryCached.at >= 10 * 6e4) {
|
|
39151
|
-
goDiscoveryPending ??= fetchOpenCodeGoLimits(key2).catch(() => /* @__PURE__ */ new Map()).then((limits) => {
|
|
39152
|
-
goDiscoveryCached = { at: now.getTime(), limits };
|
|
39153
|
-
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;
|
|
39154
39150
|
}).finally(() => {
|
|
39155
|
-
|
|
39151
|
+
goPlanPending = void 0;
|
|
39156
39152
|
});
|
|
39157
39153
|
}
|
|
39158
|
-
return
|
|
39154
|
+
return goPlanPending ? await goPlanPending : goPlanCached.windows;
|
|
39159
39155
|
}
|
|
39160
39156
|
async function readOpenCodeGoUsage(now = /* @__PURE__ */ new Date(), options = {}) {
|
|
39161
|
-
const [
|
|
39162
|
-
if (!key2) return openCodeGoUsage(
|
|
39163
|
-
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);
|
|
39164
39159
|
try {
|
|
39165
|
-
|
|
39160
|
+
const windows = options.fetchImpl ? await fetchOpenCodeGoPlan(key2, options.fetchImpl) : await cachedOpenCodeGoPlan(key2, now);
|
|
39161
|
+
return openCodeGoUsage(windows, refusals, now, true);
|
|
39166
39162
|
} catch {
|
|
39163
|
+
return openCodeGoUsage([], refusals, now, true, true);
|
|
39167
39164
|
}
|
|
39168
|
-
return openCodeGoUsage(totals, limits, now, true);
|
|
39169
39165
|
}
|
|
39170
39166
|
async function fetchOpenRouterUsage(key2, fetchImpl = fetch, now = /* @__PURE__ */ new Date()) {
|
|
39171
39167
|
const controller = new AbortController();
|
|
@@ -39392,14 +39388,55 @@ function readCodexLimits(executable2 = codexExecutable()) {
|
|
|
39392
39388
|
send2({ id: 0, method: "initialize", params: { clientInfo: { name: "phren_usage", title: "Phren Usage", version: "1" } } });
|
|
39393
39389
|
});
|
|
39394
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
|
+
}
|
|
39395
39431
|
var AccountUsageReader = class {
|
|
39396
|
-
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) {
|
|
39397
39433
|
this.readCodex = readCodex;
|
|
39398
39434
|
this.now = now;
|
|
39399
39435
|
this.readClaudeLive = readClaudeLive;
|
|
39400
39436
|
this.readOpenCode = readOpenCode;
|
|
39401
39437
|
this.readOpenRouter = readOpenRouter;
|
|
39402
39438
|
this.readOpenCodeGo = readOpenCodeGo;
|
|
39439
|
+
this.readCopilot = readCopilot;
|
|
39403
39440
|
}
|
|
39404
39441
|
readCodex;
|
|
39405
39442
|
now;
|
|
@@ -39407,6 +39444,7 @@ var AccountUsageReader = class {
|
|
|
39407
39444
|
readOpenCode;
|
|
39408
39445
|
readOpenRouter;
|
|
39409
39446
|
readOpenCodeGo;
|
|
39447
|
+
readCopilot;
|
|
39410
39448
|
cached;
|
|
39411
39449
|
pending;
|
|
39412
39450
|
claudeCached;
|
|
@@ -39429,7 +39467,7 @@ var AccountUsageReader = class {
|
|
|
39429
39467
|
async spending() {
|
|
39430
39468
|
if (!this.spendingCached || this.now() - this.spendingCached.at >= 6e4) {
|
|
39431
39469
|
const at = this.now();
|
|
39432
|
-
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) => {
|
|
39433
39471
|
this.spendingCached = { at, value: value2 };
|
|
39434
39472
|
return value2;
|
|
39435
39473
|
}).finally(() => {
|
|
@@ -39462,8 +39500,8 @@ var AccountUsageReader = class {
|
|
|
39462
39500
|
try {
|
|
39463
39501
|
const handle = await open9(claudeFile(), "r");
|
|
39464
39502
|
try {
|
|
39465
|
-
const
|
|
39466
|
-
if (!
|
|
39503
|
+
const stat26 = await handle.stat();
|
|
39504
|
+
if (!stat26.isFile() || stat26.size > 16384) throw new Error("Invalid usage snapshot");
|
|
39467
39505
|
const saved = object2(JSON.parse(await handle.readFile("utf8")));
|
|
39468
39506
|
const date5 = new Date(String(saved.updatedAt));
|
|
39469
39507
|
if (!Number.isFinite(date5.getTime()) || date5.getTime() > this.now() + 6e4) throw new Error("Invalid usage timestamp");
|
|
@@ -39476,8 +39514,8 @@ var AccountUsageReader = class {
|
|
|
39476
39514
|
try {
|
|
39477
39515
|
const handle = await open9(claudeConfigFile(), "r");
|
|
39478
39516
|
try {
|
|
39479
|
-
const
|
|
39480
|
-
if (!
|
|
39517
|
+
const stat26 = await handle.stat();
|
|
39518
|
+
if (!stat26.isFile() || stat26.size > 16777216) throw new Error("Invalid Claude config");
|
|
39481
39519
|
const scoped = claudeScopedWindows(JSON.parse(await handle.readFile("utf8")), new Date(this.now())).filter((entry) => !claude2.windows.some((existing) => existing.id === entry.id));
|
|
39482
39520
|
if (scoped.length) claude2 = { ...claude2, windows: [...claude2.windows, ...scoped], message: void 0 };
|
|
39483
39521
|
} finally {
|
|
@@ -40242,10 +40280,10 @@ function projectAgents(values, parent, receipt, fallbackComputer, fallbackTarget
|
|
|
40242
40280
|
for (const value2 of values.slice(0, 128)) {
|
|
40243
40281
|
if (state.count >= 128) break;
|
|
40244
40282
|
const raw = object2(value2), id2 = childID.safeParse(raw.id), source = provider.safeParse(raw.provider);
|
|
40245
|
-
const
|
|
40283
|
+
const path87 = publicLabel(raw.path);
|
|
40246
40284
|
const callId = typeof raw.callId === "string" && raw.callId.length > 0 && raw.callId.length <= 200 ? raw.callId : void 0;
|
|
40247
40285
|
const routed = destination(raw, fallbackComputer, fallbackTarget);
|
|
40248
|
-
if (!id2.success || !source.success || !
|
|
40286
|
+
if (!id2.success || !source.success || !path87 || !callId || !routed) continue;
|
|
40249
40287
|
const descendant = lineage ? `${lineage}/${id2.data}` : id2.data;
|
|
40250
40288
|
const nestedSession = sessionId.safeParse(raw.session);
|
|
40251
40289
|
const cycleIdentity = nestedSession.success ? nestedSession.data : routed.remote.child ?? routed.remote.target.session;
|
|
@@ -40258,7 +40296,7 @@ function projectAgents(values, parent, receipt, fallbackComputer, fallbackTarget
|
|
|
40258
40296
|
projected.push({
|
|
40259
40297
|
id: publicID(parent, routed.computer.id, receipt.id, descendant),
|
|
40260
40298
|
provider: source.data,
|
|
40261
|
-
path:
|
|
40299
|
+
path: path87,
|
|
40262
40300
|
callId,
|
|
40263
40301
|
state: raw.failed === true ? "failed" : childState,
|
|
40264
40302
|
...typeof raw.finishedAt === "string" && Number.isFinite(Date.parse(raw.finishedAt)) ? { finishedAt: raw.finishedAt } : {},
|
|
@@ -40576,8 +40614,8 @@ async function dispatchProjectDirectory(project) {
|
|
|
40576
40614
|
const name = projectName.parse(project);
|
|
40577
40615
|
const source = readProjectConfig(phrenStoreRoot(), name).sourcePath;
|
|
40578
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.");
|
|
40579
|
-
const directory = await
|
|
40580
|
-
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.");
|
|
40581
40619
|
return directory;
|
|
40582
40620
|
}
|
|
40583
40621
|
async function save(receipt) {
|
|
@@ -40588,7 +40626,7 @@ async function save(receipt) {
|
|
|
40588
40626
|
var MAX_RECEIPT_BYTES = 65536;
|
|
40589
40627
|
var receiptUpdates = Promise.resolve();
|
|
40590
40628
|
function updateReceipt(receiptID, change) {
|
|
40591
|
-
const
|
|
40629
|
+
const run2 = receiptUpdates.then(async () => {
|
|
40592
40630
|
const file2 = path51.join(bridgeRoot(), "dispatches", `${external_exports.string().uuid().parse(receiptID)}.json`);
|
|
40593
40631
|
const info = await lstat12(file2).catch(() => void 0);
|
|
40594
40632
|
if (!info?.isFile() || info.isSymbolicLink() || info.size > MAX_RECEIPT_BYTES) return void 0;
|
|
@@ -40599,8 +40637,8 @@ function updateReceipt(receiptID, change) {
|
|
|
40599
40637
|
await atomic(file2, receiptSchema2.parse(receipt));
|
|
40600
40638
|
return receipt;
|
|
40601
40639
|
});
|
|
40602
|
-
receiptUpdates =
|
|
40603
|
-
return
|
|
40640
|
+
receiptUpdates = run2.catch(() => void 0);
|
|
40641
|
+
return run2;
|
|
40604
40642
|
}
|
|
40605
40643
|
async function receiptNames(root) {
|
|
40606
40644
|
try {
|
|
@@ -40909,7 +40947,7 @@ init_protocol();
|
|
|
40909
40947
|
|
|
40910
40948
|
// src/bridge/schedule-watch.ts
|
|
40911
40949
|
init_herdr();
|
|
40912
|
-
import { open as open11, stat as
|
|
40950
|
+
import { open as open11, stat as stat15 } from "node:fs/promises";
|
|
40913
40951
|
init_protocol();
|
|
40914
40952
|
init_transcripts();
|
|
40915
40953
|
init_terminal_text();
|
|
@@ -41044,7 +41082,7 @@ function ownerQuestion(text4) {
|
|
|
41044
41082
|
async function realTranscriptStamp(source, sessionId2) {
|
|
41045
41083
|
if (!sessionId2) return void 0;
|
|
41046
41084
|
const file2 = await transcriptPath(source, sessionId2).catch(() => void 0);
|
|
41047
|
-
const metadata = file2 ? await
|
|
41085
|
+
const metadata = file2 ? await stat15(file2).catch(() => void 0) : void 0;
|
|
41048
41086
|
return metadata ? { size: metadata.size, mtimeMs: metadata.mtimeMs } : void 0;
|
|
41049
41087
|
}
|
|
41050
41088
|
async function watchHerdrRun(server, target, signal, startup, env = {}) {
|
|
@@ -41374,7 +41412,7 @@ init_herdr();
|
|
|
41374
41412
|
init_transcripts();
|
|
41375
41413
|
import { execFile as execFile10 } from "node:child_process";
|
|
41376
41414
|
import { createHash as createHash12 } from "node:crypto";
|
|
41377
|
-
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";
|
|
41378
41416
|
import path52 from "node:path";
|
|
41379
41417
|
import { promisify as promisify9 } from "node:util";
|
|
41380
41418
|
init_transcript_index();
|
|
@@ -41495,7 +41533,7 @@ var CodexQuestions = class {
|
|
|
41495
41533
|
const cached2 = this.snapshots.get(target.session);
|
|
41496
41534
|
let pending = cached2?.pending;
|
|
41497
41535
|
if (!cached2 || Date.now() - cached2.at > 1e3) {
|
|
41498
|
-
const metadata = await
|
|
41536
|
+
const metadata = await stat16(file2), stamp = `${metadata.ino}:${metadata.size}:${metadata.mtimeMs}`;
|
|
41499
41537
|
pending = cached2?.stamp === stamp ? cached2.pending : await pendingAsyncQuestions(file2).catch((error62) => {
|
|
41500
41538
|
if (this.failedSnapshots.size >= 64) this.failedSnapshots.delete(this.failedSnapshots.keys().next().value);
|
|
41501
41539
|
this.failedSnapshots.set(target.session, Date.now());
|
|
@@ -41549,7 +41587,7 @@ init_transcripts();
|
|
|
41549
41587
|
init_home_paths();
|
|
41550
41588
|
init_protocol();
|
|
41551
41589
|
import { spawn as spawn6 } from "node:child_process";
|
|
41552
|
-
import { readdir as readdir11, readFile as readFile23, stat as
|
|
41590
|
+
import { readdir as readdir11, readFile as readFile23, stat as stat17 } from "node:fs/promises";
|
|
41553
41591
|
import { homedir as homedir15 } from "node:os";
|
|
41554
41592
|
import path53 from "node:path";
|
|
41555
41593
|
function readCodexModels(executable2 = codexExecutable()) {
|
|
@@ -41635,7 +41673,7 @@ async function readClaudeCatalog(configDir = claudeConfigDir(), installed) {
|
|
|
41635
41673
|
try {
|
|
41636
41674
|
for (const name of await readdir11(directory)) {
|
|
41637
41675
|
if (!name.endsWith("-cc.json")) continue;
|
|
41638
|
-
const file2 = path53.join(directory, name), at = (await
|
|
41676
|
+
const file2 = path53.join(directory, name), at = (await stat17(file2)).mtimeMs;
|
|
41639
41677
|
if (!newest || at > newest.at) newest = { file: file2, at };
|
|
41640
41678
|
}
|
|
41641
41679
|
} catch {
|
|
@@ -42207,20 +42245,277 @@ var ModelSwitcher = class {
|
|
|
42207
42245
|
}
|
|
42208
42246
|
};
|
|
42209
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
|
+
|
|
42210
42505
|
// src/bridge/schedules.ts
|
|
42211
42506
|
init_protocol();
|
|
42212
42507
|
init_project_config();
|
|
42213
42508
|
init_shared();
|
|
42214
42509
|
import { randomUUID as randomUUID11 } from "node:crypto";
|
|
42215
42510
|
import { hostname as hostname6 } from "node:os";
|
|
42216
|
-
import
|
|
42511
|
+
import path57 from "node:path";
|
|
42217
42512
|
|
|
42218
42513
|
// src/bridge/schedule-format.ts
|
|
42219
42514
|
init_js_yaml();
|
|
42220
42515
|
init_zod();
|
|
42221
42516
|
init_protocol();
|
|
42222
|
-
import { readFile as
|
|
42223
|
-
import
|
|
42517
|
+
import { readFile as readFile25 } from "node:fs/promises";
|
|
42518
|
+
import path55 from "node:path";
|
|
42224
42519
|
var SCHEDULE_EVERY = ["interval", "daily", "weekly", "once", "cron"];
|
|
42225
42520
|
var SCHEDULE_HARNESSES = ["claude", "codex", "opencode"];
|
|
42226
42521
|
var SCHEDULE_NOTIFY = ["start", "finish", "failure"];
|
|
@@ -42233,7 +42528,7 @@ var scheduleName = singleLine(80);
|
|
|
42233
42528
|
var timestamp3 = external_exports.string().datetime({ offset: true });
|
|
42234
42529
|
var localTimestamp = external_exports.string().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/);
|
|
42235
42530
|
var clockTime = external_exports.string().regex(/^(?:[01]\d|2[0-3]):[0-5]\d$/);
|
|
42236
|
-
var schedulePath = (projectDir) =>
|
|
42531
|
+
var schedulePath = (projectDir) => path55.join(projectDir, "schedules.yaml");
|
|
42237
42532
|
var runningStatuses = /* @__PURE__ */ new Set(["launched", "running", "blocked"]);
|
|
42238
42533
|
var MAX_SCHEDULES = 64;
|
|
42239
42534
|
var MAX_RUNS = 2e3;
|
|
@@ -42289,7 +42584,7 @@ function parseSchedule(value2) {
|
|
|
42289
42584
|
async function readScheduleDocument(projectDir) {
|
|
42290
42585
|
let text4;
|
|
42291
42586
|
try {
|
|
42292
|
-
text4 = await
|
|
42587
|
+
text4 = await readFile25(schedulePath(projectDir), "utf8");
|
|
42293
42588
|
} catch (error62) {
|
|
42294
42589
|
if (error62.code === "ENOENT") return { document: { version: 1 }, schedules: [] };
|
|
42295
42590
|
throw error62;
|
|
@@ -42410,7 +42705,7 @@ function nextRun(schedule, lastRun) {
|
|
|
42410
42705
|
async function readScheduleRuns(file2) {
|
|
42411
42706
|
let text4;
|
|
42412
42707
|
try {
|
|
42413
|
-
text4 = await
|
|
42708
|
+
text4 = await readFile25(file2, "utf8");
|
|
42414
42709
|
} catch (error62) {
|
|
42415
42710
|
if (error62.code === "ENOENT") return [];
|
|
42416
42711
|
throw error62;
|
|
@@ -42430,10 +42725,10 @@ async function readScheduleRuns(file2) {
|
|
|
42430
42725
|
}
|
|
42431
42726
|
async function writeScheduleRuns(file2, runs) {
|
|
42432
42727
|
const kept = runs.slice(-MAX_RUNS);
|
|
42433
|
-
await atomicInPrivateDir(file2, kept.map((
|
|
42728
|
+
await atomicInPrivateDir(file2, kept.map((run2) => JSON.stringify(run2)).join("\n") + (kept.length ? "\n" : ""));
|
|
42434
42729
|
}
|
|
42435
42730
|
function scheduleRunsFile() {
|
|
42436
|
-
return
|
|
42731
|
+
return path55.join(bridgeRoot(), "schedule-runs.jsonl");
|
|
42437
42732
|
}
|
|
42438
42733
|
|
|
42439
42734
|
// src/bridge/schedule-launch.ts
|
|
@@ -42446,8 +42741,8 @@ init_logger();
|
|
|
42446
42741
|
init_shared();
|
|
42447
42742
|
import { spawn as spawn7 } from "node:child_process";
|
|
42448
42743
|
import { createWriteStream } from "node:fs";
|
|
42449
|
-
import { mkdir as mkdir14, readFile as
|
|
42450
|
-
import
|
|
42744
|
+
import { mkdir as mkdir14, readFile as readFile26, stat as stat18 } from "node:fs/promises";
|
|
42745
|
+
import path56 from "node:path";
|
|
42451
42746
|
import { finished as streamFinished } from "node:stream/promises";
|
|
42452
42747
|
var CLAUDE_SCHEDULE_SETTINGS = JSON.stringify({ enableAllProjectMcpServers: true });
|
|
42453
42748
|
function createScheduleLauncher(launchHerdr, store = defaultPhrenPath()) {
|
|
@@ -42465,22 +42760,22 @@ function createScheduleLauncher(launchHerdr, store = defaultPhrenPath()) {
|
|
|
42465
42760
|
for (const child of children) child.kill("SIGTERM");
|
|
42466
42761
|
children.clear();
|
|
42467
42762
|
};
|
|
42468
|
-
launcher.resume = (
|
|
42763
|
+
launcher.resume = (run2, schedule) => resumeScheduleRun(run2, schedule, abort.signal);
|
|
42469
42764
|
return launcher;
|
|
42470
42765
|
}
|
|
42471
|
-
async function resumeScheduleRun(
|
|
42472
|
-
const launch2 =
|
|
42473
|
-
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." };
|
|
42474
42769
|
if (launch2.mode === "herdr" && launch2.server && launch2.workspaceId && launch2.tabId && launch2.paneId) {
|
|
42475
42770
|
return watch2(
|
|
42476
42771
|
launch2.server,
|
|
42477
42772
|
{ workspaceId: launch2.workspaceId, tabId: launch2.tabId, paneId: launch2.paneId },
|
|
42478
42773
|
signal,
|
|
42479
|
-
{ source: schedule.harness, startedAt: Date.parse(
|
|
42774
|
+
{ source: schedule.harness, startedAt: Date.parse(run2.startedAt), sessionId: launch2.sessionId }
|
|
42480
42775
|
);
|
|
42481
42776
|
}
|
|
42482
42777
|
if (launch2.mode === "headless" && launch2.jobDir) {
|
|
42483
|
-
const manifest = await
|
|
42778
|
+
const manifest = await readFile26(path56.join(launch2.jobDir, "manifest.json"), "utf8").then((text4) => JSON.parse(text4)).catch(() => void 0);
|
|
42484
42779
|
if (manifest?.status === "completed") return { status: "finished" };
|
|
42485
42780
|
if (manifest?.status === "failed") {
|
|
42486
42781
|
return { status: "failed", reason: typeof manifest.exitCode === "number" ? `The scheduled agent exited with code ${manifest.exitCode}.` : "The scheduled agent failed." };
|
|
@@ -42528,7 +42823,7 @@ async function promptWhenReady(server, paneId, text4, signal, waitMs = 6e4) {
|
|
|
42528
42823
|
}
|
|
42529
42824
|
}
|
|
42530
42825
|
async function launchHeadless(context, store, started) {
|
|
42531
|
-
const root = fanoutRoot({ ...process.env, PHREN_PATH: store }), jobDir =
|
|
42826
|
+
const root = fanoutRoot({ ...process.env, PHREN_PATH: store }), jobDir = path56.join(root, context.runId);
|
|
42532
42827
|
await mkdir14(jobDir, { recursive: true, mode: 448 });
|
|
42533
42828
|
const eventLog = "events.jsonl", now = (/* @__PURE__ */ new Date()).toISOString();
|
|
42534
42829
|
const manifest = {
|
|
@@ -42548,7 +42843,7 @@ async function launchHeadless(context, store, started) {
|
|
|
42548
42843
|
};
|
|
42549
42844
|
await writeManifest2(jobDir, manifest);
|
|
42550
42845
|
const command = headlessCommand(context.schedule, context.cwd);
|
|
42551
|
-
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)}`));
|
|
42552
42847
|
let child;
|
|
42553
42848
|
try {
|
|
42554
42849
|
child = spawn7(command.file, command.args, { cwd: command.cwd, env: process.env, stdio: ["pipe", "pipe", "pipe"] });
|
|
@@ -42560,8 +42855,8 @@ async function launchHeadless(context, store, started) {
|
|
|
42560
42855
|
const closed = new Promise((resolve11) => {
|
|
42561
42856
|
child.once("close", (code, signal) => resolve11({ code, signal }));
|
|
42562
42857
|
});
|
|
42563
|
-
const output2 = createWriteStream(
|
|
42564
|
-
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 });
|
|
42565
42860
|
const streamsFinished = Promise.all([streamFinished(output2), streamFinished(errors)]).then(() => void 0).catch(() => void 0);
|
|
42566
42861
|
child.stdin?.on("error", () => {
|
|
42567
42862
|
});
|
|
@@ -42614,19 +42909,19 @@ function tomlQuote(value2) {
|
|
|
42614
42909
|
}
|
|
42615
42910
|
async function ensureCodexDirTrusted(cwd) {
|
|
42616
42911
|
const directory = codexHome();
|
|
42617
|
-
const file2 =
|
|
42912
|
+
const file2 = path56.join(directory, "config.toml");
|
|
42618
42913
|
let text4 = "";
|
|
42619
42914
|
try {
|
|
42620
|
-
text4 = await
|
|
42915
|
+
text4 = await readFile26(file2, "utf8");
|
|
42621
42916
|
} catch (error62) {
|
|
42622
42917
|
if (error62.code !== "ENOENT") throw error62;
|
|
42623
42918
|
}
|
|
42624
|
-
const
|
|
42919
|
+
const header = `[projects.${tomlQuote(cwd)}]`;
|
|
42625
42920
|
const trustLine = 'trust_level = "trusted"';
|
|
42626
42921
|
let next;
|
|
42627
|
-
const at = text4.indexOf(
|
|
42922
|
+
const at = text4.indexOf(header);
|
|
42628
42923
|
if (at >= 0) {
|
|
42629
|
-
const bodyStart = at +
|
|
42924
|
+
const bodyStart = at + header.length;
|
|
42630
42925
|
const rest = text4.slice(bodyStart);
|
|
42631
42926
|
const nextTable = rest.search(/^\s*\[/m);
|
|
42632
42927
|
const section = nextTable >= 0 ? rest.slice(0, nextTable) : rest;
|
|
@@ -42641,17 +42936,17 @@ async function ensureCodexDirTrusted(cwd) {
|
|
|
42641
42936
|
}
|
|
42642
42937
|
} else {
|
|
42643
42938
|
const separator = text4 && !text4.endsWith("\n") ? "\n\n" : text4 ? "\n" : "";
|
|
42644
|
-
next = text4 + `${separator}${
|
|
42939
|
+
next = text4 + `${separator}${header}
|
|
42645
42940
|
${trustLine}
|
|
42646
42941
|
`;
|
|
42647
42942
|
}
|
|
42648
42943
|
await mkdir14(directory, { recursive: true, mode: 448 });
|
|
42649
|
-
const metadata = await
|
|
42944
|
+
const metadata = await stat18(file2).catch(() => void 0);
|
|
42650
42945
|
const mode = metadata ? metadata.mode & 511 : 384;
|
|
42651
42946
|
await atomic(file2, next, mode);
|
|
42652
42947
|
}
|
|
42653
42948
|
async function writeManifest2(jobDir, manifest) {
|
|
42654
|
-
await atomicInPrivateDir(
|
|
42949
|
+
await atomicInPrivateDir(path56.join(jobDir, "manifest.json"), JSON.stringify(manifest, null, 2) + "\n");
|
|
42655
42950
|
}
|
|
42656
42951
|
|
|
42657
42952
|
// src/bridge/schedules.ts
|
|
@@ -42689,7 +42984,7 @@ var Scheduler = class {
|
|
|
42689
42984
|
return getProjectDirs(this.store);
|
|
42690
42985
|
}
|
|
42691
42986
|
projectDirectory(project) {
|
|
42692
|
-
const found = this.projectDirectories().find((directory) =>
|
|
42987
|
+
const found = this.projectDirectories().find((directory) => path57.basename(directory).toLowerCase() === project.toLowerCase());
|
|
42693
42988
|
if (!found) throw new BridgeError(404, `Unknown project "${project}".`);
|
|
42694
42989
|
return found;
|
|
42695
42990
|
}
|
|
@@ -42715,10 +43010,10 @@ var Scheduler = class {
|
|
|
42715
43010
|
} catch {
|
|
42716
43011
|
continue;
|
|
42717
43012
|
}
|
|
42718
|
-
const project =
|
|
43013
|
+
const project = path57.basename(directory);
|
|
42719
43014
|
for (const schedule of schedules) {
|
|
42720
|
-
const matching = runs.filter((
|
|
42721
|
-
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));
|
|
42722
43017
|
const due = computerMatches(schedule.computer, computer) ? nextRun(schedule, last) : null;
|
|
42723
43018
|
result.push({
|
|
42724
43019
|
...schedule,
|
|
@@ -42741,28 +43036,28 @@ var Scheduler = class {
|
|
|
42741
43036
|
}
|
|
42742
43037
|
async history(filters = {}) {
|
|
42743
43038
|
const limit = Math.min(500, Math.max(1, filters.limit ?? 50));
|
|
42744
|
-
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();
|
|
42745
43040
|
}
|
|
42746
43041
|
async launchNow(projectName2, id2) {
|
|
42747
43042
|
const prepared = await this.exclusive(async () => {
|
|
42748
|
-
const projectDir = this.projectDirectory(projectName2), project =
|
|
43043
|
+
const projectDir = this.projectDirectory(projectName2), project = path57.basename(projectDir);
|
|
42749
43044
|
const file2 = await readScheduleDocument(projectDir), schedule = file2.schedules.find((item) => item.id === id2);
|
|
42750
43045
|
if (!schedule) throw new BridgeError(404, `Schedule "${id2}" was not found in ${project}.`);
|
|
42751
43046
|
if (!computerMatches(schedule.computer, this.computer())) throw new BridgeError(409, `${schedule.computer} owns this schedule; run it from that computer.`);
|
|
42752
43047
|
const runs = await readScheduleRuns(this.runsFile);
|
|
42753
|
-
if (runs.some((
|
|
43048
|
+
if (runs.some((run3) => run3.project === project && run3.scheduleId === id2 && runningStatuses.has(run3.status))) {
|
|
42754
43049
|
throw new BridgeError(409, `Schedule "${schedule.name}" is already running.`);
|
|
42755
43050
|
}
|
|
42756
|
-
const
|
|
42757
|
-
this.own.add(
|
|
42758
|
-
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]);
|
|
42759
43054
|
if (schedule.every === "once" && schedule.enabled) {
|
|
42760
43055
|
const updatedAt = this.now().toISOString();
|
|
42761
43056
|
const schedules = file2.schedules.map((item) => item.id === id2 ? { ...item, enabled: false, updatedAt } : item);
|
|
42762
43057
|
await writeScheduleDocument(projectDir, schedules, file2.document);
|
|
42763
43058
|
}
|
|
42764
43059
|
const source = getProjectSourcePath(this.store, project);
|
|
42765
|
-
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 };
|
|
42766
43061
|
});
|
|
42767
43062
|
try {
|
|
42768
43063
|
const launched = await this.launch({
|
|
@@ -42796,7 +43091,7 @@ var Scheduler = class {
|
|
|
42796
43091
|
}
|
|
42797
43092
|
async updateRun(id2, patch) {
|
|
42798
43093
|
return this.exclusive(async () => {
|
|
42799
|
-
const runs = await readScheduleRuns(this.runsFile), index2 = runs.findIndex((
|
|
43094
|
+
const runs = await readScheduleRuns(this.runsFile), index2 = runs.findIndex((run2) => run2.id === id2);
|
|
42800
43095
|
if (index2 < 0) throw new Error("The schedule run record disappeared.");
|
|
42801
43096
|
runs[index2] = { ...runs[index2], ...patch };
|
|
42802
43097
|
await writeScheduleRuns(this.runsFile, runs);
|
|
@@ -42804,34 +43099,34 @@ var Scheduler = class {
|
|
|
42804
43099
|
});
|
|
42805
43100
|
}
|
|
42806
43101
|
async finishRun(id2, schedule, status, reason2, previousNotification) {
|
|
42807
|
-
const
|
|
43102
|
+
const run2 = await this.updateRun(id2, { status, finishedAt: this.now().toISOString(), ...reason2 ? { reason: reason2 } : {} });
|
|
42808
43103
|
await previousNotification;
|
|
42809
|
-
if (
|
|
42810
|
-
await this.notifyRun(
|
|
43104
|
+
if (run2.blockedStartupPrompt && run2.blockNotified) return;
|
|
43105
|
+
await this.notifyRun(run2, schedule, status === "failed" ? "scheduleFailed" : "scheduleFinished");
|
|
42811
43106
|
}
|
|
42812
43107
|
async recordBlockedStartup(id2, schedule, promptText2) {
|
|
42813
43108
|
try {
|
|
42814
43109
|
const prompt = promptText2.slice(0, 4e3);
|
|
42815
|
-
const
|
|
42816
|
-
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}`);
|
|
42817
43112
|
if (delivered) await this.updateRun(id2, { blockNotified: true });
|
|
42818
43113
|
} catch (error62) {
|
|
42819
43114
|
this.log(`[schedule] blocked-at-startup record for run ${id2} failed: ${error62 instanceof Error ? error62.message : "unknown error"}`);
|
|
42820
43115
|
}
|
|
42821
43116
|
}
|
|
42822
|
-
async notifyRun(
|
|
43117
|
+
async notifyRun(run2, schedule, kind, reason2) {
|
|
42823
43118
|
const preference = kind === "scheduleStarted" ? "start" : kind === "scheduleFinished" ? "finish" : "failure";
|
|
42824
43119
|
if (!scheduleNotifications(schedule).has(preference)) return false;
|
|
42825
|
-
const route2 = scheduleSessionRoute(schedule,
|
|
42826
|
-
const text4 = reason2 ??
|
|
43120
|
+
const route2 = scheduleSessionRoute(schedule, run2.launch);
|
|
43121
|
+
const text4 = reason2 ?? run2.reason;
|
|
42827
43122
|
const value2 = {
|
|
42828
43123
|
kind,
|
|
42829
43124
|
scheduleId: schedule.id,
|
|
42830
|
-
project:
|
|
43125
|
+
project: run2.project,
|
|
42831
43126
|
name: schedule.name,
|
|
42832
43127
|
computer: schedule.computer,
|
|
42833
|
-
runId:
|
|
42834
|
-
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",
|
|
42835
43130
|
...text4 ? { reason: text4 } : {},
|
|
42836
43131
|
...route2 ? { route: route2 } : {}
|
|
42837
43132
|
};
|
|
@@ -42842,11 +43137,11 @@ var Scheduler = class {
|
|
|
42842
43137
|
result = { notified: false, reason: "push delivery failed" };
|
|
42843
43138
|
}
|
|
42844
43139
|
try {
|
|
42845
|
-
await this.updateRun(
|
|
43140
|
+
await this.updateRun(run2.id, { notified: result.notified, ...result.reason ? { notifyReason: result.reason } : { notifyReason: void 0 } });
|
|
42846
43141
|
} catch (error62) {
|
|
42847
|
-
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"}`);
|
|
42848
43143
|
}
|
|
42849
|
-
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"}`);
|
|
42850
43145
|
return result.notified;
|
|
42851
43146
|
}
|
|
42852
43147
|
/**
|
|
@@ -42859,26 +43154,26 @@ var Scheduler = class {
|
|
|
42859
43154
|
const resume = this.launch.resume;
|
|
42860
43155
|
if (this.recovered || !resume) return;
|
|
42861
43156
|
this.recovered = true;
|
|
42862
|
-
const open17 = (await readScheduleRuns(this.runsFile)).filter((
|
|
42863
|
-
for (const
|
|
42864
|
-
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);
|
|
42865
43160
|
let schedule;
|
|
42866
43161
|
try {
|
|
42867
|
-
schedule = (await readScheduleDocument(this.projectDirectory(
|
|
43162
|
+
schedule = (await readScheduleDocument(this.projectDirectory(run2.project))).schedules.find((item) => item.id === run2.scheduleId);
|
|
42868
43163
|
} catch {
|
|
42869
43164
|
schedule = void 0;
|
|
42870
43165
|
}
|
|
42871
43166
|
if (!schedule) {
|
|
42872
|
-
await this.updateRun(
|
|
43167
|
+
await this.updateRun(run2.id, {
|
|
42873
43168
|
status: "failed",
|
|
42874
43169
|
finishedAt: this.now().toISOString(),
|
|
42875
43170
|
reason: "Phren Hook restarted during this run, and its schedule no longer exists."
|
|
42876
|
-
}).catch((error62) => this.log(`[schedule] Could not close run ${
|
|
43171
|
+
}).catch((error62) => this.log(`[schedule] Could not close run ${run2.id}: ${String(error62)}`));
|
|
42877
43172
|
continue;
|
|
42878
43173
|
}
|
|
42879
43174
|
const known = schedule;
|
|
42880
|
-
this.log(`[schedule] Following run ${
|
|
42881
|
-
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)}`));
|
|
42882
43177
|
}
|
|
42883
43178
|
}
|
|
42884
43179
|
async tick() {
|
|
@@ -42904,23 +43199,23 @@ var Scheduler = class {
|
|
|
42904
43199
|
|
|
42905
43200
|
// src/bridge/canary.ts
|
|
42906
43201
|
init_phren_paths();
|
|
42907
|
-
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";
|
|
42908
43203
|
import { hostname as hostname8, tmpdir } from "node:os";
|
|
42909
|
-
import
|
|
43204
|
+
import path61 from "node:path";
|
|
42910
43205
|
|
|
42911
43206
|
// src/bridge/health.ts
|
|
42912
43207
|
init_policy();
|
|
42913
43208
|
init_phren_paths();
|
|
42914
43209
|
init_store_registry();
|
|
42915
|
-
import { execFile as
|
|
42916
|
-
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";
|
|
42917
43212
|
import { homedir as homedir16, hostname as hostname7 } from "node:os";
|
|
42918
|
-
import
|
|
42919
|
-
import { promisify as
|
|
43213
|
+
import path60 from "node:path";
|
|
43214
|
+
import { promisify as promisify11 } from "node:util";
|
|
42920
43215
|
init_protocol();
|
|
42921
43216
|
init_metrics();
|
|
42922
43217
|
init_terminal_tmux();
|
|
42923
|
-
var
|
|
43218
|
+
var exec11 = promisify11(execFile12);
|
|
42924
43219
|
async function terminalHealth() {
|
|
42925
43220
|
const [{ servers: servers2 }, tmux2] = await Promise.all([Promise.resolve().then(() => (init_herdr(), herdr_exports)), tmuxHealth()]);
|
|
42926
43221
|
const running2 = (await servers2().catch(() => [])).map((server) => ({
|
|
@@ -42981,7 +43276,7 @@ function plainError(value2) {
|
|
|
42981
43276
|
async function git3(cwd, args) {
|
|
42982
43277
|
try {
|
|
42983
43278
|
countGit("health");
|
|
42984
|
-
const { stdout } = await
|
|
43279
|
+
const { stdout } = await exec11("git", args, { cwd, timeout: 5e3, maxBuffer: 65536, env: { ...process.env, GIT_TERMINAL_PROMPT: "0" } });
|
|
42985
43280
|
return stdout.trim();
|
|
42986
43281
|
} catch {
|
|
42987
43282
|
return void 0;
|
|
@@ -43026,10 +43321,10 @@ async function storeSync(store) {
|
|
|
43026
43321
|
}
|
|
43027
43322
|
async function lastScheduledRun(store, runsFile = scheduleRunsFile()) {
|
|
43028
43323
|
const runs = await readScheduleRuns(runsFile).catch(() => []);
|
|
43029
|
-
const last = runs.reduce((newest,
|
|
43324
|
+
const last = runs.reduce((newest, run2) => !newest || run2.startedAt >= newest.startedAt ? run2 : newest, void 0);
|
|
43030
43325
|
if (!last) return null;
|
|
43031
43326
|
let name;
|
|
43032
|
-
const directory = getProjectDirs(store).find((dir) =>
|
|
43327
|
+
const directory = getProjectDirs(store).find((dir) => path60.basename(dir).toLowerCase() === last.project.toLowerCase());
|
|
43033
43328
|
if (directory) name = (await readScheduleDocument(directory).catch(() => void 0))?.schedules.find((item) => item.id === last.scheduleId)?.name;
|
|
43034
43329
|
return {
|
|
43035
43330
|
...name ? { name } : {},
|
|
@@ -43042,7 +43337,7 @@ async function lastScheduledRun(store, runsFile = scheduleRunsFile()) {
|
|
|
43042
43337
|
}
|
|
43043
43338
|
async function ownHostKey() {
|
|
43044
43339
|
try {
|
|
43045
|
-
return publicComputerKey(await
|
|
43340
|
+
return publicComputerKey(await readFile27("/etc/ssh/ssh_host_ed25519_key.pub", "utf8"));
|
|
43046
43341
|
} catch {
|
|
43047
43342
|
return void 0;
|
|
43048
43343
|
}
|
|
@@ -43083,20 +43378,20 @@ async function probePeer(peer, caller) {
|
|
|
43083
43378
|
}
|
|
43084
43379
|
}
|
|
43085
43380
|
function canaryFile(root = bridgeRoot()) {
|
|
43086
|
-
return
|
|
43381
|
+
return path60.join(root, "canary.json");
|
|
43087
43382
|
}
|
|
43088
43383
|
async function readCanary(root = bridgeRoot()) {
|
|
43089
43384
|
try {
|
|
43090
43385
|
const info = await lstat13(canaryFile(root));
|
|
43091
43386
|
if (!info.isFile() || info.size > 65536) return null;
|
|
43092
|
-
const value2 = JSON.parse(await
|
|
43387
|
+
const value2 = JSON.parse(await readFile27(canaryFile(root), "utf8"));
|
|
43093
43388
|
return value2 && value2.version === 1 && Array.isArray(value2.steps) ? value2 : null;
|
|
43094
43389
|
} catch {
|
|
43095
43390
|
return null;
|
|
43096
43391
|
}
|
|
43097
43392
|
}
|
|
43098
43393
|
async function pushConfigured() {
|
|
43099
|
-
const file2 = process.env.PHREN_APNS_CONFIG ||
|
|
43394
|
+
const file2 = process.env.PHREN_APNS_CONFIG || path60.join(bridgeRoot(), "apns.json");
|
|
43100
43395
|
const info = await lstat13(file2).catch(() => void 0);
|
|
43101
43396
|
return { configured: !!info?.isFile() };
|
|
43102
43397
|
}
|
|
@@ -43155,10 +43450,10 @@ function reason(error62) {
|
|
|
43155
43450
|
const text4 = error62 instanceof Error ? error62.message : "Unknown failure.";
|
|
43156
43451
|
return text4.replace(/[\x00-\x1f\x7f]+/g, " ").trim().slice(0, 300) || "Unknown failure.";
|
|
43157
43452
|
}
|
|
43158
|
-
async function step(steps, name,
|
|
43453
|
+
async function step(steps, name, run2) {
|
|
43159
43454
|
const started = Date.now();
|
|
43160
43455
|
try {
|
|
43161
|
-
steps.push({ name, durationMs: 0, ...await
|
|
43456
|
+
steps.push({ name, durationMs: 0, ...await run2() });
|
|
43162
43457
|
} catch (error62) {
|
|
43163
43458
|
steps.push({ name, durationMs: 0, status: "failed", reason: reason(error62) });
|
|
43164
43459
|
}
|
|
@@ -43185,7 +43480,7 @@ async function closeCanaryWorkspaces(server, before, created) {
|
|
|
43185
43480
|
}
|
|
43186
43481
|
async function conductorStep(options, server) {
|
|
43187
43482
|
const before = new Set(objects((await snapshot(server)).workspaces).map((workspace) => String(workspace.workspace_id)));
|
|
43188
|
-
const folder = await
|
|
43483
|
+
const folder = await realpath10(await mkdtemp4(path61.join(tmpdir(), "phren-canary-")));
|
|
43189
43484
|
let created, failure2, detail;
|
|
43190
43485
|
try {
|
|
43191
43486
|
const launched = await options.launch(server, { role: "conductor", kind: "claude", label: CANARY_LABEL, cwd: folder, timeoutMs: 45e3 });
|
|
@@ -43206,12 +43501,12 @@ async function scheduleStep(options) {
|
|
|
43206
43501
|
let count2 = 0;
|
|
43207
43502
|
const broken = [];
|
|
43208
43503
|
for (const directory of getProjectDirs(options.store)) {
|
|
43209
|
-
const present2 = await lstat14(
|
|
43504
|
+
const present2 = await lstat14(path61.join(directory, "schedules.yaml")).catch(() => void 0);
|
|
43210
43505
|
if (!present2) continue;
|
|
43211
43506
|
try {
|
|
43212
43507
|
count2 += (await readScheduleDocument(directory)).schedules.length;
|
|
43213
43508
|
} catch (error62) {
|
|
43214
|
-
broken.push(`${
|
|
43509
|
+
broken.push(`${path61.basename(directory)}: ${reason(error62)}`);
|
|
43215
43510
|
}
|
|
43216
43511
|
}
|
|
43217
43512
|
const tick = options.scheduler.lastTickAt;
|
|
@@ -43281,7 +43576,7 @@ function runCanary(options) {
|
|
|
43281
43576
|
}
|
|
43282
43577
|
async function dailyCanaryEnabled(root = bridgeRoot()) {
|
|
43283
43578
|
if (process.env.PHREN_CANARY_DAILY === "1") return true;
|
|
43284
|
-
return !!(await lstat14(
|
|
43579
|
+
return !!(await lstat14(path61.join(root, "canary-daily")).catch(() => void 0))?.isFile();
|
|
43285
43580
|
}
|
|
43286
43581
|
async function dailyCanaryDue(root = bridgeRoot(), now = Date.now()) {
|
|
43287
43582
|
if (running || !await dailyCanaryEnabled(root)) return false;
|
|
@@ -43294,11 +43589,11 @@ init_shared();
|
|
|
43294
43589
|
|
|
43295
43590
|
// src/bridge/server-routes.ts
|
|
43296
43591
|
init_zod();
|
|
43297
|
-
import
|
|
43592
|
+
import path84 from "node:path";
|
|
43298
43593
|
|
|
43299
43594
|
// src/bridge/code-note.ts
|
|
43300
43595
|
init_zod();
|
|
43301
|
-
import * as
|
|
43596
|
+
import * as path67 from "node:path";
|
|
43302
43597
|
|
|
43303
43598
|
// src/content/validate.ts
|
|
43304
43599
|
init_utils_helpers();
|
|
@@ -43312,7 +43607,7 @@ init_store_routing();
|
|
|
43312
43607
|
init_locks();
|
|
43313
43608
|
init_data_utils();
|
|
43314
43609
|
import * as fs28 from "fs";
|
|
43315
|
-
import * as
|
|
43610
|
+
import * as path63 from "path";
|
|
43316
43611
|
import * as crypto7 from "crypto";
|
|
43317
43612
|
|
|
43318
43613
|
// src/project-topics.ts
|
|
@@ -43324,7 +43619,7 @@ init_data_utils();
|
|
|
43324
43619
|
init_filenames();
|
|
43325
43620
|
import * as crypto6 from "crypto";
|
|
43326
43621
|
import * as fs27 from "fs";
|
|
43327
|
-
import * as
|
|
43622
|
+
import * as path62 from "path";
|
|
43328
43623
|
var TOPIC_CONFIG_FILENAME = "topic-config.json";
|
|
43329
43624
|
var SOFTWARE_TOPICS = [
|
|
43330
43625
|
{
|
|
@@ -43862,7 +44157,7 @@ function topicDocHeader(project, topic) {
|
|
|
43862
44157
|
}
|
|
43863
44158
|
function appendArchivedEntriesToTopicDoc(filePath, project, topic, entries2) {
|
|
43864
44159
|
if (entries2.length === 0) return;
|
|
43865
|
-
fs27.mkdirSync(
|
|
44160
|
+
fs27.mkdirSync(path62.dirname(filePath), { recursive: true });
|
|
43866
44161
|
withFileLock(filePath, () => {
|
|
43867
44162
|
let existing = "";
|
|
43868
44163
|
if (fs27.existsSync(filePath)) existing = fs27.readFileSync(filePath, "utf8");
|
|
@@ -43981,7 +44276,7 @@ function autoArchiveToReference(phrenPath, project, keepCount) {
|
|
|
43981
44276
|
if (!isValidProjectName(project)) return phrenErr(`Invalid project name: "${project}".`, PhrenError.INVALID_PROJECT_NAME);
|
|
43982
44277
|
const resolvedDir = storeAwareProjectPath(phrenPath, project);
|
|
43983
44278
|
if (!resolvedDir || !fs28.existsSync(resolvedDir)) return phrenErr(`Project "${project}" not found in phren.`, PhrenError.PROJECT_NOT_FOUND);
|
|
43984
|
-
const learningsPath =
|
|
44279
|
+
const learningsPath = path63.join(resolvedDir, FINDINGS_FILENAME);
|
|
43985
44280
|
if (!fs28.existsSync(learningsPath)) return phrenOk(0);
|
|
43986
44281
|
const STALE_LOCK_MS = 6e5;
|
|
43987
44282
|
const lockFile = runtimeFile(phrenPath, `consolidation-${project}.lock`);
|
|
@@ -43990,8 +44285,8 @@ function autoArchiveToReference(phrenPath, project, keepCount) {
|
|
|
43990
44285
|
} catch (e) {
|
|
43991
44286
|
if (e.code === "EEXIST") {
|
|
43992
44287
|
try {
|
|
43993
|
-
const
|
|
43994
|
-
if (Date.now() -
|
|
44288
|
+
const stat26 = fs28.statSync(lockFile);
|
|
44289
|
+
if (Date.now() - stat26.mtimeMs < STALE_LOCK_MS) {
|
|
43995
44290
|
return phrenErr("Consolidation already running", PhrenError.LOCK_TIMEOUT);
|
|
43996
44291
|
}
|
|
43997
44292
|
tryUnlink(lockFile);
|
|
@@ -44017,7 +44312,7 @@ function autoArchiveToReference(phrenPath, project, keepCount) {
|
|
|
44017
44312
|
const entries2 = parseActiveEntries(content);
|
|
44018
44313
|
if (entries2.length <= keepCount) return phrenOk(0);
|
|
44019
44314
|
const toArchive = entries2.slice(0, entries2.length - keepCount);
|
|
44020
|
-
const referenceDir =
|
|
44315
|
+
const referenceDir = path63.join(resolvedDir, "reference");
|
|
44021
44316
|
const { topics } = readProjectTopics(phrenPath, project);
|
|
44022
44317
|
const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
|
|
44023
44318
|
const archivedSet = buildArchivedBulletSet(referenceDir);
|
|
@@ -44581,7 +44876,7 @@ var DEFAULT_DECAY = {
|
|
|
44581
44876
|
var DEFAULT_UNDATED_CONFIDENCE = DEFAULT_DECAY.d120;
|
|
44582
44877
|
|
|
44583
44878
|
// src/content/dedup.ts
|
|
44584
|
-
import * as
|
|
44879
|
+
import * as path64 from "path";
|
|
44585
44880
|
init_shared();
|
|
44586
44881
|
init_utils();
|
|
44587
44882
|
init_store_routing();
|
|
@@ -44705,7 +45000,7 @@ function resolveCoref(text4, context) {
|
|
|
44705
45000
|
result = result.replace(/\bthe project\b/gi, context.project);
|
|
44706
45001
|
}
|
|
44707
45002
|
if (context.file) {
|
|
44708
|
-
const basename12 =
|
|
45003
|
+
const basename12 = path64.basename(context.file);
|
|
44709
45004
|
result = result.replace(/\b(this file|the file)\b/gi, basename12);
|
|
44710
45005
|
}
|
|
44711
45006
|
if (context.project && /\b(it|this|that|they|them)\b/i.test(result)) {
|
|
@@ -44722,7 +45017,7 @@ init_shared();
|
|
|
44722
45017
|
init_shared();
|
|
44723
45018
|
init_governance();
|
|
44724
45019
|
import * as fs30 from "fs";
|
|
44725
|
-
import * as
|
|
45020
|
+
import * as path66 from "path";
|
|
44726
45021
|
import * as crypto8 from "crypto";
|
|
44727
45022
|
|
|
44728
45023
|
// src/finding-graph-id.ts
|
|
@@ -44757,7 +45052,7 @@ init_store_routing();
|
|
|
44757
45052
|
// src/finding/context.ts
|
|
44758
45053
|
init_utils();
|
|
44759
45054
|
import * as fs29 from "fs";
|
|
44760
|
-
import * as
|
|
45055
|
+
import * as path65 from "path";
|
|
44761
45056
|
|
|
44762
45057
|
// src/session/utils.ts
|
|
44763
45058
|
init_utils();
|
|
@@ -44839,14 +45134,14 @@ function resolveFindingTaskReference(phrenPath, project, match) {
|
|
|
44839
45134
|
const projectDir = safeProjectPath(phrenPath, project);
|
|
44840
45135
|
if (!projectDir) return { error: `Invalid project name: "${project}".` };
|
|
44841
45136
|
const taskPath = resolveTaskFilePath(phrenPath, project);
|
|
44842
|
-
const items = parseTaskItems(taskPath ??
|
|
45137
|
+
const items = parseTaskItems(taskPath ?? path65.join(projectDir, "tasks.md"));
|
|
44843
45138
|
return resolveTaskItemMatch(items, match);
|
|
44844
45139
|
}
|
|
44845
45140
|
function resolveAutoFindingTaskItem(phrenPath, project) {
|
|
44846
45141
|
const projectDir = safeProjectPath(phrenPath, project);
|
|
44847
45142
|
if (!projectDir) return void 0;
|
|
44848
45143
|
const taskPath = resolveTaskFilePath(phrenPath, project);
|
|
44849
|
-
const active = parseTaskItems(taskPath ??
|
|
45144
|
+
const active = parseTaskItems(taskPath ?? path65.join(projectDir, "tasks.md")).filter(
|
|
44850
45145
|
(item) => item.section === "Active" && item.stableId
|
|
44851
45146
|
);
|
|
44852
45147
|
if (active.length === 1) return active[0].stableId;
|
|
@@ -44886,7 +45181,7 @@ function buildFindingCitation(citationInput, nowIso, inferredRepo, headCommit) {
|
|
|
44886
45181
|
function resolveInferredCitationRepo(citationInput) {
|
|
44887
45182
|
if (citationInput?.repo) return citationInput.repo;
|
|
44888
45183
|
if (citationInput?.file) {
|
|
44889
|
-
const fileDir =
|
|
45184
|
+
const fileDir = path66.dirname(citationInput.file);
|
|
44890
45185
|
return getRepoRoot(fileDir);
|
|
44891
45186
|
}
|
|
44892
45187
|
return void 0;
|
|
@@ -45021,7 +45316,7 @@ function addFindingToFile(phrenPath, project, learning, citationInput, opts) {
|
|
|
45021
45316
|
if (!isValidProjectName(project)) return phrenErr(`Invalid project name: "${project}".`, PhrenError.INVALID_PROJECT_NAME);
|
|
45022
45317
|
const resolvedDir = storeAwareProjectPath(phrenPath, project);
|
|
45023
45318
|
if (!resolvedDir) return phrenErr(`Invalid project name: "${project}".`, PhrenError.INVALID_PROJECT_NAME);
|
|
45024
|
-
const learningsPath =
|
|
45319
|
+
const learningsPath = path66.join(resolvedDir, FINDINGS_FILENAME);
|
|
45025
45320
|
const nowIso = (opts?.now ?? /* @__PURE__ */ new Date()).toISOString();
|
|
45026
45321
|
const today = nowIso.slice(0, 10);
|
|
45027
45322
|
const resolvedCitationInputResult = resolveFindingCitationInput(phrenPath, project, citationInput);
|
|
@@ -45203,7 +45498,7 @@ var codeNoteSchema = external_exports.object({
|
|
|
45203
45498
|
// phone's spelling, accepted until 0.3.1.
|
|
45204
45499
|
name: external_exports.string().min(1).max(4600).optional(),
|
|
45205
45500
|
symbol: external_exports.string().min(1).max(4600).optional(),
|
|
45206
|
-
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("..")),
|
|
45207
45502
|
line: external_exports.number().int().positive(),
|
|
45208
45503
|
text: external_exports.string().trim().min(1).max(4500).refine((text4) => !/[\x00-\x08\x0b-\x1f\x7f]/.test(text4)),
|
|
45209
45504
|
target: external_exports.union([external_exports.object({ session: sessionId }).strict(), external_exports.object({ harness: external_exports.enum(["codex", "claude", "opencode"]) }).strict()]).optional()
|
|
@@ -45253,29 +45548,29 @@ init_utils_helpers();
|
|
|
45253
45548
|
init_protocol();
|
|
45254
45549
|
init_herdr();
|
|
45255
45550
|
init_transcripts();
|
|
45256
|
-
import { execFile as
|
|
45257
|
-
import { promisify as
|
|
45551
|
+
import { execFile as execFile13 } from "node:child_process";
|
|
45552
|
+
import { promisify as promisify12 } from "node:util";
|
|
45258
45553
|
import { realpathSync as realpathSync5 } from "node:fs";
|
|
45259
|
-
import { readdir as
|
|
45554
|
+
import { readdir as readdir13, readFile as readFile28, stat as stat19, mkdir as mkdir15 } from "node:fs/promises";
|
|
45260
45555
|
import { homedir as homedir17 } from "node:os";
|
|
45261
|
-
import
|
|
45556
|
+
import path72 from "node:path";
|
|
45262
45557
|
|
|
45263
45558
|
// src/core/project.ts
|
|
45264
45559
|
init_shared();
|
|
45265
|
-
import * as
|
|
45560
|
+
import * as path70 from "path";
|
|
45266
45561
|
|
|
45267
45562
|
// src/core/project-registry.ts
|
|
45268
45563
|
init_phren_paths();
|
|
45269
45564
|
import * as fs32 from "fs";
|
|
45270
|
-
import * as
|
|
45565
|
+
import * as path69 from "path";
|
|
45271
45566
|
|
|
45272
45567
|
// src/git-worktree.ts
|
|
45273
45568
|
import * as fs31 from "fs";
|
|
45274
|
-
import * as
|
|
45569
|
+
import * as path68 from "path";
|
|
45275
45570
|
var WORKTREE_CONTAINER_NAMES = /* @__PURE__ */ new Set(["worktrees", ".worktrees"]);
|
|
45276
|
-
var LINKED_WORKTREE_SEGMENT = `${
|
|
45571
|
+
var LINKED_WORKTREE_SEGMENT = `${path68.sep}.git${path68.sep}worktrees${path68.sep}`;
|
|
45277
45572
|
function resolveWorktreeParent(dir) {
|
|
45278
|
-
const resolved =
|
|
45573
|
+
const resolved = path68.resolve(dir);
|
|
45279
45574
|
const agentParent = parentFromAgentWorktreePath(resolved);
|
|
45280
45575
|
if (agentParent) return { repoRoot: agentParent, reason: "agent-worktree-dir" };
|
|
45281
45576
|
const linkedParent = parentFromLinkedWorktree(resolved);
|
|
@@ -45283,23 +45578,23 @@ function resolveWorktreeParent(dir) {
|
|
|
45283
45578
|
return null;
|
|
45284
45579
|
}
|
|
45285
45580
|
function parentFromAgentWorktreePath(resolved) {
|
|
45286
|
-
const segments = resolved.split(
|
|
45581
|
+
const segments = resolved.split(path68.sep);
|
|
45287
45582
|
for (let i = 1; i < segments.length; i++) {
|
|
45288
45583
|
if (!WORKTREE_CONTAINER_NAMES.has(segments[i])) continue;
|
|
45289
45584
|
let j = i - 1;
|
|
45290
45585
|
if (!segments[j]?.startsWith(".")) continue;
|
|
45291
45586
|
while (j >= 1 && segments[j].startsWith(".")) j--;
|
|
45292
45587
|
if (j < 1) continue;
|
|
45293
|
-
return segments.slice(0, j + 1).join(
|
|
45588
|
+
return segments.slice(0, j + 1).join(path68.sep) || path68.sep;
|
|
45294
45589
|
}
|
|
45295
45590
|
return null;
|
|
45296
45591
|
}
|
|
45297
45592
|
function parentFromLinkedWorktree(resolved) {
|
|
45298
45593
|
let current2 = resolved;
|
|
45299
45594
|
while (true) {
|
|
45300
|
-
const parent = repoRootFromGitFile(
|
|
45595
|
+
const parent = repoRootFromGitFile(path68.join(current2, ".git"));
|
|
45301
45596
|
if (parent) return parent;
|
|
45302
|
-
const next =
|
|
45597
|
+
const next = path68.dirname(current2);
|
|
45303
45598
|
if (next === current2) return null;
|
|
45304
45599
|
current2 = next;
|
|
45305
45600
|
}
|
|
@@ -45314,7 +45609,7 @@ function repoRootFromGitFile(gitPath) {
|
|
|
45314
45609
|
}
|
|
45315
45610
|
const match = raw.match(/^\s*gitdir:\s*(.+?)\s*$/m);
|
|
45316
45611
|
if (!match) return null;
|
|
45317
|
-
const gitDir =
|
|
45612
|
+
const gitDir = path68.resolve(path68.dirname(gitPath), match[1].replace(/[/\\]/g, path68.sep));
|
|
45318
45613
|
const idx = gitDir.indexOf(LINKED_WORKTREE_SEGMENT);
|
|
45319
45614
|
if (idx === -1) return null;
|
|
45320
45615
|
return gitDir.slice(0, idx);
|
|
@@ -45467,8 +45762,8 @@ function addTermCount(terms, rawText, weight = 1) {
|
|
|
45467
45762
|
}
|
|
45468
45763
|
function maybeReadUtf8(filePath, maxBytes = 256e3) {
|
|
45469
45764
|
try {
|
|
45470
|
-
const
|
|
45471
|
-
if (!
|
|
45765
|
+
const stat26 = fs32.statSync(filePath);
|
|
45766
|
+
if (!stat26.isFile() || stat26.size > maxBytes) return "";
|
|
45472
45767
|
return fs32.readFileSync(filePath, "utf8");
|
|
45473
45768
|
} catch {
|
|
45474
45769
|
return "";
|
|
@@ -45527,7 +45822,7 @@ function scoreTopicsFromTerms(domain2, terms, docsText) {
|
|
|
45527
45822
|
return topics;
|
|
45528
45823
|
}
|
|
45529
45824
|
function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
|
|
45530
|
-
const resolvedRoot =
|
|
45825
|
+
const resolvedRoot = path69.resolve(repoRoot);
|
|
45531
45826
|
if (!fs32.existsSync(resolvedRoot)) return null;
|
|
45532
45827
|
const signal = {
|
|
45533
45828
|
domainScores: { software: 0, music: 0, game: 0, research: 0, writing: 0, creative: 0, other: 0 },
|
|
@@ -45538,7 +45833,7 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
|
|
|
45538
45833
|
usefulSignals: 0
|
|
45539
45834
|
};
|
|
45540
45835
|
const skipDirs = /* @__PURE__ */ new Set([".git", ".phren", "node_modules", "dist", "build", "coverage", ".next", ".turbo", "target"]);
|
|
45541
|
-
const packageJsonPath =
|
|
45836
|
+
const packageJsonPath = path69.join(resolvedRoot, "package.json");
|
|
45542
45837
|
if (fs32.existsSync(packageJsonPath)) {
|
|
45543
45838
|
signal.usefulSignals++;
|
|
45544
45839
|
addDomainScores(signal.domainScores, DOMAIN_CONFIG_HINTS["package.json"]);
|
|
@@ -45568,33 +45863,33 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
|
|
|
45568
45863
|
debugLog(`inferInitScaffoldFromRepo package.json parse failed: ${errorMessage(err)}`);
|
|
45569
45864
|
}
|
|
45570
45865
|
}
|
|
45571
|
-
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)));
|
|
45572
45867
|
for (const configName of topLevelConfigs) {
|
|
45573
45868
|
signal.usefulSignals++;
|
|
45574
45869
|
const configScore = DOMAIN_CONFIG_HINTS[configName];
|
|
45575
45870
|
if (configScore) addDomainScores(signal.domainScores, configScore);
|
|
45576
45871
|
}
|
|
45577
45872
|
const readmeCandidates = [
|
|
45578
|
-
|
|
45579
|
-
|
|
45873
|
+
path69.join(resolvedRoot, "README.md"),
|
|
45874
|
+
path69.join(resolvedRoot, "readme.md")
|
|
45580
45875
|
];
|
|
45581
45876
|
for (const readmePath of readmeCandidates) {
|
|
45582
45877
|
if (!fs32.existsSync(readmePath)) continue;
|
|
45583
45878
|
const content = maybeReadUtf8(readmePath);
|
|
45584
45879
|
if (!content) continue;
|
|
45585
45880
|
signal.usefulSignals++;
|
|
45586
|
-
signal.referenceHints.push(
|
|
45881
|
+
signal.referenceHints.push(path69.relative(resolvedRoot, readmePath));
|
|
45587
45882
|
addTermCount(signal.terms, content, 2);
|
|
45588
45883
|
signal.docsText += ` ${content.toLowerCase()}`;
|
|
45589
45884
|
break;
|
|
45590
45885
|
}
|
|
45591
|
-
const docsDir =
|
|
45886
|
+
const docsDir = path69.join(resolvedRoot, "docs");
|
|
45592
45887
|
if (fs32.existsSync(docsDir) && fs32.statSync(docsDir).isDirectory()) {
|
|
45593
45888
|
signal.referenceHints.push("docs/");
|
|
45594
45889
|
for (const entry of fs32.readdirSync(docsDir, { withFileTypes: true })) {
|
|
45595
45890
|
if (!entry.isFile()) continue;
|
|
45596
45891
|
if (!/\.(md|txt|rst)$/i.test(entry.name)) continue;
|
|
45597
|
-
const docsContent = maybeReadUtf8(
|
|
45892
|
+
const docsContent = maybeReadUtf8(path69.join(docsDir, entry.name));
|
|
45598
45893
|
if (!docsContent) continue;
|
|
45599
45894
|
signal.usefulSignals++;
|
|
45600
45895
|
addTermCount(signal.terms, docsContent, 1);
|
|
@@ -45602,7 +45897,7 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
|
|
|
45602
45897
|
}
|
|
45603
45898
|
}
|
|
45604
45899
|
for (const folderName of ["reference", "specs", "design", "architecture", "src", "packages", "apps"]) {
|
|
45605
|
-
const fullPath =
|
|
45900
|
+
const fullPath = path69.join(resolvedRoot, folderName);
|
|
45606
45901
|
if (fs32.existsSync(fullPath)) {
|
|
45607
45902
|
signal.referenceHints.push(`${folderName}/`);
|
|
45608
45903
|
}
|
|
@@ -45613,14 +45908,14 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
|
|
|
45613
45908
|
if (scannedFiles >= maxFiles) return;
|
|
45614
45909
|
for (const entry of fs32.readdirSync(dir, { withFileTypes: true })) {
|
|
45615
45910
|
if (scannedFiles >= maxFiles) return;
|
|
45616
|
-
const fullPath =
|
|
45911
|
+
const fullPath = path69.join(dir, entry.name);
|
|
45617
45912
|
if (entry.isDirectory()) {
|
|
45618
45913
|
if (skipDirs.has(entry.name)) continue;
|
|
45619
45914
|
walk(fullPath);
|
|
45620
45915
|
continue;
|
|
45621
45916
|
}
|
|
45622
45917
|
scannedFiles++;
|
|
45623
|
-
const ext =
|
|
45918
|
+
const ext = path69.extname(entry.name).toLowerCase();
|
|
45624
45919
|
if (!ext) continue;
|
|
45625
45920
|
const extScore = EXTENSION_DOMAIN_HINTS[ext];
|
|
45626
45921
|
if (extScore) {
|
|
@@ -45794,7 +46089,7 @@ function findExistingProjectForSource(phrenPath, sourceRoot, derivedName) {
|
|
|
45794
46089
|
return null;
|
|
45795
46090
|
}
|
|
45796
46091
|
};
|
|
45797
|
-
const resolvedSource =
|
|
46092
|
+
const resolvedSource = path69.resolve(sourceRoot);
|
|
45798
46093
|
for (const project of candidates) {
|
|
45799
46094
|
if (sourceOf(project) === resolvedSource) return project;
|
|
45800
46095
|
}
|
|
@@ -45808,7 +46103,7 @@ function findExistingProjectForSource(phrenPath, sourceRoot, derivedName) {
|
|
|
45808
46103
|
function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
|
|
45809
46104
|
const profile = typeof opts === "string" ? opts : opts.profile;
|
|
45810
46105
|
const profilePhrenPath = typeof opts === "string" ? phrenPath : opts.profilePhrenPath ?? phrenPath;
|
|
45811
|
-
const resolvedPath =
|
|
46106
|
+
const resolvedPath = path69.resolve(projectPath);
|
|
45812
46107
|
if (!fs32.existsSync(resolvedPath)) {
|
|
45813
46108
|
throw new Error(`Path does not exist: ${resolvedPath}`);
|
|
45814
46109
|
}
|
|
@@ -45819,17 +46114,17 @@ function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
|
|
|
45819
46114
|
if (worktreeRepoRoot) {
|
|
45820
46115
|
debugLog(`bootstrapFromExisting: ${resolvedPath} is a ${worktree.reason}; attributing to ${worktreeRepoRoot}`);
|
|
45821
46116
|
}
|
|
45822
|
-
const sourceRoot = isProjectLocal ?
|
|
46117
|
+
const sourceRoot = isProjectLocal ? path69.resolve(manifest.workspaceRoot || resolvedPath) : worktreeRepoRoot ?? resolvedPath;
|
|
45823
46118
|
if (isProjectLocal) {
|
|
45824
|
-
const matchesWorkspace = resolvedPath === sourceRoot || resolvedPath.startsWith(sourceRoot +
|
|
46119
|
+
const matchesWorkspace = resolvedPath === sourceRoot || resolvedPath.startsWith(sourceRoot + path69.sep);
|
|
45825
46120
|
if (!matchesWorkspace) {
|
|
45826
46121
|
throw new Error(`Project-local phren can only enroll the owning workspace: ${sourceRoot}`);
|
|
45827
46122
|
}
|
|
45828
46123
|
}
|
|
45829
46124
|
let claudeMdPath = null;
|
|
45830
46125
|
const candidates = [
|
|
45831
|
-
|
|
45832
|
-
|
|
46126
|
+
path69.join(sourceRoot, "AGENTS.md"),
|
|
46127
|
+
path69.join(sourceRoot, ".claude", "CLAUDE.md")
|
|
45833
46128
|
];
|
|
45834
46129
|
for (const c of candidates) {
|
|
45835
46130
|
if (fs32.existsSync(c)) {
|
|
@@ -45849,12 +46144,12 @@ function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
|
|
|
45849
46144
|
`Project "${existingProject}" already exists with different casing. Refusing to bootstrap "${projectName2}" because it would split the same project on case-sensitive filesystems.`
|
|
45850
46145
|
);
|
|
45851
46146
|
}
|
|
45852
|
-
const projDir =
|
|
46147
|
+
const projDir = path69.join(phrenPath, projectName2);
|
|
45853
46148
|
fs32.mkdirSync(projDir, { recursive: true });
|
|
45854
46149
|
const inferredScaffold = inferInitScaffoldFromRepo(sourceRoot);
|
|
45855
46150
|
const existingConfig = readProjectConfig(phrenPath, projectName2);
|
|
45856
46151
|
const ownership = typeof opts === "string" ? parseProjectOwnershipMode(existingConfig.ownership) ?? getProjectOwnershipDefault(phrenPath) : opts.ownership ?? parseProjectOwnershipMode(existingConfig.ownership) ?? getProjectOwnershipDefault(phrenPath);
|
|
45857
|
-
const claudePath =
|
|
46152
|
+
const claudePath = path69.join(projDir, "AGENTS.md");
|
|
45858
46153
|
if (ownership !== "repo-managed") {
|
|
45859
46154
|
if (claudeContent) {
|
|
45860
46155
|
if (!fs32.existsSync(claudePath)) {
|
|
@@ -45889,7 +46184,7 @@ function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
|
|
|
45889
46184
|
}
|
|
45890
46185
|
}
|
|
45891
46186
|
const sourceInfo = claudeMdPath ? `**Source AGENTS.md:** ${claudeMdPath}` : `**Source:** ${sourceRoot}`;
|
|
45892
|
-
const summaryPath =
|
|
46187
|
+
const summaryPath = path69.join(projDir, "summary.md");
|
|
45893
46188
|
if (!fs32.existsSync(summaryPath)) {
|
|
45894
46189
|
atomicWriteText(
|
|
45895
46190
|
summaryPath,
|
|
@@ -45902,18 +46197,18 @@ ${summaryLines.length > 1 ? summaryLines.slice(1).join("\n") : ""}
|
|
|
45902
46197
|
`
|
|
45903
46198
|
);
|
|
45904
46199
|
}
|
|
45905
|
-
if (!fs32.existsSync(
|
|
46200
|
+
if (!fs32.existsSync(path69.join(projDir, FINDINGS_FILENAME))) {
|
|
45906
46201
|
atomicWriteText(
|
|
45907
|
-
|
|
46202
|
+
path69.join(projDir, FINDINGS_FILENAME),
|
|
45908
46203
|
`# ${projectName2} FINDINGS
|
|
45909
46204
|
|
|
45910
46205
|
<!-- Bootstrapped from ${sourceRoot} -->
|
|
45911
46206
|
`
|
|
45912
46207
|
);
|
|
45913
46208
|
}
|
|
45914
|
-
if (moduleEnabled(phrenPath, "tasks") && !fs32.existsSync(
|
|
46209
|
+
if (moduleEnabled(phrenPath, "tasks") && !fs32.existsSync(path69.join(projDir, TASKS_FILENAME))) {
|
|
45915
46210
|
atomicWriteText(
|
|
45916
|
-
|
|
46211
|
+
path69.join(projDir, TASKS_FILENAME),
|
|
45917
46212
|
`# ${projectName2} tasks
|
|
45918
46213
|
|
|
45919
46214
|
## Active
|
|
@@ -45924,11 +46219,11 @@ ${summaryLines.length > 1 ? summaryLines.slice(1).join("\n") : ""}
|
|
|
45924
46219
|
`
|
|
45925
46220
|
);
|
|
45926
46221
|
}
|
|
45927
|
-
if (!fs32.existsSync(
|
|
46222
|
+
if (!fs32.existsSync(path69.join(projDir, "topic-config.json"))) {
|
|
45928
46223
|
const inferredDomain = normalizeBuiltinTopicDomain(inferredScaffold?.domain ?? "software");
|
|
45929
46224
|
const inferredTopics = inferredScaffold?.topics?.length ? inferredScaffold.topics : getBuiltinTopicConfig(inferredDomain);
|
|
45930
46225
|
atomicWriteText(
|
|
45931
|
-
|
|
46226
|
+
path69.join(projDir, "topic-config.json"),
|
|
45932
46227
|
JSON.stringify({ version: 1, domain: inferredDomain, topics: inferredTopics }, null, 2) + "\n"
|
|
45933
46228
|
);
|
|
45934
46229
|
}
|
|
@@ -45960,10 +46255,10 @@ function addProjectFromPath(phrenPath, targetPath, requestedProfile, ownership,
|
|
|
45960
46255
|
if (!activeProfile.ok) return activeProfile;
|
|
45961
46256
|
const writePhrenPath = options.writeToPath ?? phrenPath;
|
|
45962
46257
|
const manifest = readRootManifest(phrenPath);
|
|
45963
|
-
const resolvedPath =
|
|
46258
|
+
const resolvedPath = path70.resolve(targetPath);
|
|
45964
46259
|
if (manifest?.installMode === "project-local") {
|
|
45965
|
-
const workspaceRoot =
|
|
45966
|
-
const matchesWorkspace = resolvedPath === workspaceRoot || resolvedPath.startsWith(workspaceRoot +
|
|
46260
|
+
const workspaceRoot = path70.resolve(manifest.workspaceRoot || "");
|
|
46261
|
+
const matchesWorkspace = resolvedPath === workspaceRoot || resolvedPath.startsWith(workspaceRoot + path70.sep);
|
|
45967
46262
|
if (!matchesWorkspace) {
|
|
45968
46263
|
return phrenErr(`Project-local phren can only add the owning workspace: ${workspaceRoot}`);
|
|
45969
46264
|
}
|
|
@@ -45981,9 +46276,9 @@ function addProjectFromPath(phrenPath, targetPath, requestedProfile, ownership,
|
|
|
45981
46276
|
ownership: added.ownership,
|
|
45982
46277
|
files: {
|
|
45983
46278
|
claude: added.claudePath,
|
|
45984
|
-
summary:
|
|
45985
|
-
findings:
|
|
45986
|
-
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)
|
|
45987
46282
|
}
|
|
45988
46283
|
});
|
|
45989
46284
|
}
|
|
@@ -46009,7 +46304,7 @@ import { execFileSync as execFileSync6, spawnSync as spawnSync2 } from "child_pr
|
|
|
46009
46304
|
import * as crypto9 from "crypto";
|
|
46010
46305
|
import * as fs33 from "fs";
|
|
46011
46306
|
import * as os3 from "os";
|
|
46012
|
-
import * as
|
|
46307
|
+
import * as path71 from "path";
|
|
46013
46308
|
|
|
46014
46309
|
// src/content/summarize.ts
|
|
46015
46310
|
init_phren_dotenv();
|
|
@@ -46170,7 +46465,7 @@ function mergeTasksByBid(base, ours, theirs) {
|
|
|
46170
46465
|
// src/sync/conflict-resolve.ts
|
|
46171
46466
|
function conflictStrategy(relFile) {
|
|
46172
46467
|
const file2 = relFile.replace(/\\/g, "/");
|
|
46173
|
-
const name =
|
|
46468
|
+
const name = path71.posix.basename(file2).toLowerCase();
|
|
46174
46469
|
if (isTaskFileName(name)) return "tasks";
|
|
46175
46470
|
if (name === "findings.md") return "findings";
|
|
46176
46471
|
if (/^\.config\/task-archive\/[^/]+\.md$/i.test(file2)) return "archive";
|
|
@@ -46205,9 +46500,9 @@ function splitBlock(content, start, end) {
|
|
|
46205
46500
|
function mergeText(base, ours, theirs) {
|
|
46206
46501
|
if (ours === theirs || ours === base) return theirs;
|
|
46207
46502
|
if (theirs === base) return ours;
|
|
46208
|
-
const dir = fs33.mkdtempSync(
|
|
46503
|
+
const dir = fs33.mkdtempSync(path71.join(os3.tmpdir(), "phren-merge-"));
|
|
46209
46504
|
try {
|
|
46210
|
-
const [o, b, t] = ["ours", "base", "theirs"].map((name) =>
|
|
46505
|
+
const [o, b, t] = ["ours", "base", "theirs"].map((name) => path71.join(dir, name));
|
|
46211
46506
|
fs33.writeFileSync(o, ours);
|
|
46212
46507
|
fs33.writeFileSync(b, base);
|
|
46213
46508
|
fs33.writeFileSync(t, theirs);
|
|
@@ -46220,9 +46515,9 @@ function mergeText(base, ours, theirs) {
|
|
|
46220
46515
|
function unionText(base, ours, theirs) {
|
|
46221
46516
|
const clean2 = mergeText(base, ours, theirs);
|
|
46222
46517
|
if (clean2 !== null) return clean2;
|
|
46223
|
-
const dir = fs33.mkdtempSync(
|
|
46518
|
+
const dir = fs33.mkdtempSync(path71.join(os3.tmpdir(), "phren-merge-"));
|
|
46224
46519
|
try {
|
|
46225
|
-
const [o, b, t] = ["ours", "base", "theirs"].map((name) =>
|
|
46520
|
+
const [o, b, t] = ["ours", "base", "theirs"].map((name) => path71.join(dir, name));
|
|
46226
46521
|
fs33.writeFileSync(o, ours);
|
|
46227
46522
|
fs33.writeFileSync(b, base);
|
|
46228
46523
|
fs33.writeFileSync(t, theirs);
|
|
@@ -46282,7 +46577,7 @@ function resolveStoreConflicts(cwd) {
|
|
|
46282
46577
|
const base = stage(cwd, 1, relFile) ?? "";
|
|
46283
46578
|
const ours = stage(cwd, 2, relFile);
|
|
46284
46579
|
const theirs = stage(cwd, 3, relFile);
|
|
46285
|
-
const fullPath =
|
|
46580
|
+
const fullPath = path71.join(cwd, relFile);
|
|
46286
46581
|
if (ours === null && theirs === null) {
|
|
46287
46582
|
unresolved.push(relFile);
|
|
46288
46583
|
continue;
|
|
@@ -46293,7 +46588,7 @@ function resolveStoreConflicts(cwd) {
|
|
|
46293
46588
|
continue;
|
|
46294
46589
|
}
|
|
46295
46590
|
const tmp = `${fullPath}.tmp-${crypto9.randomUUID()}`;
|
|
46296
|
-
fs33.mkdirSync(
|
|
46591
|
+
fs33.mkdirSync(path71.dirname(fullPath), { recursive: true });
|
|
46297
46592
|
fs33.writeFileSync(tmp, merged);
|
|
46298
46593
|
fs33.renameSync(tmp, fullPath);
|
|
46299
46594
|
git4(cwd, ["add", "--", relFile]);
|
|
@@ -46560,7 +46855,7 @@ async function runBestEffortGit(args, cwd) {
|
|
|
46560
46855
|
// src/bridge/enroll.ts
|
|
46561
46856
|
init_metrics();
|
|
46562
46857
|
init_machine_identity();
|
|
46563
|
-
var
|
|
46858
|
+
var exec12 = promisify12(execFile13);
|
|
46564
46859
|
var runEnrollStoreGit = async (cwd, args) => {
|
|
46565
46860
|
const result = await runBestEffortGit(args, cwd);
|
|
46566
46861
|
return { ok: result.ok, output: result.output ?? "", error: result.error };
|
|
@@ -46573,7 +46868,7 @@ function repoName(url2) {
|
|
|
46573
46868
|
}
|
|
46574
46869
|
async function isRepository(directory) {
|
|
46575
46870
|
try {
|
|
46576
|
-
await
|
|
46871
|
+
await stat19(path72.join(directory, ".git"));
|
|
46577
46872
|
return true;
|
|
46578
46873
|
} catch {
|
|
46579
46874
|
return false;
|
|
@@ -46584,7 +46879,7 @@ async function registeredSources(env) {
|
|
|
46584
46879
|
const paths = /* @__PURE__ */ new Set(), names = /* @__PURE__ */ new Set();
|
|
46585
46880
|
let entries2 = [];
|
|
46586
46881
|
try {
|
|
46587
|
-
entries2 = (await
|
|
46882
|
+
entries2 = (await readdir13(store, { withFileTypes: true })).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => e.name);
|
|
46588
46883
|
} catch {
|
|
46589
46884
|
return { paths, names };
|
|
46590
46885
|
}
|
|
@@ -46593,7 +46888,7 @@ async function registeredSources(env) {
|
|
|
46593
46888
|
const source = readProjectConfig(store, project).sourcePath;
|
|
46594
46889
|
if (typeof source === "string" && source) {
|
|
46595
46890
|
try {
|
|
46596
|
-
paths.add(realpathSync5.native(
|
|
46891
|
+
paths.add(realpathSync5.native(path72.resolve(source)));
|
|
46597
46892
|
} catch {
|
|
46598
46893
|
}
|
|
46599
46894
|
}
|
|
@@ -46605,9 +46900,9 @@ async function candidateRepos(activity, env = process.env) {
|
|
|
46605
46900
|
const found = [];
|
|
46606
46901
|
const seen = /* @__PURE__ */ new Set();
|
|
46607
46902
|
const offer = async (directory, source, lastSeen) => {
|
|
46608
|
-
let dir =
|
|
46903
|
+
let dir = path72.resolve(directory);
|
|
46609
46904
|
try {
|
|
46610
|
-
if (!(await
|
|
46905
|
+
if (!(await stat19(dir)).isDirectory()) return;
|
|
46611
46906
|
dir = realpathSync5.native(dir);
|
|
46612
46907
|
} catch {
|
|
46613
46908
|
return;
|
|
@@ -46619,39 +46914,39 @@ async function candidateRepos(activity, env = process.env) {
|
|
|
46619
46914
|
};
|
|
46620
46915
|
const toplevel = async (directory) => {
|
|
46621
46916
|
let existing = directory;
|
|
46622
|
-
while (!await
|
|
46623
|
-
const parent =
|
|
46917
|
+
while (!await stat19(existing).catch(() => void 0)) {
|
|
46918
|
+
const parent = path72.dirname(existing);
|
|
46624
46919
|
if (parent === existing) return void 0;
|
|
46625
46920
|
existing = parent;
|
|
46626
46921
|
}
|
|
46627
46922
|
try {
|
|
46628
46923
|
countGit("enroll");
|
|
46629
|
-
return (await
|
|
46924
|
+
return (await exec12("git", ["-C", existing, "rev-parse", "--show-toplevel"], { env: nonInteractiveGitEnv(), timeout: 5e3 })).stdout.trim() || void 0;
|
|
46630
46925
|
} catch {
|
|
46631
46926
|
return void 0;
|
|
46632
46927
|
}
|
|
46633
46928
|
};
|
|
46634
46929
|
for (const event of [...activity].reverse()) {
|
|
46635
46930
|
const directory = typeof event.directory === "string" ? event.directory : void 0;
|
|
46636
|
-
if (!directory || !
|
|
46931
|
+
if (!directory || !path72.isAbsolute(directory)) continue;
|
|
46637
46932
|
const root = await toplevel(directory);
|
|
46638
46933
|
if (root) await offer(root, "activity", typeof event.at === "string" ? event.at : void 0);
|
|
46639
46934
|
}
|
|
46640
46935
|
try {
|
|
46641
|
-
const session = JSON.parse(await
|
|
46936
|
+
const session = JSON.parse(await readFile28(path72.join(herdrRoot(), "session.json"), "utf8"));
|
|
46642
46937
|
for (const match of JSON.stringify(session).matchAll(/"cwd":\s*"((?:\\.|[^"\\])*)"/g)) {
|
|
46643
46938
|
const directory = JSON.parse(`"${match[1]}"`);
|
|
46644
|
-
if (!
|
|
46939
|
+
if (!path72.isAbsolute(directory)) continue;
|
|
46645
46940
|
const root = await toplevel(directory);
|
|
46646
46941
|
if (root) await offer(root, "herdr");
|
|
46647
46942
|
}
|
|
46648
46943
|
} catch {
|
|
46649
46944
|
}
|
|
46650
46945
|
const home = homedir17();
|
|
46651
|
-
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))]) {
|
|
46652
46947
|
let children = [];
|
|
46653
46948
|
try {
|
|
46654
|
-
children = (await
|
|
46949
|
+
children = (await readdir13(root, { withFileTypes: true })).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => path72.join(root, e.name));
|
|
46655
46950
|
} catch {
|
|
46656
46951
|
continue;
|
|
46657
46952
|
}
|
|
@@ -46661,13 +46956,13 @@ async function candidateRepos(activity, env = process.env) {
|
|
|
46661
46956
|
}
|
|
46662
46957
|
async function cloneRoot(env) {
|
|
46663
46958
|
const home = homedir17();
|
|
46664
|
-
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))]) {
|
|
46665
46960
|
try {
|
|
46666
|
-
if ((await
|
|
46961
|
+
if ((await stat19(root)).isDirectory()) return root;
|
|
46667
46962
|
} catch {
|
|
46668
46963
|
}
|
|
46669
46964
|
}
|
|
46670
|
-
const fallback =
|
|
46965
|
+
const fallback = path72.join(home, "Projects");
|
|
46671
46966
|
await mkdir15(fallback, { recursive: true });
|
|
46672
46967
|
return fallback;
|
|
46673
46968
|
}
|
|
@@ -46689,7 +46984,7 @@ async function publishStore(store, project) {
|
|
|
46689
46984
|
async function enrollProject(input2, env = process.env) {
|
|
46690
46985
|
const store = phrenStoreRoot(env);
|
|
46691
46986
|
try {
|
|
46692
|
-
if (!(await
|
|
46987
|
+
if (!(await stat19(path72.join(store, ".config"))).isDirectory()) throw new Error();
|
|
46693
46988
|
} catch {
|
|
46694
46989
|
throw new BridgeError(409, "phren is not set up on this computer. Run phren init there.");
|
|
46695
46990
|
}
|
|
@@ -46700,16 +46995,16 @@ async function enrollProject(input2, env = process.env) {
|
|
|
46700
46995
|
if (url2.length > 512 || !CLONE_URL.test(url2)) throw new BridgeError(400, "Enter a GitHub repository URL (https://github.com/owner/repo).");
|
|
46701
46996
|
const name = repoName(url2);
|
|
46702
46997
|
if (!name || name === "." || name === "..") throw new BridgeError(400, "That URL has no repository name.");
|
|
46703
|
-
directory =
|
|
46998
|
+
directory = path72.join(await cloneRoot(env), name);
|
|
46704
46999
|
try {
|
|
46705
|
-
await
|
|
47000
|
+
await stat19(directory);
|
|
46706
47001
|
throw new BridgeError(409, `${directory} already exists on this computer. Add that folder instead.`);
|
|
46707
47002
|
} catch (error62) {
|
|
46708
47003
|
if (error62 instanceof BridgeError) throw error62;
|
|
46709
47004
|
}
|
|
46710
47005
|
try {
|
|
46711
47006
|
countGit("enroll");
|
|
46712
|
-
await
|
|
47007
|
+
await exec12("git", ["clone", "--", url2, directory], { timeout: 18e4, maxBuffer: 4194304, env: nonInteractiveGitEnv(env) });
|
|
46713
47008
|
} catch (error62) {
|
|
46714
47009
|
const detail = error62 instanceof Error && "stderr" in error62 ? String(error62.stderr ?? "").trim().split("\n").pop() : void 0;
|
|
46715
47010
|
throw new BridgeError(502, `git clone failed${detail ? `: ${detail}` : ""}.`);
|
|
@@ -46717,10 +47012,10 @@ async function enrollProject(input2, env = process.env) {
|
|
|
46717
47012
|
cloned = true;
|
|
46718
47013
|
} else if (typeof input2.directory === "string" && input2.directory) {
|
|
46719
47014
|
const raw = input2.directory;
|
|
46720
|
-
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.");
|
|
46721
47016
|
try {
|
|
46722
47017
|
directory = realpathSync5.native(raw);
|
|
46723
|
-
if (!(await
|
|
47018
|
+
if (!(await stat19(directory)).isDirectory()) throw new Error();
|
|
46724
47019
|
} catch {
|
|
46725
47020
|
throw new BridgeError(404, "That folder is not on this computer.");
|
|
46726
47021
|
}
|
|
@@ -46733,29 +47028,29 @@ async function enrollProject(input2, env = process.env) {
|
|
|
46733
47028
|
// src/bridge/files.ts
|
|
46734
47029
|
init_protocol();
|
|
46735
47030
|
import { constants as constants4 } from "node:fs";
|
|
46736
|
-
import { lstat as lstat15, open as open13, readdir as
|
|
46737
|
-
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";
|
|
46738
47033
|
var MAX_BYTES = 2097152;
|
|
46739
47034
|
async function browseFiles(root, relative3) {
|
|
46740
|
-
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")) {
|
|
46741
47036
|
throw new BridgeError(400, "Invalid repository path.");
|
|
46742
47037
|
}
|
|
46743
|
-
const base = await
|
|
47038
|
+
const base = await realpath11(root);
|
|
46744
47039
|
let file2 = base;
|
|
46745
47040
|
for (const part of relative3.split("/").filter((part2) => part2 && part2 !== ".")) {
|
|
46746
|
-
file2 =
|
|
47041
|
+
file2 = path73.join(file2, part);
|
|
46747
47042
|
if ((await lstat15(file2)).isSymbolicLink()) throw new BridgeError(403, "Symbolic links cannot be browsed.");
|
|
46748
47043
|
}
|
|
46749
|
-
const resolved = await
|
|
46750
|
-
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.");
|
|
46751
47046
|
const metadata = await lstat15(resolved);
|
|
46752
47047
|
if (metadata.isDirectory()) {
|
|
46753
|
-
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));
|
|
46754
47049
|
return {
|
|
46755
47050
|
path: relative3,
|
|
46756
47051
|
kind: "directory",
|
|
46757
47052
|
truncated: entries2.length > 500,
|
|
46758
|
-
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" }))
|
|
46759
47054
|
};
|
|
46760
47055
|
}
|
|
46761
47056
|
if (!metadata.isFile()) throw new BridgeError(400, "Only regular files can be viewed.");
|
|
@@ -46781,8 +47076,8 @@ async function browseFiles(root, relative3) {
|
|
|
46781
47076
|
// src/bridge/file-range.ts
|
|
46782
47077
|
init_protocol();
|
|
46783
47078
|
import { constants as constants5 } from "node:fs";
|
|
46784
|
-
import { lstat as lstat16, open as open14, realpath as
|
|
46785
|
-
import
|
|
47079
|
+
import { lstat as lstat16, open as open14, realpath as realpath12 } from "node:fs/promises";
|
|
47080
|
+
import path74 from "node:path";
|
|
46786
47081
|
var MAX_FILE_RANGE = 4 * 1024 * 1024;
|
|
46787
47082
|
var types = {
|
|
46788
47083
|
mp4: "video/mp4",
|
|
@@ -46819,11 +47114,11 @@ var types = {
|
|
|
46819
47114
|
xml: "text/xml"
|
|
46820
47115
|
};
|
|
46821
47116
|
function fileContentType(file2) {
|
|
46822
|
-
const ext =
|
|
47117
|
+
const ext = path74.extname(file2).slice(1).toLowerCase();
|
|
46823
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");
|
|
46824
47119
|
}
|
|
46825
|
-
function version2(
|
|
46826
|
-
return `${
|
|
47120
|
+
function version2(stat26) {
|
|
47121
|
+
return `${stat26.dev}:${stat26.ino}:${stat26.size}:${stat26.mtimeMs}:${stat26.ctimeMs}`;
|
|
46827
47122
|
}
|
|
46828
47123
|
function rangeInteger(value2, fallback) {
|
|
46829
47124
|
if (value2 === null) return fallback;
|
|
@@ -46836,22 +47131,22 @@ async function readFileRange(root, requested, offset, length, expectedVersion) {
|
|
|
46836
47131
|
throw new BridgeError(400, "File ranges must be between 0 and 4 MiB.");
|
|
46837
47132
|
}
|
|
46838
47133
|
try {
|
|
46839
|
-
const base = await
|
|
46840
|
-
const relative3 =
|
|
46841
|
-
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.");
|
|
46842
47137
|
let file2 = base;
|
|
46843
|
-
for (const part of relative3.split(
|
|
46844
|
-
file2 =
|
|
47138
|
+
for (const part of relative3.split(path74.sep).filter((part2) => part2 && part2 !== ".")) {
|
|
47139
|
+
file2 = path74.join(file2, part);
|
|
46845
47140
|
if ((await lstat16(file2)).isSymbolicLink()) throw new BridgeError(403, "Symbolic links cannot be opened.");
|
|
46846
47141
|
}
|
|
46847
|
-
const resolved = await
|
|
46848
|
-
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.");
|
|
46849
47144
|
const metadata = await lstat16(resolved);
|
|
46850
47145
|
if (!metadata.isFile()) throw new BridgeError(400, "Only regular files can be opened.");
|
|
46851
47146
|
const handle = await open14(resolved, constants5.O_RDONLY | constants5.O_NOFOLLOW | constants5.O_NONBLOCK);
|
|
46852
47147
|
try {
|
|
46853
47148
|
const current2 = await handle.stat();
|
|
46854
|
-
if (!current2.isFile() || version2(current2) !== version2(metadata) || await
|
|
47149
|
+
if (!current2.isFile() || version2(current2) !== version2(metadata) || await realpath12(file2) !== resolved) {
|
|
46855
47150
|
throw new BridgeError(409, "The file changed. Open it again.");
|
|
46856
47151
|
}
|
|
46857
47152
|
const revision = version2(current2);
|
|
@@ -46887,12 +47182,12 @@ async function readFileRange(root, requested, offset, length, expectedVersion) {
|
|
|
46887
47182
|
// src/bridge/memory-store.ts
|
|
46888
47183
|
init_zod();
|
|
46889
47184
|
init_protocol();
|
|
46890
|
-
import { execFile as
|
|
47185
|
+
import { execFile as execFile14 } from "node:child_process";
|
|
46891
47186
|
import { createHash as createHash15 } from "node:crypto";
|
|
46892
|
-
import { lstat as lstat17, mkdir as mkdir16, readFile as
|
|
46893
|
-
import
|
|
46894
|
-
import { promisify as
|
|
46895
|
-
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);
|
|
46896
47191
|
var SHA = /^[0-9a-f]{40}$/;
|
|
46897
47192
|
var MAX_FILE = 4 * 1024 * 1024;
|
|
46898
47193
|
var queue = Promise.resolve();
|
|
@@ -46903,7 +47198,7 @@ function serialized(work) {
|
|
|
46903
47198
|
}
|
|
46904
47199
|
async function git5(store, args, env = {}) {
|
|
46905
47200
|
try {
|
|
46906
|
-
const { stdout } = await
|
|
47201
|
+
const { stdout } = await exec13("git", ["-C", store, ...args], {
|
|
46907
47202
|
env: { ...process.env, ...env, GIT_TERMINAL_PROMPT: "0" },
|
|
46908
47203
|
maxBuffer: 64 * 1024 * 1024,
|
|
46909
47204
|
timeout: 6e4
|
|
@@ -46918,12 +47213,12 @@ function blobSha(content) {
|
|
|
46918
47213
|
return createHash15("sha1").update(`blob ${content.length}\0`).update(content).digest("hex");
|
|
46919
47214
|
}
|
|
46920
47215
|
async function isRepository2(store) {
|
|
46921
|
-
return await lstat17(
|
|
47216
|
+
return await lstat17(path75.join(store, ".git")).catch(() => void 0) !== void 0;
|
|
46922
47217
|
}
|
|
46923
|
-
function storeHead(store, indexFile =
|
|
47218
|
+
function storeHead(store, indexFile = path75.join(bridgeRoot(), "store-snapshot.index")) {
|
|
46924
47219
|
return serialized(async () => {
|
|
46925
47220
|
if (!await isRepository2(store)) throw new BridgeError(409, "This computer's phren store is not a git repository. Run phren init.");
|
|
46926
|
-
await mkdir16(
|
|
47221
|
+
await mkdir16(path75.dirname(indexFile), { recursive: true, mode: 448 });
|
|
46927
47222
|
const env = { GIT_INDEX_FILE: indexFile };
|
|
46928
47223
|
if (!await lstat17(indexFile).catch(() => void 0)) {
|
|
46929
47224
|
const head = await git5(store, ["rev-parse", "--verify", "--quiet", "HEAD"]).catch(() => "");
|
|
@@ -46946,31 +47241,31 @@ async function storeTree(store, sha) {
|
|
|
46946
47241
|
async function storeBlob(store, sha) {
|
|
46947
47242
|
if (!SHA.test(sha)) throw new BridgeError(400, "Invalid blob sha.");
|
|
46948
47243
|
if ((await git5(store, ["cat-file", "-t", sha]).catch(() => "")).trim() !== "blob") throw new BridgeError(404, "Unknown blob.");
|
|
46949
|
-
const { stdout } = await
|
|
47244
|
+
const { stdout } = await exec13("git", ["-C", store, "cat-file", "blob", sha], { encoding: "buffer", maxBuffer: MAX_FILE * 4 });
|
|
46950
47245
|
return { sha, encoding: "base64", content: stdout.toString("base64") };
|
|
46951
47246
|
}
|
|
46952
47247
|
async function storeFile(store, relative3) {
|
|
46953
|
-
const normalized =
|
|
46954
|
-
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)) {
|
|
46955
47250
|
throw new BridgeError(400, "Invalid store path.");
|
|
46956
47251
|
}
|
|
46957
|
-
const root = await
|
|
46958
|
-
let parent =
|
|
47252
|
+
const root = await realpath13(store);
|
|
47253
|
+
let parent = path75.dirname(path75.join(root, normalized));
|
|
46959
47254
|
for (; ; ) {
|
|
46960
|
-
const real2 = await
|
|
47255
|
+
const real2 = await realpath13(parent).catch(() => void 0);
|
|
46961
47256
|
if (real2) {
|
|
46962
|
-
if (real2 !== root && !real2.startsWith(root +
|
|
47257
|
+
if (real2 !== root && !real2.startsWith(root + path75.sep)) throw new BridgeError(400, "Invalid store path.");
|
|
46963
47258
|
break;
|
|
46964
47259
|
}
|
|
46965
|
-
parent =
|
|
47260
|
+
parent = path75.dirname(parent);
|
|
46966
47261
|
}
|
|
46967
|
-
const file2 =
|
|
47262
|
+
const file2 = path75.join(root, normalized);
|
|
46968
47263
|
const info = await lstat17(file2).catch(() => void 0);
|
|
46969
47264
|
if (info && !info.isFile()) throw new BridgeError(400, "Invalid store path.");
|
|
46970
47265
|
return file2;
|
|
46971
47266
|
}
|
|
46972
47267
|
async function currentSha(file2) {
|
|
46973
|
-
const content = await
|
|
47268
|
+
const content = await readFile29(file2).catch((error62) => {
|
|
46974
47269
|
if (error62.code === "ENOENT") return null;
|
|
46975
47270
|
throw error62;
|
|
46976
47271
|
});
|
|
@@ -46985,7 +47280,7 @@ function putStoreFile(store, data) {
|
|
|
46985
47280
|
return serialized(async () => {
|
|
46986
47281
|
const file2 = await storeFile(store, input2.path);
|
|
46987
47282
|
if (await currentSha(file2) !== (input2.sha ?? null)) throw new BridgeError(409, `${input2.path} changed on this computer.`);
|
|
46988
|
-
await mkdir16(
|
|
47283
|
+
await mkdir16(path75.dirname(file2), { recursive: true });
|
|
46989
47284
|
const temporary = `${file2}.phren-${process.pid}-${Date.now()}`;
|
|
46990
47285
|
await writeFile8(temporary, content, { flag: "wx" });
|
|
46991
47286
|
await rename7(temporary, file2);
|
|
@@ -47017,17 +47312,17 @@ init_protocol();
|
|
|
47017
47312
|
|
|
47018
47313
|
// src/bridge/simulators.ts
|
|
47019
47314
|
init_protocol();
|
|
47020
|
-
import { execFile as
|
|
47021
|
-
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";
|
|
47022
47317
|
import { tmpdir as tmpdir3 } from "node:os";
|
|
47023
|
-
import
|
|
47318
|
+
import path76 from "node:path";
|
|
47024
47319
|
import { createHash as createHash16, randomUUID as randomUUID17 } from "node:crypto";
|
|
47025
|
-
import { promisify as
|
|
47026
|
-
var
|
|
47320
|
+
import { promisify as promisify14 } from "node:util";
|
|
47321
|
+
var exec14 = promisify14(execFile15);
|
|
47027
47322
|
var UDID = /^[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}$/i;
|
|
47028
47323
|
async function bootedSimulators() {
|
|
47029
47324
|
if (process.platform !== "darwin") return [];
|
|
47030
|
-
const { stdout } = await
|
|
47325
|
+
const { stdout } = await exec14("/usr/bin/xcrun", ["simctl", "list", "devices", "booted", "-j"], { timeout: 8e3, maxBuffer: 4194304 }).catch(() => ({ stdout: "{}" }));
|
|
47031
47326
|
let parsed = {};
|
|
47032
47327
|
try {
|
|
47033
47328
|
parsed = JSON.parse(stdout);
|
|
@@ -47048,10 +47343,10 @@ async function bootedSimulators() {
|
|
|
47048
47343
|
async function simulatorScreenshot(udid) {
|
|
47049
47344
|
if (!UDID.test(udid)) throw new BridgeError(400, "Invalid simulator identifier.");
|
|
47050
47345
|
if (process.platform !== "darwin") throw new BridgeError(404, "Simulators run on macOS only.");
|
|
47051
|
-
const file2 =
|
|
47346
|
+
const file2 = path76.join(tmpdir3(), `phren-sim-${randomUUID17()}.png`);
|
|
47052
47347
|
try {
|
|
47053
|
-
await
|
|
47054
|
-
return await
|
|
47348
|
+
await exec14("/usr/bin/xcrun", ["simctl", "io", udid, "screenshot", "--type=png", file2], { timeout: 15e3 });
|
|
47349
|
+
return await readFile30(file2);
|
|
47055
47350
|
} catch (error62) {
|
|
47056
47351
|
if (error62 instanceof BridgeError) throw error62;
|
|
47057
47352
|
throw new BridgeError(409, "Couldn't capture that simulator. Is it still booted?");
|
|
@@ -47067,22 +47362,22 @@ function helper() {
|
|
|
47067
47362
|
return building;
|
|
47068
47363
|
}
|
|
47069
47364
|
async function buildHelper() {
|
|
47070
|
-
const dir =
|
|
47071
|
-
const binary =
|
|
47072
|
-
const code = true ? '// Touches and keys for the iOS Simulator, without AppleScript: the window\n// is found through the Accessibility API and events are posted with CGEvent,\n// so one Accessibility grant for this helper is all macOS asks for.\n// Built on demand by Phren Hook with swiftc; see simulators.ts.\nimport ApplicationServices\nimport Cocoa\n\nfunc fail(_ code: Int32, _ message: String) -> Never { FileHandle.standardError.write((message + "\\n").data(using: .utf8)!); exit(code) }\n\nlet args = CommandLine.arguments\nguard args.count >= 3 else { fail(2, "usage: simtap <window-title-prefix> tap <fx> <fy> | key <keycode> [cmd] [shift] | type <text> | raise") }\nlet prefix = args[1], command = args[2]\n\nguard AXIsProcessTrusted() else { fail(3, "accessibility") }\nguard let app = NSRunningApplication.runningApplications(withBundleIdentifier: "com.apple.iphonesimulator").first else { fail(4, "Simulator is not running") }\nlet element = AXUIElementCreateApplication(app.processIdentifier)\nvar windowsRef: CFTypeRef?\nAXUIElementCopyAttributeValue(element, kAXWindowsAttribute as CFString, &windowsRef)\nlet windows = (windowsRef as? [AXUIElement]) ?? []\nvar target: AXUIElement?\nfor window in windows {\n var titleRef: CFTypeRef?\n AXUIElementCopyAttributeValue(window, kAXTitleAttribute as CFString, &titleRef)\n if let title = titleRef as? String, title.hasPrefix(prefix + " ") || title == prefix { target = window; break }\n}\nguard let window = target else { fail(5, "no window for \\(prefix)") }\n\nfunc frame(_ window: AXUIElement) -> CGRect {\n var posRef: CFTypeRef?, sizeRef: CFTypeRef?\n AXUIElementCopyAttributeValue(window, kAXPositionAttribute as CFString, &posRef)\n AXUIElementCopyAttributeValue(window, kAXSizeAttribute as CFString, &sizeRef)\n var pos = CGPoint.zero, size = CGSize.zero\n if let p = posRef { AXValueGetValue(p as! AXValue, .cgPoint, &pos) }\n if let s = sizeRef { AXValueGetValue(s as! AXValue, .cgSize, &size) }\n return CGRect(origin: pos, size: size)\n}\nfunc raise() {\n app.activate(options: [])\n AXUIElementPerformAction(window, kAXRaiseAction as CFString)\n usleep(120_000)\n}\nfunc post(_ event: CGEvent?) {\n guard NSWorkspace.shared.frontmostApplication?.processIdentifier == app.processIdentifier else { fail(6, "focus lost") }\n event?.postToPid(app.processIdentifier)\n usleep(40_000)\n}\n\nswitch command {\ncase "raise": raise()\ncase "tap":\n guard args.count >= 5, let fx = Double(args[3]), let fy = Double(args[4]) else { fail(2, "tap needs fx fy") }\n raise()\n let f = frame(window)\n // The device screen fills the window below its title bar.\n let titleBar: CGFloat = 28\n let point = CGPoint(x: f.origin.x + CGFloat(fx) * f.width, y: f.origin.y + titleBar + CGFloat(fy) * (f.height - titleBar))\n post(CGEvent(mouseEventSource: nil, mouseType: .mouseMoved, mouseCursorPosition: point, mouseButton: .left))\n post(CGEvent(mouseEventSource: nil, mouseType: .leftMouseDown, mouseCursorPosition: point, mouseButton: .left))\n post(CGEvent(mouseEventSource: nil, mouseType: .leftMouseUp, mouseCursorPosition: point, mouseButton: .left))\ncase "key":\n guard args.count >= 4, let code = UInt16(args[3]) else { fail(2, "key needs a keycode") }\n raise()\n var flags: CGEventFlags = []\n if args.contains("cmd") { flags.insert(.maskCommand) }\n if args.contains("shift") { flags.insert(.maskShift) }\n let down = CGEvent(keyboardEventSource: nil, virtualKey: code, keyDown: true), up = CGEvent(keyboardEventSource: nil, virtualKey: code, keyDown: false)\n down?.flags = flags; up?.flags = flags\n post(down); post(up)\ncase "type":\n guard args.count >= 4, !args[3].isEmpty, args[3].utf16.count <= 500 else { fail(2, "type needs at most 500 characters") }\n let submit = args.count == 5 && args[4] == "submit"\n guard args[3].unicodeScalars.allSatisfy({ scalar in\n (scalar.value >= 32 && scalar.value != 127) || (scalar.value == 10 && submit)\n }) else { fail(2, "invalid type controls; newline needs submit") }\n raise()\n for scalar in args[3].unicodeScalars {\n var chars = Array(String(scalar).utf16)\n let down = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: true), up = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: false)\n down?.keyboardSetUnicodeString(stringLength: chars.count, unicodeString: &chars)\n up?.keyboardSetUnicodeString(stringLength: chars.count, unicodeString: &chars)\n post(down); post(up)\n }\ndefault: fail(2, "unknown command \\(command)")\n}\n' : await
|
|
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");
|
|
47073
47368
|
const digest2 = createHash16("sha256").update(code).digest("hex");
|
|
47074
|
-
const saved = await
|
|
47075
|
-
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;
|
|
47076
47371
|
await mkdir17(dir, { recursive: true, mode: 448 });
|
|
47077
|
-
const temporary =
|
|
47372
|
+
const temporary = path76.join(dir, `simtap.${randomUUID17()}`), source = temporary + ".swift";
|
|
47078
47373
|
const sidecar = temporary + ".sha256";
|
|
47079
47374
|
try {
|
|
47080
47375
|
await writeFile9(source, code, { mode: 384, flag: "wx" });
|
|
47081
|
-
await
|
|
47376
|
+
await exec14("/usr/bin/swiftc", ["-O", "-o", temporary, source], { timeout: 18e4 }).catch(() => {
|
|
47082
47377
|
throw new BridgeError(409, "Couldn't build the simulator input helper (needs Xcode's swiftc).");
|
|
47083
47378
|
});
|
|
47084
47379
|
await chmod4(temporary, 448);
|
|
47085
|
-
const binarySha = createHash16("sha256").update(await
|
|
47380
|
+
const binarySha = createHash16("sha256").update(await readFile30(temporary)).digest("hex");
|
|
47086
47381
|
await writeFile9(sidecar, JSON.stringify({ sourceSha: digest2, binarySha }), { mode: 384, flag: "wx" });
|
|
47087
47382
|
await rename8(temporary, binary);
|
|
47088
47383
|
await rename8(sidecar, binary + ".sha256");
|
|
@@ -47100,11 +47395,11 @@ function simtap(name, ...args) {
|
|
|
47100
47395
|
}
|
|
47101
47396
|
async function executeSimtap(name, ...args) {
|
|
47102
47397
|
const binary = await helper();
|
|
47103
|
-
const saved = await
|
|
47104
|
-
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");
|
|
47105
47400
|
if (!saved || saved.binarySha !== binarySha) throw new BridgeError(409, "Simulator input helper integrity check failed.");
|
|
47106
47401
|
try {
|
|
47107
|
-
await
|
|
47402
|
+
await exec14(binary, [name, ...args], { timeout: 6e4 });
|
|
47108
47403
|
} catch (error62) {
|
|
47109
47404
|
const failure2 = error62;
|
|
47110
47405
|
const message = String(failure2?.stderr ?? failure2?.message ?? "");
|
|
@@ -47120,7 +47415,7 @@ async function simulatorAct(udid, request6) {
|
|
|
47120
47415
|
if (!UDID.test(udid)) throw new BridgeError(400, "Invalid simulator identifier.");
|
|
47121
47416
|
if (!["boot", "shutdown", "launch", "openurl", "home", "lock", "type", "tap", "screenshot-ready"].includes(request6.action)) throw new BridgeError(400, "Unknown simulator action.");
|
|
47122
47417
|
if (process.platform !== "darwin") throw new BridgeError(404, "Simulators run on macOS only.");
|
|
47123
|
-
const simctl = (...args) =>
|
|
47418
|
+
const simctl = (...args) => exec14("/usr/bin/xcrun", ["simctl", ...args], { timeout: 3e4 }).catch(() => {
|
|
47124
47419
|
throw new BridgeError(409, `simctl ${args[0]} failed for that simulator.`);
|
|
47125
47420
|
});
|
|
47126
47421
|
switch (request6.action) {
|
|
@@ -47169,7 +47464,7 @@ async function deviceName(udid) {
|
|
|
47169
47464
|
async function simulatorApps(udid) {
|
|
47170
47465
|
if (!UDID.test(udid)) throw new BridgeError(400, "Invalid simulator identifier.");
|
|
47171
47466
|
if (process.platform !== "darwin") return [];
|
|
47172
|
-
const { stdout } = await
|
|
47467
|
+
const { stdout } = await exec14("/usr/bin/xcrun", ["simctl", "listapps", udid], { timeout: 15e3, maxBuffer: 4194304 }).catch(() => ({ stdout: "" }));
|
|
47173
47468
|
const apps = [];
|
|
47174
47469
|
const blocks = stdout.split(/\n(?=\s{4}"[^"]+" =\s+\{)/);
|
|
47175
47470
|
for (const block of blocks) {
|
|
@@ -47185,8 +47480,8 @@ init_transcripts();
|
|
|
47185
47480
|
|
|
47186
47481
|
// src/bridge/uploads.ts
|
|
47187
47482
|
init_protocol();
|
|
47188
|
-
import { mkdir as mkdir18, readdir as
|
|
47189
|
-
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";
|
|
47190
47485
|
import { randomUUID as randomUUID18 } from "node:crypto";
|
|
47191
47486
|
function imageBytes(bytes) {
|
|
47192
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";
|
|
@@ -47199,24 +47494,24 @@ async function saveUpload(session, name, bytes) {
|
|
|
47199
47494
|
let saved = "";
|
|
47200
47495
|
const task = uploadQueue.catch(() => {
|
|
47201
47496
|
}).then(async () => {
|
|
47202
|
-
const root =
|
|
47497
|
+
const root = path77.join(bridgeRoot(), "uploads");
|
|
47203
47498
|
await mkdir18(root, { recursive: true, mode: 448 });
|
|
47204
47499
|
let used = 0;
|
|
47205
|
-
const directories = await
|
|
47500
|
+
const directories = await readdir15(root, { withFileTypes: true });
|
|
47206
47501
|
for (const dir of directories) {
|
|
47207
47502
|
if (!dir.isDirectory()) continue;
|
|
47208
|
-
const folder2 =
|
|
47209
|
-
for (const entry of await
|
|
47503
|
+
const folder2 = path77.join(root, dir.name);
|
|
47504
|
+
for (const entry of await readdir15(folder2, { withFileTypes: true })) {
|
|
47210
47505
|
if (!entry.isFile()) continue;
|
|
47211
|
-
const file2 =
|
|
47506
|
+
const file2 = path77.join(folder2, entry.name), metadata = await lstat18(file2);
|
|
47212
47507
|
if (Date.now() - metadata.mtimeMs > 14 * 864e5) await unlink6(file2);
|
|
47213
47508
|
else used += metadata.size;
|
|
47214
47509
|
}
|
|
47215
47510
|
}
|
|
47216
47511
|
if (used + bytes.length > 268435456) throw new BridgeError(413, "Phren's image storage is full. Remove older uploads on the computer.");
|
|
47217
|
-
const folder =
|
|
47512
|
+
const folder = path77.join(root, session);
|
|
47218
47513
|
await mkdir18(folder, { recursive: true, mode: 448 });
|
|
47219
|
-
saved =
|
|
47514
|
+
saved = path77.join(folder, `${randomUUID18()}-${name}`);
|
|
47220
47515
|
await writeFile10(saved, bytes, { flag: "wx", mode: 384 });
|
|
47221
47516
|
});
|
|
47222
47517
|
uploadQueue = task;
|
|
@@ -47224,26 +47519,26 @@ async function saveUpload(session, name, bytes) {
|
|
|
47224
47519
|
return saved;
|
|
47225
47520
|
}
|
|
47226
47521
|
async function listUploads(session) {
|
|
47227
|
-
const folder =
|
|
47228
|
-
const entries2 = await
|
|
47522
|
+
const folder = path77.join(bridgeRoot(), "uploads", session);
|
|
47523
|
+
const entries2 = await readdir15(folder, { withFileTypes: true }).catch(() => []);
|
|
47229
47524
|
const files = [];
|
|
47230
47525
|
for (const entry of entries2) {
|
|
47231
47526
|
if (!entry.isFile()) continue;
|
|
47232
|
-
const file2 =
|
|
47527
|
+
const file2 = path77.join(folder, entry.name), metadata = await stat21(file2);
|
|
47233
47528
|
files.push({ name: entry.name.replace(/^[0-9a-f-]{36}-/, ""), path: file2, size: metadata.size, modified: metadata.mtime.toISOString() });
|
|
47234
47529
|
}
|
|
47235
47530
|
return files.sort((a, b) => b.modified.localeCompare(a.modified)).slice(0, 200);
|
|
47236
47531
|
}
|
|
47237
47532
|
async function uploadImage(requested) {
|
|
47238
47533
|
const missing = new BridgeError(404, "This image is not one of the phone's uploads.");
|
|
47239
|
-
if (!requested || requested.length > 4096 || !
|
|
47240
|
-
const root = await
|
|
47241
|
-
const file2 = await
|
|
47242
|
-
if (!root || !file2 || !file2.startsWith(root +
|
|
47243
|
-
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);
|
|
47244
47539
|
if (!metadata.isFile()) throw missing;
|
|
47245
47540
|
if (metadata.size > 8388608) throw new BridgeError(413, "This image is too large.");
|
|
47246
|
-
const bytes = await
|
|
47541
|
+
const bytes = await readFile31(file2);
|
|
47247
47542
|
if (bytes.length > 8388608) throw new BridgeError(413, "This image is too large.");
|
|
47248
47543
|
if (!imageBytes(bytes)) throw missing;
|
|
47249
47544
|
return bytes;
|
|
@@ -47253,7 +47548,7 @@ async function uploadImage(requested) {
|
|
|
47253
47548
|
init_transcript_index();
|
|
47254
47549
|
init_transcripts();
|
|
47255
47550
|
import { homedir as homedir18, tmpdir as tmpdir4 } from "node:os";
|
|
47256
|
-
import
|
|
47551
|
+
import path78 from "node:path";
|
|
47257
47552
|
init_protocol();
|
|
47258
47553
|
var cache = /* @__PURE__ */ new Map();
|
|
47259
47554
|
var modelCache = /* @__PURE__ */ new Map();
|
|
@@ -47391,7 +47686,7 @@ function describe3(tool, args) {
|
|
|
47391
47686
|
return "";
|
|
47392
47687
|
};
|
|
47393
47688
|
const firstLine = (v) => v.split(/\r?\n/).map((l) => l.trim()).find((l) => l) ?? "";
|
|
47394
|
-
const base = (v) =>
|
|
47689
|
+
const base = (v) => path78.basename(v.split(" \xB7 ")[0].trim()) || "file";
|
|
47395
47690
|
const name = tool.toLowerCase();
|
|
47396
47691
|
let value2;
|
|
47397
47692
|
if (["bash", "shell", "exec_command", "exec", "parallel", "tools", "write_stdin", "container.exec"].includes(name)) {
|
|
@@ -47426,17 +47721,17 @@ init_shared();
|
|
|
47426
47721
|
|
|
47427
47722
|
// src/bridge/server-pane-routes.ts
|
|
47428
47723
|
init_zod();
|
|
47429
|
-
import
|
|
47724
|
+
import path81 from "node:path";
|
|
47430
47725
|
import { setTimeout as sleep2 } from "node:timers/promises";
|
|
47431
47726
|
|
|
47432
47727
|
// src/bridge/git.ts
|
|
47433
47728
|
init_protocol();
|
|
47434
47729
|
import { createHash as createHash17 } from "node:crypto";
|
|
47435
|
-
import { execFile as
|
|
47436
|
-
import { lstat as lstat19, readdir as
|
|
47437
|
-
import
|
|
47438
|
-
import { promisify as
|
|
47439
|
-
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);
|
|
47440
47735
|
function statusLetter(code) {
|
|
47441
47736
|
const letter = code[0];
|
|
47442
47737
|
return ["M", "A", "D", "R", "C", "U"].includes(letter) ? letter : "M";
|
|
@@ -47480,9 +47775,9 @@ function parseNumstat(out) {
|
|
|
47480
47775
|
}
|
|
47481
47776
|
async function countLines(root, rel) {
|
|
47482
47777
|
try {
|
|
47483
|
-
const abs =
|
|
47484
|
-
if ((await
|
|
47485
|
-
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);
|
|
47486
47781
|
if (!bytes.length || bytes.includes(0)) return 0;
|
|
47487
47782
|
let lines = 0;
|
|
47488
47783
|
for (const byte of bytes) if (byte === 10) lines++;
|
|
@@ -47648,7 +47943,7 @@ function checkRollup(items) {
|
|
|
47648
47943
|
}
|
|
47649
47944
|
async function currentPull(root, branch) {
|
|
47650
47945
|
try {
|
|
47651
|
-
const { stdout } = await
|
|
47946
|
+
const { stdout } = await exec15("gh", ["pr", "view", "--json", "number,title,url,state,isDraft,headRefName,baseRefName,statusCheckRollup"], {
|
|
47652
47947
|
cwd: root,
|
|
47653
47948
|
timeout: 15e3,
|
|
47654
47949
|
maxBuffer: 4194304,
|
|
@@ -47675,7 +47970,7 @@ async function gitPulls(cwd) {
|
|
|
47675
47970
|
const branch = (await git2(root, "branch", "--show-current").catch(() => "")).trim();
|
|
47676
47971
|
try {
|
|
47677
47972
|
const [{ stdout }, current2] = await Promise.all([
|
|
47678
|
-
|
|
47973
|
+
exec15("gh", ["pr", "list", "--json", "number,title,headRefName,baseRefName,author,url,isDraft,state,updatedAt", "--limit", "50"], {
|
|
47679
47974
|
cwd: root,
|
|
47680
47975
|
timeout: 15e3,
|
|
47681
47976
|
maxBuffer: 4194304,
|
|
@@ -47704,13 +47999,13 @@ async function gitPulls(cwd) {
|
|
|
47704
47999
|
}
|
|
47705
48000
|
}
|
|
47706
48001
|
async function repositoryPath(root, raw, allowRoot = false) {
|
|
47707
|
-
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.");
|
|
47708
48003
|
const segments = raw.split(/[\\/]/);
|
|
47709
48004
|
if (segments.includes("..")) throw new BridgeError(400, "Invalid path.");
|
|
47710
48005
|
const clean2 = segments.filter((part) => part && part !== ".").join("/");
|
|
47711
48006
|
if (!clean2 && !allowRoot || clean2.startsWith("-")) throw new BridgeError(400, "Invalid path.");
|
|
47712
|
-
const abs =
|
|
47713
|
-
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.");
|
|
47714
48009
|
let existing = abs;
|
|
47715
48010
|
while (true) {
|
|
47716
48011
|
try {
|
|
@@ -47718,16 +48013,16 @@ async function repositoryPath(root, raw, allowRoot = false) {
|
|
|
47718
48013
|
break;
|
|
47719
48014
|
} catch (error62) {
|
|
47720
48015
|
if (error62.code !== "ENOENT" || existing === root) throw new BridgeError(400, "Invalid path.");
|
|
47721
|
-
existing =
|
|
48016
|
+
existing = path79.dirname(existing);
|
|
47722
48017
|
}
|
|
47723
48018
|
}
|
|
47724
48019
|
let resolved;
|
|
47725
48020
|
try {
|
|
47726
|
-
resolved = await
|
|
48021
|
+
resolved = await realpath15(existing);
|
|
47727
48022
|
} catch {
|
|
47728
48023
|
throw new BridgeError(403, "This path cannot be resolved inside the repository.");
|
|
47729
48024
|
}
|
|
47730
|
-
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.");
|
|
47731
48026
|
return clean2;
|
|
47732
48027
|
}
|
|
47733
48028
|
var treeCache = /* @__PURE__ */ new Map();
|
|
@@ -47809,7 +48104,7 @@ async function ignoredEntries(root, prefix, shown) {
|
|
|
47809
48104
|
const entries2 = /* @__PURE__ */ new Map();
|
|
47810
48105
|
const inside = prefix && listing.some((item) => item.endsWith("/") && (prefix + "/").startsWith(item));
|
|
47811
48106
|
if (inside) {
|
|
47812
|
-
const dirents = await
|
|
48107
|
+
const dirents = await readdir16(path79.join(root, prefix), { withFileTypes: true }).catch(() => []);
|
|
47813
48108
|
for (const dirent of dirents) {
|
|
47814
48109
|
if (dirent.name === ".git" || taken.has(dirent.name) || entries2.size >= MAX_IGNORED_ENTRIES) continue;
|
|
47815
48110
|
entries2.set(dirent.name, { name: dirent.name, path: `${prefix}/${dirent.name}`, kind: dirent.isDirectory() ? "dir" : "file", ignored: true });
|
|
@@ -47906,9 +48201,9 @@ init_fanouts();
|
|
|
47906
48201
|
// src/bridge/git-worktrees.ts
|
|
47907
48202
|
init_protocol();
|
|
47908
48203
|
import { createHash as createHash18 } from "node:crypto";
|
|
47909
|
-
import { realpath as
|
|
48204
|
+
import { realpath as realpath16, stat as stat23 } from "node:fs/promises";
|
|
47910
48205
|
import { homedir as homedir19 } from "node:os";
|
|
47911
|
-
import
|
|
48206
|
+
import path80 from "node:path";
|
|
47912
48207
|
var MAX_WORKTREES = 64;
|
|
47913
48208
|
var worktreeIdPattern = /^[a-f0-9]{32}$/;
|
|
47914
48209
|
function worktreeId(abs) {
|
|
@@ -47936,8 +48231,8 @@ async function listed(root) {
|
|
|
47936
48231
|
let main;
|
|
47937
48232
|
for (const [index2, block] of blocks.entries()) {
|
|
47938
48233
|
if (block.bare !== void 0 || block.prunable !== void 0) continue;
|
|
47939
|
-
const abs = await
|
|
47940
|
-
if (!abs || !(await
|
|
48234
|
+
const abs = await realpath16(block.worktree).catch(() => void 0);
|
|
48235
|
+
if (!abs || !(await stat23(abs).catch(() => void 0))?.isDirectory()) continue;
|
|
47941
48236
|
if (index2 === 0) main = abs;
|
|
47942
48237
|
const branch = block.branch?.startsWith("refs/heads/") ? block.branch.slice("refs/heads/".length) : null;
|
|
47943
48238
|
worktrees.push({ abs, head: block.HEAD ?? "", branch, locked: block.locked !== void 0 });
|
|
@@ -47947,11 +48242,11 @@ async function listed(root) {
|
|
|
47947
48242
|
}
|
|
47948
48243
|
function displayPath(abs, roots) {
|
|
47949
48244
|
for (const root of roots) {
|
|
47950
|
-
const rel =
|
|
47951
|
-
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("/");
|
|
47952
48247
|
}
|
|
47953
48248
|
const home = homedir19();
|
|
47954
|
-
return abs === home ? "~" : abs.startsWith(home +
|
|
48249
|
+
return abs === home ? "~" : abs.startsWith(home + path80.sep) ? "~/" + path80.relative(home, abs).split(path80.sep).join("/") : abs;
|
|
47955
48250
|
}
|
|
47956
48251
|
function uncommitted(status) {
|
|
47957
48252
|
const tokens = status.split("\0");
|
|
@@ -47965,12 +48260,12 @@ function uncommitted(status) {
|
|
|
47965
48260
|
return count2;
|
|
47966
48261
|
}
|
|
47967
48262
|
async function workerFor(abs, workers, all = []) {
|
|
47968
|
-
const nested = all.filter((other) => other.startsWith(abs +
|
|
48263
|
+
const nested = all.filter((other) => other.startsWith(abs + path80.sep));
|
|
47969
48264
|
let best;
|
|
47970
48265
|
for (const worker of workers) {
|
|
47971
|
-
const cwd = await
|
|
47972
|
-
if (cwd !== abs && !cwd.startsWith(abs +
|
|
47973
|
-
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;
|
|
47974
48269
|
const score = (cwd === abs ? 2 : 0) + (worker.child ? 1 : 0);
|
|
47975
48270
|
if (!best || score > best.score) best = { worker, score };
|
|
47976
48271
|
}
|
|
@@ -48041,10 +48336,10 @@ var MAX_MESSAGE = 2e4;
|
|
|
48041
48336
|
function runCombined(command, args, cwd, timeout) {
|
|
48042
48337
|
return new Promise((resolve11) => {
|
|
48043
48338
|
let output2 = "", truncated = false, timedOut = false, settled = false;
|
|
48044
|
-
const finish = (
|
|
48339
|
+
const finish = (run2) => {
|
|
48045
48340
|
if (!settled) {
|
|
48046
48341
|
settled = true;
|
|
48047
|
-
resolve11(
|
|
48342
|
+
resolve11(run2);
|
|
48048
48343
|
}
|
|
48049
48344
|
};
|
|
48050
48345
|
const child = spawn9(command, args, {
|
|
@@ -48098,13 +48393,13 @@ async function gitCommit(cwd, message) {
|
|
|
48098
48393
|
invalidateTree(root);
|
|
48099
48394
|
try {
|
|
48100
48395
|
countGit("projects");
|
|
48101
|
-
const
|
|
48102
|
-
if (
|
|
48103
|
-
return { ok: false, output:
|
|
48104
|
-
[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." };
|
|
48105
48400
|
}
|
|
48106
48401
|
const [sha, short, subject] = (await git2(root, "log", "-1", "--format=%H%x00%h%x00%s")).trim().split("\0");
|
|
48107
|
-
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 } : {} };
|
|
48108
48403
|
} finally {
|
|
48109
48404
|
invalidateTree(root);
|
|
48110
48405
|
}
|
|
@@ -48127,13 +48422,13 @@ async function gitPush(cwd, confirmDefault) {
|
|
|
48127
48422
|
}
|
|
48128
48423
|
const args = ["-C", root, "--no-pager", "push", "--porcelain", ...tracked ? [] : ["--set-upstream"], remote, `refs/heads/${branch}:refs/heads/${destination2}`];
|
|
48129
48424
|
countGit("projects");
|
|
48130
|
-
const
|
|
48425
|
+
const run2 = await runCombined("git", args, root, PUSH_TIMEOUT_MS);
|
|
48131
48426
|
invalidateTree(root);
|
|
48132
|
-
if (
|
|
48133
|
-
return { ok: false, output:
|
|
48134
|
-
[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." };
|
|
48135
48430
|
}
|
|
48136
|
-
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 };
|
|
48137
48432
|
}
|
|
48138
48433
|
var PULL_URL = /https:\/\/[^\s"'<>]+\/pull\/\d+/;
|
|
48139
48434
|
async function gitPullRequest(cwd, draft) {
|
|
@@ -48147,12 +48442,12 @@ async function gitPullRequest(cwd, draft) {
|
|
|
48147
48442
|
if (auth.code !== 0) {
|
|
48148
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 };
|
|
48149
48444
|
}
|
|
48150
|
-
const
|
|
48151
|
-
const url2 = PULL_URL.exec(
|
|
48152
|
-
if (
|
|
48153
|
-
if (url2 && /already exists/i.test(
|
|
48154
|
-
return { ok: false, reason: "failed", output:
|
|
48155
|
-
[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." };
|
|
48156
48451
|
}
|
|
48157
48452
|
|
|
48158
48453
|
// src/bridge/server-pane-routes.ts
|
|
@@ -48163,11 +48458,11 @@ init_terminal();
|
|
|
48163
48458
|
init_protocol();
|
|
48164
48459
|
init_herdr();
|
|
48165
48460
|
init_terminal();
|
|
48166
|
-
import { execFile as
|
|
48167
|
-
import { open as open15, stat as
|
|
48168
|
-
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";
|
|
48169
48464
|
init_transcripts();
|
|
48170
|
-
var
|
|
48465
|
+
var exec16 = promisify16(execFile17);
|
|
48171
48466
|
var MAX_DEPTH = 64;
|
|
48172
48467
|
var TRANSCRIPT_TAIL_BYTES = 1048576;
|
|
48173
48468
|
var MAX_OTHER_PANES = 48;
|
|
@@ -48198,8 +48493,8 @@ function attributeServers(input2) {
|
|
|
48198
48493
|
}
|
|
48199
48494
|
return result.sort((a, b) => Number(a.source === "mentioned") - Number(b.source === "mentioned") || a.port - b.port);
|
|
48200
48495
|
}
|
|
48201
|
-
async function
|
|
48202
|
-
const { stdout } = await
|
|
48496
|
+
async function processTable3(session) {
|
|
48497
|
+
const { stdout } = await exec16("ps", ["-axo", "pid=,ppid=,args="], { timeout: 4e3, maxBuffer: 16777216 });
|
|
48203
48498
|
const parents = /* @__PURE__ */ new Map();
|
|
48204
48499
|
const runners = [];
|
|
48205
48500
|
const flag = `--session-id ${session}`;
|
|
@@ -48220,11 +48515,11 @@ async function paneRoots(server, paneId) {
|
|
|
48220
48515
|
}
|
|
48221
48516
|
async function transcriptHolders(file2) {
|
|
48222
48517
|
const lsof = process.platform === "darwin" ? "/usr/sbin/lsof" : "lsof";
|
|
48223
|
-
const { stdout } = await
|
|
48518
|
+
const { stdout } = await exec16(lsof, ["-t", "--", file2], { timeout: 3e3 }).catch(() => ({ stdout: "" }));
|
|
48224
48519
|
return stdout.split("\n").map(Number).filter((pid) => Number.isSafeInteger(pid) && pid > 1 && pid !== process.pid);
|
|
48225
48520
|
}
|
|
48226
48521
|
async function transcriptTail(file2) {
|
|
48227
|
-
const size = (await
|
|
48522
|
+
const size = (await stat24(file2)).size;
|
|
48228
48523
|
const handle = await open15(file2, "r");
|
|
48229
48524
|
try {
|
|
48230
48525
|
const length = Math.min(size, TRANSCRIPT_TAIL_BYTES);
|
|
@@ -48238,7 +48533,7 @@ async function transcriptTail(file2) {
|
|
|
48238
48533
|
async function sessionWebServers(target, pane) {
|
|
48239
48534
|
const [servers2, table2, own2, file2] = await Promise.all([
|
|
48240
48535
|
webServers(),
|
|
48241
|
-
|
|
48536
|
+
processTable3(target.session),
|
|
48242
48537
|
paneRoots(target.server, pane.pane_id),
|
|
48243
48538
|
transcriptPath(target.source, target.session).catch(() => void 0)
|
|
48244
48539
|
]);
|
|
@@ -48354,7 +48649,7 @@ function herdrWorktreeWorkers(s) {
|
|
|
48354
48649
|
const workers = [];
|
|
48355
48650
|
for (const pane of objects(s.panes)) {
|
|
48356
48651
|
const cwd = pane.foreground_cwd || pane.cwd;
|
|
48357
|
-
if (typeof pane.agent !== "string" || typeof cwd !== "string" || !
|
|
48652
|
+
if (typeof pane.agent !== "string" || typeof cwd !== "string" || !path81.isAbsolute(cwd)) continue;
|
|
48358
48653
|
const name = paneAgentName(s, pane);
|
|
48359
48654
|
workers.push({
|
|
48360
48655
|
cwd,
|
|
@@ -48672,8 +48967,8 @@ async function paneRouteOnce(ctx, url2, data, response, typing) {
|
|
|
48672
48967
|
}
|
|
48673
48968
|
|
|
48674
48969
|
// src/bridge/server-launch.ts
|
|
48675
|
-
import { mkdir as mkdir20, readFile as
|
|
48676
|
-
import
|
|
48970
|
+
import { mkdir as mkdir20, readFile as readFile33 } from "node:fs/promises";
|
|
48971
|
+
import path83 from "node:path";
|
|
48677
48972
|
init_zod();
|
|
48678
48973
|
init_home_paths();
|
|
48679
48974
|
init_herdr();
|
|
@@ -48683,15 +48978,15 @@ init_terminal();
|
|
|
48683
48978
|
init_zod();
|
|
48684
48979
|
init_utils_helpers();
|
|
48685
48980
|
init_metrics();
|
|
48686
|
-
import { execFile as
|
|
48687
|
-
import { mkdir as mkdir19, realpath as
|
|
48688
|
-
import
|
|
48689
|
-
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";
|
|
48690
48985
|
init_protocol();
|
|
48691
|
-
var
|
|
48986
|
+
var exec17 = promisify17(execFile18);
|
|
48692
48987
|
async function git6(cwd, ...args) {
|
|
48693
48988
|
countGit("launch-worktree");
|
|
48694
|
-
return (await
|
|
48989
|
+
return (await exec17("git", ["-C", cwd, "--no-pager", ...args], {
|
|
48695
48990
|
timeout: 12e4,
|
|
48696
48991
|
maxBuffer: 1048576,
|
|
48697
48992
|
env: nonInteractiveGitEnv({ ...process.env, GIT_CONFIG_NOSYSTEM: "1" })
|
|
@@ -48714,21 +49009,21 @@ async function createLaunchWorktree(cwd, request6) {
|
|
|
48714
49009
|
if (await git6(root, "show-ref", "--verify", "--quiet", `refs/heads/${branch}`).then(() => true, () => false)) {
|
|
48715
49010
|
throw new BridgeError(409, `A branch named "${branch}" already exists in this repository. Choose another branch name.`);
|
|
48716
49011
|
}
|
|
48717
|
-
const worktree =
|
|
48718
|
-
if (await
|
|
49012
|
+
const worktree = path82.join(root, ".claude", "worktrees", worktreeFolderName(branch));
|
|
49013
|
+
if (await stat25(worktree).then(() => true, () => false)) {
|
|
48719
49014
|
throw new BridgeError(409, `The folder .claude/worktrees/${worktreeFolderName(branch)} already exists. Choose another branch name.`);
|
|
48720
49015
|
}
|
|
48721
|
-
await mkdir19(
|
|
49016
|
+
await mkdir19(path82.dirname(worktree), { recursive: true });
|
|
48722
49017
|
try {
|
|
48723
49018
|
await git6(root, "worktree", "add", "-b", branch, worktree, head);
|
|
48724
49019
|
} catch (error62) {
|
|
48725
49020
|
const detail = error62 instanceof Error && "stderr" in error62 ? String(error62.stderr ?? "").trim().split("\n").at(-1) : "";
|
|
48726
49021
|
throw new BridgeError(409, `Git could not create the worktree${detail ? `: ${detail.replace(/^fatal:\s*/, "")}` : "."}`);
|
|
48727
49022
|
}
|
|
48728
|
-
const abs = await
|
|
48729
|
-
const inside =
|
|
48730
|
-
const start = inside && !inside.startsWith("..") ?
|
|
48731
|
-
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;
|
|
48732
49027
|
return {
|
|
48733
49028
|
cwd: startDir,
|
|
48734
49029
|
path: abs,
|
|
@@ -48768,14 +49063,14 @@ var launchKinds = ["codex", "claude", "copilot", "opencode"];
|
|
|
48768
49063
|
var plainText = (max) => external_exports.string().min(1).max(max).refine((t) => !/[\x00-\x1f\x7f]/.test(t));
|
|
48769
49064
|
async function conductorBrief() {
|
|
48770
49065
|
let source;
|
|
48771
|
-
if (true) source = "---\nname: conductor\ndescription: Coordinate independent Phren tasks across every project in the store and every enrolled computer, supervise their local agent fanout, and integrate verified returns in a concise dispatcher voice.\n---\n\n# Conductor\n\nYou are the owner's dispatcher for the whole store, not one project. You start\nin the phren store itself; that folder is not a project and not your work.\n\nFirst, before trusting your tools, check which phren you are running:\n`phren --version` and `command -v phren`. If the version is older than the one\nthe store or the owner expects, or the path is not the install you expect (a\nstale global package, an old checkout), tell the owner in one line and say\nwhich tools may be missing or behave differently.\n\nThen read the relevant projects' summaries and Phren tasks\n(`get_project_summary`, `get_tasks`) before selecting work.\n\nYour tools, use these instead of exploring the CLI or the Hook's files:\n\n- `live_sessions` (CLI `phren dispatch sessions`): every live agent on this\n computer and each enrolled one, with project, harness, status, `idleFor`\n (seconds since it last changed) and the target `hand_off` takes. Start here\n when asked what is running. Computers it could not reach are listed; say so\n rather than guessing. Computers in `notLinked` are registered in the store\n but have no Hook link here: say they were not checked, never that nothing is\n running there.\n- `hand_off`: send a prompt to one of those sessions.\n- `dispatch`: start a new worker on a computer (or `anywhere`).\n- `dispatch_returns` (CLI `phren dispatch returns`): what your workers sent\n back since you last asked: done with the final reply, needs-you with the\n question, failed with the error (a usage limit), blocked, or gone. Reading them marks them read. In core use\n `phren_admin(action: \"dispatch_returns\")`.\n- `phren dispatch status`: receipts of what you dispatched.\n- `get_tasks`, `get_project_summary`, `search_knowledge`: the store's memory.\n\nKeep engineering detail in worker briefs, Phren tasks and findings, and review\nartifacts, not in the owner's chat.\n\n## Voice and pace\n\nThe owner talks to you from the phone, often in talk mode, where your replies\nare read aloud in their voice. Sound like a good dispatcher: short, quick and\nconversational.\n\n- Lead with the outcome in one sentence. Keep the whole reply to one to four\n short sentences unless the owner asks for detail.\n- No tables, file paths, SHAs, PR numbers or run IDs in a reply unless the\n owner asks for them. Record them in Phren tasks and findings instead.\n- One short line per dispatch or return: who, what, result. A routine watcher\n or monitor event where nothing changed gets silence or a single line.\n- When the owner gives you a task, dispatch an engineer for it right away and\n say so in one line. That is the owner's standing rule; do not ask first.\n- Ask at most one question at a time, and name the options.\n- Delegate reading and analysis to workers instead of running long\n investigations yourself, so your own turns stay fast.\n- A message that begins with `[voice]` was spoken in talk mode, and your reply\n will be read aloud. Answer in one or two spoken sentences with no markdown,\n lists, symbols or code, written to sound natural read aloud: \"back in about\n twenty minutes\", not \"ETA ~20m\".\n\n```text\nLinuxbox has the parser checks on Codex, back around two twenty.\nDesk finished the navigation checks: tests passed, not merged yet.\n```\n\nIf a result or return time is unknown, say so. Surface a worker's question in\nthe same short voice, with the worker's own choices.\n\n## Dispatching\n\nPick five to ten independent tasks when that many are available and capacity\npermits. Do not manufacture tasks to fill the batch. Separate dependencies and\nfile ownership; give each remote lead a base revision, acceptance checks, local\nfanout limit, report time and integration instructions. Every brief repeats the\nowner's repository constraints, including any prohibition on commits, pushes,\nbranches or particular tests. Dispatch never expands the owner's authorization.\n\nYou are the one conductor for this computer and every computer linked with\nit; a second conductor in the group is refused at launch. Conductors on\ncomputers that are not linked share only the store, so claim a task before you\ndispatch it: `claim_task` (in core, `manage_task` with `action: \"claim\"`).\nSkip tasks marked `[claimed: <computer>]` by another computer. A claim that\ncomes back not claimed, with `heldBy`, means another conductor got there first:\nmove on. Completing a task clears its claim; release one you will not do. Start\nworkers with `dispatch` or `hand_off`, never as tabs in your own Herdr\nworkspace. When a computer shows up in `notLinked`, tell the owner that\n`phren bridge link <host>` can link it; never link a computer yourself.\n\nPrefer Codex. Use OpenCode Go when its account and harness are connected. Use\nOpenRouter only when the owner explicitly requests it; an unavailable account\ndoes not authorize another paid provider. Name an explicit model when instructed,\notherwise use and report the remote configured default. Each remote lead owns\nits local checkouts, fanout and provider rate limits. Where installed, local\nworkers use the fanout wrapper's `scripts/run.sh --provider codex|opencode\n--label --worktree [--model] [--mode]` contract and parent-bound manifests.\n\nPrefer handing work to a session that already owns the project and is idle or\ndoing related work; call `hand_off` in full or `phren_admin(action: \"hand_off\",\ncomputer?, target|session, text)` in core. Otherwise dispatch a new worker.\nWrite one short line either way. Call `dispatch` in full or\n`phren_admin(action: \"dispatch\", computer, project, harness, model?, prompt, label)`\nin core. The CLI equivalent is `phren dispatch <computer|anywhere> <project>\n--harness <harness> --label <label> --prompt <brief> [--model <model>]`.\n`anywhere` chooses the connected computer with the fewest working agents. Place\nbriefs sequentially, respecting busy/rate-limit responses. Keep their dispatch\nIDs. Do not send local filesystem paths as remote project names.\n\n`accepted` on a receipt is prompt acceptance, not worker completion. Returns\narrive on their own: the Hook follows every worker you dispatch, and when you\nare idle it types one line into this session, such as `Return: Linuxbox parser\nchecks done, tests passed (dispatch <id>). Call dispatch_returns.` When you see\none, call `dispatch_returns` and report each return in one short line. You may\nalso call it whenever you want the current state; do not poll it in a loop, and\ndo not read remote transcripts by hand to learn whether a worker finished. Tell\nthe owner a return time as an expectation, not a promise.\n\nFor a `needs-you` return, surface the worker's question in the owner's chat\nwith its choices as the worker wrote them; do not rewrite or answer it for the\nowner unless the owner already decided. Send the answer back with `hand_off`\nto the row's `target`. A `blocked` worker waits on terminal input, such as a\npermission prompt: say so and point the owner to the phone or the terminal. A\n`gone` worker's pane closed or was taken over: say so, and decide with the\nowner before giving its work to another agent. A `done` reply is the worker's\nown account; check its evidence before saying tests passed or work merged.\n\nAn uncertain delivery is never retried automatically. Inspect its known target\nor status before deciding with the owner whether a replacement is needed. Keep\nunavailable workers visible instead of giving their work to another agent\nwhile the original may still be running.\n\nIntegrate returned changes in dependency order within the owner's allowed\nworkflow. Run a cleanup pass across the combined result and the affected checks.\nRequire evidence before saying tests passed or merged. Ship only within existing\nauthorization; if publication is not authorized, return the reviewable result.\nUpdate Phren tasks when verified complete and save durable decisions. A worker's\nfinished turn alone does not complete the owner's task.\n";
|
|
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";
|
|
48772
49067
|
else {
|
|
48773
|
-
const here =
|
|
49068
|
+
const here = path83.dirname(fileURLToPath(import.meta.url));
|
|
48774
49069
|
for (const candidate of [
|
|
48775
|
-
|
|
48776
|
-
|
|
49070
|
+
path83.join(here, "..", "starter", "global", "skills", "conductor", "SKILL.md"),
|
|
49071
|
+
path83.join(here, "..", "..", "starter", "global", "skills", "conductor", "SKILL.md")
|
|
48777
49072
|
]) {
|
|
48778
|
-
source = await
|
|
49073
|
+
source = await readFile33(candidate, "utf8").catch(() => void 0);
|
|
48779
49074
|
if (source !== void 0) break;
|
|
48780
49075
|
}
|
|
48781
49076
|
}
|
|
@@ -48794,15 +49089,15 @@ function effortArgs(kind, effort) {
|
|
|
48794
49089
|
}
|
|
48795
49090
|
async function prepareConductor(kind, effort, model) {
|
|
48796
49091
|
const brief = await conductorBrief();
|
|
48797
|
-
const briefDirectory =
|
|
49092
|
+
const briefDirectory = path83.join(bridgeRoot(), "conductor");
|
|
48798
49093
|
await mkdir20(briefDirectory, { recursive: true, mode: 448 });
|
|
48799
|
-
const briefFile =
|
|
48800
|
-
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");
|
|
48801
49096
|
if (kind === "claude") return [...model ? ["--model", model] : [], "--append-system-prompt-file", briefFile, "--effort", effort];
|
|
48802
49097
|
if (kind === "codex") return [...model ? ["--model", model] : [], "-c", `model_reasoning_effort=${effort}`, "-c", `developer_instructions=${JSON.stringify(brief)}`];
|
|
48803
49098
|
if (kind === "opencode") {
|
|
48804
|
-
const directory =
|
|
48805
|
-
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");
|
|
48806
49101
|
const definition = `---
|
|
48807
49102
|
description: Coordinate the owner's work across agent sessions.
|
|
48808
49103
|
mode: primary
|
|
@@ -48811,7 +49106,7 @@ mode: primary
|
|
|
48811
49106
|
${brief}
|
|
48812
49107
|
`;
|
|
48813
49108
|
await mkdir20(directory, { recursive: true, mode: 448 });
|
|
48814
|
-
if (await
|
|
49109
|
+
if (await readFile33(file2, "utf8").catch(() => void 0) !== definition) await atomic(file2, definition, 420);
|
|
48815
49110
|
return [...model ? ["--model", model] : [], "--agent", "conductor", "--variant", effort];
|
|
48816
49111
|
}
|
|
48817
49112
|
throw new BridgeError(400, "The selected harness cannot run as a conductor.");
|
|
@@ -48839,7 +49134,7 @@ function herdrAgentName(label2) {
|
|
|
48839
49134
|
}
|
|
48840
49135
|
async function launchSession(server, data, options = {}) {
|
|
48841
49136
|
const role = external_exports.enum(["agent", "conductor"]).default("agent").parse(data.role);
|
|
48842
|
-
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);
|
|
48843
49138
|
const worktreeRequest = data.worktree === void 0 || data.worktree === null ? void 0 : launchWorktreeSchema.parse(data.worktree);
|
|
48844
49139
|
if (worktreeRequest && role === "conductor") throw new BridgeError(400, "A conductor works across projects, so it cannot start in a worktree.");
|
|
48845
49140
|
const label2 = plainText(200).parse(data.label);
|
|
@@ -48931,7 +49226,7 @@ async function workspaceAction(server, operation, data) {
|
|
|
48931
49226
|
if (tab && !objects(s.tabs).some((t) => t.tab_id === tab && (!workspace || t.workspace_id === workspace))) throw new BridgeError(409, "The tab changed.");
|
|
48932
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.");
|
|
48933
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);
|
|
48934
|
-
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);
|
|
48935
49230
|
if (operation === "create") await terminalProvider().create(server, { workspace, label: label2, cwd });
|
|
48936
49231
|
else if (!workspace && !tab && !pane) throw new BridgeError(400, "Choose a Herdr destination.");
|
|
48937
49232
|
else if (pane && operation === "focus") await terminalProvider().focusPane(server, pane);
|
|
@@ -49106,7 +49401,8 @@ var capabilities = {
|
|
|
49106
49401
|
speechTimestamps: true,
|
|
49107
49402
|
transcribe: true,
|
|
49108
49403
|
memoryStore: true,
|
|
49109
|
-
promptOnce: true
|
|
49404
|
+
promptOnce: true,
|
|
49405
|
+
resources: true
|
|
49110
49406
|
};
|
|
49111
49407
|
function capabilitiesForModules(snapshot2) {
|
|
49112
49408
|
const allowed = new Set(snapshot2.modules.flatMap((module) => module.capabilities));
|
|
@@ -49205,6 +49501,19 @@ function workspacesReader(ctx) {
|
|
|
49205
49501
|
return { ...workspaces, phren: info };
|
|
49206
49502
|
};
|
|
49207
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
|
+
}
|
|
49208
49517
|
function createRouteHandler(ctx) {
|
|
49209
49518
|
const {
|
|
49210
49519
|
version: version3,
|
|
@@ -49218,6 +49527,7 @@ function createRouteHandler(ctx) {
|
|
|
49218
49527
|
journal,
|
|
49219
49528
|
modelCatalog,
|
|
49220
49529
|
accountUsage,
|
|
49530
|
+
resources,
|
|
49221
49531
|
launches,
|
|
49222
49532
|
locatedDirectories,
|
|
49223
49533
|
fanoutMessages,
|
|
@@ -49303,7 +49613,7 @@ function createRouteHandler(ctx) {
|
|
|
49303
49613
|
case "/v1/files/range": {
|
|
49304
49614
|
let root;
|
|
49305
49615
|
if (url2.searchParams.get("scope") === "uploads") {
|
|
49306
|
-
root =
|
|
49616
|
+
root = path84.join(bridgeRoot(), "uploads");
|
|
49307
49617
|
} else if (url2.searchParams.has("session")) {
|
|
49308
49618
|
const target = targetFromURL(url2), pane = await validateTarget(target);
|
|
49309
49619
|
const cwd = await gitRepository(pane, target, url2.searchParams.get("child") ?? void 0, url2.searchParams.get("worktree") ?? void 0);
|
|
@@ -49348,8 +49658,19 @@ function createRouteHandler(ctx) {
|
|
|
49348
49658
|
break;
|
|
49349
49659
|
case "/v1/usage": {
|
|
49350
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";
|
|
49351
49662
|
const usage = await accountUsage.read();
|
|
49352
|
-
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") };
|
|
49353
49674
|
break;
|
|
49354
49675
|
}
|
|
49355
49676
|
case "/v1/push/status":
|
|
@@ -49747,10 +50068,10 @@ function copilotThinking(rendered) {
|
|
|
49747
50068
|
if (/^\s*❯\s+(?!\d+[.)]\s)\S/.test(line)) from = index2 + 1;
|
|
49748
50069
|
});
|
|
49749
50070
|
for (let i = lines.length - 1; i >= from; i--) {
|
|
49750
|
-
const
|
|
49751
|
-
if (!
|
|
49752
|
-
if (
|
|
49753
|
-
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]);
|
|
49754
50075
|
if (seconds !== void 0) return { verb: "Working", thinking: false, thoughtFor: seconds };
|
|
49755
50076
|
}
|
|
49756
50077
|
return void 0;
|
|
@@ -49843,8 +50164,8 @@ async function readDeltaPreview(target, file2, rollout) {
|
|
|
49843
50164
|
const handle = await open16(file2 + ".preview.json", constants6.O_RDONLY | constants6.O_NOFOLLOW | constants6.O_NONBLOCK);
|
|
49844
50165
|
let bytes;
|
|
49845
50166
|
try {
|
|
49846
|
-
const
|
|
49847
|
-
if (!
|
|
50167
|
+
const stat26 = await handle.stat();
|
|
50168
|
+
if (!stat26.isFile() || stat26.size > MAX_PREVIEW_BYTES) return null;
|
|
49848
50169
|
const buffer = Buffer.alloc(MAX_PREVIEW_BYTES + 1);
|
|
49849
50170
|
const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
|
|
49850
50171
|
if (bytesRead > MAX_PREVIEW_BYTES) return null;
|
|
@@ -50194,12 +50515,14 @@ function transcriptStreams(ctx) {
|
|
|
50194
50515
|
var OVERVIEW_TICK_MS = intervalFromEnv("PHREN_OVERVIEW_TICK_MS", 5e3, 250, 6e4);
|
|
50195
50516
|
var OVERVIEW_REFRESH_MS = intervalFromEnv("PHREN_OVERVIEW_REFRESH_MS", 1e4, 1e3, 12e4);
|
|
50196
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);
|
|
50197
50519
|
function overviewStream(options) {
|
|
50198
50520
|
const snapshot2 = options.snapshot ?? sharedSnapshot;
|
|
50199
50521
|
const now = options.now ?? Date.now;
|
|
50200
50522
|
const tickMs = options.tickMs ?? OVERVIEW_TICK_MS;
|
|
50201
50523
|
const refreshMs = options.refreshMs ?? OVERVIEW_REFRESH_MS;
|
|
50202
50524
|
const heartbeatMs = options.heartbeatMs ?? OVERVIEW_HEARTBEAT_MS;
|
|
50525
|
+
const resourcesMs = options.resourcesMs ?? OVERVIEW_RESOURCES_MS;
|
|
50203
50526
|
function send2(client, frame) {
|
|
50204
50527
|
if (client.readyState !== import_websocket.default.OPEN) return false;
|
|
50205
50528
|
const data = JSON.stringify(frame);
|
|
@@ -50210,15 +50533,21 @@ function overviewStream(options) {
|
|
|
50210
50533
|
client.send(data);
|
|
50211
50534
|
return true;
|
|
50212
50535
|
}
|
|
50213
|
-
return function stream(client, server, watchApprovals) {
|
|
50536
|
+
return function stream(client, server, watchApprovals, withResources = false) {
|
|
50214
50537
|
let closed = false, busy = false, first = true;
|
|
50215
|
-
let snapshotKey = "", builtAt = 0, sentKey = "", sentAt = 0;
|
|
50538
|
+
let snapshotKey = "", builtAt = 0, sentKey = "", sentAt = 0, resourcesAt = -Infinity;
|
|
50216
50539
|
const tick = async () => {
|
|
50217
50540
|
if (busy || closed) return;
|
|
50218
50541
|
busy = true;
|
|
50219
50542
|
try {
|
|
50220
50543
|
countTick("overview-stream");
|
|
50221
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
|
+
}
|
|
50222
50551
|
const held = await snapshot2(server, first ? 0 : tickMs);
|
|
50223
50552
|
if (closed) return;
|
|
50224
50553
|
const key2 = JSON.stringify(held);
|
|
@@ -50275,9 +50604,9 @@ async function serve(version3) {
|
|
|
50275
50604
|
await mkdir21(root, { recursive: true, mode: 448 });
|
|
50276
50605
|
await chmod5(root, 448);
|
|
50277
50606
|
let computerID2;
|
|
50278
|
-
const identityFile =
|
|
50607
|
+
const identityFile = path85.join(root, "computer-id");
|
|
50279
50608
|
try {
|
|
50280
|
-
computerID2 = (await
|
|
50609
|
+
computerID2 = (await readFile34(identityFile, "utf8")).trim();
|
|
50281
50610
|
} catch {
|
|
50282
50611
|
computerID2 = randomUUID19();
|
|
50283
50612
|
await writeFile11(identityFile, computerID2, { flag: "wx", mode: 384 });
|
|
@@ -50304,6 +50633,7 @@ async function serve(version3) {
|
|
|
50304
50633
|
const sideQuestions = new SideQuestions();
|
|
50305
50634
|
const contextUsage = new WorkspaceContextUsage();
|
|
50306
50635
|
const accountUsage = new AccountUsageReader();
|
|
50636
|
+
const resources = new ResourceMonitor();
|
|
50307
50637
|
const tabActivity = new TabActivityStore();
|
|
50308
50638
|
const codexQuestions = new CodexQuestions();
|
|
50309
50639
|
const scheduleStore = defaultPhrenPath();
|
|
@@ -50325,7 +50655,7 @@ async function serve(version3) {
|
|
|
50325
50655
|
if (codeReindexer) agentHooks.changes.onRecord = (files) => codeReindexer.record(files);
|
|
50326
50656
|
function gatewayTiming() {
|
|
50327
50657
|
try {
|
|
50328
|
-
const parsed = JSON.parse(readFileSync32(
|
|
50658
|
+
const parsed = JSON.parse(readFileSync32(path85.join(root, "gateway.json"), "utf8"));
|
|
50329
50659
|
if (typeof parsed.ms === "number" && Number.isFinite(parsed.ms) && parsed.ms >= 0) return Math.round(parsed.ms);
|
|
50330
50660
|
} catch {
|
|
50331
50661
|
}
|
|
@@ -50342,7 +50672,7 @@ async function serve(version3) {
|
|
|
50342
50672
|
profile: modules.profile,
|
|
50343
50673
|
generation: modules.generation,
|
|
50344
50674
|
get load() {
|
|
50345
|
-
return { average: Number(
|
|
50675
|
+
return { average: Number(loadavg2()[0].toFixed(2)), cpus: cpus2().length };
|
|
50346
50676
|
},
|
|
50347
50677
|
get gatewayMs() {
|
|
50348
50678
|
return gatewayTiming();
|
|
@@ -50371,13 +50701,14 @@ async function serve(version3) {
|
|
|
50371
50701
|
}
|
|
50372
50702
|
const stopRetention = modules.has("git") ? await startChangeRetention() : () => {
|
|
50373
50703
|
};
|
|
50374
|
-
if (modules.has("git")) await rm10(
|
|
50704
|
+
if (modules.has("git")) await rm10(path85.join(root, "changes-scratch"), { recursive: true, force: true });
|
|
50375
50705
|
const streams = transcriptStreams({ modules, agentHooks, codexQuestions, sideQuestions, info, activeCapabilities });
|
|
50376
50706
|
const { stream } = streams;
|
|
50377
50707
|
const overview = overviewStream({
|
|
50378
50708
|
read: workspacesReader({ modules, info, agentHooks, journal, tabActivity, contextUsage }),
|
|
50379
50709
|
info: () => ({ ...info, capabilities: info.capabilities }),
|
|
50380
|
-
renew: (server) => agentHooks.overview.renew(server)
|
|
50710
|
+
renew: (server) => agentHooks.overview.renew(server),
|
|
50711
|
+
resources: () => resources.read()
|
|
50381
50712
|
});
|
|
50382
50713
|
const http = createServer2(createRouteHandler({
|
|
50383
50714
|
version: version3,
|
|
@@ -50395,6 +50726,7 @@ async function serve(version3) {
|
|
|
50395
50726
|
modelSwitcher,
|
|
50396
50727
|
sideQuestions,
|
|
50397
50728
|
accountUsage,
|
|
50729
|
+
resources,
|
|
50398
50730
|
codexQuestions,
|
|
50399
50731
|
launches,
|
|
50400
50732
|
locatedDirectories,
|
|
@@ -50424,7 +50756,7 @@ async function serve(version3) {
|
|
|
50424
50756
|
ws.clients.delete(oldest);
|
|
50425
50757
|
}
|
|
50426
50758
|
if (overviewServer !== void 0) {
|
|
50427
|
-
overview(client, overviewServer, url2.searchParams.get("watchApprovals") === "1");
|
|
50759
|
+
overview(client, overviewServer, url2.searchParams.get("watchApprovals") === "1", url2.searchParams.get("resources") === "1");
|
|
50428
50760
|
return;
|
|
50429
50761
|
}
|
|
50430
50762
|
if (url2.pathname === "/v1/speech/transcribe") {
|
|
@@ -50518,13 +50850,13 @@ init_protocol();
|
|
|
50518
50850
|
// src/bridge/link.ts
|
|
50519
50851
|
init_profile_store();
|
|
50520
50852
|
init_phren_paths();
|
|
50521
|
-
import { execFile as
|
|
50522
|
-
import { readFile as
|
|
50853
|
+
import { execFile as execFile19 } from "node:child_process";
|
|
50854
|
+
import { readFile as readFile35 } from "node:fs/promises";
|
|
50523
50855
|
import { homedir as homedir20, hostname as hostname10, userInfo as userInfo3 } from "node:os";
|
|
50524
|
-
import
|
|
50525
|
-
import { promisify as
|
|
50856
|
+
import path86 from "node:path";
|
|
50857
|
+
import { promisify as promisify18 } from "node:util";
|
|
50526
50858
|
init_protocol();
|
|
50527
|
-
var
|
|
50859
|
+
var exec18 = promisify18(execFile19);
|
|
50528
50860
|
var REMOTE_PATH = 'PATH="$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin:$PATH"';
|
|
50529
50861
|
var GIT_HOSTS = /(^|\.)(github\.com|gitlab\.com|bitbucket\.org)$/i;
|
|
50530
50862
|
function sshConfigHosts(text4) {
|
|
@@ -50549,7 +50881,7 @@ function sshConfigHosts(text4) {
|
|
|
50549
50881
|
}
|
|
50550
50882
|
async function ssh(host, command, input2, timeout = 2e4) {
|
|
50551
50883
|
return new Promise((resolve11, reject) => {
|
|
50552
|
-
const child =
|
|
50884
|
+
const child = execFile19(
|
|
50553
50885
|
"ssh",
|
|
50554
50886
|
["-o", "BatchMode=yes", "-o", "ConnectTimeout=5", "--", host, command],
|
|
50555
50887
|
{ timeout, maxBuffer: 1048576 },
|
|
@@ -50568,11 +50900,11 @@ async function probe2(host) {
|
|
|
50568
50900
|
return computerId ? { host, computerId, user: field("user") ?? "", client: field("client") } : void 0;
|
|
50569
50901
|
}
|
|
50570
50902
|
async function discoverComputers(options = {}) {
|
|
50571
|
-
const config3 = options.sshConfig ?? await
|
|
50903
|
+
const config3 = options.sshConfig ?? await readFile35(path86.join(homedir20(), ".ssh", "config"), "utf8").catch(() => "");
|
|
50572
50904
|
const store = options.store !== void 0 ? options.store : findPhrenPath();
|
|
50573
50905
|
const machines = store ? listMachines(store) : void 0;
|
|
50574
50906
|
const { peers } = await optionalHookPeers();
|
|
50575
|
-
const own2 = (await
|
|
50907
|
+
const own2 = (await readFile35(path86.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
|
|
50576
50908
|
const known = new Set([...localNames(), ...peers.flatMap((peer) => [peer.name, peer.address])].map(computerLabel));
|
|
50577
50909
|
const candidates = [.../* @__PURE__ */ new Set([...sshConfigHosts(config3), ...machines?.ok ? Object.keys(machines.data) : []])].filter((host) => !known.has(computerLabel(host))).slice(0, 32);
|
|
50578
50910
|
const [found, peerIds] = await Promise.all([
|
|
@@ -50594,15 +50926,15 @@ function slugName(value2) {
|
|
|
50594
50926
|
async function linkComputer(host, options = {}) {
|
|
50595
50927
|
const remote = await probe2(host);
|
|
50596
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.`);
|
|
50597
|
-
const own2 = (await
|
|
50929
|
+
const own2 = (await readFile35(path86.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
|
|
50598
50930
|
if (remote.computerId === own2) throw new BridgeError(409, `${host} is this computer.`);
|
|
50599
50931
|
const name = computerName.parse(options.name ?? slugName(host));
|
|
50600
50932
|
const as = computerName.parse(options.as ?? slugName(hostname10()));
|
|
50601
50933
|
const backAddress = options.backAddress ?? remote.client;
|
|
50602
50934
|
if (!backAddress) throw new BridgeError(409, `${host} did not report this computer's address; pass --back-address.`);
|
|
50603
|
-
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(" ")]));
|
|
50604
50936
|
const remoteHostKey = publicComputerKey((await ssh(host, "cat /etc/ssh/ssh_host_ed25519_key.pub")).trim().split(/\s+/).slice(0, 2).join(" "));
|
|
50605
|
-
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(" "));
|
|
50606
50938
|
const remoteLine = (await ssh(host, `${REMOTE_PATH} phren bridge enroll-computer ${name}`)).trim();
|
|
50607
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));
|
|
50608
50940
|
await acceptComputer(name, remoteLine);
|
|
@@ -50637,7 +50969,7 @@ async function runBridge(args, version3) {
|
|
|
50637
50969
|
case "enroll-computer": {
|
|
50638
50970
|
if (args.length === 2) console.log(await enrollComputer(args[1]));
|
|
50639
50971
|
else if (args.length === 4 && args[2] === "--accept") {
|
|
50640
|
-
await acceptComputer(args[1], await
|
|
50972
|
+
await acceptComputer(args[1], await readFile36(args[3], "utf8"));
|
|
50641
50973
|
console.log(`Enrolled ${args[1]} for Phren Hook.`);
|
|
50642
50974
|
} else throw new Error("Usage: phren bridge enroll-computer <name> [--accept <public-key-file>]");
|
|
50643
50975
|
break;
|
|
@@ -50795,7 +51127,7 @@ async function readSecret(prompt) {
|
|
|
50795
51127
|
// src/bridge/hook-main.ts
|
|
50796
51128
|
init_utils_helpers();
|
|
50797
51129
|
Object.assign(process.env, nonInteractiveGitEnv());
|
|
50798
|
-
runBridge(process.argv.slice(2), "0.3.
|
|
51130
|
+
runBridge(process.argv.slice(2), "0.3.11").then((code) => {
|
|
50799
51131
|
process.exitCode = code;
|
|
50800
51132
|
}).catch((error62) => {
|
|
50801
51133
|
console.error(error62 instanceof Error ? error62.message : "Phren Hook failed.");
|