@phren/cli 0.3.44 → 0.3.46
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-hook-asks.d.ts +34 -0
- package/dist/bridge/agent-hook-asks.js +72 -0
- package/dist/bridge/agent-hook-callback.d.ts +22 -0
- package/dist/bridge/agent-hook-callback.js +114 -0
- package/dist/bridge/agent-hooks.d.ts +7 -74
- package/dist/bridge/agent-hooks.js +22 -186
- package/dist/bridge/claude-question-dialog.d.ts +6 -0
- package/dist/bridge/claude-question-dialog.js +29 -7
- package/dist/bridge/codex-app-server.d.ts +5 -0
- package/dist/bridge/codex-app-server.js +15 -0
- package/dist/bridge/codex-auth-refresh.js +7 -0
- package/dist/bridge/dispatch-command.js +7 -1
- package/dist/bridge/file-write.js +3 -1
- package/dist/bridge/git-host-auth.d.ts +6 -0
- package/dist/bridge/git-host-auth.js +45 -0
- package/dist/bridge/git-publish.d.ts +1 -1
- package/dist/bridge/git-publish.js +75 -8
- package/dist/bridge/git-review.js +23 -2
- package/dist/bridge/git.d.ts +5 -1
- package/dist/bridge/git.js +103 -8
- package/dist/bridge/health.d.ts +1 -0
- package/dist/bridge/health.js +8 -5
- package/dist/bridge/lookup-cache.d.ts +17 -0
- package/dist/bridge/lookup-cache.js +70 -0
- package/dist/bridge/memory-store.js +40 -14
- package/dist/bridge/pair.js +4 -0
- package/dist/bridge/peers.js +36 -0
- package/dist/bridge/projects.d.ts +14 -0
- package/dist/bridge/projects.js +48 -1
- package/dist/bridge/prompt-deliveries.d.ts +38 -3
- package/dist/bridge/prompt-deliveries.js +196 -36
- package/dist/bridge/schedule-format.d.ts +4 -0
- package/dist/bridge/schedule-format.js +34 -0
- package/dist/bridge/schedule-problems.js +4 -0
- package/dist/bridge/scoped-gateway.d.ts +1 -0
- package/dist/bridge/scoped-gateway.js +10 -1
- package/dist/bridge/server-launch.js +6 -2
- package/dist/bridge/server-routes.js +5 -1
- package/dist/bridge/session-activity.d.ts +10 -0
- package/dist/bridge/session-activity.js +25 -0
- package/dist/bridge/session-servers.js +3 -0
- package/dist/bridge/{codex-thread-origin.d.ts → thread-origin.d.ts} +8 -0
- package/dist/bridge/{codex-thread-origin.js → thread-origin.js} +24 -6
- package/dist/bridge/usage.d.ts +4 -0
- package/dist/bridge/usage.js +22 -8
- package/dist/bridge-hook.mjs +1149 -469
- package/dist/cli/namespaces-tasks.js +19 -5
- package/dist/cli/ops.d.ts +1 -1
- package/dist/cli/ops.js +2 -2
- package/dist/cli/schedules.js +16 -9
- package/dist/content/summarize.js +46 -6
- package/dist/content/validate.d.ts +3 -1
- package/dist/content/validate.js +33 -4
- package/dist/data/access.d.ts +8 -1
- package/dist/data/access.js +27 -9
- package/dist/data/notes.d.ts +2 -0
- package/dist/data/notes.js +2 -1
- package/dist/entrypoint.js +2 -1
- package/dist/generated/memory-ui-graph.browser.js +1 -1
- package/dist/governance/locks.js +17 -1
- package/dist/governance/policy.js +37 -23
- package/dist/link/link.js +6 -1
- package/dist/memory-ui-graph.runtime.js +1 -1
- package/dist/sync/conflict-resolve.d.ts +1 -1
- package/dist/sync/conflict-resolve.js +91 -8
- package/dist/task/lifecycle.js +2 -1
- package/package.json +1 -1
package/dist/bridge-hook.mjs
CHANGED
|
@@ -20016,21 +20016,21 @@ function visit(schema, fnOrHandlers) {
|
|
|
20016
20016
|
case "object": {
|
|
20017
20017
|
const oldShape = def.shape;
|
|
20018
20018
|
const keys2 = Object.keys(oldShape);
|
|
20019
|
-
let
|
|
20019
|
+
let changed = false;
|
|
20020
20020
|
const newShape = {};
|
|
20021
20021
|
for (const k2 of keys2) {
|
|
20022
20022
|
const mapped = run4(oldShape[k2]);
|
|
20023
20023
|
if (mapped !== oldShape[k2])
|
|
20024
|
-
|
|
20024
|
+
changed = true;
|
|
20025
20025
|
newShape[k2] = mapped;
|
|
20026
20026
|
}
|
|
20027
20027
|
let newCatchall = def.catchall;
|
|
20028
20028
|
if (def.catchall) {
|
|
20029
20029
|
newCatchall = run4(def.catchall);
|
|
20030
20030
|
if (newCatchall !== def.catchall)
|
|
20031
|
-
|
|
20031
|
+
changed = true;
|
|
20032
20032
|
}
|
|
20033
|
-
return
|
|
20033
|
+
return changed ? clone(s, { ...def, shape: newShape, catchall: newCatchall }) : s;
|
|
20034
20034
|
}
|
|
20035
20035
|
case "array": {
|
|
20036
20036
|
const mapped = run4(def.element);
|
|
@@ -20038,21 +20038,21 @@ function visit(schema, fnOrHandlers) {
|
|
|
20038
20038
|
}
|
|
20039
20039
|
case "tuple": {
|
|
20040
20040
|
const oldItems = def.items;
|
|
20041
|
-
let
|
|
20041
|
+
let changed = false;
|
|
20042
20042
|
const newItems = [];
|
|
20043
20043
|
for (const item of oldItems) {
|
|
20044
20044
|
const mapped = run4(item);
|
|
20045
20045
|
if (mapped !== item)
|
|
20046
|
-
|
|
20046
|
+
changed = true;
|
|
20047
20047
|
newItems.push(mapped);
|
|
20048
20048
|
}
|
|
20049
20049
|
let newRest = def.rest;
|
|
20050
20050
|
if (def.rest) {
|
|
20051
20051
|
newRest = run4(def.rest);
|
|
20052
20052
|
if (newRest !== def.rest)
|
|
20053
|
-
|
|
20053
|
+
changed = true;
|
|
20054
20054
|
}
|
|
20055
|
-
return
|
|
20055
|
+
return changed ? clone(s, { ...def, items: newItems, rest: newRest }) : s;
|
|
20056
20056
|
}
|
|
20057
20057
|
case "record":
|
|
20058
20058
|
case "map": {
|
|
@@ -20066,15 +20066,15 @@ function visit(schema, fnOrHandlers) {
|
|
|
20066
20066
|
}
|
|
20067
20067
|
case "union": {
|
|
20068
20068
|
const oldOptions = def.options;
|
|
20069
|
-
let
|
|
20069
|
+
let changed = false;
|
|
20070
20070
|
const newOptions = [];
|
|
20071
20071
|
for (const opt of oldOptions) {
|
|
20072
20072
|
const mapped = run4(opt);
|
|
20073
20073
|
if (mapped !== opt)
|
|
20074
|
-
|
|
20074
|
+
changed = true;
|
|
20075
20075
|
newOptions.push(mapped);
|
|
20076
20076
|
}
|
|
20077
|
-
return
|
|
20077
|
+
return changed ? clone(s, { ...def, options: newOptions }) : s;
|
|
20078
20078
|
}
|
|
20079
20079
|
case "intersection": {
|
|
20080
20080
|
const newLeft = run4(def.left);
|
|
@@ -24366,7 +24366,18 @@ ${Math.random()}`;
|
|
|
24366
24366
|
}
|
|
24367
24367
|
};
|
|
24368
24368
|
} catch (err) {
|
|
24369
|
-
|
|
24369
|
+
const code = err.code;
|
|
24370
|
+
if (process.platform === "win32" && (code === "EPERM" || code === "EACCES" || code === "EBUSY")) {
|
|
24371
|
+
let present2 = true;
|
|
24372
|
+
try {
|
|
24373
|
+
fs3.statSync(lockPath);
|
|
24374
|
+
} catch (statErr) {
|
|
24375
|
+
present2 = statErr.code !== "ENOENT";
|
|
24376
|
+
}
|
|
24377
|
+
if (present2) return null;
|
|
24378
|
+
throw err;
|
|
24379
|
+
}
|
|
24380
|
+
if (code !== "EEXIST") throw err;
|
|
24370
24381
|
try {
|
|
24371
24382
|
const contents = fs3.readFileSync(lockPath, "utf8");
|
|
24372
24383
|
const pid = Number.parseInt(contents.split("\n")[0], 10);
|
|
@@ -26309,6 +26320,74 @@ var init_locate = __esm({
|
|
|
26309
26320
|
}
|
|
26310
26321
|
});
|
|
26311
26322
|
|
|
26323
|
+
// src/bridge/lookup-cache.ts
|
|
26324
|
+
var LookupCache;
|
|
26325
|
+
var init_lookup_cache = __esm({
|
|
26326
|
+
"src/bridge/lookup-cache.ts"() {
|
|
26327
|
+
"use strict";
|
|
26328
|
+
init_protocol();
|
|
26329
|
+
LookupCache = class {
|
|
26330
|
+
constructor(ttl, maxAge = 3e5, limit = 64, available = () => true, pendingTimeout = 45e3, revokes = () => false) {
|
|
26331
|
+
this.ttl = ttl;
|
|
26332
|
+
this.maxAge = maxAge;
|
|
26333
|
+
this.limit = limit;
|
|
26334
|
+
this.available = available;
|
|
26335
|
+
this.pendingTimeout = pendingTimeout;
|
|
26336
|
+
this.revokes = revokes;
|
|
26337
|
+
}
|
|
26338
|
+
ttl;
|
|
26339
|
+
maxAge;
|
|
26340
|
+
limit;
|
|
26341
|
+
available;
|
|
26342
|
+
pendingTimeout;
|
|
26343
|
+
revokes;
|
|
26344
|
+
entries = /* @__PURE__ */ new Map();
|
|
26345
|
+
invalidate(matches) {
|
|
26346
|
+
for (const key4 of this.entries.keys()) if (matches(key4)) this.entries.delete(key4);
|
|
26347
|
+
}
|
|
26348
|
+
get(key4, read) {
|
|
26349
|
+
let entry2 = this.entries.get(key4);
|
|
26350
|
+
if (!entry2) {
|
|
26351
|
+
entry2 = {};
|
|
26352
|
+
this.entries.set(key4, entry2);
|
|
26353
|
+
if (this.entries.size > this.limit) this.entries.delete(this.entries.keys().next().value);
|
|
26354
|
+
}
|
|
26355
|
+
const cached3 = entry2.value;
|
|
26356
|
+
const age = cached3 ? Date.now() - cached3.at : Infinity;
|
|
26357
|
+
const available = cached3 && this.available(cached3.data);
|
|
26358
|
+
const ttl = available ? this.ttl : 5e3;
|
|
26359
|
+
const maxAge = available ? this.maxAge : 5e3;
|
|
26360
|
+
if (cached3 && age < ttl) return Promise.resolve(cached3.data);
|
|
26361
|
+
if (!entry2.pending) {
|
|
26362
|
+
const current2 = entry2;
|
|
26363
|
+
let timer;
|
|
26364
|
+
const timeout = new Promise((_2, reject) => {
|
|
26365
|
+
timer = setTimeout(() => reject(new BridgeError(504, "Lookup did not finish within the request time limit.", { code: "lookup-timeout" })), this.pendingTimeout);
|
|
26366
|
+
});
|
|
26367
|
+
const pending = Promise.race([Promise.resolve().then(read), timeout]).then((data) => {
|
|
26368
|
+
if (this.entries.get(key4) === current2 && current2.pending === pending) {
|
|
26369
|
+
const previous = current2.value;
|
|
26370
|
+
const keepSuccess = previous && this.available(previous.data) && !this.available(data) && !this.revokes(data) && Date.now() - previous.at < this.maxAge;
|
|
26371
|
+
if (!keepSuccess) current2.value = { data, at: Date.now() };
|
|
26372
|
+
}
|
|
26373
|
+
return data;
|
|
26374
|
+
}).finally(() => {
|
|
26375
|
+
clearTimeout(timer);
|
|
26376
|
+
if (current2.pending === pending) current2.pending = void 0;
|
|
26377
|
+
});
|
|
26378
|
+
entry2.pending = pending;
|
|
26379
|
+
}
|
|
26380
|
+
if (cached3 && age < maxAge && !this.revokes(cached3.data)) {
|
|
26381
|
+
void entry2.pending.catch(() => {
|
|
26382
|
+
});
|
|
26383
|
+
return Promise.resolve(cached3.data);
|
|
26384
|
+
}
|
|
26385
|
+
return entry2.pending;
|
|
26386
|
+
}
|
|
26387
|
+
};
|
|
26388
|
+
}
|
|
26389
|
+
});
|
|
26390
|
+
|
|
26312
26391
|
// src/bridge/metrics.ts
|
|
26313
26392
|
var MAX_NAMES, NAME, HookMetrics, hookMetrics, countHerdr, countIdentity, countGit, countTick;
|
|
26314
26393
|
var init_metrics = __esm({
|
|
@@ -26423,6 +26502,12 @@ async function withGitReadDeadline(read) {
|
|
|
26423
26502
|
await Promise.allSettled([...budget.pending]);
|
|
26424
26503
|
}
|
|
26425
26504
|
}
|
|
26505
|
+
function withoutGitReadDeadline(read) {
|
|
26506
|
+
return gitReadBudget.exit(read);
|
|
26507
|
+
}
|
|
26508
|
+
function withIndependentGitReadDeadline(read) {
|
|
26509
|
+
return gitReadBudget.exit(() => withGitReadDeadline(read));
|
|
26510
|
+
}
|
|
26426
26511
|
function checkoutGitEnv() {
|
|
26427
26512
|
const env = nonInteractiveGitEnv({ ...process.env, GIT_OPTIONAL_LOCKS: "0", LC_ALL: "C" });
|
|
26428
26513
|
for (const key4 of ["GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE", "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_PREFIX"]) delete env[key4];
|
|
@@ -26653,9 +26738,14 @@ function probe(port, host) {
|
|
|
26653
26738
|
const finish = (value2) => {
|
|
26654
26739
|
if (!settled3) {
|
|
26655
26740
|
settled3 = true;
|
|
26741
|
+
clearTimeout(deadline);
|
|
26656
26742
|
resolve17(value2);
|
|
26657
26743
|
}
|
|
26658
26744
|
};
|
|
26745
|
+
const deadline = setTimeout(() => {
|
|
26746
|
+
finish(null);
|
|
26747
|
+
req.destroy();
|
|
26748
|
+
}, 1200);
|
|
26659
26749
|
const req = request({ hostname: host, port, path: "/", method: "GET", timeout: 1200, headers: { Host: `localhost:${port}` } }, (res) => {
|
|
26660
26750
|
let body2 = "";
|
|
26661
26751
|
res.on("data", (data) => {
|
|
@@ -26709,6 +26799,18 @@ async function listenersFromSs(ports) {
|
|
|
26709
26799
|
}
|
|
26710
26800
|
}
|
|
26711
26801
|
async function webServers() {
|
|
26802
|
+
const servers2 = await serversCache.get("listeners", scanWebServers);
|
|
26803
|
+
if (!servers2.some((server) => server.pid !== void 0) || Date.now() - (scanStarted.get(servers2) ?? 0) < LISTENER_TRUST_MS) return servers2;
|
|
26804
|
+
const live = await readListeners().catch(() => void 0);
|
|
26805
|
+
if (!live) return servers2.map(({ pid: _pid, ...server }) => ({ ...server, unverified: true }));
|
|
26806
|
+
const kept = servers2.filter((server) => server.pid === void 0 || live.get(listenerKey(server))?.pid === server.pid);
|
|
26807
|
+
if (kept.length !== servers2.length) serversCache.invalidate(() => true);
|
|
26808
|
+
return kept;
|
|
26809
|
+
}
|
|
26810
|
+
function listenerKey(server) {
|
|
26811
|
+
return `${server.origin.includes("[::1]") ? "[::1]" : "127.0.0.1"}:${server.port}`;
|
|
26812
|
+
}
|
|
26813
|
+
async function readListeners() {
|
|
26712
26814
|
const ports = /* @__PURE__ */ new Map();
|
|
26713
26815
|
const readers = process.platform === "linux" ? [listenersFromSs, listenersFromLsof] : [listenersFromLsof, listenersFromSs];
|
|
26714
26816
|
let lastError;
|
|
@@ -26722,6 +26824,11 @@ async function webServers() {
|
|
|
26722
26824
|
}
|
|
26723
26825
|
}
|
|
26724
26826
|
if (lastError && ports.size === 0) throw new BridgeError(503, "No socket listing tool found: install lsof (or iproute2's ss on Linux).");
|
|
26827
|
+
return ports;
|
|
26828
|
+
}
|
|
26829
|
+
async function scanWebServers() {
|
|
26830
|
+
const started = Date.now();
|
|
26831
|
+
const ports = await readListeners();
|
|
26725
26832
|
const candidates = [...ports.values()].sort((a, b) => Number(a.port >= EPHEMERAL_PORT) - Number(b.port >= EPHEMERAL_PORT) || a.port - b.port).slice(0, 64);
|
|
26726
26833
|
const found = [];
|
|
26727
26834
|
for (let i = 0; i < candidates.length; i += 8) {
|
|
@@ -26730,7 +26837,9 @@ async function webServers() {
|
|
|
26730
26837
|
if (name !== null) found.push({ ...server, name });
|
|
26731
26838
|
}));
|
|
26732
26839
|
}
|
|
26733
|
-
|
|
26840
|
+
const listing = found.sort((a, b) => a.port - b.port);
|
|
26841
|
+
scanStarted.set(listing, started);
|
|
26842
|
+
return listing;
|
|
26734
26843
|
}
|
|
26735
26844
|
async function launchDirectory(raw, activity = [], located = []) {
|
|
26736
26845
|
if (typeof raw !== "string" || raw.length > 4096 || !path17.isAbsolute(raw) || /[\x00-\x1f\x7f]/.test(raw)) throw new BridgeError(400, "Invalid workspace directory.");
|
|
@@ -26755,7 +26864,7 @@ async function launchDirectory(raw, activity = [], located = []) {
|
|
|
26755
26864
|
}
|
|
26756
26865
|
throw new BridgeError(403, "Workspace directory must be under home or a located project.");
|
|
26757
26866
|
}
|
|
26758
|
-
var exec, gitReadBudget, GIT_READ_MS, gitTimeout, BRANCH_FRESH_MS, BRANCH_MAX_MS, branches, ENTITIES, LISTEN_HOST, EPHEMERAL_PORT;
|
|
26867
|
+
var exec, gitReadBudget, GIT_READ_MS, gitTimeout, BRANCH_FRESH_MS, BRANCH_MAX_MS, branches, ENTITIES, LISTEN_HOST, EPHEMERAL_PORT, serversCache, scanStarted, LISTENER_TRUST_MS;
|
|
26759
26868
|
var init_projects = __esm({
|
|
26760
26869
|
"src/bridge/projects.ts"() {
|
|
26761
26870
|
"use strict";
|
|
@@ -26764,6 +26873,7 @@ var init_projects = __esm({
|
|
|
26764
26873
|
init_transcripts();
|
|
26765
26874
|
init_locate();
|
|
26766
26875
|
init_protocol();
|
|
26876
|
+
init_lookup_cache();
|
|
26767
26877
|
init_metrics();
|
|
26768
26878
|
exec = promisify(execFile);
|
|
26769
26879
|
gitReadBudget = new AsyncLocalStorage();
|
|
@@ -26775,6 +26885,9 @@ var init_projects = __esm({
|
|
|
26775
26885
|
ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " };
|
|
26776
26886
|
LISTEN_HOST = /^(\*|127\.0\.0\.1|localhost|0\.0\.0\.0|\[::\]|\[::1\]|::|::1)$/;
|
|
26777
26887
|
EPHEMERAL_PORT = 32768;
|
|
26888
|
+
serversCache = new LookupCache(1e4, 3e5, 1, () => true, 2e4);
|
|
26889
|
+
scanStarted = /* @__PURE__ */ new WeakMap();
|
|
26890
|
+
LISTENER_TRUST_MS = 1e3;
|
|
26778
26891
|
}
|
|
26779
26892
|
});
|
|
26780
26893
|
|
|
@@ -27719,8 +27832,8 @@ function boundedValue(value2, depth, cap) {
|
|
|
27719
27832
|
if (value2 && typeof value2 === "object") {
|
|
27720
27833
|
const out = /* @__PURE__ */ Object.create(null);
|
|
27721
27834
|
for (const [key4, item] of Object.entries(value2).slice(0, 64)) {
|
|
27722
|
-
const
|
|
27723
|
-
if (
|
|
27835
|
+
const bounded2 = boundedValue(item, depth + 1, cap);
|
|
27836
|
+
if (bounded2 !== void 0) out[key4] = bounded2;
|
|
27724
27837
|
}
|
|
27725
27838
|
return out;
|
|
27726
27839
|
}
|
|
@@ -29611,6 +29724,14 @@ function markBackground(tab, count2) {
|
|
|
29611
29724
|
tab.backgroundTasks = count2;
|
|
29612
29725
|
} else if (typeof tab.backgroundTasks === "number") tab.backgroundTasks = Math.max(tab.backgroundTasks, count2);
|
|
29613
29726
|
}
|
|
29727
|
+
function replyExcerpt(record4) {
|
|
29728
|
+
if (!record4) return void 0;
|
|
29729
|
+
const phase = turnPhase(record4);
|
|
29730
|
+
if (phase.phase !== "ended" || !phase.reply) return void 0;
|
|
29731
|
+
const line = phase.reply.replace(/```[\s\S]*?(```|$)/g, " ").replace(/(^|\n)\s*(#{1,6}|>|[-*+]|\d+\.)\s+/g, "$1").replace(/(\*\*|__|\*|`)/g, "").replace(/\s+/g, " ").trim();
|
|
29732
|
+
if (!line) return void 0;
|
|
29733
|
+
return line.length > REPLY_EXCERPT_CHARS ? `${line.slice(0, REPLY_EXCERPT_CHARS - 1).trimEnd()}\u2026` : line;
|
|
29734
|
+
}
|
|
29614
29735
|
function meaningfulLabel(value2) {
|
|
29615
29736
|
if (typeof value2 !== "string") return void 0;
|
|
29616
29737
|
const text5 = value2.trim();
|
|
@@ -29639,7 +29760,7 @@ async function recordTitle(record4, input2) {
|
|
|
29639
29760
|
const dispatch2 = record4?.dispatch;
|
|
29640
29761
|
return sessionTitle({ ...input2, dispatched: !!dispatch2, dispatchLabel: dispatch2 ? await briefLabel(dispatch2) : void 0 });
|
|
29641
29762
|
}
|
|
29642
|
-
var BACKGROUND_STALE_MS, GLYPHS_AROUND;
|
|
29763
|
+
var BACKGROUND_STALE_MS, REPLY_EXCERPT_CHARS, GLYPHS_AROUND;
|
|
29643
29764
|
var init_session_activity = __esm({
|
|
29644
29765
|
"src/bridge/session-activity.ts"() {
|
|
29645
29766
|
"use strict";
|
|
@@ -29647,6 +29768,7 @@ var init_session_activity = __esm({
|
|
|
29647
29768
|
init_protocol();
|
|
29648
29769
|
init_turn_records();
|
|
29649
29770
|
BACKGROUND_STALE_MS = 2 * 60 * 60 * 1e3;
|
|
29771
|
+
REPLY_EXCERPT_CHARS = 240;
|
|
29650
29772
|
GLYPHS_AROUND = /^[\u2800-\u28ff\u2700-\u27bf\u25a0-\u25ff\u23f0-\u23ff\u2022\u00b7\u2219\u22c5\u2605\u2606\s]+|[\s\u2800-\u28ff\u2700-\u27bf\u25a0-\u25ff\u23f0-\u23ff\u2022\u00b7\u2219\u22c5\u2605\u2606]+$/gu;
|
|
29651
29773
|
}
|
|
29652
29774
|
});
|
|
@@ -29680,7 +29802,7 @@ var init_tab_activity = __esm({
|
|
|
29680
29802
|
await this.load();
|
|
29681
29803
|
const prefix = JSON.stringify(server) + ":";
|
|
29682
29804
|
const seen = /* @__PURE__ */ new Set(), times = /* @__PURE__ */ new Map();
|
|
29683
|
-
let
|
|
29805
|
+
let changed = false;
|
|
29684
29806
|
for (const tab of objects(snapshot2.tabs)) {
|
|
29685
29807
|
const tabKey = tabActivityKey(tab.workspace_id, tab.tab_id), key4 = prefix + tabKey;
|
|
29686
29808
|
seen.add(key4);
|
|
@@ -29690,17 +29812,17 @@ var init_tab_activity = __esm({
|
|
|
29690
29812
|
if (stamp2?.signature !== signature) {
|
|
29691
29813
|
stamp2 = { signature, lastChangedAt: at2 };
|
|
29692
29814
|
this.entries.set(key4, stamp2);
|
|
29693
|
-
|
|
29815
|
+
changed = true;
|
|
29694
29816
|
}
|
|
29695
29817
|
times.set(tabKey, stamp2.lastChangedAt);
|
|
29696
29818
|
}
|
|
29697
29819
|
for (const key4 of this.entries.keys()) {
|
|
29698
29820
|
if (key4.startsWith(prefix) && !seen.has(key4)) {
|
|
29699
29821
|
this.entries.delete(key4);
|
|
29700
|
-
|
|
29822
|
+
changed = true;
|
|
29701
29823
|
}
|
|
29702
29824
|
}
|
|
29703
|
-
this.dirty ||=
|
|
29825
|
+
this.dirty ||= changed;
|
|
29704
29826
|
await this.persist();
|
|
29705
29827
|
return times;
|
|
29706
29828
|
});
|
|
@@ -32170,7 +32292,7 @@ var require_websocket = __commonJS({
|
|
|
32170
32292
|
var http = __require("http");
|
|
32171
32293
|
var net2 = __require("net");
|
|
32172
32294
|
var tls = __require("tls");
|
|
32173
|
-
var { randomBytes: randomBytes10, createHash:
|
|
32295
|
+
var { randomBytes: randomBytes10, createHash: createHash32 } = __require("crypto");
|
|
32174
32296
|
var { Duplex: Duplex2, Readable: Readable2 } = __require("stream");
|
|
32175
32297
|
var { URL: URL2 } = __require("url");
|
|
32176
32298
|
var PerMessageDeflate2 = require_permessage_deflate();
|
|
@@ -32851,7 +32973,7 @@ var require_websocket = __commonJS({
|
|
|
32851
32973
|
abortHandshake(websocket, socket, "Invalid Upgrade header");
|
|
32852
32974
|
return;
|
|
32853
32975
|
}
|
|
32854
|
-
const digest2 =
|
|
32976
|
+
const digest2 = createHash32("sha1").update(key4 + GUID).digest("base64");
|
|
32855
32977
|
if (res.headers["sec-websocket-accept"] !== digest2) {
|
|
32856
32978
|
abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
|
|
32857
32979
|
return;
|
|
@@ -33220,7 +33342,7 @@ var require_websocket_server = __commonJS({
|
|
|
33220
33342
|
var EventEmitter2 = __require("events");
|
|
33221
33343
|
var http = __require("http");
|
|
33222
33344
|
var { Duplex: Duplex2 } = __require("stream");
|
|
33223
|
-
var { createHash:
|
|
33345
|
+
var { createHash: createHash32 } = __require("crypto");
|
|
33224
33346
|
var extension2 = require_extension();
|
|
33225
33347
|
var PerMessageDeflate2 = require_permessage_deflate();
|
|
33226
33348
|
var subprotocol2 = require_subprotocol();
|
|
@@ -33527,7 +33649,7 @@ var require_websocket_server = __commonJS({
|
|
|
33527
33649
|
);
|
|
33528
33650
|
}
|
|
33529
33651
|
if (this._state > RUNNING) return abortHandshake(socket, 503);
|
|
33530
|
-
const digest2 =
|
|
33652
|
+
const digest2 = createHash32("sha1").update(key4 + GUID).digest("base64");
|
|
33531
33653
|
const headers = [
|
|
33532
33654
|
"HTTP/1.1 101 Switching Protocols",
|
|
33533
33655
|
"Upgrade: websocket",
|
|
@@ -33685,6 +33807,8 @@ import path28 from "node:path";
|
|
|
33685
33807
|
async function spawnAppServer(options) {
|
|
33686
33808
|
const env = { ...options.replaceEnv ? {} : process.env, ...options.env ?? {}, ...options.codexHome ? { CODEX_HOME: options.codexHome } : {} };
|
|
33687
33809
|
const codexBin = options.codexBin ?? codexExecutable(env);
|
|
33810
|
+
const known2 = unixListenUnsupported.get(codexBin);
|
|
33811
|
+
if (known2) throw new AppServerUnsupportedError(known2);
|
|
33688
33812
|
await mkdir7(path28.dirname(options.socketPath), { recursive: true, mode: 448 });
|
|
33689
33813
|
await rm4(options.socketPath, { force: true });
|
|
33690
33814
|
const log2 = options.logFile ? await open8(options.logFile, "a", 384) : void 0;
|
|
@@ -33719,6 +33843,12 @@ async function spawnAppServer(options) {
|
|
|
33719
33843
|
while (true) {
|
|
33720
33844
|
if (failure2) throw new Error(`codex app-server could not start: ${failure2.message}`);
|
|
33721
33845
|
if (child.exitCode !== null || child.signalCode !== null) {
|
|
33846
|
+
const detail = await why();
|
|
33847
|
+
if (/unsupported --listen URL/.test(detail)) {
|
|
33848
|
+
const message = `this codex build cannot listen on a unix socket (needs a newer codex)${detail}`;
|
|
33849
|
+
unixListenUnsupported.set(codexBin, message);
|
|
33850
|
+
throw new AppServerUnsupportedError(message);
|
|
33851
|
+
}
|
|
33722
33852
|
throw new Error(`codex app-server exited before ${options.socketPath} was ready (${child.exitCode ?? child.signalCode})${await why()}`);
|
|
33723
33853
|
}
|
|
33724
33854
|
if (await socketAccepts(options.socketPath)) break;
|
|
@@ -33830,7 +33960,7 @@ function declineResult(method) {
|
|
|
33830
33960
|
return {};
|
|
33831
33961
|
}
|
|
33832
33962
|
}
|
|
33833
|
-
var STARTUP_TIMEOUT_MS, STARTUP_POLL_MS, DEFAULT_REQUEST_TIMEOUT_MS, KILL_GRACE_MS, AppServerRpcError, AppServerConnection;
|
|
33963
|
+
var STARTUP_TIMEOUT_MS, STARTUP_POLL_MS, DEFAULT_REQUEST_TIMEOUT_MS, KILL_GRACE_MS, AppServerRpcError, AppServerUnsupportedError, unixListenUnsupported, AppServerConnection;
|
|
33834
33964
|
var init_codex_app_server = __esm({
|
|
33835
33965
|
"src/bridge/codex-app-server.ts"() {
|
|
33836
33966
|
"use strict";
|
|
@@ -33851,6 +33981,9 @@ var init_codex_app_server = __esm({
|
|
|
33851
33981
|
code;
|
|
33852
33982
|
method;
|
|
33853
33983
|
};
|
|
33984
|
+
AppServerUnsupportedError = class extends Error {
|
|
33985
|
+
};
|
|
33986
|
+
unixListenUnsupported = /* @__PURE__ */ new Map();
|
|
33854
33987
|
AppServerConnection = class {
|
|
33855
33988
|
constructor(ws2) {
|
|
33856
33989
|
this.ws = ws2;
|
|
@@ -34733,8 +34866,15 @@ function claudeQuestionDialog(text5) {
|
|
|
34733
34866
|
}
|
|
34734
34867
|
async function answerClaudeQuestionDialog(io, questions, answers, options = {}) {
|
|
34735
34868
|
const from = options.from ?? 0, submit = options.submit ?? true;
|
|
34869
|
+
let sent = false;
|
|
34870
|
+
const changed = (message) => refusal(message, sent);
|
|
34871
|
+
const realKeys = io.keys.bind(io);
|
|
34872
|
+
io = { ...io, keys: async (keys2) => {
|
|
34873
|
+
sent = true;
|
|
34874
|
+
await realKeys(keys2);
|
|
34875
|
+
} };
|
|
34736
34876
|
const sleep5 = io.sleep ?? ((ms2) => new Promise((resolve17) => setTimeout(resolve17, ms2)));
|
|
34737
|
-
const matches = (screen, index2) => screen?.kind === "question" && screen.title
|
|
34877
|
+
const matches = (screen, index2) => screen?.kind === "question" && sameTitle(screen.title, questions[index2].question);
|
|
34738
34878
|
const settle2 = async (check2, ms2 = 2e3) => {
|
|
34739
34879
|
for (let waited = 0; ; waited += 120) {
|
|
34740
34880
|
const value2 = check2(claudeQuestionDialog(await io.read()));
|
|
@@ -34748,8 +34888,8 @@ async function answerClaudeQuestionDialog(io, questions, answers, options = {})
|
|
|
34748
34888
|
if (initial.tabs.length !== questions.length) throw changed("The terminal is asking a different set of questions.");
|
|
34749
34889
|
const reach = async (index2) => {
|
|
34750
34890
|
const screen = await settle2((value2) => value2);
|
|
34751
|
-
if (screen?.kind === "question" && screen.title
|
|
34752
|
-
const at2 = screen?.kind === "review" ? questions.length : screen?.kind === "question" ? questions.findIndex((question2) =>
|
|
34891
|
+
if (screen?.kind === "question" && sameTitle(screen.title, questions[index2].question)) return screen;
|
|
34892
|
+
const at2 = screen?.kind === "review" ? questions.length : screen?.kind === "question" ? questions.findIndex((question2) => sameTitle(screen.title, question2.question)) : -1;
|
|
34753
34893
|
if (at2 < 0) throw changed("The terminal is showing a different question.");
|
|
34754
34894
|
if (screen?.kind === "question" && screen.other && screen.cursor === screen.other.number) await io.keys(["up"]);
|
|
34755
34895
|
await io.keys(Array(Math.abs(index2 - at2)).fill(index2 > at2 ? "right" : "left"));
|
|
@@ -34763,7 +34903,7 @@ async function answerClaudeQuestionDialog(io, questions, answers, options = {})
|
|
|
34763
34903
|
if (!question2) throw new BridgeError(400, "The answer names a question that was not asked.");
|
|
34764
34904
|
const typed = answer.text?.trim() ?? "";
|
|
34765
34905
|
let screen = await reach(index2);
|
|
34766
|
-
if (screen.multiSelect !== !!question2.multiSelect || screen.options.length !== question2.options.length || screen.options.some((row, position) => row.label
|
|
34906
|
+
if (screen.multiSelect !== !!question2.multiSelect || screen.options.length !== question2.options.length || screen.options.some((row, position) => !sameLabel(row.label, question2.options[position].label))) {
|
|
34767
34907
|
throw changed("The terminal's options differ from the question being answered.");
|
|
34768
34908
|
}
|
|
34769
34909
|
if (!screen.multiSelect) {
|
|
@@ -34812,14 +34952,13 @@ async function answerClaudeQuestionDialog(io, questions, answers, options = {})
|
|
|
34812
34952
|
const review = await settle2((value2) => value2?.kind === "review" ? value2 : value2 === void 0 ? "gone" : void 0, ANSWERED_MS);
|
|
34813
34953
|
if (review === "gone") return;
|
|
34814
34954
|
if (!review) throw changed("The terminal did not reach the review of the answers.");
|
|
34815
|
-
|
|
34816
|
-
if (review.answers.length !== questions.length || review.answers.some((row, position) => normalize(row.question) !== expected[position] || !row.answer)) {
|
|
34955
|
+
if (review.answers.length !== questions.length || review.answers.some((row, position) => !sameTitle(normalize(row.question), questions[position].question) || !row.answer)) {
|
|
34817
34956
|
throw changed("Not every question has an answer in the terminal.");
|
|
34818
34957
|
}
|
|
34819
34958
|
await io.keys(["1"]);
|
|
34820
34959
|
if (await settle2((value2) => value2 === void 0 ? "gone" : void 0, ANSWERED_MS) !== "gone") throw changed("The terminal did not submit the answers.");
|
|
34821
34960
|
}
|
|
34822
|
-
var TAB_BAR, ROW, NEXT, normalize, GUTTER,
|
|
34961
|
+
var TAB_BAR, ROW, NEXT, normalize, sameTitle, sameLabel, GUTTER, refusal, typedKeys;
|
|
34823
34962
|
var init_claude_question_dialog = __esm({
|
|
34824
34963
|
"src/bridge/claude-question-dialog.ts"() {
|
|
34825
34964
|
"use strict";
|
|
@@ -34828,8 +34967,17 @@ var init_claude_question_dialog = __esm({
|
|
|
34828
34967
|
ROW = /^\s*(❯)?\s*(\d)\.\s+(?:\[([ ✔])\]\s+)?(.*?)\s*$/;
|
|
34829
34968
|
NEXT = /^\s*(❯)?\s+(?:Next|Submit)\s*$/;
|
|
34830
34969
|
normalize = (text5) => text5.replace(/\s+/g, " ").trim();
|
|
34970
|
+
sameTitle = (shown, asked) => {
|
|
34971
|
+
const want = normalize(asked);
|
|
34972
|
+
if (shown === want) return true;
|
|
34973
|
+
return shown.endsWith("\u2026") && shown.length > 200 && want.startsWith(shown.slice(0, -1).trimEnd());
|
|
34974
|
+
};
|
|
34975
|
+
sameLabel = (shown, asked) => {
|
|
34976
|
+
const want = normalize(asked);
|
|
34977
|
+
return shown === want || shown.length >= 30 && want.startsWith(shown);
|
|
34978
|
+
};
|
|
34831
34979
|
GUTTER = /^(\s*)│(?: |$)/;
|
|
34832
|
-
|
|
34980
|
+
refusal = (message, sent) => sent ? new BridgeError(409, `${message} Some keys were already sent, so check the terminal before answering again, or cancel the question.`, { code: "question-unconfirmed" }) : new BridgeError(409, `${message} Nothing was sent; check the question and answer again, or cancel it.`, { code: "question-not-shown" });
|
|
34833
34981
|
typedKeys = (text5) => [...text5].map((character) => character === " " ? "space" : character);
|
|
34834
34982
|
}
|
|
34835
34983
|
});
|
|
@@ -36191,7 +36339,7 @@ function workspaceSnapshot(s, contextUsedPercent, approvalPanes, lastChanged, co
|
|
|
36191
36339
|
children: objects(s.tabs).filter((t) => t.workspace_id === w.workspace_id).map((t) => {
|
|
36192
36340
|
const panes2 = objects(s.panes).filter((p) => p.tab_id === t.tab_id && p.workspace_id === t.workspace_id);
|
|
36193
36341
|
const agent = panes2.find((p) => p.agent);
|
|
36194
|
-
const
|
|
36342
|
+
const changed = Math.max(0, ...panes2.map((p) => Number.isSafeInteger(p.state_change_seq) ? Number(p.state_change_seq) : 0));
|
|
36195
36343
|
return {
|
|
36196
36344
|
id: t.tab_id,
|
|
36197
36345
|
label: t.label,
|
|
@@ -36201,7 +36349,7 @@ function workspaceSnapshot(s, contextUsedPercent, approvalPanes, lastChanged, co
|
|
|
36201
36349
|
agentStatus: t.agent_status,
|
|
36202
36350
|
cwd: agent?.foreground_cwd || agent?.cwd,
|
|
36203
36351
|
role: (conductorPane2 === void 0 ? isConductorName(paneAgentName(s, agent)) : !!agent && agent.pane_id === conductorPane2) ? "conductor" : void 0,
|
|
36204
|
-
changedSeq:
|
|
36352
|
+
changedSeq: changed || void 0,
|
|
36205
36353
|
lastChangedAt: lastChanged?.get(tabActivityKey(t.workspace_id, t.tab_id)),
|
|
36206
36354
|
approvalPending: panes2.some((p) => approvalPanes?.has(String(p.pane_id))) || void 0,
|
|
36207
36355
|
contextUsedPercent: agent && panes2.filter((p) => p.agent).length === 1 ? contextUsedPercent?.get(agent) : void 0,
|
|
@@ -37852,7 +38000,7 @@ var init_package_metadata = __esm({
|
|
|
37852
38000
|
__dirname = path37.dirname(fileURLToPath2(import.meta.url));
|
|
37853
38001
|
ROOT = path37.join(__dirname, "..");
|
|
37854
38002
|
PACKAGE_JSON_PATH = path37.join(ROOT, "package.json");
|
|
37855
|
-
BUNDLED_VERSION = true ? "0.3.
|
|
38003
|
+
BUNDLED_VERSION = true ? "0.3.46" : "0.0.0";
|
|
37856
38004
|
PACKAGE_JSON = readPackageJson();
|
|
37857
38005
|
PACKAGE_NAME = PACKAGE_JSON.name || "phren";
|
|
37858
38006
|
VERSION = PACKAGE_JSON.version || BUNDLED_VERSION;
|
|
@@ -40362,6 +40510,14 @@ function settleClaudeUsage(usage, now) {
|
|
|
40362
40510
|
const since = usage.updatedAt?.slice(0, 10);
|
|
40363
40511
|
return { ...usage, windows, message: `No usage report from Claude on this computer${since ? ` since ${since}` : ""}. It updates when Claude Code runs here.` };
|
|
40364
40512
|
}
|
|
40513
|
+
function bounded(read, fallback2, ms2 = USAGE_READ_LIMIT_MS) {
|
|
40514
|
+
let timer;
|
|
40515
|
+
const late = new Promise((resolve17) => {
|
|
40516
|
+
timer = setTimeout(() => resolve17(fallback2()), ms2);
|
|
40517
|
+
timer.unref?.();
|
|
40518
|
+
});
|
|
40519
|
+
return Promise.race([read, late]).finally(() => clearTimeout(timer));
|
|
40520
|
+
}
|
|
40365
40521
|
function usageStatusLine(current2, program, remove) {
|
|
40366
40522
|
const prefix = `${quote2(process.execPath)} ${quote2(program)} usage-statusline `;
|
|
40367
40523
|
const command = object2(current2).command;
|
|
@@ -40408,7 +40564,7 @@ async function captureClaudeUsage(original) {
|
|
|
40408
40564
|
});
|
|
40409
40565
|
}
|
|
40410
40566
|
}
|
|
40411
|
-
var exec7, claudeFile, safeText, openCodeAuthFile, GO_GATEWAY, GO_KEY_MESSAGE, GO_WINDOWS, openCodeLogDir, refusalScans, FIRST_SCAN_BYTES, clock, goPlanCached, goPlanPending, claudeCredentialsFile, isCreditWindow, CLAUDE_REPORT_MAX_AGE_MS, OPENCODE_STATS_REUSE_MS, AccountUsageReader, quote2;
|
|
40567
|
+
var exec7, claudeFile, safeText, openCodeAuthFile, GO_GATEWAY, GO_KEY_MESSAGE, GO_WINDOWS, openCodeLogDir, refusalScans, FIRST_SCAN_BYTES, clock, goPlanCached, goPlanPending, claudeCredentialsFile, isCreditWindow, CLAUDE_REPORT_MAX_AGE_MS, OPENCODE_STATS_REUSE_MS, USAGE_READ_LIMIT_MS, unanswered, AccountUsageReader, quote2;
|
|
40412
40568
|
var init_usage = __esm({
|
|
40413
40569
|
"src/bridge/usage.ts"() {
|
|
40414
40570
|
"use strict";
|
|
@@ -40444,6 +40600,8 @@ var init_usage = __esm({
|
|
|
40444
40600
|
isCreditWindow = (window2) => window2.id.startsWith("credit:");
|
|
40445
40601
|
CLAUDE_REPORT_MAX_AGE_MS = 3 * 864e5;
|
|
40446
40602
|
OPENCODE_STATS_REUSE_MS = 10 * 6e4;
|
|
40603
|
+
USAGE_READ_LIMIT_MS = 3e4;
|
|
40604
|
+
unanswered = (source, name) => ({ source, windows: [], message: `${name} did not answer in time on this computer. Phren will ask again shortly.` });
|
|
40447
40605
|
AccountUsageReader = class {
|
|
40448
40606
|
constructor(readCodex = readCodexLimits, now = Date.now, readClaudeLive = liveClaudeUsage, readOpenCode = (now2) => readOpenCodeUsage("opencode", now2), readOpenRouter = liveOpenRouterUsage, readOpenCodeGo = readOpenCodeGoUsage, readCopilot = readCopilotUsage, platform = process.platform, readElevenLabs = liveElevenLabsUsage, readAuth = (home) => claudeAuthStatus(home)) {
|
|
40449
40607
|
this.readCodex = readCodex;
|
|
@@ -40487,7 +40645,7 @@ var init_usage = __esm({
|
|
|
40487
40645
|
/** Codex and every Claude home, without the spend readers: what a dispatch capacity probe asks. */
|
|
40488
40646
|
async limits(allAccounts = true) {
|
|
40489
40647
|
if (!this.cached || this.now() - this.cached.at >= 6e4) {
|
|
40490
|
-
this.pending ??= this.readCodex().then((value2) => {
|
|
40648
|
+
this.pending ??= bounded(this.readCodex(), () => unanswered("codex", "Codex")).then((value2) => {
|
|
40491
40649
|
this.cached = { at: this.now(), value: value2 };
|
|
40492
40650
|
return value2;
|
|
40493
40651
|
}).finally(() => {
|
|
@@ -40500,7 +40658,7 @@ var init_usage = __esm({
|
|
|
40500
40658
|
const now = new Date(this.now());
|
|
40501
40659
|
const email3 = claudeAccountEmail(home);
|
|
40502
40660
|
const credits = claudeCredits(home.id);
|
|
40503
|
-
const auth = credits.length || claudePlanUnknown(home) ? await this.readAuth(home).catch(() => void 0) : void 0;
|
|
40661
|
+
const auth = credits.length || claudePlanUnknown(home) ? await bounded(this.readAuth(home).catch(() => void 0), () => void 0) : void 0;
|
|
40504
40662
|
const fallback2 = auth?.console ? "Console" : auth?.plan ? claudePlan({ subscriptionType: auth.plan }) : void 0;
|
|
40505
40663
|
const subscription2 = claudeAccountSubscription(home, now, fallback2);
|
|
40506
40664
|
const usage = settleClaudeUsage(await this.claude(home), this.now());
|
|
@@ -40520,10 +40678,10 @@ var init_usage = __esm({
|
|
|
40520
40678
|
if (!this.spendingPending.has(key4)) {
|
|
40521
40679
|
const pending = Promise.all([
|
|
40522
40680
|
this.openCode(at2),
|
|
40523
|
-
this.readOpenCodeGo(new Date(at2)),
|
|
40524
|
-
this.readOpenRouter(new Date(at2)),
|
|
40525
|
-
includeCopilot ? this.readCopilot(new Date(at2)) : Promise.resolve(void 0),
|
|
40526
|
-
includeElevenLabs ? this.readElevenLabs(new Date(at2)).catch(() => void 0) : Promise.resolve(void 0)
|
|
40681
|
+
bounded(this.readOpenCodeGo(new Date(at2)), () => unanswered("opencode-go", "OpenCode Go")),
|
|
40682
|
+
bounded(this.readOpenRouter(new Date(at2)), () => void 0),
|
|
40683
|
+
includeCopilot ? bounded(this.readCopilot(new Date(at2)), () => unanswered("copilot", "GitHub Copilot")) : Promise.resolve(void 0),
|
|
40684
|
+
includeElevenLabs ? bounded(this.readElevenLabs(new Date(at2)).catch(() => void 0), () => void 0) : Promise.resolve(void 0)
|
|
40527
40685
|
]).then(([openCode, openCodeGo, openRouter, copilot, elevenLabs2]) => [openCode, openCodeGo, ...openRouter ? [openRouter] : [], ...copilot ? [copilot] : [], ...elevenLabs2 ? [elevenLabs2] : []]).then((value2) => {
|
|
40528
40686
|
this.spendingCached.set(key4, { at: at2, value: value2 });
|
|
40529
40687
|
return value2;
|
|
@@ -40538,8 +40696,12 @@ var init_usage = __esm({
|
|
|
40538
40696
|
/** One `opencode stats` run serves every spending key for `OPENCODE_STATS_REUSE_MS`. */
|
|
40539
40697
|
openCode(at2) {
|
|
40540
40698
|
if (this.openCodeCached && at2 - this.openCodeCached.at < OPENCODE_STATS_REUSE_MS) return Promise.resolve(this.openCodeCached.value);
|
|
40541
|
-
|
|
40542
|
-
|
|
40699
|
+
let late = false;
|
|
40700
|
+
this.openCodePending ??= bounded(this.readOpenCode(new Date(at2)), () => {
|
|
40701
|
+
late = true;
|
|
40702
|
+
return unanswered("opencode", "opencode stats");
|
|
40703
|
+
}).then((value2) => {
|
|
40704
|
+
if (!late) this.openCodeCached = { at: at2, value: value2 };
|
|
40543
40705
|
return value2;
|
|
40544
40706
|
}).finally(() => {
|
|
40545
40707
|
this.openCodePending = void 0;
|
|
@@ -40555,7 +40717,7 @@ var init_usage = __esm({
|
|
|
40555
40717
|
const cached3 = this.claudeCached.get(home.dir);
|
|
40556
40718
|
if (!cached3 || this.now() - cached3.at >= 6e4) {
|
|
40557
40719
|
const at2 = this.now();
|
|
40558
|
-
if (!this.claudePending.has(home.dir)) this.claudePending.set(home.dir, this.readClaudeLive(new Date(at2), home).then((value2) => {
|
|
40720
|
+
if (!this.claudePending.has(home.dir)) this.claudePending.set(home.dir, bounded(this.readClaudeLive(new Date(at2), home), () => void 0).then((value2) => {
|
|
40559
40721
|
this.claudeCached.set(home.dir, { at: at2, value: value2 });
|
|
40560
40722
|
return value2;
|
|
40561
40723
|
}).catch(() => {
|
|
@@ -40634,9 +40796,9 @@ async function mergeMcpServers(file4, servers2) {
|
|
|
40634
40796
|
async function syncAccountMcpServers(env = process.env) {
|
|
40635
40797
|
const homes = claudeHomes(env);
|
|
40636
40798
|
const servers2 = await mcpServersOf(homes[0].configFile);
|
|
40637
|
-
const
|
|
40638
|
-
for (const home of homes.slice(1)) if (await mergeMcpServers(home.configFile, servers2))
|
|
40639
|
-
return
|
|
40799
|
+
const changed = [];
|
|
40800
|
+
for (const home of homes.slice(1)) if (await mergeMcpServers(home.configFile, servers2)) changed.push(home.id);
|
|
40801
|
+
return changed;
|
|
40640
40802
|
}
|
|
40641
40803
|
async function addClaudeAccount(slug, opts = {}) {
|
|
40642
40804
|
const env = opts.env ?? process.env;
|
|
@@ -41389,7 +41551,7 @@ function keyOptions(line) {
|
|
|
41389
41551
|
return void 0;
|
|
41390
41552
|
}
|
|
41391
41553
|
function upgradeKeys(text5) {
|
|
41392
|
-
let
|
|
41554
|
+
let changed = 0;
|
|
41393
41555
|
const result = text5.split(/(?<=\n)/).map((line) => {
|
|
41394
41556
|
const parsed = keyOptions(line);
|
|
41395
41557
|
if (!parsed || parsed.options[0] !== "restrict" || !/^\s+ssh-ed25519 [A-Za-z0-9+/=]+ phren-(?:iphone|android)\s*$/.test(parsed.rest)) return line;
|
|
@@ -41398,10 +41560,10 @@ function upgradeKeys(text5) {
|
|
|
41398
41560
|
const options = parsed.options.filter((option) => option.toLowerCase() !== "port-forwarding" && !option.toLowerCase().startsWith("permitopen=")).map((option) => old.test(option) ? forcedCommand : option);
|
|
41399
41561
|
if (!options.includes("pty")) options.splice(1, 0, "pty");
|
|
41400
41562
|
const next = options.join(",") + parsed.rest;
|
|
41401
|
-
if (next !== line)
|
|
41563
|
+
if (next !== line) changed++;
|
|
41402
41564
|
return next;
|
|
41403
41565
|
}).join("");
|
|
41404
|
-
return { text: result, changed
|
|
41566
|
+
return { text: result, changed };
|
|
41405
41567
|
}
|
|
41406
41568
|
async function extraLaunchAgentEnvironment(file4, read = async (f) => (await exec8("plutil", ["-convert", "json", "-o", "-", f])).stdout) {
|
|
41407
41569
|
let parsed;
|
|
@@ -42088,6 +42250,33 @@ async function hookPeers(root = bridgeRoot()) {
|
|
|
42088
42250
|
}
|
|
42089
42251
|
async function addHookPeer(input2, root = bridgeRoot()) {
|
|
42090
42252
|
const peer = peerSchema.parse(input2);
|
|
42253
|
+
return lockedHooksYaml(root, () => addHookPeerNow(peer, root));
|
|
42254
|
+
}
|
|
42255
|
+
async function lockedHooksYaml(root, work) {
|
|
42256
|
+
const file4 = path55.join(path55.resolve(root), "hooks.yaml");
|
|
42257
|
+
const previous = hooksYamlQueues.get(file4) ?? Promise.resolve();
|
|
42258
|
+
const next = previous.catch(() => void 0).then(async () => {
|
|
42259
|
+
const deadline = Date.now() + HOOKS_YAML_LOCK_WAIT_MS;
|
|
42260
|
+
let release = tryFileLock(file4);
|
|
42261
|
+
while (!release) {
|
|
42262
|
+
if (Date.now() >= deadline) throw new BridgeError(409, "hooks.yaml is being changed by another process. Try again.");
|
|
42263
|
+
await new Promise((resolve17) => setTimeout(resolve17, 50));
|
|
42264
|
+
release = tryFileLock(file4);
|
|
42265
|
+
}
|
|
42266
|
+
try {
|
|
42267
|
+
return await work();
|
|
42268
|
+
} finally {
|
|
42269
|
+
release();
|
|
42270
|
+
}
|
|
42271
|
+
});
|
|
42272
|
+
hooksYamlQueues.set(file4, next);
|
|
42273
|
+
try {
|
|
42274
|
+
return await next;
|
|
42275
|
+
} finally {
|
|
42276
|
+
if (hooksYamlQueues.get(file4) === next) hooksYamlQueues.delete(file4);
|
|
42277
|
+
}
|
|
42278
|
+
}
|
|
42279
|
+
async function addHookPeerNow(peer, root) {
|
|
42091
42280
|
const existing = await hookPeers(root).catch((error62) => {
|
|
42092
42281
|
if (error62 instanceof BridgeError && error62.details?.hooksYaml === "missing") return [];
|
|
42093
42282
|
throw error62;
|
|
@@ -42233,12 +42422,13 @@ async function peerRequest(peer, route2, data, timeout) {
|
|
|
42233
42422
|
await rm8(temporary, { recursive: true, force: true });
|
|
42234
42423
|
}
|
|
42235
42424
|
}
|
|
42236
|
-
var peerSchema, lastPeerError;
|
|
42425
|
+
var peerSchema, hooksYamlQueues, HOOKS_YAML_LOCK_WAIT_MS, lastPeerError;
|
|
42237
42426
|
var init_peers = __esm({
|
|
42238
42427
|
"src/bridge/peers.ts"() {
|
|
42239
42428
|
"use strict";
|
|
42240
42429
|
init_js_yaml();
|
|
42241
42430
|
init_zod();
|
|
42431
|
+
init_locks();
|
|
42242
42432
|
init_logger();
|
|
42243
42433
|
init_client();
|
|
42244
42434
|
init_computers();
|
|
@@ -42251,6 +42441,8 @@ var init_peers = __esm({
|
|
|
42251
42441
|
hostKey: external_exports.string().transform(publicComputerKey),
|
|
42252
42442
|
server: serverName.default("default")
|
|
42253
42443
|
}).strict();
|
|
42444
|
+
hooksYamlQueues = /* @__PURE__ */ new Map();
|
|
42445
|
+
HOOKS_YAML_LOCK_WAIT_MS = 5e3;
|
|
42254
42446
|
}
|
|
42255
42447
|
});
|
|
42256
42448
|
|
|
@@ -42528,6 +42720,7 @@ var init_schedule_format = __esm({
|
|
|
42528
42720
|
init_zod();
|
|
42529
42721
|
init_protocol();
|
|
42530
42722
|
init_utils_paths();
|
|
42723
|
+
init_locks();
|
|
42531
42724
|
init_claude_accounts();
|
|
42532
42725
|
SCHEDULE_EVERY = ["interval", "daily", "weekly", "once", "cron"];
|
|
42533
42726
|
SCHEDULE_HARNESSES = ["claude", "codex", "opencode", "copilot"];
|
|
@@ -42555,6 +42748,9 @@ import { stat as stat15 } from "node:fs/promises";
|
|
|
42555
42748
|
import path57 from "node:path";
|
|
42556
42749
|
async function scheduleProblems(schedule, project, options) {
|
|
42557
42750
|
const problems = [];
|
|
42751
|
+
if ((schedule.prompt.match(/[\p{L}\p{N}]/gu) ?? []).length < 3) {
|
|
42752
|
+
problems.push("The prompt has no words in it, so every run would start with an empty brief. Set a prompt with --prompt or --prompt-file.");
|
|
42753
|
+
}
|
|
42558
42754
|
const machines = listMachines(options.store);
|
|
42559
42755
|
if (!options.owned && machines.ok && !Object.keys(machines.data).some((name) => canonicalComputer(name) === canonicalComputer(schedule.computer))) {
|
|
42560
42756
|
problems.push(`Computer "${schedule.computer}" is not a machine in this store, so no Hook will run this schedule.`);
|
|
@@ -44740,8 +44936,8 @@ async function readIntegrator() {
|
|
|
44740
44936
|
}
|
|
44741
44937
|
async function setIntegrator(input2) {
|
|
44742
44938
|
if (input2 === null) {
|
|
44743
|
-
const { rm:
|
|
44744
|
-
await
|
|
44939
|
+
const { rm: rm18 } = await import("node:fs/promises");
|
|
44940
|
+
await rm18(path62.join(bridgeRoot(), "integrator.json"), { force: true });
|
|
44745
44941
|
return { ok: true, integrator: null };
|
|
44746
44942
|
}
|
|
44747
44943
|
const data = integratorSchema.parse(input2);
|
|
@@ -44973,11 +45169,11 @@ function approvalSummary(value2) {
|
|
|
44973
45169
|
requestKind = "tool";
|
|
44974
45170
|
} else {
|
|
44975
45171
|
const patch = string4(input2.patch) ?? (typeof value2.input === "string" ? value2.input : void 0);
|
|
44976
|
-
const
|
|
45172
|
+
const changed = patch ? new Set([...patch.matchAll(/^\*\*\* (?:Add|Update|Delete) File: (.+)$|^diff --git a\/(.+?) b\/(.+)$/gm)].map((match) => match[1] ?? match[3])).size : 0;
|
|
44977
45173
|
const file4 = string4(input2.file_path) ?? string4(input2.filePath) ?? string4(input2.path);
|
|
44978
|
-
if (
|
|
45174
|
+
if (changed > 1) line = `Apply patch: ${changed} files`;
|
|
44979
45175
|
else if (file4 && /(?:edit|write|patch|apply)/i.test(tool)) line = `${/write/i.test(tool) || /\*\*\* Add File:/.test(patch ?? "") ? "Write" : "Edit"}: ${relativeFile(file4, value2.cwd)}`;
|
|
44980
|
-
else if (
|
|
45176
|
+
else if (changed === 1 && patch) {
|
|
44981
45177
|
const match = /^\*\*\* (Add|Update|Delete) File: (.+)$/m.exec(patch);
|
|
44982
45178
|
line = match ? `${match[1] === "Add" ? "Write" : "Edit"}: ${relativeFile(match[2], value2.cwd)}` : "Apply patch: 1 file";
|
|
44983
45179
|
}
|
|
@@ -46299,7 +46495,7 @@ function observeApproval(receipt, value2, now) {
|
|
|
46299
46495
|
function observeState(receipt, parsed, now) {
|
|
46300
46496
|
let seen = parsed;
|
|
46301
46497
|
const at2 = new Date(now).toISOString();
|
|
46302
|
-
let
|
|
46498
|
+
let changed = false;
|
|
46303
46499
|
if (seen.session && receipt.target && !("session" in receipt.target)) {
|
|
46304
46500
|
const full2 = targetSchema.safeParse({
|
|
46305
46501
|
server: receipt.target.server,
|
|
@@ -46311,7 +46507,7 @@ function observeState(receipt, parsed, now) {
|
|
|
46311
46507
|
});
|
|
46312
46508
|
if (full2.success) {
|
|
46313
46509
|
receipt.target = full2.data;
|
|
46314
|
-
|
|
46510
|
+
changed = true;
|
|
46315
46511
|
}
|
|
46316
46512
|
}
|
|
46317
46513
|
const carried = seen.state === "working" && receipt.worker && receipt.worker.state !== "working" ? 0 : receipt.worker?.background ?? 0;
|
|
@@ -46339,18 +46535,18 @@ function observeState(receipt, parsed, now) {
|
|
|
46339
46535
|
if (repeated) {
|
|
46340
46536
|
if (receipt.worker && receipt.worker.sawWorking !== sawWorking) {
|
|
46341
46537
|
receipt.worker.sawWorking = sawWorking;
|
|
46342
|
-
|
|
46538
|
+
changed = true;
|
|
46343
46539
|
}
|
|
46344
46540
|
if (receipt.worker && background > (receipt.worker.background ?? 0)) {
|
|
46345
46541
|
receipt.worker.background = background;
|
|
46346
|
-
|
|
46542
|
+
changed = true;
|
|
46347
46543
|
}
|
|
46348
46544
|
if (receipt.worker && receipt.worker.waitingSince !== waitingSince) {
|
|
46349
46545
|
if (waitingSince) receipt.worker.waitingSince = waitingSince;
|
|
46350
46546
|
else delete receipt.worker.waitingSince;
|
|
46351
|
-
|
|
46547
|
+
changed = true;
|
|
46352
46548
|
}
|
|
46353
|
-
return
|
|
46549
|
+
return changed;
|
|
46354
46550
|
}
|
|
46355
46551
|
receipt.worker = {
|
|
46356
46552
|
state: next,
|
|
@@ -46672,9 +46868,9 @@ var init_dispatch_returns = __esm({
|
|
|
46672
46868
|
const seen = await this.grantAnswered(receipt, workers[index2]);
|
|
46673
46869
|
let fresh;
|
|
46674
46870
|
const current2 = await updateReceipt(receipt.id, (value2) => {
|
|
46675
|
-
const before = value2.approval?.actionId,
|
|
46871
|
+
const before = value2.approval?.actionId, changed = observe(value2, seen, this.now());
|
|
46676
46872
|
if (value2.approval && value2.approval.actionId !== before) fresh = value2.approval;
|
|
46677
|
-
return
|
|
46873
|
+
return changed;
|
|
46678
46874
|
}).catch(() => void 0);
|
|
46679
46875
|
if (!fresh || !current2) continue;
|
|
46680
46876
|
const pushed = await Promise.resolve(this.onApproval?.(current2, fresh)).catch(() => void 0);
|
|
@@ -48726,10 +48922,12 @@ function unionTrailing(ourTrailing, theirTrailing) {
|
|
|
48726
48922
|
function significantLines(content) {
|
|
48727
48923
|
return content.split("\n").slice(1).map((line) => line.trim()).filter((line) => line !== "").filter((line) => !(line.startsWith("## ") && /^\d{4}-\d{2}-\d{2}$/.test(line.slice(3).trim())));
|
|
48728
48924
|
}
|
|
48729
|
-
function mergeFindings(ours, theirs) {
|
|
48730
|
-
const
|
|
48925
|
+
function mergeFindings(ours, theirs, base) {
|
|
48926
|
+
const removed = base === void 0 ? /* @__PURE__ */ new Map() : removedFindings(base, ours, theirs);
|
|
48927
|
+
const { text: text5, dedupedContinuations } = buildMergedFindings(ours, theirs, removed);
|
|
48928
|
+
const removedLines = new Set([...removed.values()].flatMap((block) => block.split("\n").map((line) => line.trim())));
|
|
48731
48929
|
const present2 = new Set(text5.split("\n").map((line) => line.trim()));
|
|
48732
|
-
const lost = [...significantLines(ours), ...significantLines(theirs)].filter((line) => !present2.has(line)).filter((line) => !dedupedContinuations.has(line));
|
|
48930
|
+
const lost = [...significantLines(ours), ...significantLines(theirs)].filter((line) => !present2.has(line)).filter((line) => !dedupedContinuations.has(line)).filter((line) => !removedLines.has(line));
|
|
48733
48931
|
if (lost.length > 0) {
|
|
48734
48932
|
throw new FindingsMergeLossError(
|
|
48735
48933
|
`Refusing to auto-merge ${FINDINGS_FILENAME}: ${lost.length} line(s) would be dropped, starting with "${lost[0].slice(0, 80)}". Resolve this conflict by hand.`
|
|
@@ -48737,7 +48935,20 @@ function mergeFindings(ours, theirs) {
|
|
|
48737
48935
|
}
|
|
48738
48936
|
return text5;
|
|
48739
48937
|
}
|
|
48740
|
-
function
|
|
48938
|
+
function removedFindings(base, ours, theirs) {
|
|
48939
|
+
const blocks = (content) => {
|
|
48940
|
+
const byKey = /* @__PURE__ */ new Map();
|
|
48941
|
+
for (const list of parseFindings(content).dates.values()) for (const block of list) byKey.set(findingBulletText(block), block);
|
|
48942
|
+
return byKey;
|
|
48943
|
+
};
|
|
48944
|
+
const [b, o, t] = [blocks(base), blocks(ours), blocks(theirs)];
|
|
48945
|
+
const removed = /* @__PURE__ */ new Map();
|
|
48946
|
+
for (const [key4, block] of b) {
|
|
48947
|
+
if (!o.has(key4) && t.get(key4) === block || !t.has(key4) && o.get(key4) === block) removed.set(key4, block);
|
|
48948
|
+
}
|
|
48949
|
+
return removed;
|
|
48950
|
+
}
|
|
48951
|
+
function buildMergedFindings(ours, theirs, removed = /* @__PURE__ */ new Map()) {
|
|
48741
48952
|
const ourSide = parseFindings(ours);
|
|
48742
48953
|
const theirSide = parseFindings(theirs);
|
|
48743
48954
|
const allDates = [.../* @__PURE__ */ new Set([...ourSide.dates.keys(), ...theirSide.dates.keys()])].sort().reverse();
|
|
@@ -48751,6 +48962,7 @@ function buildMergedFindings(ours, theirs) {
|
|
|
48751
48962
|
const merged = [];
|
|
48752
48963
|
for (const block of [...ourSide.dates.get(date5) ?? [], ...theirSide.dates.get(date5) ?? []]) {
|
|
48753
48964
|
const key4 = findingBulletText(block);
|
|
48965
|
+
if (removed.has(key4)) continue;
|
|
48754
48966
|
if (seen.has(key4)) {
|
|
48755
48967
|
for (const line of block.split("\n").slice(1)) {
|
|
48756
48968
|
const trimmed = line.trim();
|
|
@@ -49230,7 +49442,8 @@ var init_task_format = __esm({
|
|
|
49230
49442
|
// src/bridge/memory-store.ts
|
|
49231
49443
|
import { execFile as execFile16, spawn as spawn8 } from "node:child_process";
|
|
49232
49444
|
import { createHash as createHash21 } from "node:crypto";
|
|
49233
|
-
import {
|
|
49445
|
+
import { mkdirSync as mkdirSync16, readFileSync as readFileSync32, renameSync as renameSync9, unlinkSync as unlinkSync6, writeFileSync as writeFileSync14 } from "node:fs";
|
|
49446
|
+
import { lstat as lstat21, mkdir as mkdir21, realpath as realpath11 } from "node:fs/promises";
|
|
49234
49447
|
import path75 from "node:path";
|
|
49235
49448
|
import { promisify as promisify14 } from "node:util";
|
|
49236
49449
|
function serialized2(work) {
|
|
@@ -49407,12 +49620,21 @@ async function storeFile(store, relative5) {
|
|
|
49407
49620
|
if (info && !info.isFile()) throw new BridgeError(400, "Invalid store path.");
|
|
49408
49621
|
return file4;
|
|
49409
49622
|
}
|
|
49410
|
-
|
|
49411
|
-
|
|
49623
|
+
function lockedStoreFile(file4, rel, work) {
|
|
49624
|
+
try {
|
|
49625
|
+
withFileLock(file4, work);
|
|
49626
|
+
} catch (error62) {
|
|
49627
|
+
if (error62 instanceof BridgeError || !/could not acquire lock/.test(String(error62?.message))) throw error62;
|
|
49628
|
+
throw new BridgeError(409, `${rel} is being written on this computer (its lock is held). Try again.`);
|
|
49629
|
+
}
|
|
49630
|
+
}
|
|
49631
|
+
function currentShaSync(file4) {
|
|
49632
|
+
try {
|
|
49633
|
+
return blobSha(readFileSync32(file4));
|
|
49634
|
+
} catch (error62) {
|
|
49412
49635
|
if (error62.code === "ENOENT") return null;
|
|
49413
49636
|
throw error62;
|
|
49414
|
-
}
|
|
49415
|
-
return content === null ? null : blobSha(content);
|
|
49637
|
+
}
|
|
49416
49638
|
}
|
|
49417
49639
|
function putStoreFile(store, data) {
|
|
49418
49640
|
const input2 = putSchema.parse(data);
|
|
@@ -49420,11 +49642,13 @@ function putStoreFile(store, data) {
|
|
|
49420
49642
|
if (content.length > MAX_FILE) throw new BridgeError(413, "This file is too large for the phone to write.");
|
|
49421
49643
|
return serialized2(async () => {
|
|
49422
49644
|
const file4 = await storeFile(store, input2.path);
|
|
49423
|
-
|
|
49424
|
-
|
|
49425
|
-
|
|
49426
|
-
|
|
49427
|
-
|
|
49645
|
+
lockedStoreFile(file4, input2.path, () => {
|
|
49646
|
+
if (currentShaSync(file4) !== (input2.sha ?? null)) throw new BridgeError(409, `${input2.path} changed on this computer.`);
|
|
49647
|
+
mkdirSync16(path75.dirname(file4), { recursive: true });
|
|
49648
|
+
const temporary = `${file4}.phren-${process.pid}-${Date.now()}`;
|
|
49649
|
+
writeFileSync14(temporary, content, { flag: "wx" });
|
|
49650
|
+
renameSync9(temporary, file4);
|
|
49651
|
+
});
|
|
49428
49652
|
return { content: { sha: blobSha(content), path: input2.path }, commit: { sha: blobSha(content) } };
|
|
49429
49653
|
});
|
|
49430
49654
|
}
|
|
@@ -49432,8 +49656,10 @@ function deleteStoreFile(store, data) {
|
|
|
49432
49656
|
const input2 = deleteSchema.parse(data);
|
|
49433
49657
|
return serialized2(async () => {
|
|
49434
49658
|
const file4 = await storeFile(store, input2.path);
|
|
49435
|
-
|
|
49436
|
-
|
|
49659
|
+
lockedStoreFile(file4, input2.path, () => {
|
|
49660
|
+
if (currentShaSync(file4) !== input2.sha) throw new BridgeError(409, `${input2.path} changed on this computer.`);
|
|
49661
|
+
unlinkSync6(file4);
|
|
49662
|
+
});
|
|
49437
49663
|
return { ok: true };
|
|
49438
49664
|
});
|
|
49439
49665
|
}
|
|
@@ -49451,6 +49677,7 @@ var init_memory_store = __esm({
|
|
|
49451
49677
|
"src/bridge/memory-store.ts"() {
|
|
49452
49678
|
"use strict";
|
|
49453
49679
|
init_zod();
|
|
49680
|
+
init_locks();
|
|
49454
49681
|
init_protocol();
|
|
49455
49682
|
exec12 = promisify14(execFile16);
|
|
49456
49683
|
SHA = /^[0-9a-f]{40}$/;
|
|
@@ -50976,7 +51203,7 @@ function resolveDuplicateMatches(matches) {
|
|
|
50976
51203
|
const first = bulletContentKey(matches[0].line);
|
|
50977
51204
|
return matches.every(({ line }) => bulletContentKey(line) === first) ? matches[0] : null;
|
|
50978
51205
|
}
|
|
50979
|
-
function findMatchingFindingBullet(bulletLines, needle, match) {
|
|
51206
|
+
function findMatchingFindingBullet(bulletLines, needle, match, exactOnly = false) {
|
|
50980
51207
|
const fidNeedle = needle.replace(/^fid:/, "");
|
|
50981
51208
|
const fidMatch = /^[a-z0-9]{8}$/.test(fidNeedle) ? bulletLines.filter(({ line }) => new RegExp(`<!--\\s*fid:${fidNeedle}\\s*-->`).test(line)) : [];
|
|
50982
51209
|
const exactMatches = bulletLines.filter(
|
|
@@ -50990,6 +51217,14 @@ function findMatchingFindingBullet(bulletLines, needle, match) {
|
|
|
50990
51217
|
if (dup) return { kind: "found", idx: dup.i };
|
|
50991
51218
|
return { kind: "ambiguous", error: `"${match}" is ambiguous (${exactMatches.length} exact matches). Use a more specific phrase.` };
|
|
50992
51219
|
}
|
|
51220
|
+
if (exactOnly) {
|
|
51221
|
+
const bare = withoutTypeTag(needle);
|
|
51222
|
+
const tagged = bulletLines.filter(({ line }) => withoutTypeTag(normalizeFindingText(line)) === bare);
|
|
51223
|
+
if (tagged.length === 0) return { kind: "not_found" };
|
|
51224
|
+
const dup = tagged.length === 1 ? tagged[0] : resolveDuplicateMatches(tagged);
|
|
51225
|
+
if (dup) return { kind: "found", idx: dup.i };
|
|
51226
|
+
return { kind: "ambiguous", error: `"${match}" is ambiguous (${tagged.length} matches). Use a more specific phrase.` };
|
|
51227
|
+
}
|
|
50993
51228
|
if (partialMatches.length === 1) return { kind: "found", idx: partialMatches[0].i };
|
|
50994
51229
|
if (partialMatches.length > 1) {
|
|
50995
51230
|
const dup = resolveDuplicateMatches(partialMatches);
|
|
@@ -51107,7 +51342,7 @@ function parseFindingsContent(content, opts = {}) {
|
|
|
51107
51342
|
}
|
|
51108
51343
|
return items;
|
|
51109
51344
|
}
|
|
51110
|
-
function removeFinding(phrenPath, project, match) {
|
|
51345
|
+
function removeFinding(phrenPath, project, match, opts = {}) {
|
|
51111
51346
|
const ensured = ensureProject(phrenPath, project);
|
|
51112
51347
|
if (!ensured.ok) return forwardErr(ensured);
|
|
51113
51348
|
const findingsPath = path83.resolve(path83.join(ensured.data, FINDINGS_FILENAME));
|
|
@@ -51120,12 +51355,12 @@ function removeFinding(phrenPath, project, match) {
|
|
|
51120
51355
|
const lines = fs36.readFileSync(filePath, "utf8").split("\n");
|
|
51121
51356
|
const needle = normalizeFindingText(match);
|
|
51122
51357
|
const bulletLines = collectFindingBulletLines(lines);
|
|
51123
|
-
const activeMatch = findMatchingFindingBullet(bulletLines.filter(({ archived }) => !archived), needle, match);
|
|
51358
|
+
const activeMatch = findMatchingFindingBullet(bulletLines.filter(({ archived }) => !archived), needle, match, opts.exactOnly);
|
|
51124
51359
|
if (activeMatch.kind === "ambiguous") {
|
|
51125
51360
|
return phrenErr(activeMatch.error, PhrenError.AMBIGUOUS_MATCH);
|
|
51126
51361
|
}
|
|
51127
51362
|
if (activeMatch.kind === "not_found") {
|
|
51128
|
-
const archivedMatch = findMatchingFindingBullet(bulletLines.filter(({ archived }) => archived), needle, match);
|
|
51363
|
+
const archivedMatch = findMatchingFindingBullet(bulletLines.filter(({ archived }) => archived), needle, match, opts.exactOnly);
|
|
51129
51364
|
if (archivedMatch.kind === "ambiguous" || archivedMatch.kind === "found") {
|
|
51130
51365
|
return phrenErr(`Finding "${match}" is archived and read-only. Restore or re-add it before mutating history.`, PhrenError.VALIDATION_ERROR);
|
|
51131
51366
|
}
|
|
@@ -51181,6 +51416,7 @@ function editFinding(phrenPath, project, oldText, newText) {
|
|
|
51181
51416
|
return phrenOk(`Updated finding in ${project}`);
|
|
51182
51417
|
});
|
|
51183
51418
|
}
|
|
51419
|
+
var withoutTypeTag;
|
|
51184
51420
|
var init_access = __esm({
|
|
51185
51421
|
"src/data/access.ts"() {
|
|
51186
51422
|
"use strict";
|
|
@@ -51201,6 +51437,7 @@ var init_access = __esm({
|
|
|
51201
51437
|
init_governance();
|
|
51202
51438
|
init_filenames();
|
|
51203
51439
|
init_filenames();
|
|
51440
|
+
withoutTypeTag = (text5) => text5.replace(/^\[[a-z-]+\]\s*/i, "");
|
|
51204
51441
|
}
|
|
51205
51442
|
});
|
|
51206
51443
|
|
|
@@ -52007,6 +52244,7 @@ var init_summarize = __esm({
|
|
|
52007
52244
|
init_store_routing();
|
|
52008
52245
|
init_phren_paths();
|
|
52009
52246
|
init_utils();
|
|
52247
|
+
init_locks();
|
|
52010
52248
|
NOW_START = "<!-- phren:now:start -->";
|
|
52011
52249
|
NOW_END = "<!-- phren:now:end -->";
|
|
52012
52250
|
KNOWS_START = "<!-- phren:knows:start -->";
|
|
@@ -52205,6 +52443,19 @@ ${entry2.lines.join("\n")}` : void 0;
|
|
|
52205
52443
|
}
|
|
52206
52444
|
});
|
|
52207
52445
|
|
|
52446
|
+
// src/data/notes.ts
|
|
52447
|
+
var NOTE_HEADING_RE;
|
|
52448
|
+
var init_notes = __esm({
|
|
52449
|
+
"src/data/notes.ts"() {
|
|
52450
|
+
"use strict";
|
|
52451
|
+
init_shared();
|
|
52452
|
+
init_dedup();
|
|
52453
|
+
init_phren_paths();
|
|
52454
|
+
init_data_utils();
|
|
52455
|
+
NOTE_HEADING_RE = /^##\s+(\d{2}:\d{2}(?::\d{2})?)\s+<!--\s*nid:([a-f0-9]{8})\s*-->(?:\s+<!--\s*promoted\s*-->)?\s*$/i;
|
|
52456
|
+
}
|
|
52457
|
+
});
|
|
52458
|
+
|
|
52208
52459
|
// src/sync/conflict-resolve.ts
|
|
52209
52460
|
import { execFileSync as execFileSync5, spawnSync as spawnSync2 } from "child_process";
|
|
52210
52461
|
import * as crypto11 from "crypto";
|
|
@@ -52221,7 +52472,8 @@ function conflictStrategy(relFile) {
|
|
|
52221
52472
|
if (name === "summary.md") return "summary";
|
|
52222
52473
|
if (name === "review.md" || name === "truths.md") return "union";
|
|
52223
52474
|
if (file4 === ".config/maintenance-writer.json") return "theirs";
|
|
52224
|
-
if (/(^|\/)
|
|
52475
|
+
if (/(^|\/)notes\/[^/]+\.md$/i.test(file4)) return "notes";
|
|
52476
|
+
if (/(^|\/)journal\/[^/]+\.md$/i.test(file4)) return "union";
|
|
52225
52477
|
return null;
|
|
52226
52478
|
}
|
|
52227
52479
|
function git4(cwd, args) {
|
|
@@ -52277,6 +52529,51 @@ function unionText(base, ours, theirs) {
|
|
|
52277
52529
|
fs39.rmSync(dir, { recursive: true, force: true });
|
|
52278
52530
|
}
|
|
52279
52531
|
}
|
|
52532
|
+
function noteBlocks(content) {
|
|
52533
|
+
const lines = content.split("\n");
|
|
52534
|
+
const first = lines.findIndex((line) => NOTE_HEADING_RE.test(line));
|
|
52535
|
+
const notes = /* @__PURE__ */ new Map();
|
|
52536
|
+
if (first === -1) return { header: content.trimEnd(), notes };
|
|
52537
|
+
let id2 = "";
|
|
52538
|
+
let body2 = [];
|
|
52539
|
+
const flush = () => {
|
|
52540
|
+
if (id2) notes.set(id2, body2.join("\n").trimEnd());
|
|
52541
|
+
};
|
|
52542
|
+
for (const line of lines.slice(first)) {
|
|
52543
|
+
const m = NOTE_HEADING_RE.exec(line);
|
|
52544
|
+
if (!m) {
|
|
52545
|
+
body2.push(line);
|
|
52546
|
+
continue;
|
|
52547
|
+
}
|
|
52548
|
+
flush();
|
|
52549
|
+
if (notes.has(m[2])) return null;
|
|
52550
|
+
id2 = m[2];
|
|
52551
|
+
body2 = [line];
|
|
52552
|
+
}
|
|
52553
|
+
flush();
|
|
52554
|
+
return { header: lines.slice(0, first).join("\n").trimEnd(), notes };
|
|
52555
|
+
}
|
|
52556
|
+
function mergeNotes(base, ours, theirs) {
|
|
52557
|
+
const b = noteBlocks(base);
|
|
52558
|
+
if (!b) return null;
|
|
52559
|
+
const deleted = { header: b.header, notes: /* @__PURE__ */ new Map() };
|
|
52560
|
+
const [o, t] = [ours === null ? deleted : noteBlocks(ours), theirs === null ? deleted : noteBlocks(theirs)];
|
|
52561
|
+
if (!o || !t) return null;
|
|
52562
|
+
const header = mergeText(b.header, o.header, t.header);
|
|
52563
|
+
if (header === null) return null;
|
|
52564
|
+
const out = [];
|
|
52565
|
+
for (const id2 of /* @__PURE__ */ new Set([...o.notes.keys(), ...t.notes.keys()])) {
|
|
52566
|
+
const [was, mine, incoming] = [b.notes.get(id2), o.notes.get(id2), t.notes.get(id2)];
|
|
52567
|
+
let note;
|
|
52568
|
+
if (mine === incoming || incoming === was) note = mine;
|
|
52569
|
+
else if (mine === was) note = incoming;
|
|
52570
|
+
else if (mine === void 0 || incoming === void 0) note = mine ?? incoming;
|
|
52571
|
+
else return null;
|
|
52572
|
+
if (note !== void 0) out.push(note);
|
|
52573
|
+
}
|
|
52574
|
+
if (!out.length && (ours === null || theirs === null)) return DELETED_FILE;
|
|
52575
|
+
return [header, ...out].join("\n\n") + "\n";
|
|
52576
|
+
}
|
|
52280
52577
|
function mergeWithGeneratedBlock(base, ours, theirs, start, end, where, merge2 = unionText) {
|
|
52281
52578
|
const b = splitBlock(base, start, end);
|
|
52282
52579
|
const o = splitBlock(ours, start, end);
|
|
@@ -52303,7 +52600,7 @@ function resolveContent(strategy, base, ours, theirs) {
|
|
|
52303
52600
|
case "tasks":
|
|
52304
52601
|
return orUnion(() => mergeTasksByBid(base, ours, theirs), base, ours, theirs, dedupe);
|
|
52305
52602
|
case "findings":
|
|
52306
|
-
return orUnion(() => mergeFindings(ours, theirs), base, ours, theirs);
|
|
52603
|
+
return orUnion(() => mergeFindings(ours, theirs, base), base, ours, theirs);
|
|
52307
52604
|
// Archived tasks only accumulate: keep both sides, the incoming version of any duplicate.
|
|
52308
52605
|
case "archive":
|
|
52309
52606
|
return dedupe(orUnion(() => mergeTask(theirs, ours), base, ours, theirs));
|
|
@@ -52314,6 +52611,10 @@ function resolveContent(strategy, base, ours, theirs) {
|
|
|
52314
52611
|
// summarize pass fold in anything only this machine had.
|
|
52315
52612
|
case "summary":
|
|
52316
52613
|
return mergeWithGeneratedBlock(base, ours, theirs, KNOWS_START, KNOWS_END, "bottom", mergeText) ?? theirs;
|
|
52614
|
+
case "notes": {
|
|
52615
|
+
const merged = mergeNotes(base, ours, theirs);
|
|
52616
|
+
return typeof merged === "string" ? merged : unionText(base, ours, theirs);
|
|
52617
|
+
}
|
|
52317
52618
|
case "union":
|
|
52318
52619
|
return unionText(base, ours, theirs);
|
|
52319
52620
|
case "theirs":
|
|
@@ -52345,7 +52646,13 @@ function resolveStoreConflicts(cwd) {
|
|
|
52345
52646
|
unresolved.push(relFile);
|
|
52346
52647
|
continue;
|
|
52347
52648
|
}
|
|
52348
|
-
const
|
|
52649
|
+
const notesMerge = strategy === "notes" && (ours === null || theirs === null) ? mergeNotes(base, ours, theirs) : null;
|
|
52650
|
+
if (notesMerge === DELETED_FILE) {
|
|
52651
|
+
git4(cwd, ["rm", "--quiet", "--force", "--ignore-unmatch", "--", relFile]);
|
|
52652
|
+
resolved.push(relFile);
|
|
52653
|
+
continue;
|
|
52654
|
+
}
|
|
52655
|
+
const merged = notesMerge ?? (ours === null ? theirs : theirs === null ? ours : resolveContent(strategy, base, ours, theirs));
|
|
52349
52656
|
if (merged === null) {
|
|
52350
52657
|
unresolved.push(relFile);
|
|
52351
52658
|
continue;
|
|
@@ -52363,7 +52670,7 @@ function resolveStoreConflicts(cwd) {
|
|
|
52363
52670
|
}
|
|
52364
52671
|
return { resolved, unresolved };
|
|
52365
52672
|
}
|
|
52366
|
-
var dedupe;
|
|
52673
|
+
var DELETED_FILE, dedupe;
|
|
52367
52674
|
var init_conflict_resolve = __esm({
|
|
52368
52675
|
"src/sync/conflict-resolve.ts"() {
|
|
52369
52676
|
"use strict";
|
|
@@ -52374,6 +52681,8 @@ var init_conflict_resolve = __esm({
|
|
|
52374
52681
|
init_validate();
|
|
52375
52682
|
init_summarize();
|
|
52376
52683
|
init_task_merge();
|
|
52684
|
+
init_notes();
|
|
52685
|
+
DELETED_FILE = /* @__PURE__ */ Symbol("deleted");
|
|
52377
52686
|
dedupe = (content) => content === null ? null : dedupeTaskIds(content).content;
|
|
52378
52687
|
}
|
|
52379
52688
|
});
|
|
@@ -52808,7 +53117,7 @@ var init_store_sync = __esm({
|
|
|
52808
53117
|
|
|
52809
53118
|
// src/bridge/health.ts
|
|
52810
53119
|
import { execFile as execFile19, spawn as spawn9 } from "node:child_process";
|
|
52811
|
-
import { lstat as lstat22, readFile as
|
|
53120
|
+
import { lstat as lstat22, readFile as readFile35 } from "node:fs/promises";
|
|
52812
53121
|
import { homedir as homedir14, hostname as hostname7 } from "node:os";
|
|
52813
53122
|
import path89 from "node:path";
|
|
52814
53123
|
import { promisify as promisify17 } from "node:util";
|
|
@@ -52942,11 +53251,16 @@ async function lastScheduledRun(store, runsFile = scheduleRunsFile()) {
|
|
|
52942
53251
|
const owner2 = newest2.scheduleProject ?? newest2.project;
|
|
52943
53252
|
const matching = runs.filter((run4) => (run4.scheduleProject ?? run4.project) === owner2 && run4.scheduleId === newest2.scheduleId && (newest2.batchId ? run4.batchId === newest2.batchId : run4.id === newest2.id));
|
|
52944
53253
|
const last = latestScheduleBatch(matching).lastRun;
|
|
52945
|
-
let name;
|
|
53254
|
+
let name, paused = false;
|
|
52946
53255
|
const directory = getProjectDirs(store).find((dir) => path89.basename(dir).toLowerCase() === owner2.toLowerCase());
|
|
52947
|
-
if (directory)
|
|
53256
|
+
if (directory) {
|
|
53257
|
+
const found = (await readScheduleDocument(directory).catch(() => void 0))?.schedules.find((item) => item.id === last.scheduleId);
|
|
53258
|
+
name = found?.name;
|
|
53259
|
+
paused = found?.enabled === false;
|
|
53260
|
+
}
|
|
52948
53261
|
return {
|
|
52949
53262
|
...name ? { name } : {},
|
|
53263
|
+
...paused ? { paused } : {},
|
|
52950
53264
|
project: owner2,
|
|
52951
53265
|
status: last.status,
|
|
52952
53266
|
...last.reason ? { reason: plainError(last.reason) } : {},
|
|
@@ -53004,7 +53318,7 @@ async function readCanary(root = bridgeRoot()) {
|
|
|
53004
53318
|
try {
|
|
53005
53319
|
const info = await lstat22(canaryFile(root));
|
|
53006
53320
|
if (!info.isFile() || info.size > 65536) return null;
|
|
53007
|
-
const value2 = JSON.parse(await
|
|
53321
|
+
const value2 = JSON.parse(await readFile35(canaryFile(root), "utf8"));
|
|
53008
53322
|
return value2 && value2.version === 1 && Array.isArray(value2.steps) ? value2 : null;
|
|
53009
53323
|
} catch {
|
|
53010
53324
|
return null;
|
|
@@ -53157,7 +53471,7 @@ var init_harnesses = __esm({
|
|
|
53157
53471
|
});
|
|
53158
53472
|
|
|
53159
53473
|
// src/bridge/account-choice.ts
|
|
53160
|
-
import { readFile as
|
|
53474
|
+
import { readFile as readFile36 } from "node:fs/promises";
|
|
53161
53475
|
import path91 from "node:path";
|
|
53162
53476
|
function windowRoom2(window2, now) {
|
|
53163
53477
|
if (!window2) return void 0;
|
|
@@ -53203,7 +53517,7 @@ function claudeRooms(inventory, usage, now) {
|
|
|
53203
53517
|
}
|
|
53204
53518
|
async function readAccountLimits(now = Date.now()) {
|
|
53205
53519
|
try {
|
|
53206
|
-
const parsed = ledgerSchema.parse(JSON.parse(await
|
|
53520
|
+
const parsed = ledgerSchema.parse(JSON.parse(await readFile36(limitsFile(), "utf8")));
|
|
53207
53521
|
return parsed.limits.filter((entry2) => Date.parse(entry2.until) > now);
|
|
53208
53522
|
} catch (error62) {
|
|
53209
53523
|
if (error62.code !== "ENOENT") logger.warn("accounts", `Could not read account-limits.json: ${error62 instanceof Error ? error62.message : String(error62)}`);
|
|
@@ -53297,7 +53611,7 @@ var init_account_choice = __esm({
|
|
|
53297
53611
|
|
|
53298
53612
|
// src/bridge/owner-inbox.ts
|
|
53299
53613
|
import { randomUUID as randomUUID21 } from "node:crypto";
|
|
53300
|
-
import { lstat as lstat23, mkdir as mkdir22, readFile as
|
|
53614
|
+
import { lstat as lstat23, mkdir as mkdir22, readFile as readFile37 } from "node:fs/promises";
|
|
53301
53615
|
import path92 from "node:path";
|
|
53302
53616
|
function sourceKey(row) {
|
|
53303
53617
|
const t = row.target;
|
|
@@ -53362,7 +53676,7 @@ var init_owner_inbox = __esm({
|
|
|
53362
53676
|
});
|
|
53363
53677
|
if (!info) return [];
|
|
53364
53678
|
if (!info.isFile() || info.isSymbolicLink() || info.size > 4 * 1024 * 1024) throw new BridgeError(409, "The owner inbox cannot be read safely.");
|
|
53365
|
-
return external_exports.array(itemSchema).max(1e4).parse(JSON.parse(await
|
|
53679
|
+
return external_exports.array(itemSchema).max(1e4).parse(JSON.parse(await readFile37(this.file, "utf8")));
|
|
53366
53680
|
}
|
|
53367
53681
|
run(input2) {
|
|
53368
53682
|
const run4 = this.pending.then(async () => {
|
|
@@ -53377,7 +53691,7 @@ var init_owner_inbox = __esm({
|
|
|
53377
53691
|
}
|
|
53378
53692
|
try {
|
|
53379
53693
|
const rows2 = await this.read(), at2 = (/* @__PURE__ */ new Date()).toISOString();
|
|
53380
|
-
let
|
|
53694
|
+
let changed = false;
|
|
53381
53695
|
if (data.action === "list") {
|
|
53382
53696
|
const observed = await this.sources();
|
|
53383
53697
|
const { sources, unavailableDispatches = [] } = Array.isArray(observed) ? { sources: observed } : observed;
|
|
@@ -53389,7 +53703,7 @@ var init_owner_inbox = __esm({
|
|
|
53389
53703
|
row.resolvedAt = at2;
|
|
53390
53704
|
row.updatedAt = at2;
|
|
53391
53705
|
row.resolution = reason2;
|
|
53392
|
-
|
|
53706
|
+
changed = true;
|
|
53393
53707
|
};
|
|
53394
53708
|
for (const row of rows2) {
|
|
53395
53709
|
if (row.kind === "manual") continue;
|
|
@@ -53400,7 +53714,7 @@ var init_owner_inbox = __esm({
|
|
|
53400
53714
|
if (row.live !== live) {
|
|
53401
53715
|
row.live = live;
|
|
53402
53716
|
row.updatedAt = at2;
|
|
53403
|
-
|
|
53717
|
+
changed = true;
|
|
53404
53718
|
}
|
|
53405
53719
|
if (!source) {
|
|
53406
53720
|
if (row.state === "open" && !unavailable) resolve17(row, "stale: source gone");
|
|
@@ -53413,14 +53727,14 @@ var init_owner_inbox = __esm({
|
|
|
53413
53727
|
retained.add(key4);
|
|
53414
53728
|
if (row.state === "open" && JSON.stringify({ ...row, ...source }) !== JSON.stringify(row)) {
|
|
53415
53729
|
Object.assign(row, source, { updatedAt: at2 });
|
|
53416
|
-
|
|
53730
|
+
changed = true;
|
|
53417
53731
|
}
|
|
53418
53732
|
}
|
|
53419
53733
|
for (const [key4, source] of active) {
|
|
53420
53734
|
if (retained.has(key4)) continue;
|
|
53421
53735
|
if (rows2.length >= 1e4) throw new BridgeError(409, "The owner inbox is full.");
|
|
53422
53736
|
rows2.push(itemSchema.parse({ ...source, id: randomUUID21(), state: "open", live: true, createdAt: at2, updatedAt: at2 }));
|
|
53423
|
-
|
|
53737
|
+
changed = true;
|
|
53424
53738
|
}
|
|
53425
53739
|
}
|
|
53426
53740
|
if (data.action === "add") {
|
|
@@ -53431,9 +53745,9 @@ var init_owner_inbox = __esm({
|
|
|
53431
53745
|
if (!prior) {
|
|
53432
53746
|
if (rows2.length >= 1e4) throw new BridgeError(409, "The owner inbox is full.");
|
|
53433
53747
|
rows2.push(item);
|
|
53434
|
-
|
|
53748
|
+
changed = true;
|
|
53435
53749
|
}
|
|
53436
|
-
if (
|
|
53750
|
+
if (changed) await atomicInPrivateDir(this.file, rows2);
|
|
53437
53751
|
return { ok: true, item: prior ?? item };
|
|
53438
53752
|
}
|
|
53439
53753
|
if (data.action === "resolve") {
|
|
@@ -53444,12 +53758,12 @@ var init_owner_inbox = __esm({
|
|
|
53444
53758
|
item.resolvedAt = at2;
|
|
53445
53759
|
item.updatedAt = at2;
|
|
53446
53760
|
item.resolution = data.resolution;
|
|
53447
|
-
|
|
53761
|
+
changed = true;
|
|
53448
53762
|
}
|
|
53449
|
-
if (
|
|
53763
|
+
if (changed) await atomicInPrivateDir(this.file, rows2);
|
|
53450
53764
|
return { ok: true, item };
|
|
53451
53765
|
}
|
|
53452
|
-
if (
|
|
53766
|
+
if (changed) await atomicInPrivateDir(this.file, rows2);
|
|
53453
53767
|
return { ok: true, items: rows2.filter((row) => data.includeResolved || row.state === "open" && (row.kind === "manual" || row.live === true)).sort((a, b) => a.createdAt.localeCompare(b.createdAt)) };
|
|
53454
53768
|
} finally {
|
|
53455
53769
|
release();
|
|
@@ -53568,7 +53882,7 @@ var init_owner_inbox_sources = __esm({
|
|
|
53568
53882
|
|
|
53569
53883
|
// src/bridge/hand-off-queue.ts
|
|
53570
53884
|
import { createHash as createHash24, randomUUID as randomUUID22 } from "node:crypto";
|
|
53571
|
-
import { lstat as lstat24, open as open16, readFile as
|
|
53885
|
+
import { lstat as lstat24, open as open16, readFile as readFile38, readdir as readdir14, unlink as unlink5 } from "node:fs/promises";
|
|
53572
53886
|
import path93 from "node:path";
|
|
53573
53887
|
var queuedHandOffSchema, rowSchema, DAY3, HAND_OFF_RETENTION_MS, HAND_OFF_MAX_ROWS, settled2, samePane, HandOffQueue;
|
|
53574
53888
|
var init_hand_off_queue = __esm({
|
|
@@ -53640,7 +53954,7 @@ var init_hand_off_queue = __esm({
|
|
|
53640
53954
|
});
|
|
53641
53955
|
if (!info) return void 0;
|
|
53642
53956
|
if (!info.isFile() || info.isSymbolicLink() || info.size > 1e5) throw new BridgeError(409, "The hand-off record cannot be read safely.");
|
|
53643
|
-
const row = rowSchema.parse(JSON.parse(await
|
|
53957
|
+
const row = rowSchema.parse(JSON.parse(await readFile38(file4, "utf8")));
|
|
53644
53958
|
if (row.state === "attempting") {
|
|
53645
53959
|
row.state = "uncertain";
|
|
53646
53960
|
row.error = "The Hook restarted before delivery was confirmed.";
|
|
@@ -53847,8 +54161,9 @@ var init_hand_off_queue = __esm({
|
|
|
53847
54161
|
});
|
|
53848
54162
|
|
|
53849
54163
|
// src/bridge/git-host-auth.ts
|
|
54164
|
+
import { createHash as createHash25 } from "node:crypto";
|
|
53850
54165
|
import { execFile as execFile20 } from "node:child_process";
|
|
53851
|
-
import { mkdir as mkdir23, readFile as
|
|
54166
|
+
import { mkdir as mkdir23, readFile as readFile39, stat as stat19 } from "node:fs/promises";
|
|
53852
54167
|
import path94 from "node:path";
|
|
53853
54168
|
import { promisify as promisify18 } from "node:util";
|
|
53854
54169
|
function gitHostsFile() {
|
|
@@ -53870,7 +54185,7 @@ async function readStore(file4 = gitHostsFile()) {
|
|
|
53870
54185
|
if (!info.isFile()) return null;
|
|
53871
54186
|
if (process.platform !== "win32" && ((info.mode & 63) !== 0 || process.getuid && info.uid !== process.getuid())) return "unsafe";
|
|
53872
54187
|
try {
|
|
53873
|
-
const parsed = JSON.parse(await
|
|
54188
|
+
const parsed = JSON.parse(await readFile39(file4, "utf8"));
|
|
53874
54189
|
const hosts = {};
|
|
53875
54190
|
if (parsed.hosts && typeof parsed.hosts === "object") {
|
|
53876
54191
|
for (const [domain2, raw] of Object.entries(parsed.hosts)) {
|
|
@@ -53895,6 +54210,7 @@ async function writeHostToken(domain2, kind, token, user, file4 = gitHostsFile()
|
|
|
53895
54210
|
else delete hosts[key4];
|
|
53896
54211
|
await mkdir23(path94.dirname(file4), { recursive: true, mode: 448 });
|
|
53897
54212
|
await atomic(file4, JSON.stringify({ hosts }, null, 2) + "\n", 384);
|
|
54213
|
+
invalidatePullsForDomain(key4);
|
|
53898
54214
|
}
|
|
53899
54215
|
function fromEnv(kind, domain2, env) {
|
|
53900
54216
|
if (kind === "gitlab") {
|
|
@@ -53932,10 +54248,49 @@ async function listHostTokens(file4 = gitHostsFile()) {
|
|
|
53932
54248
|
if (store === "unsafe") return "unsafe";
|
|
53933
54249
|
return Object.entries(store?.hosts ?? {}).map(([domain2, { kind, user, savedAt }]) => ({ domain: domain2, kind, ...user ? { user } : {}, ...savedAt ? { savedAt } : {} }));
|
|
53934
54250
|
}
|
|
54251
|
+
function ghHostBlock(hostsYml, domain2) {
|
|
54252
|
+
const want = domain2.trim().toLowerCase().replace(/\.$/, "");
|
|
54253
|
+
const out = [];
|
|
54254
|
+
let inside = false;
|
|
54255
|
+
for (const line of hostsYml.split(/\r?\n/)) {
|
|
54256
|
+
const top = /^(\S[^:]*):\s*$/.exec(line);
|
|
54257
|
+
if (top) {
|
|
54258
|
+
inside = top[1].trim().replace(/^["']|["']$/g, "").toLowerCase() === want;
|
|
54259
|
+
if (inside) out.push(line);
|
|
54260
|
+
continue;
|
|
54261
|
+
}
|
|
54262
|
+
if (inside && (line.startsWith(" ") || line.startsWith(" ") || line.trim() === "")) out.push(line);
|
|
54263
|
+
else if (line.trim()) inside = false;
|
|
54264
|
+
}
|
|
54265
|
+
return out.join("\n").trimEnd();
|
|
54266
|
+
}
|
|
54267
|
+
async function hostCredentialIdentity(host) {
|
|
54268
|
+
let state = null;
|
|
54269
|
+
if (host.kind === "github") {
|
|
54270
|
+
const dir = process.env.GH_CONFIG_DIR || path94.join(process.env.XDG_CONFIG_HOME || path94.join(homeDir(), ".config"), "gh");
|
|
54271
|
+
const hosts = await readFile39(path94.join(dir, "hosts.yml"), "utf8").catch(() => "");
|
|
54272
|
+
state = [
|
|
54273
|
+
process.env.GH_TOKEN,
|
|
54274
|
+
process.env.GITHUB_TOKEN,
|
|
54275
|
+
process.env.GH_ENTERPRISE_TOKEN,
|
|
54276
|
+
process.env.GITHUB_ENTERPRISE_TOKEN,
|
|
54277
|
+
ghHostBlock(hosts, host.domain ?? "github.com")
|
|
54278
|
+
];
|
|
54279
|
+
} else if (host.kind && host.domain) {
|
|
54280
|
+
const store = await readStore();
|
|
54281
|
+
state = [
|
|
54282
|
+
await resolveHostToken(host.kind, host.domain),
|
|
54283
|
+
store && store !== "unsafe" ? store.hosts[normalDomain(host.domain)] : store
|
|
54284
|
+
];
|
|
54285
|
+
}
|
|
54286
|
+
return createHash25("sha256").update(JSON.stringify(state)).digest("hex");
|
|
54287
|
+
}
|
|
53935
54288
|
var exec15;
|
|
53936
54289
|
var init_git_host_auth = __esm({
|
|
53937
54290
|
"src/bridge/git-host-auth.ts"() {
|
|
53938
54291
|
"use strict";
|
|
54292
|
+
init_home_paths();
|
|
54293
|
+
init_git();
|
|
53939
54294
|
init_protocol();
|
|
53940
54295
|
exec15 = promisify18(execFile20);
|
|
53941
54296
|
}
|
|
@@ -54008,18 +54363,21 @@ var init_git_host_http = __esm({
|
|
|
54008
54363
|
|
|
54009
54364
|
// src/bridge/git-publish.ts
|
|
54010
54365
|
import { spawn as spawn10 } from "node:child_process";
|
|
54011
|
-
function runCombined(command, args, cwd, timeout, extraEnv = {}) {
|
|
54366
|
+
function runCombined(command, args, cwd, timeout, extraEnv = {}, killGraceMs = KILL_GRACE_MS2) {
|
|
54012
54367
|
return new Promise((resolve17) => {
|
|
54013
54368
|
let output2 = "", truncated = false, timedOut = false, settled3 = false;
|
|
54369
|
+
let deadline;
|
|
54014
54370
|
const finish = (run4) => {
|
|
54015
|
-
if (
|
|
54016
|
-
|
|
54017
|
-
|
|
54018
|
-
|
|
54371
|
+
if (settled3) return;
|
|
54372
|
+
settled3 = true;
|
|
54373
|
+
clearTimeout(deadline);
|
|
54374
|
+
resolve17(run4);
|
|
54019
54375
|
};
|
|
54376
|
+
const group = process.platform !== "win32";
|
|
54020
54377
|
const child = spawn10(command, args, {
|
|
54021
54378
|
cwd,
|
|
54022
54379
|
stdio: ["ignore", "pipe", "pipe"],
|
|
54380
|
+
detached: group,
|
|
54023
54381
|
env: nonInteractiveGitEnv({ ...process.env, ...extraEnv, GIT_CONFIG_NOSYSTEM: "1", GIT_EDITOR: "true", GH_PROMPT_DISABLED: "1", GH_NO_UPDATE_NOTIFIER: "1", NO_COLOR: "1" })
|
|
54024
54382
|
});
|
|
54025
54383
|
const append = (chunk) => {
|
|
@@ -54032,9 +54390,38 @@ function runCombined(command, args, cwd, timeout, extraEnv = {}) {
|
|
|
54032
54390
|
};
|
|
54033
54391
|
child.stdout.on("data", append);
|
|
54034
54392
|
child.stderr.on("data", append);
|
|
54393
|
+
const kill = (signal) => {
|
|
54394
|
+
try {
|
|
54395
|
+
if (group && child.pid) process.kill(-child.pid, signal);
|
|
54396
|
+
else child.kill(signal);
|
|
54397
|
+
} catch {
|
|
54398
|
+
child.kill(signal);
|
|
54399
|
+
}
|
|
54400
|
+
};
|
|
54401
|
+
const escalate = () => {
|
|
54402
|
+
if (!group || !child.pid) {
|
|
54403
|
+
child.kill("SIGKILL");
|
|
54404
|
+
return;
|
|
54405
|
+
}
|
|
54406
|
+
try {
|
|
54407
|
+
process.kill(-child.pid, 0);
|
|
54408
|
+
} catch {
|
|
54409
|
+
return;
|
|
54410
|
+
}
|
|
54411
|
+
try {
|
|
54412
|
+
process.kill(-child.pid, "SIGKILL");
|
|
54413
|
+
} catch {
|
|
54414
|
+
}
|
|
54415
|
+
};
|
|
54035
54416
|
const timer = setTimeout(() => {
|
|
54036
54417
|
timedOut = true;
|
|
54037
|
-
|
|
54418
|
+
kill("SIGTERM");
|
|
54419
|
+
setTimeout(escalate, killGraceMs).unref();
|
|
54420
|
+
deadline = setTimeout(() => {
|
|
54421
|
+
child.stdout.destroy();
|
|
54422
|
+
child.stderr.destroy();
|
|
54423
|
+
finish({ code: null, output: output2.trimEnd(), missing: false, timedOut: true });
|
|
54424
|
+
}, killGraceMs * 2);
|
|
54038
54425
|
}, timeout);
|
|
54039
54426
|
child.on("error", (error62) => {
|
|
54040
54427
|
clearTimeout(timer);
|
|
@@ -54114,7 +54501,11 @@ async function gitPullRequest(cwd, draft) {
|
|
|
54114
54501
|
const { reason: reason2, message } = unknownHost(host);
|
|
54115
54502
|
return { ok: false, reason: reason2, message, host };
|
|
54116
54503
|
}
|
|
54117
|
-
|
|
54504
|
+
try {
|
|
54505
|
+
return { ...await provider2.open(root, branch, draft === true, host), host };
|
|
54506
|
+
} finally {
|
|
54507
|
+
invalidatePulls(root);
|
|
54508
|
+
}
|
|
54118
54509
|
}
|
|
54119
54510
|
async function gitMergeRequest(cwd, data) {
|
|
54120
54511
|
const request9 = MergeBody.parse(data);
|
|
@@ -54126,7 +54517,11 @@ async function gitMergeRequest(cwd, data) {
|
|
|
54126
54517
|
const { reason: reason2, message } = unknownHost(host);
|
|
54127
54518
|
return { ok: false, reason: reason2, message, host };
|
|
54128
54519
|
}
|
|
54129
|
-
|
|
54520
|
+
try {
|
|
54521
|
+
return { ...await provider2.merge(root, request9, host), host };
|
|
54522
|
+
} finally {
|
|
54523
|
+
invalidatePulls(root);
|
|
54524
|
+
}
|
|
54130
54525
|
}
|
|
54131
54526
|
async function gitHostToken(cwd, data) {
|
|
54132
54527
|
const { token } = external_exports.object({ token: external_exports.string().max(4096) }).parse(data);
|
|
@@ -54153,7 +54548,7 @@ async function gitHostToken(cwd, data) {
|
|
|
54153
54548
|
throw error62;
|
|
54154
54549
|
}
|
|
54155
54550
|
}
|
|
54156
|
-
var MAX_OUTPUT, COMMIT_TIMEOUT_MS, PUSH_TIMEOUT_MS, MAX_MESSAGE, MergeBody;
|
|
54551
|
+
var MAX_OUTPUT, COMMIT_TIMEOUT_MS, PUSH_TIMEOUT_MS, MAX_MESSAGE, KILL_GRACE_MS2, MergeBody;
|
|
54157
54552
|
var init_git_publish = __esm({
|
|
54158
54553
|
"src/bridge/git-publish.ts"() {
|
|
54159
54554
|
"use strict";
|
|
@@ -54170,6 +54565,7 @@ var init_git_publish = __esm({
|
|
|
54170
54565
|
COMMIT_TIMEOUT_MS = 11e4;
|
|
54171
54566
|
PUSH_TIMEOUT_MS = 11e4;
|
|
54172
54567
|
MAX_MESSAGE = 2e4;
|
|
54568
|
+
KILL_GRACE_MS2 = 2e3;
|
|
54173
54569
|
MergeBody = external_exports.object({
|
|
54174
54570
|
number: external_exports.number().int().positive(),
|
|
54175
54571
|
method: external_exports.enum(["merge", "squash", "rebase"]).default("merge"),
|
|
@@ -54894,7 +55290,8 @@ var init_git_hosts = __esm({
|
|
|
54894
55290
|
});
|
|
54895
55291
|
|
|
54896
55292
|
// src/bridge/git.ts
|
|
54897
|
-
import { createHash as
|
|
55293
|
+
import { createHash as createHash26 } from "node:crypto";
|
|
55294
|
+
import { readFileSync as readFileSync42, realpathSync as realpathSync3 } from "node:fs";
|
|
54898
55295
|
import { lstat as lstat25, open as open17, readdir as readdir15, realpath as realpath12 } from "node:fs/promises";
|
|
54899
55296
|
import path95 from "node:path";
|
|
54900
55297
|
function statusLetter(code) {
|
|
@@ -55117,13 +55514,70 @@ async function gitBranches(cwd) {
|
|
|
55117
55514
|
}
|
|
55118
55515
|
return { current: current2, local, remote };
|
|
55119
55516
|
}
|
|
55120
|
-
|
|
55121
|
-
const
|
|
55122
|
-
const
|
|
55123
|
-
|
|
55517
|
+
function credentialIdentity(host, fresh = false) {
|
|
55518
|
+
const key4 = JSON.stringify([host.kind ?? null, (host.domain ?? "").toLowerCase()]);
|
|
55519
|
+
const hit = credentialReads.get(key4);
|
|
55520
|
+
if (host.kind !== "gitlab") return hostCredentialIdentity(host);
|
|
55521
|
+
if (!fresh && hit && Date.now() - hit.at < CREDENTIAL_TTL_MS) return hit.value;
|
|
55522
|
+
const value2 = hostCredentialIdentity(host).catch((error62) => {
|
|
55523
|
+
credentialReads.delete(key4);
|
|
55524
|
+
throw error62;
|
|
55525
|
+
});
|
|
55526
|
+
credentialReads.set(key4, { at: Date.now(), value: value2 });
|
|
55527
|
+
if (credentialReads.size > 64) credentialReads.delete(credentialReads.keys().next().value);
|
|
55528
|
+
return value2;
|
|
55529
|
+
}
|
|
55530
|
+
function repositoryId(root) {
|
|
55531
|
+
try {
|
|
55532
|
+
const dotGit = path95.join(root, ".git");
|
|
55533
|
+
let gitDir2 = dotGit;
|
|
55534
|
+
try {
|
|
55535
|
+
const link = /^gitdir:\s*(.+)$/m.exec(readFileSync42(dotGit, "utf8"));
|
|
55536
|
+
if (link) gitDir2 = path95.resolve(root, link[1].trim());
|
|
55537
|
+
} catch {
|
|
55538
|
+
}
|
|
55539
|
+
let common = gitDir2;
|
|
55540
|
+
try {
|
|
55541
|
+
common = path95.resolve(gitDir2, readFileSync42(path95.join(gitDir2, "commondir"), "utf8").trim());
|
|
55542
|
+
} catch {
|
|
55543
|
+
}
|
|
55544
|
+
return realpathSync3(common);
|
|
55545
|
+
} catch {
|
|
55546
|
+
return root;
|
|
55547
|
+
}
|
|
55548
|
+
}
|
|
55549
|
+
function invalidatePulls(root) {
|
|
55550
|
+
const prefix = repositoryId(root) + "\0";
|
|
55551
|
+
pullsCache.invalidate((key4) => key4.startsWith(prefix));
|
|
55552
|
+
}
|
|
55553
|
+
function invalidatePullsForDomain(domain2) {
|
|
55554
|
+
const normalized = domain2.trim().toLowerCase().replace(/\.$/, "");
|
|
55555
|
+
for (const key4 of credentialReads.keys()) if (JSON.parse(key4)[1] === normalized) credentialReads.delete(key4);
|
|
55556
|
+
pullsCache.invalidate((key4) => key4.split("\0")[1] === normalized);
|
|
55557
|
+
}
|
|
55558
|
+
async function gitPulls(cwd, retried = false) {
|
|
55559
|
+
const { root, branch, host } = await withIndependentGitReadDeadline(async () => {
|
|
55560
|
+
const root2 = await repository2(cwd);
|
|
55561
|
+
const branch2 = (await git(root2, "branch", "--show-current").catch(() => "")).trim();
|
|
55562
|
+
return { root: root2, branch: branch2, host: await detectHost(root2, branch2) };
|
|
55563
|
+
});
|
|
55124
55564
|
const provider2 = providerFor(host);
|
|
55125
|
-
const
|
|
55126
|
-
|
|
55565
|
+
const credential = await credentialIdentity(host);
|
|
55566
|
+
const key4 = repositoryId(root) + "\0" + (host.domain ?? "").toLowerCase().replace(/\.$/, "") + "\0" + JSON.stringify([branch, host, credential]);
|
|
55567
|
+
try {
|
|
55568
|
+
return await pullsCache.get(key4, () => withoutGitReadDeadline(async () => {
|
|
55569
|
+
const list = provider2 ? await provider2.list(root, branch, host) : unknownHost(host);
|
|
55570
|
+
if (await credentialIdentity(host, true) !== credential) {
|
|
55571
|
+
pullsCache.invalidate((candidate) => candidate === key4);
|
|
55572
|
+
throw new CredentialsChanged();
|
|
55573
|
+
}
|
|
55574
|
+
return { ...list, branch: branch || null, host };
|
|
55575
|
+
}));
|
|
55576
|
+
} catch (error62) {
|
|
55577
|
+
if (!(error62 instanceof CredentialsChanged)) throw error62;
|
|
55578
|
+
if (!retried) return gitPulls(cwd, true);
|
|
55579
|
+
throw new BridgeError(409, "Forge credentials keep changing. Retry.");
|
|
55580
|
+
}
|
|
55127
55581
|
}
|
|
55128
55582
|
async function repositoryPath(root, raw, allowRoot = false) {
|
|
55129
55583
|
if (typeof raw !== "string" || raw.length > 4096 || raw.includes("\0") || path95.isAbsolute(raw) || path95.win32.isAbsolute(raw) || raw.startsWith("\\")) throw new BridgeError(400, "Invalid path.");
|
|
@@ -55154,13 +55608,14 @@ async function repositoryPath(root, raw, allowRoot = false) {
|
|
|
55154
55608
|
}
|
|
55155
55609
|
function invalidateTree(root) {
|
|
55156
55610
|
treeCache.delete(root);
|
|
55611
|
+
invalidatePulls(root);
|
|
55157
55612
|
}
|
|
55158
55613
|
async function treeSnapshot(root, head) {
|
|
55159
55614
|
const [tracked, porcelain] = await Promise.all([
|
|
55160
55615
|
git(root, "ls-files", "-z"),
|
|
55161
55616
|
git(root, "status", "--porcelain=v1", "-z", "--untracked-files=all")
|
|
55162
55617
|
]);
|
|
55163
|
-
const
|
|
55618
|
+
const changed = /* @__PURE__ */ new Map();
|
|
55164
55619
|
const files = new Set(tracked.split("\0").filter(Boolean));
|
|
55165
55620
|
const tokens = porcelain.split("\0");
|
|
55166
55621
|
for (let i = 0; i < tokens.length; i++) {
|
|
@@ -55168,7 +55623,7 @@ async function treeSnapshot(root, head) {
|
|
|
55168
55623
|
if (!row) continue;
|
|
55169
55624
|
const xy = row.slice(0, 2), file4 = row.slice(3);
|
|
55170
55625
|
const letter = xy === "??" ? "?" : statusLetter(xy[1] !== " " ? xy[1] : xy[0]);
|
|
55171
|
-
|
|
55626
|
+
changed.set(file4, letter);
|
|
55172
55627
|
files.add(file4);
|
|
55173
55628
|
if (/[RC]/.test(xy)) i++;
|
|
55174
55629
|
}
|
|
@@ -55193,12 +55648,12 @@ async function treeSnapshot(root, head) {
|
|
|
55193
55648
|
}
|
|
55194
55649
|
if (directory) {
|
|
55195
55650
|
entry2.fileCount = (entry2.fileCount ?? 0) + 1;
|
|
55196
|
-
if (
|
|
55197
|
-
} else if (
|
|
55651
|
+
if (changed.has(file4)) entry2.status = "changed";
|
|
55652
|
+
} else if (changed.has(file4)) entry2.status = entry2.kind === "dir" ? "changed" : changed.get(file4);
|
|
55198
55653
|
parent = full2;
|
|
55199
55654
|
}
|
|
55200
55655
|
}
|
|
55201
|
-
const version2 =
|
|
55656
|
+
const version2 = createHash26("sha256").update(head).update(tracked).update(porcelain).digest("hex");
|
|
55202
55657
|
return { version: version2, levels: new Map([...levels].map(([directory, entries2]) => [
|
|
55203
55658
|
directory,
|
|
55204
55659
|
[...entries2.values()].sort((a, b) => a.kind === b.kind ? a.name.localeCompare(b.name) : a.kind === "dir" ? -1 : 1)
|
|
@@ -55322,6 +55777,16 @@ async function gitDiscard(cwd, paths) {
|
|
|
55322
55777
|
treeCache.delete(root);
|
|
55323
55778
|
try {
|
|
55324
55779
|
const files = await repositoryPaths(root, paths);
|
|
55780
|
+
for (const file4 of files) {
|
|
55781
|
+
const info = await lstat25(path95.join(root, file4)).catch((error62) => {
|
|
55782
|
+
if (error62.code === "ENOENT") return void 0;
|
|
55783
|
+
throw error62;
|
|
55784
|
+
});
|
|
55785
|
+
const indexed = info ? "" : await git(root, "ls-files", "-z", "--", `:(literal)${file4}`);
|
|
55786
|
+
if (info?.isDirectory() || indexed.split("\0").some((entry2) => entry2.startsWith(`${file4}/`))) {
|
|
55787
|
+
throw new BridgeError(409, "Discard the files in this directory one at a time.");
|
|
55788
|
+
}
|
|
55789
|
+
}
|
|
55325
55790
|
const untracked = new Set((await git(root, "ls-files", "--others", "--exclude-standard", "-z")).split("\0").filter(Boolean));
|
|
55326
55791
|
for (const file4 of files) {
|
|
55327
55792
|
const literal2 = `:(literal)${file4}`;
|
|
@@ -55420,17 +55885,32 @@ async function readGitShow(cwd, sha) {
|
|
|
55420
55885
|
truncated
|
|
55421
55886
|
};
|
|
55422
55887
|
}
|
|
55423
|
-
var UNKNOWN_COUNTS, NO_DIFF2, MAX_STATUS_ROWS, treeCache, TREE_TTL_MS, MAX_IGNORED_ENTRIES, ignoredCache, MAX_SHOW_FILES, MAX_SHOW_PATCH, MAX_FILE_PATCH;
|
|
55888
|
+
var UNKNOWN_COUNTS, NO_DIFF2, MAX_STATUS_ROWS, REVOKING, pullsCache, credentialReads, CREDENTIAL_TTL_MS, CredentialsChanged, treeCache, TREE_TTL_MS, MAX_IGNORED_ENTRIES, ignoredCache, MAX_SHOW_FILES, MAX_SHOW_PATCH, MAX_FILE_PATCH;
|
|
55424
55889
|
var init_git = __esm({
|
|
55425
55890
|
"src/bridge/git.ts"() {
|
|
55426
55891
|
"use strict";
|
|
55427
55892
|
init_protocol();
|
|
55428
55893
|
init_projects();
|
|
55429
55894
|
init_git_hosts();
|
|
55895
|
+
init_git_host_auth();
|
|
55896
|
+
init_lookup_cache();
|
|
55430
55897
|
init_git_hosts();
|
|
55431
55898
|
UNKNOWN_COUNTS = { additions: 0, deletions: 0, countsComplete: false };
|
|
55432
55899
|
NO_DIFF2 = ["diff", "--no-ext-diff", "--no-textconv", "--no-color"];
|
|
55433
55900
|
MAX_STATUS_ROWS = 500;
|
|
55901
|
+
REVOKING = /* @__PURE__ */ new Set(["auth", "not-found"]);
|
|
55902
|
+
pullsCache = new LookupCache(
|
|
55903
|
+
3e4,
|
|
55904
|
+
3e5,
|
|
55905
|
+
64,
|
|
55906
|
+
(value2) => value2.available === true,
|
|
55907
|
+
45e3,
|
|
55908
|
+
(value2) => value2.available === false && REVOKING.has(String(value2.reason))
|
|
55909
|
+
);
|
|
55910
|
+
credentialReads = /* @__PURE__ */ new Map();
|
|
55911
|
+
CREDENTIAL_TTL_MS = 5e3;
|
|
55912
|
+
CredentialsChanged = class extends Error {
|
|
55913
|
+
};
|
|
55434
55914
|
treeCache = /* @__PURE__ */ new Map();
|
|
55435
55915
|
TREE_TTL_MS = 2e3;
|
|
55436
55916
|
MAX_IGNORED_ENTRIES = 1e3;
|
|
@@ -55442,12 +55922,12 @@ var init_git = __esm({
|
|
|
55442
55922
|
});
|
|
55443
55923
|
|
|
55444
55924
|
// src/bridge/git-worktrees.ts
|
|
55445
|
-
import { createHash as
|
|
55925
|
+
import { createHash as createHash27 } from "node:crypto";
|
|
55446
55926
|
import { realpath as realpath13, stat as stat20 } from "node:fs/promises";
|
|
55447
55927
|
import { homedir as homedir15 } from "node:os";
|
|
55448
55928
|
import path96 from "node:path";
|
|
55449
55929
|
function worktreeId(abs) {
|
|
55450
|
-
return
|
|
55930
|
+
return createHash27("sha256").update(`worktree\0${abs}`).digest("hex").slice(0, 32);
|
|
55451
55931
|
}
|
|
55452
55932
|
async function listed3(root) {
|
|
55453
55933
|
const output2 = await git(root, "worktree", "list", "--porcelain", "-z");
|
|
@@ -55528,7 +56008,7 @@ async function readGitWorktrees(cwd, workers) {
|
|
|
55528
56008
|
behind = Number(counts[0]);
|
|
55529
56009
|
ahead = Number(counts[1]);
|
|
55530
56010
|
}
|
|
55531
|
-
const
|
|
56011
|
+
const changed = uncommitted(await git(worktree.abs, "status", "--porcelain=v1", "-z", "--untracked-files=normal"));
|
|
55532
56012
|
const worker = await workerFor(worktree.abs, workers, worktrees.map((item) => item.abs));
|
|
55533
56013
|
return {
|
|
55534
56014
|
id: worktreeId(worktree.abs),
|
|
@@ -55537,7 +56017,7 @@ async function readGitWorktrees(cwd, workers) {
|
|
|
55537
56017
|
head: worktree.head,
|
|
55538
56018
|
ahead,
|
|
55539
56019
|
behind,
|
|
55540
|
-
changed
|
|
56020
|
+
changed,
|
|
55541
56021
|
...worktree.abs === main2 ? { main: true } : {},
|
|
55542
56022
|
...worktree.locked ? { locked: true } : {},
|
|
55543
56023
|
...worker ? { worker: {
|
|
@@ -55686,7 +56166,7 @@ var init_git_sync = __esm({
|
|
|
55686
56166
|
});
|
|
55687
56167
|
|
|
55688
56168
|
// src/bridge/git-review.ts
|
|
55689
|
-
import { mkdtemp as mkdtemp5, rm as
|
|
56169
|
+
import { mkdtemp as mkdtemp5, rm as rm11, writeFile as writeFile6 } from "node:fs/promises";
|
|
55690
56170
|
import { tmpdir as tmpdir4 } from "node:os";
|
|
55691
56171
|
import path97 from "node:path";
|
|
55692
56172
|
async function repository4(cwd) {
|
|
@@ -55741,7 +56221,25 @@ function headerName(raw) {
|
|
|
55741
56221
|
function patchFiles(patch) {
|
|
55742
56222
|
const files = /* @__PURE__ */ new Set();
|
|
55743
56223
|
let hunks = 0;
|
|
56224
|
+
let oldLeft = 0, newLeft = 0;
|
|
55744
56225
|
for (const line of patch.split("\n")) {
|
|
56226
|
+
if (oldLeft > 0 || newLeft > 0) {
|
|
56227
|
+
if (line.startsWith("\\")) continue;
|
|
56228
|
+
if (line.startsWith("-")) oldLeft--;
|
|
56229
|
+
else if (line.startsWith("+")) newLeft--;
|
|
56230
|
+
else {
|
|
56231
|
+
oldLeft--;
|
|
56232
|
+
newLeft--;
|
|
56233
|
+
}
|
|
56234
|
+
continue;
|
|
56235
|
+
}
|
|
56236
|
+
const hunk = /^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@/.exec(line);
|
|
56237
|
+
if (hunk) {
|
|
56238
|
+
hunks++;
|
|
56239
|
+
oldLeft = hunk[1] === void 0 ? 1 : Number(hunk[1]);
|
|
56240
|
+
newLeft = hunk[2] === void 0 ? 1 : Number(hunk[2]);
|
|
56241
|
+
continue;
|
|
56242
|
+
}
|
|
55745
56243
|
if (/^(?:rename|copy) (?:from|to) |^(?:old|new|deleted file|new file) mode |^GIT binary patch|^Binary files /.test(line)) {
|
|
55746
56244
|
throw new BridgeError(400, "Only text hunks can be staged one at a time. Stage the whole file instead.");
|
|
55747
56245
|
}
|
|
@@ -55749,7 +56247,6 @@ function patchFiles(patch) {
|
|
|
55749
56247
|
const name = headerName(line.slice(4).replace(/\t.*$/, ""));
|
|
55750
56248
|
if (name) files.add(name);
|
|
55751
56249
|
}
|
|
55752
|
-
if (line.startsWith("@@ ")) hunks++;
|
|
55753
56250
|
}
|
|
55754
56251
|
if (!files.size || !hunks) throw new BridgeError(400, "This patch has no hunks.");
|
|
55755
56252
|
if (files.size > 1) throw new BridgeError(400, "Stage hunks of one file at a time.");
|
|
@@ -55764,7 +56261,7 @@ async function gitApply(cwd, rawPatch, reverse) {
|
|
|
55764
56261
|
const scratch = await mkdtemp5(path97.join(tmpdir4(), "phren-apply-"));
|
|
55765
56262
|
const patchFile = path97.join(scratch, "hunk.patch");
|
|
55766
56263
|
try {
|
|
55767
|
-
await
|
|
56264
|
+
await writeFile6(patchFile, rawPatch.endsWith("\n") ? rawPatch : rawPatch + "\n", { mode: 384 });
|
|
55768
56265
|
const args = ["apply", "--cached", "--whitespace=nowarn", ...reverse === true ? ["-R"] : [], "--", patchFile];
|
|
55769
56266
|
invalidateTree(root);
|
|
55770
56267
|
try {
|
|
@@ -55776,7 +56273,7 @@ async function gitApply(cwd, rawPatch, reverse) {
|
|
|
55776
56273
|
return { ok: true, path: file4, staged: reverse !== true };
|
|
55777
56274
|
} finally {
|
|
55778
56275
|
invalidateTree(root);
|
|
55779
|
-
await
|
|
56276
|
+
await rm11(scratch, { recursive: true, force: true });
|
|
55780
56277
|
}
|
|
55781
56278
|
}
|
|
55782
56279
|
function sessionChanges(root, history) {
|
|
@@ -55835,8 +56332,8 @@ var init_git_review = __esm({
|
|
|
55835
56332
|
// src/bridge/approval-rules.ts
|
|
55836
56333
|
import { execFile as execFile22 } from "node:child_process";
|
|
55837
56334
|
import { promisify as promisify20 } from "node:util";
|
|
55838
|
-
import { createHash as
|
|
55839
|
-
import { lstat as lstat26, mkdir as mkdir24, readFile as
|
|
56335
|
+
import { createHash as createHash28, createPublicKey, verify } from "node:crypto";
|
|
56336
|
+
import { lstat as lstat26, mkdir as mkdir24, readFile as readFile40, realpath as realpath14 } from "node:fs/promises";
|
|
55840
56337
|
import { hostname as hostname8 } from "node:os";
|
|
55841
56338
|
import path98 from "node:path";
|
|
55842
56339
|
async function git6(cwd, ...args) {
|
|
@@ -55847,7 +56344,7 @@ async function git6(cwd, ...args) {
|
|
|
55847
56344
|
})).stdout;
|
|
55848
56345
|
}
|
|
55849
56346
|
async function ownerKeys() {
|
|
55850
|
-
const keys2 = await
|
|
56347
|
+
const keys2 = await readFile40(path98.join(homeDir(), ".ssh", "authorized_keys"), "utf8");
|
|
55851
56348
|
const result = /* @__PURE__ */ new Set();
|
|
55852
56349
|
for (const line of keys2.split("\n")) {
|
|
55853
56350
|
const match = /^restrict,pty,command="sh ~\/\.local\/share\/phren\/bridge\/dispatch" ssh-ed25519 ([A-Za-z0-9+/]+={0,2}) phren-iphone\s*$/.exec(line);
|
|
@@ -55863,7 +56360,7 @@ function verified(envelope, keys2) {
|
|
|
55863
56360
|
const key4 = createPublicKey({ key: Buffer.concat([Buffer.from("302a300506032b6570032100", "hex"), raw]), format: "der", type: "spki" });
|
|
55864
56361
|
if (!verify(null, payload, key4, signature)) throw forbidden();
|
|
55865
56362
|
const operation = operationSchema.parse(JSON.parse(payload.toString("utf8")));
|
|
55866
|
-
return { operation, owner:
|
|
56363
|
+
return { operation, owner: createHash28("sha256").update(raw).digest("hex") };
|
|
55867
56364
|
}
|
|
55868
56365
|
async function privateJSON(file4, fallback2, max = 2097152) {
|
|
55869
56366
|
const info = await lstat26(file4).catch((error62) => {
|
|
@@ -55872,7 +56369,7 @@ async function privateJSON(file4, fallback2, max = 2097152) {
|
|
|
55872
56369
|
});
|
|
55873
56370
|
if (!info) return fallback2;
|
|
55874
56371
|
if (!info.isFile() || info.isSymbolicLink() || info.mode & 63 || info.size > max) throw new BridgeError(409, "Approval policy must be a private regular file.");
|
|
55875
|
-
return JSON.parse(await
|
|
56372
|
+
return JSON.parse(await readFile40(file4, "utf8"));
|
|
55876
56373
|
}
|
|
55877
56374
|
async function readPolicy(root) {
|
|
55878
56375
|
const policy = policySchema.parse(await privateJSON(policyPath(root), { operations: [] }));
|
|
@@ -55913,7 +56410,7 @@ async function locked(root, work) {
|
|
|
55913
56410
|
}
|
|
55914
56411
|
async function listApprovalRules(root = bridgeRoot(), pairedKey) {
|
|
55915
56412
|
try {
|
|
55916
|
-
const pairedOwner = pairedKey ?
|
|
56413
|
+
const pairedOwner = pairedKey ? createHash28("sha256").update(Buffer.from(pairedKey, "base64")).digest("hex") : void 0;
|
|
55917
56414
|
return [...(await readPolicy(root)).rules.values()].map((rule2) => ({
|
|
55918
56415
|
...rule2,
|
|
55919
56416
|
signerFingerprint: "SHA256:" + Buffer.from(rule2.owner, "hex").toString("base64").replace(/=+$/, ""),
|
|
@@ -56031,7 +56528,7 @@ var init_approval_rules = __esm({
|
|
|
56031
56528
|
});
|
|
56032
56529
|
|
|
56033
56530
|
// src/bridge/conductor-context.ts
|
|
56034
|
-
import { readFile as
|
|
56531
|
+
import { readFile as readFile41 } from "node:fs/promises";
|
|
56035
56532
|
import path99 from "node:path";
|
|
56036
56533
|
async function conductorBrief() {
|
|
56037
56534
|
let source;
|
|
@@ -56042,7 +56539,7 @@ async function conductorBrief() {
|
|
|
56042
56539
|
path99.join(here, "..", "starter", "global", "skills", "conductor", "SKILL.md"),
|
|
56043
56540
|
path99.join(here, "..", "..", "starter", "global", "skills", "conductor", "SKILL.md")
|
|
56044
56541
|
]) {
|
|
56045
|
-
source = await
|
|
56542
|
+
source = await readFile41(candidate, "utf8").catch(() => void 0);
|
|
56046
56543
|
if (source !== void 0) break;
|
|
56047
56544
|
}
|
|
56048
56545
|
}
|
|
@@ -56055,7 +56552,7 @@ async function conductorBrief() {
|
|
|
56055
56552
|
async function ensureConductorBrief(brief) {
|
|
56056
56553
|
const file4 = path99.join(bridgeRoot(), "conductor", "brief.md");
|
|
56057
56554
|
const content = (brief ?? await conductorBrief()) + "\n";
|
|
56058
|
-
if (await
|
|
56555
|
+
if (await readFile41(file4, "utf8").catch(() => void 0) !== content) await atomicInPrivateDir(file4, content);
|
|
56059
56556
|
return file4;
|
|
56060
56557
|
}
|
|
56061
56558
|
async function conductorContext(target, snapshot2) {
|
|
@@ -56075,92 +56572,11 @@ var init_conductor_context = __esm({
|
|
|
56075
56572
|
}
|
|
56076
56573
|
});
|
|
56077
56574
|
|
|
56078
|
-
// src/bridge/codex-review-mode.ts
|
|
56079
|
-
import { open as open18 } from "node:fs/promises";
|
|
56080
|
-
import path100 from "node:path";
|
|
56081
|
-
async function codexAutoReview(transcriptPath2) {
|
|
56082
|
-
if (typeof transcriptPath2 !== "string" || !path100.isAbsolute(transcriptPath2) || !/^rollout-.*\.jsonl$/.test(path100.basename(transcriptPath2))) return false;
|
|
56083
|
-
const file4 = await open18(transcriptPath2, "r").catch(() => void 0);
|
|
56084
|
-
if (!file4) return false;
|
|
56085
|
-
try {
|
|
56086
|
-
const size = (await file4.stat()).size;
|
|
56087
|
-
let end = size, carry = Buffer.alloc(0);
|
|
56088
|
-
while (end > 0 && size - end < SCAN_LIMIT) {
|
|
56089
|
-
const start = Math.max(0, end - CHUNK), buffer = Buffer.alloc(end - start);
|
|
56090
|
-
await file4.read(buffer, 0, buffer.length, start);
|
|
56091
|
-
const bytes = Buffer.concat([buffer, carry]);
|
|
56092
|
-
let lineEnd = bytes.length;
|
|
56093
|
-
for (let at2 = bytes.lastIndexOf(10, lineEnd - 1); at2 >= 0; at2 = bytes.lastIndexOf(10, lineEnd - 1)) {
|
|
56094
|
-
const settings2 = reviewSettings(bytes.subarray(at2 + 1, lineEnd).toString("utf8"));
|
|
56095
|
-
if (settings2) return autoReviewed(settings2);
|
|
56096
|
-
lineEnd = at2;
|
|
56097
|
-
if (at2 === 0) break;
|
|
56098
|
-
}
|
|
56099
|
-
carry = bytes.subarray(0, lineEnd);
|
|
56100
|
-
end = start;
|
|
56101
|
-
}
|
|
56102
|
-
const settings = end === 0 ? reviewSettings(carry.toString("utf8")) : void 0;
|
|
56103
|
-
return !!settings && autoReviewed(settings);
|
|
56104
|
-
} catch {
|
|
56105
|
-
return false;
|
|
56106
|
-
} finally {
|
|
56107
|
-
await file4.close().catch(() => {
|
|
56108
|
-
});
|
|
56109
|
-
}
|
|
56110
|
-
}
|
|
56111
|
-
function reviewSettings(line) {
|
|
56112
|
-
if (!line.includes('"approvals_reviewer"') || !(line.includes('"type":"turn_context"') || line.includes('"type":"thread_settings_applied"'))) return void 0;
|
|
56113
|
-
try {
|
|
56114
|
-
const entry2 = JSON.parse(line);
|
|
56115
|
-
const payload = entry2?.payload;
|
|
56116
|
-
const settings = entry2?.type === "turn_context" ? payload : entry2?.type === "event_msg" && payload?.type === "thread_settings_applied" ? payload.thread_settings : void 0;
|
|
56117
|
-
if (!settings || !("approvals_reviewer" in settings)) return void 0;
|
|
56118
|
-
return { reviewer: settings.approvals_reviewer, policy: settings.approval_policy };
|
|
56119
|
-
} catch {
|
|
56120
|
-
return void 0;
|
|
56121
|
-
}
|
|
56122
|
-
}
|
|
56123
|
-
function autoReviewed({ reviewer, policy }) {
|
|
56124
|
-
return reviewer === "auto_review" && (policy === "on-request" || !!policy && typeof policy === "object" && "granular" in policy);
|
|
56125
|
-
}
|
|
56126
|
-
var SCAN_LIMIT, CHUNK;
|
|
56127
|
-
var init_codex_review_mode = __esm({
|
|
56128
|
-
"src/bridge/codex-review-mode.ts"() {
|
|
56129
|
-
"use strict";
|
|
56130
|
-
SCAN_LIMIT = 64 * 1048576;
|
|
56131
|
-
CHUNK = 1048576;
|
|
56132
|
-
}
|
|
56133
|
-
});
|
|
56134
|
-
|
|
56135
|
-
// src/bridge/codex-thread-origin.ts
|
|
56136
|
-
import { open as open19 } from "node:fs/promises";
|
|
56137
|
-
import path101 from "node:path";
|
|
56138
|
-
async function codexForeignThread(transcriptPath2) {
|
|
56139
|
-
if (typeof transcriptPath2 !== "string" || !path101.isAbsolute(transcriptPath2) || !/^rollout-.*\.jsonl$/.test(path101.basename(transcriptPath2))) return false;
|
|
56140
|
-
const file4 = await open19(transcriptPath2, "r").catch(() => void 0);
|
|
56141
|
-
if (!file4) return false;
|
|
56142
|
-
try {
|
|
56143
|
-
const buffer = Buffer.alloc(4096), { bytesRead } = await file4.read(buffer, 0, buffer.length, 0);
|
|
56144
|
-
return foreignMeta(buffer.subarray(0, bytesRead).toString("utf8"));
|
|
56145
|
-
} finally {
|
|
56146
|
-
await file4.close();
|
|
56147
|
-
}
|
|
56148
|
-
}
|
|
56149
|
-
function foreignMeta(head) {
|
|
56150
|
-
if (!head.includes('"session_meta"')) return false;
|
|
56151
|
-
return /"originator"\s*:\s*"codex_exec"/.test(head) || /"source"\s*:\s*"exec"/.test(head) || /"source"\s*:\s*\{\s*"subagent"/.test(head);
|
|
56152
|
-
}
|
|
56153
|
-
var init_codex_thread_origin = __esm({
|
|
56154
|
-
"src/bridge/codex-thread-origin.ts"() {
|
|
56155
|
-
"use strict";
|
|
56156
|
-
}
|
|
56157
|
-
});
|
|
56158
|
-
|
|
56159
56575
|
// src/bridge/push.ts
|
|
56160
56576
|
import { createCipheriv, createHmac as createHmac3, createPrivateKey, randomBytes as randomBytes6, sign } from "node:crypto";
|
|
56161
|
-
import { readFile as
|
|
56577
|
+
import { readFile as readFile42, stat as stat21 } from "node:fs/promises";
|
|
56162
56578
|
import { connect as connect3 } from "node:http2";
|
|
56163
|
-
import
|
|
56579
|
+
import path100 from "node:path";
|
|
56164
56580
|
function scheduleCollapseId(kind, runId) {
|
|
56165
56581
|
return `${runId.slice(0, 63 - kind.length)}-${kind}`;
|
|
56166
56582
|
}
|
|
@@ -56229,7 +56645,7 @@ async function secureJSON(file4, schema) {
|
|
|
56229
56645
|
try {
|
|
56230
56646
|
const metadata = await stat21(file4);
|
|
56231
56647
|
if ((metadata.mode & 63) !== 0 || process.getuid && metadata.uid !== process.getuid()) return void 0;
|
|
56232
|
-
return schema.parse(JSON.parse(await
|
|
56648
|
+
return schema.parse(JSON.parse(await readFile42(file4, "utf8")));
|
|
56233
56649
|
} catch {
|
|
56234
56650
|
return void 0;
|
|
56235
56651
|
}
|
|
@@ -56238,12 +56654,12 @@ async function secureFile(file4) {
|
|
|
56238
56654
|
try {
|
|
56239
56655
|
const metadata = await stat21(file4);
|
|
56240
56656
|
if (!metadata.isFile() || (metadata.mode & 63) !== 0 || process.getuid && metadata.uid !== process.getuid()) return void 0;
|
|
56241
|
-
return await
|
|
56657
|
+
return await readFile42(file4, "utf8");
|
|
56242
56658
|
} catch {
|
|
56243
56659
|
return void 0;
|
|
56244
56660
|
}
|
|
56245
56661
|
}
|
|
56246
|
-
function apnsSetupSteps(configFile = process.env.PHREN_APNS_CONFIG ||
|
|
56662
|
+
function apnsSetupSteps(configFile = process.env.PHREN_APNS_CONFIG || path100.join(bridgeRoot(), "apns.json")) {
|
|
56247
56663
|
return [
|
|
56248
56664
|
"Approval push is not configured: the phone only alerts while Phren runs, and a registered phone gets nothing while suspended.",
|
|
56249
56665
|
"1. In your Apple developer account, create an APNs key (Keys, Apple Push Notifications service) and download AuthKey_<KEYID>.p8.",
|
|
@@ -56396,13 +56812,13 @@ var init_push = __esm({
|
|
|
56396
56812
|
ApprovalPushService = class {
|
|
56397
56813
|
devices = [];
|
|
56398
56814
|
sender;
|
|
56399
|
-
devicesFile =
|
|
56815
|
+
devicesFile = path100.join(bridgeRoot(), "push-devices.json");
|
|
56400
56816
|
async start() {
|
|
56401
56817
|
this.devices = await secureJSON(this.devicesFile, external_exports.array(deviceSchema).max(16)) ?? [];
|
|
56402
|
-
const configFile = process.env.PHREN_APNS_CONFIG ||
|
|
56818
|
+
const configFile = process.env.PHREN_APNS_CONFIG || path100.join(bridgeRoot(), "apns.json");
|
|
56403
56819
|
const config4 = await secureJSON(configFile, configSchema2);
|
|
56404
56820
|
if (!config4) return;
|
|
56405
|
-
const keyPath =
|
|
56821
|
+
const keyPath = path100.isAbsolute(config4.privateKeyPath) ? config4.privateKeyPath : path100.resolve(path100.dirname(configFile), config4.privateKeyPath);
|
|
56406
56822
|
const key4 = await secureFile(keyPath);
|
|
56407
56823
|
if (key4) this.sender = new APNsSender(config4, key4);
|
|
56408
56824
|
}
|
|
@@ -56730,10 +57146,18 @@ async function scopedDispatch(scope, command, io) {
|
|
|
56730
57146
|
answered = true;
|
|
56731
57147
|
io.output.write(httpResponse(503, "Phren Hook is not running on this computer."));
|
|
56732
57148
|
});
|
|
56733
|
-
socket.
|
|
57149
|
+
socket.setTimeout(io.answerIdleMs ?? ANSWER_IDLE_MS, () => socket.destroy());
|
|
57150
|
+
const drop = () => socket.destroy();
|
|
57151
|
+
io.output.once("error", drop);
|
|
57152
|
+
io.output.once("close", drop);
|
|
57153
|
+
socket.on("close", () => {
|
|
57154
|
+
io.output.off("error", drop);
|
|
57155
|
+
io.output.off("close", drop);
|
|
57156
|
+
resolve17();
|
|
57157
|
+
});
|
|
56734
57158
|
});
|
|
56735
57159
|
}
|
|
56736
|
-
var GATEWAY_SCOPES, SCOPE_KEY_COMMENT, SCOPED_COMMAND, MAX_HEAD, MAX_HEADER_LINE, MAX_HEADERS, READ_TIMEOUT_MS, PROJECT, one, only, RULES, DESCRIBE, refuse, REASONS;
|
|
57160
|
+
var GATEWAY_SCOPES, SCOPE_KEY_COMMENT, SCOPED_COMMAND, MAX_HEAD, MAX_HEADER_LINE, MAX_HEADERS, READ_TIMEOUT_MS, ANSWER_IDLE_MS, PROJECT, one, only, RULES, DESCRIBE, refuse, REASONS;
|
|
56737
57161
|
var init_scoped_gateway = __esm({
|
|
56738
57162
|
"src/bridge/scoped-gateway.ts"() {
|
|
56739
57163
|
"use strict";
|
|
@@ -56746,6 +57170,7 @@ var init_scoped_gateway = __esm({
|
|
|
56746
57170
|
MAX_HEADER_LINE = 8192;
|
|
56747
57171
|
MAX_HEADERS = 32;
|
|
56748
57172
|
READ_TIMEOUT_MS = 1e4;
|
|
57173
|
+
ANSWER_IDLE_MS = 6e4;
|
|
56749
57174
|
PROJECT = PROJECT_NAME2.source.slice(1, -1);
|
|
56750
57175
|
one = (query, key4) => query.get(key4)?.length === 1 ? query.get(key4)[0] : void 0;
|
|
56751
57176
|
only = (query, keys2) => [...query.keys()].every((key4) => keys2.includes(key4));
|
|
@@ -56819,10 +57244,10 @@ var init_pair = __esm({
|
|
|
56819
57244
|
|
|
56820
57245
|
// src/bridge/opencode-permissions.ts
|
|
56821
57246
|
import { randomUUID as randomUUID23 } from "node:crypto";
|
|
56822
|
-
import { lstat as lstat27, mkdir as mkdir25, readFile as
|
|
56823
|
-
import
|
|
57247
|
+
import { lstat as lstat27, mkdir as mkdir25, readFile as readFile43, rename as rename6, unlink as unlink6, writeFile as writeFile7 } from "node:fs/promises";
|
|
57248
|
+
import path101 from "node:path";
|
|
56824
57249
|
function opencodeConfigPath(env = process.env, home = homeDir(env)) {
|
|
56825
|
-
return
|
|
57250
|
+
return path101.join(env.XDG_CONFIG_HOME || path101.join(home, ".config"), "opencode", "opencode.json");
|
|
56826
57251
|
}
|
|
56827
57252
|
function opencodeToolName(value2) {
|
|
56828
57253
|
if (typeof value2 !== "string") return void 0;
|
|
@@ -56832,7 +57257,7 @@ function opencodeToolName(value2) {
|
|
|
56832
57257
|
async function readConfig2(file4) {
|
|
56833
57258
|
let text5;
|
|
56834
57259
|
try {
|
|
56835
|
-
text5 = await
|
|
57260
|
+
text5 = await readFile43(file4, "utf8");
|
|
56836
57261
|
} catch (error62) {
|
|
56837
57262
|
if (error62.code === "ENOENT") return {};
|
|
56838
57263
|
throw new BridgeError(409, "Could not read ~/.config/opencode/opencode.json.");
|
|
@@ -56870,12 +57295,12 @@ async function allowOpencodeToolEverywhere(tool, file4 = opencodeConfigPath()) {
|
|
|
56870
57295
|
try {
|
|
56871
57296
|
const config4 = withAllowedTool(await readConfig2(file4), name);
|
|
56872
57297
|
const mode = (await lstat27(file4).catch(() => void 0))?.mode;
|
|
56873
|
-
await mkdir25(
|
|
57298
|
+
await mkdir25(path101.dirname(file4), { recursive: true, mode: 448 });
|
|
56874
57299
|
const temporary = `${file4}.${randomUUID23()}.tmp`;
|
|
56875
|
-
await
|
|
57300
|
+
await writeFile7(temporary, `${JSON.stringify(config4, null, 2)}
|
|
56876
57301
|
`, { mode: mode === void 0 ? 384 : mode & 511, flag: "wx" });
|
|
56877
57302
|
try {
|
|
56878
|
-
await
|
|
57303
|
+
await rename6(temporary, file4);
|
|
56879
57304
|
} finally {
|
|
56880
57305
|
await unlink6(temporary).catch(() => {
|
|
56881
57306
|
});
|
|
@@ -56895,29 +57320,37 @@ var init_opencode_permissions = __esm({
|
|
|
56895
57320
|
});
|
|
56896
57321
|
|
|
56897
57322
|
// src/bridge/prompt-deliveries.ts
|
|
56898
|
-
import { createHash as
|
|
56899
|
-
import { readFileSync as
|
|
56900
|
-
import { open as
|
|
57323
|
+
import { createHash as createHash29 } from "node:crypto";
|
|
57324
|
+
import { readFileSync as readFileSync43 } from "node:fs";
|
|
57325
|
+
import { open as open18 } from "node:fs/promises";
|
|
56901
57326
|
function promptKey(text5) {
|
|
56902
57327
|
return unwrapPastedContent(text5).split("\n").filter((line) => !PICTURE_PATH_LINE.test(line)).join("\n").replace(/\[Image #\d+\]/g, " ").replace(/\s+/g, " ").trim();
|
|
56903
57328
|
}
|
|
56904
|
-
|
|
56905
|
-
const
|
|
57329
|
+
function matchingOffsets(buffer, start, record4) {
|
|
57330
|
+
const entries2 = [];
|
|
57331
|
+
const lines = buffer.toString("utf8").split("\n");
|
|
57332
|
+
let offset = start + buffer.length;
|
|
57333
|
+
for (let index2 = lines.length - 1; index2 >= 0; index2--) {
|
|
57334
|
+
const line = lines[index2];
|
|
57335
|
+
offset -= Buffer.byteLength(line) + (index2 < lines.length - 1 ? 1 : 0);
|
|
57336
|
+
let row;
|
|
57337
|
+
try {
|
|
57338
|
+
row = object2(JSON.parse(line));
|
|
57339
|
+
} catch {
|
|
57340
|
+
continue;
|
|
57341
|
+
}
|
|
57342
|
+
const stamp2 = Date.parse(String(row.timestamp ?? ""));
|
|
57343
|
+
if (Number.isFinite(stamp2) && stamp2 < record4.at - 5e3) break;
|
|
57344
|
+
if (userTexts(row).some((text5) => promptHash(text5) === record4.hash)) entries2.push({ offset, hook: row.type === "user" });
|
|
57345
|
+
}
|
|
57346
|
+
return entries2;
|
|
57347
|
+
}
|
|
57348
|
+
async function transcriptEntries(record4) {
|
|
57349
|
+
const file4 = await open18(await transcriptPath(record4.source, record4.session), "r");
|
|
56906
57350
|
try {
|
|
56907
57351
|
const size = (await file4.stat()).size, start = Math.max(0, size - 524288), buffer = Buffer.alloc(size - start);
|
|
56908
57352
|
await file4.read(buffer, 0, buffer.length, start);
|
|
56909
|
-
|
|
56910
|
-
let row;
|
|
56911
|
-
try {
|
|
56912
|
-
row = object2(JSON.parse(line));
|
|
56913
|
-
} catch {
|
|
56914
|
-
continue;
|
|
56915
|
-
}
|
|
56916
|
-
const stamp2 = Date.parse(String(row.timestamp ?? ""));
|
|
56917
|
-
if (Number.isFinite(stamp2) && stamp2 < record4.at - 5e3) break;
|
|
56918
|
-
for (const text5 of userTexts(row)) if (promptHash(text5) === record4.hash) return true;
|
|
56919
|
-
}
|
|
56920
|
-
return false;
|
|
57353
|
+
return matchingOffsets(buffer, start, record4);
|
|
56921
57354
|
} finally {
|
|
56922
57355
|
await file4.close();
|
|
56923
57356
|
}
|
|
@@ -56929,12 +57362,13 @@ function userTexts(row) {
|
|
|
56929
57362
|
else for (const block of objects(content)) if (typeof block.text === "string") texts.push(block.text);
|
|
56930
57363
|
};
|
|
56931
57364
|
if (row.type === "user" && !row.isMeta) blocks(object2(row.message).content);
|
|
57365
|
+
if (row.type === "queue-operation" && row.operation === "remove" && typeof row.content === "string" && (row.reason === "absorbed_mid_turn" || row.reason === "delivered_to_agent")) texts.push(row.content);
|
|
56932
57366
|
const payload = object2(row.payload);
|
|
56933
57367
|
if (payload.type === "user_message" && typeof payload.message === "string") texts.push(payload.message);
|
|
56934
57368
|
if (payload.type === "message" && payload.role === "user") blocks(payload.content);
|
|
56935
57369
|
return texts;
|
|
56936
57370
|
}
|
|
56937
|
-
var DELIVERY_RETENTION_MS, DELIVERY_GIVE_UP_MS, MAX_RECORDS, PICTURE_PATH_LINE, promptHash, recordSchema2, PromptDeliveries;
|
|
57371
|
+
var DELIVERY_RETENTION_MS, DELIVERY_GIVE_UP_MS, MAX_RECORDS, LANDED_CHECK_MS, ENTRY_SLACK_MS, PICTURE_PATH_LINE, promptHash, recordSchema2, PromptDeliveries;
|
|
56938
57372
|
var init_prompt_deliveries = __esm({
|
|
56939
57373
|
"src/bridge/prompt-deliveries.ts"() {
|
|
56940
57374
|
"use strict";
|
|
@@ -56944,8 +57378,10 @@ var init_prompt_deliveries = __esm({
|
|
|
56944
57378
|
DELIVERY_RETENTION_MS = 24 * 36e5;
|
|
56945
57379
|
DELIVERY_GIVE_UP_MS = 3e4;
|
|
56946
57380
|
MAX_RECORDS = 512;
|
|
57381
|
+
LANDED_CHECK_MS = 3e3;
|
|
57382
|
+
ENTRY_SLACK_MS = 5e3;
|
|
56947
57383
|
PICTURE_PATH_LINE = /^\s*\/.*\.(?:png|jpe?g|gif|webp)\s*$/i;
|
|
56948
|
-
promptHash = (text5) =>
|
|
57384
|
+
promptHash = (text5) => createHash29("sha256").update(promptKey(text5)).digest("hex");
|
|
56949
57385
|
recordSchema2 = external_exports.object({
|
|
56950
57386
|
id: external_exports.string().regex(/^[A-Za-z0-9_-]{8,64}$/).optional(),
|
|
56951
57387
|
hash: external_exports.string().regex(/^[0-9a-f]{64}$/),
|
|
@@ -56958,16 +57394,18 @@ var init_prompt_deliveries = __esm({
|
|
|
56958
57394
|
reason: external_exports.string().max(500).optional(),
|
|
56959
57395
|
at: external_exports.number(),
|
|
56960
57396
|
settledAt: external_exports.number().optional(),
|
|
56961
|
-
stoppedAt: external_exports.number().optional()
|
|
57397
|
+
stoppedAt: external_exports.number().optional(),
|
|
57398
|
+
/** The transcript entry (byte offset) that settled it, so no other message claims the same one. */
|
|
57399
|
+
entry: external_exports.number().optional()
|
|
56962
57400
|
}).strict();
|
|
56963
|
-
PromptDeliveries = class {
|
|
56964
|
-
constructor(file4, now = Date.now, landed =
|
|
57401
|
+
PromptDeliveries = class _PromptDeliveries {
|
|
57402
|
+
constructor(file4, now = Date.now, landed = transcriptEntries) {
|
|
56965
57403
|
this.file = file4;
|
|
56966
57404
|
this.now = now;
|
|
56967
57405
|
this.landed = landed;
|
|
56968
57406
|
if (!file4) return;
|
|
56969
57407
|
try {
|
|
56970
|
-
for (const row of objects(object2(JSON.parse(
|
|
57408
|
+
for (const row of objects(object2(JSON.parse(readFileSync43(file4, "utf8"))).records)) {
|
|
56971
57409
|
const parsed = recordSchema2.safeParse(row);
|
|
56972
57410
|
if (parsed.success) this.records.push({ ...parsed.data, state: parsed.data.state === "typed" ? "queued" : parsed.data.state });
|
|
56973
57411
|
}
|
|
@@ -56981,6 +57419,18 @@ var init_prompt_deliveries = __esm({
|
|
|
56981
57419
|
records = [];
|
|
56982
57420
|
waiters = /* @__PURE__ */ new Map();
|
|
56983
57421
|
writing = Promise.resolve();
|
|
57422
|
+
/** Panes (server, pane, agent) that sent a UserPromptSubmit or Stop since the Hook started. */
|
|
57423
|
+
hookPanes = /* @__PURE__ */ new Set();
|
|
57424
|
+
paneKey(target) {
|
|
57425
|
+
return [target.server, target.pane, target.source].join("|");
|
|
57426
|
+
}
|
|
57427
|
+
static open(record4) {
|
|
57428
|
+
return record4.state === "typed" || record4.state === "queued";
|
|
57429
|
+
}
|
|
57430
|
+
/** Open, or failed with its own hook's claim still waiting for its row (a late delivery). */
|
|
57431
|
+
static claimable(record4) {
|
|
57432
|
+
return _PromptDeliveries.open(record4) || record4.state === "failed" && !!record4.hookClaim;
|
|
57433
|
+
}
|
|
56984
57434
|
samePane(record4, target) {
|
|
56985
57435
|
return record4.server === target.server && record4.pane === target.pane && record4.source === target.source;
|
|
56986
57436
|
}
|
|
@@ -56994,7 +57444,7 @@ var init_prompt_deliveries = __esm({
|
|
|
56994
57444
|
}
|
|
56995
57445
|
save() {
|
|
56996
57446
|
if (!this.file) return;
|
|
56997
|
-
const rows2 = this.records.filter((record4) => record4.id).map(({ idleSince: _2, ...row }) => row);
|
|
57447
|
+
const rows2 = this.records.filter((record4) => record4.id || record4.entry !== void 0).map(({ idleSince: _2, checkedAt: __, hookClaim: ___, seenRow: ____, ...row }) => row);
|
|
56998
57448
|
const file4 = this.file;
|
|
56999
57449
|
this.writing = this.writing.then(() => atomicInPrivateDir(file4, { records: rows2 })).catch(() => void 0);
|
|
57000
57450
|
}
|
|
@@ -57117,14 +57567,14 @@ var init_prompt_deliveries = __esm({
|
|
|
57117
57567
|
* input still pending on the old one stays there, out of the pane's view.
|
|
57118
57568
|
* Fails loudly; a late UserPromptSubmit from the old thread still settles it. */
|
|
57119
57569
|
threadChanged(previous) {
|
|
57120
|
-
let
|
|
57570
|
+
let changed = false;
|
|
57121
57571
|
for (const record4 of this.records) if ((record4.state === "typed" || record4.state === "queued") && this.samePane(record4, previous) && record4.session === previous.session) {
|
|
57122
57572
|
record4.state = "failed";
|
|
57123
57573
|
record4.settledAt = this.now();
|
|
57124
|
-
|
|
57574
|
+
changed = true;
|
|
57125
57575
|
record4.reason = "The pane moved to another Codex conversation before the agent took the message.";
|
|
57126
57576
|
}
|
|
57127
|
-
if (
|
|
57577
|
+
if (changed) this.save();
|
|
57128
57578
|
}
|
|
57129
57579
|
/** False when `id` names another message: other words or another pane. */
|
|
57130
57580
|
sameMessage(id2, target, text5) {
|
|
@@ -57145,23 +57595,104 @@ var init_prompt_deliveries = __esm({
|
|
|
57145
57595
|
/** Conversation `target` just submitted `prompt`. Its own record wins, then
|
|
57146
57596
|
* the oldest open one in the same pane: the agent kept the text across a
|
|
57147
57597
|
* conversation change, and the conversation now in the pane is where it
|
|
57148
|
-
* went. A prompt nothing matches was typed locally. Never refused.
|
|
57149
|
-
|
|
57598
|
+
* went. A prompt nothing matches was typed locally. Never refused.
|
|
57599
|
+
* For Claude the transcript is consulted first and the submission claims
|
|
57600
|
+
* the earliest unclaimed user row with these words, through the same
|
|
57601
|
+
* `settle` and the same table of claimed entries the idle check uses: a
|
|
57602
|
+
* callback for a row already claimed (the idle check settled it, the hook
|
|
57603
|
+
* came late) settles nothing more. */
|
|
57604
|
+
async submitted(target, prompt) {
|
|
57150
57605
|
const hash2 = promptHash(prompt);
|
|
57151
|
-
|
|
57152
|
-
const
|
|
57606
|
+
this.hookPanes.add(this.paneKey(target));
|
|
57607
|
+
const pick3 = () => {
|
|
57608
|
+
const open30 = this.records.filter((record5) => record5.hash === hash2 && this.samePane(record5, target) && record5.state !== "delivered");
|
|
57609
|
+
return open30.find((entry3) => entry3.session === target.session) ?? open30[0];
|
|
57610
|
+
};
|
|
57611
|
+
let record4 = pick3();
|
|
57153
57612
|
if (!record4) return;
|
|
57613
|
+
let entry2;
|
|
57614
|
+
if (target.source === "claude") {
|
|
57615
|
+
let rows2;
|
|
57616
|
+
try {
|
|
57617
|
+
rows2 = (await this.landed({ source: target.source, session: target.session, hash: hash2, at: record4.at })).filter((row) => row.hook);
|
|
57618
|
+
} catch {
|
|
57619
|
+
rows2 = void 0;
|
|
57620
|
+
}
|
|
57621
|
+
record4 = pick3();
|
|
57622
|
+
if (!record4) return;
|
|
57623
|
+
const claimed = new Set(this.records.filter((other) => other.hash === hash2 && this.samePane(other, target) && other.session === target.session && other.entry !== void 0).map((other) => other.entry));
|
|
57624
|
+
if (!rows2 && !claimed.size) {
|
|
57625
|
+
this.settle(record4, void 0, target.session);
|
|
57626
|
+
this.save();
|
|
57627
|
+
return;
|
|
57628
|
+
}
|
|
57629
|
+
if (!rows2?.length) {
|
|
57630
|
+
record4.hookClaim = true;
|
|
57631
|
+
record4.session = target.session;
|
|
57632
|
+
return;
|
|
57633
|
+
}
|
|
57634
|
+
const free = rows2.filter((row) => !claimed.has(row.offset)).sort((a, b) => a.offset - b.offset)[0];
|
|
57635
|
+
if (!free) return;
|
|
57636
|
+
entry2 = free.offset;
|
|
57637
|
+
}
|
|
57638
|
+
this.settle(record4, entry2, target.session);
|
|
57639
|
+
this.save();
|
|
57640
|
+
}
|
|
57641
|
+
/** Marks `record` delivered, with the transcript entry that settled it when known. */
|
|
57642
|
+
settle(record4, entry2, session) {
|
|
57154
57643
|
record4.state = "delivered";
|
|
57155
|
-
record4.session = target.session;
|
|
57156
57644
|
record4.settledAt = this.now();
|
|
57157
57645
|
delete record4.reason;
|
|
57158
|
-
|
|
57646
|
+
delete record4.hookClaim;
|
|
57647
|
+
delete record4.seenRow;
|
|
57648
|
+
if (session) record4.session = session;
|
|
57649
|
+
if (entry2 !== void 0) record4.entry = entry2;
|
|
57159
57650
|
this.release(record4, "delivered");
|
|
57160
57651
|
}
|
|
57652
|
+
/** Whether the transcript shows the agent took `record`'s message, claiming the entry it settled with.
|
|
57653
|
+
* An entry settles one message: the table of records' `entry` offsets (per conversation) is the only
|
|
57654
|
+
* state, so neither this path nor the hook's can settle two messages with one turn. A user row is a
|
|
57655
|
+
* turn start whose UserPromptSubmit hook settles the message itself, so while the agent works only a
|
|
57656
|
+
* mid-turn queue removal (no hook fires for it) settles from the transcript; once the agent is idle
|
|
57657
|
+
* (`working` false) a user row settles too, for a hook that never came. Of several identical open
|
|
57658
|
+
* messages the oldest take the entries. `pass` carries the entries still unclaimed within one observe. */
|
|
57659
|
+
async taken(record4, pass, working = false) {
|
|
57660
|
+
if (record4.source !== "claude") return (await this.landed(record4).catch(() => [])).length > 0;
|
|
57661
|
+
const same2 = (other) => other.hash === record4.hash && other.server === record4.server && other.pane === record4.pane && other.session === record4.session;
|
|
57662
|
+
const open30 = this.records.filter((other) => same2(other) && _PromptDeliveries.claimable(other)).sort((a, b) => a.at - b.at);
|
|
57663
|
+
if (open30[0] !== record4) return false;
|
|
57664
|
+
const key4 = [record4.hash, record4.server, record4.pane, record4.session, working].join("|");
|
|
57665
|
+
let free = pass.get(key4);
|
|
57666
|
+
if (!free) {
|
|
57667
|
+
const found = (await this.landed(record4).catch(() => [])).sort((a, b) => a.offset - b.offset);
|
|
57668
|
+
const used = new Set(this.records.filter((other) => same2(other) && other.entry !== void 0).map((other) => other.entry));
|
|
57669
|
+
let hooked = this.records.filter((other) => same2(other) && other.state === "delivered" && other.entry === void 0 && (other.settledAt ?? 0) >= record4.at - ENTRY_SLACK_MS).length;
|
|
57670
|
+
const unclaimed = found.filter((entry3) => !used.has(entry3.offset)).filter((entry3) => !(entry3.hook && hooked-- > 0));
|
|
57671
|
+
if (working) {
|
|
57672
|
+
const row = unclaimed.find((entry3) => entry3.hook);
|
|
57673
|
+
const hookless = !this.hookPanes.has(this.paneKey(record4));
|
|
57674
|
+
const own2 = row && (record4.hookClaim || hookless && record4.seenRow === row.offset);
|
|
57675
|
+
if (row && hookless && !own2) record4.seenRow = row.offset;
|
|
57676
|
+
free = unclaimed.filter((entry3) => !entry3.hook || own2 && entry3 === row);
|
|
57677
|
+
} else free = unclaimed;
|
|
57678
|
+
}
|
|
57679
|
+
if (!_PromptDeliveries.claimable(record4)) return false;
|
|
57680
|
+
const entry2 = free.shift();
|
|
57681
|
+
pass.set(key4, free);
|
|
57682
|
+
if (entry2 === void 0) return false;
|
|
57683
|
+
record4.entry = entry2.offset;
|
|
57684
|
+
return true;
|
|
57685
|
+
}
|
|
57161
57686
|
/** A turn in `target`'s pane ended: the agent now takes held input or never will. */
|
|
57162
57687
|
stopped(target) {
|
|
57163
57688
|
const at2 = this.now();
|
|
57164
|
-
|
|
57689
|
+
this.hookPanes.add(this.paneKey(target));
|
|
57690
|
+
let marked = false;
|
|
57691
|
+
for (const record4 of this.records) if (this.samePane(record4, target) && (record4.state === "typed" || record4.state === "queued") && record4.at < at2) {
|
|
57692
|
+
record4.stoppedAt = at2;
|
|
57693
|
+
marked = true;
|
|
57694
|
+
}
|
|
57695
|
+
if (marked) this.save();
|
|
57165
57696
|
}
|
|
57166
57697
|
/** Called on the Hook's activity tick with a server's panes. A message
|
|
57167
57698
|
* still held fails loudly when its pane closed, its agent restarted, or the
|
|
@@ -57169,53 +57700,126 @@ var init_prompt_deliveries = __esm({
|
|
|
57169
57700
|
* transcript shows it after all). */
|
|
57170
57701
|
async observe(server, panes2) {
|
|
57171
57702
|
const now = this.now();
|
|
57172
|
-
let
|
|
57703
|
+
let changed = false;
|
|
57704
|
+
const pass = /* @__PURE__ */ new Map();
|
|
57173
57705
|
for (const record4 of this.records) {
|
|
57174
|
-
if (record4.server !== server
|
|
57706
|
+
if (record4.server !== server) continue;
|
|
57707
|
+
if (record4.state === "failed" && record4.hookClaim) {
|
|
57708
|
+
if (record4.source === "claude" && (record4.checkedAt === void 0 || now - record4.checkedAt >= LANDED_CHECK_MS)) {
|
|
57709
|
+
record4.checkedAt = now;
|
|
57710
|
+
if (await this.taken(record4, pass, true)) {
|
|
57711
|
+
this.settle(record4);
|
|
57712
|
+
changed = true;
|
|
57713
|
+
}
|
|
57714
|
+
}
|
|
57715
|
+
continue;
|
|
57716
|
+
}
|
|
57717
|
+
if (record4.state !== "typed" && record4.state !== "queued") continue;
|
|
57175
57718
|
const pane = panes2.find((entry2) => entry2.pane_id === record4.pane);
|
|
57176
57719
|
if (!pane || record4.terminal && pane.terminal_id !== record4.terminal || pane.agent && pane.agent !== record4.source) {
|
|
57177
|
-
if (await this.
|
|
57178
|
-
record4
|
|
57179
|
-
|
|
57180
|
-
changed2 = true;
|
|
57181
|
-
this.release(record4, "delivered");
|
|
57720
|
+
if (await this.taken(record4, pass)) {
|
|
57721
|
+
this.settle(record4);
|
|
57722
|
+
changed = true;
|
|
57182
57723
|
continue;
|
|
57183
57724
|
}
|
|
57725
|
+
if (!_PromptDeliveries.open(record4)) continue;
|
|
57184
57726
|
record4.state = "failed";
|
|
57185
57727
|
record4.settledAt = now;
|
|
57186
|
-
|
|
57728
|
+
changed = true;
|
|
57187
57729
|
record4.reason = pane ? "The agent in this pane restarted before it took the message." : "The agent's pane closed before it took the message.";
|
|
57188
57730
|
continue;
|
|
57189
57731
|
}
|
|
57190
57732
|
if (!["idle", "done"].includes(String(pane.agent_status))) {
|
|
57191
57733
|
record4.idleSince = void 0;
|
|
57734
|
+
if (record4.source === "claude" && (record4.checkedAt === void 0 || now - record4.checkedAt >= LANDED_CHECK_MS)) {
|
|
57735
|
+
record4.checkedAt = now;
|
|
57736
|
+
if (await this.taken(record4, pass, true)) {
|
|
57737
|
+
this.settle(record4);
|
|
57738
|
+
changed = true;
|
|
57739
|
+
}
|
|
57740
|
+
}
|
|
57192
57741
|
continue;
|
|
57193
57742
|
}
|
|
57194
57743
|
record4.idleSince ??= now;
|
|
57195
57744
|
if (record4.stoppedAt === void 0 || now - Math.max(record4.idleSince, record4.stoppedAt) < DELIVERY_GIVE_UP_MS) continue;
|
|
57196
|
-
if (await this.
|
|
57197
|
-
record4
|
|
57198
|
-
|
|
57199
|
-
changed2 = true;
|
|
57200
|
-
this.release(record4, "delivered");
|
|
57745
|
+
if (await this.taken(record4, pass)) {
|
|
57746
|
+
this.settle(record4);
|
|
57747
|
+
changed = true;
|
|
57201
57748
|
continue;
|
|
57202
57749
|
}
|
|
57750
|
+
if (!_PromptDeliveries.open(record4)) continue;
|
|
57203
57751
|
record4.state = "failed";
|
|
57204
57752
|
record4.settledAt = now;
|
|
57205
|
-
|
|
57753
|
+
changed = true;
|
|
57206
57754
|
record4.reason = "The agent finished its turn without taking the message.";
|
|
57207
57755
|
}
|
|
57208
|
-
if (
|
|
57756
|
+
if (changed) this.save();
|
|
57209
57757
|
}
|
|
57210
57758
|
};
|
|
57211
57759
|
}
|
|
57212
57760
|
});
|
|
57213
57761
|
|
|
57762
|
+
// src/bridge/agent-hook-asks.ts
|
|
57763
|
+
function appServerApproval(request9) {
|
|
57764
|
+
const params = request9.params;
|
|
57765
|
+
const reason2 = typeof params.reason === "string" && params.reason ? { reason: params.reason } : {};
|
|
57766
|
+
if (request9.method === "item/commandExecution/requestApproval") {
|
|
57767
|
+
return { tool: "Bash", input: {
|
|
57768
|
+
...typeof params.command === "string" ? { command: params.command } : {},
|
|
57769
|
+
...typeof params.cwd === "string" ? { cwd: params.cwd } : {},
|
|
57770
|
+
...reason2
|
|
57771
|
+
} };
|
|
57772
|
+
}
|
|
57773
|
+
if (request9.method === "item/fileChange/requestApproval") {
|
|
57774
|
+
const changes = objects(params.changes);
|
|
57775
|
+
const verb = (change) => object2(change.kind).type === "add" ? "Add" : object2(change.kind).type === "delete" ? "Delete" : "Update";
|
|
57776
|
+
const patch = changes.filter((change) => typeof change.path === "string").map((change) => `*** ${verb(change)} File: ${change.path}`).join("\n");
|
|
57777
|
+
return { tool: "apply_patch", input: { ...patch ? { patch } : {}, ...typeof params.grantRoot === "string" ? { grantRoot: params.grantRoot } : {}, ...reason2 } };
|
|
57778
|
+
}
|
|
57779
|
+
if (request9.method === "item/permissions/requestApproval") return { tool: "Permissions", input: { permissions: params.permissions ?? {}, ...reason2 } };
|
|
57780
|
+
return void 0;
|
|
57781
|
+
}
|
|
57782
|
+
function appServerDecision(request9, allow) {
|
|
57783
|
+
if (request9.method === "item/permissions/requestApproval") return { permissions: allow ? object2(request9.params.permissions) : {}, scope: "turn" };
|
|
57784
|
+
return { decision: allow ? "accept" : "decline" };
|
|
57785
|
+
}
|
|
57786
|
+
function conductorCall(tool, input2) {
|
|
57787
|
+
const tail2 = /(?:^|[.:/]|__)(dispatch|hand_off|phren_admin)$/.exec(tool.replace(/^mcp_phren_/, ""))?.[1];
|
|
57788
|
+
const fields2 = object2(input2);
|
|
57789
|
+
let action;
|
|
57790
|
+
if (tail2 === "dispatch") action = "dispatch";
|
|
57791
|
+
else if (tail2 === "hand_off") action = "hand_off";
|
|
57792
|
+
else if (tail2 === "phren_admin" && (fields2.action === "dispatch" || fields2.action === "hand_off")) action = fields2.action;
|
|
57793
|
+
if (!action) return void 0;
|
|
57794
|
+
const project = typeof fields2.project === "string" ? fields2.project : void 0;
|
|
57795
|
+
const computer = typeof fields2.computer === "string" ? fields2.computer : void 0;
|
|
57796
|
+
return { action, ...project ? { project } : {}, ...computer ? { computer } : {} };
|
|
57797
|
+
}
|
|
57798
|
+
function opencodePermissionReply(decision) {
|
|
57799
|
+
if (decision === "approve") return "once";
|
|
57800
|
+
if (decision === "deny") return "reject";
|
|
57801
|
+
if (decision === "allow-project" || decision === "allow-everywhere") return "always";
|
|
57802
|
+
return void 0;
|
|
57803
|
+
}
|
|
57804
|
+
var OPENCODE_APPROVAL_OPTIONS;
|
|
57805
|
+
var init_agent_hook_asks = __esm({
|
|
57806
|
+
"src/bridge/agent-hook-asks.ts"() {
|
|
57807
|
+
"use strict";
|
|
57808
|
+
init_protocol();
|
|
57809
|
+
OPENCODE_APPROVAL_OPTIONS = [
|
|
57810
|
+
{ label: "Allow once", decision: "approve" },
|
|
57811
|
+
{ label: "Allow for this project", decision: "allow-project" },
|
|
57812
|
+
{ label: "Allow everywhere", decision: "allow-everywhere" },
|
|
57813
|
+
{ label: "Deny", decision: "deny" }
|
|
57814
|
+
];
|
|
57815
|
+
}
|
|
57816
|
+
});
|
|
57817
|
+
|
|
57214
57818
|
// src/bridge/opencode-pane-server.ts
|
|
57215
57819
|
import * as crypto12 from "node:crypto";
|
|
57216
57820
|
import * as fs42 from "node:fs";
|
|
57217
57821
|
import * as net from "node:net";
|
|
57218
|
-
import * as
|
|
57822
|
+
import * as path102 from "node:path";
|
|
57219
57823
|
function safeSegment(value2) {
|
|
57220
57824
|
return typeof value2 === "string" && value2.length > 0 && value2 !== "." && value2 !== ".." && !/[/\\\u0000-\u001f\u007f]/.test(value2);
|
|
57221
57825
|
}
|
|
@@ -57233,7 +57837,7 @@ function alive(pid) {
|
|
|
57233
57837
|
}
|
|
57234
57838
|
}
|
|
57235
57839
|
function paneServerFile(dir, server, pane) {
|
|
57236
|
-
return
|
|
57840
|
+
return path102.join(dir, `${encodeURIComponent(`${server}/${pane}`)}.json`);
|
|
57237
57841
|
}
|
|
57238
57842
|
function registerPaneServer(dir, entry2) {
|
|
57239
57843
|
if (!validEntry(entry2)) throw new Error("Invalid OpenCode pane server entry.");
|
|
@@ -57271,7 +57875,7 @@ function listPaneServers(dir) {
|
|
|
57271
57875
|
const entries2 = [];
|
|
57272
57876
|
for (const name of names.slice(0, 1024)) {
|
|
57273
57877
|
if (!name.endsWith(".json")) continue;
|
|
57274
|
-
const file4 =
|
|
57878
|
+
const file4 = path102.join(dir, name);
|
|
57275
57879
|
let parsed;
|
|
57276
57880
|
try {
|
|
57277
57881
|
const info = fs42.lstatSync(file4);
|
|
@@ -57483,10 +58087,10 @@ var init_opencode_pane_server = __esm({
|
|
|
57483
58087
|
|
|
57484
58088
|
// src/bridge/opencode-panes.ts
|
|
57485
58089
|
import { execFile as execFile24 } from "node:child_process";
|
|
57486
|
-
import
|
|
58090
|
+
import path103 from "node:path";
|
|
57487
58091
|
import { promisify as promisify22 } from "node:util";
|
|
57488
58092
|
function paneServersDir() {
|
|
57489
|
-
return
|
|
58093
|
+
return path103.join(bridgeRoot(), "opencode-panes");
|
|
57490
58094
|
}
|
|
57491
58095
|
function servedPane(server, pane) {
|
|
57492
58096
|
return readPaneServer(paneServersDir(), server, pane);
|
|
@@ -57720,69 +58324,99 @@ var init_opencode_panes = __esm({
|
|
|
57720
58324
|
}
|
|
57721
58325
|
});
|
|
57722
58326
|
|
|
57723
|
-
// src/bridge/
|
|
57724
|
-
import {
|
|
57725
|
-
import
|
|
57726
|
-
|
|
57727
|
-
|
|
57728
|
-
|
|
57729
|
-
|
|
57730
|
-
|
|
57731
|
-
|
|
57732
|
-
|
|
57733
|
-
|
|
57734
|
-
|
|
57735
|
-
|
|
57736
|
-
|
|
57737
|
-
|
|
57738
|
-
|
|
57739
|
-
|
|
58327
|
+
// src/bridge/codex-review-mode.ts
|
|
58328
|
+
import { open as open19 } from "node:fs/promises";
|
|
58329
|
+
import path104 from "node:path";
|
|
58330
|
+
async function codexAutoReview(transcriptPath2) {
|
|
58331
|
+
if (typeof transcriptPath2 !== "string" || !path104.isAbsolute(transcriptPath2) || !/^rollout-.*\.jsonl$/.test(path104.basename(transcriptPath2))) return false;
|
|
58332
|
+
const file4 = await open19(transcriptPath2, "r").catch(() => void 0);
|
|
58333
|
+
if (!file4) return false;
|
|
58334
|
+
try {
|
|
58335
|
+
const size = (await file4.stat()).size;
|
|
58336
|
+
let end = size, carry = Buffer.alloc(0);
|
|
58337
|
+
while (end > 0 && size - end < SCAN_LIMIT) {
|
|
58338
|
+
const start = Math.max(0, end - CHUNK), buffer = Buffer.alloc(end - start);
|
|
58339
|
+
await file4.read(buffer, 0, buffer.length, start);
|
|
58340
|
+
const bytes = Buffer.concat([buffer, carry]);
|
|
58341
|
+
let lineEnd = bytes.length;
|
|
58342
|
+
for (let at2 = bytes.lastIndexOf(10, lineEnd - 1); at2 >= 0; at2 = bytes.lastIndexOf(10, lineEnd - 1)) {
|
|
58343
|
+
const settings2 = reviewSettings(bytes.subarray(at2 + 1, lineEnd).toString("utf8"));
|
|
58344
|
+
if (settings2) return autoReviewed(settings2);
|
|
58345
|
+
lineEnd = at2;
|
|
58346
|
+
if (at2 === 0) break;
|
|
58347
|
+
}
|
|
58348
|
+
carry = bytes.subarray(0, lineEnd);
|
|
58349
|
+
end = start;
|
|
58350
|
+
}
|
|
58351
|
+
const settings = end === 0 ? reviewSettings(carry.toString("utf8")) : void 0;
|
|
58352
|
+
return !!settings && autoReviewed(settings);
|
|
58353
|
+
} catch {
|
|
58354
|
+
return false;
|
|
58355
|
+
} finally {
|
|
58356
|
+
await file4.close().catch(() => {
|
|
58357
|
+
});
|
|
58358
|
+
}
|
|
57740
58359
|
}
|
|
57741
|
-
function
|
|
57742
|
-
|
|
57743
|
-
|
|
57744
|
-
|
|
57745
|
-
|
|
57746
|
-
|
|
57747
|
-
|
|
57748
|
-
|
|
57749
|
-
|
|
58360
|
+
function reviewSettings(line) {
|
|
58361
|
+
if (!line.includes('"approvals_reviewer"') || !(line.includes('"type":"turn_context"') || line.includes('"type":"thread_settings_applied"'))) return void 0;
|
|
58362
|
+
try {
|
|
58363
|
+
const entry2 = JSON.parse(line);
|
|
58364
|
+
const payload = entry2?.payload;
|
|
58365
|
+
const settings = entry2?.type === "turn_context" ? payload : entry2?.type === "event_msg" && payload?.type === "thread_settings_applied" ? payload.thread_settings : void 0;
|
|
58366
|
+
if (!settings || !("approvals_reviewer" in settings)) return void 0;
|
|
58367
|
+
return { reviewer: settings.approvals_reviewer, policy: settings.approval_policy };
|
|
58368
|
+
} catch {
|
|
58369
|
+
return void 0;
|
|
57750
58370
|
}
|
|
57751
|
-
|
|
57752
|
-
|
|
57753
|
-
|
|
57754
|
-
|
|
57755
|
-
|
|
58371
|
+
}
|
|
58372
|
+
function autoReviewed({ reviewer, policy }) {
|
|
58373
|
+
return reviewer === "auto_review" && (policy === "on-request" || !!policy && typeof policy === "object" && "granular" in policy);
|
|
58374
|
+
}
|
|
58375
|
+
var SCAN_LIMIT, CHUNK;
|
|
58376
|
+
var init_codex_review_mode = __esm({
|
|
58377
|
+
"src/bridge/codex-review-mode.ts"() {
|
|
58378
|
+
"use strict";
|
|
58379
|
+
SCAN_LIMIT = 64 * 1048576;
|
|
58380
|
+
CHUNK = 1048576;
|
|
57756
58381
|
}
|
|
57757
|
-
|
|
57758
|
-
|
|
58382
|
+
});
|
|
58383
|
+
|
|
58384
|
+
// src/bridge/thread-origin.ts
|
|
58385
|
+
import { open as open20 } from "node:fs/promises";
|
|
58386
|
+
import path105 from "node:path";
|
|
58387
|
+
async function codexForeignThread(transcriptPath2) {
|
|
58388
|
+
if (typeof transcriptPath2 !== "string" || !path105.isAbsolute(transcriptPath2) || !/^rollout-.*\.jsonl$/.test(path105.basename(transcriptPath2))) return false;
|
|
58389
|
+
return foreignMeta(await readHead(transcriptPath2, 4096));
|
|
57759
58390
|
}
|
|
57760
|
-
function
|
|
57761
|
-
|
|
57762
|
-
|
|
58391
|
+
async function readHead(file4, bytes) {
|
|
58392
|
+
const handle = await open20(file4, "r").catch(() => void 0);
|
|
58393
|
+
if (!handle) return "";
|
|
58394
|
+
try {
|
|
58395
|
+
const buffer = Buffer.alloc(bytes), { bytesRead } = await handle.read(buffer, 0, bytes, 0);
|
|
58396
|
+
return buffer.subarray(0, bytesRead).toString("utf8");
|
|
58397
|
+
} finally {
|
|
58398
|
+
await handle.close();
|
|
58399
|
+
}
|
|
57763
58400
|
}
|
|
57764
|
-
function
|
|
57765
|
-
|
|
57766
|
-
|
|
57767
|
-
let action;
|
|
57768
|
-
if (tail2 === "dispatch") action = "dispatch";
|
|
57769
|
-
else if (tail2 === "hand_off") action = "hand_off";
|
|
57770
|
-
else if (tail2 === "phren_admin" && (fields2.action === "dispatch" || fields2.action === "hand_off")) action = fields2.action;
|
|
57771
|
-
if (!action) return void 0;
|
|
57772
|
-
const project = typeof fields2.project === "string" ? fields2.project : void 0;
|
|
57773
|
-
const computer = typeof fields2.computer === "string" ? fields2.computer : void 0;
|
|
57774
|
-
return { action, ...project ? { project } : {}, ...computer ? { computer } : {} };
|
|
58401
|
+
function foreignMeta(head) {
|
|
58402
|
+
if (!head.includes('"session_meta"')) return false;
|
|
58403
|
+
return /"originator"\s*:\s*"codex_exec"/.test(head) || /"source"\s*:\s*"exec"/.test(head) || /"source"\s*:\s*\{\s*"subagent"/.test(head);
|
|
57775
58404
|
}
|
|
57776
|
-
function
|
|
57777
|
-
if (
|
|
57778
|
-
|
|
57779
|
-
if (decision === "allow-project" || decision === "allow-everywhere") return "always";
|
|
57780
|
-
return void 0;
|
|
58405
|
+
async function claudeHeadlessThread(transcriptPath2) {
|
|
58406
|
+
if (typeof transcriptPath2 !== "string" || !path105.isAbsolute(transcriptPath2) || !transcriptPath2.endsWith(".jsonl")) return false;
|
|
58407
|
+
return headlessEntrypoint(await readHead(transcriptPath2, 32768));
|
|
57781
58408
|
}
|
|
57782
|
-
function
|
|
57783
|
-
|
|
57784
|
-
return project ? { project } : {};
|
|
58409
|
+
function headlessEntrypoint(head) {
|
|
58410
|
+
return /"entrypoint"\s*:\s*"sdk-[a-z]+"/.test(head);
|
|
57785
58411
|
}
|
|
58412
|
+
var init_thread_origin = __esm({
|
|
58413
|
+
"src/bridge/thread-origin.ts"() {
|
|
58414
|
+
"use strict";
|
|
58415
|
+
}
|
|
58416
|
+
});
|
|
58417
|
+
|
|
58418
|
+
// src/bridge/agent-hook-callback.ts
|
|
58419
|
+
import { request as request6 } from "node:http";
|
|
57786
58420
|
function stopFacts(value2) {
|
|
57787
58421
|
const tasks = Array.isArray(value2.background_tasks) ? value2.background_tasks.filter((task2) => !["completed", "failed", "killed", "stopped"].includes(String(object2(task2).status))) : void 0;
|
|
57788
58422
|
return {
|
|
@@ -57802,6 +58436,7 @@ async function agentHook(source, elapsed = () => performance.now()) {
|
|
|
57802
58436
|
const value2 = object2(JSON.parse(input2));
|
|
57803
58437
|
if (value2.agent_id || value2.agentId || value2.isSidechain || value2.is_sidechain) return;
|
|
57804
58438
|
if (source === "codex" && await codexForeignThread(value2.transcript_path).catch(() => false)) return;
|
|
58439
|
+
if (source === "claude" && await claudeHeadlessThread(value2.transcript_path).catch(() => false)) return;
|
|
57805
58440
|
const target = targetSchema.parse({
|
|
57806
58441
|
server: place.server,
|
|
57807
58442
|
workspace: place.workspace,
|
|
@@ -57875,23 +58510,56 @@ async function forwardHook(source, target, event, value2, left3) {
|
|
|
57875
58510
|
req.end(data);
|
|
57876
58511
|
});
|
|
57877
58512
|
}
|
|
57878
|
-
var
|
|
58513
|
+
var init_agent_hook_callback = __esm({
|
|
58514
|
+
"src/bridge/agent-hook-callback.ts"() {
|
|
58515
|
+
"use strict";
|
|
58516
|
+
init_shared();
|
|
58517
|
+
init_runtime();
|
|
58518
|
+
init_protocol();
|
|
58519
|
+
init_hook_fast();
|
|
58520
|
+
init_codex_daemon();
|
|
58521
|
+
init_codex_review_mode();
|
|
58522
|
+
init_thread_origin();
|
|
58523
|
+
init_terminal();
|
|
58524
|
+
init_launch_brief();
|
|
58525
|
+
init_codex_servers();
|
|
58526
|
+
init_agent_hook_stores();
|
|
58527
|
+
}
|
|
58528
|
+
});
|
|
58529
|
+
|
|
58530
|
+
// src/bridge/agent-hooks.ts
|
|
58531
|
+
import { createServer as createServer3 } from "node:http";
|
|
58532
|
+
import { mkdir as mkdir26, readFile as readFile44, chmod as chmod4, unlink as unlink7, lstat as lstat28 } from "node:fs/promises";
|
|
58533
|
+
import { watch } from "node:fs";
|
|
58534
|
+
import path106 from "node:path";
|
|
58535
|
+
import { randomUUID as randomUUID24 } from "node:crypto";
|
|
58536
|
+
import { hostname as hostname10 } from "node:os";
|
|
58537
|
+
function watchHangUp(res) {
|
|
58538
|
+
let closed = res.destroyed || res.socket?.destroyed === true;
|
|
58539
|
+
const onClose = () => {
|
|
58540
|
+
if (!res.writableEnded) closed = true;
|
|
58541
|
+
};
|
|
58542
|
+
res.once("close", onClose);
|
|
58543
|
+
return () => {
|
|
58544
|
+
res.off("close", onClose);
|
|
58545
|
+
return closed || res.destroyed;
|
|
58546
|
+
};
|
|
58547
|
+
}
|
|
58548
|
+
function projectField(cwd) {
|
|
58549
|
+
const project = paneProject(cwd, phrenStoreRoot());
|
|
58550
|
+
return project ? { project } : {};
|
|
58551
|
+
}
|
|
58552
|
+
var APPROVAL_SWEEP_MS, OPENCODE_PANES_FRESH_MS, APPROVAL_DEBOUNCE_MS, APPROVAL_HOLD_MS, QUESTION_READ_LINES, DIALOG_READ_MS2, DIALOG_PUSH_MS, FANOUT_SWEEP_MS, SERVED_ASK_MS, FANOUT_ARCHIVE_MS, DISPATCH_LEASE_MS, AgentHooks;
|
|
57879
58553
|
var init_agent_hooks = __esm({
|
|
57880
58554
|
"src/bridge/agent-hooks.ts"() {
|
|
57881
58555
|
"use strict";
|
|
57882
58556
|
init_approval_rules();
|
|
57883
58557
|
init_conductor_role();
|
|
57884
58558
|
init_conductor_context();
|
|
57885
|
-
init_shared();
|
|
57886
58559
|
init_registry();
|
|
57887
|
-
init_runtime();
|
|
57888
58560
|
init_logger();
|
|
57889
58561
|
init_protocol();
|
|
57890
58562
|
init_herdr();
|
|
57891
|
-
init_hook_fast();
|
|
57892
|
-
init_codex_daemon();
|
|
57893
|
-
init_codex_review_mode();
|
|
57894
|
-
init_codex_thread_origin();
|
|
57895
58563
|
init_terminal();
|
|
57896
58564
|
init_pane_text();
|
|
57897
58565
|
init_changes();
|
|
@@ -57913,10 +58581,13 @@ var init_agent_hooks = __esm({
|
|
|
57913
58581
|
init_prompt_deliveries();
|
|
57914
58582
|
init_metrics();
|
|
57915
58583
|
init_launch_brief();
|
|
58584
|
+
init_agent_hook_asks();
|
|
57916
58585
|
init_sudo();
|
|
57917
58586
|
init_codex_servers();
|
|
57918
58587
|
init_opencode_panes();
|
|
57919
58588
|
init_terminal_choice();
|
|
58589
|
+
init_agent_hook_asks();
|
|
58590
|
+
init_agent_hook_callback();
|
|
57920
58591
|
init_agent_hook_stores();
|
|
57921
58592
|
APPROVAL_SWEEP_MS = 2e3;
|
|
57922
58593
|
OPENCODE_PANES_FRESH_MS = 15e3;
|
|
@@ -57925,18 +58596,13 @@ var init_agent_hooks = __esm({
|
|
|
57925
58596
|
const value2 = Number(process.env.PHREN_APPROVAL_HOLD_MS);
|
|
57926
58597
|
return Number.isFinite(value2) && value2 >= 50 && value2 <= 6e4 ? Math.floor(value2) : 55e3;
|
|
57927
58598
|
})();
|
|
58599
|
+
QUESTION_READ_LINES = 120;
|
|
57928
58600
|
DIALOG_READ_MS2 = intervalFromEnv("PHREN_DIALOG_THROTTLE_MS", 3e3);
|
|
57929
58601
|
DIALOG_PUSH_MS = 10 * 6e4;
|
|
57930
58602
|
FANOUT_SWEEP_MS = 5e3;
|
|
57931
58603
|
SERVED_ASK_MS = 60 * 6e4;
|
|
57932
58604
|
FANOUT_ARCHIVE_MS = 60 * 60 * 1e3;
|
|
57933
58605
|
DISPATCH_LEASE_MS = 45e3;
|
|
57934
|
-
OPENCODE_APPROVAL_OPTIONS = [
|
|
57935
|
-
{ label: "Allow once", decision: "approve" },
|
|
57936
|
-
{ label: "Allow for this project", decision: "allow-project" },
|
|
57937
|
-
{ label: "Allow everywhere", decision: "allow-everywhere" },
|
|
57938
|
-
{ label: "Deny", decision: "deny" }
|
|
57939
|
-
];
|
|
57940
58606
|
AgentHooks = class {
|
|
57941
58607
|
constructor(push = new ApprovalPushService(), modules, deliveriesFile) {
|
|
57942
58608
|
this.push = push;
|
|
@@ -58309,7 +58975,7 @@ var init_agent_hooks = __esm({
|
|
|
58309
58975
|
try {
|
|
58310
58976
|
const file4 = path106.join(root, folder, name), info = await lstat28(file4);
|
|
58311
58977
|
if (!info.isFile() || info.size > 65536) continue;
|
|
58312
|
-
value2 = object2(JSON.parse(await
|
|
58978
|
+
value2 = object2(JSON.parse(await readFile44(file4, "utf8")));
|
|
58313
58979
|
} catch {
|
|
58314
58980
|
continue;
|
|
58315
58981
|
}
|
|
@@ -58499,9 +59165,11 @@ var init_agent_hooks = __esm({
|
|
|
58499
59165
|
this.dialogReads.set(key4, now);
|
|
58500
59166
|
while (this.dialogReads.size > 128) this.dialogReads.delete(this.dialogReads.keys().next().value);
|
|
58501
59167
|
const text5 = await this.paneLines(target);
|
|
59168
|
+
const tall = target.source === "claude" && /Chat about this/.test(text5) && !claudeQuestionDialog(text5) ? await this.paneLines(target, true, QUESTION_READ_LINES).catch(() => "") : "";
|
|
59169
|
+
const asking = target.source === "claude" && !!(claudeQuestionDialog(text5) || tall && claudeQuestionDialog(tall));
|
|
58502
59170
|
this.passwords.set(key4, passwordLine(text5));
|
|
58503
59171
|
while (this.passwords.size > 128) this.passwords.delete(this.passwords.keys().next().value);
|
|
58504
|
-
if (
|
|
59172
|
+
if (asking) {
|
|
58505
59173
|
if (entry2 && !question2) this.terminalPrompts.delete(key4);
|
|
58506
59174
|
return;
|
|
58507
59175
|
}
|
|
@@ -58609,7 +59277,8 @@ var init_agent_hooks = __esm({
|
|
|
58609
59277
|
async answerClaudeQuestions(target, questions, answers, options = {}) {
|
|
58610
59278
|
const key4 = JSON.stringify(target);
|
|
58611
59279
|
await answerClaudeQuestionDialog({
|
|
58612
|
-
|
|
59280
|
+
// A tall question (long text, many options) pushes its tab bar out of 40 lines.
|
|
59281
|
+
read: () => this.paneLines(target, true, QUESTION_READ_LINES),
|
|
58613
59282
|
keys: async (keys2) => {
|
|
58614
59283
|
if (!keys2.length) return;
|
|
58615
59284
|
await validateTarget(target, false, true);
|
|
@@ -58675,8 +59344,8 @@ var init_agent_hooks = __esm({
|
|
|
58675
59344
|
return readPaneText(target.server, target.pane, { scope: "agent", source: "visible", lines: 40, stripAnsi: false, format: "ansi", timeoutMs: 2e3 });
|
|
58676
59345
|
}
|
|
58677
59346
|
/** Read what the pane draws, stripping ANSI unless placeholder styling is needed. */
|
|
58678
|
-
paneLines(target, stripAnsi = true) {
|
|
58679
|
-
return readPaneText(target.server, target.pane, { scope: "agent", source: "visible", lines
|
|
59347
|
+
paneLines(target, stripAnsi = true, lines = 40) {
|
|
59348
|
+
return readPaneText(target.server, target.pane, { scope: "agent", source: "visible", lines, stripAnsi, timeoutMs: 2e3 });
|
|
58680
59349
|
}
|
|
58681
59350
|
/** After the phone walks Codex's /permissions menu onto Full Access, the
|
|
58682
59351
|
* agent draws a second "Enable full access?" confirmation. Watch the pane's
|
|
@@ -59375,7 +60044,7 @@ ${await conductorBrief()}` : context3 } : {}));
|
|
|
59375
60044
|
}
|
|
59376
60045
|
if (["SessionStart", "UserPromptSubmit", "Stop"].includes(String(body2.event))) this.stopCompacting(target);
|
|
59377
60046
|
if (body2.event === "UserPromptSubmit") {
|
|
59378
|
-
if (typeof body2.prompt === "string") this.deliveries.submitted(target, body2.prompt.slice(0, 65536));
|
|
60047
|
+
if (typeof body2.prompt === "string") await this.deliveries.submitted(target, body2.prompt.slice(0, 65536));
|
|
59379
60048
|
await this.recordTurn(target, pane, body2, dispatch2);
|
|
59380
60049
|
const context3 = this.modules?.has("conductor") === false ? void 0 : await conductorContext(target, s).catch(() => void 0);
|
|
59381
60050
|
res.end(JSON.stringify(context3 ? { hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: context3 } } : {}));
|
|
@@ -59579,7 +60248,7 @@ ${await conductorBrief()}` : context3 } : {}));
|
|
|
59579
60248
|
|
|
59580
60249
|
// src/bridge/models.ts
|
|
59581
60250
|
import { spawn as spawn11 } from "node:child_process";
|
|
59582
|
-
import { readdir as readdir16, readFile as
|
|
60251
|
+
import { readdir as readdir16, readFile as readFile45, stat as stat22 } from "node:fs/promises";
|
|
59583
60252
|
import { homedir as homedir17 } from "node:os";
|
|
59584
60253
|
import path107 from "node:path";
|
|
59585
60254
|
function readCodexModels(executable2 = codexExecutable()) {
|
|
@@ -59667,7 +60336,7 @@ async function readClaudeCatalog(configDir2 = claudeConfigDir(), installed) {
|
|
|
59667
60336
|
if (!newest2) return [];
|
|
59668
60337
|
let parsed;
|
|
59669
60338
|
try {
|
|
59670
|
-
parsed = JSON.parse(await
|
|
60339
|
+
parsed = JSON.parse(await readFile45(newest2.file, "utf8"));
|
|
59671
60340
|
} catch {
|
|
59672
60341
|
return [];
|
|
59673
60342
|
}
|
|
@@ -59766,7 +60435,7 @@ async function readOpenCodeModels(executable2 = "opencode", configDir2 = path107
|
|
|
59766
60435
|
let configured;
|
|
59767
60436
|
for (const file4 of ["opencode.json", "opencode.jsonc"]) {
|
|
59768
60437
|
try {
|
|
59769
|
-
const text5 = await
|
|
60438
|
+
const text5 = await readFile45(path107.join(configDir2, file4), "utf8");
|
|
59770
60439
|
const model = /"model"\s*:\s*"([^"]+)"/.exec(text5)?.[1];
|
|
59771
60440
|
if (model) {
|
|
59772
60441
|
configured = model.slice(0, 200);
|
|
@@ -60470,6 +61139,7 @@ function descendsFrom(pid, roots, parents) {
|
|
|
60470
61139
|
function attributeServers(input2) {
|
|
60471
61140
|
const result = [];
|
|
60472
61141
|
for (const server of input2.servers) {
|
|
61142
|
+
if (server.unverified) continue;
|
|
60473
61143
|
if (descendsFrom(server.pid, input2.ownRoots, input2.parents)) result.push({ ...server, source: "started" });
|
|
60474
61144
|
else if (input2.mentioned.has(server.port) && !descendsFrom(server.pid, input2.otherRoots, input2.parents)) {
|
|
60475
61145
|
result.push({ ...server, source: "mentioned" });
|
|
@@ -60556,7 +61226,7 @@ var init_session_servers = __esm({
|
|
|
60556
61226
|
});
|
|
60557
61227
|
|
|
60558
61228
|
// src/bridge/uploads.ts
|
|
60559
|
-
import { mkdir as mkdir27, readdir as readdir17, lstat as lstat29, realpath as realpath15, readFile as
|
|
61229
|
+
import { mkdir as mkdir27, readdir as readdir17, lstat as lstat29, realpath as realpath15, readFile as readFile46, stat as stat24, unlink as unlink8, writeFile as writeFile8 } from "node:fs/promises";
|
|
60560
61230
|
import path108 from "node:path";
|
|
60561
61231
|
import { randomUUID as randomUUID26 } from "node:crypto";
|
|
60562
61232
|
function imageBytes(bytes) {
|
|
@@ -60586,7 +61256,7 @@ async function saveUpload(session, name, bytes) {
|
|
|
60586
61256
|
const folder = path108.join(root, session);
|
|
60587
61257
|
await mkdir27(folder, { recursive: true, mode: 448 });
|
|
60588
61258
|
saved = path108.join(folder, `${randomUUID26()}-${name}`);
|
|
60589
|
-
await
|
|
61259
|
+
await writeFile8(saved, bytes, { flag: "wx", mode: 384 });
|
|
60590
61260
|
});
|
|
60591
61261
|
uploadQueue = task2;
|
|
60592
61262
|
await task2;
|
|
@@ -60621,7 +61291,7 @@ async function uploadImage(requested) {
|
|
|
60621
61291
|
const metadata = await stat24(file4);
|
|
60622
61292
|
if (!metadata.isFile()) throw missing;
|
|
60623
61293
|
if (metadata.size > 8388608) throw new BridgeError(413, "This image is too large.");
|
|
60624
|
-
const bytes = await
|
|
61294
|
+
const bytes = await readFile46(file4);
|
|
60625
61295
|
if (bytes.length > 8388608) throw new BridgeError(413, "This image is too large.");
|
|
60626
61296
|
if (!imageBytes(bytes)) throw missing;
|
|
60627
61297
|
return bytes;
|
|
@@ -60760,7 +61430,7 @@ var init_file_range = __esm({
|
|
|
60760
61430
|
// src/bridge/file-write.ts
|
|
60761
61431
|
import { randomBytes as randomBytes8 } from "node:crypto";
|
|
60762
61432
|
import { constants as constants4 } from "node:fs";
|
|
60763
|
-
import { lstat as lstat31, open as open23, realpath as realpath17, rename as
|
|
61433
|
+
import { lstat as lstat31, open as open23, realpath as realpath17, rename as rename7, rm as rm12 } from "node:fs/promises";
|
|
60764
61434
|
import path110 from "node:path";
|
|
60765
61435
|
async function serialized3(key4, work) {
|
|
60766
61436
|
const previous = fileLocks.get(key4) ?? Promise.resolve();
|
|
@@ -60773,7 +61443,8 @@ async function serialized3(key4, work) {
|
|
|
60773
61443
|
}
|
|
60774
61444
|
}
|
|
60775
61445
|
async function writeRepoFile(root, requested, content, expectedVersion) {
|
|
60776
|
-
const
|
|
61446
|
+
const name = typeof requested === "string" ? path110.posix.normalize(requested) : requested;
|
|
61447
|
+
const key4 = `${await realpath17(root).catch(() => root)}\0${name}`;
|
|
60777
61448
|
return serialized3(key4, () => writeRepoFileNow(root, requested, content, expectedVersion));
|
|
60778
61449
|
}
|
|
60779
61450
|
async function writeRepoFileNow(root, requested, content, expectedVersion) {
|
|
@@ -60833,9 +61504,9 @@ async function writeRepoFileNow(root, requested, content, expectedVersion) {
|
|
|
60833
61504
|
if (!current2 || current2.isSymbolicLink() || fileVersion(current2) !== expectedVersion) {
|
|
60834
61505
|
throw new BridgeError(409, "The file changed since you opened it.", { code: "file-changed" });
|
|
60835
61506
|
}
|
|
60836
|
-
await
|
|
61507
|
+
await rename7(temporary, file4);
|
|
60837
61508
|
} finally {
|
|
60838
|
-
await
|
|
61509
|
+
await rm12(temporary, { force: true });
|
|
60839
61510
|
}
|
|
60840
61511
|
const saved = await lstat31(file4);
|
|
60841
61512
|
return { path: requested, version: fileVersion(saved), size: saved.size, created: false };
|
|
@@ -61997,8 +62668,8 @@ async function launch(options, reservation = createJob(options)) {
|
|
|
61997
62668
|
for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) process.off(signal, cancel);
|
|
61998
62669
|
fs44.closeSync(out);
|
|
61999
62670
|
fs44.closeSync(err);
|
|
62000
|
-
const blockedFile = path114.join(job, "blocked.json"),
|
|
62001
|
-
if (
|
|
62671
|
+
const blockedFile = path114.join(job, "blocked.json"), refusal2 = refused2 ?? stderrRefusal(stderr);
|
|
62672
|
+
if (refusal2 && !fs44.existsSync(blockedFile)) atomicWriteText(blockedFile, JSON.stringify({ ...refusal2, at: (/* @__PURE__ */ new Date()).toISOString() }));
|
|
62002
62673
|
const blocked = fs44.existsSync(blockedFile);
|
|
62003
62674
|
if (blocked) console.error(`blocked: ${fs44.readFileSync(blockedFile, "utf8").slice(0, 4e3)}`);
|
|
62004
62675
|
fs44.writeFileSync(path114.join(job, "exit.txt"), `${exitCode}
|
|
@@ -62029,7 +62700,7 @@ var init_launcher = __esm({
|
|
|
62029
62700
|
|
|
62030
62701
|
// src/bridge/fanout-messages.ts
|
|
62031
62702
|
import { randomUUID as randomUUID27 } from "node:crypto";
|
|
62032
|
-
import { appendFile as appendFile2, lstat as lstat32, mkdir as mkdir28, readdir as readdir18, readFile as
|
|
62703
|
+
import { appendFile as appendFile2, lstat as lstat32, mkdir as mkdir28, readdir as readdir18, readFile as readFile47, realpath as realpath18, rename as rename8, rm as rm13, writeFile as writeFile9 } from "node:fs/promises";
|
|
62033
62704
|
import path115 from "node:path";
|
|
62034
62705
|
var fanoutMessageSchema, receiptSchema2, FanoutMessages;
|
|
62035
62706
|
var init_fanout_messages = __esm({
|
|
@@ -62083,7 +62754,7 @@ var init_fanout_messages = __esm({
|
|
|
62083
62754
|
if (!(await lstat32(directory)).isDirectory() || await realpath18(directory) !== directory) continue;
|
|
62084
62755
|
const file4 = path115.join(directory, "manifest.json"), info = await lstat32(file4);
|
|
62085
62756
|
if (!info.isFile() || info.isSymbolicLink() || info.size > 65536) continue;
|
|
62086
|
-
const manifest = manifestSchema.parse(JSON.parse(await
|
|
62757
|
+
const manifest = manifestSchema.parse(JSON.parse(await readFile47(file4, "utf8")));
|
|
62087
62758
|
if (manifest.id === name) jobs.push({ directory, manifest });
|
|
62088
62759
|
} catch {
|
|
62089
62760
|
}
|
|
@@ -62147,7 +62818,7 @@ var init_fanout_messages = __esm({
|
|
|
62147
62818
|
const file4 = path115.join(directory, name), info2 = await lstat32(file4);
|
|
62148
62819
|
if (!info2.isFile() || info2.isSymbolicLink() || info2.size > 262144) continue;
|
|
62149
62820
|
try {
|
|
62150
|
-
rows2.push({ file: file4, message: receiptSchema2.parse(JSON.parse(await
|
|
62821
|
+
rows2.push({ file: file4, message: receiptSchema2.parse(JSON.parse(await readFile47(file4, "utf8"))) });
|
|
62151
62822
|
} catch {
|
|
62152
62823
|
}
|
|
62153
62824
|
}
|
|
@@ -62193,17 +62864,17 @@ var init_fanout_messages = __esm({
|
|
|
62193
62864
|
if (await realpath18(round) !== round) throw new BridgeError(400, "Invalid worker round directory.");
|
|
62194
62865
|
const roundDir = path115.join(round, next.message.id);
|
|
62195
62866
|
await mkdir28(roundDir, { mode: 448 });
|
|
62196
|
-
await
|
|
62867
|
+
await writeFile9(path115.join(roundDir, "prompt.txt"), next.message.text, { mode: 384 });
|
|
62197
62868
|
for (const name of ["stderr.log", "final.txt", "exit.txt", "blocked.json", "prompt.txt"]) {
|
|
62198
|
-
await
|
|
62869
|
+
await rename8(path115.join(fresh.directory, name), path115.join(roundDir, `previous-${name}`)).catch((error62) => {
|
|
62199
62870
|
if (error62.code !== "ENOENT") throw error62;
|
|
62200
62871
|
});
|
|
62201
62872
|
}
|
|
62202
|
-
await
|
|
62873
|
+
await writeFile9(path115.join(fresh.directory, "prompt.txt"), next.message.text, { mode: 384 });
|
|
62203
62874
|
const sentFile = next.file.replace(/\.queued\.json$/, ".sent.json");
|
|
62204
62875
|
const message = { ...next.message, status: "running" };
|
|
62205
62876
|
await atomic(next.file, JSON.stringify(message));
|
|
62206
|
-
await
|
|
62877
|
+
await rename8(next.file, sentFile);
|
|
62207
62878
|
pending = { file: sentFile, message };
|
|
62208
62879
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
62209
62880
|
const manifest = {
|
|
@@ -62243,20 +62914,20 @@ var init_fanout_messages = __esm({
|
|
|
62243
62914
|
await atomic(sentFile, JSON.stringify({ ...message, status: "failed" }));
|
|
62244
62915
|
await atomic(path115.join(fresh.directory, "manifest.json"), JSON.stringify({ ...manifest, status: "failed", finishedAt: (/* @__PURE__ */ new Date()).toISOString() }));
|
|
62245
62916
|
}).finally(async () => {
|
|
62246
|
-
await
|
|
62917
|
+
await rm13(lock, { recursive: true, force: true });
|
|
62247
62918
|
}).catch(() => {
|
|
62248
62919
|
});
|
|
62249
62920
|
} catch (error62) {
|
|
62250
62921
|
if (!pending) throw error62;
|
|
62251
62922
|
await atomic(pending.file, JSON.stringify({ ...pending.message, status: "failed" }));
|
|
62252
|
-
if (pending.file.endsWith(".queued.json")) await
|
|
62923
|
+
if (pending.file.endsWith(".queued.json")) await rename8(pending.file, pending.file.replace(/\.queued\.json$/, ".sent.json"));
|
|
62253
62924
|
if (started) await atomic(path115.join(job.directory, "manifest.json"), JSON.stringify({
|
|
62254
62925
|
...started,
|
|
62255
62926
|
status: "failed",
|
|
62256
62927
|
finishedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
62257
62928
|
}));
|
|
62258
62929
|
} finally {
|
|
62259
|
-
if (!launched) await
|
|
62930
|
+
if (!launched) await rm13(lock, { recursive: true, force: true });
|
|
62260
62931
|
}
|
|
62261
62932
|
}
|
|
62262
62933
|
};
|
|
@@ -63044,7 +63715,7 @@ var init_speech_transcribe = __esm({
|
|
|
63044
63715
|
});
|
|
63045
63716
|
|
|
63046
63717
|
// src/bridge/activity.ts
|
|
63047
|
-
import { appendFile as appendFile3, mkdir as mkdir29, readFile as
|
|
63718
|
+
import { appendFile as appendFile3, mkdir as mkdir29, readFile as readFile48, rename as rename9, stat as stat25 } from "node:fs/promises";
|
|
63048
63719
|
import path116 from "node:path";
|
|
63049
63720
|
var ActivityJournal;
|
|
63050
63721
|
var init_activity2 = __esm({
|
|
@@ -63079,14 +63750,14 @@ var init_activity2 = __esm({
|
|
|
63079
63750
|
if (!changes.length) return;
|
|
63080
63751
|
const root = bridgeRoot(), file4 = path116.join(root, "activity.jsonl");
|
|
63081
63752
|
await mkdir29(root, { recursive: true, mode: 448 });
|
|
63082
|
-
if ((await stat25(file4).catch(() => null))?.size && (await stat25(file4)).size > 2097152) await
|
|
63753
|
+
if ((await stat25(file4).catch(() => null))?.size && (await stat25(file4)).size > 2097152) await rename9(file4, file4 + ".previous");
|
|
63083
63754
|
await appendFile3(file4, changes.map((row) => JSON.stringify(row)).join("\n") + "\n", { mode: 384 });
|
|
63084
63755
|
if (this.previous.size > 4096) this.previous.clear();
|
|
63085
63756
|
});
|
|
63086
63757
|
return this.pending;
|
|
63087
63758
|
}
|
|
63088
63759
|
async recent() {
|
|
63089
|
-
const text5 = await
|
|
63760
|
+
const text5 = await readFile48(path116.join(bridgeRoot(), "activity.jsonl"), "utf8").catch(() => "");
|
|
63090
63761
|
return text5.trim().split("\n").slice(-500).flatMap((line) => {
|
|
63091
63762
|
try {
|
|
63092
63763
|
return [JSON.parse(line)];
|
|
@@ -63220,7 +63891,7 @@ var init_code_package = __esm({
|
|
|
63220
63891
|
});
|
|
63221
63892
|
|
|
63222
63893
|
// src/bridge/code-routes.ts
|
|
63223
|
-
import { rm as
|
|
63894
|
+
import { rm as rm14 } from "node:fs/promises";
|
|
63224
63895
|
import * as fs46 from "node:fs";
|
|
63225
63896
|
import * as path118 from "node:path";
|
|
63226
63897
|
async function requireCodePackage(store) {
|
|
@@ -63245,7 +63916,7 @@ async function resolveCodeStore(base, value2, write = false) {
|
|
|
63245
63916
|
function noIndex(project) {
|
|
63246
63917
|
return new BridgeError(404, `No code index for "${project}" on this computer. Build one with: phren code index ${project}`);
|
|
63247
63918
|
}
|
|
63248
|
-
function
|
|
63919
|
+
function readHead2(root) {
|
|
63249
63920
|
try {
|
|
63250
63921
|
const dotGit = path118.join(root, ".git");
|
|
63251
63922
|
const gitDirectory2 = fs46.statSync(dotGit).isDirectory() ? dotGit : (() => {
|
|
@@ -63483,7 +64154,7 @@ var init_code_routes = __esm({
|
|
|
63483
64154
|
const project = projectSchema.parse(projectValue ?? "");
|
|
63484
64155
|
const { codeDatabasePath } = await requireCodePackage(this.store);
|
|
63485
64156
|
const file4 = codeDatabasePath(this.store, project);
|
|
63486
|
-
await Promise.all([file4, `${file4}-journal`, `${file4}-wal`, `${file4}-shm`].map((path145) =>
|
|
64157
|
+
await Promise.all([file4, `${file4}-journal`, `${file4}-wal`, `${file4}-shm`].map((path145) => rm14(path145, { force: true })));
|
|
63487
64158
|
return { project, disabled: true };
|
|
63488
64159
|
}
|
|
63489
64160
|
async reindex(projectValue) {
|
|
@@ -63575,7 +64246,7 @@ var init_code_routes = __esm({
|
|
|
63575
64246
|
for (const root of new Set(files.map((file4) => file4.root))) {
|
|
63576
64247
|
const project = projects.find((entry2) => entry2.root === root);
|
|
63577
64248
|
if (!project) continue;
|
|
63578
|
-
const head =
|
|
64249
|
+
const head = readHead2(root);
|
|
63579
64250
|
const previous = this.heads.get(root);
|
|
63580
64251
|
if (head !== void 0) this.heads.set(root, head);
|
|
63581
64252
|
this.schedule(project.project, previous !== void 0 && head !== void 0 && previous !== head);
|
|
@@ -63771,8 +64442,8 @@ var init_context2 = __esm({
|
|
|
63771
64442
|
|
|
63772
64443
|
// src/bridge/questions.ts
|
|
63773
64444
|
import { execFile as execFile26 } from "node:child_process";
|
|
63774
|
-
import { createHash as
|
|
63775
|
-
import { mkdir as mkdir30, open as open25, stat as stat26, readFile as
|
|
64445
|
+
import { createHash as createHash30 } from "node:crypto";
|
|
64446
|
+
import { mkdir as mkdir30, open as open25, stat as stat26, readFile as readFile49, writeFile as writeFile10 } from "node:fs/promises";
|
|
63776
64447
|
import path119 from "node:path";
|
|
63777
64448
|
import { promisify as promisify24 } from "node:util";
|
|
63778
64449
|
function asyncQuestion(raw, id2) {
|
|
@@ -64014,8 +64685,8 @@ ${attachedFiles(paths)}` : answer;
|
|
|
64014
64685
|
this.snapshots.set(target.session, { at: Date.now(), stamp: stamp2, pending });
|
|
64015
64686
|
}
|
|
64016
64687
|
return Promise.all((pending ?? []).map(async (p) => {
|
|
64017
|
-
const key4 =
|
|
64018
|
-
const submitted = await
|
|
64688
|
+
const key4 = createHash30("sha256").update(JSON.stringify([target.source, target.session, p.id])).digest("hex");
|
|
64689
|
+
const submitted = await readFile49(path119.join(bridgeRoot(), "question-replies", key4), "utf8").then((value2) => value2 === "submitted").catch(() => false);
|
|
64019
64690
|
return { toolUseId: p.id, isAsync: true, submitted, questions: asPrompt(p.questions) };
|
|
64020
64691
|
})).then((prompts) => prompts.filter((p) => !p.submitted));
|
|
64021
64692
|
}
|
|
@@ -64050,7 +64721,7 @@ ${attachedFiles(paths)}` : answer;
|
|
|
64050
64721
|
if (await paneIdentity(target.server, pane, true) !== target.session) throw new BridgeError(409, "This pane's conversation changed. Reopen the chat.");
|
|
64051
64722
|
const directory = path119.join(bridgeRoot(), "question-replies");
|
|
64052
64723
|
await mkdir30(directory, { recursive: true, mode: 448 });
|
|
64053
|
-
const key4 =
|
|
64724
|
+
const key4 = createHash30("sha256").update(JSON.stringify([target.source, target.session, id2])).digest("hex");
|
|
64054
64725
|
const receiptPath = path119.join(directory, key4);
|
|
64055
64726
|
const receipt = await open25(receiptPath, "wx", 384).catch((error62) => {
|
|
64056
64727
|
if (error62.code === "EEXIST") throw new BridgeError(409, "An answer was already submitted. Check the conversation before answering again.");
|
|
@@ -64060,7 +64731,7 @@ ${attachedFiles(paths)}` : answer;
|
|
|
64060
64731
|
try {
|
|
64061
64732
|
if (entry2) await this.served.steer(entry2, reply, extra);
|
|
64062
64733
|
else await exec21(this.executable, ["queue", "--thread", target.session, "--message", reply], { timeout: 8e3, maxBuffer: 65536 });
|
|
64063
|
-
await
|
|
64734
|
+
await writeFile10(receiptPath, "submitted", { mode: 384 });
|
|
64064
64735
|
} catch {
|
|
64065
64736
|
throw new BridgeError(409, "Codex did not confirm the answer. Check the conversation; Phren has not retried it.");
|
|
64066
64737
|
}
|
|
@@ -64287,7 +64958,7 @@ var init_settings_switch = __esm({
|
|
|
64287
64958
|
if (pane.agent_status === "working") throw new BridgeError(409, "The agent started working during the settings change. The result is unconfirmed; check the terminal.");
|
|
64288
64959
|
};
|
|
64289
64960
|
const screenMode = async () => claudeFooterMode(await this.hooks.paneLines(target));
|
|
64290
|
-
const
|
|
64961
|
+
const changed = async (from, wait) => {
|
|
64291
64962
|
const deadline = Date.now() + wait;
|
|
64292
64963
|
do {
|
|
64293
64964
|
await new Promise((resolve17) => setTimeout(resolve17, 150));
|
|
@@ -64339,7 +65010,7 @@ var init_settings_switch = __esm({
|
|
|
64339
65010
|
if (change.plan === true) {
|
|
64340
65011
|
if (started !== "plan") {
|
|
64341
65012
|
await slash("/plan");
|
|
64342
|
-
mode = await
|
|
65013
|
+
mode = await changed(started, this.wait);
|
|
64343
65014
|
if (mode !== "plan") throw new BridgeError(409, "Claude did not enter plan mode. Open terminal to check.");
|
|
64344
65015
|
}
|
|
64345
65016
|
} else if (change.permissionMode || change.plan === false) {
|
|
@@ -64349,7 +65020,7 @@ var init_settings_switch = __esm({
|
|
|
64349
65020
|
if (presses >= MAX_PRESSES || presses > 0 && mode === started) throw new BridgeError(422, "Claude doesn't offer that mode in this session.");
|
|
64350
65021
|
await validate2();
|
|
64351
65022
|
await terminalProvider().sendKeys(target.server, target.pane, ["shift+tab"]);
|
|
64352
|
-
mode = await
|
|
65023
|
+
mode = await changed(mode, this.wait);
|
|
64353
65024
|
}
|
|
64354
65025
|
}
|
|
64355
65026
|
const phone = mode ? CLAUDE_MODES[mode] : void 0;
|
|
@@ -64365,7 +65036,7 @@ var init_settings_switch = __esm({
|
|
|
64365
65036
|
});
|
|
64366
65037
|
|
|
64367
65038
|
// src/bridge/job-registry.ts
|
|
64368
|
-
import { readFileSync as
|
|
65039
|
+
import { readFileSync as readFileSync49 } from "node:fs";
|
|
64369
65040
|
import path120 from "node:path";
|
|
64370
65041
|
function jobKey(job) {
|
|
64371
65042
|
if (job.pane) return `pane:${paneKey3(job.pane)}`;
|
|
@@ -64506,7 +65177,7 @@ var init_job_registry = __esm({
|
|
|
64506
65177
|
now;
|
|
64507
65178
|
async list() {
|
|
64508
65179
|
try {
|
|
64509
|
-
const parsed = stateSchema2.safeParse(JSON.parse(
|
|
65180
|
+
const parsed = stateSchema2.safeParse(JSON.parse(readFileSync49(this.file, "utf8")));
|
|
64510
65181
|
return parsed.success ? parsed.data.jobs : [];
|
|
64511
65182
|
} catch {
|
|
64512
65183
|
return [];
|
|
@@ -64565,7 +65236,7 @@ var init_job_registry = __esm({
|
|
|
64565
65236
|
|
|
64566
65237
|
// src/bridge/resources.ts
|
|
64567
65238
|
import { execFile as execFile27 } from "node:child_process";
|
|
64568
|
-
import { readdir as readdir19, readFile as
|
|
65239
|
+
import { readdir as readdir19, readFile as readFile50, statfs } from "node:fs/promises";
|
|
64569
65240
|
import { cpus, loadavg, totalmem, uptime } from "node:os";
|
|
64570
65241
|
import path121 from "node:path";
|
|
64571
65242
|
import { promisify as promisify25 } from "node:util";
|
|
@@ -64600,12 +65271,12 @@ function computerHardware(platform = process.platform) {
|
|
|
64600
65271
|
return { ...found, ...base };
|
|
64601
65272
|
}
|
|
64602
65273
|
if (platform === "linux") {
|
|
64603
|
-
const dmi = (name) =>
|
|
65274
|
+
const dmi = (name) => readFile50(`/sys/devices/virtual/dmi/id/${name}`, "utf8").catch(() => void 0);
|
|
64604
65275
|
const [vendor, product, version2, cpuinfo] = await Promise.all([
|
|
64605
65276
|
dmi("sys_vendor"),
|
|
64606
65277
|
dmi("product_name"),
|
|
64607
65278
|
dmi("product_version"),
|
|
64608
|
-
|
|
65279
|
+
readFile50("/proc/cpuinfo", "utf8").catch(() => "")
|
|
64609
65280
|
]);
|
|
64610
65281
|
const model = linuxModel(vendor, product, version2), chip = linuxChip(cpuinfo);
|
|
64611
65282
|
return { ...model ? { model } : {}, ...chip ? { chip } : {}, ...base };
|
|
@@ -64824,7 +65495,7 @@ async function linuxBattery() {
|
|
|
64824
65495
|
const names = await readdir19(root).catch(() => []);
|
|
64825
65496
|
const battery = names.find((name) => /^BAT/.test(name));
|
|
64826
65497
|
if (!battery) return void 0;
|
|
64827
|
-
const read = (name, field) =>
|
|
65498
|
+
const read = (name, field) => readFile50(path121.join(root, name, field), "utf8").then((text5) => text5.trim()).catch(() => "");
|
|
64828
65499
|
const [capacity2, status] = await Promise.all([read(battery, "capacity"), read(battery, "status")]);
|
|
64829
65500
|
const online = await Promise.all(names.filter((name) => !/^BAT/.test(name)).map((name) => read(name, "online")));
|
|
64830
65501
|
const percent = Number(capacity2);
|
|
@@ -64894,7 +65565,7 @@ async function collectResources(deps2) {
|
|
|
64894
65565
|
const platform = deps2.platform;
|
|
64895
65566
|
const registry2 = deps2.jobs ?? new JobRegistry();
|
|
64896
65567
|
const [memory, disk, battery, rows2, registered, hardware] = await Promise.all([
|
|
64897
|
-
platform === "darwin" ? darwinMemory() : platform === "linux" ?
|
|
65568
|
+
platform === "darwin" ? darwinMemory() : platform === "linux" ? readFile50("/proc/meminfo", "utf8").then(parseMeminfo).catch(() => ({ totalBytes: totalmem() })) : Promise.resolve({ totalBytes: totalmem() }),
|
|
64898
65569
|
statfs(deps2.home()).then((info) => ({ path: "~", totalBytes: info.blocks * info.bsize, freeBytes: info.bavail * info.bsize })).catch(() => void 0),
|
|
64899
65570
|
platform === "darwin" ? run3("/usr/bin/pmset", ["-g", "batt"]).then(parsePmset).catch(() => void 0) : platform === "linux" ? linuxBattery() : Promise.resolve(void 0),
|
|
64900
65571
|
deps2.processes().catch(() => []),
|
|
@@ -64975,7 +65646,7 @@ var init_resources = __esm({
|
|
|
64975
65646
|
});
|
|
64976
65647
|
|
|
64977
65648
|
// src/bridge/canary.ts
|
|
64978
|
-
import { lstat as lstat33, mkdtemp as mkdtemp6, realpath as realpath19, rm as
|
|
65649
|
+
import { lstat as lstat33, mkdtemp as mkdtemp6, realpath as realpath19, rm as rm15 } from "node:fs/promises";
|
|
64979
65650
|
import { hostname as hostname11, tmpdir as tmpdir5 } from "node:os";
|
|
64980
65651
|
import path122 from "node:path";
|
|
64981
65652
|
function reason(error62) {
|
|
@@ -65022,7 +65693,7 @@ async function conductorStep(options, server) {
|
|
|
65022
65693
|
failure2 = reason(error62);
|
|
65023
65694
|
} finally {
|
|
65024
65695
|
const cleanup = await closeCanaryWorkspaces(server, before, created);
|
|
65025
|
-
await
|
|
65696
|
+
await rm15(folder, { recursive: true, force: true }).catch(() => {
|
|
65026
65697
|
});
|
|
65027
65698
|
if (cleanup) failure2 = failure2 ? `${failure2}; ${cleanup}` : cleanup;
|
|
65028
65699
|
}
|
|
@@ -65134,7 +65805,7 @@ var init_canary = __esm({
|
|
|
65134
65805
|
|
|
65135
65806
|
// src/bridge/launch-worktree.ts
|
|
65136
65807
|
import { execFile as execFile28 } from "node:child_process";
|
|
65137
|
-
import { mkdir as mkdir31, realpath as realpath20, rm as
|
|
65808
|
+
import { mkdir as mkdir31, realpath as realpath20, rm as rm16, stat as stat28 } from "node:fs/promises";
|
|
65138
65809
|
import path123 from "node:path";
|
|
65139
65810
|
import { promisify as promisify26 } from "node:util";
|
|
65140
65811
|
async function git7(cwd, ...args) {
|
|
@@ -65180,7 +65851,7 @@ async function createLaunchWorktree(cwd, request9) {
|
|
|
65180
65851
|
path: abs,
|
|
65181
65852
|
branch,
|
|
65182
65853
|
async discard() {
|
|
65183
|
-
await git7(root, "worktree", "remove", "--force", abs).catch(() =>
|
|
65854
|
+
await git7(root, "worktree", "remove", "--force", abs).catch(() => rm16(abs, { recursive: true, force: true }));
|
|
65184
65855
|
await git7(root, "worktree", "prune").catch(() => void 0);
|
|
65185
65856
|
await git7(root, "branch", "-D", branch).catch(() => void 0);
|
|
65186
65857
|
}
|
|
@@ -65202,7 +65873,7 @@ var init_launch_worktree = __esm({
|
|
|
65202
65873
|
});
|
|
65203
65874
|
|
|
65204
65875
|
// src/bridge/server-launch.ts
|
|
65205
|
-
import { mkdir as mkdir32, mkdtemp as mkdtemp7, readFile as
|
|
65876
|
+
import { mkdir as mkdir32, mkdtemp as mkdtemp7, readFile as readFile51, realpath as realpath21, rmdir as rmdir2 } from "node:fs/promises";
|
|
65206
65877
|
import path124 from "node:path";
|
|
65207
65878
|
function effortArgs(kind, effort) {
|
|
65208
65879
|
if (kind === "claude") return ["--effort", effort];
|
|
@@ -65222,7 +65893,7 @@ async function phrenLaunchArgs(kind, data, store = phrenStoreRoot()) {
|
|
|
65222
65893
|
return [...mode === "chat" ? ["--mode", "chat"] : [], ...resume ? ["--session", resume] : []];
|
|
65223
65894
|
}
|
|
65224
65895
|
async function sessionUsedTools(session, store = phrenStoreRoot()) {
|
|
65225
|
-
const raw = await
|
|
65896
|
+
const raw = await readFile51(path124.join(store, ".sessions", `session-${session}.events.jsonl`), "utf8").catch(() => "");
|
|
65226
65897
|
const withTools = (message) => {
|
|
65227
65898
|
const content = message?.content;
|
|
65228
65899
|
return Array.isArray(content) && content.some((block) => ["tool_use", "tool_result"].includes(String(block?.type)));
|
|
@@ -65264,7 +65935,7 @@ mode: primary
|
|
|
65264
65935
|
${brief}
|
|
65265
65936
|
`;
|
|
65266
65937
|
await mkdir32(directory, { recursive: true, mode: 448 });
|
|
65267
|
-
if (await
|
|
65938
|
+
if (await readFile51(file4, "utf8").catch(() => void 0) !== definition) await atomic(file4, definition, 420);
|
|
65268
65939
|
return [...model ? ["--model", model] : [], "--agent", "conductor", "--variant", effort];
|
|
65269
65940
|
}
|
|
65270
65941
|
if (kind === "phren") return [...PHREN_AGENT_ARGS, ...model ? phrenModelArgs(model) : [], "--append-system-prompt-file", briefFile, ...effortArgs(kind, effort)];
|
|
@@ -65492,7 +66163,9 @@ async function startSession(server, data, options) {
|
|
|
65492
66163
|
startThread: !!brief,
|
|
65493
66164
|
...permissionMode ? { remoteArgs: codexModeFlags(permissionMode) } : {}
|
|
65494
66165
|
}).catch((error62) => {
|
|
65495
|
-
|
|
66166
|
+
const note = `Codex app-server unavailable, typing instead: ${error62 instanceof Error ? error62.message : String(error62)}`;
|
|
66167
|
+
if (error62 instanceof AppServerUnsupportedError) logger.debug("launch", note);
|
|
66168
|
+
else logger.warn("launch", note);
|
|
65496
66169
|
return void 0;
|
|
65497
66170
|
}) : void 0;
|
|
65498
66171
|
const appServer = structuredLaunch?.entry;
|
|
@@ -66771,8 +67444,8 @@ var init_session_git = __esm({
|
|
|
66771
67444
|
// src/bridge/enroll.ts
|
|
66772
67445
|
import { execFile as execFile29 } from "node:child_process";
|
|
66773
67446
|
import { promisify as promisify27 } from "node:util";
|
|
66774
|
-
import { realpathSync as
|
|
66775
|
-
import { readdir as readdir20, readFile as
|
|
67447
|
+
import { realpathSync as realpathSync6 } from "node:fs";
|
|
67448
|
+
import { readdir as readdir20, readFile as readFile52, stat as stat30, mkdir as mkdir33 } from "node:fs/promises";
|
|
66776
67449
|
import { homedir as homedir19 } from "node:os";
|
|
66777
67450
|
import path130 from "node:path";
|
|
66778
67451
|
function repoName(url2) {
|
|
@@ -66801,7 +67474,7 @@ async function registeredSources(env) {
|
|
|
66801
67474
|
const source = readProjectConfig(store, project).sourcePath;
|
|
66802
67475
|
if (typeof source === "string" && source) {
|
|
66803
67476
|
try {
|
|
66804
|
-
paths.add(
|
|
67477
|
+
paths.add(realpathSync6.native(path130.resolve(source)));
|
|
66805
67478
|
} catch {
|
|
66806
67479
|
}
|
|
66807
67480
|
}
|
|
@@ -66816,7 +67489,7 @@ async function candidateRepos(activity, env = process.env) {
|
|
|
66816
67489
|
let dir = path130.resolve(directory);
|
|
66817
67490
|
try {
|
|
66818
67491
|
if (!(await stat30(dir)).isDirectory()) return;
|
|
66819
|
-
dir =
|
|
67492
|
+
dir = realpathSync6.native(dir);
|
|
66820
67493
|
} catch {
|
|
66821
67494
|
return;
|
|
66822
67495
|
}
|
|
@@ -66860,7 +67533,7 @@ async function candidateRepos(activity, env = process.env) {
|
|
|
66860
67533
|
if (root) await offer(root, "activity", typeof event.at === "string" ? event.at : void 0);
|
|
66861
67534
|
}
|
|
66862
67535
|
try {
|
|
66863
|
-
const session = JSON.parse(await
|
|
67536
|
+
const session = JSON.parse(await readFile52(path130.join(herdrRoot(), "session.json"), "utf8"));
|
|
66864
67537
|
for (const match of JSON.stringify(session).matchAll(/"cwd":\s*"((?:\\.|[^"\\])*)"/g)) {
|
|
66865
67538
|
const directory = JSON.parse(`"${match[1]}"`);
|
|
66866
67539
|
if (!path130.isAbsolute(directory)) continue;
|
|
@@ -66945,7 +67618,7 @@ async function enrollProject(input2, env = process.env) {
|
|
|
66945
67618
|
const raw = input2.directory;
|
|
66946
67619
|
if (raw.length > 4096 || raw.includes("\0") || !path130.isAbsolute(raw)) throw new BridgeError(400, "Enter the full folder path on this computer.");
|
|
66947
67620
|
try {
|
|
66948
|
-
directory =
|
|
67621
|
+
directory = realpathSync6.native(raw);
|
|
66949
67622
|
if (!(await stat30(directory)).isDirectory()) throw new Error();
|
|
66950
67623
|
} catch {
|
|
66951
67624
|
throw new BridgeError(404, "That folder is not on this computer.");
|
|
@@ -72160,10 +72833,10 @@ var init_project_git = __esm({
|
|
|
72160
72833
|
|
|
72161
72834
|
// src/bridge/simulators.ts
|
|
72162
72835
|
import { execFile as execFile30 } from "node:child_process";
|
|
72163
|
-
import { chmod as chmod5, mkdir as mkdir34, readFile as
|
|
72836
|
+
import { chmod as chmod5, mkdir as mkdir34, readFile as readFile53, rename as rename10, stat as stat31, unlink as unlink9, writeFile as writeFile11 } from "node:fs/promises";
|
|
72164
72837
|
import { tmpdir as tmpdir6 } from "node:os";
|
|
72165
72838
|
import path137 from "node:path";
|
|
72166
|
-
import { createHash as
|
|
72839
|
+
import { createHash as createHash31, randomUUID as randomUUID29 } from "node:crypto";
|
|
72167
72840
|
import { promisify as promisify28 } from "node:util";
|
|
72168
72841
|
async function bootedSimulators() {
|
|
72169
72842
|
if (process.platform !== "darwin") return [];
|
|
@@ -72191,7 +72864,7 @@ async function simulatorScreenshot(udid) {
|
|
|
72191
72864
|
const file4 = path137.join(tmpdir6(), `phren-sim-${randomUUID29()}.png`);
|
|
72192
72865
|
try {
|
|
72193
72866
|
await exec25("/usr/bin/xcrun", ["simctl", "io", udid, "screenshot", "--type=png", file4], { timeout: 15e3 });
|
|
72194
|
-
return await
|
|
72867
|
+
return await readFile53(file4);
|
|
72195
72868
|
} catch (error62) {
|
|
72196
72869
|
if (error62 instanceof BridgeError) throw error62;
|
|
72197
72870
|
throw new BridgeError(409, "Couldn't capture that simulator. Is it still booted?");
|
|
@@ -72299,23 +72972,23 @@ case "type":
|
|
|
72299
72972
|
}
|
|
72300
72973
|
default: fail(2, "unknown command \\(command)")
|
|
72301
72974
|
}
|
|
72302
|
-
` : await
|
|
72303
|
-
const digest2 =
|
|
72304
|
-
const saved = await
|
|
72975
|
+
` : await readFile53(new URL("./native/simtap.swift", import.meta.url), "utf8");
|
|
72976
|
+
const digest2 = createHash31("sha256").update(code).digest("hex");
|
|
72977
|
+
const saved = await readFile53(binary + ".sha256", "utf8").then(JSON.parse).catch(() => void 0);
|
|
72305
72978
|
if (await stat31(binary).catch(() => void 0) && saved?.sourceSha === digest2) return binary;
|
|
72306
72979
|
await mkdir34(dir, { recursive: true, mode: 448 });
|
|
72307
72980
|
const temporary = path137.join(dir, `simtap.${randomUUID29()}`), source = temporary + ".swift";
|
|
72308
72981
|
const sidecar = temporary + ".sha256";
|
|
72309
72982
|
try {
|
|
72310
|
-
await
|
|
72983
|
+
await writeFile11(source, code, { mode: 384, flag: "wx" });
|
|
72311
72984
|
await exec25("/usr/bin/swiftc", ["-O", "-o", temporary, source], { timeout: 18e4 }).catch(() => {
|
|
72312
72985
|
throw new BridgeError(409, "Couldn't build the simulator input helper (needs Xcode's swiftc).");
|
|
72313
72986
|
});
|
|
72314
72987
|
await chmod5(temporary, 448);
|
|
72315
|
-
const binarySha =
|
|
72316
|
-
await
|
|
72317
|
-
await
|
|
72318
|
-
await
|
|
72988
|
+
const binarySha = createHash31("sha256").update(await readFile53(temporary)).digest("hex");
|
|
72989
|
+
await writeFile11(sidecar, JSON.stringify({ sourceSha: digest2, binarySha }), { mode: 384, flag: "wx" });
|
|
72990
|
+
await rename10(temporary, binary);
|
|
72991
|
+
await rename10(sidecar, binary + ".sha256");
|
|
72319
72992
|
} finally {
|
|
72320
72993
|
await Promise.all([source, temporary, sidecar].map((file4) => unlink9(file4).catch(() => void 0)));
|
|
72321
72994
|
}
|
|
@@ -72329,8 +73002,8 @@ function simtap(name, ...args) {
|
|
|
72329
73002
|
}
|
|
72330
73003
|
async function verifiedHelper() {
|
|
72331
73004
|
const binary = await helper();
|
|
72332
|
-
const saved = await
|
|
72333
|
-
const binarySha =
|
|
73005
|
+
const saved = await readFile53(binary + ".sha256", "utf8").then(JSON.parse).catch(() => void 0);
|
|
73006
|
+
const binarySha = createHash31("sha256").update(await readFile53(binary)).digest("hex");
|
|
72334
73007
|
if (!saved || saved.binarySha !== binarySha) throw new BridgeError(409, "Simulator input helper integrity check failed.");
|
|
72335
73008
|
return binary;
|
|
72336
73009
|
}
|
|
@@ -72786,7 +73459,7 @@ var init_session_rename = __esm({
|
|
|
72786
73459
|
|
|
72787
73460
|
// src/bridge/link.ts
|
|
72788
73461
|
import { execFile as execFile31 } from "node:child_process";
|
|
72789
|
-
import { readFile as
|
|
73462
|
+
import { readFile as readFile54 } from "node:fs/promises";
|
|
72790
73463
|
import { homedir as homedir21, hostname as hostname12, userInfo as userInfo5 } from "node:os";
|
|
72791
73464
|
import path140 from "node:path";
|
|
72792
73465
|
import { promisify as promisify29 } from "node:util";
|
|
@@ -72831,11 +73504,11 @@ async function probe2(host) {
|
|
|
72831
73504
|
return computerId ? { host, computerId, user: field("user") ?? "", client: field("client") } : void 0;
|
|
72832
73505
|
}
|
|
72833
73506
|
async function discoverComputers(options = {}) {
|
|
72834
|
-
const config4 = options.sshConfig ?? await
|
|
73507
|
+
const config4 = options.sshConfig ?? await readFile54(path140.join(homedir21(), ".ssh", "config"), "utf8").catch(() => "");
|
|
72835
73508
|
const store = options.store !== void 0 ? options.store : findPhrenPath();
|
|
72836
73509
|
const machines = store ? listMachines(store) : void 0;
|
|
72837
73510
|
const { peers } = await optionalHookPeers();
|
|
72838
|
-
const own2 = (await
|
|
73511
|
+
const own2 = (await readFile54(path140.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
|
|
72839
73512
|
const known2 = new Set([...localNames(), ...peers.flatMap((peer) => [peer.name, peer.address])].map(computerLabel));
|
|
72840
73513
|
const candidates = [.../* @__PURE__ */ new Set([...sshConfigHosts(config4), ...machines?.ok ? Object.keys(machines.data) : []])].filter((host) => !known2.has(computerLabel(host))).slice(0, 32);
|
|
72841
73514
|
const [found, peerIds] = await Promise.all([
|
|
@@ -72857,7 +73530,7 @@ function slugName(value2) {
|
|
|
72857
73530
|
async function linkComputer(host, options = {}) {
|
|
72858
73531
|
const remote = await probe2(host);
|
|
72859
73532
|
if (!remote) throw new BridgeError(409, `${host} answers over ssh but Phren Hook is not installed there. Run phren bridge install on it first.`);
|
|
72860
|
-
const own2 = (await
|
|
73533
|
+
const own2 = (await readFile54(path140.join(bridgeRoot(), "computer-id"), "utf8").catch(() => "")).trim();
|
|
72861
73534
|
if (remote.computerId === own2) throw new BridgeError(409, `${host} is this computer.`);
|
|
72862
73535
|
const name = computerName.parse(options.name ?? slugName(host));
|
|
72863
73536
|
const as2 = computerName.parse(options.as ?? slugName(hostname12()));
|
|
@@ -73153,6 +73826,8 @@ function workspacesReader(ctx) {
|
|
|
73153
73826
|
if (expired) return;
|
|
73154
73827
|
Object.assign(tab, stall);
|
|
73155
73828
|
tab.title = title2;
|
|
73829
|
+
const reply = tab.agentStatus === "working" ? void 0 : replyExcerpt(record4);
|
|
73830
|
+
if (reply) tab.lastReply = reply;
|
|
73156
73831
|
}));
|
|
73157
73832
|
const eachTab = (read) => {
|
|
73158
73833
|
let next = 0;
|
|
@@ -74742,11 +75417,11 @@ var init_server_overview = __esm({
|
|
|
74742
75417
|
});
|
|
74743
75418
|
|
|
74744
75419
|
// src/bridge/codex-auth-refresh.ts
|
|
74745
|
-
import { readFile as
|
|
75420
|
+
import { readFile as readFile55 } from "node:fs/promises";
|
|
74746
75421
|
import path142 from "node:path";
|
|
74747
75422
|
async function lastCodexRefresh(file4 = path142.join(codexHome(), "auth.json")) {
|
|
74748
75423
|
try {
|
|
74749
|
-
const auth = object2(JSON.parse(await
|
|
75424
|
+
const auth = object2(JSON.parse(await readFile55(file4, "utf8")));
|
|
74750
75425
|
if (!object2(auth.tokens).refresh_token) return void 0;
|
|
74751
75426
|
const at2 = Date.parse(String(auth.last_refresh ?? ""));
|
|
74752
75427
|
return Number.isFinite(at2) ? at2 : 0;
|
|
@@ -74763,6 +75438,7 @@ var init_codex_auth_refresh = __esm({
|
|
|
74763
75438
|
"use strict";
|
|
74764
75439
|
init_home_paths();
|
|
74765
75440
|
init_logger();
|
|
75441
|
+
init_codex_app_server();
|
|
74766
75442
|
init_protocol();
|
|
74767
75443
|
REFRESH_AFTER_MS = 6 * 864e5;
|
|
74768
75444
|
CodexAuthKeeper = class {
|
|
@@ -74787,6 +75463,10 @@ var init_codex_auth_refresh = __esm({
|
|
|
74787
75463
|
try {
|
|
74788
75464
|
await this.refresher.refreshAuth();
|
|
74789
75465
|
} catch (error62) {
|
|
75466
|
+
if (error62 instanceof AppServerUnsupportedError) {
|
|
75467
|
+
logger.debug("codex-auth", `Sign-in refresh skipped: ${error62.message}`);
|
|
75468
|
+
return false;
|
|
75469
|
+
}
|
|
74790
75470
|
logger.warn("codex-auth", `Could not refresh the Codex sign-in ahead of its workers: ${error62 instanceof Error ? error62.message : String(error62)}`);
|
|
74791
75471
|
return false;
|
|
74792
75472
|
}
|
|
@@ -74802,8 +75482,8 @@ var init_codex_auth_refresh = __esm({
|
|
|
74802
75482
|
|
|
74803
75483
|
// src/bridge/server.ts
|
|
74804
75484
|
import { randomUUID as randomUUID30 } from "node:crypto";
|
|
74805
|
-
import { chmod as chmod6, lstat as lstat36, mkdir as mkdir35, readFile as
|
|
74806
|
-
import { readFileSync as
|
|
75485
|
+
import { chmod as chmod6, lstat as lstat36, mkdir as mkdir35, readFile as readFile56, rm as rm17, unlink as unlink10, writeFile as writeFile12 } from "node:fs/promises";
|
|
75486
|
+
import { readFileSync as readFileSync57 } from "node:fs";
|
|
74807
75487
|
import { createServer as createServer4 } from "node:http";
|
|
74808
75488
|
import { cpus as cpus2, hostname as hostname13, loadavg as loadavg2 } from "node:os";
|
|
74809
75489
|
import path143 from "node:path";
|
|
@@ -74818,10 +75498,10 @@ async function serve(version2, options = {}) {
|
|
|
74818
75498
|
let computerID2;
|
|
74819
75499
|
const identityFile = path143.join(root, "computer-id");
|
|
74820
75500
|
try {
|
|
74821
|
-
computerID2 = (await
|
|
75501
|
+
computerID2 = (await readFile56(identityFile, "utf8")).trim();
|
|
74822
75502
|
} catch {
|
|
74823
75503
|
computerID2 = randomUUID30();
|
|
74824
|
-
await
|
|
75504
|
+
await writeFile12(identityFile, computerID2, { flag: "wx", mode: 384 });
|
|
74825
75505
|
}
|
|
74826
75506
|
const launches = new LaunchLimiter();
|
|
74827
75507
|
const dispatches = modules.has("conductor") ? new DispatchService({
|
|
@@ -74943,7 +75623,7 @@ async function serve(version2, options = {}) {
|
|
|
74943
75623
|
if (codeReindexer) agentHooks.changes.onRecord = (files) => codeReindexer.record(files);
|
|
74944
75624
|
function gatewayTiming() {
|
|
74945
75625
|
try {
|
|
74946
|
-
const parsed = JSON.parse(
|
|
75626
|
+
const parsed = JSON.parse(readFileSync57(path143.join(root, "gateway.json"), "utf8"));
|
|
74947
75627
|
if (typeof parsed.ms === "number" && Number.isFinite(parsed.ms) && parsed.ms >= 0) return Math.round(parsed.ms);
|
|
74948
75628
|
} catch {
|
|
74949
75629
|
}
|
|
@@ -74989,7 +75669,7 @@ async function serve(version2, options = {}) {
|
|
|
74989
75669
|
}
|
|
74990
75670
|
const stopRetention = modules.has("git") ? await startChangeRetention() : () => {
|
|
74991
75671
|
};
|
|
74992
|
-
if (modules.has("git")) await
|
|
75672
|
+
if (modules.has("git")) await rm17(path143.join(root, "changes-scratch"), { recursive: true, force: true });
|
|
74993
75673
|
const streams = transcriptStreams({ modules, agentHooks, codexQuestions, sideQuestions, settingsSwitcher, info, activeCapabilities });
|
|
74994
75674
|
const { stream } = streams;
|
|
74995
75675
|
const overview = overviewStream({
|
|
@@ -75255,7 +75935,7 @@ __export(device_enroll_exports, {
|
|
|
75255
75935
|
enrollDevice: () => enrollDevice,
|
|
75256
75936
|
runEnrollDevice: () => runEnrollDevice
|
|
75257
75937
|
});
|
|
75258
|
-
import { readFile as
|
|
75938
|
+
import { readFile as readFile57 } from "node:fs/promises";
|
|
75259
75939
|
import { homedir as homedir22, userInfo as userInfo6 } from "node:os";
|
|
75260
75940
|
import path144 from "node:path";
|
|
75261
75941
|
async function enrollDevice(input2, options) {
|
|
@@ -75265,14 +75945,14 @@ async function enrollDevice(input2, options) {
|
|
|
75265
75945
|
const line = `restrict,pty,${forcedCommand} ${publicKey} ${comment}`;
|
|
75266
75946
|
const encoded = publicKey.split(" ")[1];
|
|
75267
75947
|
const file4 = path144.join(options.sshDirectory ?? path144.join(homedir22(), ".ssh"), "authorized_keys");
|
|
75268
|
-
const before = await
|
|
75948
|
+
const before = await readFile57(file4, "utf8").catch(() => "");
|
|
75269
75949
|
await appendAuthorizedKey(
|
|
75270
75950
|
line,
|
|
75271
75951
|
(existing) => existing.split(/\s+/).includes(encoded),
|
|
75272
75952
|
"This phone key is already authorized with different options.",
|
|
75273
75953
|
options.sshDirectory
|
|
75274
75954
|
);
|
|
75275
|
-
const id2 = await
|
|
75955
|
+
const id2 = await readFile57(path144.join(options.root ?? bridgeRoot(), "computer-id"), "utf8").then((value2) => value2.trim() || null).catch(() => null);
|
|
75276
75956
|
return {
|
|
75277
75957
|
v: 1,
|
|
75278
75958
|
ok: true,
|
|
@@ -75323,13 +76003,13 @@ __export(command_exports, {
|
|
|
75323
76003
|
approvalPushCheck: () => approvalPushCheck,
|
|
75324
76004
|
runBridge: () => runBridge
|
|
75325
76005
|
});
|
|
75326
|
-
import { readFile as
|
|
76006
|
+
import { readFile as readFile58 } from "node:fs/promises";
|
|
75327
76007
|
async function runBridge(args, version2) {
|
|
75328
76008
|
switch (args[0]) {
|
|
75329
76009
|
case "enroll-computer": {
|
|
75330
76010
|
if (args.length === 2) console.log(await enrollComputer(args[1]));
|
|
75331
76011
|
else if (args.length === 4 && args[2] === "--accept") {
|
|
75332
|
-
await acceptComputer(args[1], await
|
|
76012
|
+
await acceptComputer(args[1], await readFile58(args[3], "utf8"));
|
|
75333
76013
|
console.log(`Enrolled ${args[1]} for Phren Hook.`);
|
|
75334
76014
|
} else throw new Error("Usage: phren bridge enroll-computer <name> [--accept <public-key-file>]");
|
|
75335
76015
|
break;
|
|
@@ -75504,7 +76184,7 @@ async function runBridge(args, version2) {
|
|
|
75504
76184
|
break;
|
|
75505
76185
|
}
|
|
75506
76186
|
const readModels = async (source) => {
|
|
75507
|
-
const rows2 = JSON.parse(await
|
|
76187
|
+
const rows2 = JSON.parse(await readFile58(fixture, "utf8"));
|
|
75508
76188
|
return Array.isArray(rows2[source]) ? rows2[source] : [];
|
|
75509
76189
|
};
|
|
75510
76190
|
const emptyUsage = (source) => ({ source, windows: [] });
|
|
@@ -75661,7 +76341,7 @@ async function main() {
|
|
|
75661
76341
|
return askpass2(args[1]);
|
|
75662
76342
|
}
|
|
75663
76343
|
const { runBridge: runBridge2 } = await Promise.resolve().then(() => (init_command(), command_exports));
|
|
75664
|
-
return runBridge2(args, "0.3.
|
|
76344
|
+
return runBridge2(args, "0.3.46");
|
|
75665
76345
|
}
|
|
75666
76346
|
main().then((code) => {
|
|
75667
76347
|
process.exitCode = code;
|