@phren/cli 0.3.20 → 0.3.22
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/agent-hooks.d.ts +22 -19
- package/dist/bridge/agent-hooks.js +49 -33
- package/dist/bridge/approval-summary.d.ts +4 -0
- package/dist/bridge/approval-summary.js +12 -1
- package/dist/bridge/code-note.d.ts +1 -0
- package/dist/bridge/code-note.js +2 -2
- package/dist/bridge/codex-binary.d.ts +5 -0
- package/dist/bridge/codex-binary.js +7 -0
- package/dist/bridge/dispatch-command.js +1 -1
- package/dist/bridge/dispatch-returns.d.ts +3 -2
- package/dist/bridge/dispatch-returns.js +27 -11
- package/dist/bridge/dispatch.d.ts +4 -0
- package/dist/bridge/dispatch.js +5 -3
- package/dist/bridge/folder-trust.d.ts +13 -3
- package/dist/bridge/folder-trust.js +42 -4
- package/dist/bridge/hand-off.js +2 -1
- package/dist/bridge/herdr.js +6 -5
- package/dist/bridge/launch-brief.d.ts +3 -1
- package/dist/bridge/launch-brief.js +3 -1
- package/dist/bridge/memory-store.d.ts +7 -0
- package/dist/bridge/memory-store.js +41 -2
- package/dist/bridge/schedule-format.d.ts +1 -1
- package/dist/bridge/schedule-format.js +1 -1
- package/dist/bridge/schedule-launch.js +5 -0
- package/dist/bridge/schedule-watch.d.ts +5 -2
- package/dist/bridge/schedule-watch.js +59 -20
- package/dist/bridge/server-launch.d.ts +6 -0
- package/dist/bridge/server-launch.js +59 -11
- package/dist/bridge/server-pane-routes.js +20 -13
- package/dist/bridge/server-routes.d.ts +1 -0
- package/dist/bridge/server-routes.js +1 -1
- package/dist/bridge/server-stream.js +12 -0
- package/dist/bridge/server.js +2 -2
- package/dist/bridge/session-activity.d.ts +6 -0
- package/dist/bridge/session-activity.js +16 -0
- package/dist/bridge/settings-switch.d.ts +7 -0
- package/dist/bridge/settings-switch.js +15 -0
- package/dist/bridge/speech-transcribe.d.ts +8 -1
- package/dist/bridge/speech-transcribe.js +18 -3
- package/dist/bridge/transcript-claude.js +39 -10
- package/dist/bridge/worker-close.js +3 -2
- package/dist/bridge/worker-unfinished.d.ts +8 -2
- package/dist/bridge/worker-unfinished.js +57 -24
- package/dist/bridge-hook.mjs +520 -278
- package/dist/cli-registry.js +1 -1
- package/dist/data/tasks.js +6 -1
- package/dist/home-paths.d.ts +2 -0
- package/dist/home-paths.js +4 -0
- package/dist/modules/registry.js +1 -1
- package/dist/test-global-setup.js +2 -1
- package/dist/test-sandbox.d.ts +15 -0
- package/dist/test-sandbox.js +36 -0
- package/package.json +1 -1
- package/starter/global/skills/conductor/SKILL.md +2 -1
package/dist/bridge-hook.mjs
CHANGED
|
@@ -23733,6 +23733,9 @@ function claudeConfigDir(env = process.env) {
|
|
|
23733
23733
|
function codexHome(env = process.env) {
|
|
23734
23734
|
return configuredDir(env.CODEX_HOME, env, ".codex");
|
|
23735
23735
|
}
|
|
23736
|
+
function copilotHome(env = process.env) {
|
|
23737
|
+
return configuredDir(env.COPILOT_HOME, env, ".copilot");
|
|
23738
|
+
}
|
|
23736
23739
|
var init_home_paths = __esm({
|
|
23737
23740
|
"src/home-paths.ts"() {
|
|
23738
23741
|
"use strict";
|
|
@@ -25349,7 +25352,7 @@ var init_package_metadata = __esm({
|
|
|
25349
25352
|
__dirname = path15.dirname(fileURLToPath2(import.meta.url));
|
|
25350
25353
|
ROOT = path15.join(__dirname, "..");
|
|
25351
25354
|
PACKAGE_JSON_PATH = path15.join(ROOT, "package.json");
|
|
25352
|
-
BUNDLED_VERSION = true ? "0.3.
|
|
25355
|
+
BUNDLED_VERSION = true ? "0.3.22" : "0.0.0";
|
|
25353
25356
|
PACKAGE_JSON = readPackageJson();
|
|
25354
25357
|
PACKAGE_NAME = PACKAGE_JSON.name || "phren";
|
|
25355
25358
|
VERSION = PACKAGE_JSON.version || BUNDLED_VERSION;
|
|
@@ -25373,6 +25376,7 @@ var init_terminal_text = __esm({
|
|
|
25373
25376
|
import { accessSync, closeSync, constants, openSync, readSync, statSync as statSync9 } from "node:fs";
|
|
25374
25377
|
import path19 from "node:path";
|
|
25375
25378
|
function codexExecutable(env = process.env) {
|
|
25379
|
+
if (/^(?:0|off|false|no)$/i.test(env.PHREN_CODEX_BINARY ?? "")) return CODEX_OFF;
|
|
25376
25380
|
if (process.platform === "win32") return "codex";
|
|
25377
25381
|
for (const directory of (env.PATH ?? "").split(path19.delimiter)) {
|
|
25378
25382
|
if (!path19.isAbsolute(directory)) continue;
|
|
@@ -25409,9 +25413,11 @@ function phrenWrapperTarget(file3) {
|
|
|
25409
25413
|
const target = match?.[1].replace(/'\\''/g, "'");
|
|
25410
25414
|
return target && path19.isAbsolute(target) ? target : "";
|
|
25411
25415
|
}
|
|
25416
|
+
var CODEX_OFF;
|
|
25412
25417
|
var init_codex_binary = __esm({
|
|
25413
25418
|
"src/bridge/codex-binary.ts"() {
|
|
25414
25419
|
"use strict";
|
|
25420
|
+
CODEX_OFF = "/nonexistent/phren-codex-off";
|
|
25415
25421
|
}
|
|
25416
25422
|
});
|
|
25417
25423
|
|
|
@@ -27695,6 +27701,10 @@ async function claudeChildAgents(file3, session) {
|
|
|
27695
27701
|
cached3.relations = await withClaudeChildModels(cached3.relations);
|
|
27696
27702
|
return cached3.relations;
|
|
27697
27703
|
}
|
|
27704
|
+
const rows = cached3?.signature === signature && cached3.rows ? cached3.rows : await claudeParentRows(file3);
|
|
27705
|
+
return claudeChildRelations(file3, session, signature, rows);
|
|
27706
|
+
}
|
|
27707
|
+
async function claudeParentRows(file3) {
|
|
27698
27708
|
const launches = /* @__PURE__ */ new Map();
|
|
27699
27709
|
const stops = /* @__PURE__ */ new Map();
|
|
27700
27710
|
const skills = /* @__PURE__ */ new Set();
|
|
@@ -27760,14 +27770,21 @@ async function claudeChildAgents(file3, session) {
|
|
|
27760
27770
|
if (previous && ["completed", "failed", "cancelled", "canceled", "killed", "stopped"].includes(taskStatus ?? "")) previous.state = "completed";
|
|
27761
27771
|
}
|
|
27762
27772
|
}
|
|
27763
|
-
|
|
27764
|
-
const from =
|
|
27765
|
-
const
|
|
27766
|
-
|
|
27773
|
+
for (const match of content.includes("<teammate-message") ? content.matchAll(/<teammate-message teammate_id="([A-Za-z0-9][A-Za-z0-9_-]{0,63})"[^>]*>([\s\S]*?)<\/teammate-message>/g) : []) {
|
|
27774
|
+
const [, from, body2] = match;
|
|
27775
|
+
const type = /"type":"([a-z_]+)"/.exec(body2)?.[1];
|
|
27776
|
+
const ended = from === "system" && type === "teammate_terminated" ? /"message":"([A-Za-z0-9][A-Za-z0-9_-]{0,63}) has shut down/.exec(body2)?.[1] : void 0;
|
|
27777
|
+
const teammate = teammates.get(ended ?? from);
|
|
27778
|
+
if (teammate) teammate.state = ended || type === "idle_notification" || type === "shutdown_approved" ? "completed" : "running";
|
|
27767
27779
|
}
|
|
27768
27780
|
} catch {
|
|
27769
27781
|
}
|
|
27770
27782
|
}
|
|
27783
|
+
return { launches, skills, workflows, teammates };
|
|
27784
|
+
}
|
|
27785
|
+
async function claudeChildRelations(file3, session, signature, rows) {
|
|
27786
|
+
const kept = copyRows(rows);
|
|
27787
|
+
const { launches, workflows, teammates } = copyRows(rows);
|
|
27771
27788
|
const relations = [];
|
|
27772
27789
|
let awaiting = false, live = false;
|
|
27773
27790
|
const root = await realpath3(path32.join(path32.dirname(file3), session, "subagents")).catch(() => void 0);
|
|
@@ -27777,7 +27794,7 @@ async function claudeChildAgents(file3, session) {
|
|
|
27777
27794
|
if (launch2.state === "running") awaiting = true;
|
|
27778
27795
|
continue;
|
|
27779
27796
|
}
|
|
27780
|
-
if (
|
|
27797
|
+
if (launch2.state === "running") {
|
|
27781
27798
|
if (await claudeSkillFinished(childFile).catch(() => false)) launch2.state = "completed";
|
|
27782
27799
|
else live = true;
|
|
27783
27800
|
}
|
|
@@ -27811,6 +27828,10 @@ async function claudeChildAgents(file3, session) {
|
|
|
27811
27828
|
if (launch2.state === "running") awaiting = true;
|
|
27812
27829
|
continue;
|
|
27813
27830
|
}
|
|
27831
|
+
if (launch2.state === "running") {
|
|
27832
|
+
if (await claudeSkillFinished(childFile).catch(() => false)) launch2.state = "completed";
|
|
27833
|
+
else live = true;
|
|
27834
|
+
}
|
|
27814
27835
|
const meta3 = await readFile12(childFile.slice(0, -".jsonl".length) + ".meta.json", "utf8").then((v) => object2(JSON.parse(v))).catch(() => ({}));
|
|
27815
27836
|
const model = await claudeChildModel(childFile).catch(() => void 0) ?? (typeof meta3.model === "string" && meta3.model ? meta3.model.slice(0, 200) : void 0);
|
|
27816
27837
|
const checkout = await claudeChildCheckout(childFile).catch(() => ({}));
|
|
@@ -27837,7 +27858,7 @@ async function claudeChildAgents(file3, session) {
|
|
|
27837
27858
|
}
|
|
27838
27859
|
}
|
|
27839
27860
|
}
|
|
27840
|
-
claudeRelationCache.set(file3, { signature, relations, ...awaiting || live ? { recheckAt: Date.now() + (awaiting ? 2e3 : 5e3) } : {} });
|
|
27861
|
+
claudeRelationCache.set(file3, { signature, relations, ...awaiting || live ? { recheckAt: Date.now() + (awaiting ? 2e3 : 5e3), rows: kept } : {} });
|
|
27841
27862
|
while (claudeRelationCache.size > 64) claudeRelationCache.delete(claudeRelationCache.keys().next().value);
|
|
27842
27863
|
return relations;
|
|
27843
27864
|
}
|
|
@@ -28069,12 +28090,18 @@ function visibleClaudeEvent(raw, includeSidechain = false, queue3) {
|
|
|
28069
28090
|
if (Array.isArray(message.content)) return { ...raw, message: { ...message, content: objects(message.content).map((b) => ["text", "image", "tool_use", "tool_result"].includes(String(b.type)) ? b : isNarration(b) ? { type: "text", text: String(b.thinking), narration: true } : { type: "redacted" }) } };
|
|
28070
28091
|
return void 0;
|
|
28071
28092
|
}
|
|
28072
|
-
var claudeRelationCache, claudeChildModelCache, CLAUDE_SKILL_QUIET_MS, CLAUDE_KEYS, harnessPreamble, PASTED_CONTENT, HOOK_CONTEXT_LIMIT, SKILL_BODY, QUEUED_IMAGE_LABEL, QUEUED_IMAGE_LABELS, ATTACHED_FILES_FOOTER;
|
|
28093
|
+
var claudeRelationCache, copyRows, claudeChildModelCache, CLAUDE_SKILL_QUIET_MS, CLAUDE_KEYS, harnessPreamble, PASTED_CONTENT, HOOK_CONTEXT_LIMIT, SKILL_BODY, QUEUED_IMAGE_LABEL, QUEUED_IMAGE_LABELS, ATTACHED_FILES_FOOTER;
|
|
28073
28094
|
var init_transcript_claude = __esm({
|
|
28074
28095
|
"src/bridge/transcript-claude.ts"() {
|
|
28075
28096
|
"use strict";
|
|
28076
28097
|
init_protocol();
|
|
28077
28098
|
claudeRelationCache = /* @__PURE__ */ new Map();
|
|
28099
|
+
copyRows = (rows) => ({
|
|
28100
|
+
launches: new Map([...rows.launches].map(([id2, launch2]) => [id2, { ...launch2 }])),
|
|
28101
|
+
skills: new Set(rows.skills),
|
|
28102
|
+
workflows: new Map([...rows.workflows].map(([id2, workflow]) => [id2, { ...workflow }])),
|
|
28103
|
+
teammates: new Map([...rows.teammates].map(([name, launch2]) => [name, { ...launch2 }]))
|
|
28104
|
+
});
|
|
28078
28105
|
claudeChildModelCache = /* @__PURE__ */ new Map();
|
|
28079
28106
|
CLAUDE_SKILL_QUIET_MS = 30 * 60 * 1e3;
|
|
28080
28107
|
CLAUDE_KEYS = /* @__PURE__ */ new Set(["type", "uuid", "parentUuid", "timestamp", "message", "gitBranch", "cwd", "requestId", "isMeta", "isSidechain", "isCompactSummary", "phrenQueued", "phrenQueueKey", "phrenBackground", "phrenCompacted", "effort", "permissionMode"]);
|
|
@@ -29274,6 +29301,15 @@ function liveWork(record2, final, runningChildren = 0, now = Date.now()) {
|
|
|
29274
29301
|
const total = (awaitedShells(record2, final, now) ?? 0) + runningChildren;
|
|
29275
29302
|
return total || void 0;
|
|
29276
29303
|
}
|
|
29304
|
+
function runningTasks(record2, final, now = Date.now()) {
|
|
29305
|
+
const phase = record2 ? turnPhase(record2) : void 0, endless = final?.endless ?? 0;
|
|
29306
|
+
if (phase?.phase === "ended" && phase.background !== void 0) {
|
|
29307
|
+
if (!(now - Date.parse(phase.at) < BACKGROUND_STALE_MS)) return 0;
|
|
29308
|
+
return Math.max(0, backgroundLeft(phase.background, phase.at, final?.finishedTasks) - endless);
|
|
29309
|
+
}
|
|
29310
|
+
if (phase?.phase === "ended" && !(now - Date.parse(phase.at) < BACKGROUND_STALE_MS)) return 0;
|
|
29311
|
+
return final?.completed ? Math.max(0, (final.background ?? 0) - endless) : 0;
|
|
29312
|
+
}
|
|
29277
29313
|
async function liveBackground(record2, readFinal, now = Date.now()) {
|
|
29278
29314
|
if (!record2 || record2.source !== "claude" || !recordedBackground(record2, [], now)) return void 0;
|
|
29279
29315
|
const final = await readFinal("claude", record2.session).catch(() => void 0);
|
|
@@ -33344,10 +33380,10 @@ async function socketAccepts(socketPath2) {
|
|
|
33344
33380
|
}
|
|
33345
33381
|
return new Promise((resolve11) => {
|
|
33346
33382
|
const ws = new import_websocket.default(socketUrl(socketPath2), { perMessageDeflate: false });
|
|
33347
|
-
let
|
|
33383
|
+
let settled3 = false;
|
|
33348
33384
|
const finish = (ok) => {
|
|
33349
|
-
if (
|
|
33350
|
-
|
|
33385
|
+
if (settled3) return;
|
|
33386
|
+
settled3 = true;
|
|
33351
33387
|
ws.close();
|
|
33352
33388
|
resolve11(ok);
|
|
33353
33389
|
};
|
|
@@ -35117,10 +35153,10 @@ async function tmuxScroll(server, pane, lines) {
|
|
|
35117
35153
|
const target = pane ? toTmuxId(pane, "p") : await activeClientPane(server);
|
|
35118
35154
|
const key3 = `${server}\0${target}`;
|
|
35119
35155
|
const run2 = (scrollQueues.get(key3) ?? Promise.resolve()).then(() => scrollPane(server, target, lines), () => scrollPane(server, target, lines));
|
|
35120
|
-
const
|
|
35121
|
-
scrollQueues.set(key3,
|
|
35122
|
-
void
|
|
35123
|
-
if (scrollQueues.get(key3) ===
|
|
35156
|
+
const settled3 = run2.catch(() => void 0);
|
|
35157
|
+
scrollQueues.set(key3, settled3);
|
|
35158
|
+
void settled3.then(() => {
|
|
35159
|
+
if (scrollQueues.get(key3) === settled3) scrollQueues.delete(key3);
|
|
35124
35160
|
});
|
|
35125
35161
|
return run2;
|
|
35126
35162
|
}
|
|
@@ -35848,14 +35884,14 @@ async function resolveIdentity(server, pane, fresh) {
|
|
|
35848
35884
|
const owned = pane.agent === "codex" && !!codexServers.forPane(server, String(pane.pane_id))?.threadId;
|
|
35849
35885
|
if (pane.agent !== "copilot" && !owned && reported.kind === "id" && reported.agent === pane.agent && typeof reported.value === "string" && sessionId.safeParse(reported.value).success) {
|
|
35850
35886
|
countIdentity("reported");
|
|
35851
|
-
return { sessionId: reported.value };
|
|
35887
|
+
return { sessionId: reported.value, noTranscriptLogs: false };
|
|
35852
35888
|
}
|
|
35853
35889
|
const pids = await foregroundPids(server, pane);
|
|
35854
35890
|
const key3 = identityKey(server, pane, pids);
|
|
35855
35891
|
const cached3 = identities.get(key3);
|
|
35856
35892
|
if (!fresh && cached3 && Date.now() - cached3.at < IDENTITY_CACHE_MS) {
|
|
35857
35893
|
countIdentity("cached");
|
|
35858
|
-
return {
|
|
35894
|
+
return { ...await cached3.result, pids };
|
|
35859
35895
|
}
|
|
35860
35896
|
countIdentity(fresh ? "probe-fresh" : "probe");
|
|
35861
35897
|
const result = identityFromProcesses(server, pane, pids);
|
|
@@ -35866,12 +35902,12 @@ async function resolveIdentity(server, pane, fresh) {
|
|
|
35866
35902
|
}, () => {
|
|
35867
35903
|
});
|
|
35868
35904
|
identities.set(key3, entry2);
|
|
35869
|
-
return {
|
|
35905
|
+
return { ...await result, pids };
|
|
35870
35906
|
}
|
|
35871
35907
|
async function paneIdentity(server, pane, fresh = false) {
|
|
35872
35908
|
return (await resolveIdentity(server, pane, fresh)).sessionId;
|
|
35873
35909
|
}
|
|
35874
|
-
async function copilotForegroundSession(pids, home =
|
|
35910
|
+
async function copilotForegroundSession(pids, home = copilotHome2()) {
|
|
35875
35911
|
if (!pids.length) return void 0;
|
|
35876
35912
|
const folder = path41.join(home, "logs");
|
|
35877
35913
|
const names = await readdir10(folder).catch(() => []);
|
|
@@ -35927,7 +35963,7 @@ async function identityFromProcesses(server, pane, pids) {
|
|
|
35927
35963
|
}
|
|
35928
35964
|
if (pane.agent === "copilot") {
|
|
35929
35965
|
const current2 = await copilotForegroundSession(pids).catch(() => void 0);
|
|
35930
|
-
if (current2) return await stat11(path41.join(
|
|
35966
|
+
if (current2) return await stat11(path41.join(copilotHome2(), "session-state", current2, "events.jsonl")).then(() => ({ sessionId: current2, noTranscriptLogs: false }), () => ({ noTranscriptLogs: true }));
|
|
35931
35967
|
const reported = object2(pane.agent_session);
|
|
35932
35968
|
if (reported.kind === "id" && reported.agent === "copilot" && typeof reported.value === "string" && sessionId.safeParse(reported.value).success) return { sessionId: reported.value, noTranscriptLogs: false };
|
|
35933
35969
|
}
|
|
@@ -36014,8 +36050,7 @@ async function paneChatState(server, pane, options = {}) {
|
|
|
36014
36050
|
if (sessionId2 && options.tokenWhenIdentified === false) return { sessionId: sessionId2 };
|
|
36015
36051
|
const pids = identity.pids ?? await foregroundPids(server, pane);
|
|
36016
36052
|
const process2 = typeof pane.terminal_id === "string" && pids.length ? JSON.stringify([key3, pids[0]]) : void 0;
|
|
36017
|
-
const
|
|
36018
|
-
const starting = !sessionId2 && !!process2 && !!evidence && Date.now() - evidence.at < IDENTITY_CACHE_MS && (await evidence.result).noTranscriptLogs;
|
|
36053
|
+
const starting = !sessionId2 && !!process2 && identity.noTranscriptLogs;
|
|
36019
36054
|
let binding = startingBindings.get(key3);
|
|
36020
36055
|
if (process2) {
|
|
36021
36056
|
if (!binding || binding.process !== process2 || !sessionId2 && (!!binding.sessionId || binding.wasStarting !== starting)) {
|
|
@@ -36101,7 +36136,7 @@ async function trustedDirectory(pane) {
|
|
|
36101
36136
|
if (typeof cwd !== "string" || !path41.isAbsolute(cwd)) throw new BridgeError(409, "This pane has no project folder.");
|
|
36102
36137
|
return realpath6(cwd);
|
|
36103
36138
|
}
|
|
36104
|
-
var terminal, exec5, optionalReadFailures, SERVER_LIST_REUSE_MS, serverList, knownServers, SNAPSHOT_SHARE_MS, sharedSnapshots, inFlightSnapshots, IDENTITY_CACHE_MS, identities, identityKey,
|
|
36139
|
+
var terminal, exec5, optionalReadFailures, SERVER_LIST_REUSE_MS, serverList, knownServers, SNAPSHOT_SHARE_MS, sharedSnapshots, inFlightSnapshots, IDENTITY_CACHE_MS, identities, identityKey, copilotHome2, rolloutIds, paneCwd, startingKey, startingBindings, startingPaneKey, startingToken, sharedIdentities;
|
|
36105
36140
|
var init_herdr = __esm({
|
|
36106
36141
|
"src/bridge/herdr.ts"() {
|
|
36107
36142
|
"use strict";
|
|
@@ -36126,7 +36161,7 @@ var init_herdr = __esm({
|
|
|
36126
36161
|
IDENTITY_CACHE_MS = intervalFromEnv("PHREN_IDENTITY_CACHE_MS", 2e3);
|
|
36127
36162
|
identities = /* @__PURE__ */ new Map();
|
|
36128
36163
|
identityKey = (server, pane, pids) => JSON.stringify([server, pane.pane_id, pane.terminal_id, pids, pane.agent]);
|
|
36129
|
-
|
|
36164
|
+
copilotHome2 = () => process.env.COPILOT_HOME || path41.join(homedir9(), ".copilot");
|
|
36130
36165
|
rolloutIds = (files) => files.flatMap((file3) => /rollout-.*-([a-f0-9-]{36})\.jsonl$/i.exec(file3)?.[1] ?? []);
|
|
36131
36166
|
paneCwd = (pane) => pane.foreground_cwd || pane.cwd;
|
|
36132
36167
|
startingKey = randomBytes2(32);
|
|
@@ -37830,6 +37865,7 @@ var BUILTIN_MODULES = [
|
|
|
37830
37865
|
"transcribe",
|
|
37831
37866
|
"promptOnce",
|
|
37832
37867
|
"promptStatus",
|
|
37868
|
+
"deliveryFrames",
|
|
37833
37869
|
"resources",
|
|
37834
37870
|
"sessionRename",
|
|
37835
37871
|
"sudo",
|
|
@@ -39369,10 +39405,10 @@ function decodeEntities(text4) {
|
|
|
39369
39405
|
}
|
|
39370
39406
|
function probe(port, host) {
|
|
39371
39407
|
return new Promise((resolve11) => {
|
|
39372
|
-
let
|
|
39408
|
+
let settled3 = false;
|
|
39373
39409
|
const finish = (value2) => {
|
|
39374
|
-
if (!
|
|
39375
|
-
|
|
39410
|
+
if (!settled3) {
|
|
39411
|
+
settled3 = true;
|
|
39376
39412
|
resolve11(value2);
|
|
39377
39413
|
}
|
|
39378
39414
|
};
|
|
@@ -40257,17 +40293,42 @@ async function ensureCodexDirTrusted(dir, env = process.env) {
|
|
|
40257
40293
|
}
|
|
40258
40294
|
throw new Error("config.toml kept changing while it was being updated");
|
|
40259
40295
|
}
|
|
40296
|
+
async function ensureCopilotFolderTrusted(dir, env = process.env) {
|
|
40297
|
+
const directory = copilotHome(env);
|
|
40298
|
+
const configured = path47.join(directory, "settings.json");
|
|
40299
|
+
const file3 = await realpath8(configured).catch(() => configured);
|
|
40300
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
40301
|
+
let text4 = "";
|
|
40302
|
+
try {
|
|
40303
|
+
text4 = await readFile21(file3, "utf8");
|
|
40304
|
+
} catch (error62) {
|
|
40305
|
+
if (error62.code !== "ENOENT") throw error62;
|
|
40306
|
+
}
|
|
40307
|
+
const settings = text4.trim() ? JSON.parse(text4) : {};
|
|
40308
|
+
if (!settings || typeof settings !== "object" || Array.isArray(settings)) throw new Error("settings.json is not a JSON object");
|
|
40309
|
+
const record2 = settings;
|
|
40310
|
+
if (record2.trustedFolders !== void 0 && !Array.isArray(record2.trustedFolders)) throw new Error("trustedFolders in settings.json is not a list");
|
|
40311
|
+
const trusted = record2.trustedFolders ?? [];
|
|
40312
|
+
if (trusted.includes(dir)) return "already";
|
|
40313
|
+
await mkdir12(directory, { recursive: true, mode: 448 });
|
|
40314
|
+
const metadata = await lstat9(file3).catch(() => void 0);
|
|
40315
|
+
if (await readFile21(file3, "utf8").catch(() => "") !== text4) continue;
|
|
40316
|
+
await atomic(file3, JSON.stringify({ ...record2, trustedFolders: [...trusted, dir] }, null, 2) + "\n", metadata ? metadata.mode & 511 : 384);
|
|
40317
|
+
return "trusted";
|
|
40318
|
+
}
|
|
40319
|
+
throw new Error("settings.json kept changing while it was being updated");
|
|
40320
|
+
}
|
|
40260
40321
|
async function pretrustFolder(harness, dir, why, env = process.env) {
|
|
40261
|
-
if (harness !== "claude" && harness !== "codex") return "skipped";
|
|
40322
|
+
if (harness !== "claude" && harness !== "codex" && harness !== "copilot") return "skipped";
|
|
40262
40323
|
if (!pretrustEnabled(env)) return "skipped";
|
|
40263
40324
|
if (!path47.isAbsolute(dir)) return "skipped";
|
|
40264
|
-
const name = harness === "claude" ? "Claude" : "Codex";
|
|
40325
|
+
const name = harness === "claude" ? "Claude" : harness === "codex" ? "Codex" : "Copilot";
|
|
40265
40326
|
const real2 = await realpath8(dir).catch(() => void 0);
|
|
40266
40327
|
if (!real2 || !await stat14(real2).then((info) => info.isDirectory(), () => false)) return "skipped";
|
|
40267
40328
|
let outcome = "already";
|
|
40268
40329
|
for (const folder of [.../* @__PURE__ */ new Set([dir, real2])]) {
|
|
40269
40330
|
try {
|
|
40270
|
-
const result = harness === "claude" ? await ensureClaudeFolderTrusted(folder, env) : await ensureCodexDirTrusted(folder, env);
|
|
40331
|
+
const result = harness === "claude" ? await ensureClaudeFolderTrusted(folder, env) : harness === "codex" ? await ensureCodexDirTrusted(folder, env) : await ensureCopilotFolderTrusted(folder, env);
|
|
40271
40332
|
if (result === "trusted") logger.info("launch", `Marked ${folder} trusted for ${name} (${why}).`);
|
|
40272
40333
|
else if (result === "skipped") logger.warn("launch", `Did not mark ${folder} trusted for ${name}: its config file does not exist yet.`);
|
|
40273
40334
|
if (result === "trusted" || result === "skipped" && outcome === "already") outcome = result;
|
|
@@ -41908,7 +41969,7 @@ init_claude_accounts();
|
|
|
41908
41969
|
import { readFile as readFile28 } from "node:fs/promises";
|
|
41909
41970
|
import path57 from "node:path";
|
|
41910
41971
|
var SCHEDULE_EVERY = ["interval", "daily", "weekly", "once", "cron"];
|
|
41911
|
-
var SCHEDULE_HARNESSES = ["claude", "codex", "opencode"];
|
|
41972
|
+
var SCHEDULE_HARNESSES = ["claude", "codex", "opencode", "copilot"];
|
|
41912
41973
|
var SCHEDULE_NOTIFY = ["start", "finish", "failure"];
|
|
41913
41974
|
var WEEKDAYS = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
|
|
41914
41975
|
var SCHEDULE_RUN_STATUSES = ["launched", "running", "blocked", "finished", "needs-you", "failed", "skipped"];
|
|
@@ -42200,34 +42261,52 @@ function publicAssistant(raw, source) {
|
|
|
42200
42261
|
const text4 = typeof message.content === "string" ? message.content : objects(message.content).filter((block) => block.type === "text").map((block) => String(block.text ?? "")).join("\n");
|
|
42201
42262
|
return text4.trim() || void 0;
|
|
42202
42263
|
}
|
|
42264
|
+
if (source === "copilot") {
|
|
42265
|
+
const data = object2(raw.data);
|
|
42266
|
+
if (raw.type !== "assistant.message" || raw.agentId || typeof data.content !== "string") return;
|
|
42267
|
+
return data.content.trim() || void 0;
|
|
42268
|
+
}
|
|
42203
42269
|
return;
|
|
42204
42270
|
}
|
|
42205
42271
|
var FINAL_TURN_TAIL_BYTES = 512 * 1024;
|
|
42206
|
-
function turnEnded(raw, source) {
|
|
42272
|
+
function turnEnded(raw, source, copilotFinal = false) {
|
|
42207
42273
|
const payload = object2(raw.payload), message = object2(raw.message), data = object2(raw.data);
|
|
42208
42274
|
if (source === "claude") return raw.type === "assistant" && message.stop_reason === "end_turn" || raw.type === "system" && raw.subtype === "turn_duration";
|
|
42209
42275
|
if (source === "codex") return raw.type === "event_msg" && ["task_complete", "task_completed"].includes(String(payload.type));
|
|
42276
|
+
if (source === "copilot") return raw.type === "session.error" || raw.type === "assistant.turn_end" && !raw.agentId && copilotFinal;
|
|
42210
42277
|
return data.stop_reason === "end_turn";
|
|
42211
42278
|
}
|
|
42212
42279
|
function turnError(raw, source) {
|
|
42280
|
+
if (source === "copilot") {
|
|
42281
|
+
const data = object2(raw.data), message2 = raw.type === "session.error" && typeof data.message === "string" ? data.message.replace(/\s+/g, " ").trim() : "";
|
|
42282
|
+
return message2 ? message2.slice(0, 500) : raw.type === "session.error" ? "Copilot stopped on an error." : void 0;
|
|
42283
|
+
}
|
|
42213
42284
|
if (source !== "codex") return;
|
|
42214
42285
|
const error62 = object2(object2(raw.payload).error), message = typeof error62.message === "string" ? error62.message.replace(/\s+/g, " ").trim() : "";
|
|
42215
42286
|
return message ? message.slice(0, 500) : void 0;
|
|
42216
42287
|
}
|
|
42217
42288
|
function turnInterrupted(raw, source) {
|
|
42218
42289
|
if (source === "codex") return raw.type === "event_msg" && object2(raw.payload).type === "turn_aborted";
|
|
42290
|
+
if (source === "copilot") return raw.type === "abort";
|
|
42219
42291
|
if (source !== "claude" || raw.type !== "user") return false;
|
|
42220
42292
|
const content = object2(raw.message).content;
|
|
42221
42293
|
const text4 = typeof content === "string" ? content : objects(content).filter((block) => block.type === "text").map((block) => String(block.text ?? "")).join("");
|
|
42222
42294
|
return text4.startsWith("[Request interrupted by user");
|
|
42223
42295
|
}
|
|
42224
|
-
var ENDLESS_COMMAND = /\btail\s+(?:-[a-zA-Z]*[fF][a-zA-Z]*\b|--follow\b)|\bjournalctl\b[^|;&]*\s(?:-[a-zA-Z]*f[a-zA-Z]*\b|--follow\b)|\blog\s+stream\b|\blogcat\b|\
|
|
42296
|
+
var ENDLESS_COMMAND = /\btail\s+(?:-[a-zA-Z]*[fF][a-zA-Z]*\b|--follow\b)|\bjournalctl\b[^|;&]*\s(?:-[a-zA-Z]*f[a-zA-Z]*\b|--follow\b)|\blog\s+stream\b|\blogcat\b|(?:^|[;&|(]|\b(?:sudo|nohup|exec)\s)\s*watch\s|--watch\b|\binotifywait\b[^|;&]*\s-m\b|\bfswatch\b|\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:dev|serve|preview)\b|\bhttp\.server\b|\bsleep\s+infinity\b/;
|
|
42225
42297
|
function backgroundTasks(raw, running2, finished2, tail2) {
|
|
42226
42298
|
const result = object2(raw.toolUseResult), blocks = objects(object2(raw.message).content);
|
|
42227
42299
|
if (raw.type === "assistant") {
|
|
42228
42300
|
for (const block of blocks) {
|
|
42229
42301
|
const input2 = object2(block.input);
|
|
42230
|
-
if (block.type === "tool_use" && typeof block.id === "string" &&
|
|
42302
|
+
if (block.type === "tool_use" && typeof block.id === "string" && typeof input2.command === "string") tail2.commands.set(block.id, input2.command.slice(0, 2e3));
|
|
42303
|
+
if (block.type === "tool_use" && tail2.earlier.size) {
|
|
42304
|
+
const named = JSON.stringify(block.input ?? {});
|
|
42305
|
+
for (const id2 of tail2.earlier) if (named.includes(id2)) {
|
|
42306
|
+
tail2.earlier.delete(id2);
|
|
42307
|
+
tail2.awaited.add(id2);
|
|
42308
|
+
}
|
|
42309
|
+
}
|
|
42231
42310
|
}
|
|
42232
42311
|
}
|
|
42233
42312
|
const shell = typeof result.backgroundTaskId === "string" ? result.backgroundTaskId : void 0;
|
|
@@ -42237,12 +42316,16 @@ function backgroundTasks(raw, running2, finished2, tail2) {
|
|
|
42237
42316
|
if (shell) {
|
|
42238
42317
|
const call = blocks.find((block) => block.type === "tool_result")?.tool_use_id;
|
|
42239
42318
|
const command = typeof call === "string" ? tail2.commands.get(call) : void 0;
|
|
42240
|
-
if (
|
|
42319
|
+
if (command && ENDLESS_COMMAND.test(command)) tail2.endless.add(shell);
|
|
42320
|
+
else tail2.awaited.add(shell);
|
|
42241
42321
|
} else if (monitor) tail2.awaited.add(monitor);
|
|
42242
|
-
|
|
42243
|
-
running2.delete(
|
|
42244
|
-
tail2.awaited.delete(
|
|
42245
|
-
|
|
42322
|
+
const ended = (id2) => {
|
|
42323
|
+
running2.delete(id2);
|
|
42324
|
+
tail2.awaited.delete(id2);
|
|
42325
|
+
tail2.earlier.delete(id2);
|
|
42326
|
+
tail2.endless.delete(id2);
|
|
42327
|
+
};
|
|
42328
|
+
if (typeof result.task_id === "string" && typeof result.message === "string" && /\bstopped\b/i.test(result.message)) ended(result.task_id);
|
|
42246
42329
|
const content = object2(raw.message).content, attachment = object2(raw.attachment);
|
|
42247
42330
|
const notices = [
|
|
42248
42331
|
typeof content === "string" ? content : "",
|
|
@@ -42252,14 +42335,13 @@ function backgroundTasks(raw, running2, finished2, tail2) {
|
|
|
42252
42335
|
for (const block of notices.flatMap((notice) => notice.split("<task-notification>").slice(1))) {
|
|
42253
42336
|
const id2 = /<task-id>([^<\s]{1,100})<\/task-id>/.exec(block)?.[1];
|
|
42254
42337
|
if (!id2 || !/<status>(?:completed|failed|killed|stopped)<\/status>/.test(block)) continue;
|
|
42255
|
-
|
|
42256
|
-
tail2.awaited.delete(id2);
|
|
42338
|
+
ended(id2);
|
|
42257
42339
|
if (!finished2.has(id2) && typeof raw.timestamp === "string" && !Number.isNaN(Date.parse(raw.timestamp))) finished2.set(id2, raw.timestamp);
|
|
42258
42340
|
}
|
|
42259
42341
|
}
|
|
42260
42342
|
function finalTurnFromLines(lines, source) {
|
|
42261
|
-
let completed2 = false, lastAssistant, error62, interrupted = false;
|
|
42262
|
-
const running2 = /* @__PURE__ */ new Set(), finished2 = /* @__PURE__ */ new Map(), tail2 = { commands: /* @__PURE__ */ new Map(), awaited: /* @__PURE__ */ new Set() };
|
|
42343
|
+
let completed2 = false, lastAssistant, error62, interrupted = false, copilotFinal = false;
|
|
42344
|
+
const running2 = /* @__PURE__ */ new Set(), finished2 = /* @__PURE__ */ new Map(), tail2 = { commands: /* @__PURE__ */ new Map(), awaited: /* @__PURE__ */ new Set(), earlier: /* @__PURE__ */ new Set(), endless: /* @__PURE__ */ new Set() };
|
|
42263
42345
|
for (const line of lines) {
|
|
42264
42346
|
if (!line.trim()) continue;
|
|
42265
42347
|
let raw;
|
|
@@ -42271,19 +42353,23 @@ function finalTurnFromLines(lines, source) {
|
|
|
42271
42353
|
const payload = object2(raw.payload);
|
|
42272
42354
|
if (source === "claude") {
|
|
42273
42355
|
backgroundTasks(raw, running2, finished2, tail2);
|
|
42274
|
-
if (ownerPrompt(raw))
|
|
42356
|
+
if (ownerPrompt(raw)) {
|
|
42357
|
+
for (const id2 of tail2.awaited) tail2.earlier.add(id2);
|
|
42358
|
+
tail2.awaited.clear();
|
|
42359
|
+
}
|
|
42275
42360
|
}
|
|
42276
42361
|
if (turnInterrupted(raw, source)) {
|
|
42277
42362
|
interrupted = true;
|
|
42278
42363
|
completed2 = false;
|
|
42279
42364
|
continue;
|
|
42280
42365
|
}
|
|
42281
|
-
const userTurn = source === "claude" ? raw.type === "user" && !raw.isMeta && typeof object2(raw.message).content === "string" : source === "codex" ? raw.type === "response_item" && payload.type === "message" && payload.role === "user" : raw.type === "user/message";
|
|
42366
|
+
const userTurn = source === "claude" ? raw.type === "user" && !raw.isMeta && typeof object2(raw.message).content === "string" : source === "codex" ? raw.type === "response_item" && payload.type === "message" && payload.role === "user" : source === "copilot" ? raw.type === "user.message" : raw.type === "user/message";
|
|
42282
42367
|
if (userTurn) {
|
|
42283
42368
|
completed2 = false;
|
|
42284
42369
|
lastAssistant = void 0;
|
|
42285
42370
|
error62 = void 0;
|
|
42286
42371
|
interrupted = false;
|
|
42372
|
+
copilotFinal = false;
|
|
42287
42373
|
continue;
|
|
42288
42374
|
}
|
|
42289
42375
|
const text4 = publicAssistant(raw, source);
|
|
@@ -42292,10 +42378,12 @@ function finalTurnFromLines(lines, source) {
|
|
|
42292
42378
|
completed2 = false;
|
|
42293
42379
|
interrupted = false;
|
|
42294
42380
|
}
|
|
42295
|
-
if (
|
|
42381
|
+
if (source === "copilot" && raw.type === "assistant.message" && !raw.agentId) copilotFinal = object2(raw.data).phase === "final_answer";
|
|
42382
|
+
if (turnEnded(raw, source, copilotFinal)) {
|
|
42296
42383
|
completed2 = true;
|
|
42297
42384
|
interrupted = false;
|
|
42298
42385
|
error62 = turnError(raw, source);
|
|
42386
|
+
copilotFinal = false;
|
|
42299
42387
|
}
|
|
42300
42388
|
}
|
|
42301
42389
|
return {
|
|
@@ -42305,7 +42393,8 @@ function finalTurnFromLines(lines, source) {
|
|
|
42305
42393
|
...interrupted ? { interrupted: true } : {},
|
|
42306
42394
|
...completed2 && running2.size ? { background: running2.size } : {},
|
|
42307
42395
|
...finished2.size ? { finishedTasks: [...finished2.values()] } : {},
|
|
42308
|
-
...tail2.awaited.size ? { awaited: tail2.awaited.size } : {}
|
|
42396
|
+
...tail2.awaited.size ? { awaited: tail2.awaited.size } : {},
|
|
42397
|
+
...completed2 && tail2.endless.size ? { endless: tail2.endless.size } : {}
|
|
42309
42398
|
};
|
|
42310
42399
|
}
|
|
42311
42400
|
function ownerPrompt(raw) {
|
|
@@ -42594,6 +42683,7 @@ function headlessCommand(schedule, cwd) {
|
|
|
42594
42683
|
"-"
|
|
42595
42684
|
] };
|
|
42596
42685
|
if (schedule.harness === "opencode") return { file: "opencode", cwd, args: ["run", "--format", "json", "--dir", cwd, ...model] };
|
|
42686
|
+
if (schedule.harness === "copilot") return { file: "copilot", cwd, args: [`--prompt=${schedule.prompt}`, "--allow-all-tools", "--output-format", "json", ...model] };
|
|
42597
42687
|
return { file: "claude", cwd, args: ["-p", "--output-format", "stream-json", "--settings", CLAUDE_SCHEDULE_SETTINGS, ...model] };
|
|
42598
42688
|
}
|
|
42599
42689
|
async function writeManifest(jobDir, manifest) {
|
|
@@ -43451,14 +43541,15 @@ function hasUsable(inventory, source, accountId) {
|
|
|
43451
43541
|
init_launch_brief();
|
|
43452
43542
|
var text2 = (max) => external_exports.string().min(1).max(max).refine((value2) => !!value2.trim() && !/[\x00-\x1f\x7f]/.test(value2));
|
|
43453
43543
|
var projectName = external_exports.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,99}$/);
|
|
43544
|
+
var DISPATCH_HARNESSES = ["codex", "claude", "opencode", "copilot"];
|
|
43454
43545
|
var dispatchSchema = external_exports.object({
|
|
43455
43546
|
computer: external_exports.union([external_exports.literal("anywhere"), computerName]).describe("Enrolled computer name, or anywhere for the least busy connected computer."),
|
|
43456
43547
|
project: projectName.describe("Project slug registered on the receiving computer."),
|
|
43457
|
-
harness: external_exports.enum(
|
|
43548
|
+
harness: external_exports.enum(DISPATCH_HARNESSES).describe("Agent harness on the receiving computer."),
|
|
43458
43549
|
model: text2(200).optional().describe("Explicit model, otherwise the remote harness default."),
|
|
43459
43550
|
effort: external_exports.enum(launchEfforts).optional().describe("Reasoning effort for the worker (minimal, low, medium, high, xhigh, max), otherwise the harness default."),
|
|
43460
43551
|
account: external_exports.string().refine(isAccountSlug, "Account must be default or a lowercase slug.").optional().describe("Claude account id to run the worker under (default, or a slug from `phren bridge accounts`). anywhere only picks computers where that account is signed in; a named computer without it fails."),
|
|
43461
|
-
permissionMode: external_exports.enum(PERMISSION_MODES).optional().describe("Permission mode the worker starts in: supervised, auto-edits, auto or full-access (Claude and
|
|
43552
|
+
permissionMode: external_exports.enum(PERMISSION_MODES).optional().describe("Permission mode the worker starts in: supervised, auto-edits, auto or full-access (Claude, Codex and Copilot; not OpenCode); otherwise the receiving computer's own default."),
|
|
43462
43553
|
releaseActions: external_exports.array(releaseAction).min(1).max(RELEASE_ACTIONS.length).optional().describe("Release-type actions the brief asks the worker to do (merge, publish, deploy, app-store, github-admin). Ask-first projects refuse them from an agent unless the owner confirmed."),
|
|
43463
43554
|
prompt: external_exports.string().min(1).max(32768).refine((value2) => !/[\x00-\x08\x0b-\x1f\x7f]/.test(value2)).describe("Worker brief, at most 32768 characters."),
|
|
43464
43555
|
label: text2(200).describe("Short task label."),
|
|
@@ -43771,7 +43862,7 @@ var DispatchService = class {
|
|
|
43771
43862
|
* Herdr variables name it; a pane without a running agent is left out. */
|
|
43772
43863
|
async dispatch(input2, originValue) {
|
|
43773
43864
|
const data = dispatchSchema.parse(input2);
|
|
43774
|
-
if (data.permissionMode && data.harness === "opencode") throw new BridgeError(400, "OpenCode takes its permissions from its own config; permissionMode is for Claude and
|
|
43865
|
+
if (data.permissionMode && data.harness === "opencode") throw new BridgeError(400, "OpenCode takes its permissions from its own config; permissionMode is for Claude, Codex and Copilot workers.");
|
|
43775
43866
|
if (this.active) throw new BridgeError(429, "A dispatch is already being placed. Try again after its receipt arrives.");
|
|
43776
43867
|
this.active = true;
|
|
43777
43868
|
let holding = true, placed;
|
|
@@ -43885,12 +43976,12 @@ var DispatchService = class {
|
|
|
43885
43976
|
return { ok: receipt.state === "accepted", ...receipt };
|
|
43886
43977
|
}
|
|
43887
43978
|
receipt.brief = "typed";
|
|
43888
|
-
const
|
|
43889
|
-
if (!
|
|
43890
|
-
if (["blocked", "waiting"].includes(String(
|
|
43891
|
-
throw new BridgeError(504, `${data.harness} started in the new "${data.label}" pane on ${peer.name} but never showed a conversation or a starting pane (last status ${
|
|
43979
|
+
const settled3 = launched.target ? { target: launched.target } : await settledTarget(peer, launched, data.harness, this.settleIntervalMs);
|
|
43980
|
+
if (!settled3.target) {
|
|
43981
|
+
if (["blocked", "waiting"].includes(String(settled3.status ?? launched.agentStatus))) throw new StartupScreen(String(settled3.status ?? launched.agentStatus));
|
|
43982
|
+
throw new BridgeError(504, `${data.harness} started in the new "${data.label}" pane on ${peer.name} but never showed a conversation or a starting pane (last status ${settled3.status ?? "unknown"}), so the brief was not sent. The pane is still open.`);
|
|
43892
43983
|
}
|
|
43893
|
-
const target = remoteTarget.parse(
|
|
43984
|
+
const target = remoteTarget.parse(settled3.target);
|
|
43894
43985
|
if (target.source !== data.harness || target.server !== peer.server) throw new BridgeError(502, "The remote Hook returned a different launch target.");
|
|
43895
43986
|
receipt.target = target;
|
|
43896
43987
|
receipt.state = "sending";
|
|
@@ -44158,7 +44249,7 @@ init_herdr();
|
|
|
44158
44249
|
init_terminal();
|
|
44159
44250
|
import { createHash as createHash19 } from "node:crypto";
|
|
44160
44251
|
import { lstat as lstat21, readFile as readFile34, rm as rm9 } from "node:fs/promises";
|
|
44161
|
-
import
|
|
44252
|
+
import path68 from "node:path";
|
|
44162
44253
|
|
|
44163
44254
|
// src/bridge/worker-reports.ts
|
|
44164
44255
|
init_zod();
|
|
@@ -44343,6 +44434,117 @@ function promptScope(target, text4) {
|
|
|
44343
44434
|
init_terminal();
|
|
44344
44435
|
init_zod();
|
|
44345
44436
|
init_client();
|
|
44437
|
+
|
|
44438
|
+
// src/bridge/approval-summary.ts
|
|
44439
|
+
import path66 from "node:path";
|
|
44440
|
+
var fallback = "Open Phren to review the request.";
|
|
44441
|
+
var fields = (value2) => value2 && typeof value2 === "object" && !Array.isArray(value2) ? value2 : {};
|
|
44442
|
+
var string4 = (value2) => typeof value2 === "string" && value2.trim() ? value2 : void 0;
|
|
44443
|
+
var oneLine = (value2) => value2.replace(/\s+/g, " ").trim();
|
|
44444
|
+
function approvalTitle(agent, project, computer) {
|
|
44445
|
+
const label2 = { claude: "Claude", codex: "Codex", opencode: "opencode", copilot: "Copilot", phren: "Phren" }[agent.toLowerCase()] ?? "Your agent";
|
|
44446
|
+
return `${label2}${project ? ` \xB7 ${project}` : ""}${computer ? ` on ${computer}` : ""}`;
|
|
44447
|
+
}
|
|
44448
|
+
function paneProject(cwd, store) {
|
|
44449
|
+
if (!cwd) return void 0;
|
|
44450
|
+
const resolved = path66.resolve(cwd);
|
|
44451
|
+
if (path66.basename(resolved) === ".phren" || store && resolved === path66.resolve(store)) return void 0;
|
|
44452
|
+
return path66.basename(resolved) || void 0;
|
|
44453
|
+
}
|
|
44454
|
+
function redactApproval(value2) {
|
|
44455
|
+
return value2.replace(/\b[A-Za-z][A-Za-z0-9+.-]*:\/\/[^\s'"<>]+/g, (raw) => {
|
|
44456
|
+
try {
|
|
44457
|
+
const suffix = /[),.;!?]+$/.exec(raw)?.[0] ?? "";
|
|
44458
|
+
const url2 = new URL(raw.slice(0, raw.length - suffix.length));
|
|
44459
|
+
return `${url2.protocol}//${url2.host}${url2.pathname}${suffix}`;
|
|
44460
|
+
} catch {
|
|
44461
|
+
return "\u2026";
|
|
44462
|
+
}
|
|
44463
|
+
}).replace(/\bAuthorization\s*:\s*Bearer\s+(\S+)/gi, (_whole, token) => `Authorization: Bearer \u2026${/["']$/.test(token) ? token.slice(-1) : ""}`).replace(/(^|\s)(--(?:token|password|secret|api-key|access-token))(?:\s+|=)(?:"[^"]*"|'[^']*'|\S+)/gi, "$1$2 \u2026").replace(/(\b(?:mysql|mysqldump|mysqladmin|mariadb)\b[^\n]*?\s-p)(?:"[^"]*"|'[^']*'|\S+)/gi, "$1\u2026").replace(/(^|[\s;&|(])([A-Za-z_][A-Za-z0-9_]*)=(?:"[^"]*"|'[^']*'|[^\s;]+)/g, "$1$2=\u2026").replace(/\b(?:gh[po]_[A-Za-z0-9_]+|github_pat_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]+|xox[abp]-[A-Za-z0-9-]+|AKIA[0-9A-Z]{16}|eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+|[A-Fa-f0-9]{32,}|[A-Za-z0-9_-]{32,})\b/g, "\u2026");
|
|
44464
|
+
}
|
|
44465
|
+
function shortApproval(value2) {
|
|
44466
|
+
const line = oneLine(redactApproval(value2));
|
|
44467
|
+
if (line.length <= 110) return line;
|
|
44468
|
+
const prefix = line.slice(0, 109);
|
|
44469
|
+
const boundary = prefix.lastIndexOf(" ");
|
|
44470
|
+
return (boundary >= 65 ? prefix.slice(0, boundary) : prefix).trimEnd() + "\u2026";
|
|
44471
|
+
}
|
|
44472
|
+
function dialogCommand(text4) {
|
|
44473
|
+
if (!text4) return void 0;
|
|
44474
|
+
return (/^\s*\$ (\S.*)$/m.exec(text4) ?? /^\s*Bash command\s*\n+\s*(\S.*)$/m.exec(text4))?.[1].trim();
|
|
44475
|
+
}
|
|
44476
|
+
function commandText3(value2) {
|
|
44477
|
+
if (typeof value2 === "string") {
|
|
44478
|
+
const wrapped = /^(?:\/[^\s]+\/)?(?:ba|z|fi)?sh\s+-[a-z]*c\s+(['"])([\s\S]*)\1$/i.exec(value2.trim());
|
|
44479
|
+
return wrapped ? wrapped[2] : value2;
|
|
44480
|
+
}
|
|
44481
|
+
if (!Array.isArray(value2)) return void 0;
|
|
44482
|
+
const argv = value2.filter((part) => typeof part === "string");
|
|
44483
|
+
if (!argv.length) return void 0;
|
|
44484
|
+
const shell = /(?:^|\/)(?:ba|z|fi)?sh$/.test(argv[0]);
|
|
44485
|
+
const option = argv.findIndex((part, index2) => index2 > 0 && /^-[a-z]*c$/.test(part));
|
|
44486
|
+
return shell && option >= 0 && argv[option + 1] ? argv[option + 1] : argv.join(" ");
|
|
44487
|
+
}
|
|
44488
|
+
function relativeFile(file3, cwd) {
|
|
44489
|
+
if (!cwd || !path66.isAbsolute(file3) || !path66.isAbsolute(cwd)) return file3;
|
|
44490
|
+
const relative3 = path66.relative(cwd, file3);
|
|
44491
|
+
return relative3 && relative3 !== ".." && !relative3.startsWith(`..${path66.sep}`) && !path66.isAbsolute(relative3) ? relative3.split(path66.sep).join("/") : file3;
|
|
44492
|
+
}
|
|
44493
|
+
function approvalSummary(value2) {
|
|
44494
|
+
const input2 = fields(value2.input), tool = value2.tool ?? "";
|
|
44495
|
+
let line, requestKind = "other";
|
|
44496
|
+
if (value2.question || /^AskUserQuestion$/i.test(tool)) {
|
|
44497
|
+
const questions = Array.isArray(input2.questions) ? input2.questions : [];
|
|
44498
|
+
line = string4(fields(questions[0]).question) ?? string4(input2.question) ?? string4(input2.message) ?? value2.message;
|
|
44499
|
+
if (line) requestKind = "question";
|
|
44500
|
+
} else {
|
|
44501
|
+
const messageCommand = /^(?:bash|shell):\s*(.+)$/is.exec(value2.message ?? "")?.[1];
|
|
44502
|
+
const shown = tool === "Question" ? dialogCommand(value2.message) : void 0;
|
|
44503
|
+
const command = commandText3(input2.command ?? input2.cmd ?? input2.commandLine ?? (Array.isArray(value2.input) ? value2.input : void 0)) ?? messageCommand ?? shown;
|
|
44504
|
+
if (command && (shown !== void 0 || /^(?:Bash|Shell|exec_command|functions\.shell|bash|shell)$/i.test(tool) || input2.command !== void 0 || input2.cmd !== void 0 || input2.commandLine !== void 0)) {
|
|
44505
|
+
line = `Run: ${command}`;
|
|
44506
|
+
requestKind = "command";
|
|
44507
|
+
} else {
|
|
44508
|
+
const mcp = /^mcp__(.+?)__(.+)$/.exec(tool);
|
|
44509
|
+
const sentence = /Allow the ([\w.-]+) MCP server to run tool ([\w.-]+)\?/i.exec(value2.message ?? string4(input2.description) ?? "");
|
|
44510
|
+
const server = mcp?.[1] ?? string4(input2.serverName) ?? string4(input2.server_name) ?? string4(input2.mcpServerName) ?? string4(input2.server) ?? sentence?.[1];
|
|
44511
|
+
const name = mcp?.[2] ?? string4(input2.toolName) ?? string4(input2.tool_name) ?? string4(input2.mcpToolName) ?? string4(input2.tool) ?? sentence?.[2];
|
|
44512
|
+
if (server && name) {
|
|
44513
|
+
line = `${server} MCP: ${name}`;
|
|
44514
|
+
requestKind = "tool";
|
|
44515
|
+
} else {
|
|
44516
|
+
const patch = string4(input2.patch) ?? (typeof value2.input === "string" ? value2.input : void 0);
|
|
44517
|
+
const changed2 = patch ? new Set([...patch.matchAll(/^\*\*\* (?:Add|Update|Delete) File: (.+)$|^diff --git a\/(.+?) b\/(.+)$/gm)].map((match) => match[1] ?? match[3])).size : 0;
|
|
44518
|
+
const file3 = string4(input2.file_path) ?? string4(input2.filePath) ?? string4(input2.path);
|
|
44519
|
+
if (changed2 > 1) line = `Apply patch: ${changed2} files`;
|
|
44520
|
+
else if (file3 && /(?:edit|write|patch|apply)/i.test(tool)) line = `${/write/i.test(tool) || /\*\*\* Add File:/.test(patch ?? "") ? "Write" : "Edit"}: ${relativeFile(file3, value2.cwd)}`;
|
|
44521
|
+
else if (changed2 === 1 && patch) {
|
|
44522
|
+
const match = /^\*\*\* (Add|Update|Delete) File: (.+)$/m.exec(patch);
|
|
44523
|
+
line = match ? `${match[1] === "Add" ? "Write" : "Edit"}: ${relativeFile(match[2], value2.cwd)}` : "Apply patch: 1 file";
|
|
44524
|
+
}
|
|
44525
|
+
if (line) requestKind = "edit";
|
|
44526
|
+
else {
|
|
44527
|
+
const primary = string4(input2.path) ?? string4(input2.file_path) ?? string4(input2.pattern) ?? string4(input2.query) ?? string4(input2.description) ?? string4(input2.question) ?? string4(input2.message) ?? value2.message;
|
|
44528
|
+
if (primary && tool === "Question") {
|
|
44529
|
+
line = primary;
|
|
44530
|
+
requestKind = "question";
|
|
44531
|
+
} else if (primary) {
|
|
44532
|
+
const argument = tool && primary.toLowerCase().startsWith(`${tool.toLowerCase()}:`) ? primary.slice(tool.length + 1).trimStart() : primary;
|
|
44533
|
+
line = `${tool && tool !== "action" ? tool : "Request"}: ${argument}`;
|
|
44534
|
+
requestKind = "tool";
|
|
44535
|
+
} else if (tool && tool !== "action") {
|
|
44536
|
+
line = tool;
|
|
44537
|
+
requestKind = "tool";
|
|
44538
|
+
}
|
|
44539
|
+
}
|
|
44540
|
+
}
|
|
44541
|
+
}
|
|
44542
|
+
}
|
|
44543
|
+
const request9 = line ? shortApproval(line) : fallback;
|
|
44544
|
+
return { request: request9 || fallback, requestKind: line ? requestKind : "other" };
|
|
44545
|
+
}
|
|
44546
|
+
|
|
44547
|
+
// src/bridge/hand-off.ts
|
|
44346
44548
|
init_claude_accounts();
|
|
44347
44549
|
init_protocol();
|
|
44348
44550
|
init_phren_paths();
|
|
@@ -44447,7 +44649,7 @@ function sessionsFrom(overview, computer, local, now = Date.now()) {
|
|
|
44447
44649
|
sessions.push({
|
|
44448
44650
|
computer,
|
|
44449
44651
|
local,
|
|
44450
|
-
project: tab.role === "conductor" ? void 0 : text4(cwd
|
|
44652
|
+
project: tab.role === "conductor" ? void 0 : text4(paneProject(cwd)),
|
|
44451
44653
|
label: text4(label2),
|
|
44452
44654
|
title: text4(tab.title),
|
|
44453
44655
|
agent: tab.agent,
|
|
@@ -44506,38 +44708,55 @@ init_utils_helpers();
|
|
|
44506
44708
|
init_metrics();
|
|
44507
44709
|
import { execFile as execFile12 } from "node:child_process";
|
|
44508
44710
|
import { lstat as lstat20 } from "node:fs/promises";
|
|
44509
|
-
import
|
|
44711
|
+
import path67 from "node:path";
|
|
44510
44712
|
import { promisify as promisify11 } from "node:util";
|
|
44511
44713
|
var exec11 = promisify11(execFile12);
|
|
44512
44714
|
var NEXT_STEP = /^(?:(?:ok(?:ay)?|alright|now|next|then|first|great|good)\b[,.!:]?\s+)*(?:let me(?! know)|let's|let us|i'll|i will|i'm going to|i am going to|i need to|i'm now|i am now|now i)\s+(.*)$/i;
|
|
44513
44715
|
var NOW_DOING = /^now,?\s+(?:adding|applying|building|checking|cleaning|committing|compiling|creating|debugging|editing|fixing|generating|implementing|installing|investigating|launching|looking|moving|opening|patching|pushing|reading|rebuilding|refactoring|removing|rerunning|re-running|running|searching|setting|starting|testing|trying|updating|verifying|wiring|working|writing)\b/i;
|
|
44514
44716
|
var HANDOVER = /^(?:just\s+)?(?:wait|await|leave|stop|hold|pause|be|hand|defer|stand|end|wrap|let you|keep an eye|check back|merge|ship|land|release|discuss|review|done|finished|ready)\b/i;
|
|
44515
44717
|
var CONDITIONAL = /\b(?:once|when|whenever|after|as soon as|if|until|unless)\b/i;
|
|
44516
|
-
|
|
44517
|
-
|
|
44718
|
+
var WAITS = /(?<!\bwhile\s)\b(?:wait(?:ing|s)?|await(?:ing|s)?)\s+(?:on|for|until)\b/i;
|
|
44719
|
+
var ONCE_DONE = /\b(?:once|when|after|as soon as|until)\s+(?:it|its|the|that|this|they|both|all|my|ci)\b/i;
|
|
44720
|
+
var FUTURE = /\b(?:i'll|i will|we'll|we will|let's|let us|then i|will)\b/i;
|
|
44721
|
+
var OWNER = /\b(?:you|your|yours|owner|reviewers?|approv\w*|let me know)\b/i;
|
|
44722
|
+
var NEGATED = /\b(?:nothing|no longer|not|no need|without)\b|n't\b/i;
|
|
44723
|
+
function closingLines(reply) {
|
|
44724
|
+
let fenced = false, lines = [];
|
|
44518
44725
|
for (const raw of reply.replace(/\r/g, "").split("\n")) {
|
|
44519
44726
|
const line = raw.trim();
|
|
44520
44727
|
if (/^(?:```|~~~)/.test(line)) {
|
|
44521
44728
|
fenced = !fenced;
|
|
44522
44729
|
continue;
|
|
44523
44730
|
}
|
|
44524
|
-
if (
|
|
44731
|
+
if (fenced) continue;
|
|
44732
|
+
if (!line) {
|
|
44733
|
+
if (lines.length) lines = [...lines, ""];
|
|
44734
|
+
continue;
|
|
44735
|
+
}
|
|
44736
|
+
if (lines.at(-1) === "") lines = [];
|
|
44737
|
+
lines.push(line);
|
|
44525
44738
|
}
|
|
44526
|
-
return
|
|
44739
|
+
return lines.filter(Boolean);
|
|
44740
|
+
}
|
|
44741
|
+
var LIST_ITEM = /^(?:[-*+>]|\d+[.)])\s+/;
|
|
44742
|
+
var sentences = (line) => line.replace(LIST_ITEM, "").replace(/[*_`#]+/g, "").replace(/[\u2018\u2019]/g, "'").trim().split(/(?<=[.!?\u2026])\s+/).map((sentence) => sentence.trim()).filter(Boolean);
|
|
44743
|
+
function nextStep(sentence) {
|
|
44744
|
+
if (CONDITIONAL.test(sentence)) return false;
|
|
44745
|
+
const step2 = NEXT_STEP.exec(sentence);
|
|
44746
|
+
return step2 ? !HANDOVER.test(step2[1]) : NOW_DOING.test(sentence);
|
|
44527
44747
|
}
|
|
44528
44748
|
function announcedNextStep(reply) {
|
|
44529
|
-
const
|
|
44530
|
-
|
|
44531
|
-
|
|
44532
|
-
|
|
44533
|
-
|
|
44534
|
-
const
|
|
44535
|
-
|
|
44536
|
-
return announced ? last.slice(0, 160) : void 0;
|
|
44749
|
+
const lines = reply ? closingLines(reply) : [];
|
|
44750
|
+
const found = lines.flatMap((line, index2) => index2 === lines.length - 1 || !LIST_ITEM.test(line) ? sentences(line) : []).find(nextStep);
|
|
44751
|
+
return found?.slice(0, 160);
|
|
44752
|
+
}
|
|
44753
|
+
function awaitedInReply(reply) {
|
|
44754
|
+
const found = (reply ? closingLines(reply) : []).flatMap(sentences).find((sentence) => !OWNER.test(sentence) && !NEGATED.test(sentence) && (WAITS.test(sentence) || ONCE_DONE.test(sentence) && FUTURE.test(sentence)));
|
|
44755
|
+
return found?.slice(0, 160);
|
|
44537
44756
|
}
|
|
44538
44757
|
var UNKNOWN = "unknown";
|
|
44539
44758
|
async function uncommittedFiles(directory, timeoutMs = 3e3) {
|
|
44540
|
-
if (!
|
|
44759
|
+
if (!path67.isAbsolute(directory)) return void 0;
|
|
44541
44760
|
countGit("worker-unfinished");
|
|
44542
44761
|
try {
|
|
44543
44762
|
const { stdout } = await exec11("git", ["-C", directory, "--no-pager", "-c", "core.fsmonitor=false", "status", "--porcelain=v1", "--untracked-files=no", "-z"], {
|
|
@@ -44566,11 +44785,11 @@ function recentUncommitted(directory, now = Date.now(), read = uncommittedFiles)
|
|
|
44566
44785
|
return files;
|
|
44567
44786
|
}
|
|
44568
44787
|
async function checkoutRoot(directory) {
|
|
44569
|
-
if (!
|
|
44570
|
-
let folder =
|
|
44788
|
+
if (!path67.isAbsolute(directory)) return void 0;
|
|
44789
|
+
let folder = path67.resolve(directory);
|
|
44571
44790
|
for (let depth = 0; depth < 64; depth++) {
|
|
44572
|
-
if (await lstat20(
|
|
44573
|
-
const parent =
|
|
44791
|
+
if (await lstat20(path67.join(folder, ".git")).then(() => true, () => false)) return folder;
|
|
44792
|
+
const parent = path67.dirname(folder);
|
|
44574
44793
|
if (parent === folder) return void 0;
|
|
44575
44794
|
folder = parent;
|
|
44576
44795
|
}
|
|
@@ -44579,7 +44798,7 @@ async function checkoutRoot(directory) {
|
|
|
44579
44798
|
async function sharedCheckout(directory, folders) {
|
|
44580
44799
|
const root = await checkoutRoot(directory);
|
|
44581
44800
|
if (!root) return false;
|
|
44582
|
-
const others = [...new Set(folders.filter((folder) => typeof folder === "string" &&
|
|
44801
|
+
const others = [...new Set(folders.filter((folder) => typeof folder === "string" && path67.isAbsolute(folder)))].slice(0, 64);
|
|
44583
44802
|
for (const folder of others) if (folder.startsWith(root) && await checkoutRoot(folder) === root) return true;
|
|
44584
44803
|
return false;
|
|
44585
44804
|
}
|
|
@@ -44587,6 +44806,8 @@ var PR_NAMED = /\/pull\/\d+|\bPR\s*#\d+/i;
|
|
|
44587
44806
|
async function unfinishedTurn(input2, uncommitted2) {
|
|
44588
44807
|
const step2 = announcedNextStep(input2.reply);
|
|
44589
44808
|
if (step2) return { unfinished: `Stopped mid-task: ${step2}` };
|
|
44809
|
+
const waiting = awaitedInReply(input2.reply);
|
|
44810
|
+
if (waiting) return { unfinished: `Stopped waiting: ${waiting}` };
|
|
44590
44811
|
if (input2.prs?.length || PR_NAMED.test(input2.reply ?? "") || !input2.directory || !uncommitted2) return {};
|
|
44591
44812
|
const files = await uncommitted2(input2.directory).catch(() => UNKNOWN);
|
|
44592
44813
|
if (files === UNKNOWN) return { unchecked: true };
|
|
@@ -44613,7 +44834,7 @@ var defaultReaders = {
|
|
|
44613
44834
|
snapshot: (server) => sharedSnapshot(server, SNAPSHOT_AGE_MS),
|
|
44614
44835
|
freshSnapshot: snapshot,
|
|
44615
44836
|
identity: (server, pane) => paneIdentity(server, pane),
|
|
44616
|
-
finalTurn: (source, session) => source === "codex" || source === "claude" || source === "opencode" ? readFinalTurn(source, session) : Promise.resolve(void 0),
|
|
44837
|
+
finalTurn: (source, session) => source === "codex" || source === "claude" || source === "opencode" || source === "copilot" ? readFinalTurn(source, session) : Promise.resolve(void 0),
|
|
44617
44838
|
turn: paneTurn,
|
|
44618
44839
|
children: (source, session) => childAgentTree(source, session).then(runningChildAgents).then((children) => children.length),
|
|
44619
44840
|
stall: (target, pane, live) => sessionStalls.observe(target, pane, live),
|
|
@@ -44633,6 +44854,10 @@ function replyFields(text4, truncated) {
|
|
|
44633
44854
|
const reply = truncateUtf8(text4);
|
|
44634
44855
|
return { reply: reply.text, ...reply.truncated || truncated ? { truncated: true } : {} };
|
|
44635
44856
|
}
|
|
44857
|
+
function settled(reply, running2) {
|
|
44858
|
+
if (running2 && awaitedInReply(reply)) return { state: "working", background: running2 };
|
|
44859
|
+
return { state: "done", ...running2 ? { background: running2 } : {} };
|
|
44860
|
+
}
|
|
44636
44861
|
async function fromTurn(record2, session, status, source, readers) {
|
|
44637
44862
|
const base = { session, hook: true };
|
|
44638
44863
|
if (status === "blocked") return { state: "blocked", ...base };
|
|
@@ -44650,12 +44875,16 @@ async function fromTurn(record2, session, status, source, readers) {
|
|
|
44650
44875
|
if (!final?.completed) return { state: "working", ...base };
|
|
44651
44876
|
const live2 = liveWork(record2, final, children, now);
|
|
44652
44877
|
if (live2) return { state: "working", ...base, background: live2 };
|
|
44653
|
-
|
|
44878
|
+
const end2 = settled(final.lastAssistant, runningTasks(record2, final, now));
|
|
44879
|
+
if (end2.state === "working") return { ...end2, ...base };
|
|
44880
|
+
return { ...end2, ...base, completed: true, ...final.error ? { error: final.error } : {}, ...replyFields(final.lastAssistant) };
|
|
44654
44881
|
}
|
|
44655
44882
|
const live = liveWork(record2, final, children, now);
|
|
44656
44883
|
if (live) return { state: "working", ...base, background: live };
|
|
44884
|
+
const end = settled(phase.reply ?? final?.lastAssistant, runningTasks(record2, final, now));
|
|
44885
|
+
if (end.state === "working") return { ...end, ...base };
|
|
44657
44886
|
return {
|
|
44658
|
-
|
|
44887
|
+
...end,
|
|
44659
44888
|
...base,
|
|
44660
44889
|
completed: true,
|
|
44661
44890
|
endedAt: phase.at,
|
|
@@ -44726,7 +44955,9 @@ async function workerStates2(input2, readers = defaultReaders) {
|
|
|
44726
44955
|
}
|
|
44727
44956
|
const turn = await readers.finalTurn(target.source, session).catch(() => void 0);
|
|
44728
44957
|
const children = readers.children ? await readers.children(target.source, session).catch(() => 0) : 0;
|
|
44729
|
-
const
|
|
44958
|
+
const now = (readers.now ?? Date.now)();
|
|
44959
|
+
const end = turn?.completed ? settled(turn.lastAssistant, runningTasks(void 0, turn, now)) : void 0;
|
|
44960
|
+
const live = turn?.completed ? liveWork(void 0, turn, children, now) ?? (end?.state === "working" ? end.background : void 0) : void 0;
|
|
44730
44961
|
if (live) {
|
|
44731
44962
|
return { state: "working", session, completed: true, background: live, ...turn?.error ? { error: turn.error } : {}, ...replyFields(turn?.lastAssistant) };
|
|
44732
44963
|
}
|
|
@@ -44734,6 +44965,7 @@ async function workerStates2(input2, readers = defaultReaders) {
|
|
|
44734
44965
|
state,
|
|
44735
44966
|
session,
|
|
44736
44967
|
completed: turn?.completed === true,
|
|
44968
|
+
...end?.background ? { background: end.background } : {},
|
|
44737
44969
|
...turn?.error ? { error: turn.error } : {},
|
|
44738
44970
|
...turn?.interrupted ? { interrupted: true } : {},
|
|
44739
44971
|
...replyFields(turn?.lastAssistant)
|
|
@@ -45243,7 +45475,7 @@ ${JSON.stringify({ dispatch: receipt.id, project: receipt.project, prs: result.p
|
|
|
45243
45475
|
|
|
45244
45476
|
// src/bridge/worker-close.ts
|
|
45245
45477
|
var closedTargetSchema = external_exports.union([targetSchema, startingTargetSchema]);
|
|
45246
|
-
var file2 = (target) =>
|
|
45478
|
+
var file2 = (target) => path68.join(bridgeRoot(), "closed-workers", `${createHash19("sha256").update(JSON.stringify([target.server, target.workspace, target.tab, target.pane, target.source, "session" in target ? target.session : target.startingToken])).digest("hex")}.json`);
|
|
45247
45479
|
async function markWorkerClosed(target, terminal2) {
|
|
45248
45480
|
await atomicInPrivateDir(file2(target), { target, terminal: terminal2, at: (/* @__PURE__ */ new Date()).toISOString() });
|
|
45249
45481
|
}
|
|
@@ -45289,7 +45521,7 @@ async function closeFinishedWorker(input2, queue3) {
|
|
|
45289
45521
|
if (!["idle", "done"].includes(String(pane.agent_status))) return { ok: true, closed: false };
|
|
45290
45522
|
const seen = (await workerStates2({ targets: [{ ...data.target, dispatch: data.dispatch }] })).workers[0];
|
|
45291
45523
|
const turn = workerTurnKey(seen);
|
|
45292
|
-
if (!seen.completed || seen.background || seen.error || seen.unfinished || seen.unchecked || turn !== data.turn) return { ok: true, closed: false };
|
|
45524
|
+
if (seen.state !== "done" && seen.state !== "idle" || !seen.completed || seen.background || seen.error || seen.unfinished || seen.unchecked || turn !== data.turn) return { ok: true, closed: false };
|
|
45293
45525
|
const current2 = await validateTarget(data.target, false, true);
|
|
45294
45526
|
if (current2.terminal_id !== pane.terminal_id || !["idle", "done"].includes(String(current2.agent_status))) throw new BridgeError(409, "The worker resumed before it could close.");
|
|
45295
45527
|
const record2 = await paneTurn(data.target.server, current2, data.target.source);
|
|
@@ -45310,7 +45542,7 @@ init_zod();
|
|
|
45310
45542
|
init_protocol();
|
|
45311
45543
|
import { createHash as createHash20, randomUUID as randomUUID15 } from "node:crypto";
|
|
45312
45544
|
import { lstat as lstat22, open as open15, readFile as readFile35, readdir as readdir13, unlink as unlink5 } from "node:fs/promises";
|
|
45313
|
-
import
|
|
45545
|
+
import path69 from "node:path";
|
|
45314
45546
|
init_terminal();
|
|
45315
45547
|
var queuedHandOffSchema = external_exports.object({
|
|
45316
45548
|
target: targetSchema,
|
|
@@ -45331,12 +45563,12 @@ var rowSchema = queuedHandOffSchema.extend({
|
|
|
45331
45563
|
var DAY2 = 864e5;
|
|
45332
45564
|
var HAND_OFF_RETENTION_MS = 7 * DAY2;
|
|
45333
45565
|
var HAND_OFF_MAX_ROWS = 512;
|
|
45334
|
-
var
|
|
45566
|
+
var settled2 = (row) => row.state !== "queued" && row.state !== "attempting";
|
|
45335
45567
|
var sameTarget2 = (a, b) => ["server", "workspace", "tab", "pane", "source", "session"].every((key3) => a[key3] === b[key3]);
|
|
45336
45568
|
var HandOffQueue = class {
|
|
45337
45569
|
constructor(options) {
|
|
45338
45570
|
this.options = options;
|
|
45339
|
-
this.root = options.root ??
|
|
45571
|
+
this.root = options.root ?? path69.join(bridgeRoot(), "hand-offs");
|
|
45340
45572
|
this.now = options.now ?? Date.now;
|
|
45341
45573
|
}
|
|
45342
45574
|
options;
|
|
@@ -45351,7 +45583,7 @@ var HandOffQueue = class {
|
|
|
45351
45583
|
return result;
|
|
45352
45584
|
}
|
|
45353
45585
|
file(id2) {
|
|
45354
|
-
return
|
|
45586
|
+
return path69.join(this.root, `${deliveryIdSchema.unwrap().parse(id2)}.json`);
|
|
45355
45587
|
}
|
|
45356
45588
|
async save(row) {
|
|
45357
45589
|
row.updatedAt = new Date(this.now()).toISOString();
|
|
@@ -45398,11 +45630,11 @@ var HandOffQueue = class {
|
|
|
45398
45630
|
async prune(rows) {
|
|
45399
45631
|
this.lastPrune = this.now();
|
|
45400
45632
|
const now = this.now(), drop = /* @__PURE__ */ new Set();
|
|
45401
|
-
for (const row of rows) if (
|
|
45633
|
+
for (const row of rows) if (settled2(row) && now - Date.parse(row.updatedAt) > HAND_OFF_RETENTION_MS) drop.add(row.deliveryId);
|
|
45402
45634
|
let excess = rows.length - drop.size - HAND_OFF_MAX_ROWS;
|
|
45403
45635
|
if (excess > 0) {
|
|
45404
45636
|
const owesNotice = (row) => row.origin && !row.notified ? 1 : 0;
|
|
45405
|
-
const candidates = rows.filter((row) =>
|
|
45637
|
+
const candidates = rows.filter((row) => settled2(row) && !drop.has(row.deliveryId)).sort((a, b) => owesNotice(a) - owesNotice(b) || a.updatedAt.localeCompare(b.updatedAt) || a.deliveryId.localeCompare(b.deliveryId));
|
|
45406
45638
|
for (const row of candidates) {
|
|
45407
45639
|
if (excess-- <= 0) break;
|
|
45408
45640
|
drop.add(row.deliveryId);
|
|
@@ -45549,7 +45781,7 @@ init_protocol();
|
|
|
45549
45781
|
import { createHash as createHash21 } from "node:crypto";
|
|
45550
45782
|
import { execFile as execFile13 } from "node:child_process";
|
|
45551
45783
|
import { lstat as lstat23, readdir as readdir14, readFile as readFile36, realpath as realpath11, stat as stat17 } from "node:fs/promises";
|
|
45552
|
-
import
|
|
45784
|
+
import path70 from "node:path";
|
|
45553
45785
|
import { promisify as promisify12 } from "node:util";
|
|
45554
45786
|
var exec12 = promisify12(execFile13);
|
|
45555
45787
|
function statusLetter(code) {
|
|
@@ -45595,7 +45827,7 @@ function parseNumstat(out) {
|
|
|
45595
45827
|
}
|
|
45596
45828
|
async function countLines(root, rel) {
|
|
45597
45829
|
try {
|
|
45598
|
-
const abs =
|
|
45830
|
+
const abs = path70.join(root, await repositoryPath(root, rel));
|
|
45599
45831
|
if ((await stat17(abs)).size > 5e6) return 0;
|
|
45600
45832
|
const bytes = await readFile36(abs);
|
|
45601
45833
|
if (!bytes.length || bytes.includes(0)) return 0;
|
|
@@ -45819,13 +46051,13 @@ async function gitPulls(cwd) {
|
|
|
45819
46051
|
}
|
|
45820
46052
|
}
|
|
45821
46053
|
async function repositoryPath(root, raw, allowRoot = false) {
|
|
45822
|
-
if (typeof raw !== "string" || raw.length > 4096 || raw.includes("\0") ||
|
|
46054
|
+
if (typeof raw !== "string" || raw.length > 4096 || raw.includes("\0") || path70.isAbsolute(raw) || path70.win32.isAbsolute(raw) || raw.startsWith("\\")) throw new BridgeError(400, "Invalid path.");
|
|
45823
46055
|
const segments = raw.split(/[\\/]/);
|
|
45824
46056
|
if (segments.includes("..")) throw new BridgeError(400, "Invalid path.");
|
|
45825
46057
|
const clean2 = segments.filter((part) => part && part !== ".").join("/");
|
|
45826
46058
|
if (!clean2 && !allowRoot || clean2.startsWith("-")) throw new BridgeError(400, "Invalid path.");
|
|
45827
|
-
const abs =
|
|
45828
|
-
if (abs !== root && !abs.startsWith(root +
|
|
46059
|
+
const abs = path70.resolve(root, clean2);
|
|
46060
|
+
if (abs !== root && !abs.startsWith(root + path70.sep)) throw new BridgeError(403, "This path is outside the repository.");
|
|
45829
46061
|
let existing = abs;
|
|
45830
46062
|
while (true) {
|
|
45831
46063
|
try {
|
|
@@ -45833,7 +46065,7 @@ async function repositoryPath(root, raw, allowRoot = false) {
|
|
|
45833
46065
|
break;
|
|
45834
46066
|
} catch (error62) {
|
|
45835
46067
|
if (error62.code !== "ENOENT" || existing === root) throw new BridgeError(400, "Invalid path.");
|
|
45836
|
-
existing =
|
|
46068
|
+
existing = path70.dirname(existing);
|
|
45837
46069
|
}
|
|
45838
46070
|
}
|
|
45839
46071
|
let resolved;
|
|
@@ -45842,7 +46074,7 @@ async function repositoryPath(root, raw, allowRoot = false) {
|
|
|
45842
46074
|
} catch {
|
|
45843
46075
|
throw new BridgeError(403, "This path cannot be resolved inside the repository.");
|
|
45844
46076
|
}
|
|
45845
|
-
if (resolved !== root && !resolved.startsWith(root +
|
|
46077
|
+
if (resolved !== root && !resolved.startsWith(root + path70.sep)) throw new BridgeError(403, "This path is outside the repository.");
|
|
45846
46078
|
return clean2;
|
|
45847
46079
|
}
|
|
45848
46080
|
var treeCache = /* @__PURE__ */ new Map();
|
|
@@ -45924,7 +46156,7 @@ async function ignoredEntries(root, prefix, shown) {
|
|
|
45924
46156
|
const entries2 = /* @__PURE__ */ new Map();
|
|
45925
46157
|
const inside = prefix && listing.some((item) => item.endsWith("/") && (prefix + "/").startsWith(item));
|
|
45926
46158
|
if (inside) {
|
|
45927
|
-
const dirents = await readdir14(
|
|
46159
|
+
const dirents = await readdir14(path70.join(root, prefix), { withFileTypes: true }).catch(() => []);
|
|
45928
46160
|
for (const dirent of dirents) {
|
|
45929
46161
|
if (dirent.name === ".git" || taken.has(dirent.name) || entries2.size >= MAX_IGNORED_ENTRIES) continue;
|
|
45930
46162
|
entries2.set(dirent.name, { name: dirent.name, path: `${prefix}/${dirent.name}`, kind: dirent.isDirectory() ? "dir" : "file", ignored: true });
|
|
@@ -46023,7 +46255,7 @@ init_protocol();
|
|
|
46023
46255
|
import { createHash as createHash22 } from "node:crypto";
|
|
46024
46256
|
import { realpath as realpath12, stat as stat18 } from "node:fs/promises";
|
|
46025
46257
|
import { homedir as homedir15 } from "node:os";
|
|
46026
|
-
import
|
|
46258
|
+
import path71 from "node:path";
|
|
46027
46259
|
var MAX_WORKTREES = 64;
|
|
46028
46260
|
var worktreeIdPattern = /^[a-f0-9]{32}$/;
|
|
46029
46261
|
function worktreeId(abs) {
|
|
@@ -46062,11 +46294,11 @@ async function listed(root) {
|
|
|
46062
46294
|
}
|
|
46063
46295
|
function displayPath(abs, roots) {
|
|
46064
46296
|
for (const root of roots) {
|
|
46065
|
-
const rel =
|
|
46066
|
-
if (rel && !rel.startsWith("..") && !
|
|
46297
|
+
const rel = path71.relative(root, abs);
|
|
46298
|
+
if (rel && !rel.startsWith("..") && !path71.isAbsolute(rel)) return rel.split(path71.sep).join("/");
|
|
46067
46299
|
}
|
|
46068
46300
|
const home = homedir15();
|
|
46069
|
-
return abs === home ? "~" : abs.startsWith(home +
|
|
46301
|
+
return abs === home ? "~" : abs.startsWith(home + path71.sep) ? "~/" + path71.relative(home, abs).split(path71.sep).join("/") : abs;
|
|
46070
46302
|
}
|
|
46071
46303
|
function uncommitted(status) {
|
|
46072
46304
|
const tokens = status.split("\0");
|
|
@@ -46080,12 +46312,12 @@ function uncommitted(status) {
|
|
|
46080
46312
|
return count2;
|
|
46081
46313
|
}
|
|
46082
46314
|
async function workerFor(abs, workers, all = []) {
|
|
46083
|
-
const nested = all.filter((other) => other.startsWith(abs +
|
|
46315
|
+
const nested = all.filter((other) => other.startsWith(abs + path71.sep));
|
|
46084
46316
|
let best;
|
|
46085
46317
|
for (const worker of workers) {
|
|
46086
|
-
const cwd = await realpath12(worker.cwd).catch(() =>
|
|
46087
|
-
if (cwd !== abs && !cwd.startsWith(abs +
|
|
46088
|
-
if (nested.some((inner) => cwd === inner || cwd.startsWith(inner +
|
|
46318
|
+
const cwd = await realpath12(worker.cwd).catch(() => path71.resolve(worker.cwd));
|
|
46319
|
+
if (cwd !== abs && !cwd.startsWith(abs + path71.sep)) continue;
|
|
46320
|
+
if (nested.some((inner) => cwd === inner || cwd.startsWith(inner + path71.sep))) continue;
|
|
46089
46321
|
const score = (cwd === abs ? 2 : 0) + (worker.child ? 1 : 0);
|
|
46090
46322
|
if (!best || score > best.score) best = { worker, score };
|
|
46091
46323
|
}
|
|
@@ -46155,10 +46387,10 @@ var PR_TIMEOUT_MS = 6e4;
|
|
|
46155
46387
|
var MAX_MESSAGE = 2e4;
|
|
46156
46388
|
function runCombined(command, args, cwd, timeout) {
|
|
46157
46389
|
return new Promise((resolve11) => {
|
|
46158
|
-
let output2 = "", truncated = false, timedOut = false,
|
|
46390
|
+
let output2 = "", truncated = false, timedOut = false, settled3 = false;
|
|
46159
46391
|
const finish = (run2) => {
|
|
46160
|
-
if (!
|
|
46161
|
-
|
|
46392
|
+
if (!settled3) {
|
|
46393
|
+
settled3 = true;
|
|
46162
46394
|
resolve11(run2);
|
|
46163
46395
|
}
|
|
46164
46396
|
};
|
|
@@ -46294,11 +46526,11 @@ init_codex_daemon();
|
|
|
46294
46526
|
|
|
46295
46527
|
// src/bridge/codex-review-mode.ts
|
|
46296
46528
|
import { open as open16 } from "node:fs/promises";
|
|
46297
|
-
import
|
|
46529
|
+
import path72 from "node:path";
|
|
46298
46530
|
var SCAN_LIMIT = 64 * 1048576;
|
|
46299
46531
|
var CHUNK = 1048576;
|
|
46300
46532
|
async function codexAutoReview(transcriptPath2) {
|
|
46301
|
-
if (typeof transcriptPath2 !== "string" || !
|
|
46533
|
+
if (typeof transcriptPath2 !== "string" || !path72.isAbsolute(transcriptPath2) || !/^rollout-.*\.jsonl$/.test(path72.basename(transcriptPath2))) return false;
|
|
46302
46534
|
const file3 = await open16(transcriptPath2, "r").catch(() => void 0);
|
|
46303
46535
|
if (!file3) return false;
|
|
46304
46536
|
try {
|
|
@@ -46356,111 +46588,6 @@ import { createCipheriv, createHmac as createHmac2, createPrivateKey, randomByte
|
|
|
46356
46588
|
import { readFile as readFile37, stat as stat19 } from "node:fs/promises";
|
|
46357
46589
|
import { connect as connect3 } from "node:http2";
|
|
46358
46590
|
import path73 from "node:path";
|
|
46359
|
-
|
|
46360
|
-
// src/bridge/approval-summary.ts
|
|
46361
|
-
import path72 from "node:path";
|
|
46362
|
-
var fallback = "Open Phren to review the request.";
|
|
46363
|
-
var fields = (value2) => value2 && typeof value2 === "object" && !Array.isArray(value2) ? value2 : {};
|
|
46364
|
-
var string4 = (value2) => typeof value2 === "string" && value2.trim() ? value2 : void 0;
|
|
46365
|
-
var oneLine = (value2) => value2.replace(/\s+/g, " ").trim();
|
|
46366
|
-
function approvalTitle(agent, project, computer) {
|
|
46367
|
-
const label2 = { claude: "Claude", codex: "Codex", opencode: "opencode", copilot: "Copilot" }[agent.toLowerCase()] ?? "Your agent";
|
|
46368
|
-
return `${label2}${project ? ` \xB7 ${project}` : ""}${computer ? ` on ${computer}` : ""}`;
|
|
46369
|
-
}
|
|
46370
|
-
function redactApproval(value2) {
|
|
46371
|
-
return value2.replace(/\b[A-Za-z][A-Za-z0-9+.-]*:\/\/[^\s'"<>]+/g, (raw) => {
|
|
46372
|
-
try {
|
|
46373
|
-
const suffix = /[),.;!?]+$/.exec(raw)?.[0] ?? "";
|
|
46374
|
-
const url2 = new URL(raw.slice(0, raw.length - suffix.length));
|
|
46375
|
-
return `${url2.protocol}//${url2.host}${url2.pathname}${suffix}`;
|
|
46376
|
-
} catch {
|
|
46377
|
-
return "\u2026";
|
|
46378
|
-
}
|
|
46379
|
-
}).replace(/\bAuthorization\s*:\s*Bearer\s+(\S+)/gi, (_whole, token) => `Authorization: Bearer \u2026${/["']$/.test(token) ? token.slice(-1) : ""}`).replace(/(^|\s)(--(?:token|password|secret|api-key|access-token))(?:\s+|=)(?:"[^"]*"|'[^']*'|\S+)/gi, "$1$2 \u2026").replace(/(\b(?:mysql|mysqldump|mysqladmin|mariadb)\b[^\n]*?\s-p)(?:"[^"]*"|'[^']*'|\S+)/gi, "$1\u2026").replace(/(^|[\s;&|(])([A-Za-z_][A-Za-z0-9_]*)=(?:"[^"]*"|'[^']*'|[^\s;]+)/g, "$1$2=\u2026").replace(/\b(?:gh[po]_[A-Za-z0-9_]+|github_pat_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]+|xox[abp]-[A-Za-z0-9-]+|AKIA[0-9A-Z]{16}|eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+|[A-Fa-f0-9]{32,}|[A-Za-z0-9_-]{32,})\b/g, "\u2026");
|
|
46380
|
-
}
|
|
46381
|
-
function shortApproval(value2) {
|
|
46382
|
-
const line = oneLine(redactApproval(value2));
|
|
46383
|
-
if (line.length <= 110) return line;
|
|
46384
|
-
const prefix = line.slice(0, 109);
|
|
46385
|
-
const boundary = prefix.lastIndexOf(" ");
|
|
46386
|
-
return (boundary >= 65 ? prefix.slice(0, boundary) : prefix).trimEnd() + "\u2026";
|
|
46387
|
-
}
|
|
46388
|
-
function dialogCommand(text4) {
|
|
46389
|
-
if (!text4) return void 0;
|
|
46390
|
-
return (/^\s*\$ (\S.*)$/m.exec(text4) ?? /^\s*Bash command\s*\n+\s*(\S.*)$/m.exec(text4))?.[1].trim();
|
|
46391
|
-
}
|
|
46392
|
-
function commandText3(value2) {
|
|
46393
|
-
if (typeof value2 === "string") {
|
|
46394
|
-
const wrapped = /^(?:\/[^\s]+\/)?(?:ba|z|fi)?sh\s+-[a-z]*c\s+(['"])([\s\S]*)\1$/i.exec(value2.trim());
|
|
46395
|
-
return wrapped ? wrapped[2] : value2;
|
|
46396
|
-
}
|
|
46397
|
-
if (!Array.isArray(value2)) return void 0;
|
|
46398
|
-
const argv = value2.filter((part) => typeof part === "string");
|
|
46399
|
-
if (!argv.length) return void 0;
|
|
46400
|
-
const shell = /(?:^|\/)(?:ba|z|fi)?sh$/.test(argv[0]);
|
|
46401
|
-
const option = argv.findIndex((part, index2) => index2 > 0 && /^-[a-z]*c$/.test(part));
|
|
46402
|
-
return shell && option >= 0 && argv[option + 1] ? argv[option + 1] : argv.join(" ");
|
|
46403
|
-
}
|
|
46404
|
-
function relativeFile(file3, cwd) {
|
|
46405
|
-
if (!cwd || !path72.isAbsolute(file3) || !path72.isAbsolute(cwd)) return file3;
|
|
46406
|
-
const relative3 = path72.relative(cwd, file3);
|
|
46407
|
-
return relative3 && relative3 !== ".." && !relative3.startsWith(`..${path72.sep}`) && !path72.isAbsolute(relative3) ? relative3.split(path72.sep).join("/") : file3;
|
|
46408
|
-
}
|
|
46409
|
-
function approvalSummary(value2) {
|
|
46410
|
-
const input2 = fields(value2.input), tool = value2.tool ?? "";
|
|
46411
|
-
let line, requestKind = "other";
|
|
46412
|
-
if (value2.question || /^AskUserQuestion$/i.test(tool)) {
|
|
46413
|
-
const questions = Array.isArray(input2.questions) ? input2.questions : [];
|
|
46414
|
-
line = string4(fields(questions[0]).question) ?? string4(input2.question) ?? string4(input2.message) ?? value2.message;
|
|
46415
|
-
if (line) requestKind = "question";
|
|
46416
|
-
} else {
|
|
46417
|
-
const messageCommand = /^(?:bash|shell):\s*(.+)$/is.exec(value2.message ?? "")?.[1];
|
|
46418
|
-
const shown = tool === "Question" ? dialogCommand(value2.message) : void 0;
|
|
46419
|
-
const command = commandText3(input2.command ?? input2.cmd ?? input2.commandLine ?? (Array.isArray(value2.input) ? value2.input : void 0)) ?? messageCommand ?? shown;
|
|
46420
|
-
if (command && (shown !== void 0 || /^(?:Bash|Shell|exec_command|functions\.shell|bash|shell)$/i.test(tool) || input2.command !== void 0 || input2.cmd !== void 0 || input2.commandLine !== void 0)) {
|
|
46421
|
-
line = `Run: ${command}`;
|
|
46422
|
-
requestKind = "command";
|
|
46423
|
-
} else {
|
|
46424
|
-
const mcp = /^mcp__(.+?)__(.+)$/.exec(tool);
|
|
46425
|
-
const sentence = /Allow the ([\w.-]+) MCP server to run tool ([\w.-]+)\?/i.exec(value2.message ?? string4(input2.description) ?? "");
|
|
46426
|
-
const server = mcp?.[1] ?? string4(input2.serverName) ?? string4(input2.server_name) ?? string4(input2.mcpServerName) ?? string4(input2.server) ?? sentence?.[1];
|
|
46427
|
-
const name = mcp?.[2] ?? string4(input2.toolName) ?? string4(input2.tool_name) ?? string4(input2.mcpToolName) ?? string4(input2.tool) ?? sentence?.[2];
|
|
46428
|
-
if (server && name) {
|
|
46429
|
-
line = `${server} MCP: ${name}`;
|
|
46430
|
-
requestKind = "tool";
|
|
46431
|
-
} else {
|
|
46432
|
-
const patch = string4(input2.patch) ?? (typeof value2.input === "string" ? value2.input : void 0);
|
|
46433
|
-
const changed2 = patch ? new Set([...patch.matchAll(/^\*\*\* (?:Add|Update|Delete) File: (.+)$|^diff --git a\/(.+?) b\/(.+)$/gm)].map((match) => match[1] ?? match[3])).size : 0;
|
|
46434
|
-
const file3 = string4(input2.file_path) ?? string4(input2.filePath) ?? string4(input2.path);
|
|
46435
|
-
if (changed2 > 1) line = `Apply patch: ${changed2} files`;
|
|
46436
|
-
else if (file3 && /(?:edit|write|patch|apply)/i.test(tool)) line = `${/write/i.test(tool) || /\*\*\* Add File:/.test(patch ?? "") ? "Write" : "Edit"}: ${relativeFile(file3, value2.cwd)}`;
|
|
46437
|
-
else if (changed2 === 1 && patch) {
|
|
46438
|
-
const match = /^\*\*\* (Add|Update|Delete) File: (.+)$/m.exec(patch);
|
|
46439
|
-
line = match ? `${match[1] === "Add" ? "Write" : "Edit"}: ${relativeFile(match[2], value2.cwd)}` : "Apply patch: 1 file";
|
|
46440
|
-
}
|
|
46441
|
-
if (line) requestKind = "edit";
|
|
46442
|
-
else {
|
|
46443
|
-
const primary = string4(input2.path) ?? string4(input2.file_path) ?? string4(input2.pattern) ?? string4(input2.query) ?? string4(input2.description) ?? string4(input2.question) ?? string4(input2.message) ?? value2.message;
|
|
46444
|
-
if (primary && tool === "Question") {
|
|
46445
|
-
line = primary;
|
|
46446
|
-
requestKind = "question";
|
|
46447
|
-
} else if (primary) {
|
|
46448
|
-
const argument = tool && primary.toLowerCase().startsWith(`${tool.toLowerCase()}:`) ? primary.slice(tool.length + 1).trimStart() : primary;
|
|
46449
|
-
line = `${tool && tool !== "action" ? tool : "Request"}: ${argument}`;
|
|
46450
|
-
requestKind = "tool";
|
|
46451
|
-
} else if (tool && tool !== "action") {
|
|
46452
|
-
line = tool;
|
|
46453
|
-
requestKind = "tool";
|
|
46454
|
-
}
|
|
46455
|
-
}
|
|
46456
|
-
}
|
|
46457
|
-
}
|
|
46458
|
-
}
|
|
46459
|
-
const request9 = line ? shortApproval(line) : fallback;
|
|
46460
|
-
return { request: request9 || fallback, requestKind: line ? requestKind : "other" };
|
|
46461
|
-
}
|
|
46462
|
-
|
|
46463
|
-
// src/bridge/push.ts
|
|
46464
46591
|
var relaySchema = external_exports.object({
|
|
46465
46592
|
url: external_exports.string().url().refine(
|
|
46466
46593
|
(value2) => /^https:\/\//.test(value2) || /^http:\/\/(127\.0\.0\.1|localhost)(:\d+)?\//.test(`${value2}/`),
|
|
@@ -46658,10 +46785,10 @@ var APNsSender = class {
|
|
|
46658
46785
|
const authority = device.environment === "production" ? "https://api.push.apple.com" : "https://api.sandbox.push.apple.com";
|
|
46659
46786
|
return new Promise((resolve11) => {
|
|
46660
46787
|
const client = connect3(authority);
|
|
46661
|
-
let
|
|
46788
|
+
let settled3 = false;
|
|
46662
46789
|
const finish = (ok) => {
|
|
46663
|
-
if (
|
|
46664
|
-
|
|
46790
|
+
if (settled3) return;
|
|
46791
|
+
settled3 = true;
|
|
46665
46792
|
client.close();
|
|
46666
46793
|
resolve11(ok);
|
|
46667
46794
|
};
|
|
@@ -47464,7 +47591,11 @@ function promptKey(text4) {
|
|
|
47464
47591
|
return unwrapPastedContent(text4).split("\n").filter((line) => !PICTURE_PATH_LINE.test(line)).join("\n").replace(/\[Image #\d+\]/g, " ").replace(/\s+/g, " ").trim();
|
|
47465
47592
|
}
|
|
47466
47593
|
var PICTURE_PATH_LINE = /^\s*\/.*\.(?:png|jpe?g|gif|webp)\s*$/i;
|
|
47467
|
-
var
|
|
47594
|
+
var promptHash = (text4) => createHash23("sha256").update(promptKey(text4)).digest("hex");
|
|
47595
|
+
function projectField(cwd) {
|
|
47596
|
+
const project = paneProject(cwd, phrenStoreRoot());
|
|
47597
|
+
return project ? { project } : {};
|
|
47598
|
+
}
|
|
47468
47599
|
var AgentHooks = class {
|
|
47469
47600
|
constructor(push = new ApprovalPushService(), modules) {
|
|
47470
47601
|
this.push = push;
|
|
@@ -47492,13 +47623,13 @@ var AgentHooks = class {
|
|
|
47492
47623
|
modules;
|
|
47493
47624
|
changes = new ToolChanges();
|
|
47494
47625
|
pending = /* @__PURE__ */ new Map();
|
|
47495
|
-
/** Prompts Phren has typed into a pane, by their
|
|
47626
|
+
/** Prompts Phren has typed into a pane, by a hash of their words, until the agent that
|
|
47496
47627
|
* actually receives one reports in through UserPromptSubmit. Herdr writes
|
|
47497
47628
|
* to a pane, not a conversation; the receiving agent's hook is the only
|
|
47498
47629
|
* party that knows which conversation consumed the text, so it is the one
|
|
47499
47630
|
* that can refuse it when that is not the conversation the phone meant. */
|
|
47500
47631
|
deliveries = /* @__PURE__ */ new Map();
|
|
47501
|
-
/** Phone messages by delivery id, until TRACK_MS: see `
|
|
47632
|
+
/** Phone messages by delivery id, until TRACK_MS: see `queueDelivery`. */
|
|
47502
47633
|
tracked = /* @__PURE__ */ new Map();
|
|
47503
47634
|
/** The permission request a conversation is drawing in its own terminal
|
|
47504
47635
|
* because nobody was there to hold it: what the phone shows above its
|
|
@@ -47626,7 +47757,7 @@ var AgentHooks = class {
|
|
|
47626
47757
|
provider: "opencode",
|
|
47627
47758
|
question: false,
|
|
47628
47759
|
expiresAt: String(request9.expiresAt),
|
|
47629
|
-
...
|
|
47760
|
+
...projectField(cwd),
|
|
47630
47761
|
computer: this.computerName,
|
|
47631
47762
|
...summary
|
|
47632
47763
|
}).then((delivered) => {
|
|
@@ -47925,12 +48056,14 @@ var AgentHooks = class {
|
|
|
47925
48056
|
* text, "blocked" if another conversation in the pane tried to, or "pending"
|
|
47926
48057
|
* after `waitMs`: a busy agent queues typed input and submits it only when
|
|
47927
48058
|
* its turn ends, so the record outlives the wait (up to ten minutes) and a
|
|
47928
|
-
* late submission to the wrong conversation is still refused.
|
|
47929
|
-
|
|
47930
|
-
|
|
47931
|
-
if (!
|
|
48059
|
+
* late submission to the wrong conversation is still refused. A phone
|
|
48060
|
+
* message's `id` follows the record, so its outcome lands on that id. */
|
|
48061
|
+
expectDelivery(target, text4, waitMs = 1500, signal, id2) {
|
|
48062
|
+
if (!promptKey(text4) || signal?.aborted) return Promise.resolve("pending");
|
|
48063
|
+
const key3 = promptHash(text4);
|
|
48064
|
+
if (id2) this.track(id2, target, "typed");
|
|
47932
48065
|
return new Promise((resolve11) => {
|
|
47933
|
-
let
|
|
48066
|
+
let settled3 = false;
|
|
47934
48067
|
const list = this.deliveries.get(key3) ?? [];
|
|
47935
48068
|
const remove = () => {
|
|
47936
48069
|
signal?.removeEventListener("abort", cancel);
|
|
@@ -47940,16 +48073,17 @@ var AgentHooks = class {
|
|
|
47940
48073
|
if (!current2.length) this.deliveries.delete(key3);
|
|
47941
48074
|
};
|
|
47942
48075
|
const settle2 = (outcome) => {
|
|
47943
|
-
if (!
|
|
47944
|
-
|
|
48076
|
+
if (!settled3) {
|
|
48077
|
+
settled3 = true;
|
|
47945
48078
|
resolve11(outcome);
|
|
47946
48079
|
} else if (outcome !== "pending") delivery.late?.(outcome);
|
|
47947
48080
|
if (outcome !== "pending") {
|
|
47948
48081
|
clearTimeout(delivery.timer);
|
|
47949
48082
|
remove();
|
|
48083
|
+
this.settleTracked(delivery, outcome);
|
|
47950
48084
|
}
|
|
47951
48085
|
};
|
|
47952
|
-
const delivery = { source: target.source, session: target.session, settle: settle2, timer: setTimeout(() => settle2("pending"), waitMs) };
|
|
48086
|
+
const delivery = { source: target.source, session: target.session, ...id2 ? { id: id2 } : {}, settle: settle2, timer: setTimeout(() => settle2("pending"), waitMs) };
|
|
47953
48087
|
const cancel = () => {
|
|
47954
48088
|
clearTimeout(delivery.timer);
|
|
47955
48089
|
settle2("pending");
|
|
@@ -47966,12 +48100,12 @@ var AgentHooks = class {
|
|
|
47966
48100
|
}
|
|
47967
48101
|
/** A prompt Phren typed into `target` that its conversation has not submitted yet. */
|
|
47968
48102
|
deliveryPending(target, text4) {
|
|
47969
|
-
return !!this.deliveries.get(
|
|
48103
|
+
return !!this.deliveries.get(promptHash(text4))?.some((entry2) => entry2.source === target.source && entry2.session === target.session);
|
|
47970
48104
|
}
|
|
47971
48105
|
/** Wait again for a delivery `expectDelivery` already reported pending,
|
|
47972
48106
|
* after the Hook pressed Enter a second time. */
|
|
47973
48107
|
awaitLateDelivery(target, text4, waitMs = 2500) {
|
|
47974
|
-
const delivery = this.deliveries.get(
|
|
48108
|
+
const delivery = this.deliveries.get(promptHash(text4))?.find((entry2) => entry2.source === target.source && entry2.session === target.session);
|
|
47975
48109
|
if (!delivery) return Promise.resolve("pending");
|
|
47976
48110
|
return new Promise((resolve11) => {
|
|
47977
48111
|
const timer = setTimeout(() => {
|
|
@@ -47986,29 +48120,37 @@ var AgentHooks = class {
|
|
|
47986
48120
|
};
|
|
47987
48121
|
});
|
|
47988
48122
|
}
|
|
47989
|
-
|
|
47990
|
-
* is tracked only while its typed record still waits for the agent's hook,
|
|
47991
|
-
* so the hook's later answer always reaches it (`settleTracked`). */
|
|
47992
|
-
trackDelivery(id2, target, text4, state) {
|
|
47993
|
-
if (state === "queued" && !this.deliveryPending(target, text4)) return;
|
|
48123
|
+
track(id2, target, state) {
|
|
47994
48124
|
const now = Date.now();
|
|
47995
48125
|
for (const [key3, entry2] of this.tracked) if (now - entry2.at > TRACK_MS) this.tracked.delete(key3);
|
|
47996
48126
|
while (this.tracked.size >= 512) this.tracked.delete(this.tracked.keys().next().value);
|
|
47997
|
-
this.tracked.set(id2, { source: target.source, session: target.session,
|
|
48127
|
+
this.tracked.set(id2, { source: target.source, session: target.session, state, at: now });
|
|
48128
|
+
}
|
|
48129
|
+
/** The Hook answered the phone message `id` as queued: its typed record
|
|
48130
|
+
* still waits for the agent's hook, which settles it by this id. */
|
|
48131
|
+
queueDelivery(id2, target) {
|
|
48132
|
+
const entry2 = this.tracked.get(id2);
|
|
48133
|
+
if (entry2?.state === "typed" && entry2.source === target.source && entry2.session === target.session) entry2.state = "queued";
|
|
47998
48134
|
}
|
|
47999
48135
|
/** What became of the phone message `id` sent to `target`'s conversation:
|
|
48000
48136
|
* queued until the agent submits it, then delivered, or blocked when
|
|
48001
|
-
* another conversation in the pane took it. Unknown
|
|
48002
|
-
*
|
|
48137
|
+
* another conversation in the pane took it. Unknown while the Hook has not
|
|
48138
|
+
* answered it, for another conversation, or older than TRACK_MS. A
|
|
48139
|
+
* message answered uncertain still turns delivered once its hook takes it. */
|
|
48003
48140
|
deliveryState(id2, target) {
|
|
48004
48141
|
const entry2 = this.tracked.get(id2);
|
|
48005
|
-
return entry2 && entry2.source === target.source && entry2.session === target.session && Date.now() - entry2.at <= TRACK_MS ? entry2.state : "unknown";
|
|
48142
|
+
return entry2 && entry2.state !== "typed" && entry2.source === target.source && entry2.session === target.session && Date.now() - entry2.at <= TRACK_MS ? entry2.state : "unknown";
|
|
48006
48143
|
}
|
|
48007
|
-
/**
|
|
48008
|
-
|
|
48009
|
-
|
|
48010
|
-
|
|
48011
|
-
|
|
48144
|
+
/** Every known phone message to `target`'s conversation, for its stream. */
|
|
48145
|
+
deliveriesFor(target) {
|
|
48146
|
+
return [...this.tracked.keys()].map((deliveryId) => ({ deliveryId, state: this.deliveryState(deliveryId, target) })).filter((item) => item.state !== "unknown");
|
|
48147
|
+
}
|
|
48148
|
+
settleTracked(delivery, outcome) {
|
|
48149
|
+
const entry2 = delivery.id ? this.tracked.get(delivery.id) : void 0;
|
|
48150
|
+
if (entry2 && entry2.source === delivery.source && entry2.session === delivery.session) {
|
|
48151
|
+
entry2.state = outcome;
|
|
48152
|
+
entry2.at = Date.now();
|
|
48153
|
+
}
|
|
48012
48154
|
}
|
|
48013
48155
|
/** The conversation `target` just submitted `prompt`. Nothing Phren typed
|
|
48014
48156
|
* matches: a locally typed prompt, always allowed. Otherwise the oldest
|
|
@@ -48016,11 +48158,10 @@ var AgentHooks = class {
|
|
|
48016
48158
|
* conversation is told to drop it, so the text is never spoken to the
|
|
48017
48159
|
* wrong agent and the phone can safely send it again. */
|
|
48018
48160
|
submitted(target, prompt) {
|
|
48019
|
-
const list = this.deliveries.get(
|
|
48161
|
+
const list = this.deliveries.get(promptHash(prompt));
|
|
48020
48162
|
const delivery = list?.find((entry2) => entry2.source === target.source && entry2.session === target.session) ?? list?.[0];
|
|
48021
48163
|
if (!delivery) return {};
|
|
48022
48164
|
const own2 = delivery.source === target.source && delivery.session === target.session;
|
|
48023
|
-
this.settleTracked(delivery, prompt, own2 ? "delivered" : "blocked");
|
|
48024
48165
|
if (own2) {
|
|
48025
48166
|
delivery.settle("delivered");
|
|
48026
48167
|
return {};
|
|
@@ -48626,7 +48767,7 @@ var AgentHooks = class {
|
|
|
48626
48767
|
provider: target.source,
|
|
48627
48768
|
question: entry2.tool === "AskUserQuestion",
|
|
48628
48769
|
expiresAt: new Date(expiresAt).toISOString(),
|
|
48629
|
-
...
|
|
48770
|
+
...projectField(cwd),
|
|
48630
48771
|
computer: this.computerName,
|
|
48631
48772
|
...summary
|
|
48632
48773
|
}).then((delivered) => {
|
|
@@ -48854,7 +48995,7 @@ ${target.source}`) ?? 0) > Date.now();
|
|
|
48854
48995
|
provider: "codex",
|
|
48855
48996
|
question: false,
|
|
48856
48997
|
expiresAt: new Date(expiresAt).toISOString(),
|
|
48857
|
-
...
|
|
48998
|
+
...projectField(cwd),
|
|
48858
48999
|
computer: this.computerName,
|
|
48859
49000
|
...summary
|
|
48860
49001
|
}).then((delivered) => {
|
|
@@ -49041,7 +49182,7 @@ ${target.source}`) ?? 0) > Date.now();
|
|
|
49041
49182
|
provider: target.source,
|
|
49042
49183
|
question: body2.tool === "AskUserQuestion",
|
|
49043
49184
|
expiresAt: new Date(pushExpiresAt).toISOString(),
|
|
49044
|
-
...
|
|
49185
|
+
...projectField(cwd),
|
|
49045
49186
|
computer: this.computerName,
|
|
49046
49187
|
...summary
|
|
49047
49188
|
}).catch(() => false).then((delivered) => {
|
|
@@ -50380,7 +50521,7 @@ async function submitStartingPrompt(server, target, terminal2, looks = 4, interv
|
|
|
50380
50521
|
return "unknown";
|
|
50381
50522
|
}
|
|
50382
50523
|
};
|
|
50383
|
-
const
|
|
50524
|
+
const settled3 = async () => {
|
|
50384
50525
|
for (let look = 0; look < looks; look++) {
|
|
50385
50526
|
await sleep4(intervalMs);
|
|
50386
50527
|
const current2 = await status();
|
|
@@ -50388,10 +50529,10 @@ async function submitStartingPrompt(server, target, terminal2, looks = 4, interv
|
|
|
50388
50529
|
}
|
|
50389
50530
|
return "idle";
|
|
50390
50531
|
};
|
|
50391
|
-
const first = await
|
|
50532
|
+
const first = await settled3();
|
|
50392
50533
|
if (first !== "idle") return first !== "gone";
|
|
50393
50534
|
await terminalProvider().sendKeys(server, target.pane, ["enter"]);
|
|
50394
|
-
const second = await
|
|
50535
|
+
const second = await settled3();
|
|
50395
50536
|
return second !== "idle" && second !== "gone";
|
|
50396
50537
|
}
|
|
50397
50538
|
function secretKeys(text4) {
|
|
@@ -50534,10 +50675,11 @@ async function paneRouteOnce(ctx, url2, data, response, typing) {
|
|
|
50534
50675
|
if (!(error62 instanceof CodexServerUnavailable)) return { ok: true, deliveryUncertain: true };
|
|
50535
50676
|
}
|
|
50536
50677
|
}
|
|
50678
|
+
const deliveryId = deliveryIdSchema.parse(data.deliveryId);
|
|
50537
50679
|
let busy = String(pane.agent_status) === "working";
|
|
50538
50680
|
let outcome = await promptWithStartupRetry(async () => {
|
|
50539
50681
|
const refused = new AbortController();
|
|
50540
|
-
const expected = agentHooks.expectDelivery(target, text4, busy && target.source !== "claude" ? 300 : 1500, refused.signal);
|
|
50682
|
+
const expected = agentHooks.expectDelivery(target, text4, busy && target.source !== "claude" ? 300 : 1500, refused.signal, deliveryId);
|
|
50541
50683
|
await typing();
|
|
50542
50684
|
try {
|
|
50543
50685
|
await terminalProvider().prompt(target.server, target.pane, text4);
|
|
@@ -50559,13 +50701,11 @@ async function paneRouteOnce(ctx, url2, data, response, typing) {
|
|
|
50559
50701
|
if (!busy) outcome = await resubmitIfIdle(agentHooks, target, text4);
|
|
50560
50702
|
else followQueuedDelivery(agentHooks, target, pane.terminal_id, text4);
|
|
50561
50703
|
}
|
|
50562
|
-
|
|
50704
|
+
const refusedHere = () => new BridgeError(409, "The conversation in this pane changed; the message was not delivered. Reopen the chat and send it again.");
|
|
50705
|
+
if (outcome === "blocked") throw refusedHere();
|
|
50563
50706
|
if (/^\/[a-z][a-z0-9_-]*$/i.test(text4.trim())) agentHooks.menuOpened(target, text4.trim());
|
|
50564
|
-
|
|
50565
|
-
if (outcome === "
|
|
50566
|
-
result = { ok: true, delivered: true };
|
|
50567
|
-
if (deliveryId) agentHooks.trackDelivery(deliveryId, target, text4, "delivered");
|
|
50568
|
-
} else if (outcome === "unsubmitted") {
|
|
50707
|
+
if (outcome === "delivered") result = { ok: true, delivered: true };
|
|
50708
|
+
else if (outcome === "unsubmitted") {
|
|
50569
50709
|
result = { ok: true, deliveryUncertain: true, unsubmitted: true };
|
|
50570
50710
|
} else {
|
|
50571
50711
|
let confirmed2 = false;
|
|
@@ -50574,8 +50714,13 @@ async function paneRouteOnce(ctx, url2, data, response, typing) {
|
|
|
50574
50714
|
confirmed2 = !!current2 && current2.terminal_id === pane.terminal_id && await paneIdentity(target.server, current2, true) === target.session;
|
|
50575
50715
|
} catch {
|
|
50576
50716
|
}
|
|
50577
|
-
|
|
50578
|
-
|
|
50717
|
+
const late = deliveryId ? agentHooks.deliveryState(deliveryId, target) : "unknown";
|
|
50718
|
+
if (late === "blocked") throw refusedHere();
|
|
50719
|
+
if (late === "delivered") result = { ok: true, delivered: true };
|
|
50720
|
+
else {
|
|
50721
|
+
if (confirmed2 && deliveryId) agentHooks.queueDelivery(deliveryId, target);
|
|
50722
|
+
result = { ok: true, ...!confirmed2 ? { deliveryUncertain: true } : { queued: true } };
|
|
50723
|
+
}
|
|
50579
50724
|
}
|
|
50580
50725
|
} else if (url2.pathname === "/v1/prompt/status") {
|
|
50581
50726
|
const id2 = deliveryIdSchema.parse(data.deliveryId);
|
|
@@ -51590,6 +51735,10 @@ var ERRORS = {
|
|
|
51590
51735
|
queue_overflow: { code: "transcribe-busy", message: "ElevenLabs is busy. Try again shortly." },
|
|
51591
51736
|
session_time_limit_exceeded: { code: "transcribe-limit", message: "This dictation reached ElevenLabs' time limit." }
|
|
51592
51737
|
};
|
|
51738
|
+
function failRelay(client) {
|
|
51739
|
+
if (client.readyState === OPEN3) client.send(JSON.stringify({ type: "error", code: "transcribe-failed", error: "Couldn't reach ElevenLabs." }));
|
|
51740
|
+
client.close(1011, "Transcription unavailable");
|
|
51741
|
+
}
|
|
51593
51742
|
function relayTranscription(client, query, options = {}) {
|
|
51594
51743
|
const connect4 = options.connect ?? ((url2, key3) => new import_websocket.default(url2, { headers: { "xi-api-key": key3 } }));
|
|
51595
51744
|
return (async () => {
|
|
@@ -51615,7 +51764,13 @@ function relayTranscription(client, query, options = {}) {
|
|
|
51615
51764
|
}
|
|
51616
51765
|
if (client.readyState === OPEN3) client.close(code, reason2);
|
|
51617
51766
|
};
|
|
51618
|
-
const
|
|
51767
|
+
const end = (reason2) => {
|
|
51768
|
+
if (!closed) tell({ type: "end", reason: reason2 });
|
|
51769
|
+
};
|
|
51770
|
+
const limit = setTimeout(() => {
|
|
51771
|
+
end("session-limit");
|
|
51772
|
+
finish(1e3, "Session limit");
|
|
51773
|
+
}, options.maxSessionMs ?? MAX_SESSION_MS2);
|
|
51619
51774
|
limit.unref?.();
|
|
51620
51775
|
const chunk = (audio, commit = false) => JSON.stringify({
|
|
51621
51776
|
message_type: "input_audio_chunk",
|
|
@@ -51647,6 +51802,7 @@ function relayTranscription(client, query, options = {}) {
|
|
|
51647
51802
|
for (const audio of pending) upstream.send(chunk(audio));
|
|
51648
51803
|
pending = [];
|
|
51649
51804
|
pendingBytes = 0;
|
|
51805
|
+
if (!closed) tell({ type: "ready" });
|
|
51650
51806
|
});
|
|
51651
51807
|
upstream.on("message", (data) => {
|
|
51652
51808
|
let message;
|
|
@@ -51670,7 +51826,10 @@ function relayTranscription(client, query, options = {}) {
|
|
|
51670
51826
|
tell({ type: "error", code: "transcribe-failed", error: "Couldn't reach ElevenLabs." });
|
|
51671
51827
|
finish(1011);
|
|
51672
51828
|
});
|
|
51673
|
-
upstream.on("close", () =>
|
|
51829
|
+
upstream.on("close", () => {
|
|
51830
|
+
end("upstream-closed");
|
|
51831
|
+
finish(1e3, "ElevenLabs closed");
|
|
51832
|
+
});
|
|
51674
51833
|
})();
|
|
51675
51834
|
}
|
|
51676
51835
|
|
|
@@ -52722,6 +52881,12 @@ function codexModeFlags(mode) {
|
|
|
52722
52881
|
const sandbox = { readOnly: "read-only", workspaceWrite: "workspace-write", dangerFullAccess: "danger-full-access" }[String(sandboxPolicy?.type)];
|
|
52723
52882
|
return ["-a", String(approvalPolicy), "-s", String(sandbox), ...approvalsReviewer === "auto_review" ? ["-c", 'approvals_reviewer="auto_review"'] : []];
|
|
52724
52883
|
}
|
|
52884
|
+
function copilotModeFlags(mode) {
|
|
52885
|
+
if (mode === "auto-edits") return ["--allow-tool=write"];
|
|
52886
|
+
if (mode === "auto") return ["--allow-all-tools"];
|
|
52887
|
+
if (mode === "full-access") return ["--allow-all"];
|
|
52888
|
+
return [];
|
|
52889
|
+
}
|
|
52725
52890
|
var MAX_PRESSES = 6;
|
|
52726
52891
|
var STEP_WAIT_MS2 = 2e3;
|
|
52727
52892
|
function settingsCapabilities(source, codexServed, claudeBypass = false) {
|
|
@@ -55584,7 +55749,7 @@ var codeNoteSchema = external_exports.object({
|
|
|
55584
55749
|
file: external_exports.string().min(1).max(4096).refine((file3) => !path97.isAbsolute(file3) && !file3.includes("\0") && !file3.split(/[\\/]/).includes("..")),
|
|
55585
55750
|
line: external_exports.number().int().positive(),
|
|
55586
55751
|
text: external_exports.string().trim().min(1).max(4500).refine((text4) => !/[\x00-\x08\x0b-\x1f\x7f]/.test(text4)),
|
|
55587
|
-
target: external_exports.union([external_exports.object({ session: sessionId }).strict(), external_exports.object({ harness: external_exports.enum(
|
|
55752
|
+
target: external_exports.union([external_exports.object({ session: sessionId }).strict(), external_exports.object({ harness: external_exports.enum(DISPATCH_HARNESSES) }).strict()]).optional()
|
|
55588
55753
|
}).strict();
|
|
55589
55754
|
var noteName = (note) => {
|
|
55590
55755
|
const name = note.name ?? note.symbol;
|
|
@@ -57299,6 +57464,34 @@ function blobSha(content) {
|
|
|
57299
57464
|
async function isRepository2(store) {
|
|
57300
57465
|
return await lstat31(path105.join(store, ".git")).catch(() => void 0) !== void 0;
|
|
57301
57466
|
}
|
|
57467
|
+
function githubStoreRepository(remote) {
|
|
57468
|
+
let host, pathname;
|
|
57469
|
+
const scp = /^(?:[^@/\s]+@)?github\.com:([^\s]+)$/i.exec(remote.trim());
|
|
57470
|
+
if (scp) {
|
|
57471
|
+
host = "github.com";
|
|
57472
|
+
pathname = scp[1];
|
|
57473
|
+
} else {
|
|
57474
|
+
try {
|
|
57475
|
+
const url2 = new URL(remote.trim());
|
|
57476
|
+
if (!["https:", "ssh:"].includes(url2.protocol) || url2.search || url2.hash) return void 0;
|
|
57477
|
+
host = url2.hostname;
|
|
57478
|
+
pathname = url2.pathname.replace(/^\//, "");
|
|
57479
|
+
} catch {
|
|
57480
|
+
return void 0;
|
|
57481
|
+
}
|
|
57482
|
+
}
|
|
57483
|
+
if (host.toLowerCase() !== "github.com") return void 0;
|
|
57484
|
+
const repository3 = pathname.replace(/\/$/, "").replace(/\.git$/i, "");
|
|
57485
|
+
return /^[A-Za-z0-9][A-Za-z0-9-]*\/[A-Za-z0-9_.-]+$/.test(repository3) ? repository3.toLowerCase() : void 0;
|
|
57486
|
+
}
|
|
57487
|
+
async function storeRepositoryIdentity(store) {
|
|
57488
|
+
const [remote, branch] = await Promise.all([
|
|
57489
|
+
git5(store, ["config", "--get", "remote.origin.url"]).catch(() => ""),
|
|
57490
|
+
git5(store, ["symbolic-ref", "--quiet", "--short", "HEAD"]).catch(() => "")
|
|
57491
|
+
]);
|
|
57492
|
+
const repository3 = githubStoreRepository(remote);
|
|
57493
|
+
return repository3 && branch.trim() ? { repository: repository3, branch: branch.trim() } : void 0;
|
|
57494
|
+
}
|
|
57302
57495
|
function storeHead(store, indexFile = path105.join(bridgeRoot(), "store-snapshot.index")) {
|
|
57303
57496
|
return serialized2(async () => {
|
|
57304
57497
|
if (!await isRepository2(store)) throw new BridgeError(409, "This computer's phren store is not a git repository. Run phren init.");
|
|
@@ -57309,7 +57502,9 @@ function storeHead(store, indexFile = path105.join(bridgeRoot(), "store-snapshot
|
|
|
57309
57502
|
await git5(store, head.trim() ? ["read-tree", "HEAD"] : ["read-tree", "--empty"], env);
|
|
57310
57503
|
}
|
|
57311
57504
|
await git5(store, ["add", "--all", "--", "."], env);
|
|
57312
|
-
|
|
57505
|
+
const sha = (await git5(store, ["write-tree"], env)).trim();
|
|
57506
|
+
const repositoryIdentity = await storeRepositoryIdentity(store);
|
|
57507
|
+
return { sha, ...repositoryIdentity ? { repositoryIdentity } : {} };
|
|
57313
57508
|
});
|
|
57314
57509
|
}
|
|
57315
57510
|
async function storeTree(store, sha) {
|
|
@@ -57325,7 +57520,13 @@ async function storeTree(store, sha) {
|
|
|
57325
57520
|
async function storeBlob(store, sha) {
|
|
57326
57521
|
if (!SHA.test(sha)) throw new BridgeError(400, "Invalid blob sha.");
|
|
57327
57522
|
if ((await git5(store, ["cat-file", "-t", sha]).catch(() => "")).trim() !== "blob") throw new BridgeError(404, "Unknown blob.");
|
|
57328
|
-
const
|
|
57523
|
+
const size = Number((await git5(store, ["cat-file", "-s", sha])).trim());
|
|
57524
|
+
if (size > MAX_FILE) throw new BridgeError(
|
|
57525
|
+
413,
|
|
57526
|
+
"This store file exceeds the phone's 4 MiB limit. Archive or shorten it on the computer, then sync again.",
|
|
57527
|
+
{ code: "store-file-too-large", size, limit: MAX_FILE }
|
|
57528
|
+
);
|
|
57529
|
+
const { stdout } = await exec19("git", ["-C", store, "cat-file", "blob", sha], { encoding: "buffer", maxBuffer: MAX_FILE, timeout: 6e4 });
|
|
57329
57530
|
return { sha, encoding: "base64", content: stdout.toString("base64") };
|
|
57330
57531
|
}
|
|
57331
57532
|
async function storeFile(store, relative3) {
|
|
@@ -57976,7 +58177,7 @@ var launchKinds = ["codex", "claude", "copilot", "opencode", "phren"];
|
|
|
57976
58177
|
var plainText = (max) => external_exports.string().min(1).max(max).refine((t) => !/[\x00-\x1f\x7f]/.test(t));
|
|
57977
58178
|
async function conductorBrief() {
|
|
57978
58179
|
let source;
|
|
57979
|
-
if (true) source = '---\nname: conductor\ndescription: Coordinate independent Phren tasks across every project in the store and every enrolled computer, supervise their local agent fanout, and integrate verified returns in a concise dispatcher voice.\n---\n\n# Conductor\n\nYou are the owner\'s dispatcher for the whole store, not one project. You start\nin the phren store itself; that folder is not a project and not your work.\n\nFirst, before trusting your tools, check which phren you are running:\n`phren --version` and `command -v phren`. If the version is older than the one\nthe store or the owner expects, or the path is not the install you expect (a\nstale global package, an old checkout), tell the owner in one line and say\nwhich tools may be missing or behave differently.\n\nThen read the relevant projects\' summaries and Phren tasks\n(`get_project_summary`, `get_tasks`) before selecting work.\n\nYour tools, use these instead of exploring the CLI or the Hook\'s files:\n\n- `live_sessions` (CLI `phren dispatch sessions`): every live agent on this\n computer and each enrolled one, with project, harness, status, `idleFor`\n (seconds since it last changed) and the target `hand_off` takes. Start here\n when asked what is running. Computers it could not reach are listed; say so\n rather than guessing. Computers in `notLinked` are registered in the store\n but have no Hook link here: say they were not checked, never that nothing is\n running there.\n- `hand_off`: send a prompt to one of those sessions.\n- `account_usage` (CLI `phren dispatch usage`): every computer\'s agent usage\n merged by account (each Claude login, Codex, OpenCode Go and the rest): percent\n left on each window, when it resets, whether the numbers are fresh, and the\n computers where it is signed in. In core use\n `phren_admin(action: "account_usage")`.\n- `hand_off`: send a prompt to one of those sessions. A busy session queues it\n durably in its Hook. Keep its `deliveryId`; `queued` means waiting, `delivered`\n means confirmed. Check with `hand_off(target|session, computer?, deliveryId,\n status:true)` and no text. Never resend with a new id because it is busy.\n- `dispatch`: start a new worker on a computer (or `anywhere`).\n- `dispatch_returns` (CLI `phren dispatch returns`): what your workers sent\n back since you last asked: done with the final reply, needs-you with the\n question, stalled with an unchanged screen and transcript, failed with the error (a usage limit), blocked, or gone. Reading them marks them read. In core use\n `phren_admin(action: "dispatch_returns")`.\n- `dispatch_report`: workers record `prs`, an array of `{url, repo, branch,\n tests, notes?}`, on their own Hook before ending the turn. The done return\n carries that evidence, and the Hook queues it to the configured integrator.\n In core use `phren_admin(action: "dispatch_report", prs)`.\n- `owner_inbox` (CLI `phren owner-inbox`): list what waits on the owner across\n linked computers, add a title with optional project, or resolve an id with\n optional resolution. In core use `phren_admin(action: "owner_inbox", ...)`.\n Use an item\'s `inboxComputer` as `computer` when resolving a remote item;\n omit it for `local`. Say which computers were unreachable.\n- `phren dispatch status`: receipts of what you dispatched.\n- `get_tasks`, `get_project_summary`, `search_knowledge`: the store\'s memory.\n\nKeep engineering detail in worker briefs, Phren tasks and findings, and review\nartifacts, not in the owner\'s chat.\n\n## Voice and pace\n\nThe owner talks to you from the phone, often in talk mode, where your replies\nare read aloud in their voice. Sound like a good dispatcher: short, quick and\nconversational.\n\n- Lead with the outcome in one sentence. Keep the whole reply to one to four\n short sentences unless the owner asks for detail.\n- No tables, file paths, SHAs, PR numbers or run IDs in a reply unless the\n owner asks for them. Record them in Phren tasks and findings instead.\n- One short line per dispatch or return: who, what, result. A routine watcher\n or monitor event where nothing changed gets silence or a single line.\n- When the owner gives you a task, dispatch an engineer for it right away and\n say so in one line. That is the owner\'s standing rule; do not ask first.\n- Ask at most one question at a time, and name the options.\n- Delegate reading and analysis to workers instead of running long\n investigations yourself, so your own turns stay fast.\n- A message that begins with `[voice]` was spoken in talk mode, and your reply\n will be read aloud. Answer in one or two spoken sentences with no markdown,\n lists, symbols or code, written to sound natural read aloud: "back in about\n twenty minutes", not "ETA ~20m".\n\n```text\nLinuxbox has the parser checks on Codex, back around two twenty.\nDesk finished the navigation checks: tests passed, not merged yet.\n```\n\nIf a result or return time is unknown, say so. Surface a worker\'s question in\nthe same short voice, with the worker\'s own choices.\n\n## Dispatching\n\nPick five to ten independent tasks when that many are available and capacity\npermits. Do not manufacture tasks to fill the batch. Separate dependencies and\nfile ownership; give each remote lead a base revision, acceptance checks, local\nfanout limit, report time and integration instructions. Every brief repeats the\nowner\'s repository constraints, including any prohibition on commits, pushes,\nbranches or particular tests. Dispatch never expands the owner\'s authorization.\nA worker that needs root runs `sudo -A <command>`: its launch sets\n`SUDO_ASKPASS`, and the owner approves the exact command and types the\npassword on the phone. Plain `sudo` fails without a terminal.\n\nYou are the one conductor for this computer and every computer linked with\nit; a second conductor in the group is refused at launch. Conductors on\ncomputers that are not linked share only the store, so claim a task before you\ndispatch it: `claim_task` (in core, `manage_task` with `action: "claim"`).\nSkip tasks marked `[claimed: <computer>]` by another computer. A claim that\ncomes back not claimed, with `heldBy`, means another conductor got there first:\nmove on. Completing a task clears its claim; release one you will not do. Start\nworkers with `dispatch` or `hand_off`, never as tabs in your own Herdr\nworkspace. When a computer shows up in `notLinked`, tell the owner that\n`phren bridge link <host>` can link it; never link a computer yourself.\n\nPrefer Codex. Use OpenCode Go when its account and harness are connected. Use\nOpenRouter only when the owner explicitly requests it; an unavailable account\ndoes not authorize another paid provider. Name an explicit model when instructed,\notherwise use and report the remote configured default. Each remote lead owns\nits local checkouts, fanout and provider rate limits. Where installed, local\nworkers use the fanout wrapper\'s `scripts/run.sh --provider codex|opencode\n--label --worktree [--model] [--mode]` contract and parent-bound manifests.\nTell every lead the same: a worker started any other way (its own `opencode\nrun` or `codex exec`, a launch script, nohup) has no manifest, so the phone and\nyou cannot see, resume or review it. Workers that exist only as processes do\nnot count as dispatched.\n\nCheck `account_usage` before you dispatch, once per batch. The one hard rule:\nnever dispatch to an account that is `exhausted` (a window at 100%, or\nrefusing requests), until its `availableIn` passes. Low quota is information,\nnot a reason to steer away: `nearLimit` (under 20% left) is still usable, and\nthe owner often wants quota used up before it resets, so an account with quota\nleft that resets soon is a good pick; use it before it resets. For Claude, pass\nthe `account` id the row\'s `computers` list gives for the computer you pick. A\n`stale` row\'s numbers may be out of date, and a window marked `reset` has\nrolled over with no new number yet: say so rather than quoting them. Name the\nchoice in the dispatch line, such as "Desk has the parser checks on Codex,\nusing its last 15% before the week resets tomorrow." When every account is\nexhausted, tell the owner before dispatching. The owner\'s explicit choice of\nharness or account always wins. Usage on `unreachable` and `notLinked`\ncomputers is unknown, not zero.\n\nPrefer handing work to a session that already owns the project and is idle or\ndoing related work; call `hand_off` in full or `phren_admin(action: "hand_off",\ncomputer?, target|session, text)` in core. Otherwise dispatch a new worker.\nWrite one short line either way. Call `dispatch` in full or\n`phren_admin(action: "dispatch", computer, project, harness, model?, effort?, permissionMode?, prompt, label)`\nin core. The CLI equivalent is `phren dispatch <computer|anywhere> <project>\n--harness <harness> --label <label> --prompt <brief> [--model <model>] [--effort <effort>]\n[--permission-mode supervised|auto-edits|auto|full-access]`. `permissionMode` sets how the\nworker starts (Claude and Codex only).\nFor release work (merge, publish, deploy, app-store, github-admin), read the\nowner\'s release authority policy first with `authority` in full or\n`phren_admin(action: "authority", project)` in core (CLI: `phren authority show\n<project>`), quote its `line` in the brief, and list the actions in\n`releaseActions`. An ask-first action is refused until the owner confirms it:\nask them, and never confirm or change the policy yourself. The policy only\nrestricts; when a worker\'s own harness still refuses release work, only the\nowner\'s own harness settings can allow it.\n`anywhere` chooses the connected computer with the fewest working agents, and\nskips one whose account for that harness is exhausted. Place\nbriefs sequentially, respecting busy/rate-limit responses. Keep their dispatch\nIDs. Do not send local filesystem paths as remote project names.\n\nConfigure the integrator once with `phren conductor integrator --session <id>\n[--computer <name>]`; list with `phren conductor integrator`, clear with\n`--clear`. A dispatch can override it with `integrator: {computer?, target}`.\nThe integrator\'s full target is bound to that conversation. Workers report\nstructured PR evidence with `dispatch_report(prs)` in full or\n`phren_admin(action:"dispatch_report", prs)` in core before finishing; they do not\nneed direct messaging or a GitHub comment to reach it. Inspect `prs` and\n`integratorDelivery` in receipts and verify the evidence before integration.\n\nFinished worker panes close after their done return is read. Use\n`closeOnFinish:false` (`--keep-open` in the CLI) for a worker you will reuse.\nThe Hook rechecks its ended turn and skips a pane with new work, background\ntasks, queued messages or uncertain delivery. Intentional closes do not return\n`gone`. Reading returns can close panes, so record any follow-up first.\n\nKeep one owner inbox item for each decision or action that waits on the owner.\nNeeds-you returns and blocked prompts appear automatically, even if their\nreturns were read. Add other actions such as restarting the router with\n`owner_inbox(operation:"add", title, project?, id?)` in full or\n`phren_admin(action:"owner_inbox", operation:"add", title, project?, id?)` in\ncore; keep the id on retries.\nResolve an item only once the owner decided or completed the action. Resolution\ndoes not send an answer, approve a prompt, or mark a task complete. Send an\nowner\'s answer separately with queued `hand_off`. A source that stopped waiting\nis retained as `live:false` until resolved; a resolved source stays resolved.\n\n`accepted` on a receipt is prompt acceptance, not worker completion. Returns\narrive on their own: the Hook follows every worker you dispatch, and when you\nare idle it types one line into this session, such as `Return: Linuxbox parser\nchecks done, tests passed (dispatch <id>). Call dispatch_returns.` When you see\none, call `dispatch_returns` and report each return in one short line. You may\nalso call it whenever you want the current state; do not poll it in a loop, and\ndo not read remote transcripts by hand to learn whether a worker finished. Tell\nthe owner a return time as an expectation, not a promise.\n\nA return with an `approval` is a permission request a worker is waiting on.\nAnswer it with `dispatch_approve` when it is plainly what the brief asked for;\ndeny when unsure and ask the owner. Standing grants already answer `dispatch`\nand `hand_off` requests they cover.\n\nFor a `needs-you` return, surface the worker\'s question in the owner\'s chat\nwith its choices as the worker wrote them; do not rewrite or answer it for the\nowner unless the owner already decided. Send the answer back with `hand_off`\nto the row\'s `target`. A `blocked` worker waits on terminal input, such as a\npermission prompt: say so and point the owner to the phone or the terminal. A\n`gone` worker\'s pane closed or was taken over: say so, and decide with the\nowner before giving its work to another agent. A `done` reply is the worker\'s\nown account; check its evidence before saying tests passed or work merged.\n\nA `stalled` return or `live_sessions` row with `stalled:true` means both the\nscreen and transcript have stopped changing while working. Check it and report\nwhat is known; do not launch a duplicate or interrupt it just because of the flag.\n\nAn uncertain delivery is never retried automatically. Inspect its known target\nor status before deciding with the owner whether a replacement is needed. Keep\nunavailable workers visible instead of giving their work to another agent\nwhile the original may still be running.\n\nIntegrate returned changes in dependency order within the owner\'s allowed\nworkflow. Run a cleanup pass across the combined result and the affected checks.\nRequire evidence before saying tests passed or merged. Ship only within existing\nauthorization; if publication is not authorized, return the reviewable result.\nUpdate Phren tasks when verified complete and save durable decisions. A worker\'s\nfinished turn alone does not complete the owner\'s task.\n';
|
|
58180
|
+
if (true) source = '---\nname: conductor\ndescription: Coordinate independent Phren tasks across every project in the store and every enrolled computer, supervise their local agent fanout, and integrate verified returns in a concise dispatcher voice.\n---\n\n# Conductor\n\nYou are the owner\'s dispatcher for the whole store, not one project. You start\nin the phren store itself; that folder is not a project and not your work.\n\nFirst, before trusting your tools, check which phren you are running:\n`phren --version` and `command -v phren`. If the version is older than the one\nthe store or the owner expects, or the path is not the install you expect (a\nstale global package, an old checkout), tell the owner in one line and say\nwhich tools may be missing or behave differently.\n\nThen read the relevant projects\' summaries and Phren tasks\n(`get_project_summary`, `get_tasks`) before selecting work.\n\nYour tools, use these instead of exploring the CLI or the Hook\'s files:\n\n- `live_sessions` (CLI `phren dispatch sessions`): every live agent on this\n computer and each enrolled one, with project, harness, status, `idleFor`\n (seconds since it last changed) and the target `hand_off` takes. Start here\n when asked what is running. Computers it could not reach are listed; say so\n rather than guessing. Computers in `notLinked` are registered in the store\n but have no Hook link here: say they were not checked, never that nothing is\n running there.\n- `hand_off`: send a prompt to one of those sessions.\n- `account_usage` (CLI `phren dispatch usage`): every computer\'s agent usage\n merged by account (each Claude login, Codex, OpenCode Go and the rest): percent\n left on each window, when it resets, whether the numbers are fresh, and the\n computers where it is signed in. In core use\n `phren_admin(action: "account_usage")`.\n- `hand_off`: send a prompt to one of those sessions. A busy session queues it\n durably in its Hook. Keep its `deliveryId`; `queued` means waiting, `delivered`\n means confirmed. Check with `hand_off(target|session, computer?, deliveryId,\n status:true)` and no text. Never resend with a new id because it is busy.\n- `dispatch`: start a new worker on a computer (or `anywhere`).\n- `dispatch_returns` (CLI `phren dispatch returns`): what your workers sent\n back since you last asked: done with the final reply, needs-you with the\n question, stalled with an unchanged screen and transcript, failed with the error (a usage limit), blocked, or gone. Reading them marks them read. In core use\n `phren_admin(action: "dispatch_returns")`.\n- `dispatch_report`: workers record `prs`, an array of `{url, repo, branch,\n tests, notes?}`, on their own Hook before ending the turn. The done return\n carries that evidence, and the Hook queues it to the configured integrator.\n In core use `phren_admin(action: "dispatch_report", prs)`.\n- `owner_inbox` (CLI `phren owner-inbox`): list what waits on the owner across\n linked computers, add a title with optional project, or resolve an id with\n optional resolution. In core use `phren_admin(action: "owner_inbox", ...)`.\n Use an item\'s `inboxComputer` as `computer` when resolving a remote item;\n omit it for `local`. Say which computers were unreachable.\n- `phren dispatch status`: receipts of what you dispatched.\n- `get_tasks`, `get_project_summary`, `search_knowledge`: the store\'s memory.\n\nKeep engineering detail in worker briefs, Phren tasks and findings, and review\nartifacts, not in the owner\'s chat.\n\n## Voice and pace\n\nThe owner talks to you from the phone, often in talk mode, where your replies\nare read aloud in their voice. Sound like a good dispatcher: short, quick and\nconversational.\n\n- Lead with the outcome in one sentence. Keep the whole reply to one to four\n short sentences unless the owner asks for detail.\n- No tables, file paths, SHAs, PR numbers or run IDs in a reply unless the\n owner asks for them. Record them in Phren tasks and findings instead.\n- One short line per dispatch or return: who, what, result. A routine watcher\n or monitor event where nothing changed gets silence or a single line.\n- When the owner gives you a task, dispatch an engineer for it right away and\n say so in one line. That is the owner\'s standing rule; do not ask first.\n- Ask at most one question at a time, and name the options.\n- Delegate reading and analysis to workers instead of running long\n investigations yourself, so your own turns stay fast.\n- A message that begins with `[voice]` was spoken in talk mode, and your reply\n will be read aloud. Answer in one or two spoken sentences with no markdown,\n lists, symbols or code, written to sound natural read aloud: "back in about\n twenty minutes", not "ETA ~20m".\n\n```text\nLinuxbox has the parser checks on Codex, back around two twenty.\nDesk finished the navigation checks: tests passed, not merged yet.\n```\n\nIf a result or return time is unknown, say so. Surface a worker\'s question in\nthe same short voice, with the worker\'s own choices.\n\n## Dispatching\n\nPick five to ten independent tasks when that many are available and capacity\npermits. Do not manufacture tasks to fill the batch. Separate dependencies and\nfile ownership; give each remote lead a base revision, acceptance checks, local\nfanout limit, report time and integration instructions. Every brief repeats the\nowner\'s repository constraints, including any prohibition on commits, pushes,\nbranches or particular tests. Dispatch never expands the owner\'s authorization.\nA worker that needs root runs `sudo -A <command>`: its launch sets\n`SUDO_ASKPASS`, and the owner approves the exact command and types the\npassword on the phone. Plain `sudo` fails without a terminal.\n\nYou are the one conductor for this computer and every computer linked with\nit; a second conductor in the group is refused at launch. Conductors on\ncomputers that are not linked share only the store, so claim a task before you\ndispatch it: `claim_task` (in core, `manage_task` with `action: "claim"`).\nSkip tasks marked `[claimed: <computer>]` by another computer. A claim that\ncomes back not claimed, with `heldBy`, means another conductor got there first:\nmove on. Completing a task clears its claim; release one you will not do. Start\nworkers with `dispatch` or `hand_off`, never as tabs in your own Herdr\nworkspace. When a computer shows up in `notLinked`, tell the owner that\n`phren bridge link <host>` can link it; never link a computer yourself.\n\nPrefer Codex. Use OpenCode Go when its account and harness are connected. Use\nOpenRouter only when the owner explicitly requests it; an unavailable account\ndoes not authorize another paid provider. Name an explicit model when instructed,\notherwise use and report the remote configured default. Each remote lead owns\nits local checkouts, fanout and provider rate limits. Where installed, local\nworkers use the fanout wrapper\'s `scripts/run.sh --provider codex|opencode\n--label --worktree [--model] [--mode]` contract and parent-bound manifests.\nTell every lead the same: a worker started any other way (its own `opencode\nrun` or `codex exec`, a launch script, nohup) has no manifest, so the phone and\nyou cannot see, resume or review it. Workers that exist only as processes do\nnot count as dispatched.\n\nCheck `account_usage` before you dispatch, once per batch. The one hard rule:\nnever dispatch to an account that is `exhausted` (a window at 100%, or\nrefusing requests), until its `availableIn` passes. Low quota is information,\nnot a reason to steer away: `nearLimit` (under 20% left) is still usable, and\nthe owner often wants quota used up before it resets, so an account with quota\nleft that resets soon is a good pick; use it before it resets. For Claude, pass\nthe `account` id the row\'s `computers` list gives for the computer you pick. A\n`stale` row\'s numbers may be out of date, and a window marked `reset` has\nrolled over with no new number yet: say so rather than quoting them. Name the\nchoice in the dispatch line, such as "Desk has the parser checks on Codex,\nusing its last 15% before the week resets tomorrow." When every account is\nexhausted, tell the owner before dispatching. The owner\'s explicit choice of\nharness or account always wins. Usage on `unreachable` and `notLinked`\ncomputers is unknown, not zero.\n\nPrefer handing work to a session that already owns the project and is idle or\ndoing related work; call `hand_off` in full or `phren_admin(action: "hand_off",\ncomputer?, target|session, text)` in core. Otherwise dispatch a new worker.\nWrite one short line either way. Call `dispatch` in full or\n`phren_admin(action: "dispatch", computer, project, harness, model?, effort?, permissionMode?, prompt, label)`\nin core. The CLI equivalent is `phren dispatch <computer|anywhere> <project>\n--harness <harness> --label <label> --prompt <brief> [--model <model>] [--effort <effort>]\n[--permission-mode supervised|auto-edits|auto|full-access]`. `permissionMode` sets how the\nworker starts (Claude, Codex and Copilot; not OpenCode). `harness` is codex,\nclaude, opencode or copilot.\nFor release work (merge, publish, deploy, app-store, github-admin), read the\nowner\'s release authority policy first with `authority` in full or\n`phren_admin(action: "authority", project)` in core (CLI: `phren authority show\n<project>`), quote its `line` in the brief, and list the actions in\n`releaseActions`. An ask-first action is refused until the owner confirms it:\nask them, and never confirm or change the policy yourself. The policy only\nrestricts; when a worker\'s own harness still refuses release work, only the\nowner\'s own harness settings can allow it.\n`anywhere` chooses the connected computer with the fewest working agents, and\nskips one whose account for that harness is exhausted. Place\nbriefs sequentially, respecting busy/rate-limit responses. Keep their dispatch\nIDs. Do not send local filesystem paths as remote project names.\n\nConfigure the integrator once with `phren conductor integrator --session <id>\n[--computer <name>]`; list with `phren conductor integrator`, clear with\n`--clear`. A dispatch can override it with `integrator: {computer?, target}`.\nThe integrator\'s full target is bound to that conversation. Workers report\nstructured PR evidence with `dispatch_report(prs)` in full or\n`phren_admin(action:"dispatch_report", prs)` in core before finishing; they do not\nneed direct messaging or a GitHub comment to reach it. Inspect `prs` and\n`integratorDelivery` in receipts and verify the evidence before integration.\n\nFinished worker panes close after their done return is read. Use\n`closeOnFinish:false` (`--keep-open` in the CLI) for a worker you will reuse.\nThe Hook rechecks its ended turn and skips a pane with new work, background\ntasks, queued messages or uncertain delivery. Intentional closes do not return\n`gone`. Reading returns can close panes, so record any follow-up first.\n\nKeep one owner inbox item for each decision or action that waits on the owner.\nNeeds-you returns and blocked prompts appear automatically, even if their\nreturns were read. Add other actions such as restarting the router with\n`owner_inbox(operation:"add", title, project?, id?)` in full or\n`phren_admin(action:"owner_inbox", operation:"add", title, project?, id?)` in\ncore; keep the id on retries.\nResolve an item only once the owner decided or completed the action. Resolution\ndoes not send an answer, approve a prompt, or mark a task complete. Send an\nowner\'s answer separately with queued `hand_off`. A source that stopped waiting\nis retained as `live:false` until resolved; a resolved source stays resolved.\n\n`accepted` on a receipt is prompt acceptance, not worker completion. Returns\narrive on their own: the Hook follows every worker you dispatch, and when you\nare idle it types one line into this session, such as `Return: Linuxbox parser\nchecks done, tests passed (dispatch <id>). Call dispatch_returns.` When you see\none, call `dispatch_returns` and report each return in one short line. You may\nalso call it whenever you want the current state; do not poll it in a loop, and\ndo not read remote transcripts by hand to learn whether a worker finished. Tell\nthe owner a return time as an expectation, not a promise.\n\nA return with an `approval` is a permission request a worker is waiting on.\nAnswer it with `dispatch_approve` when it is plainly what the brief asked for;\ndeny when unsure and ask the owner. Standing grants already answer `dispatch`\nand `hand_off` requests they cover.\n\nFor a `needs-you` return, surface the worker\'s question in the owner\'s chat\nwith its choices as the worker wrote them; do not rewrite or answer it for the\nowner unless the owner already decided. Send the answer back with `hand_off`\nto the row\'s `target`. A `blocked` worker waits on terminal input, such as a\npermission prompt: say so and point the owner to the phone or the terminal. A\n`gone` worker\'s pane closed or was taken over: say so, and decide with the\nowner before giving its work to another agent. A `done` reply is the worker\'s\nown account; check its evidence before saying tests passed or work merged.\n\nA `stalled` return or `live_sessions` row with `stalled:true` means both the\nscreen and transcript have stopped changing while working. Check it and report\nwhat is known; do not launch a duplicate or interrupt it just because of the flag.\n\nAn uncertain delivery is never retried automatically. Inspect its known target\nor status before deciding with the owner whether a replacement is needed. Keep\nunavailable workers visible instead of giving their work to another agent\nwhile the original may still be running.\n\nIntegrate returned changes in dependency order within the owner\'s allowed\nworkflow. Run a cleanup pass across the combined result and the affected checks.\nRequire evidence before saying tests passed or merged. Ship only within existing\nauthorization; if publication is not authorized, return the reviewable result.\nUpdate Phren tasks when verified complete and save durable decisions. A worker\'s\nfinished turn alone does not complete the owner\'s task.\n';
|
|
57980
58181
|
else {
|
|
57981
58182
|
const here = path110.dirname(fileURLToPath(import.meta.url));
|
|
57982
58183
|
for (const candidate of [
|
|
@@ -57997,6 +58198,7 @@ function effortArgs(kind, effort) {
|
|
|
57997
58198
|
if (kind === "claude") return ["--effort", effort];
|
|
57998
58199
|
if (kind === "codex") return ["-c", `model_reasoning_effort=${effort}`];
|
|
57999
58200
|
if (kind === "opencode") return ["--variant", effort];
|
|
58201
|
+
if (kind === "copilot") return ["--reasoning-effort", effort];
|
|
58000
58202
|
if (kind === "phren") return ["--reasoning", effort === "minimal" ? "low" : effort];
|
|
58001
58203
|
return [];
|
|
58002
58204
|
}
|
|
@@ -58064,9 +58266,8 @@ ${brief}
|
|
|
58064
58266
|
async function targetForPane(server, pane) {
|
|
58065
58267
|
if (!provider.safeParse(pane.agent).success || !id.safeParse(pane.workspace_id).success || !id.safeParse(pane.tab_id).success || !id.safeParse(pane.pane_id).success) return void 0;
|
|
58066
58268
|
const binding = { server, workspace: pane.workspace_id, tab: pane.tab_id, pane: pane.pane_id, source: pane.agent };
|
|
58067
|
-
const
|
|
58068
|
-
if (
|
|
58069
|
-
const chat = await paneChatState(server, pane).catch(() => ({}));
|
|
58269
|
+
const chat = await paneChatState(server, pane, { tokenWhenIdentified: false }).catch(() => ({}));
|
|
58270
|
+
if (typeof chat.sessionId === "string") return { ...binding, session: chat.sessionId };
|
|
58070
58271
|
return chat.starting === true ? { ...binding, starting: true, startingToken: chat.startingToken } : void 0;
|
|
58071
58272
|
}
|
|
58072
58273
|
async function localConductor(known2) {
|
|
@@ -58152,6 +58353,37 @@ async function requireAvailable(kind, account) {
|
|
|
58152
58353
|
if (!availability.ok) throw new BridgeError(409, availability.reason, { code: availability.code });
|
|
58153
58354
|
}
|
|
58154
58355
|
async function launchSession(server, data, options = {}) {
|
|
58356
|
+
const launchId = data.launchId === void 0 || data.launchId === null ? void 0 : external_exports.string().uuid("launchId must be a UUID.").parse(data.launchId);
|
|
58357
|
+
if (!launchId) return startSession(server, data, options);
|
|
58358
|
+
const now = Date.now();
|
|
58359
|
+
for (const [key4, entry3] of launchesById) if (now - entry3.at > LAUNCH_ID_TTL_MS) launchesById.delete(key4);
|
|
58360
|
+
const key3 = `${server}\0${launchId}`;
|
|
58361
|
+
const earlier = launchesById.get(key3);
|
|
58362
|
+
const result = Promise.resolve().then(async () => {
|
|
58363
|
+
if (earlier) {
|
|
58364
|
+
const previous = await earlier.result;
|
|
58365
|
+
if (await stillListed(server, previous)) return { ...previous, reused: true };
|
|
58366
|
+
}
|
|
58367
|
+
return startSession(server, data, options);
|
|
58368
|
+
});
|
|
58369
|
+
const entry2 = { at: Infinity, result };
|
|
58370
|
+
launchesById.set(key3, entry2);
|
|
58371
|
+
void result.then(() => {
|
|
58372
|
+
entry2.at = Date.now();
|
|
58373
|
+
}, () => {
|
|
58374
|
+
if (launchesById.get(key3) !== entry2) return;
|
|
58375
|
+
if (earlier && Number.isFinite(earlier.at)) launchesById.set(key3, earlier);
|
|
58376
|
+
else launchesById.delete(key3);
|
|
58377
|
+
});
|
|
58378
|
+
return result;
|
|
58379
|
+
}
|
|
58380
|
+
var launchesById = /* @__PURE__ */ new Map();
|
|
58381
|
+
var LAUNCH_ID_TTL_MS = 10 * 6e4;
|
|
58382
|
+
async function stillListed(server, result) {
|
|
58383
|
+
const s = await snapshot(server);
|
|
58384
|
+
return objects(s.tabs).some((t) => t.tab_id === result.tabId && t.workspace_id === result.workspaceId) && objects(s.panes).some((p) => p.pane_id === result.paneId && p.tab_id === result.tabId && p.workspace_id === result.workspaceId);
|
|
58385
|
+
}
|
|
58386
|
+
async function startSession(server, data, options) {
|
|
58155
58387
|
const role = external_exports.enum(["agent", "conductor"]).default("agent").parse(data.role);
|
|
58156
58388
|
const projectDirectory = external_exports.string().min(1).max(4096).refine((t) => path110.isAbsolute(t) && !/[\x00-\x1f\x7f]/.test(t)).parse(data.cwd);
|
|
58157
58389
|
const worktreeRequest = data.worktree === void 0 || data.worktree === null ? void 0 : launchWorktreeSchema.parse(data.worktree);
|
|
@@ -58162,9 +58394,8 @@ async function launchSession(server, data, options = {}) {
|
|
|
58162
58394
|
const account = data.account === void 0 || data.account === null ? void 0 : external_exports.string().refine(isAccountSlug, "Account must be default or a lowercase slug.").parse(data.account);
|
|
58163
58395
|
const permissionMode = external_exports.enum(PERMISSION_MODES).optional().parse(data.permissionMode ?? void 0);
|
|
58164
58396
|
if (permissionMode && role === "conductor") throw new BridgeError(400, "A conductor starts with its own permissions; permissionMode is for workers.");
|
|
58165
|
-
if (permissionMode && kind === "opencode") throw new BridgeError(400, "OpenCode takes its permissions from its own config; permissionMode is for Claude and
|
|
58166
|
-
if (permissionMode && kind === "
|
|
58167
|
-
if (permissionMode && kind === "phren") throw new BridgeError(400, "phren agent takes its permissions from its own settings; permissionMode is for Claude and Codex workers.");
|
|
58397
|
+
if (permissionMode && kind === "opencode") throw new BridgeError(400, "OpenCode takes its permissions from its own config; permissionMode is for Claude, Codex and Copilot workers.");
|
|
58398
|
+
if (permissionMode && kind === "phren") throw new BridgeError(400, "phren agent takes its permissions from its own settings; permissionMode is for Claude, Codex and Copilot workers.");
|
|
58168
58399
|
if (role === "conductor" && kind === "copilot") throw new BridgeError(400, "Copilot cannot run as a conductor.");
|
|
58169
58400
|
if (role === "conductor" && kind === "phren") throw new BridgeError(400, PHREN_NO_CONDUCTOR);
|
|
58170
58401
|
const phrenArgs = await phrenLaunchArgs(kind, data);
|
|
@@ -58173,7 +58404,7 @@ async function launchSession(server, data, options = {}) {
|
|
|
58173
58404
|
const baseName = herdrAgentName(data.name === void 0 ? label2 : plainText(200).parse(data.name));
|
|
58174
58405
|
const wanted = options.canary ? "phren-canary" : role === "conductor" ? isConductorName(baseName) ? baseName : herdrAgentName(`conductor-${baseName}`) : isConductorName(baseName) ? herdrAgentName(`worker-${baseName}`) : baseName;
|
|
58175
58406
|
const model = typeof data.model === "string" && data.model.trim() ? plainText(200).parse(data.model.trim()) : void 0;
|
|
58176
|
-
const modelFlag = { codex: "--model", claude: "--model", opencode: "--model", phren: "--model" };
|
|
58407
|
+
const modelFlag = { codex: "--model", claude: "--model", opencode: "--model", copilot: "--model", phren: "--model" };
|
|
58177
58408
|
let workspace = data.workspaceId === void 0 ? void 0 : id.parse(data.workspaceId);
|
|
58178
58409
|
const timeout = Math.min(12e4, Math.max(3001, data.timeoutMs === void 0 ? 45e3 : external_exports.number().int().parse(data.timeoutMs)));
|
|
58179
58410
|
await requireAvailable(kind, account);
|
|
@@ -58191,7 +58422,8 @@ async function launchSession(server, data, options = {}) {
|
|
|
58191
58422
|
...model && kind === "phren" ? phrenModelArgs(model) : model && modelFlag[kind] ? [modelFlag[kind], model] : [],
|
|
58192
58423
|
...data.effort === void 0 ? [] : effortArgs(kind, effort),
|
|
58193
58424
|
...permissionMode && kind === "claude" ? ["--permission-mode", CLAUDE_NAMES[permissionMode]] : [],
|
|
58194
|
-
...permissionMode && kind === "codex" ? codexModeFlags(permissionMode) : []
|
|
58425
|
+
...permissionMode && kind === "codex" ? codexModeFlags(permissionMode) : [],
|
|
58426
|
+
...permissionMode && kind === "copilot" ? copilotModeFlags(permissionMode) : []
|
|
58195
58427
|
];
|
|
58196
58428
|
const structured = kind === "codex" && role === "agent" && !options.canary && codexAppServerEnabled();
|
|
58197
58429
|
const served = kind === "opencode" ? await prepareServedLaunch() : void 0;
|
|
@@ -58510,6 +58742,7 @@ var capabilities = {
|
|
|
58510
58742
|
memoryStore: true,
|
|
58511
58743
|
promptOnce: true,
|
|
58512
58744
|
promptStatus: true,
|
|
58745
|
+
deliveryFrames: true,
|
|
58513
58746
|
resources: true,
|
|
58514
58747
|
sudo: true,
|
|
58515
58748
|
sudoOutcome: true,
|
|
@@ -59667,6 +59900,8 @@ function transcriptStreams(ctx) {
|
|
|
59667
59900
|
const cursor = url2.pathname === "/v1/transcripts" ? url2.searchParams.get("afterLine") : null;
|
|
59668
59901
|
const sideAnswers = url2.pathname === "/v1/transcripts" && child === null && url2.searchParams.get("sideAnswers") === "1";
|
|
59669
59902
|
const sentSide = /* @__PURE__ */ new Map();
|
|
59903
|
+
const deliveryFrames = url2.pathname === "/v1/transcripts" && child === null && url2.searchParams.get("deliveries") === "1";
|
|
59904
|
+
const sentDelivery = /* @__PURE__ */ new Map();
|
|
59670
59905
|
let resumeAfterLine = cursor === null ? void 0 : external_exports.coerce.number().int().nonnegative().max(4294967295).parse(cursor);
|
|
59671
59906
|
let conversation = { source: target.source, session: target.session };
|
|
59672
59907
|
const findTranscript = async () => {
|
|
@@ -59765,6 +60000,13 @@ function transcriptStreams(ctx) {
|
|
|
59765
60000
|
send(client, { type: "side-answer", ...conversation, ...side });
|
|
59766
60001
|
}
|
|
59767
60002
|
}
|
|
60003
|
+
if (deliveryFrames) {
|
|
60004
|
+
for (const { deliveryId, state } of agentHooks.deliveriesFor(target)) {
|
|
60005
|
+
if (sentDelivery.get(deliveryId) === state) continue;
|
|
60006
|
+
sentDelivery.set(deliveryId, state);
|
|
60007
|
+
send(client, { type: "delivery", ...conversation, deliveryId, state });
|
|
60008
|
+
}
|
|
60009
|
+
}
|
|
59768
60010
|
first = false;
|
|
59769
60011
|
}
|
|
59770
60012
|
while (pending.length && reader && !abort.signal.aborted) {
|
|
@@ -60218,7 +60460,7 @@ async function serve(version3, options = {}) {
|
|
|
60218
60460
|
return;
|
|
60219
60461
|
}
|
|
60220
60462
|
if (url2.pathname === "/v1/speech/transcribe") {
|
|
60221
|
-
void relayTranscription(client, url2.searchParams).catch(() => client
|
|
60463
|
+
void relayTranscription(client, url2.searchParams).catch(() => failRelay(client));
|
|
60222
60464
|
return;
|
|
60223
60465
|
}
|
|
60224
60466
|
if (url2.pathname === "/v1/speech/live") {
|
|
@@ -60708,7 +60950,7 @@ async function readSecret(prompt) {
|
|
|
60708
60950
|
// src/bridge/hook-main.ts
|
|
60709
60951
|
init_utils_helpers();
|
|
60710
60952
|
Object.assign(process.env, nonInteractiveGitEnv());
|
|
60711
|
-
runBridge(process.argv.slice(2), "0.3.
|
|
60953
|
+
runBridge(process.argv.slice(2), "0.3.22").then((code) => {
|
|
60712
60954
|
process.exitCode = code;
|
|
60713
60955
|
}).catch((error62) => {
|
|
60714
60956
|
console.error(error62 instanceof Error ? error62.message : "Phren Hook failed.");
|