@phren/cli 0.3.8 → 0.3.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bridge/claude-question-dialog.js +8 -4
- package/dist/bridge/codex-binary.d.ts +11 -0
- package/dist/bridge/codex-binary.js +58 -0
- package/dist/bridge/models.js +2 -1
- package/dist/bridge/questions.d.ts +4 -2
- package/dist/bridge/questions.js +12 -5
- package/dist/bridge/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.js +2 -1
- package/dist/bridge-hook.mjs +549 -349
- package/package.json +1 -1
- package/starter/global/skills/conductor/SKILL.md +4 -0
- package/starter/global/skills/fanout/SKILL.md +6 -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, path86) {
|
|
272
|
+
if (!path86)
|
|
273
273
|
return obj;
|
|
274
|
-
return
|
|
274
|
+
return path86.reduce((acc, key2) => acc?.[key2], obj);
|
|
275
275
|
}
|
|
276
276
|
function promiseAllObject(promisesObj) {
|
|
277
277
|
const keys = Object.keys(promisesObj);
|
|
@@ -530,11 +530,11 @@ function explicitlyAborted(x, startIndex = 0) {
|
|
|
530
530
|
}
|
|
531
531
|
return false;
|
|
532
532
|
}
|
|
533
|
-
function prefixIssues(
|
|
533
|
+
function prefixIssues(path86, issues) {
|
|
534
534
|
return issues.map((iss) => {
|
|
535
535
|
var _a3;
|
|
536
536
|
(_a3 = iss).path ?? (_a3.path = []);
|
|
537
|
-
iss.path.unshift(
|
|
537
|
+
iss.path.unshift(path86);
|
|
538
538
|
return iss;
|
|
539
539
|
});
|
|
540
540
|
}
|
|
@@ -1055,16 +1055,16 @@ function flattenError(error62, mapper = (issue2) => issue2.message) {
|
|
|
1055
1055
|
}
|
|
1056
1056
|
function formatError(error62, mapper = (issue2) => issue2.message) {
|
|
1057
1057
|
const fieldErrors = { _errors: [] };
|
|
1058
|
-
const processError = (error63,
|
|
1058
|
+
const processError = (error63, path86 = []) => {
|
|
1059
1059
|
for (const issue2 of error63.issues) {
|
|
1060
1060
|
if (issue2.code === "invalid_union" && issue2.errors.length) {
|
|
1061
|
-
issue2.errors.map((issues) => processError({ issues }, [...
|
|
1061
|
+
issue2.errors.map((issues) => processError({ issues }, [...path86, ...issue2.path]));
|
|
1062
1062
|
} else if (issue2.code === "invalid_key") {
|
|
1063
|
-
processError({ issues: issue2.issues }, [...
|
|
1063
|
+
processError({ issues: issue2.issues }, [...path86, ...issue2.path]);
|
|
1064
1064
|
} else if (issue2.code === "invalid_element") {
|
|
1065
|
-
processError({ issues: issue2.issues }, [...
|
|
1065
|
+
processError({ issues: issue2.issues }, [...path86, ...issue2.path]);
|
|
1066
1066
|
} else {
|
|
1067
|
-
const fullpath = [...
|
|
1067
|
+
const fullpath = [...path86, ...issue2.path];
|
|
1068
1068
|
if (fullpath.length === 0) {
|
|
1069
1069
|
fieldErrors._errors.push(mapper(issue2));
|
|
1070
1070
|
} else {
|
|
@@ -1103,17 +1103,17 @@ function formatError(error62, mapper = (issue2) => issue2.message) {
|
|
|
1103
1103
|
}
|
|
1104
1104
|
function treeifyError(error62, mapper = (issue2) => issue2.message) {
|
|
1105
1105
|
const result = { errors: [] };
|
|
1106
|
-
const processError = (error63,
|
|
1106
|
+
const processError = (error63, path86 = []) => {
|
|
1107
1107
|
var _a3;
|
|
1108
1108
|
for (const issue2 of error63.issues) {
|
|
1109
1109
|
if (issue2.code === "invalid_union" && issue2.errors.length) {
|
|
1110
|
-
issue2.errors.map((issues) => processError({ issues }, [...
|
|
1110
|
+
issue2.errors.map((issues) => processError({ issues }, [...path86, ...issue2.path]));
|
|
1111
1111
|
} else if (issue2.code === "invalid_key") {
|
|
1112
|
-
processError({ issues: issue2.issues }, [...
|
|
1112
|
+
processError({ issues: issue2.issues }, [...path86, ...issue2.path]);
|
|
1113
1113
|
} else if (issue2.code === "invalid_element") {
|
|
1114
|
-
processError({ issues: issue2.issues }, [...
|
|
1114
|
+
processError({ issues: issue2.issues }, [...path86, ...issue2.path]);
|
|
1115
1115
|
} else {
|
|
1116
|
-
const fullpath = [...
|
|
1116
|
+
const fullpath = [...path86, ...issue2.path];
|
|
1117
1117
|
if (fullpath.length === 0) {
|
|
1118
1118
|
result.errors.push(mapper(issue2));
|
|
1119
1119
|
continue;
|
|
@@ -1152,8 +1152,8 @@ function treeifyError(error62, mapper = (issue2) => issue2.message) {
|
|
|
1152
1152
|
}
|
|
1153
1153
|
function toDotPath(_path) {
|
|
1154
1154
|
const segs = [];
|
|
1155
|
-
const
|
|
1156
|
-
for (const seg of
|
|
1155
|
+
const path86 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
|
|
1156
|
+
for (const seg of path86) {
|
|
1157
1157
|
if (typeof seg === "number")
|
|
1158
1158
|
segs.push(`[${seg}]`);
|
|
1159
1159
|
else if (typeof seg === "symbol")
|
|
@@ -19149,13 +19149,13 @@ function resolveRef(ref, ctx) {
|
|
|
19149
19149
|
if (!ref.startsWith("#")) {
|
|
19150
19150
|
throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
|
|
19151
19151
|
}
|
|
19152
|
-
const
|
|
19153
|
-
if (
|
|
19152
|
+
const path86 = ref.slice(1).split("/").filter(Boolean);
|
|
19153
|
+
if (path86.length === 0) {
|
|
19154
19154
|
return ctx.rootSchema;
|
|
19155
19155
|
}
|
|
19156
19156
|
const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
|
|
19157
|
-
if (
|
|
19158
|
-
const key2 =
|
|
19157
|
+
if (path86[0] === defsKey) {
|
|
19158
|
+
const key2 = path86[1] === void 0 ? void 0 : decodeJSONPointerSegment(path86[1]);
|
|
19159
19159
|
if (!key2 || !ctx.defs[key2]) {
|
|
19160
19160
|
throw new Error(`Reference not found: ${ref}`);
|
|
19161
19161
|
}
|
|
@@ -22096,7 +22096,10 @@ function visibleCodexEvent(raw) {
|
|
|
22096
22096
|
payload: { type: "error", ...typeof p.message === "string" ? { message: p.message } : {} }
|
|
22097
22097
|
};
|
|
22098
22098
|
if (raw.type === "event_msg" && ["token_count", "task_started", "task_complete", "task_completed", "turn_aborted", "task_aborted", "error"].includes(String(p.type))) return raw;
|
|
22099
|
+
if (raw.type === "event_msg" && p.type === "item_completed") return itemCall(raw, object2(p.item));
|
|
22099
22100
|
if (raw.type !== "response_item") return void 0;
|
|
22101
|
+
const wrapper = codeModeWrapper(raw);
|
|
22102
|
+
if (wrapper) return wrapper.images.length ? imageCall(raw, wrapper) : void 0;
|
|
22100
22103
|
if (p.type === "message" && ["user", "assistant"].includes(String(p.role)) && p.channel !== "analysis") {
|
|
22101
22104
|
const text4 = typeof p.content === "string" ? p.content : objects(p.content).map((b) => typeof b.text === "string" ? b.text : "").join("\n");
|
|
22102
22105
|
return p.role === "user" && harnessPreamble(text4) ? void 0 : raw;
|
|
@@ -22104,6 +22107,136 @@ function visibleCodexEvent(raw) {
|
|
|
22104
22107
|
if (["function_call", "custom_tool_call", "function_call_output", "custom_tool_call_output"].includes(String(p.type))) return raw;
|
|
22105
22108
|
return void 0;
|
|
22106
22109
|
}
|
|
22110
|
+
function codeModeWrapper(raw) {
|
|
22111
|
+
const p = object2(raw.payload), source = p.input, callId = p.call_id;
|
|
22112
|
+
if (typeof raw.ordinal !== "number" || raw.type !== "response_item" || p.type !== "custom_tool_call" || p.name !== "exec") return void 0;
|
|
22113
|
+
if (typeof source !== "string" || typeof callId !== "string" || !callId || source.trimStart().startsWith("*** Begin Patch")) return void 0;
|
|
22114
|
+
const tools = [...source.matchAll(WRAPPED_TOOL)].map((match) => match[1]);
|
|
22115
|
+
if (!tools.length || !tools.every((tool) => ITEM_TOOLS.has(tool) || /^mcp__\w+$/.test(tool))) return void 0;
|
|
22116
|
+
const images = [...source.matchAll(VIEW_IMAGE)].map((match) => {
|
|
22117
|
+
const args = callArguments(source, (match.index ?? 0) + match[0].length - 1);
|
|
22118
|
+
return (args === void 0 ? void 0 : argumentString(args, source, ["path"])) ?? "";
|
|
22119
|
+
});
|
|
22120
|
+
return { callId, images };
|
|
22121
|
+
}
|
|
22122
|
+
function imageCall(raw, wrapper) {
|
|
22123
|
+
const file2 = wrapper.images.find(Boolean);
|
|
22124
|
+
return {
|
|
22125
|
+
type: "response_item",
|
|
22126
|
+
...raw.timestamp !== void 0 ? { timestamp: raw.timestamp } : {},
|
|
22127
|
+
payload: { type: "function_call", name: "view_image", call_id: wrapper.callId, arguments: JSON.stringify(file2 ? { path: file2.slice(0, 4096) } : {}) }
|
|
22128
|
+
};
|
|
22129
|
+
}
|
|
22130
|
+
function codeModeOutputCall(raw) {
|
|
22131
|
+
const p = object2(raw.payload);
|
|
22132
|
+
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;
|
|
22133
|
+
}
|
|
22134
|
+
function projectCodeModeOutput(raw, call) {
|
|
22135
|
+
const wrapper = call && codeModeWrapper(call);
|
|
22136
|
+
if (!call || !wrapper) return raw;
|
|
22137
|
+
const p = object2(raw.payload), blocks = Array.isArray(p.output) ? objects(p.output) : [];
|
|
22138
|
+
const images = blocks.filter((block) => ["input_image", "image"].includes(String(block.type)));
|
|
22139
|
+
if (wrapper.images.length) return images.length ? { ...raw, payload: { ...p, output: images } } : raw;
|
|
22140
|
+
const text4 = typeof p.output === "string" ? p.output : blocks.map((block) => typeof block.text === "string" ? block.text : "").join("\n");
|
|
22141
|
+
if (/^Script (completed|running)\b/.test(text4)) return void 0;
|
|
22142
|
+
return {
|
|
22143
|
+
type: "response_item",
|
|
22144
|
+
...call.timestamp !== void 0 ? { timestamp: call.timestamp } : {},
|
|
22145
|
+
payload: { type: "custom_tool_call", name: "exec", call_id: wrapper.callId, input: object2(call.payload).input },
|
|
22146
|
+
phren_item_output: raw
|
|
22147
|
+
};
|
|
22148
|
+
}
|
|
22149
|
+
async function findCodeModeCall(rows, line, callId) {
|
|
22150
|
+
const needle = Buffer.from(JSON.stringify(callId));
|
|
22151
|
+
for await (const row of rows(line, Math.max(0, line - 256))) {
|
|
22152
|
+
if (!row.bytes?.includes(needle)) continue;
|
|
22153
|
+
try {
|
|
22154
|
+
const raw = object2(JSON.parse(row.bytes.toString())), p = object2(raw.payload);
|
|
22155
|
+
if (raw.type === "response_item" && p.type === "custom_tool_call" && p.call_id === callId) return raw;
|
|
22156
|
+
} catch {
|
|
22157
|
+
}
|
|
22158
|
+
}
|
|
22159
|
+
return void 0;
|
|
22160
|
+
}
|
|
22161
|
+
function commandText(value2) {
|
|
22162
|
+
if (typeof value2 === "string") return value2;
|
|
22163
|
+
const parts = Array.isArray(value2) ? value2.filter((part) => typeof part === "string") : [];
|
|
22164
|
+
if (parts.length === 3 && ["-lc", "-c"].includes(parts[1]) && /(^|\/)(ba|z|da|fi|k)?sh$/.test(parts[0])) return parts[2];
|
|
22165
|
+
return parts.join(" ");
|
|
22166
|
+
}
|
|
22167
|
+
function localPath(value2) {
|
|
22168
|
+
if (typeof value2 !== "string" || !value2) return void 0;
|
|
22169
|
+
if (value2.startsWith("file://")) {
|
|
22170
|
+
try {
|
|
22171
|
+
const url2 = new URL(value2);
|
|
22172
|
+
if (url2.host) return void 0;
|
|
22173
|
+
const pathname = decodeURIComponent(url2.pathname);
|
|
22174
|
+
return /^\/[A-Za-z]:\//.test(pathname) ? pathname.slice(1) : pathname;
|
|
22175
|
+
} catch {
|
|
22176
|
+
return void 0;
|
|
22177
|
+
}
|
|
22178
|
+
}
|
|
22179
|
+
return value2.startsWith("/") ? value2 : void 0;
|
|
22180
|
+
}
|
|
22181
|
+
function changePatch(changes) {
|
|
22182
|
+
const sections = Object.entries(object2(changes)).slice(0, 50).map(([file2, value2]) => {
|
|
22183
|
+
const change = object2(value2), kind = String(change.type ?? "update");
|
|
22184
|
+
if (kind === "add") {
|
|
22185
|
+
const content = typeof change.content === "string" ? change.content.slice(0, PATCH_FILE).replace(/\n$/, "") : "";
|
|
22186
|
+
return `*** Add File: ${file2}
|
|
22187
|
+
` + content.split("\n").map((line) => "+" + line).join("\n");
|
|
22188
|
+
}
|
|
22189
|
+
if (kind === "delete") return `*** Delete File: ${file2}`;
|
|
22190
|
+
const moved = typeof change.move_path === "string" && change.move_path ? `
|
|
22191
|
+
*** Move to: ${change.move_path}` : "";
|
|
22192
|
+
const diff = typeof change.unified_diff === "string" ? change.unified_diff.slice(0, PATCH_FILE).replace(/\n$/, "") : "";
|
|
22193
|
+
return `*** Update File: ${file2}${moved}${diff ? "\n" + diff : ""}`;
|
|
22194
|
+
});
|
|
22195
|
+
return ["*** Begin Patch", ...sections, "*** End Patch"].join("\n");
|
|
22196
|
+
}
|
|
22197
|
+
function itemCall(raw, item) {
|
|
22198
|
+
const id2 = typeof item.id === "string" && item.id ? item.id.slice(0, 200) : "";
|
|
22199
|
+
if (!id2) return void 0;
|
|
22200
|
+
const stamp = raw.timestamp !== void 0 ? { timestamp: raw.timestamp } : {};
|
|
22201
|
+
const row = (call, output2) => ({
|
|
22202
|
+
type: "response_item",
|
|
22203
|
+
...stamp,
|
|
22204
|
+
payload: { ...call, call_id: id2 },
|
|
22205
|
+
phren_item_output: { type: "response_item", ...stamp, payload: { ...output2, call_id: id2 } }
|
|
22206
|
+
});
|
|
22207
|
+
const status = typeof item.status === "string" ? item.status : "completed";
|
|
22208
|
+
switch (item.type) {
|
|
22209
|
+
case "CommandExecution": {
|
|
22210
|
+
const workdir = localPath(item.cwd);
|
|
22211
|
+
const text4 = [item.aggregated_output, item.formatted_output].find((v) => typeof v === "string") ?? [item.stdout, item.stderr].filter((v) => typeof v === "string").join("");
|
|
22212
|
+
const tail = text4.slice(-OUTPUT_TAIL2);
|
|
22213
|
+
const output2 = typeof item.exit_code === "number" ? JSON.stringify({ output: tail, exit_code: item.exit_code }) : `${tail}${tail && !tail.endsWith("\n") ? "\n" : ""}[${status}]`;
|
|
22214
|
+
return row(
|
|
22215
|
+
{ type: "function_call", name: "exec_command", arguments: JSON.stringify({ cmd: commandText(item.command).slice(0, COMMAND), ...workdir ? { workdir } : {} }) },
|
|
22216
|
+
{ type: "function_call_output", output: output2 }
|
|
22217
|
+
);
|
|
22218
|
+
}
|
|
22219
|
+
case "FileChange": {
|
|
22220
|
+
const said = [status === "completed" ? item.stdout : item.stderr, item.stdout, item.stderr].find((v) => typeof v === "string" && v.trim());
|
|
22221
|
+
return row(
|
|
22222
|
+
{ type: "custom_tool_call", name: "apply_patch", input: changePatch(item.changes) },
|
|
22223
|
+
{ type: "custom_tool_call_output", output: (said ?? status).slice(-OUTPUT_TAIL2) }
|
|
22224
|
+
);
|
|
22225
|
+
}
|
|
22226
|
+
case "McpToolCall": {
|
|
22227
|
+
const result = object2(item.result), ok = object2(result.Ok ?? result), error62 = result.Err ?? item.error;
|
|
22228
|
+
const text4 = objects(ok.content).filter((block) => block.type === "text" && typeof block.text === "string").map((block) => String(block.text)).join("\n");
|
|
22229
|
+
const output2 = text4 || (error62 !== void 0 && error62 !== null ? typeof error62 === "string" ? error62 : JSON.stringify(error62) : status);
|
|
22230
|
+
const args = typeof item.arguments === "string" ? item.arguments : JSON.stringify(item.arguments ?? {});
|
|
22231
|
+
return row(
|
|
22232
|
+
{ type: "function_call", name: `mcp__${String(item.server ?? "mcp")}__${String(item.tool ?? "tool")}`, arguments: args.slice(0, 262144) },
|
|
22233
|
+
{ type: "function_call_output", output: output2.slice(0, MCP_OUTPUT) }
|
|
22234
|
+
);
|
|
22235
|
+
}
|
|
22236
|
+
default:
|
|
22237
|
+
return void 0;
|
|
22238
|
+
}
|
|
22239
|
+
}
|
|
22107
22240
|
function unescapeJs(value2) {
|
|
22108
22241
|
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
22242
|
if (escape[0] === "u") {
|
|
@@ -22157,16 +22290,19 @@ function callArguments(source, open17) {
|
|
|
22157
22290
|
}
|
|
22158
22291
|
return void 0;
|
|
22159
22292
|
}
|
|
22160
|
-
function
|
|
22293
|
+
function argumentString(expression, source, keys) {
|
|
22161
22294
|
const inline = resolveString(expression, source);
|
|
22162
22295
|
if (inline !== void 0) return inline;
|
|
22163
22296
|
const inner = /^\{([\s\S]*)\}$/.exec(expression.trim())?.[1];
|
|
22164
22297
|
if (inner === void 0) return void 0;
|
|
22165
22298
|
const body2 = inner.trim();
|
|
22166
22299
|
if (/^[A-Za-z_$][\w$]*$/.test(body2)) return resolveString(body2, source);
|
|
22167
|
-
const property =
|
|
22300
|
+
const property = new RegExp(`(?:^|[,{])\\s*(?:${keys.join("|")})\\s*:\\s*("(?:\\\\.|[^"\\\\])*"|'(?:\\\\.|[^'\\\\])*'|\`(?:\\\\.|[^\`\\\\])*\`|[A-Za-z_$][\\w$]*)`).exec(body2);
|
|
22168
22301
|
return property ? resolveString(property[1], source) : void 0;
|
|
22169
22302
|
}
|
|
22303
|
+
function shellCommand(expression, source) {
|
|
22304
|
+
return argumentString(expression, source, ["command", "cmd"]);
|
|
22305
|
+
}
|
|
22170
22306
|
function codeToolCalls(source) {
|
|
22171
22307
|
const calls = [], original = source.slice(0, 262144);
|
|
22172
22308
|
for (const match of source.matchAll(CODE_TOOL_CALL)) {
|
|
@@ -22216,6 +22352,12 @@ function renameProjectedChanges(raw, base) {
|
|
|
22216
22352
|
}
|
|
22217
22353
|
function projectCodexRow(raw) {
|
|
22218
22354
|
if (raw.type !== "response_item") return { rows: [raw] };
|
|
22355
|
+
if (raw.phren_item_output !== void 0) {
|
|
22356
|
+
const { phren_item_output: output2, ...call } = raw, result = object2(output2);
|
|
22357
|
+
const expanded = object2(call.payload).name === "exec" ? projectCodexRow(call) : { rows: [call] };
|
|
22358
|
+
if (!expanded.base) return { rows: [...expanded.rows, result] };
|
|
22359
|
+
return { rows: [...expanded.rows, { ...result, payload: { ...object2(result.payload), call_id: `${expanded.base}:1` } }] };
|
|
22360
|
+
}
|
|
22219
22361
|
const payload = object2(raw.payload), type = String(payload.type), callId = typeof payload.call_id === "string" ? payload.call_id : "";
|
|
22220
22362
|
if (type === "custom_tool_call" || type === "function_call") {
|
|
22221
22363
|
const source = codeToolSource(payload.input ?? payload.arguments);
|
|
@@ -22242,7 +22384,7 @@ function rewriteProjectedOutput(entries2, base) {
|
|
|
22242
22384
|
entry.raw = { ...renameProjectedChanges(entry.raw, base), payload: { ...payload, call_id: `${base}:1` } };
|
|
22243
22385
|
}
|
|
22244
22386
|
}
|
|
22245
|
-
var childRelationCache, CODE_TOOL_CALL, JS_ESCAPES, projectedCodeCalls;
|
|
22387
|
+
var childRelationCache, OUTPUT_TAIL2, MCP_OUTPUT, PATCH_FILE, COMMAND, WRAPPED_TOOL, VIEW_IMAGE, ITEM_TOOLS, CODE_TOOL_CALL, JS_ESCAPES, projectedCodeCalls;
|
|
22246
22388
|
var init_transcript_codex = __esm({
|
|
22247
22389
|
"src/bridge/transcript-codex.ts"() {
|
|
22248
22390
|
"use strict";
|
|
@@ -22250,6 +22392,13 @@ var init_transcript_codex = __esm({
|
|
|
22250
22392
|
init_fanouts();
|
|
22251
22393
|
init_transcript_claude();
|
|
22252
22394
|
childRelationCache = /* @__PURE__ */ new Map();
|
|
22395
|
+
OUTPUT_TAIL2 = 4e3;
|
|
22396
|
+
MCP_OUTPUT = 65536;
|
|
22397
|
+
PATCH_FILE = 2e5;
|
|
22398
|
+
COMMAND = 16384;
|
|
22399
|
+
WRAPPED_TOOL = /\btools\s*\.\s*([A-Za-z_$][\w$]*)\s*\(/g;
|
|
22400
|
+
VIEW_IMAGE = /\btools\s*\.\s*view_image\s*\(/g;
|
|
22401
|
+
ITEM_TOOLS = /* @__PURE__ */ new Set(["exec_command", "write_stdin", "apply_patch", "view_image"]);
|
|
22253
22402
|
CODE_TOOL_CALL = /\btools\s*\.\s*(apply_patch|shell|read)\s*\(/g;
|
|
22254
22403
|
JS_ESCAPES = { n: "\n", r: "\r", t: " ", b: "\b", f: "\f", v: "\v", "0": "\0", "'": "'", '"': '"', "\\": "\\", "/": "/" };
|
|
22255
22404
|
projectedCodeCalls = /* @__PURE__ */ new Set();
|
|
@@ -22585,6 +22734,8 @@ var init_transcripts = __esm({
|
|
|
22585
22734
|
const { isSidechain: _sidechain, ...own2 } = raw;
|
|
22586
22735
|
raw = own2;
|
|
22587
22736
|
}
|
|
22737
|
+
const codeModeCall = raw && this.source === "codex" ? codeModeOutputCall(raw) : void 0;
|
|
22738
|
+
if (raw && codeModeCall) raw = projectCodeModeOutput(raw, await findCodeModeCall((upper, lower2) => index2.rows(handle, upper, lower2, signal), row.line, codeModeCall));
|
|
22588
22739
|
if (raw) {
|
|
22589
22740
|
if (this.changes && this.imageLine === void 0) {
|
|
22590
22741
|
const ids = outputCallIds(raw, this.source);
|
|
@@ -28317,7 +28468,7 @@ var init_package_metadata = __esm({
|
|
|
28317
28468
|
__dirname = path24.dirname(fileURLToPath2(import.meta.url));
|
|
28318
28469
|
ROOT = path24.join(__dirname, "..");
|
|
28319
28470
|
PACKAGE_JSON_PATH = path24.join(ROOT, "package.json");
|
|
28320
|
-
BUNDLED_VERSION = true ? "0.3.
|
|
28471
|
+
BUNDLED_VERSION = true ? "0.3.10" : "0.0.0";
|
|
28321
28472
|
PACKAGE_JSON = readPackageJson();
|
|
28322
28473
|
PACKAGE_NAME = PACKAGE_JSON.name || "phren";
|
|
28323
28474
|
VERSION = PACKAGE_JSON.version || BUNDLED_VERSION;
|
|
@@ -32603,6 +32754,7 @@ async function answerClaudeQuestionDialog(io, questions, answers, options = {})
|
|
|
32603
32754
|
await sleep3(120);
|
|
32604
32755
|
}
|
|
32605
32756
|
};
|
|
32757
|
+
const ANSWERED_MS = 8e3;
|
|
32606
32758
|
const initial = await settle2((screen) => screen);
|
|
32607
32759
|
if (!initial) throw changed("The terminal is not showing Claude's question.");
|
|
32608
32760
|
if (initial.tabs.length !== questions.length) throw changed("The terminal is asking a different set of questions.");
|
|
@@ -32639,7 +32791,7 @@ async function answerClaudeQuestionDialog(io, questions, answers, options = {})
|
|
|
32639
32791
|
} else {
|
|
32640
32792
|
await io.keys([String(screen.options[answer.options[0]].number)]);
|
|
32641
32793
|
}
|
|
32642
|
-
if (!await settle2(leaves(index2))) throw changed("The terminal did not take the answer.");
|
|
32794
|
+
if (!await settle2(leaves(index2), ANSWERED_MS)) throw changed("The terminal did not take the answer.");
|
|
32643
32795
|
continue;
|
|
32644
32796
|
}
|
|
32645
32797
|
const rows = [...screen.options, ...screen.other ? [screen.other] : []];
|
|
@@ -32666,10 +32818,10 @@ async function answerClaudeQuestionDialog(io, questions, answers, options = {})
|
|
|
32666
32818
|
} else {
|
|
32667
32819
|
await io.keys(screen.other && screen.cursor === screen.other.number ? ["up", "tab"] : ["tab"]);
|
|
32668
32820
|
}
|
|
32669
|
-
if (!await settle2(leaves(index2))) throw changed("The terminal did not move past the question.");
|
|
32821
|
+
if (!await settle2(leaves(index2), ANSWERED_MS)) throw changed("The terminal did not move past the question.");
|
|
32670
32822
|
}
|
|
32671
32823
|
if (!submit) return;
|
|
32672
|
-
const review = await settle2((value2) => value2?.kind === "review" ? value2 : value2 === void 0 ? "gone" : void 0);
|
|
32824
|
+
const review = await settle2((value2) => value2?.kind === "review" ? value2 : value2 === void 0 ? "gone" : void 0, ANSWERED_MS);
|
|
32673
32825
|
if (review === "gone") return;
|
|
32674
32826
|
if (!review) throw changed("The terminal did not reach the review of the answers.");
|
|
32675
32827
|
const expected = questions.map((question2) => normalize(question2.question));
|
|
@@ -32677,7 +32829,7 @@ async function answerClaudeQuestionDialog(io, questions, answers, options = {})
|
|
|
32677
32829
|
throw changed("Not every question has an answer in the terminal.");
|
|
32678
32830
|
}
|
|
32679
32831
|
await io.keys(["1"]);
|
|
32680
|
-
if (await settle2((value2) => value2 === void 0 ? "gone" : void 0) !== "gone") throw changed("The terminal did not submit the answers.");
|
|
32832
|
+
if (await settle2((value2) => value2 === void 0 ? "gone" : void 0, ANSWERED_MS) !== "gone") throw changed("The terminal did not submit the answers.");
|
|
32681
32833
|
}
|
|
32682
32834
|
var TAB_BAR, ROW, NEXT, normalize, changed, typedKeys;
|
|
32683
32835
|
var init_claude_question_dialog = __esm({
|
|
@@ -32703,7 +32855,7 @@ function choiceKey(value2) {
|
|
|
32703
32855
|
if (text4 === "up" || text4 === "down" || text4 === "tab") return text4[0].toUpperCase() + text4.slice(1);
|
|
32704
32856
|
return choiceKeys.has(text4) ? text4 : void 0;
|
|
32705
32857
|
}
|
|
32706
|
-
function
|
|
32858
|
+
function commandText2(value2) {
|
|
32707
32859
|
if (typeof value2 === "string" && value2.trim()) return value2.trim();
|
|
32708
32860
|
if (Array.isArray(value2)) {
|
|
32709
32861
|
const parts = value2.filter((part) => typeof part === "string" && !!part.trim());
|
|
@@ -32852,7 +33004,7 @@ function numberedDialog(text4) {
|
|
|
32852
33004
|
return { title: title.slice(0, 4e3), options: options.slice(0, 12) };
|
|
32853
33005
|
}
|
|
32854
33006
|
function terminalChoice(input2) {
|
|
32855
|
-
const fields = object2(input2), command =
|
|
33007
|
+
const fields = object2(input2), command = commandText2(fields.command ?? fields.cmd);
|
|
32856
33008
|
let options = [fields.options, fields.choices, fields.actions, fields.answers].map(structuredOptions).find((list) => list.length >= 2) ?? [];
|
|
32857
33009
|
if (options.length < 2) {
|
|
32858
33010
|
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");
|
|
@@ -32877,7 +33029,7 @@ function permissionTitle(tool, input2) {
|
|
|
32877
33029
|
function samePermission(choice, title, tool, input2) {
|
|
32878
33030
|
const text4 = choice.title?.toLowerCase() ?? "";
|
|
32879
33031
|
if (title && text4.includes(title.toLowerCase())) return true;
|
|
32880
|
-
const command =
|
|
33032
|
+
const command = commandText2(object2(input2).command ?? object2(input2).cmd);
|
|
32881
33033
|
if (command && text4.includes(command.toLowerCase())) return true;
|
|
32882
33034
|
const name = tool.split("__").pop();
|
|
32883
33035
|
return !!name && name !== "action" && text4.includes(name.toLowerCase());
|
|
@@ -34268,11 +34420,11 @@ __export(agent_package_exports, {
|
|
|
34268
34420
|
import { execFileSync as execFileSync4, spawn as spawn4 } from "node:child_process";
|
|
34269
34421
|
import * as fs24 from "node:fs";
|
|
34270
34422
|
import { createRequire } from "node:module";
|
|
34271
|
-
import * as
|
|
34423
|
+
import * as path47 from "node:path";
|
|
34272
34424
|
import { fileURLToPath as fileURLToPath4 } from "node:url";
|
|
34273
34425
|
function readManifest(directory) {
|
|
34274
34426
|
try {
|
|
34275
|
-
return JSON.parse(fs24.readFileSync(
|
|
34427
|
+
return JSON.parse(fs24.readFileSync(path47.join(directory, "package.json"), "utf8"));
|
|
34276
34428
|
} catch {
|
|
34277
34429
|
return void 0;
|
|
34278
34430
|
}
|
|
@@ -34282,15 +34434,15 @@ function agentPackageAt(directory, source) {
|
|
|
34282
34434
|
if (manifest?.name !== "@phren/agent") return void 0;
|
|
34283
34435
|
const relative3 = typeof manifest.bin === "string" ? manifest.bin : manifest.bin?.["phren-agent"];
|
|
34284
34436
|
if (!relative3) return void 0;
|
|
34285
|
-
const bin =
|
|
34437
|
+
const bin = path47.join(directory, relative3);
|
|
34286
34438
|
return fs24.existsSync(bin) ? { directory, bin, version: manifest.version, source } : void 0;
|
|
34287
34439
|
}
|
|
34288
34440
|
function workspaceDirectory() {
|
|
34289
|
-
let directory =
|
|
34441
|
+
let directory = path47.dirname(fileURLToPath4(import.meta.url));
|
|
34290
34442
|
for (let depth = 0; depth < 8; depth++) {
|
|
34291
|
-
const candidate =
|
|
34292
|
-
if (fs24.existsSync(
|
|
34293
|
-
const parent =
|
|
34443
|
+
const candidate = path47.join(directory, "packages", "agent");
|
|
34444
|
+
if (fs24.existsSync(path47.join(candidate, "package.json"))) return candidate;
|
|
34445
|
+
const parent = path47.dirname(directory);
|
|
34294
34446
|
if (parent === directory) break;
|
|
34295
34447
|
directory = parent;
|
|
34296
34448
|
}
|
|
@@ -34298,7 +34450,7 @@ function workspaceDirectory() {
|
|
|
34298
34450
|
}
|
|
34299
34451
|
function resolvedDirectory() {
|
|
34300
34452
|
try {
|
|
34301
|
-
return
|
|
34453
|
+
return path47.dirname(createRequire(import.meta.url).resolve("@phren/agent/package.json"));
|
|
34302
34454
|
} catch {
|
|
34303
34455
|
return void 0;
|
|
34304
34456
|
}
|
|
@@ -34307,7 +34459,7 @@ function globalDirectory() {
|
|
|
34307
34459
|
try {
|
|
34308
34460
|
const options = { encoding: "utf8", timeout: 1e4, stdio: ["ignore", "pipe", "ignore"] };
|
|
34309
34461
|
const root = (process.platform === "win32" ? execFileSync4("npm.cmd", ["root", "-g"], { ...options, shell: true }) : execFileSync4("npm", ["root", "-g"], options)).trim();
|
|
34310
|
-
return root ?
|
|
34462
|
+
return root ? path47.join(root, "@phren", "agent") : void 0;
|
|
34311
34463
|
} catch {
|
|
34312
34464
|
return void 0;
|
|
34313
34465
|
}
|
|
@@ -34446,7 +34598,7 @@ var init_audit = __esm({
|
|
|
34446
34598
|
|
|
34447
34599
|
// src/governance/activity.ts
|
|
34448
34600
|
import * as fs25 from "fs";
|
|
34449
|
-
import * as
|
|
34601
|
+
import * as path57 from "path";
|
|
34450
34602
|
function clampSnippet(snippet) {
|
|
34451
34603
|
if (!snippet) return void 0;
|
|
34452
34604
|
const flat = snippet.replace(/\s+/g, " ").trim();
|
|
@@ -34457,7 +34609,7 @@ function recordLookupEvents(phrenPath, events) {
|
|
|
34457
34609
|
if (!events.length) return;
|
|
34458
34610
|
const logPath = lookupEventsLogFile(phrenPath);
|
|
34459
34611
|
try {
|
|
34460
|
-
fs25.mkdirSync(
|
|
34612
|
+
fs25.mkdirSync(path57.dirname(logPath), { recursive: true });
|
|
34461
34613
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
34462
34614
|
const lines = events.map(
|
|
34463
34615
|
(e) => JSON.stringify({
|
|
@@ -34742,7 +34894,7 @@ var init_metadata = __esm({
|
|
|
34742
34894
|
|
|
34743
34895
|
// src/governance/policy.ts
|
|
34744
34896
|
import * as fs26 from "fs";
|
|
34745
|
-
import * as
|
|
34897
|
+
import * as path58 from "path";
|
|
34746
34898
|
function assessSyncOutage(sync, nowMs = Date.now()) {
|
|
34747
34899
|
const consecutiveFailures = sync?.consecutiveFailures ?? 0;
|
|
34748
34900
|
const failingNow = sync?.lastPushStatus !== void 0 && FAILED_PUSH_STATUSES.has(sync.lastPushStatus);
|
|
@@ -34879,7 +35031,7 @@ function normalizeIndexPolicy(data) {
|
|
|
34879
35031
|
function readJsonFile(filePath, fallback) {
|
|
34880
35032
|
try {
|
|
34881
35033
|
if (!fs26.existsSync(filePath)) return fallback;
|
|
34882
|
-
const basename12 =
|
|
35034
|
+
const basename12 = path58.basename(filePath);
|
|
34883
35035
|
const schema = GOVERNANCE_FILE_SCHEMAS[basename12];
|
|
34884
35036
|
if (schema && !validateGovernanceJson(filePath, schema)) {
|
|
34885
35037
|
debugLog(`readJsonFile: ${filePath} failed validation, using defaults`);
|
|
@@ -35316,7 +35468,7 @@ import * as fs17 from "node:fs";
|
|
|
35316
35468
|
import * as path25 from "node:path";
|
|
35317
35469
|
var core = (names) => names.map((name) => ({ name, profiles: ["core", "full"] }));
|
|
35318
35470
|
var full = (names) => names.map((name) => ({ name, profiles: ["full"] }));
|
|
35319
|
-
var routes = (method, paths) => paths.map((
|
|
35471
|
+
var routes = (method, paths) => paths.map((path86) => ({ method, path: path86 }));
|
|
35320
35472
|
var BUILTIN_MODULES = [
|
|
35321
35473
|
{
|
|
35322
35474
|
schemaVersion: 1,
|
|
@@ -35839,7 +35991,7 @@ import { chmod as chmod5, lstat as lstat20, mkdir as mkdir21, readFile as readFi
|
|
|
35839
35991
|
import { readFileSync as readFileSync32 } from "node:fs";
|
|
35840
35992
|
import { createServer as createServer2 } from "node:http";
|
|
35841
35993
|
import { cpus, hostname as hostname9, loadavg } from "node:os";
|
|
35842
|
-
import
|
|
35994
|
+
import path84 from "node:path";
|
|
35843
35995
|
|
|
35844
35996
|
// ../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/wrapper.mjs
|
|
35845
35997
|
var import_stream = __toESM(require_stream(), 1);
|
|
@@ -38404,7 +38556,7 @@ var CodeRoutes = class {
|
|
|
38404
38556
|
const project = projectSchema.parse(projectValue ?? "");
|
|
38405
38557
|
const { codeDatabasePath } = await requireCodePackage(this.store);
|
|
38406
38558
|
const file2 = codeDatabasePath(this.store, project);
|
|
38407
|
-
await Promise.all([file2, `${file2}-journal`, `${file2}-wal`, `${file2}-shm`].map((
|
|
38559
|
+
await Promise.all([file2, `${file2}-journal`, `${file2}-wal`, `${file2}-shm`].map((path86) => rm4(path86, { force: true })));
|
|
38408
38560
|
return { project, disabled: true };
|
|
38409
38561
|
}
|
|
38410
38562
|
async reindex(projectValue) {
|
|
@@ -38701,13 +38853,13 @@ init_logger();
|
|
|
38701
38853
|
init_project_config();
|
|
38702
38854
|
import { randomUUID as randomUUID9 } from "node:crypto";
|
|
38703
38855
|
import { lstat as lstat12, mkdir as mkdir12, readFile as readFile21, readdir as readdir10, realpath as realpath10, stat as stat15 } from "node:fs/promises";
|
|
38704
|
-
import
|
|
38856
|
+
import path51 from "node:path";
|
|
38705
38857
|
|
|
38706
38858
|
// src/bridge/computers.ts
|
|
38707
38859
|
import { execFile as execFile9 } from "node:child_process";
|
|
38708
38860
|
import { chmod as chmod3, lstat as lstat10, mkdir as mkdir11, mkdtemp as mkdtemp2, readFile as readFile19, rename as rename6, rm as rm5, writeFile as writeFile5 } from "node:fs/promises";
|
|
38709
38861
|
import { homedir as homedir14 } from "node:os";
|
|
38710
|
-
import
|
|
38862
|
+
import path49 from "node:path";
|
|
38711
38863
|
import { promisify as promisify8 } from "node:util";
|
|
38712
38864
|
|
|
38713
38865
|
// src/bridge/install.ts
|
|
@@ -38723,10 +38875,53 @@ import { execFile as execFile7, spawn as spawn2 } from "node:child_process";
|
|
|
38723
38875
|
import { createHash as createHash9 } from "node:crypto";
|
|
38724
38876
|
import { lstat as lstat8, open as open9, readFile as readFile17, readdir as readdir9, realpath as realpath9, stat as stat14 } from "node:fs/promises";
|
|
38725
38877
|
import { homedir as homedir11 } from "node:os";
|
|
38726
|
-
import
|
|
38878
|
+
import path45 from "node:path";
|
|
38727
38879
|
import { promisify as promisify6 } from "node:util";
|
|
38880
|
+
|
|
38881
|
+
// src/bridge/codex-binary.ts
|
|
38882
|
+
import { accessSync as accessSync2, closeSync as closeSync2, constants as constants3, openSync as openSync2, readSync, statSync as statSync12 } from "node:fs";
|
|
38883
|
+
import path44 from "node:path";
|
|
38884
|
+
function codexExecutable(env = process.env) {
|
|
38885
|
+
if (process.platform === "win32") return "codex";
|
|
38886
|
+
for (const directory of (env.PATH ?? "").split(path44.delimiter)) {
|
|
38887
|
+
if (!path44.isAbsolute(directory)) continue;
|
|
38888
|
+
const candidate = path44.join(directory, "codex");
|
|
38889
|
+
if (!executable(candidate)) continue;
|
|
38890
|
+
const wrapped = phrenWrapperTarget(candidate);
|
|
38891
|
+
if (wrapped === void 0) return candidate;
|
|
38892
|
+
if (wrapped && executable(wrapped)) return wrapped;
|
|
38893
|
+
}
|
|
38894
|
+
return "codex";
|
|
38895
|
+
}
|
|
38896
|
+
function executable(file2) {
|
|
38897
|
+
try {
|
|
38898
|
+
return statSync12(file2).isFile() && (accessSync2(file2, constants3.X_OK), true);
|
|
38899
|
+
} catch {
|
|
38900
|
+
return false;
|
|
38901
|
+
}
|
|
38902
|
+
}
|
|
38903
|
+
function phrenWrapperTarget(file2) {
|
|
38904
|
+
let head = "";
|
|
38905
|
+
try {
|
|
38906
|
+
const fd = openSync2(file2, "r");
|
|
38907
|
+
try {
|
|
38908
|
+
const buffer = Buffer.alloc(4096);
|
|
38909
|
+
head = buffer.subarray(0, readSync(fd, buffer, 0, buffer.length, 0)).toString("utf8");
|
|
38910
|
+
} finally {
|
|
38911
|
+
closeSync2(fd);
|
|
38912
|
+
}
|
|
38913
|
+
} catch {
|
|
38914
|
+
return void 0;
|
|
38915
|
+
}
|
|
38916
|
+
if (!head.startsWith("#!/bin/sh") || !head.includes("phren wrapper error:")) return void 0;
|
|
38917
|
+
const match = /^REAL_BIN='((?:[^']|'\\'')*)'$/m.exec(head);
|
|
38918
|
+
const target = match?.[1].replace(/'\\''/g, "'");
|
|
38919
|
+
return target && path44.isAbsolute(target) ? target : "";
|
|
38920
|
+
}
|
|
38921
|
+
|
|
38922
|
+
// src/bridge/usage.ts
|
|
38728
38923
|
var exec6 = promisify6(execFile7);
|
|
38729
|
-
var claudeFile = () =>
|
|
38924
|
+
var claudeFile = () => path45.join(bridgeRoot(), "usage", "claude.json");
|
|
38730
38925
|
var safeText = (v) => typeof v === "string" ? v.replace(/[\x00-\x1f\x7f]/g, "").slice(0, 100) : void 0;
|
|
38731
38926
|
function window(id2, name, percent, reset) {
|
|
38732
38927
|
if (typeof percent !== "number" || !Number.isFinite(percent) || percent < 0 || percent > 100) return;
|
|
@@ -38767,9 +38962,9 @@ function openCodeUsage(output2, now = /* @__PURE__ */ new Date()) {
|
|
|
38767
38962
|
}
|
|
38768
38963
|
return { source: "opencode", windows: [], spend: { amountUSD, period: "rolling_7_days" }, updatedAt: now.toISOString() };
|
|
38769
38964
|
}
|
|
38770
|
-
async function readOpenCodeUsage(
|
|
38965
|
+
async function readOpenCodeUsage(executable2 = "opencode", now = /* @__PURE__ */ new Date()) {
|
|
38771
38966
|
try {
|
|
38772
|
-
const { stdout } = await exec6(
|
|
38967
|
+
const { stdout } = await exec6(executable2, ["stats", "--days", "7", "--pure"], { timeout: 12e3, maxBuffer: 1048576 });
|
|
38773
38968
|
return openCodeUsage(stdout, now);
|
|
38774
38969
|
} catch (error62) {
|
|
38775
38970
|
return { source: "opencode", windows: [], message: openCodeFailure(error62) };
|
|
@@ -38785,8 +38980,8 @@ function openCodeFailure(error62) {
|
|
|
38785
38980
|
const exit = typeof failure2?.code === "number" ? ` (exit ${failure2.code})` : "";
|
|
38786
38981
|
return `opencode stats --days 7 failed${exit}${said ? `: ${said}` : ""}. Run it on this computer to see why.`;
|
|
38787
38982
|
}
|
|
38788
|
-
var openCodeAuthFile = () =>
|
|
38789
|
-
process.env.OPENCODE_DATA_DIR ||
|
|
38983
|
+
var openCodeAuthFile = () => path45.join(
|
|
38984
|
+
process.env.OPENCODE_DATA_DIR || path45.join(process.env.XDG_DATA_HOME || path45.join(homedir11(), ".local", "share"), "opencode"),
|
|
38790
38985
|
"auth.json"
|
|
38791
38986
|
);
|
|
38792
38987
|
async function readOpenRouterKey() {
|
|
@@ -38980,7 +39175,7 @@ async function containedRegularFile(root, candidate, maximum) {
|
|
|
38980
39175
|
const link = await lstat8(candidate);
|
|
38981
39176
|
if (!link.isFile() || link.isSymbolicLink() || link.size > maximum) return void 0;
|
|
38982
39177
|
const resolved = await realpath9(candidate);
|
|
38983
|
-
if (!resolved.startsWith(root +
|
|
39178
|
+
if (!resolved.startsWith(root + path45.sep)) return void 0;
|
|
38984
39179
|
const metadata = await stat14(resolved);
|
|
38985
39180
|
return metadata.isFile() && metadata.size <= maximum ? resolved : void 0;
|
|
38986
39181
|
} catch {
|
|
@@ -39018,7 +39213,7 @@ async function readOpenCodeGoLedger(root = fanoutRoot(), now = /* @__PURE__ */ n
|
|
|
39018
39213
|
const names = (await readdir9(directory).catch(() => [])).slice(0, MAX_GO_JOBS);
|
|
39019
39214
|
for (const name of names) {
|
|
39020
39215
|
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(name)) continue;
|
|
39021
|
-
const manifestFile = await containedRegularFile(directory,
|
|
39216
|
+
const manifestFile = await containedRegularFile(directory, path45.join(directory, name, "manifest.json"), MAX_GO_MANIFEST_BYTES);
|
|
39022
39217
|
if (!manifestFile) continue;
|
|
39023
39218
|
let manifest;
|
|
39024
39219
|
try {
|
|
@@ -39029,9 +39224,9 @@ async function readOpenCodeGoLedger(root = fanoutRoot(), now = /* @__PURE__ */ n
|
|
|
39029
39224
|
const model = goModel(manifest.model);
|
|
39030
39225
|
const eventLog = typeof manifest.eventLog === "string" && /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}\.jsonl$/.test(manifest.eventLog) ? manifest.eventLog : void 0;
|
|
39031
39226
|
if (manifest.provider !== "opencode" || !model || !eventLog) continue;
|
|
39032
|
-
const jobRoot = await realpath9(
|
|
39033
|
-
if (!jobRoot || !jobRoot.startsWith(directory +
|
|
39034
|
-
const eventsFile = await containedRegularFile(jobRoot,
|
|
39227
|
+
const jobRoot = await realpath9(path45.join(directory, name)).catch(() => void 0);
|
|
39228
|
+
if (!jobRoot || !jobRoot.startsWith(directory + path45.sep)) continue;
|
|
39229
|
+
const eventsFile = await containedRegularFile(jobRoot, path45.join(jobRoot, eventLog), MAX_GO_EVENTS_BYTES);
|
|
39035
39230
|
if (!eventsFile) continue;
|
|
39036
39231
|
let events;
|
|
39037
39232
|
try {
|
|
@@ -39208,8 +39403,8 @@ function claudeScopedWindows(config3, now = /* @__PURE__ */ new Date()) {
|
|
|
39208
39403
|
}
|
|
39209
39404
|
return windows;
|
|
39210
39405
|
}
|
|
39211
|
-
var claudeConfigFile = () =>
|
|
39212
|
-
var claudeCredentialsFile = () =>
|
|
39406
|
+
var claudeConfigFile = () => path45.join(process.env.CLAUDE_CONFIG_DIR?.trim() ? claudeConfigDir() : homeDir(), ".claude.json");
|
|
39407
|
+
var claudeCredentialsFile = () => path45.join(claudeConfigDir(), ".credentials.json");
|
|
39213
39408
|
function claudeOAuthUsage(value2, now = /* @__PURE__ */ new Date()) {
|
|
39214
39409
|
const limits = object2(value2).limits;
|
|
39215
39410
|
const windows = [];
|
|
@@ -39288,9 +39483,9 @@ async function liveClaudeUsage(now) {
|
|
|
39288
39483
|
return void 0;
|
|
39289
39484
|
}
|
|
39290
39485
|
}
|
|
39291
|
-
function readCodexLimits(
|
|
39486
|
+
function readCodexLimits(executable2 = codexExecutable()) {
|
|
39292
39487
|
return new Promise((resolve11) => {
|
|
39293
|
-
const child = spawn2(
|
|
39488
|
+
const child = spawn2(executable2, ["app-server"], { cwd: homedir11(), stdio: ["pipe", "pipe", "ignore"] });
|
|
39294
39489
|
let pending = "", bytes = 0, initialized = false, done = false;
|
|
39295
39490
|
const finish = (result) => {
|
|
39296
39491
|
if (done) return;
|
|
@@ -39495,7 +39690,7 @@ init_protocol();
|
|
|
39495
39690
|
init_herdr();
|
|
39496
39691
|
import { chmod as chmod2, copyFile as copyFile2, mkdir as mkdir10, open as open10, readFile as readFile18, rename as rename5, symlink, unlink as unlink4, lstat as lstat9, writeFile as writeFile4 } from "node:fs/promises";
|
|
39497
39692
|
import { homedir as homedir13 } from "node:os";
|
|
39498
|
-
import
|
|
39693
|
+
import path48 from "node:path";
|
|
39499
39694
|
import { fileURLToPath as fileURLToPath5 } from "node:url";
|
|
39500
39695
|
import { promisify as promisify7 } from "node:util";
|
|
39501
39696
|
|
|
@@ -39508,17 +39703,17 @@ import { connect as connect3 } from "node:net";
|
|
|
39508
39703
|
import { request as request3 } from "node:http";
|
|
39509
39704
|
import { spawn as spawn3 } from "node:child_process";
|
|
39510
39705
|
import { homedir as homedir12 } from "node:os";
|
|
39511
|
-
import
|
|
39706
|
+
import path46 from "node:path";
|
|
39512
39707
|
function decodeShellDirectory(encoded) {
|
|
39513
39708
|
if (!/^[A-Za-z0-9_-]{1,8192}$/.test(encoded)) return void 0;
|
|
39514
39709
|
const decoded = Buffer.from(encoded, "base64url");
|
|
39515
39710
|
if (decoded.toString("base64url") !== encoded) return void 0;
|
|
39516
39711
|
const dir = decoded.toString("utf8");
|
|
39517
|
-
return
|
|
39712
|
+
return path46.isAbsolute(dir) && !/[\x00-\x1f\x7f]/.test(dir) && !dir.includes("\uFFFD") ? dir : void 0;
|
|
39518
39713
|
}
|
|
39519
39714
|
function shellEnvironment(base = process.env) {
|
|
39520
39715
|
const env = Object.fromEntries(Object.entries(base).filter(([key2]) => !key2.startsWith("HERDR_") && key2 !== "TMUX" && key2 !== "TMUX_PANE"));
|
|
39521
|
-
env.PATH = [
|
|
39716
|
+
env.PATH = [path46.join(homedir12(), ".local/bin"), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin"].join(":");
|
|
39522
39717
|
return env;
|
|
39523
39718
|
}
|
|
39524
39719
|
async function health() {
|
|
@@ -39579,7 +39774,7 @@ async function dispatch(command) {
|
|
|
39579
39774
|
};
|
|
39580
39775
|
if (command === "phren-hook v1 pipe") {
|
|
39581
39776
|
requireHook();
|
|
39582
|
-
await pipe2({ path: socketPath() },
|
|
39777
|
+
await pipe2({ path: socketPath() }, path46.join(bridgeRoot(), "gateway.json"), true);
|
|
39583
39778
|
return;
|
|
39584
39779
|
}
|
|
39585
39780
|
const preview = /^phren-hook v1 web (127\.0\.0\.1|::1) ([1-9][0-9]{0,4})$/.exec(command);
|
|
@@ -39595,7 +39790,7 @@ async function dispatch(command) {
|
|
|
39595
39790
|
if (!raw) throw new BridgeError(403, "The shell folder is not a valid absolute path.");
|
|
39596
39791
|
const cwd = await launchDirectory(raw);
|
|
39597
39792
|
if (!process.stdin.isTTY || !process.stdout.isTTY) throw new Error("Request an SSH terminal first.");
|
|
39598
|
-
const login = process.env.SHELL &&
|
|
39793
|
+
const login = process.env.SHELL && path46.isAbsolute(process.env.SHELL) ? process.env.SHELL : "/bin/sh";
|
|
39599
39794
|
const [file2, args] = shell[2] ? [shell[2], []] : [login, ["-l"]];
|
|
39600
39795
|
await attach(file2, args, { cwd, env: shellEnvironment() }, shell[2] ? `${shell[2]} exited.` : "The shell exited.");
|
|
39601
39796
|
return;
|
|
@@ -39707,9 +39902,9 @@ ${pipe3}exec ${quote2(node2)} ${quote2(bundle)} ssh
|
|
|
39707
39902
|
}
|
|
39708
39903
|
async function activate(version3) {
|
|
39709
39904
|
const root = bridgeRoot();
|
|
39710
|
-
const next =
|
|
39711
|
-
await symlink(
|
|
39712
|
-
await rename5(next,
|
|
39905
|
+
const next = path48.join(root, `current-${process.pid}`);
|
|
39906
|
+
await symlink(path48.join("versions", version3), next);
|
|
39907
|
+
await rename5(next, path48.join(root, "current"));
|
|
39713
39908
|
}
|
|
39714
39909
|
function launchDomain(uid, guiSession2) {
|
|
39715
39910
|
return guiSession2 ? `gui/${uid}` : `user/${uid}`;
|
|
@@ -39717,7 +39912,7 @@ function launchDomain(uid, guiSession2) {
|
|
|
39717
39912
|
function launchCommands(domain2, plist) {
|
|
39718
39913
|
return [`launchctl bootout ${domain2}/${label}`, `launchctl bootstrap ${domain2} ${quote2(plist)}`, `launchctl kickstart -k ${domain2}/${label}`];
|
|
39719
39914
|
}
|
|
39720
|
-
var launchAgentPlist = () =>
|
|
39915
|
+
var launchAgentPlist = () => path48.join(homedir13(), "Library/LaunchAgents", `${label}.plist`);
|
|
39721
39916
|
async function guiSession(uid) {
|
|
39722
39917
|
return exec7("launchctl", ["print", `gui/${uid}`]).then(() => true, () => false);
|
|
39723
39918
|
}
|
|
@@ -39759,52 +39954,52 @@ async function install(version3, noService = false) {
|
|
|
39759
39954
|
if (!/^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(version3)) throw new Error("Invalid helper version.");
|
|
39760
39955
|
const modules = activateModules(defaultPhrenPath(), void 0, true);
|
|
39761
39956
|
if (!modules.has("hook")) throw new Error(disabledHint("hook"));
|
|
39762
|
-
const root = bridgeRoot(), herdr = herdrRoot(), versions =
|
|
39957
|
+
const root = bridgeRoot(), herdr = herdrRoot(), versions = path48.join(root, "versions");
|
|
39763
39958
|
await mkdir10(versions, { recursive: true, mode: 448 });
|
|
39764
39959
|
await chmod2(root, 448);
|
|
39765
|
-
const serviceLog =
|
|
39960
|
+
const serviceLog = path48.join(root, "service.log");
|
|
39766
39961
|
const log2 = await open10(serviceLog, "a", 384);
|
|
39767
39962
|
try {
|
|
39768
39963
|
await log2.chmod(384);
|
|
39769
39964
|
} finally {
|
|
39770
39965
|
await log2.close();
|
|
39771
39966
|
}
|
|
39772
|
-
const hookEdits = await planAgentHooks(
|
|
39967
|
+
const hookEdits = await planAgentHooks(path48.join(root, "current/bridge-hook.mjs"), false, modules);
|
|
39773
39968
|
const own2 = fileURLToPath5(import.meta.url);
|
|
39774
|
-
const bundle = own2.endsWith("bridge-hook.mjs") ? own2 :
|
|
39775
|
-
const destination2 =
|
|
39969
|
+
const bundle = own2.endsWith("bridge-hook.mjs") ? own2 : path48.join(path48.dirname(own2), "..", "bridge-hook.mjs");
|
|
39970
|
+
const destination2 = path48.join(versions, version3);
|
|
39776
39971
|
await mkdir10(destination2, { recursive: true, mode: 448 });
|
|
39777
|
-
const installedBundle =
|
|
39972
|
+
const installedBundle = path48.join(destination2, "bridge-hook.mjs");
|
|
39778
39973
|
const previousBundle = await missingFile(readFile18(installedBundle));
|
|
39779
39974
|
const stagedBundle = installedBundle + `.phren-${process.pid}`;
|
|
39780
39975
|
await copyFile2(bundle, stagedBundle);
|
|
39781
39976
|
await rename5(stagedBundle, installedBundle);
|
|
39782
|
-
const previous = await readFile18(
|
|
39977
|
+
const previous = await readFile18(path48.join(root, "installed.json"), "utf8").then((v) => JSON.parse(v)).catch(() => null);
|
|
39783
39978
|
const gateway = await detectGateway();
|
|
39784
|
-
await atomic(
|
|
39979
|
+
await atomic(path48.join(root, "dispatch"), gatewayScript(gateway, {
|
|
39785
39980
|
root,
|
|
39786
39981
|
herdr,
|
|
39787
39982
|
store: modules.store,
|
|
39788
39983
|
profile: modules.profile,
|
|
39789
39984
|
node: process.execPath,
|
|
39790
|
-
bundle:
|
|
39985
|
+
bundle: path48.join(root, "current/bridge-hook.mjs"),
|
|
39791
39986
|
socket: socketPath(),
|
|
39792
|
-
timing:
|
|
39987
|
+
timing: path48.join(root, "gateway.json")
|
|
39793
39988
|
}), 448);
|
|
39794
|
-
const environmentPath = [
|
|
39795
|
-
const program =
|
|
39989
|
+
const environmentPath = [path48.dirname(process.execPath), path48.join(homedir13(), ".local/bin"), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin"].join(":");
|
|
39990
|
+
const program = path48.join(root, "current/bridge-hook.mjs");
|
|
39796
39991
|
if (!noService) {
|
|
39797
39992
|
if (process.platform === "darwin") {
|
|
39798
|
-
const folder =
|
|
39993
|
+
const folder = path48.join(homedir13(), "Library/LaunchAgents");
|
|
39799
39994
|
await mkdir10(folder, { recursive: true });
|
|
39800
|
-
await atomic(
|
|
39995
|
+
await atomic(path48.join(folder, `${label}.plist`), `<?xml version="1.0" encoding="UTF-8"?>
|
|
39801
39996
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
39802
|
-
<plist version="1.0"><dict><key>Label</key><string>${label}</string><key>ProgramArguments</key><array><string>${xml(process.execPath)}</string><string>${xml(program)}</string><string>serve</string></array><key>Umask</key><integer>63</integer><key>RunAtLoad</key><true/><key>KeepAlive</key><true/><key>ThrottleInterval</key><integer>5</integer><key>Nice</key><integer>-5</integer><key>EnvironmentVariables</key><dict><key>PATH</key><string>${xml(environmentPath)}</string><key>PHREN_BRIDGE_HOME</key><string>${xml(root)}</string><key>PHREN_HERDR_HOME</key><string>${xml(herdr)}</string><key>PHREN_PATH</key><string>${xml(modules.store)}</string><key>PHREN_PROFILE</key><string>${xml(modules.profile)}</string></dict><key>StandardErrorPath</key><string>${xml(
|
|
39997
|
+
<plist version="1.0"><dict><key>Label</key><string>${label}</string><key>ProgramArguments</key><array><string>${xml(process.execPath)}</string><string>${xml(program)}</string><string>serve</string></array><key>Umask</key><integer>63</integer><key>RunAtLoad</key><true/><key>KeepAlive</key><true/><key>ThrottleInterval</key><integer>5</integer><key>Nice</key><integer>-5</integer><key>EnvironmentVariables</key><dict><key>PATH</key><string>${xml(environmentPath)}</string><key>PHREN_BRIDGE_HOME</key><string>${xml(root)}</string><key>PHREN_HERDR_HOME</key><string>${xml(herdr)}</string><key>PHREN_PATH</key><string>${xml(modules.store)}</string><key>PHREN_PROFILE</key><string>${xml(modules.profile)}</string></dict><key>StandardErrorPath</key><string>${xml(path48.join(root, "service.log"))}</string></dict></plist>
|
|
39803
39998
|
`);
|
|
39804
39999
|
} else {
|
|
39805
|
-
const folder =
|
|
40000
|
+
const folder = path48.join(homedir13(), ".config/systemd/user");
|
|
39806
40001
|
await mkdir10(folder, { recursive: true });
|
|
39807
|
-
await atomic(
|
|
40002
|
+
await atomic(path48.join(folder, unit), `[Unit]
|
|
39808
40003
|
Description=Phren Hook
|
|
39809
40004
|
[Service]
|
|
39810
40005
|
ExecStart=${systemdQuote(process.execPath)} ${systemdQuote(program)} serve
|
|
@@ -39846,7 +40041,7 @@ WantedBy=default.target
|
|
|
39846
40041
|
if ((await Promise.resolve().then(() => (init_agent_package(), agent_package_exports))).agentInstalled()) {
|
|
39847
40042
|
console.log("phren-agent chat: found; it reports to this Hook itself, so restart any phren-agent session started before now.");
|
|
39848
40043
|
}
|
|
39849
|
-
const keys =
|
|
40044
|
+
const keys = path48.join(homedir13(), ".ssh/authorized_keys");
|
|
39850
40045
|
const keyStat = await lstat9(keys).catch(() => null);
|
|
39851
40046
|
if (keyStat && !keyStat.isSymbolicLink() && keyStat.isFile()) {
|
|
39852
40047
|
const before = await readFile18(keys, "utf8"), after = upgradeKeys(before);
|
|
@@ -39857,7 +40052,7 @@ WantedBy=default.target
|
|
|
39857
40052
|
}
|
|
39858
40053
|
console.log(`Updated ${after.changed} Phren iPhone key(s); other keys were preserved.`);
|
|
39859
40054
|
}
|
|
39860
|
-
await atomic(
|
|
40055
|
+
await atomic(path48.join(root, "installed.json"), JSON.stringify({ version: version3, previous: previous?.version === version3 ? previous.previous : previous?.version, node: process.execPath, gateway }, null, 2) + "\n");
|
|
39861
40056
|
console.log("Agent hooks installed. In Codex, review the new Phren entries in /hooks. Existing agents may need to resume before new hooks load.");
|
|
39862
40057
|
console.log(`SSH gateway: ${gateway}${gateway === "node" ? " (no socat or nc -U found)" : ""}.`);
|
|
39863
40058
|
console.log(`Phren Hook ${version3} installed${noService ? " (service not started)" : " and running"}. Run phren bridge doctor.`);
|
|
@@ -39882,12 +40077,12 @@ async function uninstall() {
|
|
|
39882
40077
|
else {
|
|
39883
40078
|
await exec7("systemctl", ["--user", "disable", unit]).catch(() => {
|
|
39884
40079
|
});
|
|
39885
|
-
await unlink4(
|
|
40080
|
+
await unlink4(path48.join(homedir13(), ".config/systemd/user", unit)).catch(() => {
|
|
39886
40081
|
});
|
|
39887
40082
|
await exec7("systemctl", ["--user", "daemon-reload"]).catch(() => {
|
|
39888
40083
|
});
|
|
39889
40084
|
}
|
|
39890
|
-
await applyAgentHooks(await planAgentHooks(
|
|
40085
|
+
await applyAgentHooks(await planAgentHooks(path48.join(bridgeRoot(), "current/bridge-hook.mjs"), true));
|
|
39891
40086
|
await applyOpencodePlugin(true);
|
|
39892
40087
|
console.log("Phren Hook stopped and its background service removed. Remove phren-iphone, phren-android and phren-computer keys from authorized_keys to revoke device access. Local data remains in " + bridgeRoot());
|
|
39893
40088
|
}
|
|
@@ -39902,9 +40097,9 @@ async function missingFile(operation) {
|
|
|
39902
40097
|
async function planAgentHooks(program, remove = false, modules) {
|
|
39903
40098
|
const edits = [];
|
|
39904
40099
|
for (const [source, file2] of [
|
|
39905
|
-
["codex",
|
|
39906
|
-
["claude",
|
|
39907
|
-
["copilot",
|
|
40100
|
+
["codex", path48.join(codexHome(), "hooks.json")],
|
|
40101
|
+
["claude", path48.join(claudeConfigDir(), "settings.json")],
|
|
40102
|
+
["copilot", path48.join(process.env.COPILOT_HOME || path48.join(homedir13(), ".copilot"), "hooks/phren.json")]
|
|
39908
40103
|
]) {
|
|
39909
40104
|
const metadata = await missingFile(lstat9(file2));
|
|
39910
40105
|
if (metadata && (!metadata.isFile() || metadata.isSymbolicLink() || metadata.size > 2097152)) {
|
|
@@ -39954,7 +40149,7 @@ async function planAgentHooks(program, remove = false, modules) {
|
|
|
39954
40149
|
}
|
|
39955
40150
|
return edits;
|
|
39956
40151
|
}
|
|
39957
|
-
var opencodePluginsDir = () =>
|
|
40152
|
+
var opencodePluginsDir = () => path48.join(process.env.XDG_CONFIG_HOME || path48.join(homedir13(), ".config"), "opencode", "plugins");
|
|
39958
40153
|
var OPENCODE_PLUGIN_MARKER = "// Installed by Phren Hook";
|
|
39959
40154
|
function opencodePluginNeedsWrite(existing, source) {
|
|
39960
40155
|
if (existing === void 0) return true;
|
|
@@ -39963,10 +40158,10 @@ function opencodePluginNeedsWrite(existing, source) {
|
|
|
39963
40158
|
}
|
|
39964
40159
|
async function opencodePluginSource() {
|
|
39965
40160
|
if (true) return '// Installed by Phren Hook and replaced on every update. Copy it under another name to customize.\nimport { lstatSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";\nimport { homedir } from "node:os";\nimport path from "node:path";\n\nconst PHREN_STORE = "__PHREN_STORE__";\nconst FLUSH_MS = 250;\nconst MAX_TOOL_OUTPUT = 200_000;\n// OpenCode\'s read tool returns a picture as an inline data URL on the tool\n// part (`state.attachments`). The Hook serves images up to 8 MiB; the session\n// budget bounds what every flush rewrites.\nconst MAX_IMAGE_DATA = 4_000_000;\nconst MAX_SESSION_IMAGE_DATA = 24_000_000;\nconst IMAGE_DATA_URL = /^data:(image\\/(?:png|jpeg|gif|webp));base64,([A-Za-z0-9+/=]+)$/;\nconst STOP_REASONS = { stop: "end_turn", "tool-calls": "tool_use", length: "max_tokens" };\nconst OPENCODE_SESSION = /^ses_[0-9A-Za-z]{1,64}$/;\nconst APPROVAL_POLL_MS = 200;\nconst APPROVAL_DEADLINE_MS = 50_000;\n\nfunction storeRoot() {\n if (PHREN_STORE && !PHREN_STORE.startsWith("__")) return PHREN_STORE;\n const configured = process.env.PHREN_PATH?.trim();\n if (!configured) return path.join(homedir(), ".phren");\n const expanded = configured === "~" ? homedir() : configured.startsWith("~/") ? path.join(homedir(), configured.slice(2)) : configured;\n return path.resolve(expanded);\n}\n\nfunction text(value) {\n return typeof value === "string" ? value : "";\n}\n\nfunction approvalDirectory() {\n return path.join(storeRoot(), ".runtime", "approvals");\n}\n\nfunction fanoutDirectory() {\n const configured = process.env.PHREN_FANOUT_DIR?.trim();\n if (configured) return path.resolve(configured);\n return path.join(storeRoot(), ".runtime", "agent-fanouts", text(process.env.PHREN_FANOUT_JOB));\n}\n\nfunction fanoutPatterns(input) {\n const value = input?.pattern;\n if (Array.isArray(value)) return value.filter(entry => typeof entry === "string" && entry);\n return typeof value === "string" && value ? [value] : [];\n}\n\n/** The worktree\'s grandparent is the scratch root the fan-out launcher owns:\n * external reads and writes are allowed only inside it. */\nfunction underScratchRoot(value) {\n const scratch = path.dirname(path.dirname(path.resolve(process.cwd())));\n if (scratch === path.parse(scratch).root) return false;\n const resolved = path.resolve(scratch, value);\n return resolved === scratch || resolved.startsWith(scratch + path.sep);\n}\n\nfunction under(parent, value) {\n if (!parent || parent === path.parse(parent).root) return false;\n const root = path.resolve(parent), resolved = path.resolve(root, value);\n return resolved === root || resolved.startsWith(root + path.sep);\n}\n\n/** Beyond the scratch root, a worker legitimately reads its own machine: the\n * node_modules its worktree links into the main checkout, the store it was\n * briefed from, the toolchains a build shells out to, and the temporary\n * directories those builds write. Everything outside this set is refused. */\nfunction fanoutReadable(value) {\n if (underScratchRoot(value)) return true;\n const home = process.env.HOME || "";\n const roots = [home, storeRoot(), "/tmp", "/private/tmp", "/var/folders", "/private/var/folders",\n "/Applications/Xcode.app", "/Library/Developer"];\n return roots.some(root => under(root, value));\n}\n\n/** A headless fan-out worker may edit, run commands and fetch, and continue\n * when OpenCode\'s own loop detector asks (the launcher\'s watchdog stops a real\n * loop and says why, which is a clearer failure than a refused permission).\n * Anything else is refused outright. */\nfunction fanoutAllowed(input) {\n const kind = text(input?.type);\n if (kind === "edit" || kind === "bash" || kind === "webfetch" || kind === "doom_loop") return true;\n if (kind !== "external_directory") return false;\n const patterns = fanoutPatterns(input);\n return patterns.length > 0 && patterns.every(fanoutReadable);\n}\n\nfunction writeBlocked(input) {\n try {\n const directory = fanoutDirectory();\n mkdirSync(directory, { recursive: true });\n writeJsonAtomic(path.join(directory, "blocked.json"), {\n type: text(input?.type) || "action",\n pattern: fanoutPatterns(input).join(", "),\n message: permissionMessage(input),\n at: new Date().toISOString(),\n });\n } catch {}\n}\n\nfunction approvalPaths(sessionID) {\n const base = path.join(approvalDirectory(), `opencode-${sessionID}`);\n return { request: `${base}.request.json`, answer: `${base}.answer.json` };\n}\n\nfunction writeJsonAtomic(file, value) {\n const staging = `${file}.${process.pid}.tmp`;\n writeFileSync(staging, JSON.stringify(value), { mode: 0o600 });\n renameSync(staging, file);\n}\n\nfunction removeFile(file) {\n try { unlinkSync(file); } catch {}\n}\n\nfunction sleep(ms) {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n\nfunction setStatus(output, status) {\n if (output && typeof output === "object") output.status = status;\n}\n\nfunction permissionMessage(input) {\n const type = text(input?.type) || "action";\n const pattern = Array.isArray(input?.pattern)\n ? input.pattern.filter(value => typeof value === "string").join(", ")\n : text(input?.pattern);\n const metadata = input?.metadata && typeof input.metadata === "object" ? input.metadata : {};\n const detail = [pattern, text(metadata.command), text(metadata.description), text(metadata.path), text(metadata.url)].find(value => value);\n return (detail ? `${type}: ${detail}` : `opencode asks to use ${type}.`).slice(0, 2000);\n}\n\nfunction toolOutput(state) {\n if (!state || typeof state !== "object") return "";\n const output = state.output ?? state.metadata?.output ?? state.result ?? "";\n const value = typeof output === "string" ? output : JSON.stringify(output ?? "");\n return value.length > MAX_TOOL_OUTPUT ? value.slice(0, MAX_TOOL_OUTPUT) : value;\n}\n\nfunction blocksFor(message) {\n const blocks = [];\n for (const id of message.partOrder) {\n const part = message.parts.get(id);\n if (!part || typeof part !== "object") continue;\n if (part.type === "text" && typeof part.text === "string" && part.text.length) {\n blocks.push({ type: "text", text: part.text });\n } else if (part.type === "tool" && typeof part.callID === "string") {\n blocks.push({ type: "tool_use", id: part.callID, name: text(part.tool) || "tool", input: part.state?.input ?? {} });\n }\n }\n return blocks;\n}\n\n/** A tool\'s picture attachments as Anthropic-shaped image blocks, the form the\n * Hook\'s image route and the phone already read from Claude Code. Only inline\n * data URLs are carried; an image over the caps becomes a text marker. */\nfunction toolImages(state, budget) {\n const blocks = [];\n for (const attachment of Array.isArray(state?.attachments) ? state.attachments : []) {\n if (attachment?.type !== "file" || typeof attachment.url !== "string") continue;\n const match = IMAGE_DATA_URL.exec(attachment.url);\n if (!match) continue;\n const data = match[2];\n if (data.length > MAX_IMAGE_DATA || data.length > budget.remaining) {\n blocks.push({ type: "text", text: "[Image not included: too large to show on the phone]" });\n continue;\n }\n budget.remaining -= data.length;\n blocks.push({ type: "image", source: { type: "base64", media_type: match[1], data } });\n }\n return blocks;\n}\n\nfunction toolResults(message, budget) {\n const results = [];\n for (const id of message.partOrder) {\n const part = message.parts.get(id);\n if (!part || part.type !== "tool" || typeof part.callID !== "string") continue;\n const status = part.state?.status;\n if (status !== "completed" && status !== "error") continue;\n const output = toolOutput(part.state), images = toolImages(part.state, budget);\n const content = images.length ? [{ type: "text", text: output }, ...images] : output;\n results.push({ type: "tool_result", tool_use_id: part.callID, content, is_error: status === "error" });\n }\n return results;\n}\n\nfunction linesFor(session) {\n const messages = session.order\n .map(id => session.messages.get(id))\n .filter(Boolean)\n .sort((a, b) => (a.info?.time?.created ?? 0) - (b.info?.time?.created ?? 0) || String(a.info?.id).localeCompare(String(b.info?.id)));\n const lines = [];\n const budget = { remaining: MAX_SESSION_IMAGE_DATA };\n let seq = 0;\n const emit = (type, data, created) => {\n lines.push(JSON.stringify({ seq: seq++, time: new Date(created || Date.now()).toISOString(), type, data }));\n };\n for (const message of messages) {\n const info = message.info ?? {};\n if (info.role === "user") {\n const blocks = blocksFor(message);\n if (blocks.length) emit("user/message", { source: "user", message: { role: "user", content: blocks } }, info.time?.created);\n } else if (info.role === "assistant") {\n const complete = Boolean(info.time?.completed || info.finish);\n const blocks = blocksFor(message).filter(block => complete || block.type !== "text");\n const data = { stop_reason: STOP_REASONS[info.finish] || info.finish || "end_turn", message: { role: "assistant", content: blocks } };\n if (info.tokens && (typeof info.tokens.input === "number" || typeof info.tokens.output === "number")) {\n data.usage = { input_tokens: info.tokens.input ?? 0, output_tokens: info.tokens.output ?? 0 };\n }\n if (blocks.length) emit("assistant/message", data, info.time?.created);\n const results = toolResults(message, budget);\n if (results.length) emit("tool/results", { message: { role: "user", content: results } }, info.time?.updated ?? info.time?.created);\n }\n }\n return lines;\n}\n\n/** Which conversation this OpenCode process is showing, by PID: the Hook\n * reads it to bind a pane when Herdr reports no session for it. */\nconst pidBindingFile = () => path.join(storeRoot(), ".runtime", "sessions", `opencode-pid-${process.pid}.json`);\nfunction writePidBinding(sessionID) {\n mkdirSync(path.dirname(pidBindingFile()), { recursive: true });\n writeJsonAtomic(pidBindingFile(), { session: sessionID, at: new Date().toISOString() });\n}\n\n/** What this OpenCode process is doing, by PID: "working", "idle" or\n * "blocked" (a permission waits for an answer). The Hook reads it for a pane\n * whose terminal does not watch its agents (tmux); Herdr has its own. */\nconst statusFile = () => path.join(storeRoot(), ".runtime", "sessions", `opencode-status-${process.pid}.json`);\n\nexport const PhrenTranscriptPlugin = async () => {\n const sessions = new Map();\n // Subagent sessions run inside the same process; the pane shows their parent.\n const children = new Set();\n let boundSession;\n // A reused PID must not inherit an old process\'s conversation or state.\n try { removeFile(pidBindingFile()); removeFile(statusFile()); } catch {}\n let recordedStatus;\n // Permission asks still open, by id: while any is, the process is blocked.\n const asking = new Set();\n const recordStatus = (status, sessionID) => {\n // A fan-out worker runs headless, in no pane.\n if (process.env.PHREN_FANOUT_JOB) return;\n const next = asking.size && status === "working" ? "blocked" : status;\n if (next === recordedStatus) return;\n try {\n mkdirSync(path.dirname(statusFile()), { recursive: true });\n writeJsonAtomic(statusFile(), { status: next, ...(sessionID ? { session: sessionID } : {}), at: new Date().toISOString() });\n recordedStatus = next;\n } catch {}\n };\n const permissionId = properties => text(properties?.permissionID) || text(properties?.requestID) || text(properties?.id);\n const timers = new Map();\n const written = new Map();\n const pendingApprovals = new Set();\n\n const sessionState = sessionID => {\n let state = sessions.get(sessionID);\n if (!state) { state = { messages: new Map(), order: [], idle: false }; sessions.set(sessionID, state); }\n return state;\n };\n\n const messageState = (sessionID, messageID) => {\n const state = sessionState(sessionID);\n let message = state.messages.get(messageID);\n if (!message) { message = { info: { id: messageID }, parts: new Map(), partOrder: [] }; state.messages.set(messageID, message); state.order.push(messageID); }\n return message;\n };\n\n const flush = sessionID => {\n const state = sessions.get(sessionID);\n if (!state) return;\n const body = linesFor(state);\n const content = body.length ? body.join("\\n") + "\\n" : "";\n const directory = path.join(storeRoot(), ".runtime", "sessions");\n mkdirSync(directory, { recursive: true });\n const file = path.join(directory, `opencode-${sessionID}.events.jsonl`);\n const messages = state.order.map(id => state.messages.get(id));\n const latest = messages.at(-1), info = latest?.info;\n const user = messages.findLast(message => message.info?.role === "user");\n const preview = !state.idle && info?.role === "assistant" && !info.time?.completed && !info.finish\n ? blocksFor(latest).filter(block => block.type === "text").map(block => block.text).join("\\n").slice(0, 32_768) : "";\n if (preview && user?.info.time?.created) writeJsonAtomic(file + ".preview.json", {\n turnStartedAt: new Date(user.info.time.created).toISOString(), text: preview,\n });\n else removeFile(file + ".preview.json");\n if (written.get(sessionID) === content) return;\n const staging = `${file}.${process.pid}.tmp`;\n writeFileSync(staging, content, { mode: 0o600 });\n renameSync(staging, file);\n written.set(sessionID, content);\n };\n\n const schedule = sessionID => {\n if (!sessionID || timers.has(sessionID)) return;\n timers.set(sessionID, setTimeout(() => {\n timers.delete(sessionID);\n try { flush(sessionID); } catch {}\n }, FLUSH_MS));\n };\n\n const rememberInfo = (sessionID, info) => {\n if (!info || typeof info.id !== "string") return;\n const message = messageState(sessionID, info.id);\n message.info = { ...message.info, ...info };\n if (info.role === "user") sessionState(sessionID).idle = false;\n schedule(sessionID);\n };\n\n const rememberPart = (sessionID, messageID, part) => {\n if (!part || typeof part.id !== "string" || typeof messageID !== "string") return;\n const message = messageState(sessionID, messageID);\n if (!message.parts.has(part.id)) message.partOrder.push(part.id);\n message.parts.set(part.id, part);\n schedule(sessionID);\n };\n\n return {\n "chat.message": async (input, output) => {\n if (!OPENCODE_SESSION.test(text(input?.sessionID)) || !output?.message) return;\n if (!process.env.PHREN_FANOUT_JOB && !children.has(input.sessionID) && boundSession !== input.sessionID) {\n try { writePidBinding(input.sessionID); boundSession = input.sessionID; } catch {}\n }\n rememberInfo(input.sessionID, output.message);\n for (const part of output.parts ?? []) rememberPart(input.sessionID, output.message.id, part);\n if (!children.has(input.sessionID)) recordStatus("working", input.sessionID);\n },\n "permission.ask": async (input, output) => {\n // A fan-out worker runs headless in its own worktree with nobody watching\n // the phone\'s approval queue, so edits, commands and fetches inside that\n // worktree are granted here and anything else is refused outright rather\n // than waiting 50 seconds for an answer that never comes.\n if (process.env.PHREN_FANOUT_JOB) {\n if (fanoutAllowed(input)) { setStatus(output, "allow"); return; }\n // A worker the launcher drives through `opencode serve` relays the\n // ask to the phone and resumes on the owner\'s answer.\n if (process.env.PHREN_FANOUT_APPROVALS === "1") { setStatus(output, "ask"); return; }\n setStatus(output, "deny");\n // A denied permission aborts the turn; record what was refused so the\n // Hook can report the worker as blocked rather than finished.\n writeBlocked(input);\n return;\n }\n let request, answer, pendingSession, decision;\n // The ask blocks the process until it is answered: here from the\n // phone, or in the terminal (permission.replied below).\n const askId = text(input?.id);\n if (askId) { asking.add(askId); recordStatus("blocked", text(input?.sessionID)); }\n try {\n const sessionID = text(input?.sessionID), id = text(input?.id);\n if (!OPENCODE_SESSION.test(sessionID) || !id) { setStatus(output, "ask"); return; }\n // A second request for this session belongs in the terminal until\n // the existing phone request has finished.\n if (pendingApprovals.has(sessionID)) { setStatus(output, "ask"); return; }\n pendingApprovals.add(sessionID);\n pendingSession = sessionID;\n const paths = approvalPaths(sessionID);\n request = paths.request; answer = paths.answer;\n mkdirSync(approvalDirectory(), { recursive: true });\n removeFile(answer);\n const created = Date.now();\n writeJsonAtomic(request, { id, sessionID, type: text(input.type) || "action",\n title: text(input.title) || `Allow ${text(input.type) || "action"}?`, message: permissionMessage(input),\n createdAt: new Date(created).toISOString(), expiresAt: new Date(created + APPROVAL_DEADLINE_MS).toISOString() });\n const deadline = created + APPROVAL_DEADLINE_MS;\n while (Date.now() < deadline) {\n await sleep(APPROVAL_POLL_MS);\n try {\n const info = lstatSync(answer);\n if (!info.isFile() || info.size > 65_536) continue;\n const value = JSON.parse(readFileSync(answer, "utf8"));\n if (value && value.id === id) { decision = value.decision; break; }\n } catch {}\n }\n setStatus(output, decision === "approve" ? "allow" : decision === "deny" ? "deny" : "ask");\n } catch {\n setStatus(output, "ask");\n } finally {\n if (answer) removeFile(answer);\n if (request) removeFile(request);\n if (pendingSession) pendingApprovals.delete(pendingSession);\n // Answered from the phone: back to work. Otherwise the terminal asks.\n if (askId && (decision === "approve" || decision === "deny")) { asking.delete(askId); recordStatus("working", pendingSession); }\n }\n },\n event: async ({ event }) => {\n const properties = event?.properties ?? {};\n if ((event?.type === "session.created" || event?.type === "session.updated") && properties.info?.parentID\n && OPENCODE_SESSION.test(text(properties.info.id))) children.add(properties.info.id);\n const sessionID = typeof properties.sessionID === "string" ? properties.sessionID : properties.info?.sessionID ?? properties.part?.sessionID;\n // Permission events name the ask (permission.updated / permission.asked)\n // and its answer, which may come from the terminal.\n if (event?.type === "permission.updated" || event?.type === "permission.asked") {\n const id = permissionId(properties);\n if (id) { asking.add(id); recordStatus("blocked", text(sessionID)); }\n } else if (event?.type === "permission.replied") {\n const id = permissionId(properties);\n if (id) asking.delete(id); else asking.clear();\n recordStatus("working", text(sessionID));\n }\n if (!OPENCODE_SESSION.test(text(sessionID))) return;\n if (event.type === "message.updated") rememberInfo(sessionID, properties.info);\n else if (event.type === "message.part.updated") rememberPart(sessionID, properties.part?.messageID, properties.part);\n else if (event.type === "message.part.delta" && properties.field === "text" && typeof properties.delta === "string") {\n const message = messageState(sessionID, properties.messageID);\n const part = message.parts.get(properties.partID);\n if (part?.type === "text") rememberPart(sessionID, properties.messageID, { ...part, text: text(part.text) + properties.delta });\n }\n else if (event.type === "message.removed") {\n const state = sessions.get(sessionID);\n if (state && typeof properties.messageID === "string") {\n state.messages.delete(properties.messageID);\n state.order = state.order.filter(id => id !== properties.messageID);\n schedule(sessionID);\n }\n } else if (event.type === "session.idle" || event.type === "session.error") {\n sessionState(sessionID).idle = true;\n flush(sessionID);\n if (!children.has(sessionID)) { asking.clear(); recordStatus("idle", sessionID); }\n } else if (event.type === "session.status") {\n if (properties.status?.type === "busy") sessionState(sessionID).idle = false;\n // A subagent\'s session runs inside its parent\'s turn.\n if (!children.has(sessionID) && ["busy", "retry", "idle"].includes(properties.status?.type)) {\n if (properties.status.type === "idle") asking.clear();\n recordStatus(properties.status.type === "idle" ? "idle" : "working", sessionID);\n }\n }\n },\n };\n};\n';
|
|
39966
|
-
const here =
|
|
40161
|
+
const here = path48.dirname(fileURLToPath5(import.meta.url));
|
|
39967
40162
|
for (const candidate of [
|
|
39968
|
-
|
|
39969
|
-
|
|
40163
|
+
path48.join(here, "..", "..", "plugins", "opencode", "phren-transcript.js"),
|
|
40164
|
+
path48.join(here, "..", "plugins", "opencode", "phren-transcript.js")
|
|
39970
40165
|
]) {
|
|
39971
40166
|
const source = await missingFile(readFile18(candidate, "utf8"));
|
|
39972
40167
|
if (source !== void 0) return source;
|
|
@@ -39974,7 +40169,7 @@ async function opencodePluginSource() {
|
|
|
39974
40169
|
return void 0;
|
|
39975
40170
|
}
|
|
39976
40171
|
async function applyOpencodePlugin(remove = false) {
|
|
39977
|
-
const dir = opencodePluginsDir(), file2 =
|
|
40172
|
+
const dir = opencodePluginsDir(), file2 = path48.join(dir, "phren-transcript.js");
|
|
39978
40173
|
const source = await opencodePluginSource();
|
|
39979
40174
|
const existing = await missingFile(readFile18(file2, "utf8"));
|
|
39980
40175
|
if (remove) {
|
|
@@ -39982,14 +40177,14 @@ async function applyOpencodePlugin(remove = false) {
|
|
|
39982
40177
|
return false;
|
|
39983
40178
|
}
|
|
39984
40179
|
if (source === void 0 || !opencodePluginNeedsWrite(existing, source)) return false;
|
|
39985
|
-
if (!(await lstat9(
|
|
40180
|
+
if (!(await lstat9(path48.dirname(dir)).catch(() => null))?.isDirectory()) return false;
|
|
39986
40181
|
await mkdir10(dir, { recursive: true });
|
|
39987
40182
|
await atomic(file2, source, 420);
|
|
39988
40183
|
return true;
|
|
39989
40184
|
}
|
|
39990
40185
|
async function applyAgentHooks(edits) {
|
|
39991
40186
|
for (const { file: file2, before, after } of edits) {
|
|
39992
|
-
await mkdir10(
|
|
40187
|
+
await mkdir10(path48.dirname(file2), { recursive: true, mode: 448 });
|
|
39993
40188
|
if (await missingFile(readFile18(file2, "utf8")) !== before) throw new Error("Agent settings changed during installation. Run install again.");
|
|
39994
40189
|
if (before !== void 0) await copyFile2(file2, file2 + `.phren-hook-${Date.now()}.bak`);
|
|
39995
40190
|
await atomic(file2, after);
|
|
@@ -40003,18 +40198,18 @@ async function restoreAgentHooks(edits) {
|
|
|
40003
40198
|
}
|
|
40004
40199
|
}
|
|
40005
40200
|
async function rollback() {
|
|
40006
|
-
const config3 = JSON.parse(await readFile18(
|
|
40201
|
+
const config3 = JSON.parse(await readFile18(path48.join(bridgeRoot(), "installed.json"), "utf8"));
|
|
40007
40202
|
if (!config3.previous || !/^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?$/.test(config3.previous)) throw new Error("No previous helper version is available.");
|
|
40008
40203
|
await stopService();
|
|
40009
40204
|
await activate(config3.previous);
|
|
40010
40205
|
await startService();
|
|
40011
|
-
await atomic(
|
|
40206
|
+
await atomic(path48.join(bridgeRoot(), "installed.json"), JSON.stringify({ version: config3.previous, previous: config3.version }) + "\n");
|
|
40012
40207
|
}
|
|
40013
40208
|
|
|
40014
40209
|
// src/bridge/computers.ts
|
|
40015
40210
|
init_protocol();
|
|
40016
40211
|
var exec8 = promisify8(execFile9);
|
|
40017
|
-
var dispatchKeyPath = (root = bridgeRoot()) =>
|
|
40212
|
+
var dispatchKeyPath = (root = bridgeRoot()) => path49.join(root, "id_ed25519_dispatch");
|
|
40018
40213
|
function publicComputerKey(value2) {
|
|
40019
40214
|
const match = /^ssh-ed25519 ([A-Za-z0-9+/]+={0,2})(?: [^\r\n]*)?$/.exec(value2.trim());
|
|
40020
40215
|
if (!match) throw new BridgeError(400, "Supply one ed25519 public key.");
|
|
@@ -40040,7 +40235,7 @@ async function enrollComputer(name, root = bridgeRoot()) {
|
|
|
40040
40235
|
computerName.parse(name);
|
|
40041
40236
|
await mkdir11(root, { recursive: true, mode: 448 });
|
|
40042
40237
|
await chmod3(root, 448);
|
|
40043
|
-
const lock =
|
|
40238
|
+
const lock = path49.join(root, "enroll-computer.lock");
|
|
40044
40239
|
try {
|
|
40045
40240
|
await mkdir11(lock, { mode: 448 });
|
|
40046
40241
|
} catch {
|
|
@@ -40049,9 +40244,9 @@ async function enrollComputer(name, root = bridgeRoot()) {
|
|
|
40049
40244
|
try {
|
|
40050
40245
|
const key2 = dispatchKeyPath(root);
|
|
40051
40246
|
if (!await regularFile(key2)) {
|
|
40052
|
-
const temporary = await mkdtemp2(
|
|
40247
|
+
const temporary = await mkdtemp2(path49.join(root, "enroll-"));
|
|
40053
40248
|
try {
|
|
40054
|
-
const generated =
|
|
40249
|
+
const generated = path49.join(temporary, "key");
|
|
40055
40250
|
await exec8("ssh-keygen", ["-q", "-t", "ed25519", "-N", "", "-C", "phren-computer", "-f", generated], { timeout: 1e4 });
|
|
40056
40251
|
await rename6(generated, key2);
|
|
40057
40252
|
} finally {
|
|
@@ -40065,7 +40260,7 @@ async function enrollComputer(name, root = bridgeRoot()) {
|
|
|
40065
40260
|
await rm5(lock, { recursive: true, force: true });
|
|
40066
40261
|
}
|
|
40067
40262
|
}
|
|
40068
|
-
async function acceptComputer(name, input2, sshDirectory =
|
|
40263
|
+
async function acceptComputer(name, input2, sshDirectory = path49.join(homedir14(), ".ssh")) {
|
|
40069
40264
|
computerName.parse(name);
|
|
40070
40265
|
const prefix = `restrict,pty,${forcedCommand} `;
|
|
40071
40266
|
const raw = input2.trim();
|
|
@@ -40079,19 +40274,19 @@ async function acceptComputer(name, input2, sshDirectory = path48.join(homedir14
|
|
|
40079
40274
|
sshDirectory
|
|
40080
40275
|
);
|
|
40081
40276
|
}
|
|
40082
|
-
async function appendAuthorizedKey(line, conflicts, conflictMessage, sshDirectory =
|
|
40277
|
+
async function appendAuthorizedKey(line, conflicts, conflictMessage, sshDirectory = path49.join(homedir14(), ".ssh")) {
|
|
40083
40278
|
const directory = await lstat10(sshDirectory).catch(() => void 0);
|
|
40084
40279
|
if (directory && (!directory.isDirectory() || directory.isSymbolicLink())) throw new BridgeError(409, "Refusing an unexpected SSH directory.");
|
|
40085
40280
|
await mkdir11(sshDirectory, { recursive: true, mode: 448 });
|
|
40086
40281
|
await chmod3(sshDirectory, 448);
|
|
40087
|
-
const lock =
|
|
40282
|
+
const lock = path49.join(sshDirectory, ".phren-enroll.lock");
|
|
40088
40283
|
try {
|
|
40089
40284
|
await mkdir11(lock, { mode: 448 });
|
|
40090
40285
|
} catch {
|
|
40091
40286
|
throw new BridgeError(409, "SSH enrollment is already running; inspect .phren-enroll.lock if interrupted.");
|
|
40092
40287
|
}
|
|
40093
|
-
const file2 =
|
|
40094
|
-
const temporary =
|
|
40288
|
+
const file2 = path49.join(sshDirectory, "authorized_keys");
|
|
40289
|
+
const temporary = path49.join(lock, "authorized_keys");
|
|
40095
40290
|
try {
|
|
40096
40291
|
const before = await regularFile(file2) ? await readFile19(file2, "utf8") : "";
|
|
40097
40292
|
const lines = before.split("\n").filter(Boolean);
|
|
@@ -40198,10 +40393,10 @@ function projectAgents(values, parent, receipt, fallbackComputer, fallbackTarget
|
|
|
40198
40393
|
for (const value2 of values.slice(0, 128)) {
|
|
40199
40394
|
if (state.count >= 128) break;
|
|
40200
40395
|
const raw = object2(value2), id2 = childID.safeParse(raw.id), source = provider.safeParse(raw.provider);
|
|
40201
|
-
const
|
|
40396
|
+
const path86 = publicLabel(raw.path);
|
|
40202
40397
|
const callId = typeof raw.callId === "string" && raw.callId.length > 0 && raw.callId.length <= 200 ? raw.callId : void 0;
|
|
40203
40398
|
const routed = destination(raw, fallbackComputer, fallbackTarget);
|
|
40204
|
-
if (!id2.success || !source.success || !
|
|
40399
|
+
if (!id2.success || !source.success || !path86 || !callId || !routed) continue;
|
|
40205
40400
|
const descendant = lineage ? `${lineage}/${id2.data}` : id2.data;
|
|
40206
40401
|
const nestedSession = sessionId.safeParse(raw.session);
|
|
40207
40402
|
const cycleIdentity = nestedSession.success ? nestedSession.data : routed.remote.child ?? routed.remote.target.session;
|
|
@@ -40214,7 +40409,7 @@ function projectAgents(values, parent, receipt, fallbackComputer, fallbackTarget
|
|
|
40214
40409
|
projected.push({
|
|
40215
40410
|
id: publicID(parent, routed.computer.id, receipt.id, descendant),
|
|
40216
40411
|
provider: source.data,
|
|
40217
|
-
path:
|
|
40412
|
+
path: path86,
|
|
40218
40413
|
callId,
|
|
40219
40414
|
state: raw.failed === true ? "failed" : childState,
|
|
40220
40415
|
...typeof raw.finishedAt === "string" && Number.isFinite(Date.parse(raw.finishedAt)) ? { finishedAt: raw.finishedAt } : {},
|
|
@@ -40276,7 +40471,7 @@ init_logger();
|
|
|
40276
40471
|
init_client();
|
|
40277
40472
|
import { spawn as spawn5 } from "node:child_process";
|
|
40278
40473
|
import { lstat as lstat11, mkdtemp as mkdtemp3, readFile as readFile20, rm as rm6, writeFile as writeFile6 } from "node:fs/promises";
|
|
40279
|
-
import
|
|
40474
|
+
import path50 from "node:path";
|
|
40280
40475
|
import { Duplex } from "node:stream";
|
|
40281
40476
|
init_protocol();
|
|
40282
40477
|
var peerSchema = external_exports.object({
|
|
@@ -40288,7 +40483,7 @@ var peerSchema = external_exports.object({
|
|
|
40288
40483
|
server: serverName.default("default")
|
|
40289
40484
|
}).strict();
|
|
40290
40485
|
async function hookPeers(root = bridgeRoot()) {
|
|
40291
|
-
const file2 =
|
|
40486
|
+
const file2 = path50.join(root, "hooks.yaml");
|
|
40292
40487
|
const info = await lstat11(file2).catch((error62) => {
|
|
40293
40488
|
if (error62.code === "ENOENT") return void 0;
|
|
40294
40489
|
throw new BridgeError(409, `hooks.yaml could not be read (${error62.code ?? "unknown error"}).`);
|
|
@@ -40310,7 +40505,7 @@ async function addHookPeer(input2, root = bridgeRoot()) {
|
|
|
40310
40505
|
const clash = existing.find((other) => other.name === peer.name || other.address === peer.address && other.port === peer.port && other.server === peer.server);
|
|
40311
40506
|
if (clash) throw new BridgeError(409, `hooks.yaml already has ${clash.name} at ${clash.address}; remove that entry first to link it differently.`);
|
|
40312
40507
|
if (existing.length >= 32) throw new BridgeError(409, "hooks.yaml already has 32 computers.");
|
|
40313
|
-
await atomic(
|
|
40508
|
+
await atomic(path50.join(root, "hooks.yaml"), dump({ version: 1, computers: [...existing, peer] }, { lineWidth: -1 }));
|
|
40314
40509
|
return { added: true, peer };
|
|
40315
40510
|
}
|
|
40316
40511
|
async function optionalHookPeers(root = bridgeRoot()) {
|
|
@@ -40391,10 +40586,10 @@ async function peerRequest(peer, route2, data, timeout) {
|
|
|
40391
40586
|
const root = bridgeRoot(), key2 = dispatchKeyPath(root);
|
|
40392
40587
|
const info = await lstat11(key2).catch(() => void 0);
|
|
40393
40588
|
if (!info?.isFile() || info.isSymbolicLink() || info.mode & 63) throw new BridgeError(409, "Run phren bridge enroll-computer on this computer first (private key mode 0600).", { code: "dispatch-key-missing" });
|
|
40394
|
-
const temporary = await mkdtemp3(
|
|
40589
|
+
const temporary = await mkdtemp3(path50.join(root, "peer-"));
|
|
40395
40590
|
let child, stream;
|
|
40396
40591
|
try {
|
|
40397
|
-
const knownHosts =
|
|
40592
|
+
const knownHosts = path50.join(temporary, "known_hosts");
|
|
40398
40593
|
await writeFile6(knownHosts, `phren-peer ${peer.hostKey}
|
|
40399
40594
|
`, { mode: 384 });
|
|
40400
40595
|
const ssh2 = spawn5("ssh", peerSSHArgs(peer, knownHosts, key2), { stdio: ["pipe", "pipe", "pipe"] });
|
|
@@ -40531,21 +40726,21 @@ var receiptSchema2 = dispatchSchema.omit({ prompt: true }).extend({
|
|
|
40531
40726
|
async function dispatchProjectDirectory(project) {
|
|
40532
40727
|
const name = projectName.parse(project);
|
|
40533
40728
|
const source = readProjectConfig(phrenStoreRoot(), name).sourcePath;
|
|
40534
|
-
if (typeof source !== "string" || !
|
|
40729
|
+
if (typeof source !== "string" || !path51.isAbsolute(source) || /[\x00-\x1f\x7f]/.test(source)) throw new BridgeError(404, "Project has no absolute sourcePath on this computer.");
|
|
40535
40730
|
const directory = await realpath10(source).catch(() => void 0);
|
|
40536
40731
|
if (!directory || !(await stat15(directory)).isDirectory()) throw new BridgeError(404, "Project is not on this computer.");
|
|
40537
40732
|
return directory;
|
|
40538
40733
|
}
|
|
40539
40734
|
async function save(receipt) {
|
|
40540
|
-
const root =
|
|
40735
|
+
const root = path51.join(bridgeRoot(), "dispatches");
|
|
40541
40736
|
await mkdir12(root, { recursive: true, mode: 448 });
|
|
40542
|
-
await atomic(
|
|
40737
|
+
await atomic(path51.join(root, `${receipt.id}.json`), receipt);
|
|
40543
40738
|
}
|
|
40544
40739
|
var MAX_RECEIPT_BYTES = 65536;
|
|
40545
40740
|
var receiptUpdates = Promise.resolve();
|
|
40546
40741
|
function updateReceipt(receiptID, change) {
|
|
40547
40742
|
const run = receiptUpdates.then(async () => {
|
|
40548
|
-
const file2 =
|
|
40743
|
+
const file2 = path51.join(bridgeRoot(), "dispatches", `${external_exports.string().uuid().parse(receiptID)}.json`);
|
|
40549
40744
|
const info = await lstat12(file2).catch(() => void 0);
|
|
40550
40745
|
if (!info?.isFile() || info.isSymbolicLink() || info.size > MAX_RECEIPT_BYTES) return void 0;
|
|
40551
40746
|
const receipt = receiptSchema2.parse(JSON.parse(await readFile21(file2, "utf8")));
|
|
@@ -40573,12 +40768,12 @@ function failureReason(error62) {
|
|
|
40573
40768
|
return `${typeof code === "string" && !(error62 instanceof BridgeError) ? `${code}: ` : ""}${message}`.replace(/[\x00-\x1f\x7f]/g, " ").slice(0, 200);
|
|
40574
40769
|
}
|
|
40575
40770
|
async function dispatchStatus() {
|
|
40576
|
-
const root =
|
|
40771
|
+
const root = path51.join(bridgeRoot(), "dispatches");
|
|
40577
40772
|
const names = (await receiptNames(root)).filter((name) => /^[a-f0-9-]{36}\.json$/.test(name)).slice(0, 1024);
|
|
40578
40773
|
const receipts = [];
|
|
40579
40774
|
for (const name of names) {
|
|
40580
40775
|
try {
|
|
40581
|
-
const file2 =
|
|
40776
|
+
const file2 = path51.join(root, name);
|
|
40582
40777
|
const info = await lstat12(file2);
|
|
40583
40778
|
if (!info.isFile() || info.isSymbolicLink() || info.size > MAX_RECEIPT_BYTES) continue;
|
|
40584
40779
|
const receipt = receiptSchema2.parse(JSON.parse(await readFile21(file2, "utf8")));
|
|
@@ -40653,7 +40848,7 @@ var DispatchService = class {
|
|
|
40653
40848
|
if (!this.identity) throw new BridgeError(503, "This Hook cannot validate a dispatch parent.");
|
|
40654
40849
|
await validateDispatchParent(data, this.identity.computerID, this.identity.validateParentTarget);
|
|
40655
40850
|
}
|
|
40656
|
-
if ((await receiptNames(
|
|
40851
|
+
if ((await receiptNames(path51.join(bridgeRoot(), "dispatches"))).length >= 1024) throw new BridgeError(429, "Dispatch history is full. Archive old receipts before dispatching again.");
|
|
40657
40852
|
const here = this.local();
|
|
40658
40853
|
const toLocal = data.computer !== "anywhere" && isLocalComputer(data.computer, here.names);
|
|
40659
40854
|
const enrolled = await hookPeers().catch((error62) => {
|
|
@@ -41328,12 +41523,12 @@ init_zod();
|
|
|
41328
41523
|
init_protocol();
|
|
41329
41524
|
init_herdr();
|
|
41330
41525
|
init_transcripts();
|
|
41331
|
-
init_transcript_index();
|
|
41332
41526
|
import { execFile as execFile10 } from "node:child_process";
|
|
41333
41527
|
import { createHash as createHash12 } from "node:crypto";
|
|
41334
41528
|
import { mkdir as mkdir13, open as open12, stat as stat17, readFile as readFile22, writeFile as writeFile7 } from "node:fs/promises";
|
|
41335
|
-
import
|
|
41529
|
+
import path52 from "node:path";
|
|
41336
41530
|
import { promisify as promisify9 } from "node:util";
|
|
41531
|
+
init_transcript_index();
|
|
41337
41532
|
var exec9 = promisify9(execFile10);
|
|
41338
41533
|
var text3 = external_exports.string().trim().min(1).max(4e3).refine((t) => !/[\x00-\x08\x0b-\x1f\x7f]/.test(t));
|
|
41339
41534
|
var question = external_exports.object({ title: text3, options: external_exports.array(text3).max(12).nullable().optional() });
|
|
@@ -41377,7 +41572,7 @@ var answersQuestions = (reply, questions) => questions.every((q) => {
|
|
|
41377
41572
|
});
|
|
41378
41573
|
async function pendingAsyncQuestions(file2, targetID) {
|
|
41379
41574
|
return withTranscriptIndex(file2, async (handle, index2) => {
|
|
41380
|
-
const replies = [], acknowledged = /* @__PURE__ */ new Set(), resolved = /* @__PURE__ */ new Set(), pending = [];
|
|
41575
|
+
const replies = [], acknowledged = /* @__PURE__ */ new Set(), resolved = /* @__PURE__ */ new Set(), seen = /* @__PURE__ */ new Set(), pending = [];
|
|
41381
41576
|
let bytes = 0;
|
|
41382
41577
|
for await (const row of index2.rows(handle, index2.lines, Math.max(0, index2.lines - 1e4))) {
|
|
41383
41578
|
if (!row.bytes || (bytes += row.bytes.length) > 8388608) throw new BridgeError(413, "The pending question history is too large to verify.");
|
|
@@ -41403,10 +41598,11 @@ async function pendingAsyncQuestions(file2, targetID) {
|
|
|
41403
41598
|
if (targetID && resolved.has(targetID)) return [];
|
|
41404
41599
|
if (!id2 || !acknowledged.has(id2)) continue;
|
|
41405
41600
|
const questions = asyncQuestion(raw, id2);
|
|
41406
|
-
if (questions && !replies.some((reply) => answersQuestions(reply, questions))) {
|
|
41601
|
+
if (questions && !seen.has(id2) && !replies.some((reply) => answersQuestions(reply, questions))) {
|
|
41407
41602
|
pending.push({ id: id2, questions });
|
|
41408
41603
|
if (pending.length >= 64) throw new BridgeError(413, "Too many pending questions to verify.");
|
|
41409
41604
|
}
|
|
41605
|
+
if (questions) seen.add(id2);
|
|
41410
41606
|
if (targetID && questions && id2 === targetID) return pending.filter((p2) => p2.id === targetID);
|
|
41411
41607
|
}
|
|
41412
41608
|
if (index2.lines > 1e4) throw new BridgeError(413, "The pending question history is too large to verify.");
|
|
@@ -41419,10 +41615,11 @@ async function pendingAsyncQuestion(file2, id2) {
|
|
|
41419
41615
|
return pending.questions;
|
|
41420
41616
|
}
|
|
41421
41617
|
var CodexQuestions = class {
|
|
41422
|
-
|
|
41423
|
-
|
|
41618
|
+
/** No executable: the real `codex` on PATH, past phren's session wrapper. */
|
|
41619
|
+
constructor(configured) {
|
|
41620
|
+
this.configured = configured;
|
|
41424
41621
|
}
|
|
41425
|
-
|
|
41622
|
+
configured;
|
|
41426
41623
|
snapshots = /* @__PURE__ */ new Map();
|
|
41427
41624
|
failedSnapshots = /* @__PURE__ */ new Map();
|
|
41428
41625
|
inboxAvailable = false;
|
|
@@ -41432,6 +41629,9 @@ var CodexQuestions = class {
|
|
|
41432
41629
|
return this.inboxAvailable;
|
|
41433
41630
|
}
|
|
41434
41631
|
probe;
|
|
41632
|
+
get executable() {
|
|
41633
|
+
return this.configured ?? codexExecutable();
|
|
41634
|
+
}
|
|
41435
41635
|
supported() {
|
|
41436
41636
|
if (!this.probe || Date.now() - this.probe.at > 3e5) this.probe = { at: Date.now(), result: exec9(this.executable, ["queue", "--help"], { timeout: 5e3, maxBuffer: 65536 }).then(({ stdout }) => stdout.includes("--thread") && stdout.includes("--message")).catch(() => false).then((available) => {
|
|
41437
41637
|
this.inboxAvailable = available;
|
|
@@ -41458,7 +41658,7 @@ var CodexQuestions = class {
|
|
|
41458
41658
|
}
|
|
41459
41659
|
return Promise.all((pending ?? []).map(async (p) => {
|
|
41460
41660
|
const key2 = createHash12("sha256").update(JSON.stringify([target.source, target.session, p.id])).digest("hex");
|
|
41461
|
-
const submitted = await readFile22(
|
|
41661
|
+
const submitted = await readFile22(path52.join(bridgeRoot(), "question-replies", key2), "utf8").then((value2) => value2 === "submitted").catch(() => false);
|
|
41462
41662
|
return { toolUseId: p.id, isAsync: true, submitted, questions: p.questions.map((q) => ({
|
|
41463
41663
|
question: q.title,
|
|
41464
41664
|
options: (q.options ?? []).map((label2) => ({ label: label2 })),
|
|
@@ -41474,10 +41674,10 @@ var CodexQuestions = class {
|
|
|
41474
41674
|
const reply = questionReply(questions, data.answers);
|
|
41475
41675
|
const pane = await validateTarget(target);
|
|
41476
41676
|
if (await paneIdentity(target.server, pane, true) !== target.session) throw new BridgeError(409, "This pane's conversation changed. Reopen the chat.");
|
|
41477
|
-
const directory =
|
|
41677
|
+
const directory = path52.join(bridgeRoot(), "question-replies");
|
|
41478
41678
|
await mkdir13(directory, { recursive: true, mode: 448 });
|
|
41479
41679
|
const key2 = createHash12("sha256").update(JSON.stringify([target.source, target.session, id2])).digest("hex");
|
|
41480
|
-
const receiptPath =
|
|
41680
|
+
const receiptPath = path52.join(directory, key2);
|
|
41481
41681
|
const receipt = await open12(receiptPath, "wx", 384).catch((error62) => {
|
|
41482
41682
|
if (error62.code === "EEXIST") throw new BridgeError(409, "An answer was already submitted. Check the conversation before answering again.");
|
|
41483
41683
|
throw new BridgeError(503, "Phren could not record this answer. Nothing was sent.");
|
|
@@ -41502,10 +41702,10 @@ init_protocol();
|
|
|
41502
41702
|
import { spawn as spawn6 } from "node:child_process";
|
|
41503
41703
|
import { readdir as readdir11, readFile as readFile23, stat as stat18 } from "node:fs/promises";
|
|
41504
41704
|
import { homedir as homedir15 } from "node:os";
|
|
41505
|
-
import
|
|
41506
|
-
function readCodexModels(
|
|
41705
|
+
import path53 from "node:path";
|
|
41706
|
+
function readCodexModels(executable2 = codexExecutable()) {
|
|
41507
41707
|
return new Promise((resolve11) => {
|
|
41508
|
-
const child = spawn6(
|
|
41708
|
+
const child = spawn6(executable2, ["app-server"], { cwd: homedir15(), stdio: ["pipe", "pipe", "ignore"] });
|
|
41509
41709
|
let pending = "", bytes = 0, initialized = false, done = false;
|
|
41510
41710
|
const finish = (result = []) => {
|
|
41511
41711
|
if (done) return;
|
|
@@ -41581,12 +41781,12 @@ var CLAUDE_MENU = [
|
|
|
41581
41781
|
{ id: "claude-fable-5-1[1m]", name: "Fable 5.1 (1M context)", description: "Fable 5.1 with a 1M context window." }
|
|
41582
41782
|
];
|
|
41583
41783
|
async function readClaudeCatalog(configDir = claudeConfigDir(), installed) {
|
|
41584
|
-
const directory =
|
|
41784
|
+
const directory = path53.join(configDir, "cache", "model-catalog");
|
|
41585
41785
|
let newest;
|
|
41586
41786
|
try {
|
|
41587
41787
|
for (const name of await readdir11(directory)) {
|
|
41588
41788
|
if (!name.endsWith("-cc.json")) continue;
|
|
41589
|
-
const file2 =
|
|
41789
|
+
const file2 = path53.join(directory, name), at = (await stat18(file2)).mtimeMs;
|
|
41590
41790
|
if (!newest || at > newest.at) newest = { file: file2, at };
|
|
41591
41791
|
}
|
|
41592
41792
|
} catch {
|
|
@@ -41640,9 +41840,9 @@ function olderVersion(installed, required2) {
|
|
|
41640
41840
|
for (let index2 = 0; index2 < 3; index2++) if (have[index2] !== need[index2]) return have[index2] < need[index2];
|
|
41641
41841
|
return false;
|
|
41642
41842
|
}
|
|
41643
|
-
function claudeVersion(
|
|
41843
|
+
function claudeVersion(executable2 = "claude") {
|
|
41644
41844
|
return new Promise((resolve11) => {
|
|
41645
|
-
const child = spawn6(
|
|
41845
|
+
const child = spawn6(executable2, ["--version"], { cwd: homedir15(), stdio: ["ignore", "pipe", "ignore"] });
|
|
41646
41846
|
let out = "";
|
|
41647
41847
|
const timer = setTimeout(() => {
|
|
41648
41848
|
child.kill("SIGKILL");
|
|
@@ -41667,9 +41867,9 @@ async function readClaudeModels(configDir, installed) {
|
|
|
41667
41867
|
const live = await readClaudeCatalog(configDir, version3).catch(() => []);
|
|
41668
41868
|
return live.length ? live : CLAUDE_MENU.map((model) => ({ ...model }));
|
|
41669
41869
|
}
|
|
41670
|
-
async function readOpenCodeModels(
|
|
41870
|
+
async function readOpenCodeModels(executable2 = "opencode", configDir = path53.join(homedir15(), ".config/opencode")) {
|
|
41671
41871
|
const listed2 = await new Promise((resolve11) => {
|
|
41672
|
-
const child = spawn6(
|
|
41872
|
+
const child = spawn6(executable2, ["models"], { cwd: homedir15(), stdio: ["ignore", "pipe", "ignore"] });
|
|
41673
41873
|
let out = "", done = false;
|
|
41674
41874
|
const finish = () => {
|
|
41675
41875
|
if (!done) {
|
|
@@ -41694,7 +41894,7 @@ async function readOpenCodeModels(executable = "opencode", configDir = path52.jo
|
|
|
41694
41894
|
let configured;
|
|
41695
41895
|
for (const file2 of ["opencode.json", "opencode.jsonc"]) {
|
|
41696
41896
|
try {
|
|
41697
|
-
const text4 = await readFile23(
|
|
41897
|
+
const text4 = await readFile23(path53.join(configDir, file2), "utf8");
|
|
41698
41898
|
const model = /"model"\s*:\s*"([^"]+)"/.exec(text4)?.[1];
|
|
41699
41899
|
if (model) {
|
|
41700
41900
|
configured = model.slice(0, 200);
|
|
@@ -42164,14 +42364,14 @@ init_project_config();
|
|
|
42164
42364
|
init_shared();
|
|
42165
42365
|
import { randomUUID as randomUUID11 } from "node:crypto";
|
|
42166
42366
|
import { hostname as hostname6 } from "node:os";
|
|
42167
|
-
import
|
|
42367
|
+
import path56 from "node:path";
|
|
42168
42368
|
|
|
42169
42369
|
// src/bridge/schedule-format.ts
|
|
42170
42370
|
init_js_yaml();
|
|
42171
42371
|
init_zod();
|
|
42172
42372
|
init_protocol();
|
|
42173
42373
|
import { readFile as readFile24 } from "node:fs/promises";
|
|
42174
|
-
import
|
|
42374
|
+
import path54 from "node:path";
|
|
42175
42375
|
var SCHEDULE_EVERY = ["interval", "daily", "weekly", "once", "cron"];
|
|
42176
42376
|
var SCHEDULE_HARNESSES = ["claude", "codex", "opencode"];
|
|
42177
42377
|
var SCHEDULE_NOTIFY = ["start", "finish", "failure"];
|
|
@@ -42184,7 +42384,7 @@ var scheduleName = singleLine(80);
|
|
|
42184
42384
|
var timestamp3 = external_exports.string().datetime({ offset: true });
|
|
42185
42385
|
var localTimestamp = external_exports.string().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/);
|
|
42186
42386
|
var clockTime = external_exports.string().regex(/^(?:[01]\d|2[0-3]):[0-5]\d$/);
|
|
42187
|
-
var schedulePath = (projectDir) =>
|
|
42387
|
+
var schedulePath = (projectDir) => path54.join(projectDir, "schedules.yaml");
|
|
42188
42388
|
var runningStatuses = /* @__PURE__ */ new Set(["launched", "running", "blocked"]);
|
|
42189
42389
|
var MAX_SCHEDULES = 64;
|
|
42190
42390
|
var MAX_RUNS = 2e3;
|
|
@@ -42384,7 +42584,7 @@ async function writeScheduleRuns(file2, runs) {
|
|
|
42384
42584
|
await atomicInPrivateDir(file2, kept.map((run) => JSON.stringify(run)).join("\n") + (kept.length ? "\n" : ""));
|
|
42385
42585
|
}
|
|
42386
42586
|
function scheduleRunsFile() {
|
|
42387
|
-
return
|
|
42587
|
+
return path54.join(bridgeRoot(), "schedule-runs.jsonl");
|
|
42388
42588
|
}
|
|
42389
42589
|
|
|
42390
42590
|
// src/bridge/schedule-launch.ts
|
|
@@ -42398,7 +42598,7 @@ init_shared();
|
|
|
42398
42598
|
import { spawn as spawn7 } from "node:child_process";
|
|
42399
42599
|
import { createWriteStream } from "node:fs";
|
|
42400
42600
|
import { mkdir as mkdir14, readFile as readFile25, stat as stat19 } from "node:fs/promises";
|
|
42401
|
-
import
|
|
42601
|
+
import path55 from "node:path";
|
|
42402
42602
|
import { finished as streamFinished } from "node:stream/promises";
|
|
42403
42603
|
var CLAUDE_SCHEDULE_SETTINGS = JSON.stringify({ enableAllProjectMcpServers: true });
|
|
42404
42604
|
function createScheduleLauncher(launchHerdr, store = defaultPhrenPath()) {
|
|
@@ -42431,7 +42631,7 @@ async function resumeScheduleRun(run, schedule, signal, watch2 = watchHerdrRun)
|
|
|
42431
42631
|
);
|
|
42432
42632
|
}
|
|
42433
42633
|
if (launch2.mode === "headless" && launch2.jobDir) {
|
|
42434
|
-
const manifest = await readFile25(
|
|
42634
|
+
const manifest = await readFile25(path55.join(launch2.jobDir, "manifest.json"), "utf8").then((text4) => JSON.parse(text4)).catch(() => void 0);
|
|
42435
42635
|
if (manifest?.status === "completed") return { status: "finished" };
|
|
42436
42636
|
if (manifest?.status === "failed") {
|
|
42437
42637
|
return { status: "failed", reason: typeof manifest.exitCode === "number" ? `The scheduled agent exited with code ${manifest.exitCode}.` : "The scheduled agent failed." };
|
|
@@ -42479,7 +42679,7 @@ async function promptWhenReady(server, paneId, text4, signal, waitMs = 6e4) {
|
|
|
42479
42679
|
}
|
|
42480
42680
|
}
|
|
42481
42681
|
async function launchHeadless(context, store, started) {
|
|
42482
|
-
const root = fanoutRoot({ ...process.env, PHREN_PATH: store }), jobDir =
|
|
42682
|
+
const root = fanoutRoot({ ...process.env, PHREN_PATH: store }), jobDir = path55.join(root, context.runId);
|
|
42483
42683
|
await mkdir14(jobDir, { recursive: true, mode: 448 });
|
|
42484
42684
|
const eventLog = "events.jsonl", now = (/* @__PURE__ */ new Date()).toISOString();
|
|
42485
42685
|
const manifest = {
|
|
@@ -42499,7 +42699,7 @@ async function launchHeadless(context, store, started) {
|
|
|
42499
42699
|
};
|
|
42500
42700
|
await writeManifest2(jobDir, manifest);
|
|
42501
42701
|
const command = headlessCommand(context.schedule, context.cwd);
|
|
42502
|
-
if (context.schedule.harness === "codex") await ensureCodexDirTrusted(context.cwd).catch((error62) => logger.warn("schedule", `Could not mark ${
|
|
42702
|
+
if (context.schedule.harness === "codex") await ensureCodexDirTrusted(context.cwd).catch((error62) => logger.warn("schedule", `Could not mark ${path55.basename(context.cwd)} trusted for Codex (run ${context.runId}): ${error62 instanceof Error ? error62.message.split("\n")[0] : String(error62)}`));
|
|
42503
42703
|
let child;
|
|
42504
42704
|
try {
|
|
42505
42705
|
child = spawn7(command.file, command.args, { cwd: command.cwd, env: process.env, stdio: ["pipe", "pipe", "pipe"] });
|
|
@@ -42511,8 +42711,8 @@ async function launchHeadless(context, store, started) {
|
|
|
42511
42711
|
const closed = new Promise((resolve11) => {
|
|
42512
42712
|
child.once("close", (code, signal) => resolve11({ code, signal }));
|
|
42513
42713
|
});
|
|
42514
|
-
const output2 = createWriteStream(
|
|
42515
|
-
const errors = createWriteStream(
|
|
42714
|
+
const output2 = createWriteStream(path55.join(jobDir, eventLog), { flags: "a", mode: 384 });
|
|
42715
|
+
const errors = createWriteStream(path55.join(jobDir, "stderr.log"), { flags: "a", mode: 384 });
|
|
42516
42716
|
const streamsFinished = Promise.all([streamFinished(output2), streamFinished(errors)]).then(() => void 0).catch(() => void 0);
|
|
42517
42717
|
child.stdin?.on("error", () => {
|
|
42518
42718
|
});
|
|
@@ -42565,7 +42765,7 @@ function tomlQuote(value2) {
|
|
|
42565
42765
|
}
|
|
42566
42766
|
async function ensureCodexDirTrusted(cwd) {
|
|
42567
42767
|
const directory = codexHome();
|
|
42568
|
-
const file2 =
|
|
42768
|
+
const file2 = path55.join(directory, "config.toml");
|
|
42569
42769
|
let text4 = "";
|
|
42570
42770
|
try {
|
|
42571
42771
|
text4 = await readFile25(file2, "utf8");
|
|
@@ -42602,7 +42802,7 @@ ${trustLine}
|
|
|
42602
42802
|
await atomic(file2, next, mode);
|
|
42603
42803
|
}
|
|
42604
42804
|
async function writeManifest2(jobDir, manifest) {
|
|
42605
|
-
await atomicInPrivateDir(
|
|
42805
|
+
await atomicInPrivateDir(path55.join(jobDir, "manifest.json"), JSON.stringify(manifest, null, 2) + "\n");
|
|
42606
42806
|
}
|
|
42607
42807
|
|
|
42608
42808
|
// src/bridge/schedules.ts
|
|
@@ -42640,7 +42840,7 @@ var Scheduler = class {
|
|
|
42640
42840
|
return getProjectDirs(this.store);
|
|
42641
42841
|
}
|
|
42642
42842
|
projectDirectory(project) {
|
|
42643
|
-
const found = this.projectDirectories().find((directory) =>
|
|
42843
|
+
const found = this.projectDirectories().find((directory) => path56.basename(directory).toLowerCase() === project.toLowerCase());
|
|
42644
42844
|
if (!found) throw new BridgeError(404, `Unknown project "${project}".`);
|
|
42645
42845
|
return found;
|
|
42646
42846
|
}
|
|
@@ -42666,7 +42866,7 @@ var Scheduler = class {
|
|
|
42666
42866
|
} catch {
|
|
42667
42867
|
continue;
|
|
42668
42868
|
}
|
|
42669
|
-
const project =
|
|
42869
|
+
const project = path56.basename(directory);
|
|
42670
42870
|
for (const schedule of schedules) {
|
|
42671
42871
|
const matching = runs.filter((run) => run.project === project && run.scheduleId === schedule.id);
|
|
42672
42872
|
const last = matching.at(-1), running2 = matching.some((run) => runningStatuses.has(run.status));
|
|
@@ -42696,7 +42896,7 @@ var Scheduler = class {
|
|
|
42696
42896
|
}
|
|
42697
42897
|
async launchNow(projectName2, id2) {
|
|
42698
42898
|
const prepared = await this.exclusive(async () => {
|
|
42699
|
-
const projectDir = this.projectDirectory(projectName2), project =
|
|
42899
|
+
const projectDir = this.projectDirectory(projectName2), project = path56.basename(projectDir);
|
|
42700
42900
|
const file2 = await readScheduleDocument(projectDir), schedule = file2.schedules.find((item) => item.id === id2);
|
|
42701
42901
|
if (!schedule) throw new BridgeError(404, `Schedule "${id2}" was not found in ${project}.`);
|
|
42702
42902
|
if (!computerMatches(schedule.computer, this.computer())) throw new BridgeError(409, `${schedule.computer} owns this schedule; run it from that computer.`);
|
|
@@ -42857,7 +43057,7 @@ var Scheduler = class {
|
|
|
42857
43057
|
init_phren_paths();
|
|
42858
43058
|
import { lstat as lstat14, mkdtemp as mkdtemp4, realpath as realpath11, rm as rm7 } from "node:fs/promises";
|
|
42859
43059
|
import { hostname as hostname8, tmpdir } from "node:os";
|
|
42860
|
-
import
|
|
43060
|
+
import path60 from "node:path";
|
|
42861
43061
|
|
|
42862
43062
|
// src/bridge/health.ts
|
|
42863
43063
|
init_policy();
|
|
@@ -42866,7 +43066,7 @@ init_store_registry();
|
|
|
42866
43066
|
import { execFile as execFile11, spawn as spawn8 } from "node:child_process";
|
|
42867
43067
|
import { lstat as lstat13, readFile as readFile26 } from "node:fs/promises";
|
|
42868
43068
|
import { homedir as homedir16, hostname as hostname7 } from "node:os";
|
|
42869
|
-
import
|
|
43069
|
+
import path59 from "node:path";
|
|
42870
43070
|
import { promisify as promisify10 } from "node:util";
|
|
42871
43071
|
init_protocol();
|
|
42872
43072
|
init_metrics();
|
|
@@ -42894,12 +43094,12 @@ var VERSION_TIMEOUT_MS = 3e3;
|
|
|
42894
43094
|
var VERSION_CACHE_MS = 5 * 6e4;
|
|
42895
43095
|
var PEER_TIMEOUT_MS = 5e3;
|
|
42896
43096
|
var versionCache = /* @__PURE__ */ new Map();
|
|
42897
|
-
function toolVersion(tool,
|
|
43097
|
+
function toolVersion(tool, executable2 = tool) {
|
|
42898
43098
|
const cached2 = versionCache.get(tool);
|
|
42899
43099
|
if (cached2 && Date.now() - cached2.at < VERSION_CACHE_MS) return cached2.value;
|
|
42900
43100
|
const value2 = new Promise((resolve11) => {
|
|
42901
43101
|
let out = "", done = false;
|
|
42902
|
-
const child = spawn8(
|
|
43102
|
+
const child = spawn8(executable2, ["--version"], { cwd: homedir16(), stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, NO_COLOR: "1" } });
|
|
42903
43103
|
const finish = (result) => {
|
|
42904
43104
|
if (!done) {
|
|
42905
43105
|
done = true;
|
|
@@ -42980,7 +43180,7 @@ async function lastScheduledRun(store, runsFile = scheduleRunsFile()) {
|
|
|
42980
43180
|
const last = runs.reduce((newest, run) => !newest || run.startedAt >= newest.startedAt ? run : newest, void 0);
|
|
42981
43181
|
if (!last) return null;
|
|
42982
43182
|
let name;
|
|
42983
|
-
const directory = getProjectDirs(store).find((dir) =>
|
|
43183
|
+
const directory = getProjectDirs(store).find((dir) => path59.basename(dir).toLowerCase() === last.project.toLowerCase());
|
|
42984
43184
|
if (directory) name = (await readScheduleDocument(directory).catch(() => void 0))?.schedules.find((item) => item.id === last.scheduleId)?.name;
|
|
42985
43185
|
return {
|
|
42986
43186
|
...name ? { name } : {},
|
|
@@ -43034,7 +43234,7 @@ async function probePeer(peer, caller) {
|
|
|
43034
43234
|
}
|
|
43035
43235
|
}
|
|
43036
43236
|
function canaryFile(root = bridgeRoot()) {
|
|
43037
|
-
return
|
|
43237
|
+
return path59.join(root, "canary.json");
|
|
43038
43238
|
}
|
|
43039
43239
|
async function readCanary(root = bridgeRoot()) {
|
|
43040
43240
|
try {
|
|
@@ -43047,7 +43247,7 @@ async function readCanary(root = bridgeRoot()) {
|
|
|
43047
43247
|
}
|
|
43048
43248
|
}
|
|
43049
43249
|
async function pushConfigured() {
|
|
43050
|
-
const file2 = process.env.PHREN_APNS_CONFIG ||
|
|
43250
|
+
const file2 = process.env.PHREN_APNS_CONFIG || path59.join(bridgeRoot(), "apns.json");
|
|
43051
43251
|
const info = await lstat13(file2).catch(() => void 0);
|
|
43052
43252
|
return { configured: !!info?.isFile() };
|
|
43053
43253
|
}
|
|
@@ -43136,7 +43336,7 @@ async function closeCanaryWorkspaces(server, before, created) {
|
|
|
43136
43336
|
}
|
|
43137
43337
|
async function conductorStep(options, server) {
|
|
43138
43338
|
const before = new Set(objects((await snapshot(server)).workspaces).map((workspace) => String(workspace.workspace_id)));
|
|
43139
|
-
const folder = await realpath11(await mkdtemp4(
|
|
43339
|
+
const folder = await realpath11(await mkdtemp4(path60.join(tmpdir(), "phren-canary-")));
|
|
43140
43340
|
let created, failure2, detail;
|
|
43141
43341
|
try {
|
|
43142
43342
|
const launched = await options.launch(server, { role: "conductor", kind: "claude", label: CANARY_LABEL, cwd: folder, timeoutMs: 45e3 });
|
|
@@ -43157,12 +43357,12 @@ async function scheduleStep(options) {
|
|
|
43157
43357
|
let count2 = 0;
|
|
43158
43358
|
const broken = [];
|
|
43159
43359
|
for (const directory of getProjectDirs(options.store)) {
|
|
43160
|
-
const present2 = await lstat14(
|
|
43360
|
+
const present2 = await lstat14(path60.join(directory, "schedules.yaml")).catch(() => void 0);
|
|
43161
43361
|
if (!present2) continue;
|
|
43162
43362
|
try {
|
|
43163
43363
|
count2 += (await readScheduleDocument(directory)).schedules.length;
|
|
43164
43364
|
} catch (error62) {
|
|
43165
|
-
broken.push(`${
|
|
43365
|
+
broken.push(`${path60.basename(directory)}: ${reason(error62)}`);
|
|
43166
43366
|
}
|
|
43167
43367
|
}
|
|
43168
43368
|
const tick = options.scheduler.lastTickAt;
|
|
@@ -43232,7 +43432,7 @@ function runCanary(options) {
|
|
|
43232
43432
|
}
|
|
43233
43433
|
async function dailyCanaryEnabled(root = bridgeRoot()) {
|
|
43234
43434
|
if (process.env.PHREN_CANARY_DAILY === "1") return true;
|
|
43235
|
-
return !!(await lstat14(
|
|
43435
|
+
return !!(await lstat14(path60.join(root, "canary-daily")).catch(() => void 0))?.isFile();
|
|
43236
43436
|
}
|
|
43237
43437
|
async function dailyCanaryDue(root = bridgeRoot(), now = Date.now()) {
|
|
43238
43438
|
if (running || !await dailyCanaryEnabled(root)) return false;
|
|
@@ -43245,11 +43445,11 @@ init_shared();
|
|
|
43245
43445
|
|
|
43246
43446
|
// src/bridge/server-routes.ts
|
|
43247
43447
|
init_zod();
|
|
43248
|
-
import
|
|
43448
|
+
import path83 from "node:path";
|
|
43249
43449
|
|
|
43250
43450
|
// src/bridge/code-note.ts
|
|
43251
43451
|
init_zod();
|
|
43252
|
-
import * as
|
|
43452
|
+
import * as path66 from "node:path";
|
|
43253
43453
|
|
|
43254
43454
|
// src/content/validate.ts
|
|
43255
43455
|
init_utils_helpers();
|
|
@@ -43263,7 +43463,7 @@ init_store_routing();
|
|
|
43263
43463
|
init_locks();
|
|
43264
43464
|
init_data_utils();
|
|
43265
43465
|
import * as fs28 from "fs";
|
|
43266
|
-
import * as
|
|
43466
|
+
import * as path62 from "path";
|
|
43267
43467
|
import * as crypto7 from "crypto";
|
|
43268
43468
|
|
|
43269
43469
|
// src/project-topics.ts
|
|
@@ -43275,7 +43475,7 @@ init_data_utils();
|
|
|
43275
43475
|
init_filenames();
|
|
43276
43476
|
import * as crypto6 from "crypto";
|
|
43277
43477
|
import * as fs27 from "fs";
|
|
43278
|
-
import * as
|
|
43478
|
+
import * as path61 from "path";
|
|
43279
43479
|
var TOPIC_CONFIG_FILENAME = "topic-config.json";
|
|
43280
43480
|
var SOFTWARE_TOPICS = [
|
|
43281
43481
|
{
|
|
@@ -43813,7 +44013,7 @@ function topicDocHeader(project, topic) {
|
|
|
43813
44013
|
}
|
|
43814
44014
|
function appendArchivedEntriesToTopicDoc(filePath, project, topic, entries2) {
|
|
43815
44015
|
if (entries2.length === 0) return;
|
|
43816
|
-
fs27.mkdirSync(
|
|
44016
|
+
fs27.mkdirSync(path61.dirname(filePath), { recursive: true });
|
|
43817
44017
|
withFileLock(filePath, () => {
|
|
43818
44018
|
let existing = "";
|
|
43819
44019
|
if (fs27.existsSync(filePath)) existing = fs27.readFileSync(filePath, "utf8");
|
|
@@ -43932,7 +44132,7 @@ function autoArchiveToReference(phrenPath, project, keepCount) {
|
|
|
43932
44132
|
if (!isValidProjectName(project)) return phrenErr(`Invalid project name: "${project}".`, PhrenError.INVALID_PROJECT_NAME);
|
|
43933
44133
|
const resolvedDir = storeAwareProjectPath(phrenPath, project);
|
|
43934
44134
|
if (!resolvedDir || !fs28.existsSync(resolvedDir)) return phrenErr(`Project "${project}" not found in phren.`, PhrenError.PROJECT_NOT_FOUND);
|
|
43935
|
-
const learningsPath =
|
|
44135
|
+
const learningsPath = path62.join(resolvedDir, FINDINGS_FILENAME);
|
|
43936
44136
|
if (!fs28.existsSync(learningsPath)) return phrenOk(0);
|
|
43937
44137
|
const STALE_LOCK_MS = 6e5;
|
|
43938
44138
|
const lockFile = runtimeFile(phrenPath, `consolidation-${project}.lock`);
|
|
@@ -43968,7 +44168,7 @@ function autoArchiveToReference(phrenPath, project, keepCount) {
|
|
|
43968
44168
|
const entries2 = parseActiveEntries(content);
|
|
43969
44169
|
if (entries2.length <= keepCount) return phrenOk(0);
|
|
43970
44170
|
const toArchive = entries2.slice(0, entries2.length - keepCount);
|
|
43971
|
-
const referenceDir =
|
|
44171
|
+
const referenceDir = path62.join(resolvedDir, "reference");
|
|
43972
44172
|
const { topics } = readProjectTopics(phrenPath, project);
|
|
43973
44173
|
const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
|
|
43974
44174
|
const archivedSet = buildArchivedBulletSet(referenceDir);
|
|
@@ -44532,7 +44732,7 @@ var DEFAULT_DECAY = {
|
|
|
44532
44732
|
var DEFAULT_UNDATED_CONFIDENCE = DEFAULT_DECAY.d120;
|
|
44533
44733
|
|
|
44534
44734
|
// src/content/dedup.ts
|
|
44535
|
-
import * as
|
|
44735
|
+
import * as path63 from "path";
|
|
44536
44736
|
init_shared();
|
|
44537
44737
|
init_utils();
|
|
44538
44738
|
init_store_routing();
|
|
@@ -44656,7 +44856,7 @@ function resolveCoref(text4, context) {
|
|
|
44656
44856
|
result = result.replace(/\bthe project\b/gi, context.project);
|
|
44657
44857
|
}
|
|
44658
44858
|
if (context.file) {
|
|
44659
|
-
const basename12 =
|
|
44859
|
+
const basename12 = path63.basename(context.file);
|
|
44660
44860
|
result = result.replace(/\b(this file|the file)\b/gi, basename12);
|
|
44661
44861
|
}
|
|
44662
44862
|
if (context.project && /\b(it|this|that|they|them)\b/i.test(result)) {
|
|
@@ -44673,7 +44873,7 @@ init_shared();
|
|
|
44673
44873
|
init_shared();
|
|
44674
44874
|
init_governance();
|
|
44675
44875
|
import * as fs30 from "fs";
|
|
44676
|
-
import * as
|
|
44876
|
+
import * as path65 from "path";
|
|
44677
44877
|
import * as crypto8 from "crypto";
|
|
44678
44878
|
|
|
44679
44879
|
// src/finding-graph-id.ts
|
|
@@ -44708,7 +44908,7 @@ init_store_routing();
|
|
|
44708
44908
|
// src/finding/context.ts
|
|
44709
44909
|
init_utils();
|
|
44710
44910
|
import * as fs29 from "fs";
|
|
44711
|
-
import * as
|
|
44911
|
+
import * as path64 from "path";
|
|
44712
44912
|
|
|
44713
44913
|
// src/session/utils.ts
|
|
44714
44914
|
init_utils();
|
|
@@ -44790,14 +44990,14 @@ function resolveFindingTaskReference(phrenPath, project, match) {
|
|
|
44790
44990
|
const projectDir = safeProjectPath(phrenPath, project);
|
|
44791
44991
|
if (!projectDir) return { error: `Invalid project name: "${project}".` };
|
|
44792
44992
|
const taskPath = resolveTaskFilePath(phrenPath, project);
|
|
44793
|
-
const items = parseTaskItems(taskPath ??
|
|
44993
|
+
const items = parseTaskItems(taskPath ?? path64.join(projectDir, "tasks.md"));
|
|
44794
44994
|
return resolveTaskItemMatch(items, match);
|
|
44795
44995
|
}
|
|
44796
44996
|
function resolveAutoFindingTaskItem(phrenPath, project) {
|
|
44797
44997
|
const projectDir = safeProjectPath(phrenPath, project);
|
|
44798
44998
|
if (!projectDir) return void 0;
|
|
44799
44999
|
const taskPath = resolveTaskFilePath(phrenPath, project);
|
|
44800
|
-
const active = parseTaskItems(taskPath ??
|
|
45000
|
+
const active = parseTaskItems(taskPath ?? path64.join(projectDir, "tasks.md")).filter(
|
|
44801
45001
|
(item) => item.section === "Active" && item.stableId
|
|
44802
45002
|
);
|
|
44803
45003
|
if (active.length === 1) return active[0].stableId;
|
|
@@ -44837,7 +45037,7 @@ function buildFindingCitation(citationInput, nowIso, inferredRepo, headCommit) {
|
|
|
44837
45037
|
function resolveInferredCitationRepo(citationInput) {
|
|
44838
45038
|
if (citationInput?.repo) return citationInput.repo;
|
|
44839
45039
|
if (citationInput?.file) {
|
|
44840
|
-
const fileDir =
|
|
45040
|
+
const fileDir = path65.dirname(citationInput.file);
|
|
44841
45041
|
return getRepoRoot(fileDir);
|
|
44842
45042
|
}
|
|
44843
45043
|
return void 0;
|
|
@@ -44972,7 +45172,7 @@ function addFindingToFile(phrenPath, project, learning, citationInput, opts) {
|
|
|
44972
45172
|
if (!isValidProjectName(project)) return phrenErr(`Invalid project name: "${project}".`, PhrenError.INVALID_PROJECT_NAME);
|
|
44973
45173
|
const resolvedDir = storeAwareProjectPath(phrenPath, project);
|
|
44974
45174
|
if (!resolvedDir) return phrenErr(`Invalid project name: "${project}".`, PhrenError.INVALID_PROJECT_NAME);
|
|
44975
|
-
const learningsPath =
|
|
45175
|
+
const learningsPath = path65.join(resolvedDir, FINDINGS_FILENAME);
|
|
44976
45176
|
const nowIso = (opts?.now ?? /* @__PURE__ */ new Date()).toISOString();
|
|
44977
45177
|
const today = nowIso.slice(0, 10);
|
|
44978
45178
|
const resolvedCitationInputResult = resolveFindingCitationInput(phrenPath, project, citationInput);
|
|
@@ -45154,7 +45354,7 @@ var codeNoteSchema = external_exports.object({
|
|
|
45154
45354
|
// phone's spelling, accepted until 0.3.1.
|
|
45155
45355
|
name: external_exports.string().min(1).max(4600).optional(),
|
|
45156
45356
|
symbol: external_exports.string().min(1).max(4600).optional(),
|
|
45157
|
-
file: external_exports.string().min(1).max(4096).refine((file2) => !
|
|
45357
|
+
file: external_exports.string().min(1).max(4096).refine((file2) => !path66.isAbsolute(file2) && !file2.includes("\0") && !file2.split(/[\\/]/).includes("..")),
|
|
45158
45358
|
line: external_exports.number().int().positive(),
|
|
45159
45359
|
text: external_exports.string().trim().min(1).max(4500).refine((text4) => !/[\x00-\x08\x0b-\x1f\x7f]/.test(text4)),
|
|
45160
45360
|
target: external_exports.union([external_exports.object({ session: sessionId }).strict(), external_exports.object({ harness: external_exports.enum(["codex", "claude", "opencode"]) }).strict()]).optional()
|
|
@@ -45209,24 +45409,24 @@ import { promisify as promisify11 } from "node:util";
|
|
|
45209
45409
|
import { realpathSync as realpathSync5 } from "node:fs";
|
|
45210
45410
|
import { readdir as readdir12, readFile as readFile27, stat as stat20, mkdir as mkdir15 } from "node:fs/promises";
|
|
45211
45411
|
import { homedir as homedir17 } from "node:os";
|
|
45212
|
-
import
|
|
45412
|
+
import path71 from "node:path";
|
|
45213
45413
|
|
|
45214
45414
|
// src/core/project.ts
|
|
45215
45415
|
init_shared();
|
|
45216
|
-
import * as
|
|
45416
|
+
import * as path69 from "path";
|
|
45217
45417
|
|
|
45218
45418
|
// src/core/project-registry.ts
|
|
45219
45419
|
init_phren_paths();
|
|
45220
45420
|
import * as fs32 from "fs";
|
|
45221
|
-
import * as
|
|
45421
|
+
import * as path68 from "path";
|
|
45222
45422
|
|
|
45223
45423
|
// src/git-worktree.ts
|
|
45224
45424
|
import * as fs31 from "fs";
|
|
45225
|
-
import * as
|
|
45425
|
+
import * as path67 from "path";
|
|
45226
45426
|
var WORKTREE_CONTAINER_NAMES = /* @__PURE__ */ new Set(["worktrees", ".worktrees"]);
|
|
45227
|
-
var LINKED_WORKTREE_SEGMENT = `${
|
|
45427
|
+
var LINKED_WORKTREE_SEGMENT = `${path67.sep}.git${path67.sep}worktrees${path67.sep}`;
|
|
45228
45428
|
function resolveWorktreeParent(dir) {
|
|
45229
|
-
const resolved =
|
|
45429
|
+
const resolved = path67.resolve(dir);
|
|
45230
45430
|
const agentParent = parentFromAgentWorktreePath(resolved);
|
|
45231
45431
|
if (agentParent) return { repoRoot: agentParent, reason: "agent-worktree-dir" };
|
|
45232
45432
|
const linkedParent = parentFromLinkedWorktree(resolved);
|
|
@@ -45234,23 +45434,23 @@ function resolveWorktreeParent(dir) {
|
|
|
45234
45434
|
return null;
|
|
45235
45435
|
}
|
|
45236
45436
|
function parentFromAgentWorktreePath(resolved) {
|
|
45237
|
-
const segments = resolved.split(
|
|
45437
|
+
const segments = resolved.split(path67.sep);
|
|
45238
45438
|
for (let i = 1; i < segments.length; i++) {
|
|
45239
45439
|
if (!WORKTREE_CONTAINER_NAMES.has(segments[i])) continue;
|
|
45240
45440
|
let j = i - 1;
|
|
45241
45441
|
if (!segments[j]?.startsWith(".")) continue;
|
|
45242
45442
|
while (j >= 1 && segments[j].startsWith(".")) j--;
|
|
45243
45443
|
if (j < 1) continue;
|
|
45244
|
-
return segments.slice(0, j + 1).join(
|
|
45444
|
+
return segments.slice(0, j + 1).join(path67.sep) || path67.sep;
|
|
45245
45445
|
}
|
|
45246
45446
|
return null;
|
|
45247
45447
|
}
|
|
45248
45448
|
function parentFromLinkedWorktree(resolved) {
|
|
45249
45449
|
let current2 = resolved;
|
|
45250
45450
|
while (true) {
|
|
45251
|
-
const parent = repoRootFromGitFile(
|
|
45451
|
+
const parent = repoRootFromGitFile(path67.join(current2, ".git"));
|
|
45252
45452
|
if (parent) return parent;
|
|
45253
|
-
const next =
|
|
45453
|
+
const next = path67.dirname(current2);
|
|
45254
45454
|
if (next === current2) return null;
|
|
45255
45455
|
current2 = next;
|
|
45256
45456
|
}
|
|
@@ -45265,7 +45465,7 @@ function repoRootFromGitFile(gitPath) {
|
|
|
45265
45465
|
}
|
|
45266
45466
|
const match = raw.match(/^\s*gitdir:\s*(.+?)\s*$/m);
|
|
45267
45467
|
if (!match) return null;
|
|
45268
|
-
const gitDir =
|
|
45468
|
+
const gitDir = path67.resolve(path67.dirname(gitPath), match[1].replace(/[/\\]/g, path67.sep));
|
|
45269
45469
|
const idx = gitDir.indexOf(LINKED_WORKTREE_SEGMENT);
|
|
45270
45470
|
if (idx === -1) return null;
|
|
45271
45471
|
return gitDir.slice(0, idx);
|
|
@@ -45478,7 +45678,7 @@ function scoreTopicsFromTerms(domain2, terms, docsText) {
|
|
|
45478
45678
|
return topics;
|
|
45479
45679
|
}
|
|
45480
45680
|
function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
|
|
45481
|
-
const resolvedRoot =
|
|
45681
|
+
const resolvedRoot = path68.resolve(repoRoot);
|
|
45482
45682
|
if (!fs32.existsSync(resolvedRoot)) return null;
|
|
45483
45683
|
const signal = {
|
|
45484
45684
|
domainScores: { software: 0, music: 0, game: 0, research: 0, writing: 0, creative: 0, other: 0 },
|
|
@@ -45489,7 +45689,7 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
|
|
|
45489
45689
|
usefulSignals: 0
|
|
45490
45690
|
};
|
|
45491
45691
|
const skipDirs = /* @__PURE__ */ new Set([".git", ".phren", "node_modules", "dist", "build", "coverage", ".next", ".turbo", "target"]);
|
|
45492
|
-
const packageJsonPath =
|
|
45692
|
+
const packageJsonPath = path68.join(resolvedRoot, "package.json");
|
|
45493
45693
|
if (fs32.existsSync(packageJsonPath)) {
|
|
45494
45694
|
signal.usefulSignals++;
|
|
45495
45695
|
addDomainScores(signal.domainScores, DOMAIN_CONFIG_HINTS["package.json"]);
|
|
@@ -45519,33 +45719,33 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
|
|
|
45519
45719
|
debugLog(`inferInitScaffoldFromRepo package.json parse failed: ${errorMessage(err)}`);
|
|
45520
45720
|
}
|
|
45521
45721
|
}
|
|
45522
|
-
const topLevelConfigs = Object.keys(DOMAIN_CONFIG_HINTS).filter((fileName) => fs32.existsSync(
|
|
45722
|
+
const topLevelConfigs = Object.keys(DOMAIN_CONFIG_HINTS).filter((fileName) => fs32.existsSync(path68.join(resolvedRoot, fileName)));
|
|
45523
45723
|
for (const configName of topLevelConfigs) {
|
|
45524
45724
|
signal.usefulSignals++;
|
|
45525
45725
|
const configScore = DOMAIN_CONFIG_HINTS[configName];
|
|
45526
45726
|
if (configScore) addDomainScores(signal.domainScores, configScore);
|
|
45527
45727
|
}
|
|
45528
45728
|
const readmeCandidates = [
|
|
45529
|
-
|
|
45530
|
-
|
|
45729
|
+
path68.join(resolvedRoot, "README.md"),
|
|
45730
|
+
path68.join(resolvedRoot, "readme.md")
|
|
45531
45731
|
];
|
|
45532
45732
|
for (const readmePath of readmeCandidates) {
|
|
45533
45733
|
if (!fs32.existsSync(readmePath)) continue;
|
|
45534
45734
|
const content = maybeReadUtf8(readmePath);
|
|
45535
45735
|
if (!content) continue;
|
|
45536
45736
|
signal.usefulSignals++;
|
|
45537
|
-
signal.referenceHints.push(
|
|
45737
|
+
signal.referenceHints.push(path68.relative(resolvedRoot, readmePath));
|
|
45538
45738
|
addTermCount(signal.terms, content, 2);
|
|
45539
45739
|
signal.docsText += ` ${content.toLowerCase()}`;
|
|
45540
45740
|
break;
|
|
45541
45741
|
}
|
|
45542
|
-
const docsDir =
|
|
45742
|
+
const docsDir = path68.join(resolvedRoot, "docs");
|
|
45543
45743
|
if (fs32.existsSync(docsDir) && fs32.statSync(docsDir).isDirectory()) {
|
|
45544
45744
|
signal.referenceHints.push("docs/");
|
|
45545
45745
|
for (const entry of fs32.readdirSync(docsDir, { withFileTypes: true })) {
|
|
45546
45746
|
if (!entry.isFile()) continue;
|
|
45547
45747
|
if (!/\.(md|txt|rst)$/i.test(entry.name)) continue;
|
|
45548
|
-
const docsContent = maybeReadUtf8(
|
|
45748
|
+
const docsContent = maybeReadUtf8(path68.join(docsDir, entry.name));
|
|
45549
45749
|
if (!docsContent) continue;
|
|
45550
45750
|
signal.usefulSignals++;
|
|
45551
45751
|
addTermCount(signal.terms, docsContent, 1);
|
|
@@ -45553,7 +45753,7 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
|
|
|
45553
45753
|
}
|
|
45554
45754
|
}
|
|
45555
45755
|
for (const folderName of ["reference", "specs", "design", "architecture", "src", "packages", "apps"]) {
|
|
45556
|
-
const fullPath =
|
|
45756
|
+
const fullPath = path68.join(resolvedRoot, folderName);
|
|
45557
45757
|
if (fs32.existsSync(fullPath)) {
|
|
45558
45758
|
signal.referenceHints.push(`${folderName}/`);
|
|
45559
45759
|
}
|
|
@@ -45564,14 +45764,14 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
|
|
|
45564
45764
|
if (scannedFiles >= maxFiles) return;
|
|
45565
45765
|
for (const entry of fs32.readdirSync(dir, { withFileTypes: true })) {
|
|
45566
45766
|
if (scannedFiles >= maxFiles) return;
|
|
45567
|
-
const fullPath =
|
|
45767
|
+
const fullPath = path68.join(dir, entry.name);
|
|
45568
45768
|
if (entry.isDirectory()) {
|
|
45569
45769
|
if (skipDirs.has(entry.name)) continue;
|
|
45570
45770
|
walk(fullPath);
|
|
45571
45771
|
continue;
|
|
45572
45772
|
}
|
|
45573
45773
|
scannedFiles++;
|
|
45574
|
-
const ext =
|
|
45774
|
+
const ext = path68.extname(entry.name).toLowerCase();
|
|
45575
45775
|
if (!ext) continue;
|
|
45576
45776
|
const extScore = EXTENSION_DOMAIN_HINTS[ext];
|
|
45577
45777
|
if (extScore) {
|
|
@@ -45745,7 +45945,7 @@ function findExistingProjectForSource(phrenPath, sourceRoot, derivedName) {
|
|
|
45745
45945
|
return null;
|
|
45746
45946
|
}
|
|
45747
45947
|
};
|
|
45748
|
-
const resolvedSource =
|
|
45948
|
+
const resolvedSource = path68.resolve(sourceRoot);
|
|
45749
45949
|
for (const project of candidates) {
|
|
45750
45950
|
if (sourceOf(project) === resolvedSource) return project;
|
|
45751
45951
|
}
|
|
@@ -45759,7 +45959,7 @@ function findExistingProjectForSource(phrenPath, sourceRoot, derivedName) {
|
|
|
45759
45959
|
function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
|
|
45760
45960
|
const profile = typeof opts === "string" ? opts : opts.profile;
|
|
45761
45961
|
const profilePhrenPath = typeof opts === "string" ? phrenPath : opts.profilePhrenPath ?? phrenPath;
|
|
45762
|
-
const resolvedPath =
|
|
45962
|
+
const resolvedPath = path68.resolve(projectPath);
|
|
45763
45963
|
if (!fs32.existsSync(resolvedPath)) {
|
|
45764
45964
|
throw new Error(`Path does not exist: ${resolvedPath}`);
|
|
45765
45965
|
}
|
|
@@ -45770,17 +45970,17 @@ function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
|
|
|
45770
45970
|
if (worktreeRepoRoot) {
|
|
45771
45971
|
debugLog(`bootstrapFromExisting: ${resolvedPath} is a ${worktree.reason}; attributing to ${worktreeRepoRoot}`);
|
|
45772
45972
|
}
|
|
45773
|
-
const sourceRoot = isProjectLocal ?
|
|
45973
|
+
const sourceRoot = isProjectLocal ? path68.resolve(manifest.workspaceRoot || resolvedPath) : worktreeRepoRoot ?? resolvedPath;
|
|
45774
45974
|
if (isProjectLocal) {
|
|
45775
|
-
const matchesWorkspace = resolvedPath === sourceRoot || resolvedPath.startsWith(sourceRoot +
|
|
45975
|
+
const matchesWorkspace = resolvedPath === sourceRoot || resolvedPath.startsWith(sourceRoot + path68.sep);
|
|
45776
45976
|
if (!matchesWorkspace) {
|
|
45777
45977
|
throw new Error(`Project-local phren can only enroll the owning workspace: ${sourceRoot}`);
|
|
45778
45978
|
}
|
|
45779
45979
|
}
|
|
45780
45980
|
let claudeMdPath = null;
|
|
45781
45981
|
const candidates = [
|
|
45782
|
-
|
|
45783
|
-
|
|
45982
|
+
path68.join(sourceRoot, "AGENTS.md"),
|
|
45983
|
+
path68.join(sourceRoot, ".claude", "CLAUDE.md")
|
|
45784
45984
|
];
|
|
45785
45985
|
for (const c of candidates) {
|
|
45786
45986
|
if (fs32.existsSync(c)) {
|
|
@@ -45800,12 +46000,12 @@ function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
|
|
|
45800
46000
|
`Project "${existingProject}" already exists with different casing. Refusing to bootstrap "${projectName2}" because it would split the same project on case-sensitive filesystems.`
|
|
45801
46001
|
);
|
|
45802
46002
|
}
|
|
45803
|
-
const projDir =
|
|
46003
|
+
const projDir = path68.join(phrenPath, projectName2);
|
|
45804
46004
|
fs32.mkdirSync(projDir, { recursive: true });
|
|
45805
46005
|
const inferredScaffold = inferInitScaffoldFromRepo(sourceRoot);
|
|
45806
46006
|
const existingConfig = readProjectConfig(phrenPath, projectName2);
|
|
45807
46007
|
const ownership = typeof opts === "string" ? parseProjectOwnershipMode(existingConfig.ownership) ?? getProjectOwnershipDefault(phrenPath) : opts.ownership ?? parseProjectOwnershipMode(existingConfig.ownership) ?? getProjectOwnershipDefault(phrenPath);
|
|
45808
|
-
const claudePath =
|
|
46008
|
+
const claudePath = path68.join(projDir, "AGENTS.md");
|
|
45809
46009
|
if (ownership !== "repo-managed") {
|
|
45810
46010
|
if (claudeContent) {
|
|
45811
46011
|
if (!fs32.existsSync(claudePath)) {
|
|
@@ -45840,7 +46040,7 @@ function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
|
|
|
45840
46040
|
}
|
|
45841
46041
|
}
|
|
45842
46042
|
const sourceInfo = claudeMdPath ? `**Source AGENTS.md:** ${claudeMdPath}` : `**Source:** ${sourceRoot}`;
|
|
45843
|
-
const summaryPath =
|
|
46043
|
+
const summaryPath = path68.join(projDir, "summary.md");
|
|
45844
46044
|
if (!fs32.existsSync(summaryPath)) {
|
|
45845
46045
|
atomicWriteText(
|
|
45846
46046
|
summaryPath,
|
|
@@ -45853,18 +46053,18 @@ ${summaryLines.length > 1 ? summaryLines.slice(1).join("\n") : ""}
|
|
|
45853
46053
|
`
|
|
45854
46054
|
);
|
|
45855
46055
|
}
|
|
45856
|
-
if (!fs32.existsSync(
|
|
46056
|
+
if (!fs32.existsSync(path68.join(projDir, FINDINGS_FILENAME))) {
|
|
45857
46057
|
atomicWriteText(
|
|
45858
|
-
|
|
46058
|
+
path68.join(projDir, FINDINGS_FILENAME),
|
|
45859
46059
|
`# ${projectName2} FINDINGS
|
|
45860
46060
|
|
|
45861
46061
|
<!-- Bootstrapped from ${sourceRoot} -->
|
|
45862
46062
|
`
|
|
45863
46063
|
);
|
|
45864
46064
|
}
|
|
45865
|
-
if (moduleEnabled(phrenPath, "tasks") && !fs32.existsSync(
|
|
46065
|
+
if (moduleEnabled(phrenPath, "tasks") && !fs32.existsSync(path68.join(projDir, TASKS_FILENAME))) {
|
|
45866
46066
|
atomicWriteText(
|
|
45867
|
-
|
|
46067
|
+
path68.join(projDir, TASKS_FILENAME),
|
|
45868
46068
|
`# ${projectName2} tasks
|
|
45869
46069
|
|
|
45870
46070
|
## Active
|
|
@@ -45875,11 +46075,11 @@ ${summaryLines.length > 1 ? summaryLines.slice(1).join("\n") : ""}
|
|
|
45875
46075
|
`
|
|
45876
46076
|
);
|
|
45877
46077
|
}
|
|
45878
|
-
if (!fs32.existsSync(
|
|
46078
|
+
if (!fs32.existsSync(path68.join(projDir, "topic-config.json"))) {
|
|
45879
46079
|
const inferredDomain = normalizeBuiltinTopicDomain(inferredScaffold?.domain ?? "software");
|
|
45880
46080
|
const inferredTopics = inferredScaffold?.topics?.length ? inferredScaffold.topics : getBuiltinTopicConfig(inferredDomain);
|
|
45881
46081
|
atomicWriteText(
|
|
45882
|
-
|
|
46082
|
+
path68.join(projDir, "topic-config.json"),
|
|
45883
46083
|
JSON.stringify({ version: 1, domain: inferredDomain, topics: inferredTopics }, null, 2) + "\n"
|
|
45884
46084
|
);
|
|
45885
46085
|
}
|
|
@@ -45911,10 +46111,10 @@ function addProjectFromPath(phrenPath, targetPath, requestedProfile, ownership,
|
|
|
45911
46111
|
if (!activeProfile.ok) return activeProfile;
|
|
45912
46112
|
const writePhrenPath = options.writeToPath ?? phrenPath;
|
|
45913
46113
|
const manifest = readRootManifest(phrenPath);
|
|
45914
|
-
const resolvedPath =
|
|
46114
|
+
const resolvedPath = path69.resolve(targetPath);
|
|
45915
46115
|
if (manifest?.installMode === "project-local") {
|
|
45916
|
-
const workspaceRoot =
|
|
45917
|
-
const matchesWorkspace = resolvedPath === workspaceRoot || resolvedPath.startsWith(workspaceRoot +
|
|
46116
|
+
const workspaceRoot = path69.resolve(manifest.workspaceRoot || "");
|
|
46117
|
+
const matchesWorkspace = resolvedPath === workspaceRoot || resolvedPath.startsWith(workspaceRoot + path69.sep);
|
|
45918
46118
|
if (!matchesWorkspace) {
|
|
45919
46119
|
return phrenErr(`Project-local phren can only add the owning workspace: ${workspaceRoot}`);
|
|
45920
46120
|
}
|
|
@@ -45932,9 +46132,9 @@ function addProjectFromPath(phrenPath, targetPath, requestedProfile, ownership,
|
|
|
45932
46132
|
ownership: added.ownership,
|
|
45933
46133
|
files: {
|
|
45934
46134
|
claude: added.claudePath,
|
|
45935
|
-
summary:
|
|
45936
|
-
findings:
|
|
45937
|
-
task:
|
|
46135
|
+
summary: path69.join(writePhrenPath, added.project, "summary.md"),
|
|
46136
|
+
findings: path69.join(writePhrenPath, added.project, FINDINGS_FILENAME),
|
|
46137
|
+
task: path69.join(writePhrenPath, added.project, TASKS_FILENAME)
|
|
45938
46138
|
}
|
|
45939
46139
|
});
|
|
45940
46140
|
}
|
|
@@ -45960,7 +46160,7 @@ import { execFileSync as execFileSync6, spawnSync as spawnSync2 } from "child_pr
|
|
|
45960
46160
|
import * as crypto9 from "crypto";
|
|
45961
46161
|
import * as fs33 from "fs";
|
|
45962
46162
|
import * as os3 from "os";
|
|
45963
|
-
import * as
|
|
46163
|
+
import * as path70 from "path";
|
|
45964
46164
|
|
|
45965
46165
|
// src/content/summarize.ts
|
|
45966
46166
|
init_phren_dotenv();
|
|
@@ -46121,7 +46321,7 @@ function mergeTasksByBid(base, ours, theirs) {
|
|
|
46121
46321
|
// src/sync/conflict-resolve.ts
|
|
46122
46322
|
function conflictStrategy(relFile) {
|
|
46123
46323
|
const file2 = relFile.replace(/\\/g, "/");
|
|
46124
|
-
const name =
|
|
46324
|
+
const name = path70.posix.basename(file2).toLowerCase();
|
|
46125
46325
|
if (isTaskFileName(name)) return "tasks";
|
|
46126
46326
|
if (name === "findings.md") return "findings";
|
|
46127
46327
|
if (/^\.config\/task-archive\/[^/]+\.md$/i.test(file2)) return "archive";
|
|
@@ -46156,9 +46356,9 @@ function splitBlock(content, start, end) {
|
|
|
46156
46356
|
function mergeText(base, ours, theirs) {
|
|
46157
46357
|
if (ours === theirs || ours === base) return theirs;
|
|
46158
46358
|
if (theirs === base) return ours;
|
|
46159
|
-
const dir = fs33.mkdtempSync(
|
|
46359
|
+
const dir = fs33.mkdtempSync(path70.join(os3.tmpdir(), "phren-merge-"));
|
|
46160
46360
|
try {
|
|
46161
|
-
const [o, b, t] = ["ours", "base", "theirs"].map((name) =>
|
|
46361
|
+
const [o, b, t] = ["ours", "base", "theirs"].map((name) => path70.join(dir, name));
|
|
46162
46362
|
fs33.writeFileSync(o, ours);
|
|
46163
46363
|
fs33.writeFileSync(b, base);
|
|
46164
46364
|
fs33.writeFileSync(t, theirs);
|
|
@@ -46171,9 +46371,9 @@ function mergeText(base, ours, theirs) {
|
|
|
46171
46371
|
function unionText(base, ours, theirs) {
|
|
46172
46372
|
const clean2 = mergeText(base, ours, theirs);
|
|
46173
46373
|
if (clean2 !== null) return clean2;
|
|
46174
|
-
const dir = fs33.mkdtempSync(
|
|
46374
|
+
const dir = fs33.mkdtempSync(path70.join(os3.tmpdir(), "phren-merge-"));
|
|
46175
46375
|
try {
|
|
46176
|
-
const [o, b, t] = ["ours", "base", "theirs"].map((name) =>
|
|
46376
|
+
const [o, b, t] = ["ours", "base", "theirs"].map((name) => path70.join(dir, name));
|
|
46177
46377
|
fs33.writeFileSync(o, ours);
|
|
46178
46378
|
fs33.writeFileSync(b, base);
|
|
46179
46379
|
fs33.writeFileSync(t, theirs);
|
|
@@ -46233,7 +46433,7 @@ function resolveStoreConflicts(cwd) {
|
|
|
46233
46433
|
const base = stage(cwd, 1, relFile) ?? "";
|
|
46234
46434
|
const ours = stage(cwd, 2, relFile);
|
|
46235
46435
|
const theirs = stage(cwd, 3, relFile);
|
|
46236
|
-
const fullPath =
|
|
46436
|
+
const fullPath = path70.join(cwd, relFile);
|
|
46237
46437
|
if (ours === null && theirs === null) {
|
|
46238
46438
|
unresolved.push(relFile);
|
|
46239
46439
|
continue;
|
|
@@ -46244,7 +46444,7 @@ function resolveStoreConflicts(cwd) {
|
|
|
46244
46444
|
continue;
|
|
46245
46445
|
}
|
|
46246
46446
|
const tmp = `${fullPath}.tmp-${crypto9.randomUUID()}`;
|
|
46247
|
-
fs33.mkdirSync(
|
|
46447
|
+
fs33.mkdirSync(path70.dirname(fullPath), { recursive: true });
|
|
46248
46448
|
fs33.writeFileSync(tmp, merged);
|
|
46249
46449
|
fs33.renameSync(tmp, fullPath);
|
|
46250
46450
|
git4(cwd, ["add", "--", relFile]);
|
|
@@ -46524,7 +46724,7 @@ function repoName(url2) {
|
|
|
46524
46724
|
}
|
|
46525
46725
|
async function isRepository(directory) {
|
|
46526
46726
|
try {
|
|
46527
|
-
await stat20(
|
|
46727
|
+
await stat20(path71.join(directory, ".git"));
|
|
46528
46728
|
return true;
|
|
46529
46729
|
} catch {
|
|
46530
46730
|
return false;
|
|
@@ -46544,7 +46744,7 @@ async function registeredSources(env) {
|
|
|
46544
46744
|
const source = readProjectConfig(store, project).sourcePath;
|
|
46545
46745
|
if (typeof source === "string" && source) {
|
|
46546
46746
|
try {
|
|
46547
|
-
paths.add(realpathSync5.native(
|
|
46747
|
+
paths.add(realpathSync5.native(path71.resolve(source)));
|
|
46548
46748
|
} catch {
|
|
46549
46749
|
}
|
|
46550
46750
|
}
|
|
@@ -46556,7 +46756,7 @@ async function candidateRepos(activity, env = process.env) {
|
|
|
46556
46756
|
const found = [];
|
|
46557
46757
|
const seen = /* @__PURE__ */ new Set();
|
|
46558
46758
|
const offer = async (directory, source, lastSeen) => {
|
|
46559
|
-
let dir =
|
|
46759
|
+
let dir = path71.resolve(directory);
|
|
46560
46760
|
try {
|
|
46561
46761
|
if (!(await stat20(dir)).isDirectory()) return;
|
|
46562
46762
|
dir = realpathSync5.native(dir);
|
|
@@ -46571,7 +46771,7 @@ async function candidateRepos(activity, env = process.env) {
|
|
|
46571
46771
|
const toplevel = async (directory) => {
|
|
46572
46772
|
let existing = directory;
|
|
46573
46773
|
while (!await stat20(existing).catch(() => void 0)) {
|
|
46574
|
-
const parent =
|
|
46774
|
+
const parent = path71.dirname(existing);
|
|
46575
46775
|
if (parent === existing) return void 0;
|
|
46576
46776
|
existing = parent;
|
|
46577
46777
|
}
|
|
@@ -46584,25 +46784,25 @@ async function candidateRepos(activity, env = process.env) {
|
|
|
46584
46784
|
};
|
|
46585
46785
|
for (const event of [...activity].reverse()) {
|
|
46586
46786
|
const directory = typeof event.directory === "string" ? event.directory : void 0;
|
|
46587
|
-
if (!directory || !
|
|
46787
|
+
if (!directory || !path71.isAbsolute(directory)) continue;
|
|
46588
46788
|
const root = await toplevel(directory);
|
|
46589
46789
|
if (root) await offer(root, "activity", typeof event.at === "string" ? event.at : void 0);
|
|
46590
46790
|
}
|
|
46591
46791
|
try {
|
|
46592
|
-
const session = JSON.parse(await readFile27(
|
|
46792
|
+
const session = JSON.parse(await readFile27(path71.join(herdrRoot(), "session.json"), "utf8"));
|
|
46593
46793
|
for (const match of JSON.stringify(session).matchAll(/"cwd":\s*"((?:\\.|[^"\\])*)"/g)) {
|
|
46594
46794
|
const directory = JSON.parse(`"${match[1]}"`);
|
|
46595
|
-
if (!
|
|
46795
|
+
if (!path71.isAbsolute(directory)) continue;
|
|
46596
46796
|
const root = await toplevel(directory);
|
|
46597
46797
|
if (root) await offer(root, "herdr");
|
|
46598
46798
|
}
|
|
46599
46799
|
} catch {
|
|
46600
46800
|
}
|
|
46601
46801
|
const home = homedir17();
|
|
46602
|
-
for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.map((r) =>
|
|
46802
|
+
for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.map((r) => path71.join(home, r))]) {
|
|
46603
46803
|
let children = [];
|
|
46604
46804
|
try {
|
|
46605
|
-
children = (await readdir12(root, { withFileTypes: true })).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) =>
|
|
46805
|
+
children = (await readdir12(root, { withFileTypes: true })).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => path71.join(root, e.name));
|
|
46606
46806
|
} catch {
|
|
46607
46807
|
continue;
|
|
46608
46808
|
}
|
|
@@ -46612,13 +46812,13 @@ async function candidateRepos(activity, env = process.env) {
|
|
|
46612
46812
|
}
|
|
46613
46813
|
async function cloneRoot(env) {
|
|
46614
46814
|
const home = homedir17();
|
|
46615
|
-
for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.filter((r) => r !== "Sites").map((r) =>
|
|
46815
|
+
for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.filter((r) => r !== "Sites").map((r) => path71.join(home, r))]) {
|
|
46616
46816
|
try {
|
|
46617
46817
|
if ((await stat20(root)).isDirectory()) return root;
|
|
46618
46818
|
} catch {
|
|
46619
46819
|
}
|
|
46620
46820
|
}
|
|
46621
|
-
const fallback =
|
|
46821
|
+
const fallback = path71.join(home, "Projects");
|
|
46622
46822
|
await mkdir15(fallback, { recursive: true });
|
|
46623
46823
|
return fallback;
|
|
46624
46824
|
}
|
|
@@ -46640,7 +46840,7 @@ async function publishStore(store, project) {
|
|
|
46640
46840
|
async function enrollProject(input2, env = process.env) {
|
|
46641
46841
|
const store = phrenStoreRoot(env);
|
|
46642
46842
|
try {
|
|
46643
|
-
if (!(await stat20(
|
|
46843
|
+
if (!(await stat20(path71.join(store, ".config"))).isDirectory()) throw new Error();
|
|
46644
46844
|
} catch {
|
|
46645
46845
|
throw new BridgeError(409, "phren is not set up on this computer. Run phren init there.");
|
|
46646
46846
|
}
|
|
@@ -46651,7 +46851,7 @@ async function enrollProject(input2, env = process.env) {
|
|
|
46651
46851
|
if (url2.length > 512 || !CLONE_URL.test(url2)) throw new BridgeError(400, "Enter a GitHub repository URL (https://github.com/owner/repo).");
|
|
46652
46852
|
const name = repoName(url2);
|
|
46653
46853
|
if (!name || name === "." || name === "..") throw new BridgeError(400, "That URL has no repository name.");
|
|
46654
|
-
directory =
|
|
46854
|
+
directory = path71.join(await cloneRoot(env), name);
|
|
46655
46855
|
try {
|
|
46656
46856
|
await stat20(directory);
|
|
46657
46857
|
throw new BridgeError(409, `${directory} already exists on this computer. Add that folder instead.`);
|
|
@@ -46668,7 +46868,7 @@ async function enrollProject(input2, env = process.env) {
|
|
|
46668
46868
|
cloned = true;
|
|
46669
46869
|
} else if (typeof input2.directory === "string" && input2.directory) {
|
|
46670
46870
|
const raw = input2.directory;
|
|
46671
|
-
if (raw.length > 4096 || raw.includes("\0") || !
|
|
46871
|
+
if (raw.length > 4096 || raw.includes("\0") || !path71.isAbsolute(raw)) throw new BridgeError(400, "Enter the full folder path on this computer.");
|
|
46672
46872
|
try {
|
|
46673
46873
|
directory = realpathSync5.native(raw);
|
|
46674
46874
|
if (!(await stat20(directory)).isDirectory()) throw new Error();
|
|
@@ -46683,22 +46883,22 @@ async function enrollProject(input2, env = process.env) {
|
|
|
46683
46883
|
|
|
46684
46884
|
// src/bridge/files.ts
|
|
46685
46885
|
init_protocol();
|
|
46686
|
-
import { constants as
|
|
46886
|
+
import { constants as constants4 } from "node:fs";
|
|
46687
46887
|
import { lstat as lstat15, open as open13, readdir as readdir13, realpath as realpath12 } from "node:fs/promises";
|
|
46688
|
-
import
|
|
46888
|
+
import path72 from "node:path";
|
|
46689
46889
|
var MAX_BYTES = 2097152;
|
|
46690
46890
|
async function browseFiles(root, relative3) {
|
|
46691
|
-
if (relative3.length > 4096 || relative3.includes("\0") || relative3.includes("\\") ||
|
|
46891
|
+
if (relative3.length > 4096 || relative3.includes("\0") || relative3.includes("\\") || path72.isAbsolute(relative3) || relative3.split("/").some((part) => part === ".." || part === ".git")) {
|
|
46692
46892
|
throw new BridgeError(400, "Invalid repository path.");
|
|
46693
46893
|
}
|
|
46694
46894
|
const base = await realpath12(root);
|
|
46695
46895
|
let file2 = base;
|
|
46696
46896
|
for (const part of relative3.split("/").filter((part2) => part2 && part2 !== ".")) {
|
|
46697
|
-
file2 =
|
|
46897
|
+
file2 = path72.join(file2, part);
|
|
46698
46898
|
if ((await lstat15(file2)).isSymbolicLink()) throw new BridgeError(403, "Symbolic links cannot be browsed.");
|
|
46699
46899
|
}
|
|
46700
46900
|
const resolved = await realpath12(file2);
|
|
46701
|
-
if (resolved !== base && !resolved.startsWith(base +
|
|
46901
|
+
if (resolved !== base && !resolved.startsWith(base + path72.sep)) throw new BridgeError(403, "The path is outside this repository.");
|
|
46702
46902
|
const metadata = await lstat15(resolved);
|
|
46703
46903
|
if (metadata.isDirectory()) {
|
|
46704
46904
|
const entries2 = (await readdir13(resolved, { withFileTypes: true })).filter((entry) => entry.name !== ".git" && (entry.isDirectory() || entry.isFile())).sort((a, b) => Number(b.isDirectory()) - Number(a.isDirectory()) || a.name.localeCompare(b.name));
|
|
@@ -46706,11 +46906,11 @@ async function browseFiles(root, relative3) {
|
|
|
46706
46906
|
path: relative3,
|
|
46707
46907
|
kind: "directory",
|
|
46708
46908
|
truncated: entries2.length > 500,
|
|
46709
|
-
entries: entries2.slice(0, 500).map((entry) => ({ name: entry.name, path:
|
|
46909
|
+
entries: entries2.slice(0, 500).map((entry) => ({ name: entry.name, path: path72.posix.join(relative3, entry.name), kind: entry.isDirectory() ? "directory" : "file" }))
|
|
46710
46910
|
};
|
|
46711
46911
|
}
|
|
46712
46912
|
if (!metadata.isFile()) throw new BridgeError(400, "Only regular files can be viewed.");
|
|
46713
|
-
const handle = await open13(resolved,
|
|
46913
|
+
const handle = await open13(resolved, constants4.O_RDONLY | constants4.O_NOFOLLOW | constants4.O_NONBLOCK);
|
|
46714
46914
|
try {
|
|
46715
46915
|
const current2 = await handle.stat();
|
|
46716
46916
|
if (!current2.isFile() || current2.ino !== metadata.ino || current2.dev !== metadata.dev) throw new BridgeError(409, "The file changed. Refresh and try again.");
|
|
@@ -46731,9 +46931,9 @@ async function browseFiles(root, relative3) {
|
|
|
46731
46931
|
|
|
46732
46932
|
// src/bridge/file-range.ts
|
|
46733
46933
|
init_protocol();
|
|
46734
|
-
import { constants as
|
|
46934
|
+
import { constants as constants5 } from "node:fs";
|
|
46735
46935
|
import { lstat as lstat16, open as open14, realpath as realpath13 } from "node:fs/promises";
|
|
46736
|
-
import
|
|
46936
|
+
import path73 from "node:path";
|
|
46737
46937
|
var MAX_FILE_RANGE = 4 * 1024 * 1024;
|
|
46738
46938
|
var types = {
|
|
46739
46939
|
mp4: "video/mp4",
|
|
@@ -46770,7 +46970,7 @@ var types = {
|
|
|
46770
46970
|
xml: "text/xml"
|
|
46771
46971
|
};
|
|
46772
46972
|
function fileContentType(file2) {
|
|
46773
|
-
const ext =
|
|
46973
|
+
const ext = path73.extname(file2).slice(1).toLowerCase();
|
|
46774
46974
|
return types[ext] ?? (/^(ts|tsx|js|jsx|swift|py|rs|go|rb|sh|bash|zsh|c|h|cpp|hpp|cs|java|kt|html|css|scss|sql|toml|ini)$/.test(ext) ? "text/plain" : "application/octet-stream");
|
|
46775
46975
|
}
|
|
46776
46976
|
function version2(stat27) {
|
|
@@ -46788,18 +46988,18 @@ async function readFileRange(root, requested, offset, length, expectedVersion) {
|
|
|
46788
46988
|
}
|
|
46789
46989
|
try {
|
|
46790
46990
|
const base = await realpath13(root);
|
|
46791
|
-
const relative3 =
|
|
46792
|
-
if (relative3 === ".." || relative3.startsWith(`..${
|
|
46991
|
+
const relative3 = path73.isAbsolute(requested) ? path73.relative(base, requested) : requested;
|
|
46992
|
+
if (relative3 === ".." || relative3.startsWith(`..${path73.sep}`) || path73.isAbsolute(relative3)) throw new BridgeError(403, "This file is outside the allowed folder.");
|
|
46793
46993
|
let file2 = base;
|
|
46794
|
-
for (const part of relative3.split(
|
|
46795
|
-
file2 =
|
|
46994
|
+
for (const part of relative3.split(path73.sep).filter((part2) => part2 && part2 !== ".")) {
|
|
46995
|
+
file2 = path73.join(file2, part);
|
|
46796
46996
|
if ((await lstat16(file2)).isSymbolicLink()) throw new BridgeError(403, "Symbolic links cannot be opened.");
|
|
46797
46997
|
}
|
|
46798
46998
|
const resolved = await realpath13(file2);
|
|
46799
|
-
if (!resolved.startsWith(base +
|
|
46999
|
+
if (!resolved.startsWith(base + path73.sep)) throw new BridgeError(403, "This file is outside the allowed folder.");
|
|
46800
47000
|
const metadata = await lstat16(resolved);
|
|
46801
47001
|
if (!metadata.isFile()) throw new BridgeError(400, "Only regular files can be opened.");
|
|
46802
|
-
const handle = await open14(resolved,
|
|
47002
|
+
const handle = await open14(resolved, constants5.O_RDONLY | constants5.O_NOFOLLOW | constants5.O_NONBLOCK);
|
|
46803
47003
|
try {
|
|
46804
47004
|
const current2 = await handle.stat();
|
|
46805
47005
|
if (!current2.isFile() || version2(current2) !== version2(metadata) || await realpath13(file2) !== resolved) {
|
|
@@ -46841,7 +47041,7 @@ init_protocol();
|
|
|
46841
47041
|
import { execFile as execFile13 } from "node:child_process";
|
|
46842
47042
|
import { createHash as createHash15 } from "node:crypto";
|
|
46843
47043
|
import { lstat as lstat17, mkdir as mkdir16, readFile as readFile28, realpath as realpath14, rename as rename7, rm as rm8, writeFile as writeFile8 } from "node:fs/promises";
|
|
46844
|
-
import
|
|
47044
|
+
import path74 from "node:path";
|
|
46845
47045
|
import { promisify as promisify12 } from "node:util";
|
|
46846
47046
|
var exec12 = promisify12(execFile13);
|
|
46847
47047
|
var SHA = /^[0-9a-f]{40}$/;
|
|
@@ -46869,12 +47069,12 @@ function blobSha(content) {
|
|
|
46869
47069
|
return createHash15("sha1").update(`blob ${content.length}\0`).update(content).digest("hex");
|
|
46870
47070
|
}
|
|
46871
47071
|
async function isRepository2(store) {
|
|
46872
|
-
return await lstat17(
|
|
47072
|
+
return await lstat17(path74.join(store, ".git")).catch(() => void 0) !== void 0;
|
|
46873
47073
|
}
|
|
46874
|
-
function storeHead(store, indexFile =
|
|
47074
|
+
function storeHead(store, indexFile = path74.join(bridgeRoot(), "store-snapshot.index")) {
|
|
46875
47075
|
return serialized(async () => {
|
|
46876
47076
|
if (!await isRepository2(store)) throw new BridgeError(409, "This computer's phren store is not a git repository. Run phren init.");
|
|
46877
|
-
await mkdir16(
|
|
47077
|
+
await mkdir16(path74.dirname(indexFile), { recursive: true, mode: 448 });
|
|
46878
47078
|
const env = { GIT_INDEX_FILE: indexFile };
|
|
46879
47079
|
if (!await lstat17(indexFile).catch(() => void 0)) {
|
|
46880
47080
|
const head = await git5(store, ["rev-parse", "--verify", "--quiet", "HEAD"]).catch(() => "");
|
|
@@ -46901,21 +47101,21 @@ async function storeBlob(store, sha) {
|
|
|
46901
47101
|
return { sha, encoding: "base64", content: stdout.toString("base64") };
|
|
46902
47102
|
}
|
|
46903
47103
|
async function storeFile(store, relative3) {
|
|
46904
|
-
const normalized =
|
|
46905
|
-
if (!relative3 || relative3 !== normalized || normalized.startsWith("../") || normalized === ".." ||
|
|
47104
|
+
const normalized = path74.posix.normalize(relative3);
|
|
47105
|
+
if (!relative3 || relative3 !== normalized || normalized.startsWith("../") || normalized === ".." || path74.posix.isAbsolute(normalized) || normalized.split("/").some((part) => part === ".git" || part === "" || part === ".") || /[\0\r\n]/.test(normalized)) {
|
|
46906
47106
|
throw new BridgeError(400, "Invalid store path.");
|
|
46907
47107
|
}
|
|
46908
47108
|
const root = await realpath14(store);
|
|
46909
|
-
let parent =
|
|
47109
|
+
let parent = path74.dirname(path74.join(root, normalized));
|
|
46910
47110
|
for (; ; ) {
|
|
46911
47111
|
const real2 = await realpath14(parent).catch(() => void 0);
|
|
46912
47112
|
if (real2) {
|
|
46913
|
-
if (real2 !== root && !real2.startsWith(root +
|
|
47113
|
+
if (real2 !== root && !real2.startsWith(root + path74.sep)) throw new BridgeError(400, "Invalid store path.");
|
|
46914
47114
|
break;
|
|
46915
47115
|
}
|
|
46916
|
-
parent =
|
|
47116
|
+
parent = path74.dirname(parent);
|
|
46917
47117
|
}
|
|
46918
|
-
const file2 =
|
|
47118
|
+
const file2 = path74.join(root, normalized);
|
|
46919
47119
|
const info = await lstat17(file2).catch(() => void 0);
|
|
46920
47120
|
if (info && !info.isFile()) throw new BridgeError(400, "Invalid store path.");
|
|
46921
47121
|
return file2;
|
|
@@ -46936,7 +47136,7 @@ function putStoreFile(store, data) {
|
|
|
46936
47136
|
return serialized(async () => {
|
|
46937
47137
|
const file2 = await storeFile(store, input2.path);
|
|
46938
47138
|
if (await currentSha(file2) !== (input2.sha ?? null)) throw new BridgeError(409, `${input2.path} changed on this computer.`);
|
|
46939
|
-
await mkdir16(
|
|
47139
|
+
await mkdir16(path74.dirname(file2), { recursive: true });
|
|
46940
47140
|
const temporary = `${file2}.phren-${process.pid}-${Date.now()}`;
|
|
46941
47141
|
await writeFile8(temporary, content, { flag: "wx" });
|
|
46942
47142
|
await rename7(temporary, file2);
|
|
@@ -46971,7 +47171,7 @@ init_protocol();
|
|
|
46971
47171
|
import { execFile as execFile14 } from "node:child_process";
|
|
46972
47172
|
import { chmod as chmod4, mkdir as mkdir17, readFile as readFile29, rename as rename8, stat as stat21, unlink as unlink5, writeFile as writeFile9 } from "node:fs/promises";
|
|
46973
47173
|
import { tmpdir as tmpdir3 } from "node:os";
|
|
46974
|
-
import
|
|
47174
|
+
import path75 from "node:path";
|
|
46975
47175
|
import { createHash as createHash16, randomUUID as randomUUID17 } from "node:crypto";
|
|
46976
47176
|
import { promisify as promisify13 } from "node:util";
|
|
46977
47177
|
var exec13 = promisify13(execFile14);
|
|
@@ -46999,7 +47199,7 @@ async function bootedSimulators() {
|
|
|
46999
47199
|
async function simulatorScreenshot(udid) {
|
|
47000
47200
|
if (!UDID.test(udid)) throw new BridgeError(400, "Invalid simulator identifier.");
|
|
47001
47201
|
if (process.platform !== "darwin") throw new BridgeError(404, "Simulators run on macOS only.");
|
|
47002
|
-
const file2 =
|
|
47202
|
+
const file2 = path75.join(tmpdir3(), `phren-sim-${randomUUID17()}.png`);
|
|
47003
47203
|
try {
|
|
47004
47204
|
await exec13("/usr/bin/xcrun", ["simctl", "io", udid, "screenshot", "--type=png", file2], { timeout: 15e3 });
|
|
47005
47205
|
return await readFile29(file2);
|
|
@@ -47018,14 +47218,14 @@ function helper() {
|
|
|
47018
47218
|
return building;
|
|
47019
47219
|
}
|
|
47020
47220
|
async function buildHelper() {
|
|
47021
|
-
const dir =
|
|
47022
|
-
const binary =
|
|
47221
|
+
const dir = path75.join(bridgeRoot(), "native");
|
|
47222
|
+
const binary = path75.join(dir, "simtap");
|
|
47023
47223
|
const code = true ? '// Touches and keys for the iOS Simulator, without AppleScript: the window\n// is found through the Accessibility API and events are posted with CGEvent,\n// so one Accessibility grant for this helper is all macOS asks for.\n// Built on demand by Phren Hook with swiftc; see simulators.ts.\nimport ApplicationServices\nimport Cocoa\n\nfunc fail(_ code: Int32, _ message: String) -> Never { FileHandle.standardError.write((message + "\\n").data(using: .utf8)!); exit(code) }\n\nlet args = CommandLine.arguments\nguard args.count >= 3 else { fail(2, "usage: simtap <window-title-prefix> tap <fx> <fy> | key <keycode> [cmd] [shift] | type <text> | raise") }\nlet prefix = args[1], command = args[2]\n\nguard AXIsProcessTrusted() else { fail(3, "accessibility") }\nguard let app = NSRunningApplication.runningApplications(withBundleIdentifier: "com.apple.iphonesimulator").first else { fail(4, "Simulator is not running") }\nlet element = AXUIElementCreateApplication(app.processIdentifier)\nvar windowsRef: CFTypeRef?\nAXUIElementCopyAttributeValue(element, kAXWindowsAttribute as CFString, &windowsRef)\nlet windows = (windowsRef as? [AXUIElement]) ?? []\nvar target: AXUIElement?\nfor window in windows {\n var titleRef: CFTypeRef?\n AXUIElementCopyAttributeValue(window, kAXTitleAttribute as CFString, &titleRef)\n if let title = titleRef as? String, title.hasPrefix(prefix + " ") || title == prefix { target = window; break }\n}\nguard let window = target else { fail(5, "no window for \\(prefix)") }\n\nfunc frame(_ window: AXUIElement) -> CGRect {\n var posRef: CFTypeRef?, sizeRef: CFTypeRef?\n AXUIElementCopyAttributeValue(window, kAXPositionAttribute as CFString, &posRef)\n AXUIElementCopyAttributeValue(window, kAXSizeAttribute as CFString, &sizeRef)\n var pos = CGPoint.zero, size = CGSize.zero\n if let p = posRef { AXValueGetValue(p as! AXValue, .cgPoint, &pos) }\n if let s = sizeRef { AXValueGetValue(s as! AXValue, .cgSize, &size) }\n return CGRect(origin: pos, size: size)\n}\nfunc raise() {\n app.activate(options: [])\n AXUIElementPerformAction(window, kAXRaiseAction as CFString)\n usleep(120_000)\n}\nfunc post(_ event: CGEvent?) {\n guard NSWorkspace.shared.frontmostApplication?.processIdentifier == app.processIdentifier else { fail(6, "focus lost") }\n event?.postToPid(app.processIdentifier)\n usleep(40_000)\n}\n\nswitch command {\ncase "raise": raise()\ncase "tap":\n guard args.count >= 5, let fx = Double(args[3]), let fy = Double(args[4]) else { fail(2, "tap needs fx fy") }\n raise()\n let f = frame(window)\n // The device screen fills the window below its title bar.\n let titleBar: CGFloat = 28\n let point = CGPoint(x: f.origin.x + CGFloat(fx) * f.width, y: f.origin.y + titleBar + CGFloat(fy) * (f.height - titleBar))\n post(CGEvent(mouseEventSource: nil, mouseType: .mouseMoved, mouseCursorPosition: point, mouseButton: .left))\n post(CGEvent(mouseEventSource: nil, mouseType: .leftMouseDown, mouseCursorPosition: point, mouseButton: .left))\n post(CGEvent(mouseEventSource: nil, mouseType: .leftMouseUp, mouseCursorPosition: point, mouseButton: .left))\ncase "key":\n guard args.count >= 4, let code = UInt16(args[3]) else { fail(2, "key needs a keycode") }\n raise()\n var flags: CGEventFlags = []\n if args.contains("cmd") { flags.insert(.maskCommand) }\n if args.contains("shift") { flags.insert(.maskShift) }\n let down = CGEvent(keyboardEventSource: nil, virtualKey: code, keyDown: true), up = CGEvent(keyboardEventSource: nil, virtualKey: code, keyDown: false)\n down?.flags = flags; up?.flags = flags\n post(down); post(up)\ncase "type":\n guard args.count >= 4, !args[3].isEmpty, args[3].utf16.count <= 500 else { fail(2, "type needs at most 500 characters") }\n let submit = args.count == 5 && args[4] == "submit"\n guard args[3].unicodeScalars.allSatisfy({ scalar in\n (scalar.value >= 32 && scalar.value != 127) || (scalar.value == 10 && submit)\n }) else { fail(2, "invalid type controls; newline needs submit") }\n raise()\n for scalar in args[3].unicodeScalars {\n var chars = Array(String(scalar).utf16)\n let down = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: true), up = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: false)\n down?.keyboardSetUnicodeString(stringLength: chars.count, unicodeString: &chars)\n up?.keyboardSetUnicodeString(stringLength: chars.count, unicodeString: &chars)\n post(down); post(up)\n }\ndefault: fail(2, "unknown command \\(command)")\n}\n' : await readFile29(new URL("./native/simtap.swift", import.meta.url), "utf8");
|
|
47024
47224
|
const digest2 = createHash16("sha256").update(code).digest("hex");
|
|
47025
47225
|
const saved = await readFile29(binary + ".sha256", "utf8").then(JSON.parse).catch(() => void 0);
|
|
47026
47226
|
if (await stat21(binary).catch(() => void 0) && saved?.sourceSha === digest2) return binary;
|
|
47027
47227
|
await mkdir17(dir, { recursive: true, mode: 448 });
|
|
47028
|
-
const temporary =
|
|
47228
|
+
const temporary = path75.join(dir, `simtap.${randomUUID17()}`), source = temporary + ".swift";
|
|
47029
47229
|
const sidecar = temporary + ".sha256";
|
|
47030
47230
|
try {
|
|
47031
47231
|
await writeFile9(source, code, { mode: 384, flag: "wx" });
|
|
@@ -47137,7 +47337,7 @@ init_transcripts();
|
|
|
47137
47337
|
// src/bridge/uploads.ts
|
|
47138
47338
|
init_protocol();
|
|
47139
47339
|
import { mkdir as mkdir18, readdir as readdir14, lstat as lstat18, realpath as realpath15, readFile as readFile30, stat as stat22, unlink as unlink6, writeFile as writeFile10 } from "node:fs/promises";
|
|
47140
|
-
import
|
|
47340
|
+
import path76 from "node:path";
|
|
47141
47341
|
import { randomUUID as randomUUID18 } from "node:crypto";
|
|
47142
47342
|
function imageBytes(bytes) {
|
|
47143
47343
|
return bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])) || bytes.subarray(0, 3).equals(Buffer.from([255, 216, 255])) || /^GIF8[79]a/.test(bytes.subarray(0, 6).toString()) || bytes.subarray(0, 4).toString() === "RIFF" && bytes.subarray(8, 12).toString() === "WEBP";
|
|
@@ -47150,24 +47350,24 @@ async function saveUpload(session, name, bytes) {
|
|
|
47150
47350
|
let saved = "";
|
|
47151
47351
|
const task = uploadQueue.catch(() => {
|
|
47152
47352
|
}).then(async () => {
|
|
47153
|
-
const root =
|
|
47353
|
+
const root = path76.join(bridgeRoot(), "uploads");
|
|
47154
47354
|
await mkdir18(root, { recursive: true, mode: 448 });
|
|
47155
47355
|
let used = 0;
|
|
47156
47356
|
const directories = await readdir14(root, { withFileTypes: true });
|
|
47157
47357
|
for (const dir of directories) {
|
|
47158
47358
|
if (!dir.isDirectory()) continue;
|
|
47159
|
-
const folder2 =
|
|
47359
|
+
const folder2 = path76.join(root, dir.name);
|
|
47160
47360
|
for (const entry of await readdir14(folder2, { withFileTypes: true })) {
|
|
47161
47361
|
if (!entry.isFile()) continue;
|
|
47162
|
-
const file2 =
|
|
47362
|
+
const file2 = path76.join(folder2, entry.name), metadata = await lstat18(file2);
|
|
47163
47363
|
if (Date.now() - metadata.mtimeMs > 14 * 864e5) await unlink6(file2);
|
|
47164
47364
|
else used += metadata.size;
|
|
47165
47365
|
}
|
|
47166
47366
|
}
|
|
47167
47367
|
if (used + bytes.length > 268435456) throw new BridgeError(413, "Phren's image storage is full. Remove older uploads on the computer.");
|
|
47168
|
-
const folder =
|
|
47368
|
+
const folder = path76.join(root, session);
|
|
47169
47369
|
await mkdir18(folder, { recursive: true, mode: 448 });
|
|
47170
|
-
saved =
|
|
47370
|
+
saved = path76.join(folder, `${randomUUID18()}-${name}`);
|
|
47171
47371
|
await writeFile10(saved, bytes, { flag: "wx", mode: 384 });
|
|
47172
47372
|
});
|
|
47173
47373
|
uploadQueue = task;
|
|
@@ -47175,22 +47375,22 @@ async function saveUpload(session, name, bytes) {
|
|
|
47175
47375
|
return saved;
|
|
47176
47376
|
}
|
|
47177
47377
|
async function listUploads(session) {
|
|
47178
|
-
const folder =
|
|
47378
|
+
const folder = path76.join(bridgeRoot(), "uploads", session);
|
|
47179
47379
|
const entries2 = await readdir14(folder, { withFileTypes: true }).catch(() => []);
|
|
47180
47380
|
const files = [];
|
|
47181
47381
|
for (const entry of entries2) {
|
|
47182
47382
|
if (!entry.isFile()) continue;
|
|
47183
|
-
const file2 =
|
|
47383
|
+
const file2 = path76.join(folder, entry.name), metadata = await stat22(file2);
|
|
47184
47384
|
files.push({ name: entry.name.replace(/^[0-9a-f-]{36}-/, ""), path: file2, size: metadata.size, modified: metadata.mtime.toISOString() });
|
|
47185
47385
|
}
|
|
47186
47386
|
return files.sort((a, b) => b.modified.localeCompare(a.modified)).slice(0, 200);
|
|
47187
47387
|
}
|
|
47188
47388
|
async function uploadImage(requested) {
|
|
47189
47389
|
const missing = new BridgeError(404, "This image is not one of the phone's uploads.");
|
|
47190
|
-
if (!requested || requested.length > 4096 || !
|
|
47191
|
-
const root = await realpath15(
|
|
47390
|
+
if (!requested || requested.length > 4096 || !path76.isAbsolute(requested)) throw missing;
|
|
47391
|
+
const root = await realpath15(path76.join(bridgeRoot(), "uploads")).catch(() => void 0);
|
|
47192
47392
|
const file2 = await realpath15(requested).catch(() => void 0);
|
|
47193
|
-
if (!root || !file2 || !file2.startsWith(root +
|
|
47393
|
+
if (!root || !file2 || !file2.startsWith(root + path76.sep)) throw missing;
|
|
47194
47394
|
const metadata = await stat22(file2);
|
|
47195
47395
|
if (!metadata.isFile()) throw missing;
|
|
47196
47396
|
if (metadata.size > 8388608) throw new BridgeError(413, "This image is too large.");
|
|
@@ -47204,7 +47404,7 @@ async function uploadImage(requested) {
|
|
|
47204
47404
|
init_transcript_index();
|
|
47205
47405
|
init_transcripts();
|
|
47206
47406
|
import { homedir as homedir18, tmpdir as tmpdir4 } from "node:os";
|
|
47207
|
-
import
|
|
47407
|
+
import path77 from "node:path";
|
|
47208
47408
|
init_protocol();
|
|
47209
47409
|
var cache = /* @__PURE__ */ new Map();
|
|
47210
47410
|
var modelCache = /* @__PURE__ */ new Map();
|
|
@@ -47342,7 +47542,7 @@ function describe3(tool, args) {
|
|
|
47342
47542
|
return "";
|
|
47343
47543
|
};
|
|
47344
47544
|
const firstLine = (v) => v.split(/\r?\n/).map((l) => l.trim()).find((l) => l) ?? "";
|
|
47345
|
-
const base = (v) =>
|
|
47545
|
+
const base = (v) => path77.basename(v.split(" \xB7 ")[0].trim()) || "file";
|
|
47346
47546
|
const name = tool.toLowerCase();
|
|
47347
47547
|
let value2;
|
|
47348
47548
|
if (["bash", "shell", "exec_command", "exec", "parallel", "tools", "write_stdin", "container.exec"].includes(name)) {
|
|
@@ -47377,7 +47577,7 @@ init_shared();
|
|
|
47377
47577
|
|
|
47378
47578
|
// src/bridge/server-pane-routes.ts
|
|
47379
47579
|
init_zod();
|
|
47380
|
-
import
|
|
47580
|
+
import path80 from "node:path";
|
|
47381
47581
|
import { setTimeout as sleep2 } from "node:timers/promises";
|
|
47382
47582
|
|
|
47383
47583
|
// src/bridge/git.ts
|
|
@@ -47385,7 +47585,7 @@ init_protocol();
|
|
|
47385
47585
|
import { createHash as createHash17 } from "node:crypto";
|
|
47386
47586
|
import { execFile as execFile15 } from "node:child_process";
|
|
47387
47587
|
import { lstat as lstat19, readdir as readdir15, readFile as readFile31, realpath as realpath16, stat as stat23 } from "node:fs/promises";
|
|
47388
|
-
import
|
|
47588
|
+
import path78 from "node:path";
|
|
47389
47589
|
import { promisify as promisify14 } from "node:util";
|
|
47390
47590
|
var exec14 = promisify14(execFile15);
|
|
47391
47591
|
function statusLetter(code) {
|
|
@@ -47431,7 +47631,7 @@ function parseNumstat(out) {
|
|
|
47431
47631
|
}
|
|
47432
47632
|
async function countLines(root, rel) {
|
|
47433
47633
|
try {
|
|
47434
|
-
const abs =
|
|
47634
|
+
const abs = path78.join(root, await repositoryPath(root, rel));
|
|
47435
47635
|
if ((await stat23(abs)).size > 5e6) return 0;
|
|
47436
47636
|
const bytes = await readFile31(abs);
|
|
47437
47637
|
if (!bytes.length || bytes.includes(0)) return 0;
|
|
@@ -47655,13 +47855,13 @@ async function gitPulls(cwd) {
|
|
|
47655
47855
|
}
|
|
47656
47856
|
}
|
|
47657
47857
|
async function repositoryPath(root, raw, allowRoot = false) {
|
|
47658
|
-
if (typeof raw !== "string" || raw.length > 4096 || raw.includes("\0") ||
|
|
47858
|
+
if (typeof raw !== "string" || raw.length > 4096 || raw.includes("\0") || path78.isAbsolute(raw) || path78.win32.isAbsolute(raw) || raw.startsWith("\\")) throw new BridgeError(400, "Invalid path.");
|
|
47659
47859
|
const segments = raw.split(/[\\/]/);
|
|
47660
47860
|
if (segments.includes("..")) throw new BridgeError(400, "Invalid path.");
|
|
47661
47861
|
const clean2 = segments.filter((part) => part && part !== ".").join("/");
|
|
47662
47862
|
if (!clean2 && !allowRoot || clean2.startsWith("-")) throw new BridgeError(400, "Invalid path.");
|
|
47663
|
-
const abs =
|
|
47664
|
-
if (abs !== root && !abs.startsWith(root +
|
|
47863
|
+
const abs = path78.resolve(root, clean2);
|
|
47864
|
+
if (abs !== root && !abs.startsWith(root + path78.sep)) throw new BridgeError(403, "This path is outside the repository.");
|
|
47665
47865
|
let existing = abs;
|
|
47666
47866
|
while (true) {
|
|
47667
47867
|
try {
|
|
@@ -47669,7 +47869,7 @@ async function repositoryPath(root, raw, allowRoot = false) {
|
|
|
47669
47869
|
break;
|
|
47670
47870
|
} catch (error62) {
|
|
47671
47871
|
if (error62.code !== "ENOENT" || existing === root) throw new BridgeError(400, "Invalid path.");
|
|
47672
|
-
existing =
|
|
47872
|
+
existing = path78.dirname(existing);
|
|
47673
47873
|
}
|
|
47674
47874
|
}
|
|
47675
47875
|
let resolved;
|
|
@@ -47678,7 +47878,7 @@ async function repositoryPath(root, raw, allowRoot = false) {
|
|
|
47678
47878
|
} catch {
|
|
47679
47879
|
throw new BridgeError(403, "This path cannot be resolved inside the repository.");
|
|
47680
47880
|
}
|
|
47681
|
-
if (resolved !== root && !resolved.startsWith(root +
|
|
47881
|
+
if (resolved !== root && !resolved.startsWith(root + path78.sep)) throw new BridgeError(403, "This path is outside the repository.");
|
|
47682
47882
|
return clean2;
|
|
47683
47883
|
}
|
|
47684
47884
|
var treeCache = /* @__PURE__ */ new Map();
|
|
@@ -47760,7 +47960,7 @@ async function ignoredEntries(root, prefix, shown) {
|
|
|
47760
47960
|
const entries2 = /* @__PURE__ */ new Map();
|
|
47761
47961
|
const inside = prefix && listing.some((item) => item.endsWith("/") && (prefix + "/").startsWith(item));
|
|
47762
47962
|
if (inside) {
|
|
47763
|
-
const dirents = await readdir15(
|
|
47963
|
+
const dirents = await readdir15(path78.join(root, prefix), { withFileTypes: true }).catch(() => []);
|
|
47764
47964
|
for (const dirent of dirents) {
|
|
47765
47965
|
if (dirent.name === ".git" || taken.has(dirent.name) || entries2.size >= MAX_IGNORED_ENTRIES) continue;
|
|
47766
47966
|
entries2.set(dirent.name, { name: dirent.name, path: `${prefix}/${dirent.name}`, kind: dirent.isDirectory() ? "dir" : "file", ignored: true });
|
|
@@ -47859,7 +48059,7 @@ init_protocol();
|
|
|
47859
48059
|
import { createHash as createHash18 } from "node:crypto";
|
|
47860
48060
|
import { realpath as realpath17, stat as stat24 } from "node:fs/promises";
|
|
47861
48061
|
import { homedir as homedir19 } from "node:os";
|
|
47862
|
-
import
|
|
48062
|
+
import path79 from "node:path";
|
|
47863
48063
|
var MAX_WORKTREES = 64;
|
|
47864
48064
|
var worktreeIdPattern = /^[a-f0-9]{32}$/;
|
|
47865
48065
|
function worktreeId(abs) {
|
|
@@ -47898,11 +48098,11 @@ async function listed(root) {
|
|
|
47898
48098
|
}
|
|
47899
48099
|
function displayPath(abs, roots) {
|
|
47900
48100
|
for (const root of roots) {
|
|
47901
|
-
const rel =
|
|
47902
|
-
if (rel && !rel.startsWith("..") && !
|
|
48101
|
+
const rel = path79.relative(root, abs);
|
|
48102
|
+
if (rel && !rel.startsWith("..") && !path79.isAbsolute(rel)) return rel.split(path79.sep).join("/");
|
|
47903
48103
|
}
|
|
47904
48104
|
const home = homedir19();
|
|
47905
|
-
return abs === home ? "~" : abs.startsWith(home +
|
|
48105
|
+
return abs === home ? "~" : abs.startsWith(home + path79.sep) ? "~/" + path79.relative(home, abs).split(path79.sep).join("/") : abs;
|
|
47906
48106
|
}
|
|
47907
48107
|
function uncommitted(status) {
|
|
47908
48108
|
const tokens = status.split("\0");
|
|
@@ -47916,12 +48116,12 @@ function uncommitted(status) {
|
|
|
47916
48116
|
return count2;
|
|
47917
48117
|
}
|
|
47918
48118
|
async function workerFor(abs, workers, all = []) {
|
|
47919
|
-
const nested = all.filter((other) => other.startsWith(abs +
|
|
48119
|
+
const nested = all.filter((other) => other.startsWith(abs + path79.sep));
|
|
47920
48120
|
let best;
|
|
47921
48121
|
for (const worker of workers) {
|
|
47922
|
-
const cwd = await realpath17(worker.cwd).catch(() =>
|
|
47923
|
-
if (cwd !== abs && !cwd.startsWith(abs +
|
|
47924
|
-
if (nested.some((inner) => cwd === inner || cwd.startsWith(inner +
|
|
48122
|
+
const cwd = await realpath17(worker.cwd).catch(() => path79.resolve(worker.cwd));
|
|
48123
|
+
if (cwd !== abs && !cwd.startsWith(abs + path79.sep)) continue;
|
|
48124
|
+
if (nested.some((inner) => cwd === inner || cwd.startsWith(inner + path79.sep))) continue;
|
|
47925
48125
|
const score = (cwd === abs ? 2 : 0) + (worker.child ? 1 : 0);
|
|
47926
48126
|
if (!best || score > best.score) best = { worker, score };
|
|
47927
48127
|
}
|
|
@@ -48305,7 +48505,7 @@ function herdrWorktreeWorkers(s) {
|
|
|
48305
48505
|
const workers = [];
|
|
48306
48506
|
for (const pane of objects(s.panes)) {
|
|
48307
48507
|
const cwd = pane.foreground_cwd || pane.cwd;
|
|
48308
|
-
if (typeof pane.agent !== "string" || typeof cwd !== "string" || !
|
|
48508
|
+
if (typeof pane.agent !== "string" || typeof cwd !== "string" || !path80.isAbsolute(cwd)) continue;
|
|
48309
48509
|
const name = paneAgentName(s, pane);
|
|
48310
48510
|
workers.push({
|
|
48311
48511
|
cwd,
|
|
@@ -48624,7 +48824,7 @@ async function paneRouteOnce(ctx, url2, data, response, typing) {
|
|
|
48624
48824
|
|
|
48625
48825
|
// src/bridge/server-launch.ts
|
|
48626
48826
|
import { mkdir as mkdir20, readFile as readFile32 } from "node:fs/promises";
|
|
48627
|
-
import
|
|
48827
|
+
import path82 from "node:path";
|
|
48628
48828
|
init_zod();
|
|
48629
48829
|
init_home_paths();
|
|
48630
48830
|
init_herdr();
|
|
@@ -48636,7 +48836,7 @@ init_utils_helpers();
|
|
|
48636
48836
|
init_metrics();
|
|
48637
48837
|
import { execFile as execFile17 } from "node:child_process";
|
|
48638
48838
|
import { mkdir as mkdir19, realpath as realpath18, rm as rm9, stat as stat26 } from "node:fs/promises";
|
|
48639
|
-
import
|
|
48839
|
+
import path81 from "node:path";
|
|
48640
48840
|
import { promisify as promisify16 } from "node:util";
|
|
48641
48841
|
init_protocol();
|
|
48642
48842
|
var exec16 = promisify16(execFile17);
|
|
@@ -48665,11 +48865,11 @@ async function createLaunchWorktree(cwd, request6) {
|
|
|
48665
48865
|
if (await git6(root, "show-ref", "--verify", "--quiet", `refs/heads/${branch}`).then(() => true, () => false)) {
|
|
48666
48866
|
throw new BridgeError(409, `A branch named "${branch}" already exists in this repository. Choose another branch name.`);
|
|
48667
48867
|
}
|
|
48668
|
-
const worktree =
|
|
48868
|
+
const worktree = path81.join(root, ".claude", "worktrees", worktreeFolderName(branch));
|
|
48669
48869
|
if (await stat26(worktree).then(() => true, () => false)) {
|
|
48670
48870
|
throw new BridgeError(409, `The folder .claude/worktrees/${worktreeFolderName(branch)} already exists. Choose another branch name.`);
|
|
48671
48871
|
}
|
|
48672
|
-
await mkdir19(
|
|
48872
|
+
await mkdir19(path81.dirname(worktree), { recursive: true });
|
|
48673
48873
|
try {
|
|
48674
48874
|
await git6(root, "worktree", "add", "-b", branch, worktree, head);
|
|
48675
48875
|
} catch (error62) {
|
|
@@ -48677,8 +48877,8 @@ async function createLaunchWorktree(cwd, request6) {
|
|
|
48677
48877
|
throw new BridgeError(409, `Git could not create the worktree${detail ? `: ${detail.replace(/^fatal:\s*/, "")}` : "."}`);
|
|
48678
48878
|
}
|
|
48679
48879
|
const abs = await realpath18(worktree);
|
|
48680
|
-
const inside =
|
|
48681
|
-
const start = inside && !inside.startsWith("..") ?
|
|
48880
|
+
const inside = path81.relative(root, await realpath18(cwd));
|
|
48881
|
+
const start = inside && !inside.startsWith("..") ? path81.join(abs, inside) : abs;
|
|
48682
48882
|
const startDir = await stat26(start).then((value2) => value2.isDirectory(), () => false) ? start : abs;
|
|
48683
48883
|
return {
|
|
48684
48884
|
cwd: startDir,
|
|
@@ -48719,12 +48919,12 @@ var launchKinds = ["codex", "claude", "copilot", "opencode"];
|
|
|
48719
48919
|
var plainText = (max) => external_exports.string().min(1).max(max).refine((t) => !/[\x00-\x1f\x7f]/.test(t));
|
|
48720
48920
|
async function conductorBrief() {
|
|
48721
48921
|
let source;
|
|
48722
|
-
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";
|
|
48922
|
+
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";
|
|
48723
48923
|
else {
|
|
48724
|
-
const here =
|
|
48924
|
+
const here = path82.dirname(fileURLToPath(import.meta.url));
|
|
48725
48925
|
for (const candidate of [
|
|
48726
|
-
|
|
48727
|
-
|
|
48926
|
+
path82.join(here, "..", "starter", "global", "skills", "conductor", "SKILL.md"),
|
|
48927
|
+
path82.join(here, "..", "..", "starter", "global", "skills", "conductor", "SKILL.md")
|
|
48728
48928
|
]) {
|
|
48729
48929
|
source = await readFile32(candidate, "utf8").catch(() => void 0);
|
|
48730
48930
|
if (source !== void 0) break;
|
|
@@ -48745,15 +48945,15 @@ function effortArgs(kind, effort) {
|
|
|
48745
48945
|
}
|
|
48746
48946
|
async function prepareConductor(kind, effort, model) {
|
|
48747
48947
|
const brief = await conductorBrief();
|
|
48748
|
-
const briefDirectory =
|
|
48948
|
+
const briefDirectory = path82.join(bridgeRoot(), "conductor");
|
|
48749
48949
|
await mkdir20(briefDirectory, { recursive: true, mode: 448 });
|
|
48750
|
-
const briefFile =
|
|
48950
|
+
const briefFile = path82.join(briefDirectory, "brief.md");
|
|
48751
48951
|
if (await readFile32(briefFile, "utf8").catch(() => void 0) !== brief + "\n") await atomic(briefFile, brief + "\n");
|
|
48752
48952
|
if (kind === "claude") return [...model ? ["--model", model] : [], "--append-system-prompt-file", briefFile, "--effort", effort];
|
|
48753
48953
|
if (kind === "codex") return [...model ? ["--model", model] : [], "-c", `model_reasoning_effort=${effort}`, "-c", `developer_instructions=${JSON.stringify(brief)}`];
|
|
48754
48954
|
if (kind === "opencode") {
|
|
48755
|
-
const directory =
|
|
48756
|
-
const file2 =
|
|
48955
|
+
const directory = path82.join(process.env.XDG_CONFIG_HOME || path82.join(homeDir(), ".config"), "opencode", "agents");
|
|
48956
|
+
const file2 = path82.join(directory, "conductor.md");
|
|
48757
48957
|
const definition = `---
|
|
48758
48958
|
description: Coordinate the owner's work across agent sessions.
|
|
48759
48959
|
mode: primary
|
|
@@ -48790,7 +48990,7 @@ function herdrAgentName(label2) {
|
|
|
48790
48990
|
}
|
|
48791
48991
|
async function launchSession(server, data, options = {}) {
|
|
48792
48992
|
const role = external_exports.enum(["agent", "conductor"]).default("agent").parse(data.role);
|
|
48793
|
-
const projectDirectory = external_exports.string().min(1).max(4096).refine((t) =>
|
|
48993
|
+
const projectDirectory = external_exports.string().min(1).max(4096).refine((t) => path82.isAbsolute(t) && !/[\x00-\x1f\x7f]/.test(t)).parse(data.cwd);
|
|
48794
48994
|
const worktreeRequest = data.worktree === void 0 || data.worktree === null ? void 0 : launchWorktreeSchema.parse(data.worktree);
|
|
48795
48995
|
if (worktreeRequest && role === "conductor") throw new BridgeError(400, "A conductor works across projects, so it cannot start in a worktree.");
|
|
48796
48996
|
const label2 = plainText(200).parse(data.label);
|
|
@@ -48882,7 +49082,7 @@ async function workspaceAction(server, operation, data) {
|
|
|
48882
49082
|
if (tab && !objects(s.tabs).some((t) => t.tab_id === tab && (!workspace || t.workspace_id === workspace))) throw new BridgeError(409, "The tab changed.");
|
|
48883
49083
|
if (pane && !objects(s.panes).some((p) => p.pane_id === pane && (!tab || p.tab_id === tab) && (!workspace || p.workspace_id === workspace))) throw new BridgeError(409, "The pane changed.");
|
|
48884
49084
|
const label2 = data.label === void 0 ? void 0 : external_exports.string().min(1).max(200).refine((t) => !/[\x00-\x1f\x7f]/.test(t)).parse(data.label);
|
|
48885
|
-
const cwd = data.cwd === void 0 ? void 0 : external_exports.string().max(4096).refine((t) =>
|
|
49085
|
+
const cwd = data.cwd === void 0 ? void 0 : external_exports.string().max(4096).refine((t) => path82.isAbsolute(t) && !/[\x00-\x1f\x7f]/.test(t)).parse(data.cwd);
|
|
48886
49086
|
if (operation === "create") await terminalProvider().create(server, { workspace, label: label2, cwd });
|
|
48887
49087
|
else if (!workspace && !tab && !pane) throw new BridgeError(400, "Choose a Herdr destination.");
|
|
48888
49088
|
else if (pane && operation === "focus") await terminalProvider().focusPane(server, pane);
|
|
@@ -49254,7 +49454,7 @@ function createRouteHandler(ctx) {
|
|
|
49254
49454
|
case "/v1/files/range": {
|
|
49255
49455
|
let root;
|
|
49256
49456
|
if (url2.searchParams.get("scope") === "uploads") {
|
|
49257
|
-
root =
|
|
49457
|
+
root = path83.join(bridgeRoot(), "uploads");
|
|
49258
49458
|
} else if (url2.searchParams.has("session")) {
|
|
49259
49459
|
const target = targetFromURL(url2), pane = await validateTarget(target);
|
|
49260
49460
|
const cwd = await gitRepository(pane, target, url2.searchParams.get("child") ?? void 0, url2.searchParams.get("worktree") ?? void 0);
|
|
@@ -49560,7 +49760,7 @@ init_protocol();
|
|
|
49560
49760
|
|
|
49561
49761
|
// src/bridge/transcript-preview.ts
|
|
49562
49762
|
init_codex_threads();
|
|
49563
|
-
import { constants as
|
|
49763
|
+
import { constants as constants6 } from "node:fs";
|
|
49564
49764
|
import { open as open16 } from "node:fs/promises";
|
|
49565
49765
|
init_protocol();
|
|
49566
49766
|
init_transcript_index();
|
|
@@ -49791,7 +49991,7 @@ async function readDeltaPreview(target, file2, rollout) {
|
|
|
49791
49991
|
if (target.source === "codex") return await codexThreadPreview(target.session) ?? (file2 && rollout ? await rollout.read(file2).catch(() => null) : null);
|
|
49792
49992
|
if (target.source !== "opencode" || !file2) return null;
|
|
49793
49993
|
try {
|
|
49794
|
-
const handle = await open16(file2 + ".preview.json",
|
|
49994
|
+
const handle = await open16(file2 + ".preview.json", constants6.O_RDONLY | constants6.O_NOFOLLOW | constants6.O_NONBLOCK);
|
|
49795
49995
|
let bytes;
|
|
49796
49996
|
try {
|
|
49797
49997
|
const stat27 = await handle.stat();
|
|
@@ -50226,7 +50426,7 @@ async function serve(version3) {
|
|
|
50226
50426
|
await mkdir21(root, { recursive: true, mode: 448 });
|
|
50227
50427
|
await chmod5(root, 448);
|
|
50228
50428
|
let computerID2;
|
|
50229
|
-
const identityFile =
|
|
50429
|
+
const identityFile = path84.join(root, "computer-id");
|
|
50230
50430
|
try {
|
|
50231
50431
|
computerID2 = (await readFile33(identityFile, "utf8")).trim();
|
|
50232
50432
|
} catch {
|
|
@@ -50276,7 +50476,7 @@ async function serve(version3) {
|
|
|
50276
50476
|
if (codeReindexer) agentHooks.changes.onRecord = (files) => codeReindexer.record(files);
|
|
50277
50477
|
function gatewayTiming() {
|
|
50278
50478
|
try {
|
|
50279
|
-
const parsed = JSON.parse(readFileSync32(
|
|
50479
|
+
const parsed = JSON.parse(readFileSync32(path84.join(root, "gateway.json"), "utf8"));
|
|
50280
50480
|
if (typeof parsed.ms === "number" && Number.isFinite(parsed.ms) && parsed.ms >= 0) return Math.round(parsed.ms);
|
|
50281
50481
|
} catch {
|
|
50282
50482
|
}
|
|
@@ -50322,7 +50522,7 @@ async function serve(version3) {
|
|
|
50322
50522
|
}
|
|
50323
50523
|
const stopRetention = modules.has("git") ? await startChangeRetention() : () => {
|
|
50324
50524
|
};
|
|
50325
|
-
if (modules.has("git")) await rm10(
|
|
50525
|
+
if (modules.has("git")) await rm10(path84.join(root, "changes-scratch"), { recursive: true, force: true });
|
|
50326
50526
|
const streams = transcriptStreams({ modules, agentHooks, codexQuestions, sideQuestions, info, activeCapabilities });
|
|
50327
50527
|
const { stream } = streams;
|
|
50328
50528
|
const overview = overviewStream({
|
|
@@ -50472,7 +50672,7 @@ init_phren_paths();
|
|
|
50472
50672
|
import { execFile as execFile18 } from "node:child_process";
|
|
50473
50673
|
import { readFile as readFile34 } from "node:fs/promises";
|
|
50474
50674
|
import { homedir as homedir20, hostname as hostname10, userInfo as userInfo3 } from "node:os";
|
|
50475
|
-
import
|
|
50675
|
+
import path85 from "node:path";
|
|
50476
50676
|
import { promisify as promisify17 } from "node:util";
|
|
50477
50677
|
init_protocol();
|
|
50478
50678
|
var exec17 = promisify17(execFile18);
|
|
@@ -50519,11 +50719,11 @@ async function probe2(host) {
|
|
|
50519
50719
|
return computerId ? { host, computerId, user: field("user") ?? "", client: field("client") } : void 0;
|
|
50520
50720
|
}
|
|
50521
50721
|
async function discoverComputers(options = {}) {
|
|
50522
|
-
const config3 = options.sshConfig ?? await readFile34(
|
|
50722
|
+
const config3 = options.sshConfig ?? await readFile34(path85.join(homedir20(), ".ssh", "config"), "utf8").catch(() => "");
|
|
50523
50723
|
const store = options.store !== void 0 ? options.store : findPhrenPath();
|
|
50524
50724
|
const machines = store ? listMachines(store) : void 0;
|
|
50525
50725
|
const { peers } = await optionalHookPeers();
|
|
50526
|
-
const own2 = (await readFile34(
|
|
50726
|
+
const own2 = (await readFile34(path85.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
|
|
50527
50727
|
const known = new Set([...localNames(), ...peers.flatMap((peer) => [peer.name, peer.address])].map(computerLabel));
|
|
50528
50728
|
const candidates = [.../* @__PURE__ */ new Set([...sshConfigHosts(config3), ...machines?.ok ? Object.keys(machines.data) : []])].filter((host) => !known.has(computerLabel(host))).slice(0, 32);
|
|
50529
50729
|
const [found, peerIds] = await Promise.all([
|
|
@@ -50545,7 +50745,7 @@ function slugName(value2) {
|
|
|
50545
50745
|
async function linkComputer(host, options = {}) {
|
|
50546
50746
|
const remote = await probe2(host);
|
|
50547
50747
|
if (!remote) throw new BridgeError(409, `${host} answers over ssh but Phren Hook is not installed there. Run phren bridge install on it first.`);
|
|
50548
|
-
const own2 = (await readFile34(
|
|
50748
|
+
const own2 = (await readFile34(path85.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
|
|
50549
50749
|
if (remote.computerId === own2) throw new BridgeError(409, `${host} is this computer.`);
|
|
50550
50750
|
const name = computerName.parse(options.name ?? slugName(host));
|
|
50551
50751
|
const as = computerName.parse(options.as ?? slugName(hostname10()));
|
|
@@ -50746,7 +50946,7 @@ async function readSecret(prompt) {
|
|
|
50746
50946
|
// src/bridge/hook-main.ts
|
|
50747
50947
|
init_utils_helpers();
|
|
50748
50948
|
Object.assign(process.env, nonInteractiveGitEnv());
|
|
50749
|
-
runBridge(process.argv.slice(2), "0.3.
|
|
50949
|
+
runBridge(process.argv.slice(2), "0.3.10").then((code) => {
|
|
50750
50950
|
process.exitCode = code;
|
|
50751
50951
|
}).catch((error62) => {
|
|
50752
50952
|
console.error(error62 instanceof Error ? error62.message : "Phren Hook failed.");
|