@phren/cli 0.3.57 → 0.3.58
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/computer-identity.d.ts +4 -2
- package/dist/bridge/computer-identity.js +7 -3
- package/dist/bridge/conductor-group.d.ts +1 -1
- package/dist/bridge/conductor-group.js +2 -2
- package/dist/bridge/conductor-sets.d.ts +6 -0
- package/dist/bridge/conductor-sets.js +8 -2
- package/dist/bridge/server-routes.d.ts +1 -0
- package/dist/bridge/server-routes.js +1 -1
- package/dist/bridge/server.js +6 -1
- package/dist/bridge/simulator-stream.d.ts +118 -0
- package/dist/bridge/simulator-stream.js +284 -0
- package/dist/bridge/simulators.d.ts +12 -0
- package/dist/bridge/simulators.js +32 -26
- package/dist/bridge-hook.mjs +1039 -667
- package/dist/modules/registry.js +2 -2
- package/package.json +1 -1
package/dist/bridge-hook.mjs
CHANGED
|
@@ -23730,10 +23730,10 @@ var init_js_yaml = __esm({
|
|
|
23730
23730
|
* Optional `mark` contains source snippet data. Usually, use
|
|
23731
23731
|
* {@link YAMLException.throwAt} instead of passing it directly.
|
|
23732
23732
|
*/
|
|
23733
|
-
constructor(
|
|
23733
|
+
constructor(reason3, mark) {
|
|
23734
23734
|
super();
|
|
23735
23735
|
this.name = "YAMLException";
|
|
23736
|
-
this.reason =
|
|
23736
|
+
this.reason = reason3;
|
|
23737
23737
|
this.mark = mark;
|
|
23738
23738
|
this.message = formatError2(this, false);
|
|
23739
23739
|
if (Error.captureStackTrace) Error.captureStackTrace(this, this.constructor);
|
|
@@ -24834,9 +24834,9 @@ function normalizeRegistry(parsed, problems, label2, allowEmpty = false) {
|
|
|
24834
24834
|
const stores = [];
|
|
24835
24835
|
let skippedEntries = 0;
|
|
24836
24836
|
for (const [index2, raw] of parsed.stores.entries()) {
|
|
24837
|
-
const skip = (entry2,
|
|
24837
|
+
const skip = (entry2, reason3) => {
|
|
24838
24838
|
skippedEntries += 1;
|
|
24839
|
-
problems.push(`${label2}: store ${entry2} ${
|
|
24839
|
+
problems.push(`${label2}: store ${entry2} ${reason3} \u2014 entry skipped.`);
|
|
24840
24840
|
};
|
|
24841
24841
|
if (!isRecord(raw)) {
|
|
24842
24842
|
skip(`#${index2 + 1}`, "is not a mapping");
|
|
@@ -30005,7 +30005,7 @@ async function childAgentTree(source, session, depth = 0, seen = /* @__PURE__ */
|
|
|
30005
30005
|
return [...verified2, ...fanouts];
|
|
30006
30006
|
}
|
|
30007
30007
|
function publicChildAgents(tree) {
|
|
30008
|
-
return tree.map(({ id: id2, provider: provider2, path: agentPath, callId, state, reason:
|
|
30008
|
+
return tree.map(({ id: id2, provider: provider2, path: agentPath, callId, state, reason: reason3, startedAt: startedAt2, finishedAt, model, worktreeName, branch, computer, remote, fanout, children }) => (
|
|
30009
30009
|
// A blocked worker is finished; the phone's relation contract has no failed
|
|
30010
30010
|
// state, so the reason carries what happened without breaking old clients.
|
|
30011
30011
|
{
|
|
@@ -30017,7 +30017,7 @@ function publicChildAgents(tree) {
|
|
|
30017
30017
|
...state === "failed" || state === "gone" ? { failed: true } : {},
|
|
30018
30018
|
...startedAt2 ? { startedAt: startedAt2 } : {},
|
|
30019
30019
|
...finishedAt ? { finishedAt } : {},
|
|
30020
|
-
...
|
|
30020
|
+
...reason3 !== void 0 ? { reason: reason3 } : {},
|
|
30021
30021
|
...model !== void 0 ? { model } : {},
|
|
30022
30022
|
...worktreeName !== void 0 ? { worktreeName } : {},
|
|
30023
30023
|
...branch !== void 0 ? { branch } : {},
|
|
@@ -34033,16 +34033,16 @@ var require_websocket = __commonJS({
|
|
|
34033
34033
|
process.nextTick(cb, err);
|
|
34034
34034
|
}
|
|
34035
34035
|
}
|
|
34036
|
-
function receiverOnConclude(code,
|
|
34036
|
+
function receiverOnConclude(code, reason3) {
|
|
34037
34037
|
const websocket = this[kWebSocket];
|
|
34038
34038
|
websocket._closeFrameReceived = true;
|
|
34039
|
-
websocket._closeMessage =
|
|
34039
|
+
websocket._closeMessage = reason3;
|
|
34040
34040
|
websocket._closeCode = code;
|
|
34041
34041
|
if (websocket._socket[kWebSocket] === void 0) return;
|
|
34042
34042
|
websocket._socket.removeListener("data", socketOnData);
|
|
34043
34043
|
process.nextTick(resume, websocket._socket);
|
|
34044
34044
|
if (code === 1005) websocket.close();
|
|
34045
|
-
else websocket.close(code,
|
|
34045
|
+
else websocket.close(code, reason3);
|
|
34046
34046
|
}
|
|
34047
34047
|
function receiverOnDrain() {
|
|
34048
34048
|
const websocket = this[kWebSocket];
|
|
@@ -37120,7 +37120,7 @@ var init_package_metadata = __esm({
|
|
|
37120
37120
|
__dirname = path35.dirname(fileURLToPath2(import.meta.url));
|
|
37121
37121
|
ROOT = path35.join(__dirname, "..");
|
|
37122
37122
|
PACKAGE_JSON_PATH = path35.join(ROOT, "package.json");
|
|
37123
|
-
BUNDLED_VERSION = true ? "0.3.
|
|
37123
|
+
BUNDLED_VERSION = true ? "0.3.58" : "0.0.0";
|
|
37124
37124
|
PACKAGE_JSON = readPackageJson();
|
|
37125
37125
|
PACKAGE_NAME = PACKAGE_JSON.name || "phren";
|
|
37126
37126
|
VERSION = PACKAGE_JSON.version || BUNDLED_VERSION;
|
|
@@ -37486,7 +37486,7 @@ var init_registry = __esm({
|
|
|
37486
37486
|
"/v1/sudo/answer",
|
|
37487
37487
|
"/v1/jobs/cleanup"
|
|
37488
37488
|
]),
|
|
37489
|
-
...routes("WS", ["/v1/transcripts", "/v1/status", "/v1/overview", "/v1/speech/transcribe", "/v1/speech/live"])
|
|
37489
|
+
...routes("WS", ["/v1/transcripts", "/v1/status", "/v1/overview", "/v1/speech/transcribe", "/v1/speech/live", "/v1/simulators/stream"])
|
|
37490
37490
|
],
|
|
37491
37491
|
capabilities: [
|
|
37492
37492
|
"hook",
|
|
@@ -37515,6 +37515,7 @@ var init_registry = __esm({
|
|
|
37515
37515
|
"sideQuestions",
|
|
37516
37516
|
"approvalPush",
|
|
37517
37517
|
"simulators",
|
|
37518
|
+
"simulatorStream",
|
|
37518
37519
|
"overviewStream",
|
|
37519
37520
|
"speech",
|
|
37520
37521
|
"speechTimestamps",
|
|
@@ -40277,7 +40278,7 @@ function foldComputers(facts, options = {}) {
|
|
|
40277
40278
|
const unfolded = [];
|
|
40278
40279
|
for (const [name, profile] of rest) {
|
|
40279
40280
|
const claimed = claims.get(profile);
|
|
40280
|
-
if (claimed?.size === 1) fold([...claimed][0], name, profile, false);
|
|
40281
|
+
if (claimed?.size === 1 && ![...claimed][0].local) fold([...claimed][0], name, profile, false);
|
|
40281
40282
|
else unfolded.push([name, profile]);
|
|
40282
40283
|
}
|
|
40283
40284
|
for (const [row, counts] of votes) row.profile = [...counts].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))[0][0];
|
|
@@ -42702,8 +42703,8 @@ var init_schedules = __esm({
|
|
|
42702
42703
|
await notified;
|
|
42703
42704
|
return running2;
|
|
42704
42705
|
} catch (error62) {
|
|
42705
|
-
const
|
|
42706
|
-
return this.finishRun(child.run.id, prepared.schedule, "failed",
|
|
42706
|
+
const reason3 = error62 instanceof Error ? error62.message : "The scheduled agent could not start.";
|
|
42707
|
+
return this.finishRun(child.run.id, prepared.schedule, "failed", reason3);
|
|
42707
42708
|
}
|
|
42708
42709
|
}));
|
|
42709
42710
|
}
|
|
@@ -42716,8 +42717,8 @@ var init_schedules = __esm({
|
|
|
42716
42717
|
return runs[index2];
|
|
42717
42718
|
});
|
|
42718
42719
|
}
|
|
42719
|
-
async finishRun(id2, schedule, status,
|
|
42720
|
-
const run4 = await this.updateRun(id2, { status, finishedAt: this.now().toISOString(), ...
|
|
42720
|
+
async finishRun(id2, schedule, status, reason3, previousNotification) {
|
|
42721
|
+
const run4 = await this.updateRun(id2, { status, finishedAt: this.now().toISOString(), ...reason3 ? { reason: reason3 } : {} });
|
|
42721
42722
|
await previousNotification;
|
|
42722
42723
|
if (run4.blockedStartupPrompt && run4.blockNotified) return run4;
|
|
42723
42724
|
await this.notifyRun(run4, schedule, status === "failed" ? "scheduleFailed" : "scheduleFinished");
|
|
@@ -42733,11 +42734,11 @@ var init_schedules = __esm({
|
|
|
42733
42734
|
this.log(`[schedule] blocked-at-startup record for run ${id2} failed: ${error62 instanceof Error ? error62.message : "unknown error"}`);
|
|
42734
42735
|
}
|
|
42735
42736
|
}
|
|
42736
|
-
async notifyRun(run4, schedule, kind,
|
|
42737
|
+
async notifyRun(run4, schedule, kind, reason3) {
|
|
42737
42738
|
const preference = kind === "scheduleStarted" ? "start" : kind === "scheduleFinished" ? "finish" : "failure";
|
|
42738
42739
|
if (!scheduleNotifications(schedule).has(preference)) return false;
|
|
42739
42740
|
const route2 = scheduleSessionRoute(schedule, run4.launch);
|
|
42740
|
-
const text5 =
|
|
42741
|
+
const text5 = reason3 ?? run4.reason;
|
|
42741
42742
|
const value2 = {
|
|
42742
42743
|
kind,
|
|
42743
42744
|
scheduleId: schedule.id,
|
|
@@ -42841,8 +42842,8 @@ function formatCounts(counts) {
|
|
|
42841
42842
|
return counts && typeof counts.ahead === "number" && typeof counts.behind === "number" ? ` (ahead ${counts.ahead}, behind ${counts.behind})` : "";
|
|
42842
42843
|
}
|
|
42843
42844
|
function logSyncOutcome(phrenPath, source, outcome) {
|
|
42844
|
-
const
|
|
42845
|
-
appendSyncLog(phrenPath, source, `${outcome.ok ? "ok" : "failed"}${
|
|
42845
|
+
const reason3 = firstLine(outcome.detail, 1e3);
|
|
42846
|
+
appendSyncLog(phrenPath, source, `${outcome.ok ? "ok" : "failed"}${reason3 ? ` ${reason3}` : ""}${formatCounts(outcome.counts)}`);
|
|
42846
42847
|
}
|
|
42847
42848
|
function appendSyncLog(phrenPath, source, detail) {
|
|
42848
42849
|
try {
|
|
@@ -44439,8 +44440,8 @@ function checkPermission(phrenPath, action, project) {
|
|
|
44439
44440
|
const role = resolvedActorRole(actor, effectiveAc);
|
|
44440
44441
|
const allowed = rolePermits(role, action);
|
|
44441
44442
|
if (!allowed) {
|
|
44442
|
-
const
|
|
44443
|
-
return { allowed: false, actor, role, reason:
|
|
44443
|
+
const reason3 = role === "denied" ? `Actor "${actor}" is not listed in access-control for ${project ? `project "${project}"` : "global config"}.` : `Actor "${actor}" has role "${role}" which does not permit "${action}".`;
|
|
44444
|
+
return { allowed: false, actor, role, reason: reason3 };
|
|
44444
44445
|
}
|
|
44445
44446
|
return { allowed: true, actor, role };
|
|
44446
44447
|
}
|
|
@@ -45687,13 +45688,13 @@ function resolveAutoFindingTaskItem(phrenPath, project) {
|
|
|
45687
45688
|
const projectDir = safeProjectPath(phrenPath, project);
|
|
45688
45689
|
if (!projectDir) return void 0;
|
|
45689
45690
|
const taskPath = resolveTaskFilePath(phrenPath, project);
|
|
45690
|
-
const
|
|
45691
|
+
const active2 = parseTaskItems(taskPath ?? path66.join(projectDir, "tasks.md")).filter(
|
|
45691
45692
|
(item) => item.section === "Active" && item.stableId
|
|
45692
45693
|
);
|
|
45693
|
-
if (
|
|
45694
|
-
const pinned =
|
|
45694
|
+
if (active2.length === 1) return active2[0].stableId;
|
|
45695
|
+
const pinned = active2.filter((item) => item.pinned);
|
|
45695
45696
|
if (pinned.length === 1) return pinned[0].stableId;
|
|
45696
|
-
const high =
|
|
45697
|
+
const high = active2.filter((item) => item.priority === "high");
|
|
45697
45698
|
if (high.length === 1) return high[0].stableId;
|
|
45698
45699
|
return void 0;
|
|
45699
45700
|
}
|
|
@@ -45724,9 +45725,9 @@ function sessionSortValue(state) {
|
|
|
45724
45725
|
function resolveFindingSessionId(phrenPath, project, explicitSessionId) {
|
|
45725
45726
|
const trimmed = explicitSessionId?.trim();
|
|
45726
45727
|
if (trimmed) return trimmed;
|
|
45727
|
-
const
|
|
45728
|
-
if (
|
|
45729
|
-
const matchingProject =
|
|
45728
|
+
const active2 = listActiveSessions(phrenPath);
|
|
45729
|
+
if (active2.length === 0) return void 0;
|
|
45730
|
+
const matchingProject = active2.filter((session) => session.project === project).sort((a, b) => sessionSortValue(b) - sessionSortValue(a));
|
|
45730
45731
|
if (matchingProject.length > 0) return matchingProject[0].sessionId;
|
|
45731
45732
|
return void 0;
|
|
45732
45733
|
}
|
|
@@ -46708,11 +46709,11 @@ function supersedeFinding(phrenPath, project, findingText, supersededBy) {
|
|
|
46708
46709
|
return phrenOk({ finding: matched.data.text, superseded_by: ref, status: "superseded" });
|
|
46709
46710
|
});
|
|
46710
46711
|
}
|
|
46711
|
-
function retractFinding(phrenPath, project, findingText,
|
|
46712
|
+
function retractFinding(phrenPath, project, findingText, reason3) {
|
|
46712
46713
|
const pathResult = findingsPathForProject(phrenPath, project);
|
|
46713
46714
|
if (!pathResult.ok) return pathResult;
|
|
46714
46715
|
const findingsPath = pathResult.data;
|
|
46715
|
-
const reasonText =
|
|
46716
|
+
const reasonText = reason3.trim();
|
|
46716
46717
|
if (!reasonText) return phrenErr("reason cannot be empty.", PhrenError.EMPTY_INPUT);
|
|
46717
46718
|
return withFileLock(findingsPath, () => {
|
|
46718
46719
|
const lines = fs36.readFileSync(findingsPath, "utf8").split("\n");
|
|
@@ -47936,13 +47937,13 @@ function readPollState(phrenPath) {
|
|
|
47936
47937
|
if (err.code !== "ENOENT") logPeriodicSync(phrenPath, `poll state unreadable: ${errorMessage(err).split("\n")[0]}`);
|
|
47937
47938
|
return {};
|
|
47938
47939
|
}
|
|
47939
|
-
let
|
|
47940
|
+
let reason3;
|
|
47940
47941
|
try {
|
|
47941
47942
|
const value2 = JSON.parse(text5);
|
|
47942
47943
|
if (value2 && typeof value2 === "object" && !Array.isArray(value2)) return value2;
|
|
47943
|
-
|
|
47944
|
+
reason3 = "not a JSON object";
|
|
47944
47945
|
} catch (err) {
|
|
47945
|
-
|
|
47946
|
+
reason3 = errorMessage(err).split("\n")[0];
|
|
47946
47947
|
}
|
|
47947
47948
|
const aside = `${file4}.corrupt-${Date.now()}`;
|
|
47948
47949
|
try {
|
|
@@ -47950,7 +47951,7 @@ function readPollState(phrenPath) {
|
|
|
47950
47951
|
} catch (err) {
|
|
47951
47952
|
debugLog(`poll state rename: ${errorMessage(err)}`);
|
|
47952
47953
|
}
|
|
47953
|
-
logPeriodicSync(phrenPath, `poll state was corrupt (${
|
|
47954
|
+
logPeriodicSync(phrenPath, `poll state was corrupt (${reason3}); moved it to ${path72.basename(aside)} and started fresh`);
|
|
47954
47955
|
return {};
|
|
47955
47956
|
}
|
|
47956
47957
|
async function worktreeBusy(cwd, git9) {
|
|
@@ -48030,8 +48031,8 @@ async function pollStore(phrenPath, seconds2, git9 = runPollGit, now = Date.now(
|
|
|
48030
48031
|
});
|
|
48031
48032
|
if (merged.committedLocalWrites) logPeriodicSync(phrenPath, "committed uncommitted store writes before pull");
|
|
48032
48033
|
if (merged.status === "busy" || merged.status === "conflict") {
|
|
48033
|
-
const
|
|
48034
|
-
return deferred(`Periodic pull deferred: ${
|
|
48034
|
+
const reason3 = merged.status === "conflict" ? `local and remote history diverged. ${merged.detail}` : merged.detail;
|
|
48035
|
+
return deferred(`Periodic pull deferred: ${reason3}`);
|
|
48035
48036
|
}
|
|
48036
48037
|
if (merged.status === "error") return failed3(`Periodic pull failed: ${merged.detail}`);
|
|
48037
48038
|
return finish({ status: merged.status, detail: merged.detail }, true);
|
|
@@ -48500,9 +48501,9 @@ async function probePeer(peer, caller) {
|
|
|
48500
48501
|
}
|
|
48501
48502
|
return { name: peer.name, reachable: true, ms: Date.now() - started, listsBack, ...version2 ? { version: version2 } : {} };
|
|
48502
48503
|
} catch (error62) {
|
|
48503
|
-
const
|
|
48504
|
+
const reason3 = error62 instanceof BridgeError && error62.status === 504 ? "No answer within 5 seconds." : error62 instanceof Error ? error62.message : "Unreachable.";
|
|
48504
48505
|
const code = errorCode(error62);
|
|
48505
|
-
return { name: peer.name, reachable: false, ms: Date.now() - started, error: plainError(
|
|
48506
|
+
return { name: peer.name, reachable: false, ms: Date.now() - started, error: plainError(reason3), ...code ? { code } : {}, listsBack: null };
|
|
48506
48507
|
}
|
|
48507
48508
|
}
|
|
48508
48509
|
function canaryFile(root = bridgeRoot()) {
|
|
@@ -48690,8 +48691,8 @@ function chooseAccount(rooms, blocked = () => void 0) {
|
|
|
48690
48691
|
const best = sorted[0];
|
|
48691
48692
|
if (!best) return { skipped };
|
|
48692
48693
|
const others = sorted.slice(1).map(describe3);
|
|
48693
|
-
const
|
|
48694
|
-
return { choice: { account: best.account, reason:
|
|
48694
|
+
const reason3 = `most headroom: ${describe3(best)}${others.length ? `; over ${others.join(", ")}` : ""}${skipped.length ? `; skipped ${skipped.join(", ")}` : ""}`;
|
|
48695
|
+
return { choice: { account: best.account, reason: reason3.slice(0, 400) }, skipped };
|
|
48695
48696
|
}
|
|
48696
48697
|
function claudeRooms(inventory, usage, now) {
|
|
48697
48698
|
const accounts = inventory?.harnesses.find((entry2) => entry2.source === "claude")?.accounts ?? [];
|
|
@@ -51452,10 +51453,10 @@ async function localCaller() {
|
|
|
51452
51453
|
function callerQuery(caller) {
|
|
51453
51454
|
return new URLSearchParams({ name: caller.name, ...caller.hostKey ? { hostKey: caller.hostKey } : {} }).toString();
|
|
51454
51455
|
}
|
|
51455
|
-
async function askPeers(peers, caller, ask2 = peerRequest) {
|
|
51456
|
+
async function askPeers(peers, caller, ask2 = peerRequest, timeout = 8e3) {
|
|
51456
51457
|
return Promise.all(peers.map(async (peer) => {
|
|
51457
51458
|
try {
|
|
51458
|
-
const answer2 = await ask2(peer, `/v1/conductor?${callerQuery(caller)}`, void 0,
|
|
51459
|
+
const answer2 = await ask2(peer, `/v1/conductor?${callerQuery(caller)}`, void 0, timeout);
|
|
51459
51460
|
const computer = object2(answer2.computer);
|
|
51460
51461
|
const conductor = answer2.conductor && typeof answer2.conductor === "object" ? object2(answer2.conductor) : void 0;
|
|
51461
51462
|
const set2 = object2(answer2.set);
|
|
@@ -52406,10 +52407,10 @@ var init_dispatch = __esm({
|
|
|
52406
52407
|
skipped.push({ computer: item.peer.name, reason: oneWayHint(item.peer.name) });
|
|
52407
52408
|
return false;
|
|
52408
52409
|
}
|
|
52409
|
-
const
|
|
52410
|
-
if (
|
|
52411
|
-
if (
|
|
52412
|
-
if (
|
|
52410
|
+
const reason3 = unusable(data, item.harnesses, true);
|
|
52411
|
+
if (reason3) incapable = true;
|
|
52412
|
+
if (reason3) skipped.push({ computer: item.peer.name, reason: reason3.slice(0, 200) });
|
|
52413
|
+
if (reason3) return false;
|
|
52413
52414
|
const spent = outOfQuota(data, item.usage);
|
|
52414
52415
|
if (spent) {
|
|
52415
52416
|
spentSeen = true;
|
|
@@ -52429,8 +52430,8 @@ var init_dispatch = __esm({
|
|
|
52429
52430
|
const reported = await capacity(peer, caller);
|
|
52430
52431
|
if (reported.outside) throw new BridgeError(409, `${peer.name} is not in this conductor's set. ${oneWayHint(peer.name)}`, { code: "outside_set" });
|
|
52431
52432
|
remoteComputerID = reported.computerId;
|
|
52432
|
-
const
|
|
52433
|
-
if (
|
|
52433
|
+
const reason3 = unusable(data, reported.harnesses, true);
|
|
52434
|
+
if (reason3) throw new BridgeError(409, `${peer.name} cannot run ${data.harness}${data.account ? ` account ${data.account}` : ""}: ${reason3}`);
|
|
52434
52435
|
}
|
|
52435
52436
|
const grant = await findGrant({ action: "dispatch", project: data.project, computer: peer.name });
|
|
52436
52437
|
const agent = originPaneSchema.safeParse(originValue).success;
|
|
@@ -53622,8 +53623,8 @@ var init_session_move = __esm({
|
|
|
53622
53623
|
const peer = data.to.computer ? await (await Promise.resolve().then(() => (init_move_computers(), move_computers_exports))).movePeer(data.to.computer, stableComputerName()) : void 0;
|
|
53623
53624
|
const to = { ...data.to };
|
|
53624
53625
|
if (!peer) delete to.computer;
|
|
53625
|
-
const
|
|
53626
|
-
if (
|
|
53626
|
+
const active2 = (await listMoves(this.now)).find((record5) => record5.from.target.server === target2.server && record5.from.target.pane === target2.pane && record5.state !== "moved" && record5.state !== "failed");
|
|
53627
|
+
if (active2 || [...this.running.keys()].some((key5) => key5 === `${target2.server}\0${target2.pane}`)) throw new BridgeError(409, "This session is already being moved.", { code: "move_in_progress" });
|
|
53627
53628
|
const s = await this.deps.snapshot(target2.server);
|
|
53628
53629
|
const pane = findPane(s, placeOf(target2));
|
|
53629
53630
|
if (!pane) throw new BridgeError(404, "That pane is no longer open.");
|
|
@@ -54048,14 +54049,14 @@ ${safeDocument}`));
|
|
|
54048
54049
|
}
|
|
54049
54050
|
return { reason: `it did not reply with one within ${Math.round(handoffMs / 1e3)} seconds.` };
|
|
54050
54051
|
}
|
|
54051
|
-
async fallback(record4,
|
|
54052
|
+
async fallback(record4, reason3) {
|
|
54052
54053
|
const from = record4.from.target;
|
|
54053
54054
|
const lines = await this.deps.transcript(from).catch(() => []);
|
|
54054
54055
|
const entries2 = conversationEntries(lines, from.source);
|
|
54055
54056
|
const asked = requestIndex(entries2, record4.id);
|
|
54056
54057
|
const original = record4.dispatch ? await this.deps.brief?.(record4.dispatch).catch(() => void 0) : void 0;
|
|
54057
54058
|
return fallbackHandoff({
|
|
54058
|
-
reason:
|
|
54059
|
+
reason: reason3,
|
|
54059
54060
|
from: harnessName({ harness: from.source, account: record4.from.account }),
|
|
54060
54061
|
entries: asked < 0 ? entries2 : entries2.slice(0, asked),
|
|
54061
54062
|
...original ? { original } : {},
|
|
@@ -54183,8 +54184,8 @@ ${safeDocument}`));
|
|
|
54183
54184
|
}
|
|
54184
54185
|
} else await this.deps.terminal.prompt(from.server, paneTarget2.pane, prompt);
|
|
54185
54186
|
} catch (error62) {
|
|
54186
|
-
const
|
|
54187
|
-
throw new Error(`${record4.mode === "new-chat" ? "New chat" : "Target"} started but did not receive the hand-off. The launched pane was left open. ${
|
|
54187
|
+
const reason3 = error62 instanceof Error ? error62.message : String(error62);
|
|
54188
|
+
throw new Error(`${record4.mode === "new-chat" ? "New chat" : "Target"} started but did not receive the hand-off. The launched pane was left open. ${reason3}`);
|
|
54188
54189
|
}
|
|
54189
54190
|
}
|
|
54190
54191
|
if (!samePane4 && record4.mode !== "new-chat") {
|
|
@@ -54279,17 +54280,17 @@ function herdrPaneFromEnv(env = process.env) {
|
|
|
54279
54280
|
}
|
|
54280
54281
|
function herdrSocketError(error62) {
|
|
54281
54282
|
const code = error62.code;
|
|
54282
|
-
const
|
|
54283
|
+
const reason3 = code === "ENOENT" ? "Herdr is not running" : code === "ECONNREFUSED" ? "stale socket, Herdr is not listening" : code === "EACCES" || code === "EPERM" ? "this user may not open Herdr's socket" : void 0;
|
|
54283
54284
|
const tag = code && /^[A-Z0-9_]{1,32}$/.test(code) ? code : "unknown error";
|
|
54284
54285
|
const offline = code === "ENOENT" ? "herdr-not-running" : code === "ECONNREFUSED" ? "herdr-stale-socket" : code === "EACCES" || code === "EPERM" ? "herdr-permission" : "herdr-unreachable";
|
|
54285
|
-
return new BridgeError(503, `Herdr is not reachable on this computer (${tag}${
|
|
54286
|
+
return new BridgeError(503, `Herdr is not reachable on this computer (${tag}${reason3 ? `: ${reason3}` : ""}).`, { code: offline });
|
|
54286
54287
|
}
|
|
54287
54288
|
function noteOptionalReadFailure(what, key4, error62) {
|
|
54288
|
-
const
|
|
54289
|
-
if (optionalReadFailures.get(key4) ===
|
|
54289
|
+
const reason3 = (error62 instanceof Error ? error62.message : String(error62)).split("\n")[0].slice(0, 200);
|
|
54290
|
+
if (optionalReadFailures.get(key4) === reason3) return;
|
|
54290
54291
|
if (optionalReadFailures.size >= 256) optionalReadFailures.clear();
|
|
54291
|
-
optionalReadFailures.set(key4,
|
|
54292
|
-
logger.warn("herdr", `${what} for ${key4} failed: ${
|
|
54292
|
+
optionalReadFailures.set(key4, reason3);
|
|
54293
|
+
logger.warn("herdr", `${what} for ${key4} failed: ${reason3}`);
|
|
54293
54294
|
}
|
|
54294
54295
|
async function rpc(server, method, params = {}, signal, timeoutMs = 1e4) {
|
|
54295
54296
|
const socket = herdrSocket(server);
|
|
@@ -56195,9 +56196,9 @@ var init_git_host_http = __esm({
|
|
|
56195
56196
|
init_projects();
|
|
56196
56197
|
HostApiError = class extends Error {
|
|
56197
56198
|
/** `body` is the host's own JSON for a refusal (gitboy's `details`, say). */
|
|
56198
|
-
constructor(
|
|
56199
|
+
constructor(reason3, message, status = 0, body2 = null) {
|
|
56199
56200
|
super(message);
|
|
56200
|
-
this.reason =
|
|
56201
|
+
this.reason = reason3;
|
|
56201
56202
|
this.status = status;
|
|
56202
56203
|
this.body = body2;
|
|
56203
56204
|
}
|
|
@@ -57184,8 +57185,8 @@ async function gitPullRequest(cwd, draft) {
|
|
|
57184
57185
|
const host = await detectHost(root, branch);
|
|
57185
57186
|
const provider2 = providerFor(host);
|
|
57186
57187
|
if (!provider2) {
|
|
57187
|
-
const { reason:
|
|
57188
|
-
return { ok: false, reason:
|
|
57188
|
+
const { reason: reason3, message } = unknownHost(host);
|
|
57189
|
+
return { ok: false, reason: reason3, message, host };
|
|
57189
57190
|
}
|
|
57190
57191
|
try {
|
|
57191
57192
|
return { ...await provider2.open(root, branch, draft === true, host), host };
|
|
@@ -57200,8 +57201,8 @@ async function gitMergeRequest(cwd, data) {
|
|
|
57200
57201
|
const host = await detectHost(root, branch);
|
|
57201
57202
|
const provider2 = providerFor(host);
|
|
57202
57203
|
if (!provider2) {
|
|
57203
|
-
const { reason:
|
|
57204
|
-
return { ok: false, reason:
|
|
57204
|
+
const { reason: reason3, message } = unknownHost(host);
|
|
57205
|
+
return { ok: false, reason: reason3, message, host };
|
|
57205
57206
|
}
|
|
57206
57207
|
try {
|
|
57207
57208
|
return { ...await provider2.merge(root, request10, host), host };
|
|
@@ -57221,8 +57222,8 @@ async function gitHostToken(cwd, data) {
|
|
|
57221
57222
|
}
|
|
57222
57223
|
const provider2 = providerFor(host);
|
|
57223
57224
|
if (!provider2 || !host.domain || !host.kind) {
|
|
57224
|
-
const { reason:
|
|
57225
|
-
return { ok: false, reason:
|
|
57225
|
+
const { reason: reason3, message } = unknownHost(host);
|
|
57226
|
+
return { ok: false, reason: reason3, message, host };
|
|
57226
57227
|
}
|
|
57227
57228
|
if (host.kind === "github" || !provider2.whoami || !api) return { ok: false, reason: "unsupported", message: "GitHub uses the GitHub CLI's sign-in: run gh auth login on this computer.", host };
|
|
57228
57229
|
const kind = host.kind;
|
|
@@ -58467,20 +58468,20 @@ var init_owner_inbox = __esm({
|
|
|
58467
58468
|
if (data.action === "list") {
|
|
58468
58469
|
const observed = await this.sources();
|
|
58469
58470
|
const { sources, unavailableDispatches = [] } = Array.isArray(observed) ? { sources: observed } : observed;
|
|
58470
|
-
const
|
|
58471
|
+
const active2 = new Map(sources.map((source) => [sourceKey(source), source]));
|
|
58471
58472
|
const retained = /* @__PURE__ */ new Set();
|
|
58472
|
-
const resolve17 = (row,
|
|
58473
|
+
const resolve17 = (row, reason3) => {
|
|
58473
58474
|
row.state = "resolved";
|
|
58474
58475
|
row.live = false;
|
|
58475
58476
|
row.resolvedAt = at2;
|
|
58476
58477
|
row.updatedAt = at2;
|
|
58477
|
-
row.resolution =
|
|
58478
|
+
row.resolution = reason3;
|
|
58478
58479
|
changed = true;
|
|
58479
58480
|
};
|
|
58480
58481
|
for (const row of rows2) {
|
|
58481
58482
|
if (row.kind === "manual") continue;
|
|
58482
58483
|
if (row.state === "resolved" && !row.live) continue;
|
|
58483
|
-
const key4 = sourceKey(row), source = key4 ?
|
|
58484
|
+
const key4 = sourceKey(row), source = key4 ? active2.get(key4) : void 0;
|
|
58484
58485
|
const unavailable = !!row.dispatch && unavailableDispatches.includes(row.dispatch);
|
|
58485
58486
|
const live = !!source && !retained.has(key4);
|
|
58486
58487
|
if (row.live !== live) {
|
|
@@ -58502,7 +58503,7 @@ var init_owner_inbox = __esm({
|
|
|
58502
58503
|
changed = true;
|
|
58503
58504
|
}
|
|
58504
58505
|
}
|
|
58505
|
-
for (const [key4, source] of
|
|
58506
|
+
for (const [key4, source] of active2) {
|
|
58506
58507
|
if (retained.has(key4)) continue;
|
|
58507
58508
|
if (rows2.length >= 1e4) throw new BridgeError(409, "The owner inbox is full.");
|
|
58508
58509
|
rows2.push(itemSchema.parse({ ...source, id: randomUUID22(), state: "open", live: true, createdAt: at2, updatedAt: at2 }));
|
|
@@ -59268,11 +59269,11 @@ var init_prompt_deliveries = __esm({
|
|
|
59268
59269
|
}
|
|
59269
59270
|
/** The message did not reach the agent, and why. It stays matchable, so a
|
|
59270
59271
|
* late submission still turns it delivered. */
|
|
59271
|
-
fail(id2, target2,
|
|
59272
|
+
fail(id2, target2, reason3) {
|
|
59272
59273
|
const record4 = id2 ? this.find(id2, target2) : void 0;
|
|
59273
59274
|
if (!record4 || record4.state === "delivered") return;
|
|
59274
59275
|
record4.state = "failed";
|
|
59275
|
-
record4.reason =
|
|
59276
|
+
record4.reason = reason3.slice(0, 500);
|
|
59276
59277
|
record4.settledAt = this.now();
|
|
59277
59278
|
this.save();
|
|
59278
59279
|
}
|
|
@@ -61029,21 +61030,21 @@ var init_opencode_permissions = __esm({
|
|
|
61029
61030
|
// src/bridge/agent-hook-asks.ts
|
|
61030
61031
|
function appServerApproval(request10) {
|
|
61031
61032
|
const params = request10.params;
|
|
61032
|
-
const
|
|
61033
|
+
const reason3 = typeof params.reason === "string" && params.reason ? { reason: params.reason } : {};
|
|
61033
61034
|
if (request10.method === "item/commandExecution/requestApproval") {
|
|
61034
61035
|
return { tool: "Bash", input: {
|
|
61035
61036
|
...typeof params.command === "string" ? { command: params.command } : {},
|
|
61036
61037
|
...typeof params.cwd === "string" ? { cwd: params.cwd } : {},
|
|
61037
|
-
...
|
|
61038
|
+
...reason3
|
|
61038
61039
|
} };
|
|
61039
61040
|
}
|
|
61040
61041
|
if (request10.method === "item/fileChange/requestApproval") {
|
|
61041
61042
|
const changes = objects(params.changes);
|
|
61042
61043
|
const verb = (change) => object2(change.kind).type === "add" ? "Add" : object2(change.kind).type === "delete" ? "Delete" : "Update";
|
|
61043
61044
|
const patch = changes.filter((change) => typeof change.path === "string").map((change) => `*** ${verb(change)} File: ${change.path}`).join("\n");
|
|
61044
|
-
return { tool: "apply_patch", input: { ...patch ? { patch } : {}, ...typeof params.grantRoot === "string" ? { grantRoot: params.grantRoot } : {}, ...
|
|
61045
|
+
return { tool: "apply_patch", input: { ...patch ? { patch } : {}, ...typeof params.grantRoot === "string" ? { grantRoot: params.grantRoot } : {}, ...reason3 } };
|
|
61045
61046
|
}
|
|
61046
|
-
if (request10.method === "item/permissions/requestApproval") return { tool: "Permissions", input: { permissions: params.permissions ?? {}, ...
|
|
61047
|
+
if (request10.method === "item/permissions/requestApproval") return { tool: "Permissions", input: { permissions: params.permissions ?? {}, ...reason3 } };
|
|
61047
61048
|
return void 0;
|
|
61048
61049
|
}
|
|
61049
61050
|
function appServerDecision(request10, allow) {
|
|
@@ -62388,7 +62389,7 @@ var init_agent_hooks = __esm({
|
|
|
62388
62389
|
* it when the pane leaves waiting or the dialog lines vanish. A remembered
|
|
62389
62390
|
* permission request that is not a dialog keeps the slot untouched. The same
|
|
62390
62391
|
* read notes whether the terminal is reading a password. */
|
|
62391
|
-
async syncTerminalDialog(target2,
|
|
62392
|
+
async syncTerminalDialog(target2, active2) {
|
|
62392
62393
|
const key4 = JSON.stringify(target2), entry2 = this.terminalPrompts.get(key4);
|
|
62393
62394
|
if (target2.source === "opencode" && servedPane(target2.server, target2.pane)) {
|
|
62394
62395
|
if (entry2) this.terminalPrompts.delete(key4);
|
|
@@ -62418,13 +62419,13 @@ var init_agent_hooks = __esm({
|
|
|
62418
62419
|
return;
|
|
62419
62420
|
}
|
|
62420
62421
|
const question2 = !!entry2?.questions?.length;
|
|
62421
|
-
if (question2 && !
|
|
62422
|
+
if (question2 && !active2) {
|
|
62422
62423
|
this.terminalPrompts.delete(key4);
|
|
62423
62424
|
this.passwords.delete(key4);
|
|
62424
62425
|
return;
|
|
62425
62426
|
}
|
|
62426
62427
|
if (!question2 && entry2 && !entry2.dialog && entry2.choice && !entry2.released) return;
|
|
62427
|
-
if (!
|
|
62428
|
+
if (!active2) {
|
|
62428
62429
|
if (entry2) this.terminalPrompts.delete(key4);
|
|
62429
62430
|
this.passwords.delete(key4);
|
|
62430
62431
|
return;
|
|
@@ -65328,9 +65329,9 @@ async function paneRouteOnce(ctx, url2, data, response, typing) {
|
|
|
65328
65329
|
if (/^\/[a-z][a-z0-9_-]*$/i.test(text5.trim())) agentHooks.menuOpened(target2, text5.trim());
|
|
65329
65330
|
if (outcome === "delivered") result = { ok: true, delivered: true, state: "delivered" };
|
|
65330
65331
|
else if (outcome === "unsubmitted") {
|
|
65331
|
-
const
|
|
65332
|
-
if (deliveryId) agentHooks.deliveries.fail(deliveryId, target2,
|
|
65333
|
-
result = { ok: true, deliveryUncertain: true, unsubmitted: true, ...deliveryId ? { state: "failed", reason:
|
|
65332
|
+
const reason3 = "The agent did not take the message; it may still be in its input line.";
|
|
65333
|
+
if (deliveryId) agentHooks.deliveries.fail(deliveryId, target2, reason3);
|
|
65334
|
+
result = { ok: true, deliveryUncertain: true, unsubmitted: true, ...deliveryId ? { state: "failed", reason: reason3 } : {} };
|
|
65334
65335
|
} else {
|
|
65335
65336
|
let confirmed2 = false;
|
|
65336
65337
|
try {
|
|
@@ -66008,10 +66009,10 @@ async function launch(options, reservation = createJob(options)) {
|
|
|
66008
66009
|
child.once("close", (code) => resolve17(cancelled ? 130 : code ?? 1));
|
|
66009
66010
|
});
|
|
66010
66011
|
const timer = setInterval(() => {
|
|
66011
|
-
const
|
|
66012
|
-
if (!
|
|
66013
|
-
fs45.writeFileSync(path119.join(job, "looped.txt"),
|
|
66014
|
-
atomicWriteText(path119.join(job, "blocked.json"), JSON.stringify({ type: "tool_loop", pattern: "", message:
|
|
66012
|
+
const reason3 = watchdog.reason();
|
|
66013
|
+
if (!reason3) return;
|
|
66014
|
+
fs45.writeFileSync(path119.join(job, "looped.txt"), reason3 + "\n", { mode: 384 });
|
|
66015
|
+
atomicWriteText(path119.join(job, "blocked.json"), JSON.stringify({ type: "tool_loop", pattern: "", message: reason3, at: (/* @__PURE__ */ new Date()).toISOString() }));
|
|
66015
66016
|
kill();
|
|
66016
66017
|
}, 3e4);
|
|
66017
66018
|
let exitCode;
|
|
@@ -66575,8 +66576,8 @@ var init_speech = __esm({
|
|
|
66575
66576
|
const entry2 = this.benched.get(model);
|
|
66576
66577
|
return entry2 && entry2.until > this.now() ? entry2.reason : void 0;
|
|
66577
66578
|
}
|
|
66578
|
-
bench(model,
|
|
66579
|
-
this.benched.set(model, { until: this.now() + FALLBACK_HOLD_MS, reason:
|
|
66579
|
+
bench(model, reason3) {
|
|
66580
|
+
this.benched.set(model, { until: this.now() + FALLBACK_HOLD_MS, reason: reason3 });
|
|
66580
66581
|
this.latency.delete(model);
|
|
66581
66582
|
}
|
|
66582
66583
|
/** Records how long a reply took to start; benches the model when the median
|
|
@@ -66672,7 +66673,7 @@ function relayLiveSpeech(client, query, options = {}) {
|
|
|
66672
66673
|
let saidLength = 0, done = false, closed = false, started = false;
|
|
66673
66674
|
let upstream, endpoint = "speech", format = "pcm_24000", elapsed = 0;
|
|
66674
66675
|
let watch2;
|
|
66675
|
-
const finish = (code = 1e3,
|
|
66676
|
+
const finish = (code = 1e3, reason3 = "") => {
|
|
66676
66677
|
if (closed) return;
|
|
66677
66678
|
closed = true;
|
|
66678
66679
|
clearTimeout(limit);
|
|
@@ -66682,7 +66683,7 @@ function relayLiveSpeech(client, query, options = {}) {
|
|
|
66682
66683
|
upstream?.close();
|
|
66683
66684
|
} catch {
|
|
66684
66685
|
}
|
|
66685
|
-
if (client.readyState === OPEN2) client.close(code,
|
|
66686
|
+
if (client.readyState === OPEN2) client.close(code, reason3);
|
|
66686
66687
|
};
|
|
66687
66688
|
const fail = (frame, code = 1011) => {
|
|
66688
66689
|
tell({ type: "error", ...frame });
|
|
@@ -66829,14 +66830,14 @@ function relayLiveSpeech(client, query, options = {}) {
|
|
|
66829
66830
|
fail({ code: "speech-unreachable", error: "Couldn't reach ElevenLabs from this computer." });
|
|
66830
66831
|
}
|
|
66831
66832
|
});
|
|
66832
|
-
socket.on("close", (_code,
|
|
66833
|
+
socket.on("close", (_code, reason3) => {
|
|
66833
66834
|
if (!current2()) return;
|
|
66834
66835
|
if (voiced) {
|
|
66835
66836
|
detach();
|
|
66836
66837
|
fail({ code: "speech-failed", error: "ElevenLabs stopped before the reply was voiced." });
|
|
66837
66838
|
return;
|
|
66838
66839
|
}
|
|
66839
|
-
const why =
|
|
66840
|
+
const why = reason3?.toString("utf8") ?? "";
|
|
66840
66841
|
if (accountFailure(0, why)) {
|
|
66841
66842
|
detach();
|
|
66842
66843
|
fail(liveError(why));
|
|
@@ -66944,6 +66945,656 @@ var init_speech_live = __esm({
|
|
|
66944
66945
|
}
|
|
66945
66946
|
});
|
|
66946
66947
|
|
|
66948
|
+
// src/bridge/simulators.ts
|
|
66949
|
+
import { execFile as execFile26 } from "node:child_process";
|
|
66950
|
+
import { chmod as chmod5, mkdir as mkdir29, readFile as readFile51, rename as rename10, stat as stat26, unlink as unlink9, writeFile as writeFile10 } from "node:fs/promises";
|
|
66951
|
+
import { tmpdir as tmpdir6 } from "node:os";
|
|
66952
|
+
import path121 from "node:path";
|
|
66953
|
+
import { createHash as createHash34, randomUUID as randomUUID29 } from "node:crypto";
|
|
66954
|
+
import { promisify as promisify24 } from "node:util";
|
|
66955
|
+
async function bootedSimulators() {
|
|
66956
|
+
if (process.platform !== "darwin") return [];
|
|
66957
|
+
const { stdout } = await exec21("/usr/bin/xcrun", ["simctl", "list", "devices", "booted", "-j"], { timeout: 8e3, maxBuffer: 4194304 }).catch(() => ({ stdout: "{}" }));
|
|
66958
|
+
let parsed = {};
|
|
66959
|
+
try {
|
|
66960
|
+
parsed = JSON.parse(stdout);
|
|
66961
|
+
} catch {
|
|
66962
|
+
return [];
|
|
66963
|
+
}
|
|
66964
|
+
const list = [];
|
|
66965
|
+
for (const [runtimeID, devices] of Object.entries(parsed.devices ?? {})) {
|
|
66966
|
+
const runtime = runtimeID.replace(/^.*SimRuntime\./, "").replace(/-(\d+)-(\d+)$/, " $1.$2").replace(/-/g, " ");
|
|
66967
|
+
for (const device of devices ?? []) {
|
|
66968
|
+
if (device.state !== "Booted" || !device.udid || !SIMULATOR_UDID.test(device.udid)) continue;
|
|
66969
|
+
list.push({ udid: device.udid.toUpperCase(), name: String(device.name ?? "Simulator").slice(0, 120), runtime });
|
|
66970
|
+
if (list.length >= 16) return list;
|
|
66971
|
+
}
|
|
66972
|
+
}
|
|
66973
|
+
return list;
|
|
66974
|
+
}
|
|
66975
|
+
async function simulatorScreenshot(udid) {
|
|
66976
|
+
if (!SIMULATOR_UDID.test(udid)) throw new BridgeError(400, "Invalid simulator identifier.");
|
|
66977
|
+
if (process.platform !== "darwin") throw new BridgeError(404, "Simulators run on macOS only.");
|
|
66978
|
+
const file4 = path121.join(tmpdir6(), `phren-sim-${randomUUID29()}.png`);
|
|
66979
|
+
try {
|
|
66980
|
+
await exec21("/usr/bin/xcrun", ["simctl", "io", udid, "screenshot", "--type=png", file4], { timeout: 15e3 });
|
|
66981
|
+
return await readFile51(file4);
|
|
66982
|
+
} catch (error62) {
|
|
66983
|
+
if (error62 instanceof BridgeError) throw error62;
|
|
66984
|
+
throw new BridgeError(409, "Couldn't capture that simulator. Is it still booted?");
|
|
66985
|
+
} finally {
|
|
66986
|
+
await unlink9(file4).catch(() => void 0);
|
|
66987
|
+
}
|
|
66988
|
+
}
|
|
66989
|
+
function helper(name) {
|
|
66990
|
+
let build2 = building.get(name);
|
|
66991
|
+
if (!build2) {
|
|
66992
|
+
build2 = buildHelper(name).finally(() => building.delete(name));
|
|
66993
|
+
building.set(name, build2);
|
|
66994
|
+
}
|
|
66995
|
+
return build2;
|
|
66996
|
+
}
|
|
66997
|
+
async function helperSource(name) {
|
|
66998
|
+
const bundled = name === "simtap" ? true ? `// Touches and keys for the iOS Simulator, without AppleScript: the window
|
|
66999
|
+
// is found through the Accessibility API and events are posted with CGEvent,
|
|
67000
|
+
// so one Accessibility grant for this helper is all macOS asks for.
|
|
67001
|
+
// Built on demand by Phren Hook with swiftc; see simulators.ts.
|
|
67002
|
+
import ApplicationServices
|
|
67003
|
+
import Cocoa
|
|
67004
|
+
|
|
67005
|
+
func fail(_ code: Int32, _ message: String) -> Never { FileHandle.standardError.write((message + "\\n").data(using: .utf8)!); exit(code) }
|
|
67006
|
+
|
|
67007
|
+
let args = CommandLine.arguments
|
|
67008
|
+
guard args.count >= 3 else { fail(2, "usage: simtap <window-title-prefix> tap <fx> <fy> | key <keycode> [cmd] [shift] | type <text> | raise | prompt") }
|
|
67009
|
+
let prefix = args[1], command = args[2]
|
|
67010
|
+
|
|
67011
|
+
// "prompt" asks macOS for the grant: it adds this helper to Privacy & Security
|
|
67012
|
+
// \u2192 Accessibility (switched off) and shows the system's own dialog, so the
|
|
67013
|
+
// person switches it on instead of hunting for a hidden folder behind +.
|
|
67014
|
+
if command == "prompt" {
|
|
67015
|
+
let options = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary
|
|
67016
|
+
exit(AXIsProcessTrustedWithOptions(options) ? 0 : 3)
|
|
67017
|
+
}
|
|
67018
|
+
guard AXIsProcessTrusted() else { fail(3, "accessibility") }
|
|
67019
|
+
guard let app = NSRunningApplication.runningApplications(withBundleIdentifier: "com.apple.iphonesimulator").first else { fail(4, "Simulator is not running") }
|
|
67020
|
+
let element = AXUIElementCreateApplication(app.processIdentifier)
|
|
67021
|
+
var windowsRef: CFTypeRef?
|
|
67022
|
+
AXUIElementCopyAttributeValue(element, kAXWindowsAttribute as CFString, &windowsRef)
|
|
67023
|
+
let windows = (windowsRef as? [AXUIElement]) ?? []
|
|
67024
|
+
var target: AXUIElement?
|
|
67025
|
+
for window in windows {
|
|
67026
|
+
var titleRef: CFTypeRef?
|
|
67027
|
+
AXUIElementCopyAttributeValue(window, kAXTitleAttribute as CFString, &titleRef)
|
|
67028
|
+
if let title = titleRef as? String, title.hasPrefix(prefix + " ") || title == prefix { target = window; break }
|
|
67029
|
+
}
|
|
67030
|
+
guard let window = target else { fail(5, "no window for \\(prefix)") }
|
|
67031
|
+
|
|
67032
|
+
func frame(_ window: AXUIElement) -> CGRect {
|
|
67033
|
+
var posRef: CFTypeRef?, sizeRef: CFTypeRef?
|
|
67034
|
+
AXUIElementCopyAttributeValue(window, kAXPositionAttribute as CFString, &posRef)
|
|
67035
|
+
AXUIElementCopyAttributeValue(window, kAXSizeAttribute as CFString, &sizeRef)
|
|
67036
|
+
var pos = CGPoint.zero, size = CGSize.zero
|
|
67037
|
+
if let p = posRef { AXValueGetValue(p as! AXValue, .cgPoint, &pos) }
|
|
67038
|
+
if let s = sizeRef { AXValueGetValue(s as! AXValue, .cgSize, &size) }
|
|
67039
|
+
return CGRect(origin: pos, size: size)
|
|
67040
|
+
}
|
|
67041
|
+
func raise() {
|
|
67042
|
+
app.activate(options: [])
|
|
67043
|
+
AXUIElementPerformAction(window, kAXRaiseAction as CFString)
|
|
67044
|
+
usleep(120_000)
|
|
67045
|
+
}
|
|
67046
|
+
func post(_ event: CGEvent?) {
|
|
67047
|
+
guard NSWorkspace.shared.frontmostApplication?.processIdentifier == app.processIdentifier else { fail(6, "focus lost") }
|
|
67048
|
+
event?.postToPid(app.processIdentifier)
|
|
67049
|
+
usleep(40_000)
|
|
67050
|
+
}
|
|
67051
|
+
|
|
67052
|
+
switch command {
|
|
67053
|
+
case "raise": raise()
|
|
67054
|
+
case "tap":
|
|
67055
|
+
guard args.count >= 5, let fx = Double(args[3]), let fy = Double(args[4]) else { fail(2, "tap needs fx fy") }
|
|
67056
|
+
raise()
|
|
67057
|
+
let f = frame(window)
|
|
67058
|
+
// The device screen fills the window below its title bar.
|
|
67059
|
+
let titleBar: CGFloat = 28
|
|
67060
|
+
let point = CGPoint(x: f.origin.x + CGFloat(fx) * f.width, y: f.origin.y + titleBar + CGFloat(fy) * (f.height - titleBar))
|
|
67061
|
+
post(CGEvent(mouseEventSource: nil, mouseType: .mouseMoved, mouseCursorPosition: point, mouseButton: .left))
|
|
67062
|
+
post(CGEvent(mouseEventSource: nil, mouseType: .leftMouseDown, mouseCursorPosition: point, mouseButton: .left))
|
|
67063
|
+
post(CGEvent(mouseEventSource: nil, mouseType: .leftMouseUp, mouseCursorPosition: point, mouseButton: .left))
|
|
67064
|
+
case "key":
|
|
67065
|
+
guard args.count >= 4, let code = UInt16(args[3]) else { fail(2, "key needs a keycode") }
|
|
67066
|
+
raise()
|
|
67067
|
+
var flags: CGEventFlags = []
|
|
67068
|
+
if args.contains("cmd") { flags.insert(.maskCommand) }
|
|
67069
|
+
if args.contains("shift") { flags.insert(.maskShift) }
|
|
67070
|
+
let down = CGEvent(keyboardEventSource: nil, virtualKey: code, keyDown: true), up = CGEvent(keyboardEventSource: nil, virtualKey: code, keyDown: false)
|
|
67071
|
+
down?.flags = flags; up?.flags = flags
|
|
67072
|
+
post(down); post(up)
|
|
67073
|
+
case "type":
|
|
67074
|
+
guard args.count >= 4, !args[3].isEmpty, args[3].utf16.count <= 500 else { fail(2, "type needs at most 500 characters") }
|
|
67075
|
+
let submit = args.count == 5 && args[4] == "submit"
|
|
67076
|
+
guard args[3].unicodeScalars.allSatisfy({ scalar in
|
|
67077
|
+
(scalar.value >= 32 && scalar.value != 127) || (scalar.value == 10 && submit)
|
|
67078
|
+
}) else { fail(2, "invalid type controls; newline needs submit") }
|
|
67079
|
+
raise()
|
|
67080
|
+
for scalar in args[3].unicodeScalars {
|
|
67081
|
+
var chars = Array(String(scalar).utf16)
|
|
67082
|
+
let down = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: true), up = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: false)
|
|
67083
|
+
down?.keyboardSetUnicodeString(stringLength: chars.count, unicodeString: &chars)
|
|
67084
|
+
up?.keyboardSetUnicodeString(stringLength: chars.count, unicodeString: &chars)
|
|
67085
|
+
post(down); post(up)
|
|
67086
|
+
}
|
|
67087
|
+
default: fail(2, "unknown command \\(command)")
|
|
67088
|
+
}
|
|
67089
|
+
` : void 0 : true ? `// Live frames of one simulator's screen for Phren Hook's stream
|
|
67090
|
+
// (simulator-stream.ts). It reads the device's own framebuffer through
|
|
67091
|
+
// CoreSimulator, as \`simctl io\` does, so macOS asks for no Screen Recording
|
|
67092
|
+
// grant and the Simulator window may be covered, hidden or closed. Each
|
|
67093
|
+
// changed frame is scaled and JPEG-encoded with Core Image and written to
|
|
67094
|
+
// stdout as a 4-byte big-endian length and the JPEG. Built on demand by
|
|
67095
|
+
// Phren Hook with swiftc, like simtap.
|
|
67096
|
+
import CoreImage
|
|
67097
|
+
import Foundation
|
|
67098
|
+
import IOSurface
|
|
67099
|
+
|
|
67100
|
+
func fail(_ code: Int32, _ message: String) -> Never { FileHandle.standardError.write((message + "\\n").data(using: .utf8)!); exit(code) }
|
|
67101
|
+
|
|
67102
|
+
let args = CommandLine.arguments
|
|
67103
|
+
guard args.count == 5, let udid = UUID(uuidString: args[1]), let fps = Int(args[2]), (1...30).contains(fps),
|
|
67104
|
+
let maxSide = Int(args[3]), (160...2400).contains(maxSide), let quality = Double(args[4]), quality >= 0.1, quality <= 1
|
|
67105
|
+
else { fail(2, "usage: simcast <udid> <fps 1-30> <max-side 160-2400> <quality 0.1-1>") }
|
|
67106
|
+
|
|
67107
|
+
guard dlopen("/Library/Developer/PrivateFrameworks/CoreSimulator.framework/CoreSimulator", RTLD_NOW) != nil else { fail(4, "CoreSimulator is not installed") }
|
|
67108
|
+
|
|
67109
|
+
/// An Objective-C message by name; nil when this Xcode's CoreSimulator lacks it.
|
|
67110
|
+
func call(_ target: AnyObject?, _ name: String, _ argument: Any? = nil) -> AnyObject? {
|
|
67111
|
+
let selector = NSSelectorFromString(name)
|
|
67112
|
+
guard let object = target as? NSObjectProtocol, object.responds(to: selector) else { return nil }
|
|
67113
|
+
return object.perform(selector, with: argument, with: nil)?.takeUnretainedValue()
|
|
67114
|
+
}
|
|
67115
|
+
/// An unsigned scalar getter by name. Sent with objc_msgSend rather than key-value
|
|
67116
|
+
/// coding, which CoreSimulator's proxies (ROCKImmutableProxy) refuse.
|
|
67117
|
+
let send = unsafeBitCast(dlsym(UnsafeMutableRawPointer(bitPattern: -2), "objc_msgSend"), to: (@convention(c) (AnyObject, Selector) -> UInt).self)
|
|
67118
|
+
func number(_ target: AnyObject?, _ name: String, bits: UInt = 64) -> Int? {
|
|
67119
|
+
let selector = NSSelectorFromString(name)
|
|
67120
|
+
guard let object = target as? NSObjectProtocol, object.responds(to: selector) else { return nil }
|
|
67121
|
+
let value = send(object, selector)
|
|
67122
|
+
return Int(bits >= 64 ? value : value & ((1 << bits) - 1))
|
|
67123
|
+
}
|
|
67124
|
+
|
|
67125
|
+
let developerDir: String = {
|
|
67126
|
+
if let dir = ProcessInfo.processInfo.environment["DEVELOPER_DIR"], !dir.isEmpty { return dir }
|
|
67127
|
+
let pipe = Pipe(), process = Process()
|
|
67128
|
+
process.executableURL = URL(fileURLWithPath: "/usr/bin/xcode-select"); process.arguments = ["-p"]; process.standardOutput = pipe
|
|
67129
|
+
try? process.run(); process.waitUntilExit()
|
|
67130
|
+
return String(decoding: pipe.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)
|
|
67131
|
+
}()
|
|
67132
|
+
guard let contextClass = NSClassFromString("SimServiceContext"),
|
|
67133
|
+
let context = call(contextClass, "sharedServiceContextForDeveloperDir:error:", developerDir),
|
|
67134
|
+
let deviceSet = call(context, "defaultDeviceSetWithError:"),
|
|
67135
|
+
let devices = call(deviceSet, "devices") as? [AnyObject]
|
|
67136
|
+
else { fail(4, "CoreSimulator did not answer") }
|
|
67137
|
+
guard let device = devices.first(where: { (call($0, "UDID") as? NSUUID)?.uuidString == udid.uuidString }) else { fail(5, "no such simulator") }
|
|
67138
|
+
// SimDeviceState 3 is Booted.
|
|
67139
|
+
guard number(device, "state") == 3 else { fail(5, "not booted") }
|
|
67140
|
+
|
|
67141
|
+
/// The device's main display: the IO port whose descriptor renders to an
|
|
67142
|
+
/// IOSurface and whose display class is 0 (not CarPlay or an external one).
|
|
67143
|
+
/// Each of these is a round trip to CoreSimulatorService, so the surface is
|
|
67144
|
+
/// looked up again only every \`relookEvery\` ticks (rotation or a respring swaps
|
|
67145
|
+
/// it) or when it went missing; between lookups a tick reads only its seed.
|
|
67146
|
+
func lookUpFramebuffer() -> IOSurface? {
|
|
67147
|
+
guard let ports = call(call(device, "io"), "ioPorts") as? [AnyObject] else { return nil }
|
|
67148
|
+
for port in ports {
|
|
67149
|
+
guard let descriptor = call(port, "descriptor") else { continue }
|
|
67150
|
+
if let display = number(call(descriptor, "state"), "displayClass", bits: 16), display != 0 { continue }
|
|
67151
|
+
// framebufferSurface since Xcode 13, ioSurface before it.
|
|
67152
|
+
if let surface = (call(descriptor, "framebufferSurface") ?? call(descriptor, "ioSurface")) as? IOSurface { return surface }
|
|
67153
|
+
}
|
|
67154
|
+
return nil
|
|
67155
|
+
}
|
|
67156
|
+
let relookEvery = fps
|
|
67157
|
+
var cached: IOSurface?, ticks = 0
|
|
67158
|
+
func framebuffer() -> IOSurface? {
|
|
67159
|
+
ticks += 1
|
|
67160
|
+
if cached == nil || ticks % relookEvery == 0 { cached = lookUpFramebuffer() }
|
|
67161
|
+
return cached
|
|
67162
|
+
}
|
|
67163
|
+
|
|
67164
|
+
let renderer = CIContext(options: [.cacheIntermediates: false, .name: "simcast"])
|
|
67165
|
+
let sRGB = CGColorSpace(name: CGColorSpace.sRGB)!
|
|
67166
|
+
let output = FileHandle.standardOutput
|
|
67167
|
+
var lastSurface: IOSurface?, lastSeed: UInt32 = 0, missing = 0
|
|
67168
|
+
// PHREN_SIMCAST_STATS=1 prints frames, encode time and bytes every 2 s.
|
|
67169
|
+
let stats = ProcessInfo.processInfo.environment["PHREN_SIMCAST_STATS"] == "1"
|
|
67170
|
+
var statFrames = 0, statBytes = 0, statEncode = 0.0, statSince = DispatchTime.now()
|
|
67171
|
+
|
|
67172
|
+
// Without these macOS treats a helper with no window as background work:
|
|
67173
|
+
// App Nap and timer coalescing held it to about 6 fps of a 24 fps timer.
|
|
67174
|
+
let activity = ProcessInfo.processInfo.beginActivity(options: [.userInitiated, .latencyCritical, .idleSystemSleepDisabled], reason: "Streaming a simulator's screen")
|
|
67175
|
+
let queue = DispatchQueue(label: "simcast", qos: .userInteractive)
|
|
67176
|
+
let timer = DispatchSource.makeTimerSource(flags: .strict, queue: queue)
|
|
67177
|
+
timer.schedule(deadline: .now(), repeating: .nanoseconds(1_000_000_000 / fps), leeway: .milliseconds(2))
|
|
67178
|
+
timer.setEventHandler {
|
|
67179
|
+
// The Hook went away without closing the pipe: stop rather than linger.
|
|
67180
|
+
if getppid() == 1 { exit(0) }
|
|
67181
|
+
guard let surface = framebuffer() else {
|
|
67182
|
+
// A respring drops the port briefly; a shutdown drops it for good.
|
|
67183
|
+
missing += 1
|
|
67184
|
+
if missing > fps * 3 { fail(5, "the simulator's screen went away") }
|
|
67185
|
+
return
|
|
67186
|
+
}
|
|
67187
|
+
missing = 0
|
|
67188
|
+
// The seed moves whenever the surface is written: an unchanged screen
|
|
67189
|
+
// costs one property read per tick and sends nothing.
|
|
67190
|
+
if surface === lastSurface && surface.seed == lastSeed { return }
|
|
67191
|
+
lastSurface = surface; lastSeed = surface.seed
|
|
67192
|
+
let began = DispatchTime.now()
|
|
67193
|
+
var image = CIImage(ioSurface: surface)
|
|
67194
|
+
let longest = max(image.extent.width, image.extent.height)
|
|
67195
|
+
guard longest > 0 else { return }
|
|
67196
|
+
if longest > CGFloat(maxSide) {
|
|
67197
|
+
let scale = CGFloat(maxSide) / longest
|
|
67198
|
+
image = image.samplingLinear().transformed(by: CGAffineTransform(scaleX: scale, y: scale))
|
|
67199
|
+
}
|
|
67200
|
+
guard let jpeg = renderer.jpegRepresentation(of: image, colorSpace: sRGB,
|
|
67201
|
+
options: [CIImageRepresentationOption(rawValue: kCGImageDestinationLossyCompressionQuality as String): quality])
|
|
67202
|
+
else { return }
|
|
67203
|
+
var length = UInt32(jpeg.count).bigEndian
|
|
67204
|
+
// A closed pipe raises SIGPIPE, which ends the helper with the stream.
|
|
67205
|
+
output.write(Data(bytes: &length, count: 4) + jpeg)
|
|
67206
|
+
guard stats else { return }
|
|
67207
|
+
statFrames += 1; statBytes += jpeg.count; statEncode += Double(DispatchTime.now().uptimeNanoseconds - began.uptimeNanoseconds) / 1e6
|
|
67208
|
+
let elapsed = Double(DispatchTime.now().uptimeNanoseconds - statSince.uptimeNanoseconds) / 1e9
|
|
67209
|
+
if elapsed >= 2 {
|
|
67210
|
+
FileHandle.standardError.write(String(format: "stats fps=%.1f encode=%.1fms bytes=%d size=%dx%d\\n", Double(statFrames) / elapsed,
|
|
67211
|
+
statEncode / Double(max(statFrames, 1)), statBytes / max(statFrames, 1), Int(image.extent.width), Int(image.extent.height)).data(using: .utf8)!)
|
|
67212
|
+
statFrames = 0; statBytes = 0; statEncode = 0; statSince = DispatchTime.now()
|
|
67213
|
+
}
|
|
67214
|
+
}
|
|
67215
|
+
timer.resume()
|
|
67216
|
+
dispatchMain()
|
|
67217
|
+
` : void 0;
|
|
67218
|
+
return bundled ?? await readFile51(new URL(`./native/${name}.swift`, import.meta.url), "utf8");
|
|
67219
|
+
}
|
|
67220
|
+
async function buildHelper(name) {
|
|
67221
|
+
const dir = path121.join(bridgeRoot(), "native");
|
|
67222
|
+
const binary = path121.join(dir, name);
|
|
67223
|
+
const code = await helperSource(name);
|
|
67224
|
+
const digest2 = createHash34("sha256").update(code).digest("hex");
|
|
67225
|
+
const saved = await readFile51(binary + ".sha256", "utf8").then(JSON.parse).catch(() => void 0);
|
|
67226
|
+
if (await stat26(binary).catch(() => void 0) && saved?.sourceSha === digest2) return binary;
|
|
67227
|
+
await mkdir29(dir, { recursive: true, mode: 448 });
|
|
67228
|
+
const temporary = path121.join(dir, `${name}.${randomUUID29()}`), source = temporary + ".swift";
|
|
67229
|
+
const sidecar = temporary + ".sha256";
|
|
67230
|
+
try {
|
|
67231
|
+
await writeFile10(source, code, { mode: 384, flag: "wx" });
|
|
67232
|
+
await exec21("/usr/bin/swiftc", ["-O", "-o", temporary, source], { timeout: 18e4 }).catch(() => {
|
|
67233
|
+
throw new BridgeError(409, `Couldn't build the ${HELPER_LABEL[name]} (needs Xcode's swiftc).`);
|
|
67234
|
+
});
|
|
67235
|
+
await chmod5(temporary, 448);
|
|
67236
|
+
const binarySha = createHash34("sha256").update(await readFile51(temporary)).digest("hex");
|
|
67237
|
+
await writeFile10(sidecar, JSON.stringify({ sourceSha: digest2, binarySha }), { mode: 384, flag: "wx" });
|
|
67238
|
+
await rename10(temporary, binary);
|
|
67239
|
+
await rename10(sidecar, binary + ".sha256");
|
|
67240
|
+
} finally {
|
|
67241
|
+
await Promise.all([source, temporary, sidecar].map((file4) => unlink9(file4).catch(() => void 0)));
|
|
67242
|
+
}
|
|
67243
|
+
return binary;
|
|
67244
|
+
}
|
|
67245
|
+
function simtap(name, ...args) {
|
|
67246
|
+
const task2 = inputQueue.catch(() => {
|
|
67247
|
+
}).then(() => executeSimtap(name, ...args));
|
|
67248
|
+
inputQueue = task2;
|
|
67249
|
+
return task2;
|
|
67250
|
+
}
|
|
67251
|
+
async function verifiedHelper(name = "simtap") {
|
|
67252
|
+
const binary = await helper(name);
|
|
67253
|
+
const saved = await readFile51(binary + ".sha256", "utf8").then(JSON.parse).catch(() => void 0);
|
|
67254
|
+
const binarySha = createHash34("sha256").update(await readFile51(binary)).digest("hex");
|
|
67255
|
+
if (!saved || saved.binarySha !== binarySha) throw new BridgeError(409, `${HELPER_LABEL[name][0].toUpperCase()}${HELPER_LABEL[name].slice(1)} integrity check failed.`);
|
|
67256
|
+
return binary;
|
|
67257
|
+
}
|
|
67258
|
+
async function executeSimtap(name, ...args) {
|
|
67259
|
+
const binary = await verifiedHelper();
|
|
67260
|
+
try {
|
|
67261
|
+
await exec21(binary, [name, ...args], { timeout: 6e4 });
|
|
67262
|
+
} catch (error62) {
|
|
67263
|
+
const failure2 = error62;
|
|
67264
|
+
const message = String(failure2?.stderr ?? failure2?.message ?? "");
|
|
67265
|
+
if (/accessibility/.test(message)) {
|
|
67266
|
+
await promptAccessibility(binary, false);
|
|
67267
|
+
throw new BridgeError(403, accessibilityHelp(binary), { code: "simulator-accessibility", helper: binary });
|
|
67268
|
+
}
|
|
67269
|
+
if (/no window/.test(message)) throw new BridgeError(409, "That simulator has no window on screen.");
|
|
67270
|
+
if (/not running/.test(message)) throw new BridgeError(409, "The Simulator app is not running.");
|
|
67271
|
+
throw new BridgeError(409, `The simulator did not take that: ${message.slice(0, 160) || "unknown error"}`);
|
|
67272
|
+
}
|
|
67273
|
+
}
|
|
67274
|
+
function accessibilityHelp(binary) {
|
|
67275
|
+
return `Touches and keys need Accessibility for Phren's simulator helper. On the Mac, open System Settings \u2192 Privacy & Security \u2192 Accessibility and switch on simtap. If it isn't listed, click +, press \u2318\u21E7G, paste ${binary} and click Open.`;
|
|
67276
|
+
}
|
|
67277
|
+
async function promptAccessibility(binary, force) {
|
|
67278
|
+
if (prompted && !force) return false;
|
|
67279
|
+
prompted = true;
|
|
67280
|
+
return exec21(binary, ["-", "prompt"], { timeout: 15e3 }).then(() => true, () => false);
|
|
67281
|
+
}
|
|
67282
|
+
async function simulatorAct(udid, request10) {
|
|
67283
|
+
if (!SIMULATOR_UDID.test(udid)) throw new BridgeError(400, "Invalid simulator identifier.");
|
|
67284
|
+
if (!["boot", "shutdown", "launch", "openurl", "home", "lock", "type", "tap", "screenshot-ready", "accessibility-settings"].includes(request10.action)) throw new BridgeError(400, "Unknown simulator action.");
|
|
67285
|
+
if (process.platform !== "darwin") throw new BridgeError(404, "Simulators run on macOS only.");
|
|
67286
|
+
const simctl = (...args) => exec21("/usr/bin/xcrun", ["simctl", ...args], { timeout: 3e4 }).catch(() => {
|
|
67287
|
+
throw new BridgeError(409, `simctl ${args[0]} failed for that simulator.`);
|
|
67288
|
+
});
|
|
67289
|
+
switch (request10.action) {
|
|
67290
|
+
case "boot":
|
|
67291
|
+
await simctl("boot", udid);
|
|
67292
|
+
break;
|
|
67293
|
+
case "shutdown":
|
|
67294
|
+
await simctl("shutdown", udid);
|
|
67295
|
+
break;
|
|
67296
|
+
case "launch":
|
|
67297
|
+
if (typeof request10.bundleId !== "string" || !/^[A-Za-z0-9][A-Za-z0-9.-]{2,199}$/.test(request10.bundleId)) throw new BridgeError(400, "Invalid bundle identifier.");
|
|
67298
|
+
await simctl("launch", udid, request10.bundleId);
|
|
67299
|
+
break;
|
|
67300
|
+
case "openurl":
|
|
67301
|
+
if (typeof request10.url !== "string" || !/^[a-z][a-z0-9+.-]*:/i.test(request10.url) || request10.url.length > 2048) throw new BridgeError(400, "Invalid URL.");
|
|
67302
|
+
await simctl("openurl", udid, request10.url);
|
|
67303
|
+
break;
|
|
67304
|
+
case "home":
|
|
67305
|
+
await simtap(await deviceName(udid), "key", KEY_H, "cmd", "shift");
|
|
67306
|
+
break;
|
|
67307
|
+
case "lock":
|
|
67308
|
+
await simtap(await deviceName(udid), "key", KEY_L, "cmd");
|
|
67309
|
+
break;
|
|
67310
|
+
case "type":
|
|
67311
|
+
if (typeof request10.text !== "string" || !request10.text || request10.text.length > 500 || /[\x00-\x09\x0b-\x1f\x7f]/.test(request10.text) || request10.text.includes("\n") && request10.submit !== true || request10.submit !== void 0 && typeof request10.submit !== "boolean") throw new BridgeError(400, "Type at most 500 characters; newlines require submit: true and other control characters are forbidden.");
|
|
67312
|
+
await simtap(await deviceName(udid), "type", request10.text, ...request10.submit === true ? ["submit"] : []);
|
|
67313
|
+
break;
|
|
67314
|
+
case "tap": {
|
|
67315
|
+
const { x: x2, y } = request10;
|
|
67316
|
+
if (![x2, y].every((v2) => typeof v2 === "number" && v2 >= 0 && v2 <= 1)) throw new BridgeError(400, "Tap outside the screen.");
|
|
67317
|
+
await simtap(await deviceName(udid), "tap", String(x2), String(y));
|
|
67318
|
+
break;
|
|
67319
|
+
}
|
|
67320
|
+
case "screenshot-ready":
|
|
67321
|
+
break;
|
|
67322
|
+
case "accessibility-settings": {
|
|
67323
|
+
const binary = await verifiedHelper();
|
|
67324
|
+
const trusted = await promptAccessibility(binary, true);
|
|
67325
|
+
await exec21("/usr/bin/open", [ACCESSIBILITY_PANE], { timeout: 15e3 }).catch(() => {
|
|
67326
|
+
throw new BridgeError(409, "Couldn't open System Settings on the Mac.");
|
|
67327
|
+
});
|
|
67328
|
+
return { ok: true, trusted, helper: binary };
|
|
67329
|
+
}
|
|
67330
|
+
default:
|
|
67331
|
+
throw new BridgeError(400, "Unknown simulator action.");
|
|
67332
|
+
}
|
|
67333
|
+
return { ok: true };
|
|
67334
|
+
}
|
|
67335
|
+
async function deviceName(udid) {
|
|
67336
|
+
const device = (await bootedSimulators()).find((d) => d.udid === udid.toUpperCase());
|
|
67337
|
+
if (!device) throw new BridgeError(409, "That simulator is not booted.");
|
|
67338
|
+
return String(device.name);
|
|
67339
|
+
}
|
|
67340
|
+
async function simulatorApps(udid) {
|
|
67341
|
+
if (!SIMULATOR_UDID.test(udid)) throw new BridgeError(400, "Invalid simulator identifier.");
|
|
67342
|
+
if (process.platform !== "darwin") return [];
|
|
67343
|
+
const { stdout } = await exec21("/usr/bin/xcrun", ["simctl", "listapps", udid], { timeout: 15e3, maxBuffer: 4194304 }).catch(() => ({ stdout: "" }));
|
|
67344
|
+
const apps = [];
|
|
67345
|
+
const blocks = stdout.split(/\n(?=\s{4}"[^"]+" =\s+\{)/);
|
|
67346
|
+
for (const block of blocks) {
|
|
67347
|
+
const id2 = /CFBundleIdentifier = "?([^";\n]+)"?;/.exec(block)?.[1], name = /CFBundleDisplayName = "?([^";\n]+)"?;/.exec(block)?.[1];
|
|
67348
|
+
const type = /ApplicationType = "?([^";\n]+)"?;/.exec(block)?.[1];
|
|
67349
|
+
if (id2 && name && type === "User" && !/\.xctrunner$/.test(id2)) apps.push({ bundleId: id2, name });
|
|
67350
|
+
}
|
|
67351
|
+
return apps.sort((a, b) => String(a.name).localeCompare(String(b.name))).slice(0, 100);
|
|
67352
|
+
}
|
|
67353
|
+
var execFileAsync, exec21, SIMULATOR_UDID, HELPER_LABEL, building, inputQueue, prompted, ACCESSIBILITY_PANE, KEY_H, KEY_L;
|
|
67354
|
+
var init_simulators = __esm({
|
|
67355
|
+
"src/bridge/simulators.ts"() {
|
|
67356
|
+
"use strict";
|
|
67357
|
+
init_protocol();
|
|
67358
|
+
execFileAsync = promisify24(execFile26);
|
|
67359
|
+
exec21 = (file4, args, options) => execFileAsync(file4, args, { ...options, killSignal: "SIGKILL", encoding: "utf8" });
|
|
67360
|
+
SIMULATOR_UDID = /^[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}$/i;
|
|
67361
|
+
HELPER_LABEL = { simtap: "simulator input helper", simcast: "simulator stream helper" };
|
|
67362
|
+
building = /* @__PURE__ */ new Map();
|
|
67363
|
+
inputQueue = Promise.resolve();
|
|
67364
|
+
prompted = false;
|
|
67365
|
+
ACCESSIBILITY_PANE = "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility";
|
|
67366
|
+
KEY_H = "4";
|
|
67367
|
+
KEY_L = "37";
|
|
67368
|
+
}
|
|
67369
|
+
});
|
|
67370
|
+
|
|
67371
|
+
// src/bridge/simulator-stream.ts
|
|
67372
|
+
import { spawn as spawnChild } from "node:child_process";
|
|
67373
|
+
function streamOptions(query) {
|
|
67374
|
+
const udid = query.get("udid") ?? "";
|
|
67375
|
+
if (!SIMULATOR_UDID.test(udid)) throw new BridgeError(400, "Invalid simulator identifier.");
|
|
67376
|
+
const int2 = (name, fallback2, min, max) => {
|
|
67377
|
+
const raw = query.get(name);
|
|
67378
|
+
if (raw === null) return fallback2;
|
|
67379
|
+
if (!/^\d{1,5}$/.test(raw) || Number(raw) < min || Number(raw) > max) throw new BridgeError(400, `${name} must be a whole number from ${min} to ${max}.`);
|
|
67380
|
+
return Number(raw);
|
|
67381
|
+
};
|
|
67382
|
+
const ack = query.get("ack");
|
|
67383
|
+
if (ack !== null && ack !== "1" && ack !== "0") throw new BridgeError(400, "ack must be 1 or 0.");
|
|
67384
|
+
return { udid: udid.toUpperCase(), fps: int2("fps", 24, 1, 30), size: int2("size", 1280, 240, 1600), quality: int2("quality", 60, 30, 90), ack: ack === "1" };
|
|
67385
|
+
}
|
|
67386
|
+
function reason(text5) {
|
|
67387
|
+
return Buffer.from(text5).subarray(0, 120).toString("utf8").replace(/�+$/, "");
|
|
67388
|
+
}
|
|
67389
|
+
async function streamSimulator(client, query, deps2 = defaultDeps3) {
|
|
67390
|
+
let options;
|
|
67391
|
+
try {
|
|
67392
|
+
options = streamOptions(query);
|
|
67393
|
+
} catch (error62) {
|
|
67394
|
+
client.close(1008, reason(error62.message));
|
|
67395
|
+
return;
|
|
67396
|
+
}
|
|
67397
|
+
if (deps2.platform() !== "darwin") {
|
|
67398
|
+
client.close(1008, "Simulators run on macOS only.");
|
|
67399
|
+
return;
|
|
67400
|
+
}
|
|
67401
|
+
if (active >= MAX_STREAMS) {
|
|
67402
|
+
client.close(1013, "Too many simulator streams; try again.");
|
|
67403
|
+
return;
|
|
67404
|
+
}
|
|
67405
|
+
active++;
|
|
67406
|
+
let released = false;
|
|
67407
|
+
const release = () => {
|
|
67408
|
+
if (!released) {
|
|
67409
|
+
released = true;
|
|
67410
|
+
active--;
|
|
67411
|
+
}
|
|
67412
|
+
};
|
|
67413
|
+
let ended = false, child, killer;
|
|
67414
|
+
const latest = new LatestFrame((frame, done) => {
|
|
67415
|
+
if (client.readyState !== OPEN3) {
|
|
67416
|
+
done(new Error("closed"));
|
|
67417
|
+
return;
|
|
67418
|
+
}
|
|
67419
|
+
client.send(frame, { binary: true }, done);
|
|
67420
|
+
}, { bytesPerSecond: deps2.bytesPerSecond, window: options.ack ? ACK_WINDOW : 1, acked: options.ack });
|
|
67421
|
+
client.on("message", (data, isBinary) => {
|
|
67422
|
+
if (isBinary || data.length > 64) return;
|
|
67423
|
+
try {
|
|
67424
|
+
if (JSON.parse(data.toString("utf8")).type === "ack") latest.ack();
|
|
67425
|
+
} catch {
|
|
67426
|
+
}
|
|
67427
|
+
});
|
|
67428
|
+
const end = (code, why) => {
|
|
67429
|
+
if (ended) return;
|
|
67430
|
+
ended = true;
|
|
67431
|
+
latest.close();
|
|
67432
|
+
if (child) {
|
|
67433
|
+
const running2 = child;
|
|
67434
|
+
running2.kill("SIGTERM");
|
|
67435
|
+
killer = setTimeout(() => running2.kill("SIGKILL"), 2e3);
|
|
67436
|
+
killer.unref?.();
|
|
67437
|
+
running2.once("exit", () => clearTimeout(killer));
|
|
67438
|
+
}
|
|
67439
|
+
if (code !== void 0 && client.readyState === OPEN3) client.close(code, reason(why ?? "Simulator stream ended."));
|
|
67440
|
+
};
|
|
67441
|
+
client.once("close", () => end());
|
|
67442
|
+
client.once("error", () => end());
|
|
67443
|
+
try {
|
|
67444
|
+
if (!(await deps2.booted()).some((device) => device.udid === options.udid)) {
|
|
67445
|
+
end(1008, "That simulator is not booted.");
|
|
67446
|
+
return;
|
|
67447
|
+
}
|
|
67448
|
+
if (ended || client.readyState !== OPEN3) {
|
|
67449
|
+
end();
|
|
67450
|
+
return;
|
|
67451
|
+
}
|
|
67452
|
+
const binary = await deps2.helper();
|
|
67453
|
+
if (ended || client.readyState !== OPEN3) {
|
|
67454
|
+
end();
|
|
67455
|
+
return;
|
|
67456
|
+
}
|
|
67457
|
+
child = deps2.spawn(binary, [options.udid, String(options.fps), String(options.size), (options.quality / 100).toFixed(2)]);
|
|
67458
|
+
child.once("exit", release);
|
|
67459
|
+
child.once("error", release);
|
|
67460
|
+
} catch (error62) {
|
|
67461
|
+
end(1011, error62 instanceof BridgeError ? error62.message : "Couldn't start the simulator stream.");
|
|
67462
|
+
return;
|
|
67463
|
+
} finally {
|
|
67464
|
+
if (!child) release();
|
|
67465
|
+
}
|
|
67466
|
+
const reader = new FrameReader();
|
|
67467
|
+
let stderr = "";
|
|
67468
|
+
child.stderr?.on("data", (chunk) => {
|
|
67469
|
+
stderr = (stderr + chunk.toString("utf8")).slice(-400);
|
|
67470
|
+
});
|
|
67471
|
+
child.stdout?.on("data", (chunk) => {
|
|
67472
|
+
if (ended) return;
|
|
67473
|
+
let frames;
|
|
67474
|
+
try {
|
|
67475
|
+
frames = reader.push(chunk);
|
|
67476
|
+
} catch {
|
|
67477
|
+
end(1011, "The simulator stream sent a broken frame.");
|
|
67478
|
+
return;
|
|
67479
|
+
}
|
|
67480
|
+
for (const frame of frames) latest.offer(frame);
|
|
67481
|
+
});
|
|
67482
|
+
child.once("error", () => end(1011, "Couldn't start the simulator stream."));
|
|
67483
|
+
child.once("exit", () => {
|
|
67484
|
+
const last = stderr.trim().split("\n").at(-1);
|
|
67485
|
+
end(1011, last ? `Simulator stream ended: ${last}` : "Simulator stream ended.");
|
|
67486
|
+
});
|
|
67487
|
+
client.send(JSON.stringify({ type: "start", format: "jpeg", fps: options.fps, size: options.size, quality: options.quality, ack: options.ack }), { binary: false });
|
|
67488
|
+
}
|
|
67489
|
+
var MAX_FRAME_BYTES, STREAM_BYTES_PER_SECOND, MAX_STREAMS, OPEN3, ACK_WINDOW, FrameReader, LatestFrame, defaultDeps3, active;
|
|
67490
|
+
var init_simulator_stream = __esm({
|
|
67491
|
+
"src/bridge/simulator-stream.ts"() {
|
|
67492
|
+
"use strict";
|
|
67493
|
+
init_protocol();
|
|
67494
|
+
init_simulators();
|
|
67495
|
+
MAX_FRAME_BYTES = 4 * 1024 * 1024;
|
|
67496
|
+
STREAM_BYTES_PER_SECOND = 3 * 1024 * 1024;
|
|
67497
|
+
MAX_STREAMS = 4;
|
|
67498
|
+
OPEN3 = 1;
|
|
67499
|
+
ACK_WINDOW = 2;
|
|
67500
|
+
FrameReader = class {
|
|
67501
|
+
buffered = [];
|
|
67502
|
+
bytes = 0;
|
|
67503
|
+
push(chunk) {
|
|
67504
|
+
this.buffered.push(chunk);
|
|
67505
|
+
this.bytes += chunk.length;
|
|
67506
|
+
const frames = [];
|
|
67507
|
+
while (this.bytes >= 4) {
|
|
67508
|
+
const head = this.buffered[0].length >= 4 ? this.buffered[0] : Buffer.concat(this.buffered);
|
|
67509
|
+
const length = head.readUInt32BE(0);
|
|
67510
|
+
if (length === 0 || length > MAX_FRAME_BYTES) throw new Error(`frame of ${length} bytes`);
|
|
67511
|
+
if (this.bytes < 4 + length) break;
|
|
67512
|
+
const all = this.buffered.length === 1 ? this.buffered[0] : Buffer.concat(this.buffered);
|
|
67513
|
+
frames.push(all.subarray(4, 4 + length));
|
|
67514
|
+
const rest = all.subarray(4 + length);
|
|
67515
|
+
this.buffered = rest.length ? [rest] : [];
|
|
67516
|
+
this.bytes = rest.length;
|
|
67517
|
+
}
|
|
67518
|
+
return frames;
|
|
67519
|
+
}
|
|
67520
|
+
};
|
|
67521
|
+
LatestFrame = class {
|
|
67522
|
+
constructor(send2, options = {}, now = Date.now) {
|
|
67523
|
+
this.send = send2;
|
|
67524
|
+
this.options = options;
|
|
67525
|
+
this.now = now;
|
|
67526
|
+
this.tokens = this.bytesPerSecond;
|
|
67527
|
+
this.refilled = now();
|
|
67528
|
+
}
|
|
67529
|
+
send;
|
|
67530
|
+
options;
|
|
67531
|
+
now;
|
|
67532
|
+
waiting;
|
|
67533
|
+
inFlight = 0;
|
|
67534
|
+
tokens;
|
|
67535
|
+
refilled;
|
|
67536
|
+
timer;
|
|
67537
|
+
closed = false;
|
|
67538
|
+
sent = 0;
|
|
67539
|
+
dropped = 0;
|
|
67540
|
+
offer(frame) {
|
|
67541
|
+
if (this.closed) return;
|
|
67542
|
+
if (this.waiting) this.dropped++;
|
|
67543
|
+
this.waiting = frame;
|
|
67544
|
+
this.pump();
|
|
67545
|
+
}
|
|
67546
|
+
/** The phone has a frame; an acknowledgement it owes nothing for is ignored. */
|
|
67547
|
+
ack() {
|
|
67548
|
+
if (!this.options.acked || this.inFlight === 0) return;
|
|
67549
|
+
this.inFlight--;
|
|
67550
|
+
this.pump();
|
|
67551
|
+
}
|
|
67552
|
+
close() {
|
|
67553
|
+
this.closed = true;
|
|
67554
|
+
this.waiting = void 0;
|
|
67555
|
+
clearTimeout(this.timer);
|
|
67556
|
+
}
|
|
67557
|
+
get bytesPerSecond() {
|
|
67558
|
+
return this.options.bytesPerSecond ?? STREAM_BYTES_PER_SECOND;
|
|
67559
|
+
}
|
|
67560
|
+
pump() {
|
|
67561
|
+
if (this.closed || this.inFlight >= (this.options.window ?? 1) || !this.waiting || this.timer) return;
|
|
67562
|
+
const now = this.now();
|
|
67563
|
+
this.tokens = Math.min(this.bytesPerSecond, this.tokens + (now - this.refilled) * this.bytesPerSecond / 1e3);
|
|
67564
|
+
this.refilled = now;
|
|
67565
|
+
if (this.tokens < 0) {
|
|
67566
|
+
this.timer = setTimeout(() => {
|
|
67567
|
+
this.timer = void 0;
|
|
67568
|
+
this.pump();
|
|
67569
|
+
}, Math.ceil(-this.tokens * 1e3 / this.bytesPerSecond));
|
|
67570
|
+
return;
|
|
67571
|
+
}
|
|
67572
|
+
const frame = this.waiting;
|
|
67573
|
+
this.waiting = void 0;
|
|
67574
|
+
this.inFlight++;
|
|
67575
|
+
this.tokens -= frame.length;
|
|
67576
|
+
this.send(frame, (error62) => {
|
|
67577
|
+
if (error62) {
|
|
67578
|
+
this.close();
|
|
67579
|
+
return;
|
|
67580
|
+
}
|
|
67581
|
+
this.sent++;
|
|
67582
|
+
if (this.options.acked) return;
|
|
67583
|
+
this.inFlight--;
|
|
67584
|
+
this.pump();
|
|
67585
|
+
});
|
|
67586
|
+
}
|
|
67587
|
+
};
|
|
67588
|
+
defaultDeps3 = {
|
|
67589
|
+
booted: bootedSimulators,
|
|
67590
|
+
helper: () => verifiedHelper("simcast"),
|
|
67591
|
+
spawn: (binary, args) => spawnChild(binary, args, { stdio: ["ignore", "pipe", "pipe"] }),
|
|
67592
|
+
platform: () => process.platform
|
|
67593
|
+
};
|
|
67594
|
+
active = 0;
|
|
67595
|
+
}
|
|
67596
|
+
});
|
|
67597
|
+
|
|
66947
67598
|
// src/bridge/speech-transcribe.ts
|
|
66948
67599
|
function transcribeURL(query, origin = SPEECH_REGIONS.global) {
|
|
66949
67600
|
const url2 = new URL(ENDPOINT, origin.replace(/^http/, "ws"));
|
|
@@ -66957,7 +67608,7 @@ function transcribeURL(query, origin = SPEECH_REGIONS.global) {
|
|
|
66957
67608
|
return url2.toString();
|
|
66958
67609
|
}
|
|
66959
67610
|
function failRelay(client) {
|
|
66960
|
-
if (client.readyState ===
|
|
67611
|
+
if (client.readyState === OPEN4) client.send(JSON.stringify({ type: "error", code: "transcribe-failed", error: "Couldn't reach ElevenLabs." }));
|
|
66961
67612
|
client.close(1011, "Transcription unavailable");
|
|
66962
67613
|
}
|
|
66963
67614
|
function relayTranscription(client, query, options = {}) {
|
|
@@ -66977,7 +67628,7 @@ function relayTranscription(client, query, options = {}) {
|
|
|
66977
67628
|
return (async () => {
|
|
66978
67629
|
const key4 = await (options.key ?? readSpeechKey)();
|
|
66979
67630
|
const tell = (frame) => {
|
|
66980
|
-
if (client.readyState ===
|
|
67631
|
+
if (client.readyState === OPEN4) client.send(JSON.stringify(frame));
|
|
66981
67632
|
};
|
|
66982
67633
|
if (hungUp) return;
|
|
66983
67634
|
if (!key4) {
|
|
@@ -66989,7 +67640,7 @@ function relayTranscription(client, query, options = {}) {
|
|
|
66989
67640
|
if (hungUp) return;
|
|
66990
67641
|
const upstream = connect5(transcribeURL(query, origin), key4);
|
|
66991
67642
|
let pending3 = [], pendingBytes = 0, closed = false;
|
|
66992
|
-
const finish = (code = 1e3,
|
|
67643
|
+
const finish = (code = 1e3, reason3 = "") => {
|
|
66993
67644
|
if (closed) return;
|
|
66994
67645
|
closed = true;
|
|
66995
67646
|
clearTimeout(limit);
|
|
@@ -66997,10 +67648,10 @@ function relayTranscription(client, query, options = {}) {
|
|
|
66997
67648
|
upstream.close();
|
|
66998
67649
|
} catch {
|
|
66999
67650
|
}
|
|
67000
|
-
if (client.readyState ===
|
|
67651
|
+
if (client.readyState === OPEN4) client.close(code, reason3);
|
|
67001
67652
|
};
|
|
67002
|
-
const end = (
|
|
67003
|
-
if (!closed) tell({ type: "end", reason:
|
|
67653
|
+
const end = (reason3) => {
|
|
67654
|
+
if (!closed) tell({ type: "end", reason: reason3 });
|
|
67004
67655
|
};
|
|
67005
67656
|
const limit = setTimeout(() => {
|
|
67006
67657
|
end("session-limit");
|
|
@@ -67016,11 +67667,11 @@ function relayTranscription(client, query, options = {}) {
|
|
|
67016
67667
|
receive = (data, isBinary) => {
|
|
67017
67668
|
if (closed) return;
|
|
67018
67669
|
if (!isBinary) {
|
|
67019
|
-
if (upstream.readyState ===
|
|
67670
|
+
if (upstream.readyState === OPEN4) upstream.send(chunk(Buffer.alloc(0), true));
|
|
67020
67671
|
else pending3.push(null);
|
|
67021
67672
|
return;
|
|
67022
67673
|
}
|
|
67023
|
-
if (upstream.readyState ===
|
|
67674
|
+
if (upstream.readyState === OPEN4) {
|
|
67024
67675
|
upstream.send(chunk(data));
|
|
67025
67676
|
return;
|
|
67026
67677
|
}
|
|
@@ -67070,7 +67721,7 @@ function relayTranscription(client, query, options = {}) {
|
|
|
67070
67721
|
});
|
|
67071
67722
|
})();
|
|
67072
67723
|
}
|
|
67073
|
-
var TRANSCRIBE_MODEL, TRANSCRIBE_RATE, ENDPOINT, MAX_SESSION_MS2, MAX_PENDING_BYTES, MAX_KEYTERMS,
|
|
67724
|
+
var TRANSCRIBE_MODEL, TRANSCRIBE_RATE, ENDPOINT, MAX_SESSION_MS2, MAX_PENDING_BYTES, MAX_KEYTERMS, OPEN4, ERRORS;
|
|
67074
67725
|
var init_speech_transcribe = __esm({
|
|
67075
67726
|
"src/bridge/speech-transcribe.ts"() {
|
|
67076
67727
|
"use strict";
|
|
@@ -67083,7 +67734,7 @@ var init_speech_transcribe = __esm({
|
|
|
67083
67734
|
MAX_SESSION_MS2 = 10 * 6e4;
|
|
67084
67735
|
MAX_PENDING_BYTES = TRANSCRIBE_RATE * 2 * 8;
|
|
67085
67736
|
MAX_KEYTERMS = 50;
|
|
67086
|
-
|
|
67737
|
+
OPEN4 = 1;
|
|
67087
67738
|
ERRORS = {
|
|
67088
67739
|
auth_error: { code: "transcribe-rejected", message: "ElevenLabs refused this computer's key." },
|
|
67089
67740
|
quota_exceeded: { code: "transcribe-quota", message: "The ElevenLabs quota on this computer's account is used up." },
|
|
@@ -67096,8 +67747,8 @@ var init_speech_transcribe = __esm({
|
|
|
67096
67747
|
});
|
|
67097
67748
|
|
|
67098
67749
|
// src/bridge/activity.ts
|
|
67099
|
-
import { appendFile as appendFile3, mkdir as
|
|
67100
|
-
import
|
|
67750
|
+
import { appendFile as appendFile3, mkdir as mkdir30, readFile as readFile52, rename as rename11, stat as stat27 } from "node:fs/promises";
|
|
67751
|
+
import path122 from "node:path";
|
|
67101
67752
|
var ActivityJournal;
|
|
67102
67753
|
var init_activity2 = __esm({
|
|
67103
67754
|
"src/bridge/activity.ts"() {
|
|
@@ -67129,16 +67780,16 @@ var init_activity2 = __esm({
|
|
|
67129
67780
|
});
|
|
67130
67781
|
}
|
|
67131
67782
|
if (!changes.length) return;
|
|
67132
|
-
const root = bridgeRoot(), file4 =
|
|
67133
|
-
await
|
|
67134
|
-
if ((await
|
|
67783
|
+
const root = bridgeRoot(), file4 = path122.join(root, "activity.jsonl");
|
|
67784
|
+
await mkdir30(root, { recursive: true, mode: 448 });
|
|
67785
|
+
if ((await stat27(file4).catch(() => null))?.size && (await stat27(file4)).size > 2097152) await rename11(file4, file4 + ".previous");
|
|
67135
67786
|
await appendFile3(file4, changes.map((row) => JSON.stringify(row)).join("\n") + "\n", { mode: 384 });
|
|
67136
67787
|
if (this.previous.size > 4096) this.previous.clear();
|
|
67137
67788
|
});
|
|
67138
67789
|
return this.pending;
|
|
67139
67790
|
}
|
|
67140
67791
|
async recent() {
|
|
67141
|
-
const text5 = await
|
|
67792
|
+
const text5 = await readFile52(path122.join(bridgeRoot(), "activity.jsonl"), "utf8").catch(() => "");
|
|
67142
67793
|
return text5.trim().split("\n").slice(-500).flatMap((line) => {
|
|
67143
67794
|
try {
|
|
67144
67795
|
return [JSON.parse(line)];
|
|
@@ -67155,18 +67806,18 @@ var init_activity2 = __esm({
|
|
|
67155
67806
|
import { execFileSync as execFileSync7 } from "node:child_process";
|
|
67156
67807
|
import * as fs46 from "node:fs";
|
|
67157
67808
|
import { homedir as homedir19 } from "node:os";
|
|
67158
|
-
import * as
|
|
67809
|
+
import * as path123 from "node:path";
|
|
67159
67810
|
import { fileURLToPath as fileURLToPath5, pathToFileURL } from "node:url";
|
|
67160
67811
|
function loadedFrom() {
|
|
67161
67812
|
return resolvedFrom;
|
|
67162
67813
|
}
|
|
67163
67814
|
function bridgeRoot2() {
|
|
67164
|
-
return process.env.PHREN_BRIDGE_HOME ||
|
|
67815
|
+
return process.env.PHREN_BRIDGE_HOME || path123.join(homedir19(), ".local/share/phren/bridge");
|
|
67165
67816
|
}
|
|
67166
67817
|
function npmPath() {
|
|
67167
|
-
const entries2 = (process.env.PATH ?? "").split(
|
|
67818
|
+
const entries2 = (process.env.PATH ?? "").split(path123.delimiter).filter(Boolean);
|
|
67168
67819
|
for (const entry2 of EXTRA_PATH) if (!entries2.includes(entry2) && fs46.existsSync(entry2)) entries2.push(entry2);
|
|
67169
|
-
return entries2.join(
|
|
67820
|
+
return entries2.join(path123.delimiter);
|
|
67170
67821
|
}
|
|
67171
67822
|
function npm(args, options) {
|
|
67172
67823
|
const env = { ...process.env, PATH: npmPath() };
|
|
@@ -67174,11 +67825,11 @@ function npm(args, options) {
|
|
|
67174
67825
|
return String(execFileSync7("npm.cmd", args.map((arg) => `"${arg}"`), { ...options, env, shell: true }) ?? "");
|
|
67175
67826
|
}
|
|
67176
67827
|
function packageEntry(directory) {
|
|
67177
|
-
const manifest = JSON.parse(fs46.readFileSync(
|
|
67828
|
+
const manifest = JSON.parse(fs46.readFileSync(path123.join(directory, "package.json"), "utf8"));
|
|
67178
67829
|
const exported = typeof manifest.exports === "object" && manifest.exports !== null && "." in manifest.exports ? manifest.exports["."] : manifest.exports;
|
|
67179
67830
|
const nested = typeof exported === "object" && exported !== null ? exported.default ?? exported.import : exported;
|
|
67180
67831
|
for (const candidate of [nested, manifest.module, manifest.main, "index.js", "index.mjs"]) {
|
|
67181
|
-
if (typeof candidate === "string") return
|
|
67832
|
+
if (typeof candidate === "string") return path123.join(directory, candidate);
|
|
67182
67833
|
}
|
|
67183
67834
|
throw new Error(`@phren/code has no entry point in ${directory}.`);
|
|
67184
67835
|
}
|
|
@@ -67188,7 +67839,7 @@ async function importDirectory(directory) {
|
|
|
67188
67839
|
function globalPackageDirectory() {
|
|
67189
67840
|
try {
|
|
67190
67841
|
const root = npm(["root", "-g"], { encoding: "utf8", timeout: 1e4 }).trim();
|
|
67191
|
-
return root ?
|
|
67842
|
+
return root ? path123.join(root, "@phren", "code") : void 0;
|
|
67192
67843
|
} catch {
|
|
67193
67844
|
return void 0;
|
|
67194
67845
|
}
|
|
@@ -67197,13 +67848,13 @@ async function loadCodePackage(store) {
|
|
|
67197
67848
|
if (loaded) return loaded;
|
|
67198
67849
|
const candidates = [];
|
|
67199
67850
|
if (process.env.PHREN_CODE_PACKAGE) candidates.push(process.env.PHREN_CODE_PACKAGE);
|
|
67200
|
-
candidates.push(
|
|
67851
|
+
candidates.push(path123.join(bridgeRoot2(), "node_modules", "@phren", "code"));
|
|
67201
67852
|
const root = store || process.env.PHREN_PATH;
|
|
67202
|
-
if (root) candidates.push(
|
|
67853
|
+
if (root) candidates.push(path123.join(root, ".runtime", "packages", "node_modules", "@phren", "code"));
|
|
67203
67854
|
const workspace = workspaceCodeDirectory();
|
|
67204
67855
|
if (workspace && builtEntryExists(workspace)) candidates.push(workspace);
|
|
67205
67856
|
for (const directory of candidates) {
|
|
67206
|
-
if (!fs46.existsSync(
|
|
67857
|
+
if (!fs46.existsSync(path123.join(directory, "package.json"))) continue;
|
|
67207
67858
|
try {
|
|
67208
67859
|
loaded = await importDirectory(directory);
|
|
67209
67860
|
resolvedFrom = directory;
|
|
@@ -67219,7 +67870,7 @@ async function loadCodePackage(store) {
|
|
|
67219
67870
|
if (error62.code !== "ERR_MODULE_NOT_FOUND") throw error62;
|
|
67220
67871
|
}
|
|
67221
67872
|
const global = globalPackageDirectory();
|
|
67222
|
-
if (global && fs46.existsSync(
|
|
67873
|
+
if (global && fs46.existsSync(path123.join(global, "package.json"))) {
|
|
67223
67874
|
try {
|
|
67224
67875
|
loaded = await importDirectory(global);
|
|
67225
67876
|
resolvedFrom = global;
|
|
@@ -67230,11 +67881,11 @@ async function loadCodePackage(store) {
|
|
|
67230
67881
|
return void 0;
|
|
67231
67882
|
}
|
|
67232
67883
|
function workspaceCodeDirectory() {
|
|
67233
|
-
let directory =
|
|
67884
|
+
let directory = path123.dirname(fileURLToPath5(import.meta.url));
|
|
67234
67885
|
for (let depth = 0; depth < 8; depth++) {
|
|
67235
|
-
const candidate =
|
|
67236
|
-
if (fs46.existsSync(
|
|
67237
|
-
const parent =
|
|
67886
|
+
const candidate = path123.join(directory, "packages", "code");
|
|
67887
|
+
if (fs46.existsSync(path123.join(candidate, "package.json"))) return candidate;
|
|
67888
|
+
const parent = path123.dirname(directory);
|
|
67238
67889
|
if (parent === directory) break;
|
|
67239
67890
|
directory = parent;
|
|
67240
67891
|
}
|
|
@@ -67249,7 +67900,7 @@ function builtEntryExists(directory) {
|
|
|
67249
67900
|
}
|
|
67250
67901
|
function codePackageHint(store) {
|
|
67251
67902
|
const root = store || process.env.PHREN_PATH;
|
|
67252
|
-
const linked = root &&
|
|
67903
|
+
const linked = root && path123.join(root, ".runtime", "packages", "node_modules", "@phren", "code");
|
|
67253
67904
|
const workspace = workspaceCodeDirectory();
|
|
67254
67905
|
let workspaceLink;
|
|
67255
67906
|
try {
|
|
@@ -67257,7 +67908,7 @@ function codePackageHint(store) {
|
|
|
67257
67908
|
} catch {
|
|
67258
67909
|
}
|
|
67259
67910
|
for (const directory of [workspace, workspaceLink]) {
|
|
67260
|
-
if (!directory || !fs46.existsSync(
|
|
67911
|
+
if (!directory || !fs46.existsSync(path123.join(directory, "package.json")) || builtEntryExists(directory)) continue;
|
|
67261
67912
|
return `${CODE_PACKAGE_HINT}. @phren/code at ${directory} has no built entry. From the source checkout root run: pnpm --filter @phren/code build`;
|
|
67262
67913
|
}
|
|
67263
67914
|
return `${CODE_PACKAGE_HINT}. For a source checkout, from its root run pnpm --filter @phren/code build, then node packages/cli/dist/index.js modules enable code and restart the Hook.`;
|
|
@@ -67267,14 +67918,14 @@ var init_code_package = __esm({
|
|
|
67267
67918
|
"src/modules/code-package.ts"() {
|
|
67268
67919
|
"use strict";
|
|
67269
67920
|
CODE_PACKAGE_HINT = "phren code needs @phren/code: run phren modules enable code";
|
|
67270
|
-
EXTRA_PATH = [
|
|
67921
|
+
EXTRA_PATH = [path123.join(homedir19(), ".local/share/mise/shims"), "/opt/homebrew/bin"];
|
|
67271
67922
|
}
|
|
67272
67923
|
});
|
|
67273
67924
|
|
|
67274
67925
|
// src/bridge/code-routes.ts
|
|
67275
67926
|
import { rm as rm14 } from "node:fs/promises";
|
|
67276
67927
|
import * as fs47 from "node:fs";
|
|
67277
|
-
import * as
|
|
67928
|
+
import * as path124 from "node:path";
|
|
67278
67929
|
async function requireCodePackage(store) {
|
|
67279
67930
|
const code = await loadCodePackage(store);
|
|
67280
67931
|
if (!code) throw new BridgeError(503, codePackageHint(store));
|
|
@@ -67299,13 +67950,13 @@ function noIndex(project) {
|
|
|
67299
67950
|
}
|
|
67300
67951
|
function readHead2(root) {
|
|
67301
67952
|
try {
|
|
67302
|
-
const dotGit =
|
|
67953
|
+
const dotGit = path124.join(root, ".git");
|
|
67303
67954
|
const gitDirectory2 = fs47.statSync(dotGit).isDirectory() ? dotGit : (() => {
|
|
67304
67955
|
const match = /^gitdir:\s*(.+)$/m.exec(fs47.readFileSync(dotGit, "utf8"));
|
|
67305
|
-
return match ?
|
|
67956
|
+
return match ? path124.resolve(root, match[1]) : void 0;
|
|
67306
67957
|
})();
|
|
67307
67958
|
if (!gitDirectory2) return void 0;
|
|
67308
|
-
return fs47.readFileSync(
|
|
67959
|
+
return fs47.readFileSync(path124.join(gitDirectory2, "HEAD"), "utf8").trim();
|
|
67309
67960
|
} catch {
|
|
67310
67961
|
return void 0;
|
|
67311
67962
|
}
|
|
@@ -67329,7 +67980,7 @@ var init_code_routes = __esm({
|
|
|
67329
67980
|
querySchema = external_exports.string().max(500);
|
|
67330
67981
|
symbolSchema = external_exports.string().min(1).max(4600);
|
|
67331
67982
|
pathSchema = external_exports.string().min(1).max(4096).refine((value2) => !value2.includes("\0") && !value2.split("/").includes(".."), "Choose a valid file path.");
|
|
67332
|
-
relativePathSchema = pathSchema.refine((value2) => !
|
|
67983
|
+
relativePathSchema = pathSchema.refine((value2) => !path124.isAbsolute(value2) && !path124.win32.isAbsolute(value2) && !value2.includes("\\") && !value2.split("/").some((part) => part === "." || part === ""));
|
|
67333
67984
|
optionalPath = (value2) => value2 ? relativePathSchema.parse(value2) : void 0;
|
|
67334
67985
|
offsetSchema = external_exports.coerce.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
|
|
67335
67986
|
kindSchema = external_exports.enum(KIND_VALUES);
|
|
@@ -67442,9 +68093,9 @@ var init_code_routes = __esm({
|
|
|
67442
68093
|
};
|
|
67443
68094
|
const midnight = new Date(now);
|
|
67444
68095
|
midnight.setHours(0, 0, 0, 0);
|
|
67445
|
-
const dir =
|
|
68096
|
+
const dir = path124.join(bridgeRoot(), "changes");
|
|
67446
68097
|
const logs = fs47.existsSync(dir) ? fs47.readdirSync(dir).filter((name) => name.endsWith(".jsonl")) : [];
|
|
67447
|
-
const today = logs.map((name) => ({ file:
|
|
68098
|
+
const today = logs.map((name) => ({ file: path124.join(dir, name), at: fs47.statSync(path124.join(dir, name)).mtimeMs })).filter((entry2) => entry2.at >= midnight.getTime()).sort((a, b) => b.at - a.at);
|
|
67448
68099
|
for (const log2 of today) {
|
|
67449
68100
|
for (const line of fs47.readFileSync(log2.file, "utf8").split("\n")) {
|
|
67450
68101
|
if (!line.trim()) continue;
|
|
@@ -67505,7 +68156,7 @@ var init_code_routes = __esm({
|
|
|
67505
68156
|
for (const file4 of untracked) {
|
|
67506
68157
|
let count2 = 0;
|
|
67507
68158
|
try {
|
|
67508
|
-
count2 = fs47.readFileSync(
|
|
68159
|
+
count2 = fs47.readFileSync(path124.join(root, file4), "utf8").split("\n").length;
|
|
67509
68160
|
} catch {
|
|
67510
68161
|
continue;
|
|
67511
68162
|
}
|
|
@@ -67569,7 +68220,7 @@ var init_code_routes = __esm({
|
|
|
67569
68220
|
} catch {
|
|
67570
68221
|
throw new BridgeError(400, "Choose valid paths.");
|
|
67571
68222
|
}
|
|
67572
|
-
const paths = external_exports.array(pathSchema.refine((value2) => !
|
|
68223
|
+
const paths = external_exports.array(pathSchema.refine((value2) => !path124.isAbsolute(value2) && !path124.win32.isAbsolute(value2) && !value2.split(/[\\/]/).includes(".."))).min(1).max(200).parse(raw);
|
|
67573
68224
|
const result = await (await requireCodePackage(this.store)).outlineSummary(this.store, project, [...new Set(paths)]);
|
|
67574
68225
|
if (!result.available) throw noIndex(project);
|
|
67575
68226
|
return { project, entries: result.value };
|
|
@@ -67644,7 +68295,7 @@ var init_code_routes = __esm({
|
|
|
67644
68295
|
const { codeDatabasePath, resolveRepoRoot } = await requireCodePackage(this.store);
|
|
67645
68296
|
const result = [];
|
|
67646
68297
|
for (const directory of getProjectDirs(this.store)) {
|
|
67647
|
-
const project =
|
|
68298
|
+
const project = path124.basename(directory);
|
|
67648
68299
|
if (!fs47.existsSync(codeDatabasePath(this.store, project))) continue;
|
|
67649
68300
|
try {
|
|
67650
68301
|
result.push({ project, root: fs47.realpathSync(resolveRepoRoot(this.store, project)) });
|
|
@@ -67822,11 +68473,11 @@ var init_context2 = __esm({
|
|
|
67822
68473
|
});
|
|
67823
68474
|
|
|
67824
68475
|
// src/bridge/questions.ts
|
|
67825
|
-
import { execFile as
|
|
67826
|
-
import { createHash as
|
|
67827
|
-
import { mkdir as
|
|
67828
|
-
import
|
|
67829
|
-
import { promisify as
|
|
68476
|
+
import { execFile as execFile27 } from "node:child_process";
|
|
68477
|
+
import { createHash as createHash35 } from "node:crypto";
|
|
68478
|
+
import { mkdir as mkdir31, open as open25, stat as stat28, readFile as readFile53, writeFile as writeFile11 } from "node:fs/promises";
|
|
68479
|
+
import path125 from "node:path";
|
|
68480
|
+
import { promisify as promisify25 } from "node:util";
|
|
67830
68481
|
function asyncQuestion(raw, id2) {
|
|
67831
68482
|
const p = object2(raw.payload);
|
|
67832
68483
|
const asked = deliveredQuestion(raw);
|
|
@@ -67976,7 +68627,7 @@ ${field.title}` : field.title);
|
|
|
67976
68627
|
function asPrompt(questions) {
|
|
67977
68628
|
return questions.map((q2) => ({ question: q2.title, options: (q2.options ?? []).map((label2) => ({ label: label2 })), ...!q2.options?.length ? { kind: "text" } : {} }));
|
|
67978
68629
|
}
|
|
67979
|
-
var
|
|
68630
|
+
var exec22, text4, question, questionSet, answersQuestions, attachedFiles, withAttachments, requestKey, choose, CodexQuestions;
|
|
67980
68631
|
var init_questions = __esm({
|
|
67981
68632
|
"src/bridge/questions.ts"() {
|
|
67982
68633
|
"use strict";
|
|
@@ -67988,7 +68639,7 @@ var init_questions = __esm({
|
|
|
67988
68639
|
init_transcript_index();
|
|
67989
68640
|
init_codex_question_reply();
|
|
67990
68641
|
init_uploads();
|
|
67991
|
-
|
|
68642
|
+
exec22 = promisify25(execFile27);
|
|
67992
68643
|
text4 = external_exports.string().trim().min(1).max(4e3).refine((t) => !/[\x00-\x08\x0b-\x1f\x7f]/.test(t));
|
|
67993
68644
|
question = external_exports.object({ title: text4, options: external_exports.array(text4).max(12).nullable().optional() });
|
|
67994
68645
|
questionSet = external_exports.array(question).min(1).max(8);
|
|
@@ -68034,7 +68685,7 @@ ${attachedFiles(paths)}` : answer2;
|
|
|
68034
68685
|
return this.configured ?? codexExecutable();
|
|
68035
68686
|
}
|
|
68036
68687
|
supported() {
|
|
68037
|
-
if (!this.probe || Date.now() - this.probe.at > 3e5) this.probe = { at: Date.now(), result:
|
|
68688
|
+
if (!this.probe || Date.now() - this.probe.at > 3e5) this.probe = { at: Date.now(), result: exec22(this.executable, ["queue", "--help"], { timeout: 5e3, maxBuffer: 65536 }).then(({ stdout }) => stdout.includes("--thread") && stdout.includes("--message")).catch(() => false).then((available) => {
|
|
68038
68689
|
this.inboxAvailable = available;
|
|
68039
68690
|
return available;
|
|
68040
68691
|
}) };
|
|
@@ -68055,7 +68706,7 @@ ${attachedFiles(paths)}` : answer2;
|
|
|
68055
68706
|
const cached3 = this.snapshots.get(target2.session);
|
|
68056
68707
|
let pending3 = cached3?.pending;
|
|
68057
68708
|
if (!cached3 || Date.now() - cached3.at > 1e3) {
|
|
68058
|
-
const metadata = await
|
|
68709
|
+
const metadata = await stat28(file4), stamp2 = `${metadata.ino}:${metadata.size}:${metadata.mtimeMs}`;
|
|
68059
68710
|
pending3 = cached3?.stamp === stamp2 ? cached3.pending : await pendingAsyncQuestions(file4).catch((error62) => {
|
|
68060
68711
|
if (this.failedSnapshots.size >= 64) this.failedSnapshots.delete(this.failedSnapshots.keys().next().value);
|
|
68061
68712
|
this.failedSnapshots.set(target2.session, Date.now());
|
|
@@ -68066,8 +68717,8 @@ ${attachedFiles(paths)}` : answer2;
|
|
|
68066
68717
|
this.snapshots.set(target2.session, { at: Date.now(), stamp: stamp2, pending: pending3 });
|
|
68067
68718
|
}
|
|
68068
68719
|
return Promise.all((pending3 ?? []).map(async (p) => {
|
|
68069
|
-
const key4 =
|
|
68070
|
-
const submitted = await
|
|
68720
|
+
const key4 = createHash35("sha256").update(JSON.stringify([target2.source, target2.session, p.id])).digest("hex");
|
|
68721
|
+
const submitted = await readFile53(path125.join(bridgeRoot(), "question-replies", key4), "utf8").then((value2) => value2 === "submitted").catch(() => false);
|
|
68071
68722
|
return { toolUseId: p.id, isAsync: true, submitted, questions: asPrompt(p.questions) };
|
|
68072
68723
|
})).then((prompts) => prompts.filter((p) => !p.submitted));
|
|
68073
68724
|
}
|
|
@@ -68100,10 +68751,10 @@ ${attachedFiles(paths)}` : answer2;
|
|
|
68100
68751
|
] : [];
|
|
68101
68752
|
const pane = await validateTarget(target2);
|
|
68102
68753
|
if (await paneIdentity(target2.server, pane, true) !== target2.session) throw new BridgeError(409, "This pane's conversation changed. Reopen the chat.");
|
|
68103
|
-
const directory =
|
|
68104
|
-
await
|
|
68105
|
-
const key4 =
|
|
68106
|
-
const receiptPath =
|
|
68754
|
+
const directory = path125.join(bridgeRoot(), "question-replies");
|
|
68755
|
+
await mkdir31(directory, { recursive: true, mode: 448 });
|
|
68756
|
+
const key4 = createHash35("sha256").update(JSON.stringify([target2.source, target2.session, id2])).digest("hex");
|
|
68757
|
+
const receiptPath = path125.join(directory, key4);
|
|
68107
68758
|
const receipt = await open25(receiptPath, "wx", 384).catch((error62) => {
|
|
68108
68759
|
if (error62.code === "EEXIST") throw new BridgeError(409, "An answer was already submitted. Check the conversation before answering again.");
|
|
68109
68760
|
throw new BridgeError(503, "Phren could not record this answer. Nothing was sent.");
|
|
@@ -68111,8 +68762,8 @@ ${attachedFiles(paths)}` : answer2;
|
|
|
68111
68762
|
await receipt.close();
|
|
68112
68763
|
try {
|
|
68113
68764
|
if (entry2) await this.served.steer(entry2, reply, extra);
|
|
68114
|
-
else await
|
|
68115
|
-
await
|
|
68765
|
+
else await exec22(this.executable, ["queue", "--thread", target2.session, "--message", reply], { timeout: 8e3, maxBuffer: 65536 });
|
|
68766
|
+
await writeFile11(receiptPath, "submitted", { mode: 384 });
|
|
68116
68767
|
} catch {
|
|
68117
68768
|
throw new BridgeError(409, "Codex did not confirm the answer. Check the conversation; Phren has not retried it.");
|
|
68118
68769
|
}
|
|
@@ -68122,7 +68773,7 @@ ${attachedFiles(paths)}` : answer2;
|
|
|
68122
68773
|
});
|
|
68123
68774
|
|
|
68124
68775
|
// src/bridge/settings-switch.ts
|
|
68125
|
-
import { open as open26, stat as
|
|
68776
|
+
import { open as open26, stat as stat29 } from "node:fs/promises";
|
|
68126
68777
|
function codexModeFlags(mode) {
|
|
68127
68778
|
const { approvalPolicy, approvalsReviewer, sandboxPolicy } = CODEX_MODES[mode];
|
|
68128
68779
|
const sandbox = { readOnly: "read-only", workspaceWrite: "workspace-write", dangerFullAccess: "danger-full-access" }[String(sandboxPolicy?.type)];
|
|
@@ -68219,7 +68870,7 @@ var init_settings_switch = __esm({
|
|
|
68219
68870
|
};
|
|
68220
68871
|
}
|
|
68221
68872
|
};
|
|
68222
|
-
fileSize = async (file4) => file4 ? (await
|
|
68873
|
+
fileSize = async (file4) => file4 ? (await stat29(file4).catch(() => void 0))?.size ?? 0 : 0;
|
|
68223
68874
|
SettingsSwitcher = class {
|
|
68224
68875
|
constructor(hooks, wait = STEP_WAIT_MS2) {
|
|
68225
68876
|
this.hooks = hooks;
|
|
@@ -68371,7 +69022,7 @@ var init_settings_switch = __esm({
|
|
|
68371
69022
|
|
|
68372
69023
|
// src/bridge/job-registry.ts
|
|
68373
69024
|
import { readFileSync as readFileSync51 } from "node:fs";
|
|
68374
|
-
import
|
|
69025
|
+
import path126 from "node:path";
|
|
68375
69026
|
function jobKey(job) {
|
|
68376
69027
|
if (job.pane) return `pane:${paneKey3(job.pane)}`;
|
|
68377
69028
|
if (job.session) return `session:${job.session}`;
|
|
@@ -68399,7 +69050,7 @@ function resolveJobGroups(jobs, rows2, owners) {
|
|
|
68399
69050
|
});
|
|
68400
69051
|
}
|
|
68401
69052
|
function commandMatches2(job, row) {
|
|
68402
|
-
return
|
|
69053
|
+
return path126.basename(row.command) === path126.basename(job.command) || row.args.includes(job.command);
|
|
68403
69054
|
}
|
|
68404
69055
|
function planCleanup(jobs, rows2, live, options = {}) {
|
|
68405
69056
|
const now = options.now ?? Date.now(), leaseMs = options.leaseMs ?? CLEANUP_LEASE_MS, retainMs = options.retainMs ?? CLEANUP_RETAIN_MS;
|
|
@@ -68414,7 +69065,7 @@ function planCleanup(jobs, rows2, live, options = {}) {
|
|
|
68414
69065
|
const ownGroup = rows2.find((row) => row.pid === self)?.pgid;
|
|
68415
69066
|
const kill = [], keep = [], forget = [];
|
|
68416
69067
|
for (const job of jobs) {
|
|
68417
|
-
const kept = (
|
|
69068
|
+
const kept = (reason3) => keep.push({ job, reason: reason3 });
|
|
68418
69069
|
if (!panesKnown) {
|
|
68419
69070
|
kept("unknown");
|
|
68420
69071
|
continue;
|
|
@@ -68501,7 +69152,7 @@ var init_job_registry = __esm({
|
|
|
68501
69152
|
CLEANUP_LEASE_MS = 5 * 6e4;
|
|
68502
69153
|
LEADER_START_TOLERANCE_MS = 3e3;
|
|
68503
69154
|
CLEANUP_RETAIN_MS = 24 * 60 * 6e4;
|
|
68504
|
-
defaultFile = () =>
|
|
69155
|
+
defaultFile = () => path126.join(bridgeRoot(), "jobs.json");
|
|
68505
69156
|
JobRegistry = class {
|
|
68506
69157
|
constructor(file4 = defaultFile(), now = Date.now) {
|
|
68507
69158
|
this.file = file4;
|
|
@@ -68560,7 +69211,7 @@ var init_job_registry = __esm({
|
|
|
68560
69211
|
if (remaining.length !== jobs.length) await this.replace(remaining);
|
|
68561
69212
|
return {
|
|
68562
69213
|
killed,
|
|
68563
|
-
kept: plan.keep.map(({ job, reason:
|
|
69214
|
+
kept: plan.keep.map(({ job, reason: reason3 }) => ({ ...job.pgid !== void 0 ? { pgid: job.pgid } : {}, reason: reason3 })),
|
|
68564
69215
|
forgotten: plan.forget.flatMap((job) => job.pgid !== void 0 ? [job.pgid] : [])
|
|
68565
69216
|
};
|
|
68566
69217
|
}
|
|
@@ -68569,11 +69220,11 @@ var init_job_registry = __esm({
|
|
|
68569
69220
|
});
|
|
68570
69221
|
|
|
68571
69222
|
// src/bridge/resources.ts
|
|
68572
|
-
import { execFile as
|
|
68573
|
-
import { readdir as readdir19, readFile as
|
|
69223
|
+
import { execFile as execFile28 } from "node:child_process";
|
|
69224
|
+
import { readdir as readdir19, readFile as readFile54, statfs } from "node:fs/promises";
|
|
68574
69225
|
import { cpus, loadavg, totalmem, uptime } from "node:os";
|
|
68575
|
-
import
|
|
68576
|
-
import { promisify as
|
|
69226
|
+
import path127 from "node:path";
|
|
69227
|
+
import { promisify as promisify26 } from "node:util";
|
|
68577
69228
|
function parseMacHardware(json2) {
|
|
68578
69229
|
const item = JSON.parse(json2).SPHardwareDataType?.[0] ?? {};
|
|
68579
69230
|
const text5 = (value2) => typeof value2 === "string" && value2.trim() ? value2.trim().slice(0, 80) : void 0;
|
|
@@ -68600,17 +69251,17 @@ function computerHardware(platform = process.platform) {
|
|
|
68600
69251
|
hardwareRead ??= (async () => {
|
|
68601
69252
|
const base = { memoryBytes: totalmem(), cores: cpus().length || 1 };
|
|
68602
69253
|
if (platform === "darwin") {
|
|
68603
|
-
const found = await
|
|
69254
|
+
const found = await exec23("/usr/sbin/system_profiler", ["SPHardwareDataType", "-json"], { timeout: 2e4, maxBuffer: 1024 * 1024 }).then((result) => parseMacHardware(result.stdout)).catch(() => void 0);
|
|
68604
69255
|
if (!found) hardwareRead = void 0;
|
|
68605
69256
|
return { ...found, ...base };
|
|
68606
69257
|
}
|
|
68607
69258
|
if (platform === "linux") {
|
|
68608
|
-
const dmi = (name) =>
|
|
69259
|
+
const dmi = (name) => readFile54(`/sys/devices/virtual/dmi/id/${name}`, "utf8").catch(() => void 0);
|
|
68609
69260
|
const [vendor, product, version2, cpuinfo] = await Promise.all([
|
|
68610
69261
|
dmi("sys_vendor"),
|
|
68611
69262
|
dmi("product_name"),
|
|
68612
69263
|
dmi("product_version"),
|
|
68613
|
-
|
|
69264
|
+
readFile54("/proc/cpuinfo", "utf8").catch(() => "")
|
|
68614
69265
|
]);
|
|
68615
69266
|
const model = linuxModel(vendor, product, version2), chip = linuxChip(cpuinfo);
|
|
68616
69267
|
return { ...model ? { model } : {}, ...chip ? { chip } : {}, ...base };
|
|
@@ -68647,7 +69298,7 @@ function parsePs(stats, args) {
|
|
|
68647
69298
|
return rows2;
|
|
68648
69299
|
}
|
|
68649
69300
|
function heavyKind(row) {
|
|
68650
|
-
const base =
|
|
69301
|
+
const base = path127.basename(row.command);
|
|
68651
69302
|
const args = row.args;
|
|
68652
69303
|
if (base === "launchd_sim") {
|
|
68653
69304
|
return { kind: "simulator", name: /XCTestDevices|Clone \d+ of /.test(args) ? "Simulator test clone" : "Simulator" };
|
|
@@ -68676,7 +69327,7 @@ function heavyProcesses(rows2, owners = /* @__PURE__ */ new Map(), jobs = [], li
|
|
|
68676
69327
|
}
|
|
68677
69328
|
for (const row of rows2) {
|
|
68678
69329
|
const parent = byPid.get(row.ppid);
|
|
68679
|
-
if (kinds.get(row.pid)?.kind === "codex" && parent &&
|
|
69330
|
+
if (kinds.get(row.pid)?.kind === "codex" && parent && path127.basename(parent.command) === "node" && kinds.get(parent.pid)?.kind === "codex") {
|
|
68680
69331
|
kinds.set(parent.pid, kinds.get(row.pid));
|
|
68681
69332
|
kinds.delete(row.pid);
|
|
68682
69333
|
}
|
|
@@ -68710,7 +69361,7 @@ function heavyProcesses(rows2, owners = /* @__PURE__ */ new Map(), jobs = [], li
|
|
|
68710
69361
|
const root = claim2(row);
|
|
68711
69362
|
const tracked = jobsByPgid.has(row.pgid) || root !== void 0 && trackedRoots.has(root);
|
|
68712
69363
|
if (root === void 0) {
|
|
68713
|
-
const name =
|
|
69364
|
+
const name = path127.basename(row.command).slice(0, 60);
|
|
68714
69365
|
const key4 = tracked ? `job:${row.pgid}\0${name}` : name;
|
|
68715
69366
|
const group = busy2.get(key4);
|
|
68716
69367
|
if (!group) busy2.set(key4, { kind: "busy", name, pid: row.pid, processes: 1, cpuPercent: row.cpu, memoryBytes: row.rssKB * 1024, top: row.cpu, row, ...tracked ? { tracked: true } : {} });
|
|
@@ -68808,7 +69459,7 @@ function assess(value2) {
|
|
|
68808
69459
|
};
|
|
68809
69460
|
}
|
|
68810
69461
|
async function run3(file4, args) {
|
|
68811
|
-
return (await
|
|
69462
|
+
return (await exec23(file4, args, { timeout: 4e3, maxBuffer: 8 * 1024 * 1024, env: { ...process.env, LC_ALL: "C" } })).stdout;
|
|
68812
69463
|
}
|
|
68813
69464
|
async function darwinMemory() {
|
|
68814
69465
|
const [level, pressure, swap] = await Promise.all([
|
|
@@ -68829,7 +69480,7 @@ async function linuxBattery() {
|
|
|
68829
69480
|
const names = await readdir19(root).catch(() => []);
|
|
68830
69481
|
const battery = names.find((name) => /^BAT/.test(name));
|
|
68831
69482
|
if (!battery) return void 0;
|
|
68832
|
-
const read = (name, field) =>
|
|
69483
|
+
const read = (name, field) => readFile54(path127.join(root, name, field), "utf8").then((text5) => text5.trim()).catch(() => "");
|
|
68833
69484
|
const [capacity2, status] = await Promise.all([read(battery, "capacity"), read(battery, "status")]);
|
|
68834
69485
|
const online = await Promise.all(names.filter((name) => !/^BAT/.test(name)).map((name) => read(name, "online")));
|
|
68835
69486
|
const percent = Number(capacity2);
|
|
@@ -68899,7 +69550,7 @@ async function collectResources(deps2) {
|
|
|
68899
69550
|
const platform = deps2.platform;
|
|
68900
69551
|
const registry2 = deps2.jobs ?? new JobRegistry();
|
|
68901
69552
|
const [memory, disk, battery, rows2, registered, hardware] = await Promise.all([
|
|
68902
|
-
platform === "darwin" ? darwinMemory() : platform === "linux" ?
|
|
69553
|
+
platform === "darwin" ? darwinMemory() : platform === "linux" ? readFile54("/proc/meminfo", "utf8").then(parseMeminfo).catch(() => ({ totalBytes: totalmem() })) : Promise.resolve({ totalBytes: totalmem() }),
|
|
68903
69554
|
statfs(deps2.home()).then((info) => ({ path: "~", totalBytes: info.blocks * info.bsize, freeBytes: info.bavail * info.bsize })).catch(() => void 0),
|
|
68904
69555
|
platform === "darwin" ? run3("/usr/bin/pmset", ["-g", "batt"]).then(parsePmset).catch(() => void 0) : platform === "linux" ? linuxBattery() : Promise.resolve(void 0),
|
|
68905
69556
|
deps2.processes().catch(() => []),
|
|
@@ -68923,7 +69574,7 @@ async function collectResources(deps2) {
|
|
|
68923
69574
|
};
|
|
68924
69575
|
return { ...value2, ...assess(value2) };
|
|
68925
69576
|
}
|
|
68926
|
-
var
|
|
69577
|
+
var exec23, RESOURCES_MAX_AGE_MS, LOW_DISK_BYTES, GB2, hardwareRead, ResourceMonitor;
|
|
68927
69578
|
var init_resources = __esm({
|
|
68928
69579
|
"src/bridge/resources.ts"() {
|
|
68929
69580
|
"use strict";
|
|
@@ -68932,7 +69583,7 @@ var init_resources = __esm({
|
|
|
68932
69583
|
init_job_registry();
|
|
68933
69584
|
init_limits();
|
|
68934
69585
|
init_protocol();
|
|
68935
|
-
|
|
69586
|
+
exec23 = promisify26(execFile28);
|
|
68936
69587
|
RESOURCES_MAX_AGE_MS = intervalFromEnv("PHREN_RESOURCES_MAX_AGE_MS", 1e4, 1e3, 6e4);
|
|
68937
69588
|
LOW_DISK_BYTES = 10 * 1024 ** 3;
|
|
68938
69589
|
GB2 = 1024 ** 3;
|
|
@@ -68981,9 +69632,9 @@ var init_resources = __esm({
|
|
|
68981
69632
|
|
|
68982
69633
|
// src/bridge/canary.ts
|
|
68983
69634
|
import { lstat as lstat34, mkdtemp as mkdtemp6, realpath as realpath20, rm as rm15 } from "node:fs/promises";
|
|
68984
|
-
import { hostname as hostname11, tmpdir as
|
|
68985
|
-
import
|
|
68986
|
-
function
|
|
69635
|
+
import { hostname as hostname11, tmpdir as tmpdir7 } from "node:os";
|
|
69636
|
+
import path128 from "node:path";
|
|
69637
|
+
function reason2(error62) {
|
|
68987
69638
|
const text5 = error62 instanceof Error ? error62.message : "Unknown failure.";
|
|
68988
69639
|
return text5.replace(/[\x00-\x1f\x7f]+/g, " ").trim().slice(0, 300) || "Unknown failure.";
|
|
68989
69640
|
}
|
|
@@ -68992,7 +69643,7 @@ async function step(steps, name, run4) {
|
|
|
68992
69643
|
try {
|
|
68993
69644
|
steps.push({ name, durationMs: 0, ...await run4() });
|
|
68994
69645
|
} catch (error62) {
|
|
68995
|
-
steps.push({ name, durationMs: 0, status: "failed", reason:
|
|
69646
|
+
steps.push({ name, durationMs: 0, status: "failed", reason: reason2(error62) });
|
|
68996
69647
|
}
|
|
68997
69648
|
steps.at(-1).durationMs = Date.now() - started;
|
|
68998
69649
|
}
|
|
@@ -69002,7 +69653,7 @@ async function closeCanaryWorkspaces(server, before, created) {
|
|
|
69002
69653
|
try {
|
|
69003
69654
|
current2 = await snapshot(server);
|
|
69004
69655
|
} catch (error62) {
|
|
69005
|
-
return `could not list workspaces to clean up (${
|
|
69656
|
+
return `could not list workspaces to clean up (${reason2(error62)})`;
|
|
69006
69657
|
}
|
|
69007
69658
|
const mine = objects(current2.workspaces).filter((workspace) => !before.has(String(workspace.workspace_id)) && (workspace.workspace_id === created || workspace.label === CANARY_LABEL));
|
|
69008
69659
|
for (const workspace of mine) {
|
|
@@ -69010,21 +69661,21 @@ async function closeCanaryWorkspaces(server, before, created) {
|
|
|
69010
69661
|
try {
|
|
69011
69662
|
await terminalProvider().groupAction(server, "close", { workspace: String(workspace.workspace_id) });
|
|
69012
69663
|
} catch (error62) {
|
|
69013
|
-
failures.push(`${String(workspace.workspace_id)}: ${
|
|
69664
|
+
failures.push(`${String(workspace.workspace_id)}: ${reason2(error62)}`);
|
|
69014
69665
|
}
|
|
69015
69666
|
}
|
|
69016
69667
|
return failures.length ? `cleanup failed for ${failures.join("; ")}` : void 0;
|
|
69017
69668
|
}
|
|
69018
69669
|
async function conductorStep(options, server) {
|
|
69019
69670
|
const before = new Set(objects((await snapshot(server)).workspaces).map((workspace) => String(workspace.workspace_id)));
|
|
69020
|
-
const folder = await realpath20(await mkdtemp6(
|
|
69671
|
+
const folder = await realpath20(await mkdtemp6(path128.join(tmpdir7(), "phren-canary-")));
|
|
69021
69672
|
let created, failure2, detail;
|
|
69022
69673
|
try {
|
|
69023
69674
|
const launched = await options.launch(server, { role: "conductor", kind: "claude", label: CANARY_LABEL, cwd: folder, timeoutMs: 45e3 });
|
|
69024
69675
|
created = typeof launched.workspaceId === "string" ? launched.workspaceId : void 0;
|
|
69025
69676
|
detail = `claude started (${typeof launched.agentStatus === "string" ? launched.agentStatus : "status unknown"})`;
|
|
69026
69677
|
} catch (error62) {
|
|
69027
|
-
failure2 =
|
|
69678
|
+
failure2 = reason2(error62);
|
|
69028
69679
|
} finally {
|
|
69029
69680
|
const cleanup = await closeCanaryWorkspaces(server, before, created);
|
|
69030
69681
|
await rm15(folder, { recursive: true, force: true }).catch(() => {
|
|
@@ -69038,12 +69689,12 @@ async function scheduleStep(options) {
|
|
|
69038
69689
|
let count2 = 0;
|
|
69039
69690
|
const broken = [];
|
|
69040
69691
|
for (const directory of getProjectDirs(options.store)) {
|
|
69041
|
-
const present2 = await lstat34(
|
|
69692
|
+
const present2 = await lstat34(path128.join(directory, "schedules.yaml")).catch(() => void 0);
|
|
69042
69693
|
if (!present2) continue;
|
|
69043
69694
|
try {
|
|
69044
69695
|
count2 += (await readScheduleDocument(directory)).schedules.length;
|
|
69045
69696
|
} catch (error62) {
|
|
69046
|
-
broken.push(`${
|
|
69697
|
+
broken.push(`${path128.basename(directory)}: ${reason2(error62)}`);
|
|
69047
69698
|
}
|
|
69048
69699
|
}
|
|
69049
69700
|
const tick = options.scheduler.lastTickAt;
|
|
@@ -69112,7 +69763,7 @@ function runCanary(options) {
|
|
|
69112
69763
|
}
|
|
69113
69764
|
async function dailyCanaryEnabled(root = bridgeRoot()) {
|
|
69114
69765
|
if (process.env.PHREN_CANARY_DAILY === "1") return true;
|
|
69115
|
-
return !!(await lstat34(
|
|
69766
|
+
return !!(await lstat34(path128.join(root, "canary-daily")).catch(() => void 0))?.isFile();
|
|
69116
69767
|
}
|
|
69117
69768
|
async function dailyCanaryDue(root = bridgeRoot(), now = Date.now()) {
|
|
69118
69769
|
if (running || !await dailyCanaryEnabled(root)) return false;
|
|
@@ -69139,11 +69790,11 @@ var init_canary = __esm({
|
|
|
69139
69790
|
|
|
69140
69791
|
// src/bridge/account-add.ts
|
|
69141
69792
|
import { existsSync as existsSync39 } from "node:fs";
|
|
69142
|
-
import
|
|
69793
|
+
import path129 from "node:path";
|
|
69143
69794
|
async function addClaudeAccount2(input2, server) {
|
|
69144
69795
|
const { slug } = accountAddSchema.parse(input2);
|
|
69145
69796
|
const key4 = `${bridgeRoot()}\0${slug}`;
|
|
69146
|
-
if (adding.has(key4) || claudeHomes().some((home) => home.id === slug) || existsSync39(
|
|
69797
|
+
if (adding.has(key4) || claudeHomes().some((home) => home.id === slug) || existsSync39(path129.join(homeDir(), `.claude-${slug}`))) throw new BridgeError(409, "That Claude account already exists or is being added.");
|
|
69147
69798
|
adding.add(key4);
|
|
69148
69799
|
try {
|
|
69149
69800
|
const terminal2 = terminalProvider();
|
|
@@ -69179,13 +69830,13 @@ var init_account_add = __esm({
|
|
|
69179
69830
|
});
|
|
69180
69831
|
|
|
69181
69832
|
// src/bridge/launch-worktree.ts
|
|
69182
|
-
import { execFile as
|
|
69183
|
-
import { mkdir as
|
|
69184
|
-
import
|
|
69185
|
-
import { promisify as
|
|
69833
|
+
import { execFile as execFile29 } from "node:child_process";
|
|
69834
|
+
import { mkdir as mkdir32, realpath as realpath21, rm as rm16, stat as stat30 } from "node:fs/promises";
|
|
69835
|
+
import path130 from "node:path";
|
|
69836
|
+
import { promisify as promisify27 } from "node:util";
|
|
69186
69837
|
async function git7(cwd, ...args) {
|
|
69187
69838
|
countGit("launch-worktree");
|
|
69188
|
-
return (await
|
|
69839
|
+
return (await exec24("git", ["-C", cwd, "--no-pager", ...args], {
|
|
69189
69840
|
timeout: 12e4,
|
|
69190
69841
|
maxBuffer: 1048576,
|
|
69191
69842
|
env: nonInteractiveGitEnv({ ...process.env, GIT_CONFIG_NOSYSTEM: "1" })
|
|
@@ -69206,11 +69857,11 @@ async function createLaunchWorktree(cwd, request10) {
|
|
|
69206
69857
|
if (await git7(root, "show-ref", "--verify", "--quiet", `refs/heads/${branch}`).then(() => true, () => false)) {
|
|
69207
69858
|
throw new BridgeError(409, `A branch named "${branch}" already exists in this repository. Choose another branch name.`);
|
|
69208
69859
|
}
|
|
69209
|
-
const worktree =
|
|
69210
|
-
if (await
|
|
69860
|
+
const worktree = path130.join(root, ".claude", "worktrees", worktreeFolderName(branch));
|
|
69861
|
+
if (await stat30(worktree).then(() => true, () => false)) {
|
|
69211
69862
|
throw new BridgeError(409, `The folder .claude/worktrees/${worktreeFolderName(branch)} already exists. Choose another branch name.`);
|
|
69212
69863
|
}
|
|
69213
|
-
await
|
|
69864
|
+
await mkdir32(path130.dirname(worktree), { recursive: true });
|
|
69214
69865
|
try {
|
|
69215
69866
|
await git7(root, "worktree", "add", "-b", branch, worktree, head);
|
|
69216
69867
|
} catch (error62) {
|
|
@@ -69218,9 +69869,9 @@ async function createLaunchWorktree(cwd, request10) {
|
|
|
69218
69869
|
throw new BridgeError(409, `Git could not create the worktree${detail ? `: ${detail.replace(/^fatal:\s*/, "")}` : "."}`);
|
|
69219
69870
|
}
|
|
69220
69871
|
const abs = await realpath21(worktree);
|
|
69221
|
-
const inside =
|
|
69222
|
-
const start = inside && !inside.startsWith("..") ?
|
|
69223
|
-
const startDir = await
|
|
69872
|
+
const inside = path130.relative(root, await realpath21(cwd));
|
|
69873
|
+
const start = inside && !inside.startsWith("..") ? path130.join(abs, inside) : abs;
|
|
69874
|
+
const startDir = await stat30(start).then((value2) => value2.isDirectory(), () => false) ? start : abs;
|
|
69224
69875
|
return {
|
|
69225
69876
|
cwd: startDir,
|
|
69226
69877
|
path: abs,
|
|
@@ -69232,7 +69883,7 @@ async function createLaunchWorktree(cwd, request10) {
|
|
|
69232
69883
|
}
|
|
69233
69884
|
};
|
|
69234
69885
|
}
|
|
69235
|
-
var
|
|
69886
|
+
var exec24, worktreeBranch, launchWorktreeSchema;
|
|
69236
69887
|
var init_launch_worktree = __esm({
|
|
69237
69888
|
"src/bridge/launch-worktree.ts"() {
|
|
69238
69889
|
"use strict";
|
|
@@ -69241,15 +69892,15 @@ var init_launch_worktree = __esm({
|
|
|
69241
69892
|
init_metrics();
|
|
69242
69893
|
init_projects();
|
|
69243
69894
|
init_protocol();
|
|
69244
|
-
|
|
69895
|
+
exec24 = promisify27(execFile29);
|
|
69245
69896
|
worktreeBranch = external_exports.string().trim().min(1).max(100).regex(/^[A-Za-z0-9][A-Za-z0-9._/-]*$/, "A branch name uses letters, digits, dots, dashes, underscores and slashes.");
|
|
69246
69897
|
launchWorktreeSchema = external_exports.object({ branch: worktreeBranch }).strict();
|
|
69247
69898
|
}
|
|
69248
69899
|
});
|
|
69249
69900
|
|
|
69250
69901
|
// src/bridge/server-launch.ts
|
|
69251
|
-
import { mkdir as
|
|
69252
|
-
import
|
|
69902
|
+
import { mkdir as mkdir33, mkdtemp as mkdtemp7, readFile as readFile55, realpath as realpath22, rmdir as rmdir2 } from "node:fs/promises";
|
|
69903
|
+
import path131 from "node:path";
|
|
69253
69904
|
function effortArgs(kind, effort) {
|
|
69254
69905
|
if (kind === "claude") return ["--effort", effort];
|
|
69255
69906
|
if (kind === "codex") return ["-c", `model_reasoning_effort=${effort}`];
|
|
@@ -69268,7 +69919,7 @@ async function phrenLaunchArgs(kind, data, store = phrenStoreRoot()) {
|
|
|
69268
69919
|
return [...mode === "chat" ? ["--mode", "chat"] : [], ...resume ? ["--session", resume] : []];
|
|
69269
69920
|
}
|
|
69270
69921
|
async function sessionUsedTools(session, store = phrenStoreRoot()) {
|
|
69271
|
-
const raw = await
|
|
69922
|
+
const raw = await readFile55(path131.join(store, ".sessions", `session-${session}.events.jsonl`), "utf8").catch(() => "");
|
|
69272
69923
|
const withTools = (message) => {
|
|
69273
69924
|
const content = message?.content;
|
|
69274
69925
|
return Array.isArray(content) && content.some((block) => ["tool_use", "tool_result"].includes(String(block?.type)));
|
|
@@ -69300,8 +69951,8 @@ async function prepareConductor(kind, effort, model) {
|
|
|
69300
69951
|
if (kind === "claude") return [...model ? ["--model", model] : [], "--append-system-prompt-file", briefFile, "--effort", effort];
|
|
69301
69952
|
if (kind === "codex") return [...model ? ["--model", model] : [], "-c", `model_reasoning_effort=${effort}`, "-c", `developer_instructions=${JSON.stringify(brief)}`];
|
|
69302
69953
|
if (kind === "opencode") {
|
|
69303
|
-
const directory =
|
|
69304
|
-
const file4 =
|
|
69954
|
+
const directory = path131.join(process.env.XDG_CONFIG_HOME || path131.join(homeDir(), ".config"), "opencode", "agents");
|
|
69955
|
+
const file4 = path131.join(directory, "conductor.md");
|
|
69305
69956
|
const definition = `---
|
|
69306
69957
|
description: Coordinate the owner's work across agent sessions.
|
|
69307
69958
|
mode: primary
|
|
@@ -69309,8 +69960,8 @@ mode: primary
|
|
|
69309
69960
|
|
|
69310
69961
|
${brief}
|
|
69311
69962
|
`;
|
|
69312
|
-
await
|
|
69313
|
-
if (await
|
|
69963
|
+
await mkdir33(directory, { recursive: true, mode: 448 });
|
|
69964
|
+
if (await readFile55(file4, "utf8").catch(() => void 0) !== definition) await atomic(file4, definition, 420);
|
|
69314
69965
|
return [...model ? ["--model", model] : [], "--agent", "conductor", "--variant", effort];
|
|
69315
69966
|
}
|
|
69316
69967
|
if (kind === "phren") return [...PHREN_AGENT_ARGS, ...model ? phrenModelArgs(model) : [], "--append-system-prompt-file", briefFile, ...effortArgs(kind, effort)];
|
|
@@ -69493,7 +70144,7 @@ async function startSession(server, data, options) {
|
|
|
69493
70144
|
throw new BridgeError(400, "An agent folder is for a projectless agent without cwd or worktree.");
|
|
69494
70145
|
}
|
|
69495
70146
|
if (options.into && (role !== "agent" || agentFolder || data.worktree != null)) throw new BridgeError(400, "Only a worker starts in an existing pane, in that pane's folder.");
|
|
69496
|
-
const projectDirectory = agentFolder ? void 0 : external_exports.string().min(1).max(4096).refine((t) =>
|
|
70147
|
+
const projectDirectory = agentFolder ? void 0 : external_exports.string().min(1).max(4096).refine((t) => path131.isAbsolute(t) && !/[\x00-\x1f\x7f]/.test(t)).parse(data.cwd);
|
|
69497
70148
|
const worktreeRequest = data.worktree === void 0 || data.worktree === null ? void 0 : launchWorktreeSchema.parse(data.worktree);
|
|
69498
70149
|
if (worktreeRequest && role === "conductor") throw new BridgeError(400, "A conductor works across projects, so it cannot start in a worktree.");
|
|
69499
70150
|
const label2 = plainText(200).parse(data.label);
|
|
@@ -69553,13 +70204,13 @@ async function startSession(server, data, options) {
|
|
|
69553
70204
|
let scratch;
|
|
69554
70205
|
if (agentFolder) {
|
|
69555
70206
|
const store = await realpath22(defaultPhrenPath());
|
|
69556
|
-
const runtime =
|
|
69557
|
-
await
|
|
70207
|
+
const runtime = path131.join(store, ".runtime");
|
|
70208
|
+
await mkdir33(runtime, { recursive: true, mode: 448 });
|
|
69558
70209
|
if (await realpath22(runtime) !== runtime) throw new BridgeError(403, "The runtime folder must be inside the Phren directory.");
|
|
69559
|
-
const agents =
|
|
69560
|
-
await
|
|
70210
|
+
const agents = path131.join(runtime, "agents");
|
|
70211
|
+
await mkdir33(agents, { recursive: true, mode: 448 });
|
|
69561
70212
|
if (await realpath22(agents) !== agents) throw new BridgeError(403, "The agents folder must be inside the Phren directory.");
|
|
69562
|
-
scratch = await mkdtemp7(
|
|
70213
|
+
scratch = await mkdtemp7(path131.join(agents, `${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}-${herdrAgentName(label2)}-`));
|
|
69563
70214
|
}
|
|
69564
70215
|
const cwd = scratch ?? worktree?.cwd ?? projectDirectory;
|
|
69565
70216
|
if (scratch || worktree || options.trustFolder) await pretrustFolder(
|
|
@@ -69629,9 +70280,9 @@ async function startSession(server, data, options) {
|
|
|
69629
70280
|
const blocked = agentNotReady(error62);
|
|
69630
70281
|
if (!blocked) {
|
|
69631
70282
|
const host = terminalName(server);
|
|
69632
|
-
const
|
|
69633
|
-
if (options.into) throw new BridgeError(409, `${host} couldn't start ${kind} in the "${label2}" pane (${
|
|
69634
|
-
throw new BridgeError(409, `${host} couldn't start ${kind} in the new "${label2}" pane (${
|
|
70283
|
+
const reason3 = error62 instanceof BridgeError && error62.status === 504 ? "it did not become ready in time" : error62 instanceof BridgeError && error62.message.startsWith(`${host}: `) ? error62.message.slice(host.length + 2) : `${host} reported an error`;
|
|
70284
|
+
if (options.into) throw new BridgeError(409, `${host} couldn't start ${kind} in the "${label2}" pane (${reason3}). The pane is still open at its shell prompt.`);
|
|
70285
|
+
throw new BridgeError(409, `${host} couldn't start ${kind} in the new "${label2}" pane (${reason3}). The workspace was created and is still open on the computer \u2014 open it from ${host === "Herdr" ? "Herdr workspaces" : "its tmux session"}.`);
|
|
69635
70286
|
}
|
|
69636
70287
|
}
|
|
69637
70288
|
if (appServer && !appServer.threadId) await codexServers.awaitThread(appServer);
|
|
@@ -69712,7 +70363,7 @@ async function workspaceAction(server, operation, data) {
|
|
|
69712
70363
|
if (tab && !objects(s.tabs).some((t) => t.tab_id === tab && (!workspace || t.workspace_id === workspace))) throw new BridgeError(409, "The tab changed.");
|
|
69713
70364
|
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.");
|
|
69714
70365
|
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);
|
|
69715
|
-
const cwd = data.cwd === void 0 ? void 0 : external_exports.string().max(4096).refine((t) =>
|
|
70366
|
+
const cwd = data.cwd === void 0 ? void 0 : external_exports.string().max(4096).refine((t) => path131.isAbsolute(t) && !/[\x00-\x1f\x7f]/.test(t)).parse(data.cwd);
|
|
69716
70367
|
if (operation === "create") await terminalProvider().create(server, { workspace, label: label2, cwd });
|
|
69717
70368
|
else if (!workspace && !tab && !pane) throw new BridgeError(400, "Choose a Herdr destination.");
|
|
69718
70369
|
else if (pane && operation === "focus") await terminalProvider().focusPane(server, pane);
|
|
@@ -69774,8 +70425,8 @@ var init_server_launch = __esm({
|
|
|
69774
70425
|
});
|
|
69775
70426
|
|
|
69776
70427
|
// src/bridge/task-routes.ts
|
|
69777
|
-
import * as
|
|
69778
|
-
import { realpath as realpath23, stat as
|
|
70428
|
+
import * as path132 from "node:path";
|
|
70429
|
+
import { realpath as realpath23, stat as stat31 } from "node:fs/promises";
|
|
69779
70430
|
function owner(base, id2, write) {
|
|
69780
70431
|
const matches = taskStores(base).filter((s) => s.taskStoreId === id2 && s.available !== false);
|
|
69781
70432
|
if (matches.length !== 1) throw new BridgeError(404, "Task store is unavailable or ambiguous.");
|
|
@@ -69810,7 +70461,7 @@ function getTaskRoute(base, url2) {
|
|
|
69810
70461
|
if (!taskStoreHasProject(store, project)) throw new BridgeError(404, "Project is not in that task store.");
|
|
69811
70462
|
const result = readTasks(store.path, project);
|
|
69812
70463
|
if (!result.ok) throw new BridgeError(400, result.error);
|
|
69813
|
-
if (
|
|
70464
|
+
if (path132.resolve(result.data.path) !== path132.join(path132.resolve(store.path), project, "tasks.md")) throw new BridgeError(404, "Project is not in that task store.");
|
|
69814
70465
|
const filter = external_exports.object({ responsibility: external_exports.enum(["human", "agent"]).optional(), readiness: external_exports.enum(["ready", "waiting-on-human", "waiting-on-task"]).optional() }).parse(Object.fromEntries(url2.searchParams));
|
|
69815
70466
|
const filtered = filterTaskDoc(base, result.data, filter);
|
|
69816
70467
|
const writerSafety = taskWriterSafety(store.path);
|
|
@@ -69823,7 +70474,7 @@ function updateTaskRoute(base, input2) {
|
|
|
69823
70474
|
const denied = permissionDeniedError(store.path, "update_task", data.project);
|
|
69824
70475
|
if (denied) throw new BridgeError(403, denied);
|
|
69825
70476
|
const current2 = readTasks(store.path, data.project);
|
|
69826
|
-
if (!current2.ok ||
|
|
70477
|
+
if (!current2.ok || path132.resolve(current2.data.path) !== path132.join(path132.resolve(store.path), data.project, "tasks.md")) throw new BridgeError(404, "Project is not in that task store.");
|
|
69827
70478
|
const result = updateTask(store.path, data.project, `bid:${data.stableId}`, data.updates, base);
|
|
69828
70479
|
if (!result.ok) throw new BridgeError(400, result.error);
|
|
69829
70480
|
return getTaskRoute(base, new URL(`http://phren.local/v1/tasks?storeId=${data.storeId}&project=${data.project}`));
|
|
@@ -69840,7 +70491,7 @@ function createTaskRoute(base, input2) {
|
|
|
69840
70491
|
if (denied) throw new BridgeError(403, denied);
|
|
69841
70492
|
}
|
|
69842
70493
|
const current2 = readTasks(store.path, data.project);
|
|
69843
|
-
if (!current2.ok ||
|
|
70494
|
+
if (!current2.ok || path132.resolve(current2.data.path) !== path132.join(path132.resolve(store.path), data.project, "tasks.md")) throw new BridgeError(404, "Project is not in that task store.");
|
|
69844
70495
|
const result = addTask(store.path, data.project, data.text, { stableId: data.stableId, responsibility: data.responsibility, graphRoot: base });
|
|
69845
70496
|
if (!result.ok) throw new BridgeError(409, result.error);
|
|
69846
70497
|
return getTaskRoute(base, new URL(`http://phren.local/v1/tasks?storeId=${data.storeId}&project=${data.project}`));
|
|
@@ -69861,7 +70512,7 @@ function writableTaskProject(base, storeId, project) {
|
|
|
69861
70512
|
const denied = permissionDeniedError(store.path, "update_task", project);
|
|
69862
70513
|
if (denied) throw new BridgeError(403, denied);
|
|
69863
70514
|
const current2 = readTasks(store.path, project);
|
|
69864
|
-
if (!current2.ok ||
|
|
70515
|
+
if (!current2.ok || path132.resolve(current2.data.path) !== path132.join(path132.resolve(store.path), project, "tasks.md")) throw new BridgeError(404, "Project is not in that task store.");
|
|
69865
70516
|
if (taskWriterSafety(store.path).activation !== "owner-acknowledged") throw new BridgeError(409, "Task metadata is not enabled.");
|
|
69866
70517
|
return store;
|
|
69867
70518
|
}
|
|
@@ -69878,9 +70529,9 @@ async function launchTaskRoute(base, server, input2) {
|
|
|
69878
70529
|
const store = writableTaskProject(base, data.storeId, data.project);
|
|
69879
70530
|
const configured = getProjectSourcePath(store.path, data.project);
|
|
69880
70531
|
const cwd = configured ? await realpath23(configured).catch(() => void 0) : void 0;
|
|
69881
|
-
if (!cwd || !(await
|
|
70532
|
+
if (!cwd || !(await stat31(cwd)).isDirectory()) throw new BridgeError(409, "This task project has no configured checkout on this computer.");
|
|
69882
70533
|
const currentStore = writableTaskProject(base, data.storeId, data.project);
|
|
69883
|
-
if (
|
|
70534
|
+
if (path132.resolve(currentStore.path) !== path132.resolve(store.path)) throw new BridgeError(409, "Task store changed; refresh before starting.");
|
|
69884
70535
|
const reserved = reserveTaskLaunch(store.path, data.project, data.stableId, data.expectedRevision, getMachineName(), base);
|
|
69885
70536
|
if (!reserved.ok) throw new BridgeError(409, reserved.error, { code: "task-launch-conflict" });
|
|
69886
70537
|
const task2 = reserved.data;
|
|
@@ -69998,7 +70649,7 @@ var init_owner_inbox_view = __esm({
|
|
|
69998
70649
|
});
|
|
69999
70650
|
|
|
70000
70651
|
// src/bridge/code-note.ts
|
|
70001
|
-
import * as
|
|
70652
|
+
import * as path133 from "node:path";
|
|
70002
70653
|
async function saveCodeNote(store, input2, deliver) {
|
|
70003
70654
|
const note = codeNoteSchema.parse(input2);
|
|
70004
70655
|
if (note.target && !deliver) throw new BridgeError(409, "Enable conductor to send code notes to an agent.");
|
|
@@ -70046,7 +70697,7 @@ var init_code_note = __esm({
|
|
|
70046
70697
|
// phone's spelling, accepted until 0.3.1.
|
|
70047
70698
|
name: external_exports.string().min(1).max(4600).optional(),
|
|
70048
70699
|
symbol: external_exports.string().min(1).max(4600).optional(),
|
|
70049
|
-
file: external_exports.string().min(1).max(4096).refine((file4) => !
|
|
70700
|
+
file: external_exports.string().min(1).max(4096).refine((file4) => !path133.isAbsolute(file4) && !file4.includes("\0") && !file4.split(/[\\/]/).includes("..")),
|
|
70050
70701
|
line: external_exports.number().int().positive(),
|
|
70051
70702
|
text: external_exports.string().trim().min(1).max(4500).refine((text5) => !/[\x00-\x08\x0b-\x1f\x7f]/.test(text5)),
|
|
70052
70703
|
target: external_exports.union([external_exports.object({ session: sessionId }).strict(), external_exports.object({ harness: external_exports.enum(DISPATCH_HARNESSES) }).strict()]).optional()
|
|
@@ -70061,9 +70712,9 @@ var init_code_note = __esm({
|
|
|
70061
70712
|
|
|
70062
70713
|
// src/git-worktree.ts
|
|
70063
70714
|
import * as fs48 from "fs";
|
|
70064
|
-
import * as
|
|
70715
|
+
import * as path134 from "path";
|
|
70065
70716
|
function resolveWorktreeParent(dir) {
|
|
70066
|
-
const resolved =
|
|
70717
|
+
const resolved = path134.resolve(dir);
|
|
70067
70718
|
const agentParent = parentFromAgentWorktreePath(resolved);
|
|
70068
70719
|
if (agentParent) return { repoRoot: agentParent, reason: "agent-worktree-dir" };
|
|
70069
70720
|
const linkedParent = parentFromLinkedWorktree(resolved);
|
|
@@ -70071,23 +70722,23 @@ function resolveWorktreeParent(dir) {
|
|
|
70071
70722
|
return null;
|
|
70072
70723
|
}
|
|
70073
70724
|
function parentFromAgentWorktreePath(resolved) {
|
|
70074
|
-
const segments = resolved.split(
|
|
70725
|
+
const segments = resolved.split(path134.sep);
|
|
70075
70726
|
for (let i = 1; i < segments.length; i++) {
|
|
70076
70727
|
if (!WORKTREE_CONTAINER_NAMES.has(segments[i])) continue;
|
|
70077
70728
|
let j2 = i - 1;
|
|
70078
70729
|
if (!segments[j2]?.startsWith(".")) continue;
|
|
70079
70730
|
while (j2 >= 1 && segments[j2].startsWith(".")) j2--;
|
|
70080
70731
|
if (j2 < 1) continue;
|
|
70081
|
-
return segments.slice(0, j2 + 1).join(
|
|
70732
|
+
return segments.slice(0, j2 + 1).join(path134.sep) || path134.sep;
|
|
70082
70733
|
}
|
|
70083
70734
|
return null;
|
|
70084
70735
|
}
|
|
70085
70736
|
function parentFromLinkedWorktree(resolved) {
|
|
70086
70737
|
let current2 = resolved;
|
|
70087
70738
|
while (true) {
|
|
70088
|
-
const parent = repoRootFromGitFile(
|
|
70739
|
+
const parent = repoRootFromGitFile(path134.join(current2, ".git"));
|
|
70089
70740
|
if (parent) return parent;
|
|
70090
|
-
const next =
|
|
70741
|
+
const next = path134.dirname(current2);
|
|
70091
70742
|
if (next === current2) return null;
|
|
70092
70743
|
current2 = next;
|
|
70093
70744
|
}
|
|
@@ -70102,7 +70753,7 @@ function repoRootFromGitFile(gitPath) {
|
|
|
70102
70753
|
}
|
|
70103
70754
|
const match = raw.match(/^\s*gitdir:\s*(.+?)\s*$/m);
|
|
70104
70755
|
if (!match) return null;
|
|
70105
|
-
const gitDir2 =
|
|
70756
|
+
const gitDir2 = path134.resolve(path134.dirname(gitPath), match[1].replace(/[/\\]/g, path134.sep));
|
|
70106
70757
|
const idx = gitDir2.indexOf(LINKED_WORKTREE_SEGMENT);
|
|
70107
70758
|
if (idx === -1) return null;
|
|
70108
70759
|
return gitDir2.slice(0, idx);
|
|
@@ -70112,13 +70763,13 @@ var init_git_worktree = __esm({
|
|
|
70112
70763
|
"src/git-worktree.ts"() {
|
|
70113
70764
|
"use strict";
|
|
70114
70765
|
WORKTREE_CONTAINER_NAMES = /* @__PURE__ */ new Set(["worktrees", ".worktrees"]);
|
|
70115
|
-
LINKED_WORKTREE_SEGMENT = `${
|
|
70766
|
+
LINKED_WORKTREE_SEGMENT = `${path134.sep}.git${path134.sep}worktrees${path134.sep}`;
|
|
70116
70767
|
}
|
|
70117
70768
|
});
|
|
70118
70769
|
|
|
70119
70770
|
// src/core/project-registry.ts
|
|
70120
70771
|
import * as fs49 from "fs";
|
|
70121
|
-
import * as
|
|
70772
|
+
import * as path135 from "path";
|
|
70122
70773
|
function titleCase(text5) {
|
|
70123
70774
|
return text5.split(/[\s_-]+/).filter(Boolean).map((token) => token.slice(0, 1).toUpperCase() + token.slice(1)).join(" ");
|
|
70124
70775
|
}
|
|
@@ -70190,7 +70841,7 @@ function scoreTopicsFromTerms(domain2, terms, docsText) {
|
|
|
70190
70841
|
return topics;
|
|
70191
70842
|
}
|
|
70192
70843
|
function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
|
|
70193
|
-
const resolvedRoot =
|
|
70844
|
+
const resolvedRoot = path135.resolve(repoRoot);
|
|
70194
70845
|
if (!fs49.existsSync(resolvedRoot)) return null;
|
|
70195
70846
|
const signal = {
|
|
70196
70847
|
domainScores: { software: 0, music: 0, game: 0, research: 0, writing: 0, creative: 0, other: 0 },
|
|
@@ -70201,7 +70852,7 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
|
|
|
70201
70852
|
usefulSignals: 0
|
|
70202
70853
|
};
|
|
70203
70854
|
const skipDirs = /* @__PURE__ */ new Set([".git", ".phren", "node_modules", "dist", "build", "coverage", ".next", ".turbo", "target"]);
|
|
70204
|
-
const packageJsonPath =
|
|
70855
|
+
const packageJsonPath = path135.join(resolvedRoot, "package.json");
|
|
70205
70856
|
if (fs49.existsSync(packageJsonPath)) {
|
|
70206
70857
|
signal.usefulSignals++;
|
|
70207
70858
|
addDomainScores(signal.domainScores, DOMAIN_CONFIG_HINTS["package.json"]);
|
|
@@ -70231,33 +70882,33 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
|
|
|
70231
70882
|
debugLog(`inferInitScaffoldFromRepo package.json parse failed: ${errorMessage(err)}`);
|
|
70232
70883
|
}
|
|
70233
70884
|
}
|
|
70234
|
-
const topLevelConfigs = Object.keys(DOMAIN_CONFIG_HINTS).filter((fileName) => fs49.existsSync(
|
|
70885
|
+
const topLevelConfigs = Object.keys(DOMAIN_CONFIG_HINTS).filter((fileName) => fs49.existsSync(path135.join(resolvedRoot, fileName)));
|
|
70235
70886
|
for (const configName of topLevelConfigs) {
|
|
70236
70887
|
signal.usefulSignals++;
|
|
70237
70888
|
const configScore = DOMAIN_CONFIG_HINTS[configName];
|
|
70238
70889
|
if (configScore) addDomainScores(signal.domainScores, configScore);
|
|
70239
70890
|
}
|
|
70240
70891
|
const readmeCandidates = [
|
|
70241
|
-
|
|
70242
|
-
|
|
70892
|
+
path135.join(resolvedRoot, "README.md"),
|
|
70893
|
+
path135.join(resolvedRoot, "readme.md")
|
|
70243
70894
|
];
|
|
70244
70895
|
for (const readmePath of readmeCandidates) {
|
|
70245
70896
|
if (!fs49.existsSync(readmePath)) continue;
|
|
70246
70897
|
const content = maybeReadUtf8(readmePath);
|
|
70247
70898
|
if (!content) continue;
|
|
70248
70899
|
signal.usefulSignals++;
|
|
70249
|
-
signal.referenceHints.push(
|
|
70900
|
+
signal.referenceHints.push(path135.relative(resolvedRoot, readmePath));
|
|
70250
70901
|
addTermCount(signal.terms, content, 2);
|
|
70251
70902
|
signal.docsText += ` ${content.toLowerCase()}`;
|
|
70252
70903
|
break;
|
|
70253
70904
|
}
|
|
70254
|
-
const docsDir =
|
|
70905
|
+
const docsDir = path135.join(resolvedRoot, "docs");
|
|
70255
70906
|
if (fs49.existsSync(docsDir) && fs49.statSync(docsDir).isDirectory()) {
|
|
70256
70907
|
signal.referenceHints.push("docs/");
|
|
70257
70908
|
for (const entry2 of fs49.readdirSync(docsDir, { withFileTypes: true })) {
|
|
70258
70909
|
if (!entry2.isFile()) continue;
|
|
70259
70910
|
if (!/\.(md|txt|rst)$/i.test(entry2.name)) continue;
|
|
70260
|
-
const docsContent = maybeReadUtf8(
|
|
70911
|
+
const docsContent = maybeReadUtf8(path135.join(docsDir, entry2.name));
|
|
70261
70912
|
if (!docsContent) continue;
|
|
70262
70913
|
signal.usefulSignals++;
|
|
70263
70914
|
addTermCount(signal.terms, docsContent, 1);
|
|
@@ -70265,7 +70916,7 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
|
|
|
70265
70916
|
}
|
|
70266
70917
|
}
|
|
70267
70918
|
for (const folderName of ["reference", "specs", "design", "architecture", "src", "packages", "apps"]) {
|
|
70268
|
-
const fullPath =
|
|
70919
|
+
const fullPath = path135.join(resolvedRoot, folderName);
|
|
70269
70920
|
if (fs49.existsSync(fullPath)) {
|
|
70270
70921
|
signal.referenceHints.push(`${folderName}/`);
|
|
70271
70922
|
}
|
|
@@ -70276,14 +70927,14 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
|
|
|
70276
70927
|
if (scannedFiles >= maxFiles) return;
|
|
70277
70928
|
for (const entry2 of fs49.readdirSync(dir, { withFileTypes: true })) {
|
|
70278
70929
|
if (scannedFiles >= maxFiles) return;
|
|
70279
|
-
const fullPath =
|
|
70930
|
+
const fullPath = path135.join(dir, entry2.name);
|
|
70280
70931
|
if (entry2.isDirectory()) {
|
|
70281
70932
|
if (skipDirs.has(entry2.name)) continue;
|
|
70282
70933
|
walk(fullPath);
|
|
70283
70934
|
continue;
|
|
70284
70935
|
}
|
|
70285
70936
|
scannedFiles++;
|
|
70286
|
-
const ext =
|
|
70937
|
+
const ext = path135.extname(entry2.name).toLowerCase();
|
|
70287
70938
|
if (!ext) continue;
|
|
70288
70939
|
const extScore = EXTENSION_DOMAIN_HINTS[ext];
|
|
70289
70940
|
if (extScore) {
|
|
@@ -70310,7 +70961,7 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
|
|
|
70310
70961
|
const topics = scoreTopicsFromTerms(inferredDomain, signal.terms, signal.docsText);
|
|
70311
70962
|
const references = Array.from(new Set(signal.referenceHints)).slice(0, 8);
|
|
70312
70963
|
const commands = Array.from(new Set(signal.commandHints)).slice(0, 5);
|
|
70313
|
-
const
|
|
70964
|
+
const reason3 = bestScore > 0 ? `inferred from repo files, config, and docs terminology (score ${bestScore})` : "fallback defaults";
|
|
70314
70965
|
if (signal.usefulSignals === 0) return null;
|
|
70315
70966
|
return {
|
|
70316
70967
|
domain: inferredDomain,
|
|
@@ -70318,7 +70969,7 @@ function inferInitScaffoldFromRepo(repoRoot, fallbackDomain = "software") {
|
|
|
70318
70969
|
referenceHints: references,
|
|
70319
70970
|
commandHints: commands,
|
|
70320
70971
|
confidence: Number(confidence.toFixed(2)),
|
|
70321
|
-
reason:
|
|
70972
|
+
reason: reason3
|
|
70322
70973
|
};
|
|
70323
70974
|
}
|
|
70324
70975
|
function appendInferredSections(base, inference) {
|
|
@@ -70457,7 +71108,7 @@ function findExistingProjectForSource(phrenPath, sourceRoot, derivedName) {
|
|
|
70457
71108
|
return null;
|
|
70458
71109
|
}
|
|
70459
71110
|
};
|
|
70460
|
-
const resolvedSource =
|
|
71111
|
+
const resolvedSource = path135.resolve(sourceRoot);
|
|
70461
71112
|
for (const project of candidates) {
|
|
70462
71113
|
if (sourceOf(project) === resolvedSource) return project;
|
|
70463
71114
|
}
|
|
@@ -70471,7 +71122,7 @@ function findExistingProjectForSource(phrenPath, sourceRoot, derivedName) {
|
|
|
70471
71122
|
function bootstrapFromExisting(phrenPath, projectPath2, opts = {}) {
|
|
70472
71123
|
const profile = typeof opts === "string" ? opts : opts.profile;
|
|
70473
71124
|
const profilePhrenPath = typeof opts === "string" ? phrenPath : opts.profilePhrenPath ?? phrenPath;
|
|
70474
|
-
const resolvedPath =
|
|
71125
|
+
const resolvedPath = path135.resolve(projectPath2);
|
|
70475
71126
|
if (!fs49.existsSync(resolvedPath)) {
|
|
70476
71127
|
throw new Error(`Path does not exist: ${resolvedPath}`);
|
|
70477
71128
|
}
|
|
@@ -70482,17 +71133,17 @@ function bootstrapFromExisting(phrenPath, projectPath2, opts = {}) {
|
|
|
70482
71133
|
if (worktreeRepoRoot) {
|
|
70483
71134
|
debugLog(`bootstrapFromExisting: ${resolvedPath} is a ${worktree.reason}; attributing to ${worktreeRepoRoot}`);
|
|
70484
71135
|
}
|
|
70485
|
-
const sourceRoot = isProjectLocal ?
|
|
71136
|
+
const sourceRoot = isProjectLocal ? path135.resolve(manifest.workspaceRoot || resolvedPath) : worktreeRepoRoot ?? resolvedPath;
|
|
70486
71137
|
if (isProjectLocal) {
|
|
70487
|
-
const matchesWorkspace = resolvedPath === sourceRoot || resolvedPath.startsWith(sourceRoot +
|
|
71138
|
+
const matchesWorkspace = resolvedPath === sourceRoot || resolvedPath.startsWith(sourceRoot + path135.sep);
|
|
70488
71139
|
if (!matchesWorkspace) {
|
|
70489
71140
|
throw new Error(`Project-local phren can only enroll the owning workspace: ${sourceRoot}`);
|
|
70490
71141
|
}
|
|
70491
71142
|
}
|
|
70492
71143
|
let claudeMdPath = null;
|
|
70493
71144
|
const candidates = [
|
|
70494
|
-
|
|
70495
|
-
|
|
71145
|
+
path135.join(sourceRoot, "AGENTS.md"),
|
|
71146
|
+
path135.join(sourceRoot, ".claude", "CLAUDE.md")
|
|
70496
71147
|
];
|
|
70497
71148
|
for (const c of candidates) {
|
|
70498
71149
|
if (fs49.existsSync(c)) {
|
|
@@ -70516,12 +71167,12 @@ function bootstrapFromExisting(phrenPath, projectPath2, opts = {}) {
|
|
|
70516
71167
|
`Project "${existingProject}" already exists with different casing. Refusing to bootstrap "${projectName2}" because it would split the same project on case-sensitive filesystems.`
|
|
70517
71168
|
);
|
|
70518
71169
|
}
|
|
70519
|
-
const projDir =
|
|
71170
|
+
const projDir = path135.join(phrenPath, projectName2);
|
|
70520
71171
|
fs49.mkdirSync(projDir, { recursive: true });
|
|
70521
71172
|
const inferredScaffold = inferInitScaffoldFromRepo(sourceRoot);
|
|
70522
71173
|
const existingConfig = readProjectConfig(phrenPath, projectName2);
|
|
70523
71174
|
const ownership = typeof opts === "string" ? parseProjectOwnershipMode(existingConfig.ownership) ?? getProjectOwnershipDefault(phrenPath) : opts.ownership ?? parseProjectOwnershipMode(existingConfig.ownership) ?? getProjectOwnershipDefault(phrenPath);
|
|
70524
|
-
const claudePath =
|
|
71175
|
+
const claudePath = path135.join(projDir, "AGENTS.md");
|
|
70525
71176
|
if (ownership !== "repo-managed") {
|
|
70526
71177
|
if (claudeContent) {
|
|
70527
71178
|
if (!fs49.existsSync(claudePath)) {
|
|
@@ -70556,7 +71207,7 @@ function bootstrapFromExisting(phrenPath, projectPath2, opts = {}) {
|
|
|
70556
71207
|
}
|
|
70557
71208
|
}
|
|
70558
71209
|
const sourceInfo = claudeMdPath ? `**Source AGENTS.md:** ${claudeMdPath}` : `**Source:** ${sourceRoot}`;
|
|
70559
|
-
const summaryPath =
|
|
71210
|
+
const summaryPath = path135.join(projDir, "summary.md");
|
|
70560
71211
|
if (!fs49.existsSync(summaryPath)) {
|
|
70561
71212
|
atomicWriteText(
|
|
70562
71213
|
summaryPath,
|
|
@@ -70569,18 +71220,18 @@ ${summaryLines.length > 1 ? summaryLines.slice(1).join("\n") : ""}
|
|
|
70569
71220
|
`
|
|
70570
71221
|
);
|
|
70571
71222
|
}
|
|
70572
|
-
if (!fs49.existsSync(
|
|
71223
|
+
if (!fs49.existsSync(path135.join(projDir, FINDINGS_FILENAME))) {
|
|
70573
71224
|
atomicWriteText(
|
|
70574
|
-
|
|
71225
|
+
path135.join(projDir, FINDINGS_FILENAME),
|
|
70575
71226
|
`# ${projectName2} FINDINGS
|
|
70576
71227
|
|
|
70577
71228
|
<!-- Bootstrapped from ${sourceRoot} -->
|
|
70578
71229
|
`
|
|
70579
71230
|
);
|
|
70580
71231
|
}
|
|
70581
|
-
if (moduleEnabled(phrenPath, "tasks") && !fs49.existsSync(
|
|
71232
|
+
if (moduleEnabled(phrenPath, "tasks") && !fs49.existsSync(path135.join(projDir, TASKS_FILENAME))) {
|
|
70582
71233
|
atomicWriteText(
|
|
70583
|
-
|
|
71234
|
+
path135.join(projDir, TASKS_FILENAME),
|
|
70584
71235
|
`# ${projectName2} tasks
|
|
70585
71236
|
|
|
70586
71237
|
## Active
|
|
@@ -70591,11 +71242,11 @@ ${summaryLines.length > 1 ? summaryLines.slice(1).join("\n") : ""}
|
|
|
70591
71242
|
`
|
|
70592
71243
|
);
|
|
70593
71244
|
}
|
|
70594
|
-
if (!fs49.existsSync(
|
|
71245
|
+
if (!fs49.existsSync(path135.join(projDir, "topic-config.json"))) {
|
|
70595
71246
|
const inferredDomain = normalizeBuiltinTopicDomain(inferredScaffold?.domain ?? "software");
|
|
70596
71247
|
const inferredTopics = inferredScaffold?.topics?.length ? inferredScaffold.topics : getBuiltinTopicConfig(inferredDomain);
|
|
70597
71248
|
atomicWriteText(
|
|
70598
|
-
|
|
71249
|
+
path135.join(projDir, "topic-config.json"),
|
|
70599
71250
|
JSON.stringify({ version: 1, domain: inferredDomain, topics: inferredTopics }, null, 2) + "\n"
|
|
70600
71251
|
);
|
|
70601
71252
|
}
|
|
@@ -70762,7 +71413,7 @@ var init_project_registry = __esm({
|
|
|
70762
71413
|
});
|
|
70763
71414
|
|
|
70764
71415
|
// src/core/project.ts
|
|
70765
|
-
import * as
|
|
71416
|
+
import * as path136 from "path";
|
|
70766
71417
|
function addProjectFromPath(phrenPath, targetPath, requestedProfile, ownership, options = {}) {
|
|
70767
71418
|
if (!targetPath) {
|
|
70768
71419
|
return phrenErr("Path is required. Pass the current project directory explicitly to avoid adding the wrong working directory.");
|
|
@@ -70774,10 +71425,10 @@ function addProjectFromPath(phrenPath, targetPath, requestedProfile, ownership,
|
|
|
70774
71425
|
if (!activeProfile.ok) return activeProfile;
|
|
70775
71426
|
const writePhrenPath = options.writeToPath ?? phrenPath;
|
|
70776
71427
|
const manifest = readRootManifest(phrenPath);
|
|
70777
|
-
const resolvedPath =
|
|
71428
|
+
const resolvedPath = path136.resolve(targetPath);
|
|
70778
71429
|
if (manifest?.installMode === "project-local") {
|
|
70779
|
-
const workspaceRoot =
|
|
70780
|
-
const matchesWorkspace = resolvedPath === workspaceRoot || resolvedPath.startsWith(workspaceRoot +
|
|
71430
|
+
const workspaceRoot = path136.resolve(manifest.workspaceRoot || "");
|
|
71431
|
+
const matchesWorkspace = resolvedPath === workspaceRoot || resolvedPath.startsWith(workspaceRoot + path136.sep);
|
|
70781
71432
|
if (!matchesWorkspace) {
|
|
70782
71433
|
return phrenErr(`Project-local phren can only add the owning workspace: ${workspaceRoot}`);
|
|
70783
71434
|
}
|
|
@@ -70796,9 +71447,9 @@ function addProjectFromPath(phrenPath, targetPath, requestedProfile, ownership,
|
|
|
70796
71447
|
ownership: added.ownership,
|
|
70797
71448
|
files: {
|
|
70798
71449
|
claude: added.claudePath,
|
|
70799
|
-
summary:
|
|
70800
|
-
findings:
|
|
70801
|
-
task:
|
|
71450
|
+
summary: path136.join(writePhrenPath, added.project, "summary.md"),
|
|
71451
|
+
findings: path136.join(writePhrenPath, added.project, FINDINGS_FILENAME),
|
|
71452
|
+
task: path136.join(writePhrenPath, added.project, TASKS_FILENAME)
|
|
70802
71453
|
}
|
|
70803
71454
|
});
|
|
70804
71455
|
}
|
|
@@ -70883,19 +71534,19 @@ var init_session_git = __esm({
|
|
|
70883
71534
|
});
|
|
70884
71535
|
|
|
70885
71536
|
// src/bridge/enroll.ts
|
|
70886
|
-
import { execFile as
|
|
70887
|
-
import { promisify as
|
|
71537
|
+
import { execFile as execFile30 } from "node:child_process";
|
|
71538
|
+
import { promisify as promisify28 } from "node:util";
|
|
70888
71539
|
import { realpathSync as realpathSync6 } from "node:fs";
|
|
70889
|
-
import { readdir as readdir20, readFile as
|
|
71540
|
+
import { readdir as readdir20, readFile as readFile56, stat as stat32, mkdir as mkdir34 } from "node:fs/promises";
|
|
70890
71541
|
import { homedir as homedir20 } from "node:os";
|
|
70891
|
-
import
|
|
71542
|
+
import path137 from "node:path";
|
|
70892
71543
|
function repoName(url2) {
|
|
70893
71544
|
const last = url2.replace(/\/+$/, "").split(/[/:]/).pop() ?? "";
|
|
70894
71545
|
return last.replace(/\.git$/i, "");
|
|
70895
71546
|
}
|
|
70896
71547
|
async function isRepository2(directory) {
|
|
70897
71548
|
try {
|
|
70898
|
-
await
|
|
71549
|
+
await stat32(path137.join(directory, ".git"));
|
|
70899
71550
|
return true;
|
|
70900
71551
|
} catch {
|
|
70901
71552
|
return false;
|
|
@@ -70915,7 +71566,7 @@ async function registeredSources(env) {
|
|
|
70915
71566
|
const source = readProjectConfig(store, project).sourcePath;
|
|
70916
71567
|
if (typeof source === "string" && source) {
|
|
70917
71568
|
try {
|
|
70918
|
-
paths.add(realpathSync6.native(
|
|
71569
|
+
paths.add(realpathSync6.native(path137.resolve(source)));
|
|
70919
71570
|
} catch {
|
|
70920
71571
|
}
|
|
70921
71572
|
}
|
|
@@ -70927,9 +71578,9 @@ async function candidateRepos(activity, env = process.env) {
|
|
|
70927
71578
|
const found = [];
|
|
70928
71579
|
const seen = /* @__PURE__ */ new Set();
|
|
70929
71580
|
const offer = async (directory, source, lastSeen) => {
|
|
70930
|
-
let dir =
|
|
71581
|
+
let dir = path137.resolve(directory);
|
|
70931
71582
|
try {
|
|
70932
|
-
if (!(await
|
|
71583
|
+
if (!(await stat32(dir)).isDirectory()) return;
|
|
70933
71584
|
dir = realpathSync6.native(dir);
|
|
70934
71585
|
} catch {
|
|
70935
71586
|
return;
|
|
@@ -70941,14 +71592,14 @@ async function candidateRepos(activity, env = process.env) {
|
|
|
70941
71592
|
};
|
|
70942
71593
|
const toplevel = async (directory) => {
|
|
70943
71594
|
let existing = directory;
|
|
70944
|
-
while (!await
|
|
70945
|
-
const parent =
|
|
71595
|
+
while (!await stat32(existing).catch(() => void 0)) {
|
|
71596
|
+
const parent = path137.dirname(existing);
|
|
70946
71597
|
if (parent === existing) return void 0;
|
|
70947
71598
|
existing = parent;
|
|
70948
71599
|
}
|
|
70949
71600
|
try {
|
|
70950
71601
|
countGit("enroll");
|
|
70951
|
-
return (await
|
|
71602
|
+
return (await exec25("git", ["-C", existing, "rev-parse", "--show-toplevel"], { env: nonInteractiveGitEnv(), timeout: 5e3 })).stdout.trim() || void 0;
|
|
70952
71603
|
} catch {
|
|
70953
71604
|
return void 0;
|
|
70954
71605
|
}
|
|
@@ -70962,7 +71613,7 @@ async function candidateRepos(activity, env = process.env) {
|
|
|
70962
71613
|
}
|
|
70963
71614
|
return root;
|
|
70964
71615
|
};
|
|
70965
|
-
const activityDirectory = (event) => typeof event.directory === "string" &&
|
|
71616
|
+
const activityDirectory = (event) => typeof event.directory === "string" && path137.isAbsolute(event.directory) ? event.directory : void 0;
|
|
70966
71617
|
const pending3 = [...new Set(activity.map(activityDirectory).filter((d) => !!d))];
|
|
70967
71618
|
await Promise.all(Array.from({ length: Math.min(8, pending3.length) }, async () => {
|
|
70968
71619
|
for (let directory = pending3.shift(); directory !== void 0; directory = pending3.shift()) await rootOf(directory);
|
|
@@ -70974,20 +71625,20 @@ async function candidateRepos(activity, env = process.env) {
|
|
|
70974
71625
|
if (root) await offer(root, "activity", typeof event.at === "string" ? event.at : void 0);
|
|
70975
71626
|
}
|
|
70976
71627
|
try {
|
|
70977
|
-
const session = JSON.parse(await
|
|
71628
|
+
const session = JSON.parse(await readFile56(path137.join(herdrRoot(), "session.json"), "utf8"));
|
|
70978
71629
|
for (const match of JSON.stringify(session).matchAll(/"cwd":\s*"((?:\\.|[^"\\])*)"/g)) {
|
|
70979
71630
|
const directory = JSON.parse(`"${match[1]}"`);
|
|
70980
|
-
if (!
|
|
71631
|
+
if (!path137.isAbsolute(directory)) continue;
|
|
70981
71632
|
const root = await rootOf(directory);
|
|
70982
71633
|
if (root) await offer(root, "herdr");
|
|
70983
71634
|
}
|
|
70984
71635
|
} catch {
|
|
70985
71636
|
}
|
|
70986
71637
|
const home = homedir20();
|
|
70987
|
-
for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.map((r) =>
|
|
71638
|
+
for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.map((r) => path137.join(home, r))]) {
|
|
70988
71639
|
let children = [];
|
|
70989
71640
|
try {
|
|
70990
|
-
children = (await readdir20(root, { withFileTypes: true })).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) =>
|
|
71641
|
+
children = (await readdir20(root, { withFileTypes: true })).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => path137.join(root, e.name));
|
|
70991
71642
|
} catch {
|
|
70992
71643
|
continue;
|
|
70993
71644
|
}
|
|
@@ -70997,14 +71648,14 @@ async function candidateRepos(activity, env = process.env) {
|
|
|
70997
71648
|
}
|
|
70998
71649
|
async function cloneRoot(env) {
|
|
70999
71650
|
const home = homedir20();
|
|
71000
|
-
for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.filter((r) => r !== "Sites").map((r) =>
|
|
71651
|
+
for (const root of [...env.PROJECTS_DIR ? [env.PROJECTS_DIR] : [], ...SEARCH_ROOTS2.filter((r) => r !== "Sites").map((r) => path137.join(home, r))]) {
|
|
71001
71652
|
try {
|
|
71002
|
-
if ((await
|
|
71653
|
+
if ((await stat32(root)).isDirectory()) return root;
|
|
71003
71654
|
} catch {
|
|
71004
71655
|
}
|
|
71005
71656
|
}
|
|
71006
|
-
const fallback2 =
|
|
71007
|
-
await
|
|
71657
|
+
const fallback2 = path137.join(home, "Projects");
|
|
71658
|
+
await mkdir34(fallback2, { recursive: true });
|
|
71008
71659
|
return fallback2;
|
|
71009
71660
|
}
|
|
71010
71661
|
async function publishStore(store, project) {
|
|
@@ -71029,7 +71680,7 @@ async function enrollProject(input2, env = process.env) {
|
|
|
71029
71680
|
const baseStore = phrenStoreRoot(env);
|
|
71030
71681
|
const store = await resolveCodeStore(baseStore, input2.store, true);
|
|
71031
71682
|
try {
|
|
71032
|
-
if (!(await
|
|
71683
|
+
if (!(await stat32(path137.join(baseStore, ".config"))).isDirectory()) throw new Error();
|
|
71033
71684
|
} catch {
|
|
71034
71685
|
throw new BridgeError(409, "phren is not set up on this computer. Run phren init there.");
|
|
71035
71686
|
}
|
|
@@ -71040,16 +71691,16 @@ async function enrollProject(input2, env = process.env) {
|
|
|
71040
71691
|
if (url2.length > 512 || !CLONE_URL.test(url2)) throw new BridgeError(400, "Enter a GitHub repository URL (https://github.com/owner/repo).");
|
|
71041
71692
|
const name = repoName(url2);
|
|
71042
71693
|
if (!name || name === "." || name === "..") throw new BridgeError(400, "That URL has no repository name.");
|
|
71043
|
-
directory =
|
|
71694
|
+
directory = path137.join(await cloneRoot(env), name);
|
|
71044
71695
|
try {
|
|
71045
|
-
await
|
|
71696
|
+
await stat32(directory);
|
|
71046
71697
|
throw new BridgeError(409, `${directory} already exists on this computer. Add that folder instead.`);
|
|
71047
71698
|
} catch (error62) {
|
|
71048
71699
|
if (error62 instanceof BridgeError) throw error62;
|
|
71049
71700
|
}
|
|
71050
71701
|
try {
|
|
71051
71702
|
countGit("enroll");
|
|
71052
|
-
await
|
|
71703
|
+
await exec25("git", ["clone", "--", url2, directory], { timeout: 18e4, maxBuffer: 4194304, env: nonInteractiveGitEnv(env) });
|
|
71053
71704
|
} catch (error62) {
|
|
71054
71705
|
const detail = error62 instanceof Error && "stderr" in error62 ? String(error62.stderr ?? "").trim().split("\n").pop() : void 0;
|
|
71055
71706
|
throw new BridgeError(502, `git clone failed${detail ? `: ${detail}` : ""}.`);
|
|
@@ -71057,10 +71708,10 @@ async function enrollProject(input2, env = process.env) {
|
|
|
71057
71708
|
cloned = true;
|
|
71058
71709
|
} else if (typeof input2.directory === "string" && input2.directory) {
|
|
71059
71710
|
const raw = input2.directory;
|
|
71060
|
-
if (raw.length > 4096 || raw.includes("\0") || !
|
|
71711
|
+
if (raw.length > 4096 || raw.includes("\0") || !path137.isAbsolute(raw)) throw new BridgeError(400, "Enter the full folder path on this computer.");
|
|
71061
71712
|
try {
|
|
71062
71713
|
directory = realpathSync6.native(raw);
|
|
71063
|
-
if (!(await
|
|
71714
|
+
if (!(await stat32(directory)).isDirectory()) throw new Error();
|
|
71064
71715
|
} catch {
|
|
71065
71716
|
throw new BridgeError(404, "That folder is not on this computer.");
|
|
71066
71717
|
}
|
|
@@ -71069,7 +71720,7 @@ async function enrollProject(input2, env = process.env) {
|
|
|
71069
71720
|
if (!added.ok) throw new BridgeError(409, added.error);
|
|
71070
71721
|
return { ok: true, project: added.data.project, directory, cloned, ...input2.project && input2.store ? { target: { project: added.data.project, store: input2.store } } : {}, ...await publishStore(store, added.data.project) };
|
|
71071
71722
|
}
|
|
71072
|
-
var
|
|
71723
|
+
var exec25, runEnrollStoreGit, SEARCH_ROOTS2, CLONE_URL;
|
|
71073
71724
|
var init_enroll = __esm({
|
|
71074
71725
|
"src/bridge/enroll.ts"() {
|
|
71075
71726
|
"use strict";
|
|
@@ -71086,7 +71737,7 @@ var init_enroll = __esm({
|
|
|
71086
71737
|
init_code_routes();
|
|
71087
71738
|
init_utils_paths();
|
|
71088
71739
|
init_machine_identity();
|
|
71089
|
-
|
|
71740
|
+
exec25 = promisify28(execFile30);
|
|
71090
71741
|
runEnrollStoreGit = async (cwd, args) => {
|
|
71091
71742
|
const result = await runBestEffortGit(args, cwd);
|
|
71092
71743
|
return { ok: result.ok, output: result.output ?? "", error: result.error };
|
|
@@ -71099,19 +71750,19 @@ var init_enroll = __esm({
|
|
|
71099
71750
|
// src/bridge/files.ts
|
|
71100
71751
|
import { constants as constants6 } from "node:fs";
|
|
71101
71752
|
import { lstat as lstat35, open as open27, readdir as readdir21, realpath as realpath24 } from "node:fs/promises";
|
|
71102
|
-
import
|
|
71753
|
+
import path138 from "node:path";
|
|
71103
71754
|
async function browseFiles(root, relative5) {
|
|
71104
|
-
if (relative5.length > 4096 || relative5.includes("\0") || relative5.includes("\\") ||
|
|
71755
|
+
if (relative5.length > 4096 || relative5.includes("\0") || relative5.includes("\\") || path138.isAbsolute(relative5) || relative5.split("/").some((part) => part === ".." || part === ".git")) {
|
|
71105
71756
|
throw new BridgeError(400, "Invalid repository path.");
|
|
71106
71757
|
}
|
|
71107
71758
|
const base = await realpath24(root);
|
|
71108
71759
|
let file4 = base;
|
|
71109
71760
|
for (const part of relative5.split("/").filter((part2) => part2 && part2 !== ".")) {
|
|
71110
|
-
file4 =
|
|
71761
|
+
file4 = path138.join(file4, part);
|
|
71111
71762
|
if ((await lstat35(file4)).isSymbolicLink()) throw new BridgeError(403, "Symbolic links cannot be browsed.");
|
|
71112
71763
|
}
|
|
71113
71764
|
const resolved = await realpath24(file4);
|
|
71114
|
-
if (resolved !== base && !resolved.startsWith(base +
|
|
71765
|
+
if (resolved !== base && !resolved.startsWith(base + path138.sep)) throw new BridgeError(403, "The path is outside this repository.");
|
|
71115
71766
|
const metadata = await lstat35(resolved);
|
|
71116
71767
|
if (metadata.isDirectory()) {
|
|
71117
71768
|
const entries2 = (await readdir21(resolved, { withFileTypes: true })).filter((entry2) => entry2.name !== ".git" && (entry2.isDirectory() || entry2.isFile())).sort((a, b) => Number(b.isDirectory()) - Number(a.isDirectory()) || a.name.localeCompare(b.name));
|
|
@@ -71119,7 +71770,7 @@ async function browseFiles(root, relative5) {
|
|
|
71119
71770
|
path: relative5,
|
|
71120
71771
|
kind: "directory",
|
|
71121
71772
|
truncated: entries2.length > 500,
|
|
71122
|
-
entries: entries2.slice(0, 500).map((entry2) => ({ name: entry2.name, path:
|
|
71773
|
+
entries: entries2.slice(0, 500).map((entry2) => ({ name: entry2.name, path: path138.posix.join(relative5, entry2.name), kind: entry2.isDirectory() ? "directory" : "file" }))
|
|
71123
71774
|
};
|
|
71124
71775
|
}
|
|
71125
71776
|
if (!metadata.isFile()) throw new BridgeError(400, "Only regular files can be viewed.");
|
|
@@ -71152,20 +71803,20 @@ var init_files = __esm({
|
|
|
71152
71803
|
|
|
71153
71804
|
// src/bridge/file-resolve.ts
|
|
71154
71805
|
import { lstat as lstat36, realpath as realpath25 } from "node:fs/promises";
|
|
71155
|
-
import
|
|
71806
|
+
import path139 from "node:path";
|
|
71156
71807
|
function beneath(root, file4) {
|
|
71157
|
-
const relative5 =
|
|
71158
|
-
return relative5 !== ".." && !relative5.startsWith(`..${
|
|
71808
|
+
const relative5 = path139.relative(root, file4);
|
|
71809
|
+
return relative5 !== ".." && !relative5.startsWith(`..${path139.sep}`) && !path139.isAbsolute(relative5);
|
|
71159
71810
|
}
|
|
71160
71811
|
async function resolveFilePath(root, cwd, requested) {
|
|
71161
71812
|
if (process.platform === "win32") requested = requested.replaceAll("\\", "/");
|
|
71162
|
-
if (!requested || requested.length > 4096 || /[\x00-\x1f\x7f\\]/.test(requested) || /^[A-Za-z]:[^/]/.test(requested) || requested.split("/").includes(".git") ||
|
|
71813
|
+
if (!requested || requested.length > 4096 || /[\x00-\x1f\x7f\\]/.test(requested) || /^[A-Za-z]:[^/]/.test(requested) || requested.split("/").includes(".git") || path139.win32.isAbsolute(requested) && !path139.isAbsolute(requested)) {
|
|
71163
71814
|
throw new BridgeError(400, "Invalid file path.");
|
|
71164
71815
|
}
|
|
71165
71816
|
const base = await realpath25(root), folder = await realpath25(cwd);
|
|
71166
71817
|
if (!beneath(base, folder)) throw new BridgeError(403, "This folder is outside the repository.");
|
|
71167
|
-
const roots = [base,
|
|
71168
|
-
const absolute =
|
|
71818
|
+
const roots = [base, path139.resolve(root), path139.resolve(cwd, path139.relative(folder, base))].map((value2) => value2.split(path139.sep).join("/"));
|
|
71819
|
+
const absolute = path139.isAbsolute(requested);
|
|
71169
71820
|
const alias = roots.find((candidate) => requested === candidate || requested.startsWith(candidate + "/"));
|
|
71170
71821
|
if (absolute && !alias) throw new BridgeError(403, "This file is outside the repository.");
|
|
71171
71822
|
const candidates = absolute ? [{ start: base, name: requested.slice(alias.length) }] : [.../* @__PURE__ */ new Set([folder, base])].map((start) => ({ start, name: requested }));
|
|
@@ -71173,11 +71824,11 @@ async function resolveFilePath(root, cwd, requested) {
|
|
|
71173
71824
|
try {
|
|
71174
71825
|
let file4 = candidate.start;
|
|
71175
71826
|
for (const part of candidate.name.split("/").filter((part2) => part2 && part2 !== ".")) {
|
|
71176
|
-
file4 =
|
|
71827
|
+
file4 = path139.resolve(file4, part);
|
|
71177
71828
|
if (!beneath(base, file4)) throw new BridgeError(403, "This file is outside the repository.");
|
|
71178
71829
|
if ((await lstat36(file4)).isSymbolicLink()) throw new BridgeError(403, "Symbolic links cannot be opened.");
|
|
71179
71830
|
}
|
|
71180
|
-
const relative5 =
|
|
71831
|
+
const relative5 = path139.relative(base, file4).split(path139.sep).join("/");
|
|
71181
71832
|
const metadata = await readFileRange(base, relative5, 0, 0);
|
|
71182
71833
|
return { path: relative5, size: metadata.total, contentType: metadata.contentType, version: metadata.version };
|
|
71183
71834
|
} catch (error62) {
|
|
@@ -71199,8 +71850,8 @@ var init_file_resolve = __esm({
|
|
|
71199
71850
|
// src/content/citation-freshness.ts
|
|
71200
71851
|
import { execFileSync as execFileSync9 } from "node:child_process";
|
|
71201
71852
|
import { readFileSync as readFileSync54, realpathSync as realpathSync7, renameSync as renameSync17, statSync as statSync27, unlinkSync as unlinkSync8, writeFileSync as writeFileSync23 } from "node:fs";
|
|
71202
|
-
import
|
|
71203
|
-
import { randomUUID as
|
|
71853
|
+
import path140 from "node:path";
|
|
71854
|
+
import { randomUUID as randomUUID30 } from "node:crypto";
|
|
71204
71855
|
function git8(root, timeoutMs, ...args) {
|
|
71205
71856
|
if (timeoutMs <= 0) return "";
|
|
71206
71857
|
try {
|
|
@@ -71214,13 +71865,13 @@ function git8(root, timeoutMs, ...args) {
|
|
|
71214
71865
|
}
|
|
71215
71866
|
}
|
|
71216
71867
|
function checkoutRoot2(repo, deadline) {
|
|
71217
|
-
if (!repo || !
|
|
71868
|
+
if (!repo || !path140.isAbsolute(repo)) return;
|
|
71218
71869
|
try {
|
|
71219
71870
|
const root = realpathSync7(repo);
|
|
71220
71871
|
const toplevel = git8(root, Math.min(GIT_TIMEOUT_MS, deadline - Date.now()), "rev-parse", "--show-toplevel");
|
|
71221
|
-
if (!toplevel || !
|
|
71872
|
+
if (!toplevel || !path140.isAbsolute(toplevel)) return;
|
|
71222
71873
|
const canonical3 = (value2) => {
|
|
71223
|
-
const resolved =
|
|
71874
|
+
const resolved = path140.resolve((realpathSync7.native ?? realpathSync7)(value2));
|
|
71224
71875
|
return process.platform === "win32" ? resolved.toLowerCase() : resolved;
|
|
71225
71876
|
};
|
|
71226
71877
|
return canonical3(toplevel) === canonical3(root) ? root : void 0;
|
|
@@ -71253,16 +71904,16 @@ function repository5(citation, opts, entries2, deadline) {
|
|
|
71253
71904
|
}
|
|
71254
71905
|
function target(citation, repo) {
|
|
71255
71906
|
if (!citation.file || !citation.commit || !/^[a-f0-9]{7,64}$/i.test(citation.commit)) return;
|
|
71256
|
-
let file4 = citation.file.split(
|
|
71907
|
+
let file4 = citation.file.split(path140.sep).join("/");
|
|
71257
71908
|
if (file4.includes("\\") || file4.includes("\0") || file4.split("/").includes("..")) return;
|
|
71258
71909
|
if (!repo || !validDomain(repo.domain) || !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repo.path) || repo.path.split("/").some((part) => part === "." || part === "..")) return;
|
|
71259
|
-
if (
|
|
71260
|
-
if (!repo.root || !
|
|
71261
|
-
const absolute = citation.repo &&
|
|
71262
|
-
file4 =
|
|
71263
|
-
if (file4 === ".." || file4.startsWith("../") ||
|
|
71910
|
+
if (path140.isAbsolute(file4)) {
|
|
71911
|
+
if (!repo.root || !path140.isAbsolute(repo.root)) return;
|
|
71912
|
+
const absolute = citation.repo && path140.isAbsolute(citation.repo) ? path140.resolve(repo.root, path140.relative(citation.repo, file4)) : file4;
|
|
71913
|
+
file4 = path140.relative(repo.root, absolute).split(path140.sep).join("/");
|
|
71914
|
+
if (file4 === ".." || file4.startsWith("../") || path140.isAbsolute(file4)) return;
|
|
71264
71915
|
}
|
|
71265
|
-
file4 =
|
|
71916
|
+
file4 = path140.posix.normalize(file4);
|
|
71266
71917
|
if (!file4 || file4 === "." || file4.startsWith("../")) return;
|
|
71267
71918
|
const result = { domain: repo.domain, repo: repo.path, commit: citation.commit, file: file4 };
|
|
71268
71919
|
return { ...result, key: JSON.stringify([result.domain, result.repo, result.commit, file4]) };
|
|
@@ -71299,7 +71950,7 @@ function fresh(value2) {
|
|
|
71299
71950
|
}
|
|
71300
71951
|
function save2(file4, entries2) {
|
|
71301
71952
|
if (!file4) return;
|
|
71302
|
-
const temp = `${file4}.${
|
|
71953
|
+
const temp = `${file4}.${randomUUID30()}.tmp`;
|
|
71303
71954
|
try {
|
|
71304
71955
|
const previous = readCache(file4);
|
|
71305
71956
|
const merged = { ...previous, ...entries2 };
|
|
@@ -75027,10 +75678,10 @@ var init_finding = __esm({
|
|
|
75027
75678
|
|
|
75028
75679
|
// src/tools/extract-facts.ts
|
|
75029
75680
|
import * as fs51 from "fs";
|
|
75030
|
-
import * as
|
|
75681
|
+
import * as path141 from "path";
|
|
75031
75682
|
function preferencesPath(phrenPath, project) {
|
|
75032
75683
|
const dir = storeAwareProjectPath(phrenPath, project);
|
|
75033
|
-
return dir ?
|
|
75684
|
+
return dir ? path141.join(dir, "preferences.json") : null;
|
|
75034
75685
|
}
|
|
75035
75686
|
function readExtractedFacts(phrenPath, project) {
|
|
75036
75687
|
const p = preferencesPath(phrenPath, project);
|
|
@@ -75277,10 +75928,10 @@ __export(journal_exports, {
|
|
|
75277
75928
|
readTeamJournalEntries: () => readTeamJournalEntries
|
|
75278
75929
|
});
|
|
75279
75930
|
import * as fs53 from "fs";
|
|
75280
|
-
import * as
|
|
75931
|
+
import * as path142 from "path";
|
|
75281
75932
|
import * as crypto13 from "crypto";
|
|
75282
75933
|
function journalRoot(phrenPath) {
|
|
75283
|
-
const dir =
|
|
75934
|
+
const dir = path142.join(runtimeDir(phrenPath), "finding-journal");
|
|
75284
75935
|
fs53.mkdirSync(dir, { recursive: true });
|
|
75285
75936
|
return dir;
|
|
75286
75937
|
}
|
|
@@ -75290,20 +75941,20 @@ function sanitizeSessionId(sessionId2) {
|
|
|
75290
75941
|
return safe2 || "session";
|
|
75291
75942
|
}
|
|
75292
75943
|
function journalFileFor(phrenPath, project, sessionId2) {
|
|
75293
|
-
const projectDir =
|
|
75944
|
+
const projectDir = path142.join(journalRoot(phrenPath), project);
|
|
75294
75945
|
fs53.mkdirSync(projectDir, { recursive: true });
|
|
75295
|
-
return
|
|
75946
|
+
return path142.join(projectDir, `${sanitizeSessionId(sessionId2)}.jsonl`);
|
|
75296
75947
|
}
|
|
75297
75948
|
function listJournalFiles(phrenPath, project) {
|
|
75298
75949
|
const root = journalRoot(phrenPath);
|
|
75299
|
-
const projects = project ? [project] : fs53.readdirSync(root).filter((entry2) => fs53.statSync(
|
|
75950
|
+
const projects = project ? [project] : fs53.readdirSync(root).filter((entry2) => fs53.statSync(path142.join(root, entry2)).isDirectory());
|
|
75300
75951
|
const files = [];
|
|
75301
75952
|
for (const projectName2 of projects) {
|
|
75302
|
-
const projectDir =
|
|
75953
|
+
const projectDir = path142.join(root, projectName2);
|
|
75303
75954
|
if (!fs53.existsSync(projectDir)) continue;
|
|
75304
75955
|
for (const entry2 of fs53.readdirSync(projectDir)) {
|
|
75305
75956
|
if (!entry2.endsWith(".jsonl")) continue;
|
|
75306
|
-
files.push(
|
|
75957
|
+
files.push(path142.join(projectDir, entry2));
|
|
75307
75958
|
}
|
|
75308
75959
|
}
|
|
75309
75960
|
return files.sort();
|
|
@@ -75323,7 +75974,7 @@ function appendFindingJournal(phrenPath, project, text5, opts = {}) {
|
|
|
75323
75974
|
};
|
|
75324
75975
|
try {
|
|
75325
75976
|
withFileLock(filePath, () => {
|
|
75326
|
-
fs53.mkdirSync(
|
|
75977
|
+
fs53.mkdirSync(path142.dirname(filePath), { recursive: true });
|
|
75327
75978
|
fs53.appendFileSync(filePath, JSON.stringify(entry2) + "\n");
|
|
75328
75979
|
});
|
|
75329
75980
|
return phrenOk(filePath);
|
|
@@ -75383,9 +76034,9 @@ function compactFindingJournals(phrenPath, project) {
|
|
|
75383
76034
|
function appendTeamJournal(storePath, project, finding2, actor, machine) {
|
|
75384
76035
|
const resolvedActor = actor || getCurrentActor();
|
|
75385
76036
|
const date5 = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
|
|
75386
|
-
const journalDir =
|
|
76037
|
+
const journalDir = path142.join(storePath, project, TEAM_JOURNAL_DIR);
|
|
75387
76038
|
const journalFile = `${date5}-${resolvedActor}.md`;
|
|
75388
|
-
const journalPath =
|
|
76039
|
+
const journalPath = path142.join(journalDir, journalFile);
|
|
75389
76040
|
try {
|
|
75390
76041
|
fs53.mkdirSync(journalDir, { recursive: true });
|
|
75391
76042
|
const sourceComment = buildSourceComment({ source: "human", machine, actor: resolvedActor });
|
|
@@ -75404,13 +76055,13 @@ ${entry2}`);
|
|
|
75404
76055
|
}
|
|
75405
76056
|
}
|
|
75406
76057
|
function readTeamJournalEntries(storePath, project) {
|
|
75407
|
-
const journalDir =
|
|
76058
|
+
const journalDir = path142.join(storePath, project, TEAM_JOURNAL_DIR);
|
|
75408
76059
|
if (!fs53.existsSync(journalDir)) return [];
|
|
75409
76060
|
return fs53.readdirSync(journalDir).filter((f) => f.endsWith(".md")).sort().reverse().map((file4) => {
|
|
75410
76061
|
const match = file4.match(/^(\d{4}-\d{2}-\d{2})-(.+)\.md$/);
|
|
75411
76062
|
const date5 = match?.[1] ?? "unknown";
|
|
75412
76063
|
const actor = match?.[2] ?? "unknown";
|
|
75413
|
-
const content = fs53.readFileSync(
|
|
76064
|
+
const content = fs53.readFileSync(path142.join(journalDir, file4), "utf8");
|
|
75414
76065
|
const entries2 = content.split("\n").filter((line) => line.startsWith("- ")).map((line) => line.slice(2).trim());
|
|
75415
76066
|
return { file: file4, date: date5, actor, entries: entries2 };
|
|
75416
76067
|
});
|
|
@@ -75440,7 +76091,7 @@ function materializeTeamFindings(storePath, project) {
|
|
|
75440
76091
|
}
|
|
75441
76092
|
lines.push("");
|
|
75442
76093
|
}
|
|
75443
|
-
const findingsPath =
|
|
76094
|
+
const findingsPath = path142.join(storePath, project, FINDINGS_FILENAME);
|
|
75444
76095
|
try {
|
|
75445
76096
|
atomicWriteText(findingsPath, lines.join("\n"));
|
|
75446
76097
|
return phrenOk({ entryCount: count2 });
|
|
@@ -75472,10 +76123,10 @@ __export(finding_exports, {
|
|
|
75472
76123
|
syncTeamStores: () => syncTeamStores
|
|
75473
76124
|
});
|
|
75474
76125
|
import * as fs54 from "fs";
|
|
75475
|
-
import * as
|
|
76126
|
+
import * as path143 from "path";
|
|
75476
76127
|
function findJaccardCandidates(phrenPath, project, finding2) {
|
|
75477
76128
|
try {
|
|
75478
|
-
const findingsPath =
|
|
76129
|
+
const findingsPath = path143.join(phrenPath, project, FINDINGS_FILENAME);
|
|
75479
76130
|
if (!fs54.existsSync(findingsPath)) return [];
|
|
75480
76131
|
const content = fs54.readFileSync(findingsPath, "utf8");
|
|
75481
76132
|
const newClean = stripMetadata(finding2).trim();
|
|
@@ -75499,7 +76150,7 @@ function findJaccardCandidates(phrenPath, project, finding2) {
|
|
|
75499
76150
|
}
|
|
75500
76151
|
function findConflictCandidates(phrenPath, project, finding2) {
|
|
75501
76152
|
try {
|
|
75502
|
-
const findingsPath =
|
|
76153
|
+
const findingsPath = path143.join(phrenPath, project, FINDINGS_FILENAME);
|
|
75503
76154
|
if (!fs54.existsSync(findingsPath)) return [];
|
|
75504
76155
|
const content = fs54.readFileSync(findingsPath, "utf8");
|
|
75505
76156
|
const activeBullets = content.split("\n").filter((l) => l.startsWith("- ") && !isInactiveFindingLine(l));
|
|
@@ -75533,7 +76184,7 @@ function withLifecycleMutation(phrenPath, project, writeQueue, updateIndex, hand
|
|
|
75533
76184
|
const result = handler();
|
|
75534
76185
|
if (!result.ok) return mcpResponse({ ok: false, error: result.error });
|
|
75535
76186
|
const resolvedFindingsDir = storeAwareProjectPath(phrenPath, project);
|
|
75536
|
-
if (resolvedFindingsDir) updateIndex(
|
|
76187
|
+
if (resolvedFindingsDir) updateIndex(path143.join(resolvedFindingsDir, FINDINGS_FILENAME));
|
|
75537
76188
|
const mapped = mapResponse(result.data);
|
|
75538
76189
|
return mcpResponse({ ok: true, message: mapped.message, data: mapped.data });
|
|
75539
76190
|
});
|
|
@@ -75590,7 +76241,7 @@ async function handleAddFinding(ctx, params) {
|
|
|
75590
76241
|
const result = appendTeamJournal2(phrenPath, project, taggedFinding, provenance.actor, provenance.machine);
|
|
75591
76242
|
if (result.ok) {
|
|
75592
76243
|
added.push(taggedFinding);
|
|
75593
|
-
journals.add(
|
|
76244
|
+
journals.add(path143.join(phrenPath, project, "journal", result.data));
|
|
75594
76245
|
} else {
|
|
75595
76246
|
rejected.push({ finding: taggedFinding.slice(0, 60), reason: result.error });
|
|
75596
76247
|
}
|
|
@@ -75642,7 +76293,7 @@ async function handleAddFinding(ctx, params) {
|
|
|
75642
76293
|
if (added.length > 0) {
|
|
75643
76294
|
runCustomHooks(phrenPath, "post-finding", { PHREN_PROJECT: project });
|
|
75644
76295
|
incrementSessionFindings(phrenPath, added.length, sessionId2, project);
|
|
75645
|
-
updateFileInIndex(
|
|
76296
|
+
updateFileInIndex(path143.join(phrenPath, project, FINDINGS_FILENAME));
|
|
75646
76297
|
}
|
|
75647
76298
|
const rejectedMsg = rejected.length > 0 ? `, ${rejected.length} rejected` : "";
|
|
75648
76299
|
return mcpResponse({
|
|
@@ -75681,7 +76332,7 @@ async function handleAddFinding(ctx, params) {
|
|
|
75681
76332
|
if (result.data.status === "skipped") {
|
|
75682
76333
|
return mcpResponse({ ok: true, message: result.data.message, data: { project, finding: taggedFinding, status: "skipped" } });
|
|
75683
76334
|
}
|
|
75684
|
-
updateFileInIndex(
|
|
76335
|
+
updateFileInIndex(path143.join(phrenPath, project, FINDINGS_FILENAME));
|
|
75685
76336
|
if (result.data.status === "added" || result.data.status === "created") {
|
|
75686
76337
|
runCustomHooks(phrenPath, "post-finding", { PHREN_PROJECT: project });
|
|
75687
76338
|
incrementSessionFindings(phrenPath, 1, sessionId2, project);
|
|
@@ -75691,7 +76342,7 @@ async function handleAddFinding(ctx, params) {
|
|
|
75691
76342
|
if (activeTask) {
|
|
75692
76343
|
const taskMatch = activeTask.stableId ? `bid:${activeTask.stableId}` : activeTask.line;
|
|
75693
76344
|
try {
|
|
75694
|
-
const findingsPath =
|
|
76345
|
+
const findingsPath = path143.join(phrenPath, project, FINDINGS_FILENAME);
|
|
75695
76346
|
const findingsContent = fs54.readFileSync(findingsPath, "utf8");
|
|
75696
76347
|
const lines = findingsContent.split("\n");
|
|
75697
76348
|
const taggedText = taggedFinding.replace(/^-\s+/, "").trim().slice(0, 60).toLowerCase();
|
|
@@ -75762,7 +76413,7 @@ async function handleSupersedeFinding(ctx, { project: projectInput, finding_text
|
|
|
75762
76413
|
})
|
|
75763
76414
|
);
|
|
75764
76415
|
}
|
|
75765
|
-
async function handleRetractFinding(ctx, { project: projectInput, finding_text, reason:
|
|
76416
|
+
async function handleRetractFinding(ctx, { project: projectInput, finding_text, reason: reason3 }) {
|
|
75766
76417
|
let phrenPath;
|
|
75767
76418
|
let project;
|
|
75768
76419
|
try {
|
|
@@ -75778,7 +76429,7 @@ async function handleRetractFinding(ctx, { project: projectInput, finding_text,
|
|
|
75778
76429
|
project,
|
|
75779
76430
|
withWriteQueue,
|
|
75780
76431
|
updateFileInIndex,
|
|
75781
|
-
() => retractFinding(phrenPath, project, finding_text,
|
|
76432
|
+
() => retractFinding(phrenPath, project, finding_text, reason3),
|
|
75782
76433
|
(data) => ({
|
|
75783
76434
|
message: `Retracted finding in ${project}.`,
|
|
75784
76435
|
data: { project, finding: data.finding, status: data.status, reason: data.reason }
|
|
@@ -75880,7 +76531,7 @@ async function handleEditFinding(ctx, { project: projectInput, old_text, new_tex
|
|
|
75880
76531
|
const result = editFinding(phrenPath, project, old_text, new_text);
|
|
75881
76532
|
if (!result.ok) return mcpResponse({ ok: false, error: result.error });
|
|
75882
76533
|
const resolvedFindingsDir = storeAwareProjectPath(phrenPath, project);
|
|
75883
|
-
if (resolvedFindingsDir) updateFileInIndex(
|
|
76534
|
+
if (resolvedFindingsDir) updateFileInIndex(path143.join(resolvedFindingsDir, FINDINGS_FILENAME));
|
|
75884
76535
|
return mcpResponse({
|
|
75885
76536
|
ok: true,
|
|
75886
76537
|
message: result.data,
|
|
@@ -75907,7 +76558,7 @@ async function handleRemoveFinding(ctx, { project: projectInput, finding: findin
|
|
|
75907
76558
|
const result = removeFindings(phrenPath, project, finding2);
|
|
75908
76559
|
if (!result.ok) return mcpResponse({ ok: false, error: result.message });
|
|
75909
76560
|
const resolvedFindingsDir = storeAwareProjectPath(phrenPath, project);
|
|
75910
|
-
if (resolvedFindingsDir) updateFileInIndex(
|
|
76561
|
+
if (resolvedFindingsDir) updateFileInIndex(path143.join(resolvedFindingsDir, FINDINGS_FILENAME));
|
|
75911
76562
|
return mcpResponse({ ok: true, message: result.message, data: result.data });
|
|
75912
76563
|
});
|
|
75913
76564
|
}
|
|
@@ -75915,7 +76566,7 @@ async function handleRemoveFinding(ctx, { project: projectInput, finding: findin
|
|
|
75915
76566
|
const result = removeFinding2(phrenPath, project, finding2);
|
|
75916
76567
|
if (!result.ok) return mcpResponse({ ok: false, error: result.message });
|
|
75917
76568
|
const resolvedFindingsDir = storeAwareProjectPath(phrenPath, project);
|
|
75918
|
-
if (resolvedFindingsDir) updateFileInIndex(
|
|
76569
|
+
if (resolvedFindingsDir) updateFileInIndex(path143.join(resolvedFindingsDir, FINDINGS_FILENAME));
|
|
75919
76570
|
return mcpResponse({ ok: true, message: result.message, data: result.data });
|
|
75920
76571
|
});
|
|
75921
76572
|
}
|
|
@@ -75926,7 +76577,7 @@ async function syncTeamStores(phrenPath) {
|
|
|
75926
76577
|
const { getNonPrimaryStores: getNonPrimaryStores2 } = await Promise.resolve().then(() => (init_store_registry(), store_registry_exports));
|
|
75927
76578
|
const teamStores = getNonPrimaryStores2(phrenPath).filter((s) => s.role === "team");
|
|
75928
76579
|
for (const store of teamStores) {
|
|
75929
|
-
if (!fs54.existsSync(store.path) || !fs54.existsSync(
|
|
76580
|
+
if (!fs54.existsSync(store.path) || !fs54.existsSync(path143.join(store.path, ".git"))) continue;
|
|
75930
76581
|
const runStoreGit = (args, opts = {}) => execFileSync10("git", args, {
|
|
75931
76582
|
cwd: store.path,
|
|
75932
76583
|
encoding: "utf8",
|
|
@@ -76259,7 +76910,7 @@ var init_finding2 = __esm({
|
|
|
76259
76910
|
|
|
76260
76911
|
// src/bridge/project-memory.ts
|
|
76261
76912
|
import * as fs55 from "node:fs";
|
|
76262
|
-
import * as
|
|
76913
|
+
import * as path144 from "node:path";
|
|
76263
76914
|
function freshnessOptions(root, project) {
|
|
76264
76915
|
return { phrenPath: root, projectRemote: getProjectRemote(root, project, readProjectConfig(root, project)) };
|
|
76265
76916
|
}
|
|
@@ -76301,7 +76952,7 @@ function locate(base, rawProject) {
|
|
|
76301
76952
|
} catch {
|
|
76302
76953
|
throw new BridgeError(404, "Project not found.");
|
|
76303
76954
|
}
|
|
76304
|
-
const storeId = taskStores(base).find((entry2) =>
|
|
76955
|
+
const storeId = taskStores(base).find((entry2) => path144.resolve(entry2.path) === path144.resolve(root))?.taskStoreId ?? null;
|
|
76305
76956
|
return { project, root, storeId };
|
|
76306
76957
|
}
|
|
76307
76958
|
function sortedFindings(root, project, opts) {
|
|
@@ -76314,7 +76965,7 @@ function sortedFindings(root, project, opts) {
|
|
|
76314
76965
|
return result.data.map((item, index2) => ({ item, index: index2, date: DATE.test(item.date) ? item.date : "" })).sort((a, b) => b.date.localeCompare(a.date) || a.index - b.index).map((entry2) => entry2.item);
|
|
76315
76966
|
}
|
|
76316
76967
|
function readTruths(root, project) {
|
|
76317
|
-
const file4 =
|
|
76968
|
+
const file4 = path144.join(root, project, "truths.md");
|
|
76318
76969
|
return fs55.existsSync(file4) ? fs55.readFileSync(file4, "utf8").split("\n").filter((line) => line.startsWith("- ")).map((line) => line.slice(2).trim()) : [];
|
|
76319
76970
|
}
|
|
76320
76971
|
function projectMemory(base, rawProject) {
|
|
@@ -76558,292 +77209,6 @@ var init_project_git = __esm({
|
|
|
76558
77209
|
}
|
|
76559
77210
|
});
|
|
76560
77211
|
|
|
76561
|
-
// src/bridge/simulators.ts
|
|
76562
|
-
import { execFile as execFile30 } from "node:child_process";
|
|
76563
|
-
import { chmod as chmod5, mkdir as mkdir34, readFile as readFile56, rename as rename11, stat as stat32, unlink as unlink9, writeFile as writeFile11 } from "node:fs/promises";
|
|
76564
|
-
import { tmpdir as tmpdir7 } from "node:os";
|
|
76565
|
-
import path144 from "node:path";
|
|
76566
|
-
import { createHash as createHash35, randomUUID as randomUUID31 } from "node:crypto";
|
|
76567
|
-
import { promisify as promisify28 } from "node:util";
|
|
76568
|
-
async function bootedSimulators() {
|
|
76569
|
-
if (process.platform !== "darwin") return [];
|
|
76570
|
-
const { stdout } = await exec25("/usr/bin/xcrun", ["simctl", "list", "devices", "booted", "-j"], { timeout: 8e3, maxBuffer: 4194304 }).catch(() => ({ stdout: "{}" }));
|
|
76571
|
-
let parsed = {};
|
|
76572
|
-
try {
|
|
76573
|
-
parsed = JSON.parse(stdout);
|
|
76574
|
-
} catch {
|
|
76575
|
-
return [];
|
|
76576
|
-
}
|
|
76577
|
-
const list = [];
|
|
76578
|
-
for (const [runtimeID, devices] of Object.entries(parsed.devices ?? {})) {
|
|
76579
|
-
const runtime = runtimeID.replace(/^.*SimRuntime\./, "").replace(/-(\d+)-(\d+)$/, " $1.$2").replace(/-/g, " ");
|
|
76580
|
-
for (const device of devices ?? []) {
|
|
76581
|
-
if (device.state !== "Booted" || !device.udid || !UDID.test(device.udid)) continue;
|
|
76582
|
-
list.push({ udid: device.udid.toUpperCase(), name: String(device.name ?? "Simulator").slice(0, 120), runtime });
|
|
76583
|
-
if (list.length >= 16) return list;
|
|
76584
|
-
}
|
|
76585
|
-
}
|
|
76586
|
-
return list;
|
|
76587
|
-
}
|
|
76588
|
-
async function simulatorScreenshot(udid) {
|
|
76589
|
-
if (!UDID.test(udid)) throw new BridgeError(400, "Invalid simulator identifier.");
|
|
76590
|
-
if (process.platform !== "darwin") throw new BridgeError(404, "Simulators run on macOS only.");
|
|
76591
|
-
const file4 = path144.join(tmpdir7(), `phren-sim-${randomUUID31()}.png`);
|
|
76592
|
-
try {
|
|
76593
|
-
await exec25("/usr/bin/xcrun", ["simctl", "io", udid, "screenshot", "--type=png", file4], { timeout: 15e3 });
|
|
76594
|
-
return await readFile56(file4);
|
|
76595
|
-
} catch (error62) {
|
|
76596
|
-
if (error62 instanceof BridgeError) throw error62;
|
|
76597
|
-
throw new BridgeError(409, "Couldn't capture that simulator. Is it still booted?");
|
|
76598
|
-
} finally {
|
|
76599
|
-
await unlink9(file4).catch(() => void 0);
|
|
76600
|
-
}
|
|
76601
|
-
}
|
|
76602
|
-
function helper() {
|
|
76603
|
-
building ??= buildHelper().finally(() => {
|
|
76604
|
-
building = void 0;
|
|
76605
|
-
});
|
|
76606
|
-
return building;
|
|
76607
|
-
}
|
|
76608
|
-
async function buildHelper() {
|
|
76609
|
-
const dir = path144.join(bridgeRoot(), "native");
|
|
76610
|
-
const binary = path144.join(dir, "simtap");
|
|
76611
|
-
const code = true ? `// Touches and keys for the iOS Simulator, without AppleScript: the window
|
|
76612
|
-
// is found through the Accessibility API and events are posted with CGEvent,
|
|
76613
|
-
// so one Accessibility grant for this helper is all macOS asks for.
|
|
76614
|
-
// Built on demand by Phren Hook with swiftc; see simulators.ts.
|
|
76615
|
-
import ApplicationServices
|
|
76616
|
-
import Cocoa
|
|
76617
|
-
|
|
76618
|
-
func fail(_ code: Int32, _ message: String) -> Never { FileHandle.standardError.write((message + "\\n").data(using: .utf8)!); exit(code) }
|
|
76619
|
-
|
|
76620
|
-
let args = CommandLine.arguments
|
|
76621
|
-
guard args.count >= 3 else { fail(2, "usage: simtap <window-title-prefix> tap <fx> <fy> | key <keycode> [cmd] [shift] | type <text> | raise | prompt") }
|
|
76622
|
-
let prefix = args[1], command = args[2]
|
|
76623
|
-
|
|
76624
|
-
// "prompt" asks macOS for the grant: it adds this helper to Privacy & Security
|
|
76625
|
-
// \u2192 Accessibility (switched off) and shows the system's own dialog, so the
|
|
76626
|
-
// person switches it on instead of hunting for a hidden folder behind +.
|
|
76627
|
-
if command == "prompt" {
|
|
76628
|
-
let options = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary
|
|
76629
|
-
exit(AXIsProcessTrustedWithOptions(options) ? 0 : 3)
|
|
76630
|
-
}
|
|
76631
|
-
guard AXIsProcessTrusted() else { fail(3, "accessibility") }
|
|
76632
|
-
guard let app = NSRunningApplication.runningApplications(withBundleIdentifier: "com.apple.iphonesimulator").first else { fail(4, "Simulator is not running") }
|
|
76633
|
-
let element = AXUIElementCreateApplication(app.processIdentifier)
|
|
76634
|
-
var windowsRef: CFTypeRef?
|
|
76635
|
-
AXUIElementCopyAttributeValue(element, kAXWindowsAttribute as CFString, &windowsRef)
|
|
76636
|
-
let windows = (windowsRef as? [AXUIElement]) ?? []
|
|
76637
|
-
var target: AXUIElement?
|
|
76638
|
-
for window in windows {
|
|
76639
|
-
var titleRef: CFTypeRef?
|
|
76640
|
-
AXUIElementCopyAttributeValue(window, kAXTitleAttribute as CFString, &titleRef)
|
|
76641
|
-
if let title = titleRef as? String, title.hasPrefix(prefix + " ") || title == prefix { target = window; break }
|
|
76642
|
-
}
|
|
76643
|
-
guard let window = target else { fail(5, "no window for \\(prefix)") }
|
|
76644
|
-
|
|
76645
|
-
func frame(_ window: AXUIElement) -> CGRect {
|
|
76646
|
-
var posRef: CFTypeRef?, sizeRef: CFTypeRef?
|
|
76647
|
-
AXUIElementCopyAttributeValue(window, kAXPositionAttribute as CFString, &posRef)
|
|
76648
|
-
AXUIElementCopyAttributeValue(window, kAXSizeAttribute as CFString, &sizeRef)
|
|
76649
|
-
var pos = CGPoint.zero, size = CGSize.zero
|
|
76650
|
-
if let p = posRef { AXValueGetValue(p as! AXValue, .cgPoint, &pos) }
|
|
76651
|
-
if let s = sizeRef { AXValueGetValue(s as! AXValue, .cgSize, &size) }
|
|
76652
|
-
return CGRect(origin: pos, size: size)
|
|
76653
|
-
}
|
|
76654
|
-
func raise() {
|
|
76655
|
-
app.activate(options: [])
|
|
76656
|
-
AXUIElementPerformAction(window, kAXRaiseAction as CFString)
|
|
76657
|
-
usleep(120_000)
|
|
76658
|
-
}
|
|
76659
|
-
func post(_ event: CGEvent?) {
|
|
76660
|
-
guard NSWorkspace.shared.frontmostApplication?.processIdentifier == app.processIdentifier else { fail(6, "focus lost") }
|
|
76661
|
-
event?.postToPid(app.processIdentifier)
|
|
76662
|
-
usleep(40_000)
|
|
76663
|
-
}
|
|
76664
|
-
|
|
76665
|
-
switch command {
|
|
76666
|
-
case "raise": raise()
|
|
76667
|
-
case "tap":
|
|
76668
|
-
guard args.count >= 5, let fx = Double(args[3]), let fy = Double(args[4]) else { fail(2, "tap needs fx fy") }
|
|
76669
|
-
raise()
|
|
76670
|
-
let f = frame(window)
|
|
76671
|
-
// The device screen fills the window below its title bar.
|
|
76672
|
-
let titleBar: CGFloat = 28
|
|
76673
|
-
let point = CGPoint(x: f.origin.x + CGFloat(fx) * f.width, y: f.origin.y + titleBar + CGFloat(fy) * (f.height - titleBar))
|
|
76674
|
-
post(CGEvent(mouseEventSource: nil, mouseType: .mouseMoved, mouseCursorPosition: point, mouseButton: .left))
|
|
76675
|
-
post(CGEvent(mouseEventSource: nil, mouseType: .leftMouseDown, mouseCursorPosition: point, mouseButton: .left))
|
|
76676
|
-
post(CGEvent(mouseEventSource: nil, mouseType: .leftMouseUp, mouseCursorPosition: point, mouseButton: .left))
|
|
76677
|
-
case "key":
|
|
76678
|
-
guard args.count >= 4, let code = UInt16(args[3]) else { fail(2, "key needs a keycode") }
|
|
76679
|
-
raise()
|
|
76680
|
-
var flags: CGEventFlags = []
|
|
76681
|
-
if args.contains("cmd") { flags.insert(.maskCommand) }
|
|
76682
|
-
if args.contains("shift") { flags.insert(.maskShift) }
|
|
76683
|
-
let down = CGEvent(keyboardEventSource: nil, virtualKey: code, keyDown: true), up = CGEvent(keyboardEventSource: nil, virtualKey: code, keyDown: false)
|
|
76684
|
-
down?.flags = flags; up?.flags = flags
|
|
76685
|
-
post(down); post(up)
|
|
76686
|
-
case "type":
|
|
76687
|
-
guard args.count >= 4, !args[3].isEmpty, args[3].utf16.count <= 500 else { fail(2, "type needs at most 500 characters") }
|
|
76688
|
-
let submit = args.count == 5 && args[4] == "submit"
|
|
76689
|
-
guard args[3].unicodeScalars.allSatisfy({ scalar in
|
|
76690
|
-
(scalar.value >= 32 && scalar.value != 127) || (scalar.value == 10 && submit)
|
|
76691
|
-
}) else { fail(2, "invalid type controls; newline needs submit") }
|
|
76692
|
-
raise()
|
|
76693
|
-
for scalar in args[3].unicodeScalars {
|
|
76694
|
-
var chars = Array(String(scalar).utf16)
|
|
76695
|
-
let down = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: true), up = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: false)
|
|
76696
|
-
down?.keyboardSetUnicodeString(stringLength: chars.count, unicodeString: &chars)
|
|
76697
|
-
up?.keyboardSetUnicodeString(stringLength: chars.count, unicodeString: &chars)
|
|
76698
|
-
post(down); post(up)
|
|
76699
|
-
}
|
|
76700
|
-
default: fail(2, "unknown command \\(command)")
|
|
76701
|
-
}
|
|
76702
|
-
` : await readFile56(new URL("./native/simtap.swift", import.meta.url), "utf8");
|
|
76703
|
-
const digest2 = createHash35("sha256").update(code).digest("hex");
|
|
76704
|
-
const saved = await readFile56(binary + ".sha256", "utf8").then(JSON.parse).catch(() => void 0);
|
|
76705
|
-
if (await stat32(binary).catch(() => void 0) && saved?.sourceSha === digest2) return binary;
|
|
76706
|
-
await mkdir34(dir, { recursive: true, mode: 448 });
|
|
76707
|
-
const temporary = path144.join(dir, `simtap.${randomUUID31()}`), source = temporary + ".swift";
|
|
76708
|
-
const sidecar = temporary + ".sha256";
|
|
76709
|
-
try {
|
|
76710
|
-
await writeFile11(source, code, { mode: 384, flag: "wx" });
|
|
76711
|
-
await exec25("/usr/bin/swiftc", ["-O", "-o", temporary, source], { timeout: 18e4 }).catch(() => {
|
|
76712
|
-
throw new BridgeError(409, "Couldn't build the simulator input helper (needs Xcode's swiftc).");
|
|
76713
|
-
});
|
|
76714
|
-
await chmod5(temporary, 448);
|
|
76715
|
-
const binarySha = createHash35("sha256").update(await readFile56(temporary)).digest("hex");
|
|
76716
|
-
await writeFile11(sidecar, JSON.stringify({ sourceSha: digest2, binarySha }), { mode: 384, flag: "wx" });
|
|
76717
|
-
await rename11(temporary, binary);
|
|
76718
|
-
await rename11(sidecar, binary + ".sha256");
|
|
76719
|
-
} finally {
|
|
76720
|
-
await Promise.all([source, temporary, sidecar].map((file4) => unlink9(file4).catch(() => void 0)));
|
|
76721
|
-
}
|
|
76722
|
-
return binary;
|
|
76723
|
-
}
|
|
76724
|
-
function simtap(name, ...args) {
|
|
76725
|
-
const task2 = inputQueue.catch(() => {
|
|
76726
|
-
}).then(() => executeSimtap(name, ...args));
|
|
76727
|
-
inputQueue = task2;
|
|
76728
|
-
return task2;
|
|
76729
|
-
}
|
|
76730
|
-
async function verifiedHelper() {
|
|
76731
|
-
const binary = await helper();
|
|
76732
|
-
const saved = await readFile56(binary + ".sha256", "utf8").then(JSON.parse).catch(() => void 0);
|
|
76733
|
-
const binarySha = createHash35("sha256").update(await readFile56(binary)).digest("hex");
|
|
76734
|
-
if (!saved || saved.binarySha !== binarySha) throw new BridgeError(409, "Simulator input helper integrity check failed.");
|
|
76735
|
-
return binary;
|
|
76736
|
-
}
|
|
76737
|
-
async function executeSimtap(name, ...args) {
|
|
76738
|
-
const binary = await verifiedHelper();
|
|
76739
|
-
try {
|
|
76740
|
-
await exec25(binary, [name, ...args], { timeout: 6e4 });
|
|
76741
|
-
} catch (error62) {
|
|
76742
|
-
const failure2 = error62;
|
|
76743
|
-
const message = String(failure2?.stderr ?? failure2?.message ?? "");
|
|
76744
|
-
if (/accessibility/.test(message)) {
|
|
76745
|
-
await promptAccessibility(binary, false);
|
|
76746
|
-
throw new BridgeError(403, accessibilityHelp(binary), { code: "simulator-accessibility", helper: binary });
|
|
76747
|
-
}
|
|
76748
|
-
if (/no window/.test(message)) throw new BridgeError(409, "That simulator has no window on screen.");
|
|
76749
|
-
if (/not running/.test(message)) throw new BridgeError(409, "The Simulator app is not running.");
|
|
76750
|
-
throw new BridgeError(409, `The simulator did not take that: ${message.slice(0, 160) || "unknown error"}`);
|
|
76751
|
-
}
|
|
76752
|
-
}
|
|
76753
|
-
function accessibilityHelp(binary) {
|
|
76754
|
-
return `Touches and keys need Accessibility for Phren's simulator helper. On the Mac, open System Settings \u2192 Privacy & Security \u2192 Accessibility and switch on simtap. If it isn't listed, click +, press \u2318\u21E7G, paste ${binary} and click Open.`;
|
|
76755
|
-
}
|
|
76756
|
-
async function promptAccessibility(binary, force) {
|
|
76757
|
-
if (prompted && !force) return false;
|
|
76758
|
-
prompted = true;
|
|
76759
|
-
return exec25(binary, ["-", "prompt"], { timeout: 15e3 }).then(() => true, () => false);
|
|
76760
|
-
}
|
|
76761
|
-
async function simulatorAct(udid, request10) {
|
|
76762
|
-
if (!UDID.test(udid)) throw new BridgeError(400, "Invalid simulator identifier.");
|
|
76763
|
-
if (!["boot", "shutdown", "launch", "openurl", "home", "lock", "type", "tap", "screenshot-ready", "accessibility-settings"].includes(request10.action)) throw new BridgeError(400, "Unknown simulator action.");
|
|
76764
|
-
if (process.platform !== "darwin") throw new BridgeError(404, "Simulators run on macOS only.");
|
|
76765
|
-
const simctl = (...args) => exec25("/usr/bin/xcrun", ["simctl", ...args], { timeout: 3e4 }).catch(() => {
|
|
76766
|
-
throw new BridgeError(409, `simctl ${args[0]} failed for that simulator.`);
|
|
76767
|
-
});
|
|
76768
|
-
switch (request10.action) {
|
|
76769
|
-
case "boot":
|
|
76770
|
-
await simctl("boot", udid);
|
|
76771
|
-
break;
|
|
76772
|
-
case "shutdown":
|
|
76773
|
-
await simctl("shutdown", udid);
|
|
76774
|
-
break;
|
|
76775
|
-
case "launch":
|
|
76776
|
-
if (typeof request10.bundleId !== "string" || !/^[A-Za-z0-9][A-Za-z0-9.-]{2,199}$/.test(request10.bundleId)) throw new BridgeError(400, "Invalid bundle identifier.");
|
|
76777
|
-
await simctl("launch", udid, request10.bundleId);
|
|
76778
|
-
break;
|
|
76779
|
-
case "openurl":
|
|
76780
|
-
if (typeof request10.url !== "string" || !/^[a-z][a-z0-9+.-]*:/i.test(request10.url) || request10.url.length > 2048) throw new BridgeError(400, "Invalid URL.");
|
|
76781
|
-
await simctl("openurl", udid, request10.url);
|
|
76782
|
-
break;
|
|
76783
|
-
case "home":
|
|
76784
|
-
await simtap(await deviceName(udid), "key", KEY_H, "cmd", "shift");
|
|
76785
|
-
break;
|
|
76786
|
-
case "lock":
|
|
76787
|
-
await simtap(await deviceName(udid), "key", KEY_L, "cmd");
|
|
76788
|
-
break;
|
|
76789
|
-
case "type":
|
|
76790
|
-
if (typeof request10.text !== "string" || !request10.text || request10.text.length > 500 || /[\x00-\x09\x0b-\x1f\x7f]/.test(request10.text) || request10.text.includes("\n") && request10.submit !== true || request10.submit !== void 0 && typeof request10.submit !== "boolean") throw new BridgeError(400, "Type at most 500 characters; newlines require submit: true and other control characters are forbidden.");
|
|
76791
|
-
await simtap(await deviceName(udid), "type", request10.text, ...request10.submit === true ? ["submit"] : []);
|
|
76792
|
-
break;
|
|
76793
|
-
case "tap": {
|
|
76794
|
-
const { x: x2, y } = request10;
|
|
76795
|
-
if (![x2, y].every((v2) => typeof v2 === "number" && v2 >= 0 && v2 <= 1)) throw new BridgeError(400, "Tap outside the screen.");
|
|
76796
|
-
await simtap(await deviceName(udid), "tap", String(x2), String(y));
|
|
76797
|
-
break;
|
|
76798
|
-
}
|
|
76799
|
-
case "screenshot-ready":
|
|
76800
|
-
break;
|
|
76801
|
-
case "accessibility-settings": {
|
|
76802
|
-
const binary = await verifiedHelper();
|
|
76803
|
-
const trusted = await promptAccessibility(binary, true);
|
|
76804
|
-
await exec25("/usr/bin/open", [ACCESSIBILITY_PANE], { timeout: 15e3 }).catch(() => {
|
|
76805
|
-
throw new BridgeError(409, "Couldn't open System Settings on the Mac.");
|
|
76806
|
-
});
|
|
76807
|
-
return { ok: true, trusted, helper: binary };
|
|
76808
|
-
}
|
|
76809
|
-
default:
|
|
76810
|
-
throw new BridgeError(400, "Unknown simulator action.");
|
|
76811
|
-
}
|
|
76812
|
-
return { ok: true };
|
|
76813
|
-
}
|
|
76814
|
-
async function deviceName(udid) {
|
|
76815
|
-
const device = (await bootedSimulators()).find((d) => d.udid === udid.toUpperCase());
|
|
76816
|
-
if (!device) throw new BridgeError(409, "That simulator is not booted.");
|
|
76817
|
-
return String(device.name);
|
|
76818
|
-
}
|
|
76819
|
-
async function simulatorApps(udid) {
|
|
76820
|
-
if (!UDID.test(udid)) throw new BridgeError(400, "Invalid simulator identifier.");
|
|
76821
|
-
if (process.platform !== "darwin") return [];
|
|
76822
|
-
const { stdout } = await exec25("/usr/bin/xcrun", ["simctl", "listapps", udid], { timeout: 15e3, maxBuffer: 4194304 }).catch(() => ({ stdout: "" }));
|
|
76823
|
-
const apps = [];
|
|
76824
|
-
const blocks = stdout.split(/\n(?=\s{4}"[^"]+" =\s+\{)/);
|
|
76825
|
-
for (const block of blocks) {
|
|
76826
|
-
const id2 = /CFBundleIdentifier = "?([^";\n]+)"?;/.exec(block)?.[1], name = /CFBundleDisplayName = "?([^";\n]+)"?;/.exec(block)?.[1];
|
|
76827
|
-
const type = /ApplicationType = "?([^";\n]+)"?;/.exec(block)?.[1];
|
|
76828
|
-
if (id2 && name && type === "User" && !/\.xctrunner$/.test(id2)) apps.push({ bundleId: id2, name });
|
|
76829
|
-
}
|
|
76830
|
-
return apps.sort((a, b) => String(a.name).localeCompare(String(b.name))).slice(0, 100);
|
|
76831
|
-
}
|
|
76832
|
-
var exec25, UDID, building, inputQueue, prompted, ACCESSIBILITY_PANE, KEY_H, KEY_L;
|
|
76833
|
-
var init_simulators = __esm({
|
|
76834
|
-
"src/bridge/simulators.ts"() {
|
|
76835
|
-
"use strict";
|
|
76836
|
-
init_protocol();
|
|
76837
|
-
exec25 = promisify28(execFile30);
|
|
76838
|
-
UDID = /^[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}$/i;
|
|
76839
|
-
inputQueue = Promise.resolve();
|
|
76840
|
-
prompted = false;
|
|
76841
|
-
ACCESSIBILITY_PANE = "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility";
|
|
76842
|
-
KEY_H = "4";
|
|
76843
|
-
KEY_L = "37";
|
|
76844
|
-
}
|
|
76845
|
-
});
|
|
76846
|
-
|
|
76847
77212
|
// src/bridge/steps.ts
|
|
76848
77213
|
import { homedir as homedir21, tmpdir as tmpdir8 } from "node:os";
|
|
76849
77214
|
import path145 from "node:path";
|
|
@@ -77161,7 +77526,7 @@ async function confirmed(deps2, seen) {
|
|
|
77161
77526
|
}
|
|
77162
77527
|
async function nativeRename(deps2, server, workspace, tab, pane, label2) {
|
|
77163
77528
|
const harness = typeof pane.agent === "string" && pane.agent ? pane.agent : "none";
|
|
77164
|
-
const skip = (mechanism2,
|
|
77529
|
+
const skip = (mechanism2, reason3) => ({ harness, mechanism: mechanism2, applied: false, reason: reason3 });
|
|
77165
77530
|
if (!["claude", "codex", "opencode"].includes(harness)) return skip("none", "This harness has no remote rename.");
|
|
77166
77531
|
const paneId = String(pane.pane_id), status = String(pane.agent_status);
|
|
77167
77532
|
let session;
|
|
@@ -77403,12 +77768,12 @@ async function readSets(info) {
|
|
|
77403
77768
|
readSetName(),
|
|
77404
77769
|
readComputers({ local: { id: info.computer.id } })
|
|
77405
77770
|
]);
|
|
77406
|
-
const answers = await askPeers(peers, await localCaller());
|
|
77771
|
+
const answers = await askPeers(peers, await localCaller(), void 0, SETS_PEER_TIMEOUT_MS);
|
|
77407
77772
|
const indirect = new Set(indirectMembers(answers, [info.computer.name, ...info.computer.aliases ?? [], ...localNames()]).map(computerLabel));
|
|
77408
77773
|
const reportedComputers = (await Promise.all(answers.map(async (answer2) => {
|
|
77409
77774
|
if (!answer2.ok || answer2.knowsCaller === false || !answer2.peers?.some((name) => indirect.has(computerLabel(name)))) return [];
|
|
77410
77775
|
try {
|
|
77411
|
-
const directory = await peerRequest(answer2.peer, "/v1/computers", void 0,
|
|
77776
|
+
const directory = await peerRequest(answer2.peer, "/v1/computers", void 0, 2 * SETS_PEER_TIMEOUT_MS);
|
|
77412
77777
|
return (Array.isArray(directory.computers) ? directory.computers.slice(0, 64) : []).flatMap((value2) => {
|
|
77413
77778
|
const row = object2(value2);
|
|
77414
77779
|
return typeof row.id === "string" && typeof row.name === "string" ? [{
|
|
@@ -77464,7 +77829,7 @@ async function linkSetMember(data, link = linkComputer) {
|
|
|
77464
77829
|
linking = void 0;
|
|
77465
77830
|
}
|
|
77466
77831
|
}
|
|
77467
|
-
var callerSchema, setNameValue, linkInput, linking;
|
|
77832
|
+
var callerSchema, SETS_PEER_TIMEOUT_MS, setNameValue, linkInput, linking;
|
|
77468
77833
|
var init_conductor_sets = __esm({
|
|
77469
77834
|
"src/bridge/conductor-sets.ts"() {
|
|
77470
77835
|
"use strict";
|
|
@@ -77479,6 +77844,7 @@ var init_conductor_sets = __esm({
|
|
|
77479
77844
|
init_protocol();
|
|
77480
77845
|
init_server_launch();
|
|
77481
77846
|
callerSchema = external_exports.object({ name: external_exports.string().max(253).optional(), hostKey: external_exports.string().max(512).optional() });
|
|
77847
|
+
SETS_PEER_TIMEOUT_MS = 4e3;
|
|
77482
77848
|
setNameValue = external_exports.string().trim().min(1).max(60).refine((t) => !/[\x00-\x1f\x7f]/.test(t)).nullable();
|
|
77483
77849
|
linkInput = external_exports.object({ name: external_exports.string().trim().regex(/^[A-Za-z0-9_][A-Za-z0-9_.-]{0,252}$/, "A computer name or ssh host.") }).strict();
|
|
77484
77850
|
}
|
|
@@ -78146,8 +78512,8 @@ function createRouteHandler(ctx) {
|
|
|
78146
78512
|
let remote = [];
|
|
78147
78513
|
let peerError;
|
|
78148
78514
|
if (url2.searchParams.get("remote") !== "0") {
|
|
78149
|
-
const { peers, peerError:
|
|
78150
|
-
peerError =
|
|
78515
|
+
const { peers, peerError: reason3 } = await optionalHookPeers();
|
|
78516
|
+
peerError = reason3;
|
|
78151
78517
|
remote = await remoteChildren(
|
|
78152
78518
|
{ provider: target2.source, session: target2.session, computer: computerID2 },
|
|
78153
78519
|
// A worker whose turn finished shows as a completed lead.
|
|
@@ -78600,6 +78966,7 @@ var init_server_routes = __esm({
|
|
|
78600
78966
|
queuedHandOff: true,
|
|
78601
78967
|
approvalPush: "direct-apns",
|
|
78602
78968
|
simulators: process.platform === "darwin",
|
|
78969
|
+
simulatorStream: process.platform === "darwin",
|
|
78603
78970
|
code: true,
|
|
78604
78971
|
codeFiles: true,
|
|
78605
78972
|
overviewStream: true,
|
|
@@ -79083,9 +79450,9 @@ function streamCloseReason(error62) {
|
|
|
79083
79450
|
if (error62 instanceof BridgeError && error62.status === 409) return "The conversation changed; refresh";
|
|
79084
79451
|
const code = error62?.code;
|
|
79085
79452
|
const first = (error62 instanceof Error ? error62.message : String(error62)).split("\n")[0].replace(/[\x00-\x1f\x7f]/g, " ").replace(/(?:~|\/)[^\s'",:]*\/([^\s'",:/]+)/g, "$1").trim();
|
|
79086
|
-
let
|
|
79087
|
-
while (Buffer.byteLength(
|
|
79088
|
-
return
|
|
79453
|
+
let reason3 = error62 instanceof BridgeError ? first : `Stream failed: ${typeof code === "string" && !first.startsWith(code) ? `${code} ` : ""}${first || "unknown error"}`;
|
|
79454
|
+
while (Buffer.byteLength(reason3) > 123) reason3 = reason3.slice(0, -1);
|
|
79455
|
+
return reason3;
|
|
79089
79456
|
}
|
|
79090
79457
|
function transcriptStreams(ctx) {
|
|
79091
79458
|
const { modules, agentHooks, codexQuestions, sideQuestions, settingsSwitcher, info, activeCapabilities } = ctx;
|
|
@@ -79229,10 +79596,10 @@ function transcriptStreams(ctx) {
|
|
|
79229
79596
|
}
|
|
79230
79597
|
}
|
|
79231
79598
|
if (deliveryFrames) {
|
|
79232
|
-
for (const { deliveryId, state, reason:
|
|
79599
|
+
for (const { deliveryId, state, reason: reason3 } of agentHooks.deliveries.forPane(target2)) {
|
|
79233
79600
|
if (sentDelivery.get(deliveryId) === state) continue;
|
|
79234
79601
|
sentDelivery.set(deliveryId, state);
|
|
79235
|
-
send(client, { type: "delivery", ...conversation, deliveryId, state, ...
|
|
79602
|
+
send(client, { type: "delivery", ...conversation, deliveryId, state, ...reason3 ? { reason: reason3 } : {} });
|
|
79236
79603
|
}
|
|
79237
79604
|
}
|
|
79238
79605
|
first = false;
|
|
@@ -79244,10 +79611,10 @@ function transcriptStreams(ctx) {
|
|
|
79244
79611
|
send(client, { ...page, type: "older", ...conversation });
|
|
79245
79612
|
}
|
|
79246
79613
|
} catch (error62) {
|
|
79247
|
-
const
|
|
79248
|
-
if (!(error62 instanceof BridgeError && error62.status === 409)) logger.warn("stream", `${url2.pathname} closed: ${
|
|
79614
|
+
const reason3 = streamCloseReason(error62);
|
|
79615
|
+
if (!(error62 instanceof BridgeError && error62.status === 409)) logger.warn("stream", `${url2.pathname} closed: ${reason3}`);
|
|
79249
79616
|
stop();
|
|
79250
|
-
client.close(1011,
|
|
79617
|
+
client.close(1011, reason3);
|
|
79251
79618
|
} finally {
|
|
79252
79619
|
busy2 = false;
|
|
79253
79620
|
if (pending3.length) void tick();
|
|
@@ -79382,10 +79749,10 @@ function overviewStream(options) {
|
|
|
79382
79749
|
first = false;
|
|
79383
79750
|
if (at2 - sentAt >= heartbeatMs && send2(client, { type: "heartbeat", phren: options.info() })) sentAt = at2;
|
|
79384
79751
|
} catch (error62) {
|
|
79385
|
-
const
|
|
79386
|
-
logger.warn("stream", `/v1/overview closed: ${
|
|
79752
|
+
const reason3 = streamCloseReason(error62);
|
|
79753
|
+
logger.warn("stream", `/v1/overview closed: ${reason3}`);
|
|
79387
79754
|
stop();
|
|
79388
|
-
client.close(1011,
|
|
79755
|
+
client.close(1011, reason3);
|
|
79389
79756
|
} finally {
|
|
79390
79757
|
busy2 = false;
|
|
79391
79758
|
if (!closed) collectResources2();
|
|
@@ -79815,7 +80182,7 @@ async function serve(version2, options = {}) {
|
|
|
79815
80182
|
http.on("upgrade", (request10, socket, head) => {
|
|
79816
80183
|
try {
|
|
79817
80184
|
const url2 = new URL(request10.url || "/", "http://phren.local");
|
|
79818
|
-
if (!["/v1/transcripts", "/v1/status", "/v1/overview", "/v1/speech/transcribe", "/v1/speech/live"].includes(url2.pathname) || url2.origin !== "http://phren.local") {
|
|
80185
|
+
if (!["/v1/transcripts", "/v1/status", "/v1/overview", "/v1/speech/transcribe", "/v1/speech/live", "/v1/simulators/stream"].includes(url2.pathname) || url2.origin !== "http://phren.local") {
|
|
79819
80186
|
socket.destroy();
|
|
79820
80187
|
return;
|
|
79821
80188
|
}
|
|
@@ -79837,6 +80204,10 @@ async function serve(version2, options = {}) {
|
|
|
79837
80204
|
void relayTranscription(client, url2.searchParams).catch(() => failRelay(client));
|
|
79838
80205
|
return;
|
|
79839
80206
|
}
|
|
80207
|
+
if (url2.pathname === "/v1/simulators/stream") {
|
|
80208
|
+
void streamSimulator(client, url2.searchParams).catch(() => client.close(1011, "Simulator stream unavailable"));
|
|
80209
|
+
return;
|
|
80210
|
+
}
|
|
79840
80211
|
if (url2.pathname === "/v1/speech/live") {
|
|
79841
80212
|
void relayLiveSpeech(client, url2.searchParams).catch(() => client.close(1011, "Spoken replies unavailable"));
|
|
79842
80213
|
return;
|
|
@@ -79982,6 +80353,7 @@ var init_server = __esm({
|
|
|
79982
80353
|
init_registry();
|
|
79983
80354
|
init_wrapper();
|
|
79984
80355
|
init_speech_live();
|
|
80356
|
+
init_simulator_stream();
|
|
79985
80357
|
init_speech_transcribe();
|
|
79986
80358
|
init_activity2();
|
|
79987
80359
|
init_metrics();
|
|
@@ -80448,7 +80820,7 @@ async function main() {
|
|
|
80448
80820
|
return askpass2(args[1]);
|
|
80449
80821
|
}
|
|
80450
80822
|
const { runBridge: runBridge2 } = await Promise.resolve().then(() => (init_command(), command_exports));
|
|
80451
|
-
return runBridge2(args, "0.3.
|
|
80823
|
+
return runBridge2(args, "0.3.58");
|
|
80452
80824
|
}
|
|
80453
80825
|
main().then((code) => {
|
|
80454
80826
|
process.exitCode = code;
|